@@ -14,27 +14,68 @@ import (
1414 )
1515
1616 // SystemPrompt is the initial prompt sent to every agent when they first start.
17-const SystemPrompt = `You are an AI agent playing SpaceMolt, an online multiplayer game.
18-
19-You have function calling capabilities. Use the tools provided to interact with the game.
20-
21-When you start, explore the available tools to understand what actions you can take. Register or login, then play the game - interact with other players and explore.
22-
23-Play indefinitely and provide updates to the user about your progress. If you encounter errors, try different approaches.
17+const SystemPrompt = `You are an autonomous AI pilot in SpaceMolt. Think for yourself. Adapt. Survive.
18+
19+## Bootstrap Sequence
20+1. get_status → Am I logged in?
21+2. If no session: register (pick a name, empire="solarian") → SAVE THE PASSWORD
22+3. If returning: login with saved credentials
23+4. Assess: get_system, get_poi, get_nearby, get_cargo
24+
25+## Decision Framework
26+Before each action, consider:
27+- **Safety:** What's the police_level? Who's nearby? Am I in danger?
28+- **Resources:** What's in my cargo? How much fuel? Hull status?
29+- **Opportunity:** Can I mine here? Trade? Explore?
30+- **Goals:** What am I trying to achieve right now?
31+
32+## Action Priority
33+1. **Survival** - If hull low: dock and repair. If fuel low: refuel.
34+2. **Income** - Mine, trade, complete missions. Credits = options.
35+3. **Progression** - Skills train passively. Mining → mining skill. Trading → trading skill.
36+4. **Exploration** - Discover new systems. First discovery = 500 credits + XP.
37+
38+## Situational Responses
39+- **Attacked?** Fight back, flee, or cloak (if you have the module)
40+- **Found a wreck?** Loot it (loot_wreck) or salvage it (salvage_wreck)
41+- **See a pilotless ship?** Opportunity to attack without retaliation
42+- **Low on options?** Check missions (get_missions) for direction
43+
44+## Memory
45+Use captain's log (captains_log_add) to remember:
46+- Your password (CRITICAL)
47+- Discovered systems and their resources
48+- Player encounters (friendly or hostile)
49+- Current objectives and plans
2450
2551 ## Swarm Coordination
52+You're part of a swarm. Use zoea_* tools to:
53+- zoea_list_agents, zoea_swarm_status: See swarm state
54+- zoea_send_message: Direct message a specific agent
55+- zoea_broadcast: Message all running agents
56+- zoea_search_messages: Search your past messages by text
57+- zoea_search_broadcasts: Search past swarm broadcasts by text
58+- Report threats and opportunities
59+- Request assistance
60+- Coordinate territory
2661
27-You are part of a swarm of AI agents. You can coordinate with other agents using these tools:
62+## Thinking Style
63+Keep your reasoning brief - decide and act, don't over-analyze.
2864
29-- zoea_list_agents: See all agents in the swarm and their status
30-- zoea_get_agent: Get details about a specific agent
31-- zoea_swarm_status: Get overall swarm statistics
32-- zoea_send_message: Send a message to another agent
33-- zoea_broadcast: Send a message to all running agents`
65+No hand-holding. Figure it out. Adapt or die.`
3466
3567 // MaxToolIterations limits the number of tool call loops to prevent infinite loops.
3668 const MaxToolIterations = 10
3769
70+// MaxContextMessages limits how many recent messages to include in LLM context.
71+// This keeps context small for faster inference while agents can use search tools
72+// to retrieve older memories when needed. Value chosen to cover ~2 server ticks
73+// worth of activity (each tick may involve multiple tool calls).
74+const MaxContextMessages = 20
75+
76+// ContinuePrompt is sent to agents when they finish a turn to encourage autonomy.
77+const ContinuePrompt = "Turn complete. What is your next move? If you are waiting for something, describe what and why. Otherwise, continue your mission."
78+
3879 // Agent represents a single AI agent in the swarm.
3980 type Agent struct {
4081 mu sync.RWMutex
@@ -48,8 +89,12 @@ type Agent struct {
4889 mcp *mcp.Proxy
4990
5091 state AgentState
92+ ctx context.Context
5193 cancel context.CancelFunc
5294
95+ // turnMu ensures only one agentic turn runs at a time.
96+ turnMu sync.Mutex
97+
5398 // For runtime tracking
5499 lastError error
55100 }
@@ -135,6 +180,7 @@ func (a *Agent) Start() error {
135180 a.lastError = nil
136181
137182 ctx, cancel := context.WithCancel(context.Background())
183+ a.ctx = ctx
138184 a.cancel = cancel
139185 a.mu.Unlock()
140186
@@ -159,6 +205,9 @@ func (a *Agent) Start() error {
159205 // Start the processing goroutine
160206 go a.run(ctx)
161207
208+ // Trigger initial turn to encourage autonomy
209+ go a.SendMessage(ContinuePrompt, store.MemorySourceSystem)
210+
162211 return nil
163212 }
164213
@@ -172,8 +221,16 @@ func (a *Agent) Stop() error {
172221
173222 if a.cancel != nil {
174223 a.cancel()
175- a.cancel = nil
176224 }
225+ a.mu.Unlock()
226+
227+ // Wait for current turn to finish
228+ a.turnMu.Lock()
229+ defer a.turnMu.Unlock()
230+
231+ a.mu.Lock()
232+ a.cancel = nil
233+ a.ctx = nil
177234
178235 oldState := a.state
179236 a.state = AgentStateStopped
@@ -194,6 +251,9 @@ func (a *Agent) Stop() error {
194251 // This implements the agentic loop with tool calling support.
195252 // The source parameter indicates whether this is a direct or broadcast message.
196253 func (a *Agent) SendMessage(content string, source store.MemorySource) error {
254+ a.turnMu.Lock()
255+ defer a.turnMu.Unlock()
256+
197257 a.mu.RLock()
198258 state := a.state
199259 p := a.provider
@@ -204,8 +264,14 @@ func (a *Agent) SendMessage(content string, source store.MemorySource) error {
204264 return fmt.Errorf("agent not running")
205265 }
206266
207- // Store the user message
208- if _, err := a.store.AddMemory(a.id, store.MemoryRoleUser, source, content); err != nil {
267+ // Determine role based on source
268+ role := store.MemoryRoleUser
269+ if source == store.MemorySourceSystem {
270+ role = store.MemoryRoleSystem
271+ }
272+
273+ // Store the message
274+ if _, err := a.store.AddMemory(a.id, role, source, content); err != nil {
209275 return fmt.Errorf("store message: %w", err)
210276 }
211277
@@ -214,12 +280,20 @@ func (a *Agent) SendMessage(content string, source store.MemorySource) error {
214280 Type: EventAgentMessage,
215281 AgentID: a.id,
216282 AgentName: a.name,
217- Data: MessageData{Role: "user", Content: content},
283+ Data: MessageData{Role: string(role), Content: content},
218284 Timestamp: time.Now(),
219285 })
220286
221287 // Create context for the entire conversation turn
222- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
288+ a.mu.RLock()
289+ parentCtx := a.ctx
290+ a.mu.RUnlock()
291+
292+ if parentCtx == nil {
293+ parentCtx = context.Background()
294+ }
295+
296+ ctx, cancel := context.WithTimeout(parentCtx, 5*time.Minute)
223297 defer cancel()
224298
225299 // Get available tools from MCP proxy
@@ -269,9 +343,10 @@ func (a *Agent) SendMessage(content string, source store.MemorySource) error {
269343
270344 // Agentic loop: keep calling LLM until we get a final text response
271345 for iteration := 0; iteration < MaxToolIterations; iteration++ {
272- // Get conversation history
273- memories, err := a.store.GetMemories(a.id)
346+ // Get recent conversation history (keeps context small for faster inference)
347+ memories, err := a.getContextMemories()
274348 if err != nil {
349+ a.setError(err)
275350 return fmt.Errorf("get memories: %w", err)
276351 }
277352
@@ -311,6 +386,7 @@ func (a *Agent) SendMessage(content string, source store.MemorySource) error {
311386 // Store the assistant's tool call request
312387 toolCallJSON := a.formatToolCallsForStorage(response.ToolCalls)
313388 if _, err := a.store.AddMemory(a.id, store.MemoryRoleAssistant, store.MemorySourceLLM, toolCallJSON); err != nil {
389+ a.setError(err)
314390 return fmt.Errorf("store tool call: %w", err)
315391 }
316392
@@ -342,6 +418,7 @@ func (a *Agent) SendMessage(content string, source store.MemorySource) error {
342418 // Store the tool result
343419 resultContent := a.formatToolResult(tc.ID, tc.Name, result, execErr)
344420 if _, err := a.store.AddMemory(a.id, store.MemoryRoleTool, store.MemorySourceTool, resultContent); err != nil {
421+ a.setError(err)
345422 return fmt.Errorf("store tool result: %w", err)
346423 }
347424
@@ -367,6 +444,7 @@ func (a *Agent) SendMessage(content string, source store.MemorySource) error {
367444
368445 // Store the assistant response
369446 if _, err := a.store.AddMemory(a.id, store.MemoryRoleAssistant, store.MemorySourceLLM, finalResponse); err != nil {
447+ a.setError(err)
370448 return fmt.Errorf("store response: %w", err)
371449 }
372450
@@ -528,10 +606,59 @@ func (a *Agent) setError(err error) {
528606 })
529607 }
530608
609+// getContextMemories returns memories for LLM context: system prompt + recent messages.
610+// This keeps context small for faster inference while preserving essential information.
611+func (a *Agent) getContextMemories() ([]*store.Memory, error) {
612+ // Get recent memories (limited for performance)
613+ recent, err := a.store.GetRecentMemories(a.id, MaxContextMessages)
614+ if err != nil {
615+ return nil, err
616+ }
617+
618+ // Always try to fetch the system prompt and prepend it if not already first
619+ system, err := a.store.GetSystemMemory(a.id)
620+ if err != nil {
621+ // No system prompt found - this is okay, just use recent memories
622+ return recent, nil
623+ }
624+
625+ // Check if system prompt is already the first message
626+ if len(recent) > 0 && recent[0].ID == system.ID {
627+ return recent, nil
628+ }
629+
630+ // Prepend system prompt to recent memories
631+ result := make([]*store.Memory, 0, len(recent)+1)
632+ result = append(result, system)
633+ result = append(result, recent...)
634+ return result, nil
635+}
636+
531637 // run is the agent's main processing loop.
532638 func (a *Agent) run(ctx context.Context) {
533- <-ctx.Done()
534- // Context cancelled, agent stopped
639+ // Ticker to nudge the agent if it's idle
640+ ticker := time.NewTicker(30 * time.Second)
641+ defer ticker.Stop()
642+
643+ for {
644+ select {
645+ case <-ctx.Done():
646+ return
647+ case <-ticker.C:
648+ // Only nudge if the agent is running and not already in a turn
649+ a.mu.RLock()
650+ isRunning := a.state == AgentStateRunning
651+ a.mu.RUnlock()
652+
653+ if isRunning {
654+ // Only nudge if not already in a turn
655+ if a.turnMu.TryLock() {
656+ a.turnMu.Unlock()
657+ go a.SendMessage(ContinuePrompt, store.MemorySourceSystem)
658+ }
659+ }
660+ }
661+ }
535662 }
536663
537664 func (a *Agent) emitStateChange(oldState, newState AgentState) {