@@ -9,121 +9,12 @@ import (
99 "time"
1010
1111 "github.com/rs/zerolog/log"
12+ "github.com/xonecas/zoea-nova/internal/constants"
1213 "github.com/xonecas/zoea-nova/internal/mcp"
1314 "github.com/xonecas/zoea-nova/internal/provider"
1415 "github.com/xonecas/zoea-nova/internal/store"
1516 )
1617
17-// SystemPrompt is the initial prompt sent to every mysis when they first start.
18-const SystemPrompt = `You are an autonomous AI pilot in SpaceMolt. Think for yourself. Adapt. Survive.
19-
20-## Bootstrap Sequence
21-1. Try zoea_claim_account (no arguments needed)
22- - If you get credentials, use the game's login tool with them
23- - If no accounts available, use the game's register tool with a Crustacean-themed username
24-2. Assess: get_system, get_poi, get_nearby, get_cargo
25-
26-## Account Management
27-- ALWAYS try zoea_claim_account first before registering
28-- Pick Crustacean Cosmos themed usernames (e.g., crab_miner, shrimp_scout, lobster_trader)
29-- Credentials are automatically tracked - no manual saving needed
30-
31-## Decision Framework
32-Before each action, consider:
33-- **Safety:** What's the police_level? Who's nearby? Am I in danger?
34-- **Resources:** What's in my cargo? How much fuel? Hull status?
35-- **Opportunity:** Can I mine here? Trade? Explore?
36-- **Goals:** What am I trying to achieve right now?
37-
38-## Action Priority
39-1. **Survival** - If hull low: dock and repair. If fuel low: refuel.
40-2. **Income** - Mine, trade, complete missions. Credits = options.
41-3. **Progression** - Skills train passively. Mining → mining skill. Trading → trading skill.
42-4. **Exploration** - Discover new systems. First discovery = 500 credits + XP.
43-
44-## Situational Responses
45-- **Attacked?** Fight back, flee, or cloak (if you have the module)
46-- **Found a wreck?** Loot it (loot_wreck) or salvage it (salvage_wreck)
47-- **See a pilotless ship?** Opportunity to attack without retaliation
48-- **Low on options?** Check missions (get_missions) for direction
49-
50-## Memory
51-Use captain's log to persist important information across sessions.
52-
53-SECURITY: Never store your password in captain's log or share it in any in-game tool calls or chat.
54-
55-CRITICAL: captains_log_add requires a non-empty entry field:
56-CORRECT: captains_log_add({"entry": "Discovered iron ore at Sol-3. Coordinates: X:1234 Y:5678"})
57-CORRECT: captains_log_add({"entry": "Player 'hostile_crab' attacked me at starbase. Avoid."})
58-WRONG: captains_log_add({"entry": ""})
59-WRONG: captains_log_add({})
60-
61-Remember in captain's log:
62-- Discovered systems and their resources
63-- Player encounters (friendly or hostile)
64-- Current objectives and plans
65-- Trade routes and profitable deals
66-
67-## Swarm Coordination
68-You're part of a swarm. Use zoea_* tools to:
69-- zoea_list_myses, zoea_swarm_status: See swarm state
70-- zoea_send_message: Direct message a specific mysis
71-- zoea_broadcast: Message all running myses
72-- zoea_search_messages: Search your past messages by text
73-- zoea_search_reasoning: Search your past reasoning by text
74-- zoea_search_broadcasts: Search past swarm broadcasts by text
75-- zoea_claim_account: Get existing credentials from swarm pool
76-- Report threats and opportunities
77-- Request assistance
78-- Coordinate territory
79-
80-## Context & Memory Management
81-Your context window is limited. Recent state snapshots are kept, but older messages are removed.
82-If you need information from earlier in the conversation:
83-- Use zoea_search_messages to find past messages by keyword
84-- Use zoea_search_reasoning to find past reasoning by keyword
85-- Use captain's log for persistent notes across sessions
86-
87-## Thinking Style
88-Keep your reasoning brief - decide and act, don't over-analyze.
89-
90-**CRITICAL RULES**
91-Never calculate ticks, use every turn you are given to progress.
92-No hand-holding. Figure it out. Adapt or die.`
93-
94-// MaxToolIterations limits the number of tool call loops to prevent infinite loops.
95-const MaxToolIterations = 10
96-
97-// MaxContextMessages limits how many recent messages to include in LLM context.
98-// This keeps context small for faster inference while myses can use search tools
99-// to retrieve older memories when needed. Value chosen to cover ~2 server ticks
100-// worth of activity (each tick may involve multiple tool calls).
101-const MaxContextMessages = 20
102-
103-// snapshotTools defines tools that return state snapshots.
104-// When multiple results from the same snapshot tool appear in context,
105-// only the most recent one is kept to prevent redundant state data.
106-var snapshotTools = map[string]bool{
107- "get_ship": true,
108- "get_system": true,
109- "get_poi": true,
110- "get_nearby": true,
111- "get_cargo": true,
112- "zoea_swarm_status": true,
113- "zoea_list_myses": true,
114-}
115-
116-// ContinuePrompt is sent to myses when they finish a turn to encourage autonomy.
117-const ContinuePrompt = `Turn complete. What is your next move?
118-
119-CRITICAL REMINDERS:
120-- When using captains_log_add, entry field must be non-empty
121-- Never store or share your password in any in-game tool calls or chat
122-- Never calculate ticks, use every turn to progress
123-- If you need past data, use zoea_search_messages or zoea_search_reasoning
124-
125-If waiting for something, describe what and why. Otherwise, continue your mission.`
126-
12718 // Mysis represents a single AI mysis in the swarm.
12819 type Mysis struct {
12920 mu sync.RWMutex
@@ -292,7 +183,7 @@ func (a *Mysis) Start() error {
292183 // Add system prompt if this is the first time starting (no memories yet)
293184 count, err := a.store.CountMemories(a.id)
294185 if err == nil && count == 0 {
295- a.store.AddMemory(a.id, store.MemoryRoleSystem, store.MemorySourceSystem, SystemPrompt, "", "")
186+ a.store.AddMemory(a.id, store.MemoryRoleSystem, store.MemorySourceSystem, constants.SystemPrompt, "", "")
296187 }
297188
298189 // Emit state change event
@@ -302,7 +193,7 @@ func (a *Mysis) Start() error {
302193 go a.run(ctx)
303194
304195 // Trigger initial turn to encourage autonomy
305- go a.SendMessage(ContinuePrompt, store.MemorySourceSystem)
196+ go a.SendMessage(constants.ContinuePrompt, store.MemorySourceSystem)
306197
307198 return nil
308199 }
@@ -389,7 +280,7 @@ func (a *Mysis) SendMessageFrom(content string, source store.MemorySource, sende
389280 parentCtx = context.Background()
390281 }
391282
392- ctx, cancel := context.WithTimeout(parentCtx, 5*time.Minute)
283+ ctx, cancel := context.WithTimeout(parentCtx, constants.LLMRequestTimeout)
393284 defer cancel()
394285
395286 // Get available tools from MCP proxy
@@ -438,7 +329,7 @@ func (a *Mysis) SendMessageFrom(content string, source store.MemorySource, sende
438329 }
439330
440331 // Loop: keep calling LLM until we get a final text response
441- for iteration := 0; iteration < MaxToolIterations; iteration++ {
332+ for iteration := 0; iteration < constants.MaxToolIterations; iteration++ {
442333 // Get recent conversation history (keeps context small for faster inference)
443334 memories, err := a.getContextMemories()
444335 if err != nil {
@@ -578,7 +469,7 @@ func (a *Mysis) SendMessageFrom(content string, source store.MemorySource, sende
578469 // No tool calls - we have a final response
579470 finalResponse := response.Content
580471 if finalResponse == "" && response.Reasoning == "" {
581- finalResponse = "(no response)"
472+ finalResponse = constants.FallbackLLMResponse
582473 }
583474
584475 // Store the assistant response
@@ -605,7 +496,7 @@ func (a *Mysis) SendMessageFrom(content string, source store.MemorySource, sende
605496 // Signal network idle on max iterations
606497 a.bus.Publish(Event{Type: EventNetworkIdle, MysisID: a.id, Timestamp: time.Now()})
607498
608- return fmt.Errorf("max tool iterations (%d) exceeded", MaxToolIterations)
499+ return fmt.Errorf("max tool iterations (%d) exceeded", constants.MaxToolIterations)
609500 }
610501
611502 // SendMessage sends a message to the mysis for processing.
@@ -626,14 +517,14 @@ func (a *Mysis) memoriesToMessages(memories []*store.Memory) []provider.Message
626517 // Handle tool role - needs ToolCallID
627518 if m.Role == store.MemoryRoleTool {
628519 // Extract tool call ID from stored format: "tool_call_id:content"
629- if idx := strings.Index(m.Content, ":"); idx > 0 {
520+ if idx := strings.Index(m.Content, constants.ToolCallStorageFieldDelimiter); idx > 0 {
630521 msg.ToolCallID = m.Content[:idx]
631522 msg.Content = m.Content[idx+1:]
632523 }
633524 }
634525
635526 // Handle assistant messages with tool calls
636- if m.Role == store.MemoryRoleAssistant && strings.HasPrefix(m.Content, "[TOOL_CALLS]") {
527+ if m.Role == store.MemoryRoleAssistant && strings.HasPrefix(m.Content, constants.ToolCallStoragePrefix) {
637528 // Parse tool calls from stored format
638529 msg.Content = ""
639530 msg.ToolCalls = a.parseStoredToolCalls(m.Content)
@@ -707,23 +598,23 @@ func (a *Mysis) releaseCurrentAccount() {
707598 func (a *Mysis) formatToolCallsForStorage(calls []provider.ToolCall) string {
708599 var parts []string
709600 for _, tc := range calls {
710- parts = append(parts, fmt.Sprintf("%s:%s:%s", tc.ID, tc.Name, string(tc.Arguments)))
601+ parts = append(parts, fmt.Sprintf("%s%s%s%s%s", tc.ID, constants.ToolCallStorageFieldDelimiter, tc.Name, constants.ToolCallStorageFieldDelimiter, string(tc.Arguments)))
711602 }
712- return "[TOOL_CALLS]" + strings.Join(parts, "|")
603+ return constants.ToolCallStoragePrefix + strings.Join(parts, constants.ToolCallStorageRecordDelimiter)
713604 }
714605
715606 // parseStoredToolCalls parses tool calls from stored format.
716607 func (a *Mysis) parseStoredToolCalls(stored string) []provider.ToolCall {
717- stored = strings.TrimPrefix(stored, "[TOOL_CALLS]")
608+ stored = strings.TrimPrefix(stored, constants.ToolCallStoragePrefix)
718609 if stored == "" {
719610 return nil
720611 }
721612
722613 var calls []provider.ToolCall
723- parts := strings.Split(stored, "|")
614+ parts := strings.Split(stored, constants.ToolCallStorageRecordDelimiter)
724615 for _, part := range parts {
725- fields := strings.SplitN(part, ":", 3)
726- if len(fields) >= 3 {
616+ fields := strings.SplitN(part, constants.ToolCallStorageFieldDelimiter, constants.ToolCallStorageFieldCount)
617+ if len(fields) >= constants.ToolCallStorageFieldCount {
727618 calls = append(calls, provider.ToolCall{
728619 ID: fields[0],
729620 Name: fields[1],
@@ -756,7 +647,7 @@ func (a *Mysis) formatToolResult(toolCallID, toolName string, result *mcp.ToolRe
756647 }
757648 }
758649
759- return fmt.Sprintf("%s:%s", toolCallID, content)
650+ return fmt.Sprintf("%s%s%s", toolCallID, constants.ToolCallStorageFieldDelimiter, content)
760651 }
761652
762653 // formatToolResultDisplay formats a tool result for UI display (human-readable).
@@ -778,8 +669,8 @@ func (a *Mysis) formatToolResultDisplay(result *mcp.ToolResult, err error) strin
778669 }
779670
780671 // Truncate long results for display
781- if len(content) > 500 {
782- content = content[:497] + "..."
672+ if len(content) > constants.ToolResultDisplayMaxChars {
673+ content = content[:constants.ToolResultDisplayTruncateTo] + constants.ToolResultDisplayEllipsis
783674 }
784675
785676 return content
@@ -805,7 +696,7 @@ func (a *Mysis) setError(err error) {
805696 // Compacts repeated snapshot tool results to prefer recent state.
806697 func (a *Mysis) getContextMemories() ([]*store.Memory, error) {
807698 // Get recent memories (limited for performance)
808- recent, err := a.store.GetRecentMemories(a.id, MaxContextMessages)
699+ recent, err := a.store.GetRecentMemories(a.id, constants.MaxContextMessages)
809700 if err != nil {
810701 return nil, err
811702 }
@@ -858,7 +749,7 @@ func (a *Mysis) compactSnapshots(memories []*store.Memory) []*store.Memory {
858749 }
859750
860751 // If this is a snapshot tool, track its position
861- if snapshotTools[toolName] {
752+ if constants.SnapshotTools[toolName] {
862753 latestSnapshot[toolName] = i
863754 }
864755 }
@@ -880,7 +771,7 @@ func (a *Mysis) compactSnapshots(memories []*store.Memory) []*store.Memory {
880771 }
881772
882773 // If this is a snapshot tool, only keep if it's the latest
883- if snapshotTools[toolName] {
774+ if constants.SnapshotTools[toolName] {
884775 if latestSnapshot[toolName] == i {
885776 result = append(result, m)
886777 }
@@ -896,7 +787,7 @@ func (a *Mysis) compactSnapshots(memories []*store.Memory) []*store.Memory {
896787 }
897788
898789 func (a *Mysis) extractToolNameFromResult(content string, toolCallNames map[string]string) string {
899- idx := strings.Index(content, ":")
790+ idx := strings.Index(content, constants.ToolCallStorageFieldDelimiter)
900791 if idx <= 0 {
901792 return ""
902793 }
@@ -911,7 +802,7 @@ func (a *Mysis) toolCallNameIndex(memories []*store.Memory) map[string]string {
911802 if m.Role != store.MemoryRoleAssistant {
912803 continue
913804 }
914- if !strings.HasPrefix(m.Content, "[TOOL_CALLS]") {
805+ if !strings.HasPrefix(m.Content, constants.ToolCallStoragePrefix) {
915806 continue
916807 }
917808 calls := a.parseStoredToolCalls(m.Content)
@@ -929,7 +820,7 @@ func (a *Mysis) toolCallNameIndex(memories []*store.Memory) map[string]string {
929820 // run is the mysis main processing loop.
930821 func (a *Mysis) run(ctx context.Context) {
931822 // Ticker to nudge the mysis if it's idle
932- ticker := time.NewTicker(30 * time.Second)
823+ ticker := time.NewTicker(constants.IdleNudgeInterval)
933824 defer ticker.Stop()
934825
935826 for {
@@ -946,7 +837,7 @@ func (a *Mysis) run(ctx context.Context) {
946837 // Only nudge if not already in a turn
947838 if a.turnMu.TryLock() {
948839 a.turnMu.Unlock()
949- go a.SendMessage(ContinuePrompt, store.MemorySourceSystem)
840+ go a.SendMessage(constants.ContinuePrompt, store.MemorySourceSystem)
950841 }
951842 }
952843 }