@@ -2,23 +2,50 @@ package core
22
33 import (
44 "context"
5+ "encoding/json"
56 "fmt"
7+ "strings"
68 "sync"
79 "time"
810
11+ "github.com/xonecas/zoea-nova/internal/mcp"
912 "github.com/xonecas/zoea-nova/internal/provider"
1013 "github.com/xonecas/zoea-nova/internal/store"
1114 )
1215
16+// 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.
24+
25+## Swarm Coordination
26+
27+You are part of a swarm of AI agents. You can coordinate with other agents using these tools:
28+
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`
34+
35+// MaxToolIterations limits the number of tool call loops to prevent infinite loops.
36+const MaxToolIterations = 10
37+
1338 // Agent represents a single AI agent in the swarm.
1439 type Agent struct {
1540 mu sync.RWMutex
1641
17- id string
18- name string
19- provider provider.Provider
20- store *store.Store
21- bus *EventBus
42+ id string
43+ name string
44+ createdAt time.Time
45+ provider provider.Provider
46+ store *store.Store
47+ bus *EventBus
48+ mcp *mcp.Proxy
2249
2350 state AgentState
2451 cancel context.CancelFunc
@@ -28,17 +55,25 @@ type Agent struct {
2855 }
2956
3057 // NewAgent creates a new agent from stored data.
31-func NewAgent(id, name string, p provider.Provider, s *store.Store, bus *EventBus) *Agent {
58+func NewAgent(id, name string, createdAt time.Time, p provider.Provider, s *store.Store, bus *EventBus) *Agent {
3259 return &Agent{
33- id: id,
34- name: name,
35- provider: p,
36- store: s,
37- bus: bus,
38- state: AgentStateIdle,
60+ id: id,
61+ name: name,
62+ createdAt: createdAt,
63+ provider: p,
64+ store: s,
65+ bus: bus,
66+ state: AgentStateIdle,
3967 }
4068 }
4169
70+// SetMCP sets the MCP proxy for tool calling.
71+func (a *Agent) SetMCP(proxy *mcp.Proxy) {
72+ a.mu.Lock()
73+ defer a.mu.Unlock()
74+ a.mcp = proxy
75+}
76+
4277 // ID returns the agent's unique identifier.
4378 func (a *Agent) ID() string {
4479 return a.id
@@ -51,6 +86,11 @@ func (a *Agent) Name() string {
5186 return a.name
5287 }
5388
89+// CreatedAt returns when the agent was created.
90+func (a *Agent) CreatedAt() time.Time {
91+ return a.createdAt
92+}
93+
5494 // State returns the agent's current state.
5595 func (a *Agent) State() AgentState {
5696 a.mu.RLock()
@@ -107,6 +147,12 @@ func (a *Agent) Start() error {
107147 return err
108148 }
109149
150+ // Add system prompt if this is the first time starting (no memories yet)
151+ count, err := a.store.CountMemories(a.id)
152+ if err == nil && count == 0 {
153+ a.store.AddMemory(a.id, store.MemoryRoleSystem, store.MemorySourceSystem, SystemPrompt)
154+ }
155+
110156 // Emit state change event
111157 a.emitStateChange(oldState, AgentStateRunning)
112158
@@ -145,10 +191,13 @@ func (a *Agent) Stop() error {
145191 }
146192
147193 // SendMessage sends a message to the agent for processing.
148-func (a *Agent) SendMessage(content string) error {
194+// This implements the agentic loop with tool calling support.
195+// The source parameter indicates whether this is a direct or broadcast message.
196+func (a *Agent) SendMessage(content string, source store.MemorySource) error {
149197 a.mu.RLock()
150198 state := a.state
151199 p := a.provider
200+ mcpProxy := a.mcp
152201 a.mu.RUnlock()
153202
154203 if state != AgentStateRunning {
@@ -156,7 +205,7 @@ func (a *Agent) SendMessage(content string) error {
156205 }
157206
158207 // Store the user message
159- if _, err := a.store.AddMemory(a.id, store.MemoryRoleUser, content); err != nil {
208+ if _, err := a.store.AddMemory(a.id, store.MemoryRoleUser, source, content); err != nil {
160209 return fmt.Errorf("store message: %w", err)
161210 }
162211
@@ -169,56 +218,314 @@ func (a *Agent) SendMessage(content string) error {
169218 Timestamp: time.Now(),
170219 })
171220
172- // Get conversation history
173- memories, err := a.store.GetMemories(a.id)
174- if err != nil {
175- return fmt.Errorf("get memories: %w", err)
176- }
221+ // Create context for the entire conversation turn
222+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
223+ defer cancel()
177224
178- // Convert to provider messages
179- messages := make([]provider.Message, len(memories))
180- for i, m := range memories {
181- messages[i] = provider.Message{
182- Role: string(m.Role),
183- Content: m.Content,
225+ // Get available tools from MCP proxy
226+ var tools []provider.Tool
227+ if mcpProxy != nil {
228+ mcpTools, err := mcpProxy.ListTools(ctx)
229+ if err != nil {
230+ // Log error but continue - agent can still chat without tools
231+ a.bus.Publish(Event{
232+ Type: EventAgentError,
233+ AgentID: a.id,
234+ AgentName: a.name,
235+ Data: ErrorData{Error: fmt.Sprintf("Failed to load tools: %v", err)},
236+ Timestamp: time.Now(),
237+ })
238+ } else {
239+ tools = make([]provider.Tool, len(mcpTools))
240+ toolNames := make([]string, len(mcpTools))
241+ for i, t := range mcpTools {
242+ tools[i] = provider.Tool{
243+ Name: t.Name,
244+ Description: t.Description,
245+ Parameters: t.InputSchema,
246+ }
247+ toolNames[i] = t.Name
248+ }
249+ // Log available tools (only on first message or if debugging)
250+ if len(tools) > 0 {
251+ a.bus.Publish(Event{
252+ Type: EventAgentMessage,
253+ AgentID: a.id,
254+ AgentName: a.name,
255+ Data: MessageData{Role: "system", Content: fmt.Sprintf("Tools available: %s", strings.Join(toolNames, ", "))},
256+ Timestamp: time.Now(),
257+ })
258+ }
184259 }
260+ } else {
261+ a.bus.Publish(Event{
262+ Type: EventAgentError,
263+ AgentID: a.id,
264+ AgentName: a.name,
265+ Data: ErrorData{Error: "MCP proxy not configured - no tools available"},
266+ Timestamp: time.Now(),
267+ })
185268 }
186269
187- // Get response from provider
188- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
189- defer cancel()
270+ // Agentic loop: keep calling LLM until we get a final text response
271+ for iteration := 0; iteration < MaxToolIterations; iteration++ {
272+ // Get conversation history
273+ memories, err := a.store.GetMemories(a.id)
274+ if err != nil {
275+ return fmt.Errorf("get memories: %w", err)
276+ }
190277
191- response, err := p.Chat(ctx, messages)
192- if err != nil {
193- a.mu.Lock()
194- a.lastError = err
195- a.mu.Unlock()
278+ // Convert to provider messages
279+ messages := a.memoriesToMessages(memories)
196280
281+ // Signal LLM activity start
197282 a.bus.Publish(Event{
198- Type: EventAgentError,
283+ Type: EventNetworkLLM,
199284 AgentID: a.id,
200285 AgentName: a.name,
201- Data: ErrorData{Error: err.Error()},
202286 Timestamp: time.Now(),
203287 })
204- return fmt.Errorf("provider chat: %w", err)
288+
289+ // Get response from provider
290+ var response *provider.ChatResponse
291+ if len(tools) > 0 {
292+ response, err = p.ChatWithTools(ctx, messages, tools)
293+ } else {
294+ // No tools available, use simple chat
295+ text, chatErr := p.Chat(ctx, messages)
296+ if chatErr != nil {
297+ err = chatErr
298+ } else {
299+ response = &provider.ChatResponse{Content: text}
300+ }
301+ }
302+
303+ if err != nil {
304+ a.bus.Publish(Event{Type: EventNetworkIdle, AgentID: a.id, Timestamp: time.Now()})
305+ a.setError(err)
306+ return fmt.Errorf("provider chat: %w", err)
307+ }
308+
309+ // If we have tool calls, execute them
310+ if len(response.ToolCalls) > 0 {
311+ // Store the assistant's tool call request
312+ toolCallJSON := a.formatToolCallsForStorage(response.ToolCalls)
313+ if _, err := a.store.AddMemory(a.id, store.MemoryRoleAssistant, store.MemorySourceLLM, toolCallJSON); err != nil {
314+ return fmt.Errorf("store tool call: %w", err)
315+ }
316+
317+ // Emit event showing which tools are being called
318+ toolNames := make([]string, len(response.ToolCalls))
319+ for i, tc := range response.ToolCalls {
320+ toolNames[i] = tc.Name
321+ }
322+ a.bus.Publish(Event{
323+ Type: EventAgentMessage,
324+ AgentID: a.id,
325+ AgentName: a.name,
326+ Data: MessageData{Role: "assistant", Content: fmt.Sprintf("Calling tools: %s", strings.Join(toolNames, ", "))},
327+ Timestamp: time.Now(),
328+ })
329+
330+ // Execute each tool call
331+ for _, tc := range response.ToolCalls {
332+ // Signal MCP activity
333+ a.bus.Publish(Event{
334+ Type: EventNetworkMCP,
335+ AgentID: a.id,
336+ AgentName: a.name,
337+ Timestamp: time.Now(),
338+ })
339+
340+ result, execErr := a.executeToolCall(ctx, mcpProxy, tc)
341+
342+ // Store the tool result
343+ resultContent := a.formatToolResult(tc.ID, tc.Name, result, execErr)
344+ if _, err := a.store.AddMemory(a.id, store.MemoryRoleTool, store.MemorySourceTool, resultContent); err != nil {
345+ return fmt.Errorf("store tool result: %w", err)
346+ }
347+
348+ // Emit tool result event
349+ a.bus.Publish(Event{
350+ Type: EventAgentMessage,
351+ AgentID: a.id,
352+ AgentName: a.name,
353+ Data: MessageData{Role: "tool", Content: fmt.Sprintf("[%s] %s", tc.Name, a.formatToolResultDisplay(result, execErr))},
354+ Timestamp: time.Now(),
355+ })
356+ }
357+
358+ // Continue loop to get next LLM response
359+ continue
360+ }
361+
362+ // No tool calls - we have a final response
363+ finalResponse := response.Content
364+ if finalResponse == "" {
365+ finalResponse = "(no response)"
366+ }
367+
368+ // Store the assistant response
369+ if _, err := a.store.AddMemory(a.id, store.MemoryRoleAssistant, store.MemorySourceLLM, finalResponse); err != nil {
370+ return fmt.Errorf("store response: %w", err)
371+ }
372+
Cut short: this commit's diff is over 1000 lines.