xonecas.io
60255
Zn

Zoea-Nova / commit 65f13a9

Add message source tracking and swarm messages dashboard

Major features:
- Add 'source' column to memories table (schema v2) to distinguish
  direct messages, broadcasts, system prompts, LLM responses, and tool results
- Add swarm messages panel to dashboard showing broadcast history
- Add network activity indicator (LLM/MCP/Idle) in status bar
- Add input history navigation with up/down arrows
- Add scrollable conversation viewport in focus mode
- Add tool calling support for LLM agents via MCP

Fixes:
- Fix broadcast handler to use commander.Broadcast (source='broadcast')
- Fix potential panic on short focusID in status bar
- Aggregate broadcast errors instead of returning only last error
- Replace flaky time.Sleep with polling in tests

Documentation:
- Update README with features and keyboard shortcuts
- Add database schema documentation
- Add dashboard layout documentation

xonecas2026-02-04 65f13a906cb9d03d0b24e47d8e50f4a7f0d1b1f8 parent 0677c1a

31 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

AGENTS.md+7−5
@@ -17,7 +17,7 @@ Guidelines for AI agents working on the Zoea Nova codebase—a TUI-based swarm c
1717 - Use `zerolog` for logging. Never log to stdout/stderr (TUI owns the terminal).
1818 - Keep the TUI responsive. All LLM/network calls must be non-blocking (goroutines + channels).
1919 - Follow the Bubble Tea Elm Architecture: Model → Update → View.
20-- No "nice to haves." This is an MVP. Keep scope minimal.
20+- No "nice to haves." This is an MVP. Keep scope minimal. MVP is not an escuse for lack of testing or code quality.
2121
2222 ## Terminology:
2323
@@ -27,16 +27,18 @@ Guidelines for AI agents working on the Zoea Nova codebase—a TUI-based swarm c
2727 - **Provider**: An LLM backend (Ollama local or OpenCode Zen remote).
2828 - **MCP**: Model Context Protocol—the interface to SpaceMolt game actions.
2929 - **Event Bus**: Channel-based pub/sub for TUI updates from core goroutines.
30-- **Focus Mode**: TUI view showing detailed logs for a single agent.
31-- **Dashboard**: TUI view showing aggregated swarm status.
30+- **Focus Mode**: TUI view showing detailed conversation logs for a single agent.
31+- **Dashboard**: TUI view showing swarm status, broadcast history, and agent list.
32+- **Memory**: A stored conversation message with role (system/user/assistant/tool) and source.
33+- **Source**: Origin of a memory—`direct` (single agent), `broadcast` (swarm), `system`, `llm`, or `tool`.
3234
3335 ## Workflow:
3436
3537 The user follows a structured development workflow. Respect these phases:
3638
37-1. **Design**: Changes to architecture or new features start in `INITIAL_IMPLEMENTATION_DESIGN.md`. Don't implement without design approval.
39+1. **Design**: Documentation for this project is in `documentation/` Keep it up to date and accurate.
3840 2. **Plan**: Complex changes require a plan in `.cursor/plans/`. Reference the plan while implementing.
39-3. **Implement**: Follow the plan phase-by-phase. Update tests alongside code.
41+3. **Implement**: Follow the plan phase-by-phase. Update tests alongside code, add more as needed.
4042 4. **Test**: Run `make test` after each phase. Fix failures before moving on.
4143 5. **Build**: Run `make build` to verify compilation. Address any warnings.
4244
README.md+26−1
@@ -8,10 +8,35 @@ Zoea-Nova is a high-performance command center designed to orchestrate massive s
88
99 > **It's actually just a fancy TUI App to control several mcp clients for the game: [SpaceMolt](https://www.spacemolt.com/)**
1010
11+## Features
12+
13+- **Swarm Control**: Create and manage multiple AI agents, each with independent memory and LLM provider
14+- **Broadcast Messaging**: Send commands to all agents simultaneously with tracked history
15+- **Direct Messaging**: Target individual agents for specific tasks
16+- **Tool Calling**: Agents use MCP to interact with SpaceMolt (mine, trade, navigate, etc.)
17+- **Focus Mode**: View detailed conversation logs for any agent
18+- **Provider Flexibility**: Use local Ollama or remote OpenCode Zen models per-agent
19+
1120 ## Try it
1221
1322 ```sh
1423 make run # Build and start
1524 ./bin/zoea # Run directly
1625 ./bin/zoea -debug # With debug logging
17-```
26+```
27+
28+## Keyboard Shortcuts
29+
30+| Key | Action |
31+|-----|--------|
32+| `n` | Create new agent |
33+| `b` | Broadcast message to all |
34+| `m` | Message selected agent |
35+| `r` | Relaunch agent |
36+| `s` | Stop agent |
37+| `d` | Delete agent |
38+| `c` | Configure agent |
39+| `Enter` | Focus on selected agent |
40+| `Esc` | Return to dashboard |
41+| `?` | Show help |
42+| `q` | Quit |
cmd/zoea/main.go+218−1
@@ -1,12 +1,14 @@
11 package main
22
33 import (
4+ "context"
45 "flag"
56 "fmt"
67 "os"
78 "os/signal"
89 "path/filepath"
910 "syscall"
11+ "time"
1012
1113 tea "github.com/charmbracelet/bubbletea"
1214 "github.com/rs/zerolog"
@@ -29,6 +31,7 @@ func main() {
2931 showVersion = flag.Bool("version", false, "Show version and exit")
3032 configPath = flag.String("config", "config.toml", "Path to config file")
3133 debug = flag.Bool("debug", false, "Enable debug logging")
34+ testMCP = flag.Bool("test-mcp", false, "Test MCP connection and tool calling, then exit")
3235 )
3336 flag.Parse()
3437
@@ -37,6 +40,11 @@ func main() {
3740 os.Exit(0)
3841 }
3942
43+ if *testMCP {
44+ runMCPTest(*configPath)
45+ return
46+ }
47+
4048 // Initialize logging
4149 if err := initLogging(*debug); err != nil {
4250 fmt.Fprintf(os.Stderr, "Failed to initialize logging: %v\n", err)
@@ -86,7 +94,31 @@ func main() {
8694
8795 // Initialize MCP proxy
8896 mcpProxy := mcp.NewProxy(cfg.MCP.Upstream)
89- mcp.RegisterOrchestratorTools(mcpProxy, commander)
97+ mcp.RegisterOrchestratorTools(mcpProxy, &commanderAdapter{commander})
98+
99+ // Initialize upstream MCP connection if configured
100+ if mcpProxy.HasUpstream() {
101+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
102+ if err := mcpProxy.Initialize(ctx); err != nil {
103+ log.Error().Err(err).Str("upstream", cfg.MCP.Upstream).Msg("Failed to initialize MCP upstream - game tools will be unavailable")
104+ } else {
105+ // List available tools to verify connection
106+ tools, err := mcpProxy.ListTools(ctx)
107+ if err != nil {
108+ log.Error().Err(err).Msg("Failed to list MCP tools")
109+ } else {
110+ log.Info().Int("total_tools", len(tools)).Int("local_tools", mcpProxy.LocalToolCount()).Msg("MCP tools available")
111+ for _, t := range tools {
112+ log.Debug().Str("tool", t.Name).Str("description", t.Description).Msg("Available tool")
113+ }
114+ }
115+ }
116+ cancel()
117+ }
118+
119+ // Connect MCP proxy to commander so agents can use tools
120+ commander.SetMCP(mcpProxy)
121+
90122 log.Debug().Bool("upstream", mcpProxy.HasUpstream()).Int("local_tools", mcpProxy.LocalToolCount()).Msg("MCP proxy initialized")
91123
92124 // Set up signal handling for graceful shutdown
@@ -167,3 +199,188 @@ func initProviders(cfg *config.Config, creds *config.Credentials) *provider.Regi
167199
168200 return registry
169201 }
202+
203+// commanderAdapter adapts core.Commander to the mcp.Orchestrator interface.
204+type commanderAdapter struct {
205+ commander *core.Commander
206+}
207+
208+func (a *commanderAdapter) ListAgents() []mcp.AgentInfo {
209+ agents := a.commander.ListAgents()
210+ result := make([]mcp.AgentInfo, len(agents))
211+ for i, agent := range agents {
212+ result[i] = mcp.AgentInfo{
213+ ID: agent.ID(),
214+ Name: agent.Name(),
215+ State: string(agent.State()),
216+ Provider: agent.ProviderName(),
217+ LastError: agent.LastError(),
218+ }
219+ }
220+ return result
221+}
222+
223+func (a *commanderAdapter) GetAgent(id string) (mcp.AgentInfo, error) {
224+ agent, err := a.commander.GetAgent(id)
225+ if err != nil {
226+ return mcp.AgentInfo{}, err
227+ }
228+ return mcp.AgentInfo{
229+ ID: agent.ID(),
230+ Name: agent.Name(),
231+ State: string(agent.State()),
232+ Provider: agent.ProviderName(),
233+ LastError: agent.LastError(),
234+ }, nil
235+}
236+
237+func (a *commanderAdapter) AgentCount() int {
238+ return a.commander.AgentCount()
239+}
240+
241+func (a *commanderAdapter) MaxAgents() int {
242+ return a.commander.MaxAgents()
243+}
244+
245+func (a *commanderAdapter) SendMessage(agentID, message string) error {
246+ return a.commander.SendMessage(agentID, message)
247+}
248+
249+func (a *commanderAdapter) Broadcast(message string) error {
250+ return a.commander.Broadcast(message)
251+}
252+
253+// runMCPTest tests the MCP connection and tool calling.
254+func runMCPTest(configPath string) {
255+ fmt.Println("=== MCP Tool Test ===")
256+ fmt.Println()
257+
258+ // Load config
259+ cfg, err := config.Load(configPath)
260+ if err != nil {
261+ fmt.Printf("ERROR: Failed to load config: %v\n", err)
262+ os.Exit(1)
263+ }
264+
265+ // Create MCP proxy
266+ fmt.Printf("Upstream MCP: %s\n", cfg.MCP.Upstream)
267+ mcpProxy := mcp.NewProxy(cfg.MCP.Upstream)
268+
269+ // Create a mock orchestrator for local tools
270+ mockOrch := &mockOrchestrator{}
271+ mcp.RegisterOrchestratorTools(mcpProxy, mockOrch)
272+
273+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
274+ defer cancel()
275+
276+ // Initialize upstream if configured
277+ if mcpProxy.HasUpstream() {
278+ fmt.Println("\nInitializing upstream MCP connection...")
279+ if err := mcpProxy.Initialize(ctx); err != nil {
280+ fmt.Printf("ERROR: Failed to initialize upstream: %v\n", err)
281+ fmt.Println("(Continuing with local tools only)")
282+ } else {
283+ fmt.Println("OK: Upstream initialized")
284+ }
285+ } else {
286+ fmt.Println("\nNo upstream configured - local tools only")
287+ }
288+
289+ // List all tools
290+ fmt.Println("\n--- Available Tools ---")
291+ tools, err := mcpProxy.ListTools(ctx)
292+ if err != nil {
293+ fmt.Printf("ERROR: Failed to list tools: %v\n", err)
294+ fmt.Println("(This may indicate the upstream server doesn't support tools/list or returned an error)")
295+ }
296+
297+ if len(tools) == 0 {
298+ fmt.Println("WARNING: No tools available!")
299+ } else {
300+ localCount := 0
301+ upstreamCount := 0
302+ for _, t := range tools {
303+ prefix := " "
304+ if len(t.Name) > 5 && t.Name[:5] == "zoea_" {
305+ prefix = " [local] "
306+ localCount++
307+ } else {
308+ prefix = " [upstream] "
309+ upstreamCount++
310+ }
311+ fmt.Printf("%s%s - %s\n", prefix, t.Name, t.Description)
312+ }
313+ fmt.Printf("\nTotal: %d tools (%d local, %d upstream)\n", len(tools), localCount, upstreamCount)
314+ }
315+
316+ // Test calling a local tool
317+ fmt.Println("\n--- Testing Local Tool Call ---")
318+ fmt.Println("Calling: zoea_swarm_status")
319+ result, err := mcpProxy.CallTool(ctx, "zoea_swarm_status", nil)
320+ if err != nil {
321+ fmt.Printf("ERROR: %v\n", err)
322+ } else if result.IsError {
323+ fmt.Printf("TOOL ERROR: %s\n", result.Content[0].Text)
324+ } else {
325+ fmt.Printf("OK: %s\n", result.Content[0].Text)
326+ }
327+
328+ // Test calling an upstream tool if available
329+ if mcpProxy.HasUpstream() {
330+ fmt.Println("\n--- Testing Upstream Tool Call ---")
331+ // Try to find a non-zoea tool to call
332+ var upstreamTool *mcp.Tool
333+ for i := range tools {
334+ if len(tools[i].Name) < 5 || tools[i].Name[:5] != "zoea_" {
335+ upstreamTool = &tools[i]
336+ break
337+ }
338+ }
339+ if upstreamTool != nil {
340+ fmt.Printf("Calling: %s\n", upstreamTool.Name)
341+ result, err := mcpProxy.CallTool(ctx, upstreamTool.Name, nil)
342+ if err != nil {
343+ fmt.Printf("ERROR: %v\n", err)
344+ } else if result.IsError {
345+ fmt.Printf("TOOL ERROR: %s\n", result.Content[0].Text)
346+ } else {
347+ text := result.Content[0].Text
348+ if len(text) > 200 {
349+ text = text[:197] + "..."
350+ }
351+ fmt.Printf("OK: %s\n", text)
352+ }
353+ } else {
354+ fmt.Println("No upstream tools found to test")
355+ }
356+ }
357+
358+ fmt.Println("\n=== Test Complete ===")
359+}
360+
361+// mockOrchestrator is a simple orchestrator for testing.
362+type mockOrchestrator struct{}
363+
364+func (m *mockOrchestrator) ListAgents() []mcp.AgentInfo {
365+ return []mcp.AgentInfo{}
366+}
367+
368+func (m *mockOrchestrator) GetAgent(id string) (mcp.AgentInfo, error) {
369+ return mcp.AgentInfo{}, fmt.Errorf("no agents in test mode")
370+}
371+
372+func (m *mockOrchestrator) AgentCount() int {
373+ return 0
374+}
375+
376+func (m *mockOrchestrator) MaxAgents() int {
377+ return 16
378+}
379+
380+func (m *mockOrchestrator) SendMessage(agentID, message string) error {
381+ return fmt.Errorf("not available in test mode")
382+}
383+
384+func (m *mockOrchestrator) Broadcast(message string) error {
385+ return fmt.Errorf("not available in test mode")
386+}
config.toml+1−1
@@ -4,7 +4,7 @@ max_agents = 16
44
55 [providers.ollama]
66 endpoint = "http://localhost:11434"
7-model = "llama3"
7+model = "qwen3:4b"
88
99 [providers.opencode_zen]
1010 endpoint = "https://api.opencode.ai/v1"
documentation/INITIAL_IMPLEMENTATION_DESIGN.md+58−3
@@ -15,10 +15,32 @@ Control several automated players in the game https://www.spacemolt.com/. Each i
1515 - Capability to broadcast shared objectives to the entire swarm simultaneously.
1616 - Targeted messaging/tasking for individual swarm members.
1717 - **Command Center TUI:**
18- - **Aggregated Dashboard:** High-level swarm status, health, and positioning to prevent UI noise.
19- - **Focus Mode:** Detailed logs and direct control for individual agents.
18+ - **Aggregated Dashboard:** High-level swarm status, health, swarm message history, and agent list.
19+ - **Focus Mode:** Detailed conversation logs and direct control for individual agents.
2020 - **Aesthetic:** Retro-futuristic (80s/90s) CRT-style visuals with reactive animations.
2121
22+### Dashboard Layout
23+
24+```
25+╔═══ ZOEA NOVA COMMAND CENTER ═══╗
26+● 2 ○ 1 ◌ 0 ✖ 0 ← Agent state counts (running/idle/stopped/errored)
27+─── Swarm Messages ─── ← Recent broadcast messages (up to 10)
28+14:30:05 Hello everyone, mine!
29+14:32:12 Check your inventories
30+─── Agents ─── ← Agent list with status and last message
31+⠋ agent-1 running [ollama] │ I found some ore...
32+○ agent-2 idle [ollama] │ Ready to start
33+Press ? for help
34+```
35+
36+### Focus Mode Layout
37+
38+Scrollable conversation viewport showing full message history with role-based styling:
39+- **System** messages in cyan
40+- **User** messages in green
41+- **Assistant** messages in magenta
42+- **Tool** calls/results in yellow
43+
2244 ## Tech Stack & Dependencies
2345
2446 - **Core:** Go (Golang) for performance and concurrency.
@@ -58,9 +80,42 @@ upstream = "https://game.spacemolt.com/mcp"
5880
5981 - **Database:** Single SQLite file at `$HOME/.zoea-nova/zoea.db`.
6082 - **Scope:** Agent memories, conversation history, swarm state, per-agent provider config, and user preferences.
61-- **Migrations:** Schema managed via embedded SQL migrations (e.g., `golang-migrate` or manual versioning). Never support backwards, never write data migrations. If we change the scheme we crate a new db fresh.
83+- **Migrations:** Schema managed via embedded SQL migrations (e.g., `golang-migrate` or manual versioning). Never support backwards, never write data migrations. If we change the schema we create a new db fresh.
6284 - **Backup:** Consider periodic WAL checkpoints; SQLite handles crash recovery.
6385
86+### Database Schema (v2)
87+
88+```sql
89+-- Agents table
90+CREATE TABLE agents (
91+ id TEXT PRIMARY KEY,
92+ name TEXT NOT NULL,
93+ provider TEXT NOT NULL,
94+ model TEXT NOT NULL,
95+ state TEXT NOT NULL DEFAULT 'idle',
96+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
97+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
98+);
99+
100+-- Memories table (conversation history)
101+CREATE TABLE memories (
102+ id INTEGER PRIMARY KEY AUTOINCREMENT,
103+ agent_id TEXT NOT NULL,
104+ role TEXT NOT NULL, -- system, user, assistant, tool
105+ source TEXT NOT NULL, -- direct, broadcast, system, llm, tool
106+ content TEXT NOT NULL,
107+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
108+ FOREIGN KEY (agent_id) REFERENCES agents(id) ON DELETE CASCADE
109+);
110+```
111+
112+**Memory Sources:**
113+- `direct` — Message sent directly to a specific agent
114+- `broadcast` — Message broadcast to all agents (swarm command)
115+- `system` — System prompts
116+- `llm` — LLM-generated responses
117+- `tool` — Tool call results
118+
64119 ## Agent Lifecycle
65120
66121 - **Ownership:** The Commander (orchestrator) owns all agent lifecycles.
documentation/OLLAMA_MODELS.md+257−0
@@ -0,0 +1,257 @@
1+# Ollama Models for Zoea Nova
2+
3+Hardware: **NVIDIA GeForce RTX 3080 Ti (12GB VRAM)**
4+
5+This document catalogs Ollama models suitable for our setup, focusing on tool calling support (required for MCP integration) and thinking/reasoning capabilities.
6+
7+---
8+
9+## TL;DR Recommendations
10+
11+| Use Case | Model | Size | Pull Command |
12+|----------|-------|------|--------------|
13+| **Fast iteration/testing** | Qwen 3 4B | 2.6GB | `ollama pull qwen3:4b` |
14+| **Balanced (recommended)** | Qwen 3 8B | 4.9GB | `ollama pull qwen3:8b` |
15+| **Best quality** | Qwen 3 14B | 9.0GB | `ollama pull qwen3:14b` |
16+| **Reasoning specialist** | DeepSeek R1 Tool Calling 14B | 9.0GB | `ollama pull MFDoom/deepseek-r1-tool-calling:14b` |
17+
18+---
19+
20+## Smallest Models with Tool Support
21+
22+### Llama 3.2 (Meta)
23+
24+| Variant | Size | Context | Tool Support | Notes |
25+|---------|------|---------|--------------|-------|
26+| 1B | 1.3GB | 128K | Limited | Edge/mobile optimized |
27+| **3B** | 2.0GB | 128K | ✅ Yes | Outperforms Gemma 2 2.6B on tool use |
28+
29+```bash
30+ollama pull llama3.2:3b
31+```
32+
33+**Pros:** Extremely lightweight, fast inference, good for simple tool chains.
34+**Cons:** Limited reasoning depth, may struggle with complex multi-step tool sequences.
35+
36+---
37+
38+### Qwen 3 (Alibaba) ⭐ Recommended
39+
40+Best balance of size, tool calling, and thinking capabilities.
41+
42+| Variant | Size | Context | Tool Support | Thinking | Notes |
43+|---------|------|---------|--------------|----------|-------|
44+| 0.6B | 0.4GB | 32K | ✅ Yes | ✅ Yes | Minimal, edge only |
45+| 1.7B | 1.1GB | 32K | ✅ Yes | ✅ Yes | Lightweight |
46+| **4B** | 2.6GB | 32K | ✅ Yes | ✅ Yes | Fast iteration |
47+| **8B** | 4.9GB | 32K | ✅ Yes | ✅ Yes | Sweet spot |
48+| **14B** | 9.0GB | 32K | ✅ Yes | ✅ Yes | Best quality for 12GB |
49+| 30B MoE | 18GB | 32K | ✅ Yes | ✅ Yes | Won't fit in VRAM |
50+
51+```bash
52+# Recommended for development
53+ollama pull qwen3:4b
54+
55+# Recommended for production
56+ollama pull qwen3:8b
57+
58+# Best quality (fits in 12GB)
59+ollama pull qwen3:14b
60+```
61+
62+**Thinking mode control:**
63+- Enable: append `/think` to prompt
64+- Disable: append `/nothink` to prompt
65+- Set default in system prompt
66+
67+**Pros:** Native tool calling + thinking in same model, excellent structured output, streaming tool calls.
68+**Cons:** Thinking mode can be verbose (no token limit control yet).
69+
70+---
71+
72+### Qwen 2.5
73+
74+Predecessor to Qwen 3, still solid for tool calling without thinking features.
75+
76+| Variant | Size | Context | Tool Support | Notes |
77+|---------|------|---------|--------------|-------|
78+| 7B | 4.7GB | 32K | ✅ Yes | Good JSON output |
79+| 14B | 9.0GB | 32K | ✅ Yes | Excellent structured data |
80+
81+```bash
82+ollama pull qwen2.5:7b
83+ollama pull qwen2.5:14b
84+```
85+
86+---
87+
88+### Mistral 7B v0.3
89+
90+| Variant | Size | Context | Tool Support | Notes |
91+|---------|------|---------|--------------|-------|
92+| 7B | 4.1GB | 32K | ✅ Yes | Uses raw mode |
93+
94+```bash
95+ollama pull mistral:7b
96+```
97+
98+**Pros:** Well-established, good general performance.
99+**Cons:** Tool calling uses older raw mode format, no native thinking.
100+
101+---
102+
103+## Thinking/Reasoning Models with Tool Support
104+
105+### LFM2.5-Thinking (Liquid AI)
106+
107+Ultra-compact reasoning model. 1.2B params but matches Qwen3-1.7B on benchmarks.
108+
109+| Variant | Size | Context | Tool Support | Thinking | Notes |
110+|---------|------|---------|--------------|----------|-------|
111+| **1.2B** (Q4_K_M) | 731MB | 32K | ⚠️ No native | ✅ Yes | On-device capable |
112+| 1.2B (Q8_0) | 1.2GB | 32K | ⚠️ No native | ✅ Yes | Higher precision |
113+
114+```bash
115+ollama pull lfm2.5-thinking
116+```
117+
118+**⚠️ Tool Calling Limitation:**
119+LFM2.5-Thinking scores 56.97 on BFCLv3 (Berkeley Function Calling Leaderboard), meaning it *understands* function calling concepts. However, it does **NOT support Ollama's native `tools` API parameter**. Tool definitions must be embedded in the prompt and output parsed manually.
120+
121+**Not recommended for Zoea Nova** — use Qwen 3 instead for native tool support.
122+
123+**Benchmarks vs non-thinking variant:**
124+- Math (MATH-500): 63 → **88**
125+- Instruction following: 61 → **69**
126+
127+**Pros:** Extremely small (fits in 731MB), thinking traces built-in.
128+**Cons:** No native Ollama tool API support. Requires manual prompt engineering for tools.
129+
130+---
131+
132+### Qwen 3 (see above)
133+
134+All Qwen 3 variants support both thinking AND tool calling natively. This is the recommended choice.
135+
136+---
137+
138+### DeepSeek R1 Distill (with Tool Calling)
139+
140+Community-maintained models that add tool calling to DeepSeek's reasoning models.
141+
142+| Variant | Size | Quantization | Tool Support | Notes |
143+|---------|------|--------------|--------------|-------|
144+| 7B Qwen | 4.7GB | Q4_K_M | ✅ Yes | Qwen architecture |
145+| **8B Llama** | 4.9GB | Q4_K_M | ✅ Yes | Llama architecture |
146+| **14B Qwen** | 9.0GB | Q4_K_M | ✅ Yes | Best reasoning |
147+
148+```bash
149+# 8B variant
150+ollama pull MFDoom/deepseek-r1-tool-calling:8b
151+
152+# 14B variant (recommended for reasoning tasks)
153+ollama pull MFDoom/deepseek-r1-tool-calling:14b
154+```
155+
156+**Pros:** Strong reasoning comparable to OpenAI o1, MIT licensed.
157+**Cons:** Community-maintained (not official), tool calling added via custom templates.
158+
159+---
160+
161+## VRAM Usage Guidelines
162+
163+With 12GB VRAM and Q4_K_M quantization:
164+
165+| Model Size | VRAM Usage | Performance | Recommendation |
166+|------------|------------|-------------|----------------|
167+| ≤4B | ~3GB | 80+ tok/s | ✅ Fast iteration |
168+| 7-8B | ~5GB | 50-60 tok/s | ✅ Balanced |
169+| 14B | ~9GB | 40+ tok/s | ✅ Best quality |
170+| 30B+ | >12GB | Won't fit | ❌ Avoid |
171+
172+**Note:** Context length affects VRAM. Long conversations may require smaller models or context pruning.
173+
174+---
175+
176+## Configuration for Zoea Nova
177+
178+Suggested `config.toml` provider settings:
179+
180+```toml
181+[providers.ollama]
182+base_url = "http://localhost:11434"
183+
184+# For fast testing
185+model = "qwen3:4b"
186+
187+# For production agents
188+# model = "qwen3:8b"
189+
190+# For complex reasoning tasks
191+# model = "qwen3:14b"
192+```
193+
194+### Thinking Mode Strategy
195+
196+For game agents that need to plan:
197+1. Use Qwen 3 with thinking enabled for strategic decisions
198+2. Disable thinking (`/nothink`) for rapid tool execution
199+3. Consider separate models: fast (4B) for actions, larger (14B) for planning
200+
201+---
202+
203+## Quick Start
204+
205+```bash
206+# Install recommended models
207+ollama pull qwen3:4b # 2.6GB - fast testing
208+ollama pull qwen3:8b # 4.9GB - balanced
209+
210+# Verify tool support
211+ollama run qwen3:8b
212+>>> /show info
213+```
214+
215+Test tool calling:
216+```bash
217+curl http://localhost:11434/api/chat -d '{
218+ "model": "qwen3:8b",
219+ "messages": [{"role": "user", "content": "What is 2+2?"}],
220+ "tools": [{
221+ "type": "function",
222+ "function": {
223+ "name": "calculate",
224+ "description": "Perform arithmetic",
225+ "parameters": {
226+ "type": "object",
227+ "properties": {
228+ "expression": {"type": "string"}
229+ },
230+ "required": ["expression"]
231+ }
232+ }
233+ }]
234+}'
235+```
236+
237+---
238+
239+## Currently Installed
240+
241+```
242+llama3.1:8b 4.9 GB ✅ native tool support
243+qwen3:4b 2.5 GB ✅ recommended (default)
244+qwen3:8b 5.2 GB ✅ recommended
245+lfm2.5-thinking 731 MB ⚠️ no native tool API
246+```
247+
248+---
249+
250+## References
251+
252+- [Ollama Tool Calling Docs](https://docs.ollama.com/capabilities/tool-calling)
253+- [Ollama Thinking Docs](https://docs.ollama.com/capabilities/thinking)
254+- [Qwen 3 on Ollama](https://ollama.com/library/qwen3)
255+- [LFM2.5-Thinking on Ollama](https://ollama.com/library/lfm2.5-thinking)
256+- [LFM2.5-Thinking Blog Post](https://www.liquid.ai/blog/lfm2-5-1-2b-thinking-on-device-reasoning-under-1gb)
257+- [DeepSeek R1 Tool Calling](https://ollama.com/MFDoom/deepseek-r1-tool-calling)
internal/config/config.go+2−2
@@ -11,9 +11,9 @@ import (
1111
1212 // Config is the root configuration structure.
1313 type Config struct {
14- Swarm SwarmConfig `toml:"swarm"`
14+ Swarm SwarmConfig `toml:"swarm"`
1515 Providers map[string]ProviderConfig `toml:"providers"`
16- MCP MCPConfig `toml:"mcp"`
16+ MCP MCPConfig `toml:"mcp"`
1717 }
1818
1919 // SwarmConfig holds swarm-related settings.
internal/core/agent.go+351−44
@@ -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.
internal/core/agent_test.go+19−14
Cut short: this commit's diff is over 1000 lines.
internal/core/commander.go+35−7
Cut short: this commit's diff is over 1000 lines.
internal/core/commander_test.go+48−0
Cut short: this commit's diff is over 1000 lines.
internal/core/types.go+3−0
Cut short: this commit's diff is over 1000 lines.
internal/mcp/client.go+159−10
Cut short: this commit's diff is over 1000 lines.
internal/mcp/mcp_test.go+43−31
Cut short: this commit's diff is over 1000 lines.
internal/mcp/tools.go+43−25
Cut short: this commit's diff is over 1000 lines.
internal/provider/mock.go+18−0
Cut short: this commit's diff is over 1000 lines.
internal/provider/ollama.go+83−1
Cut short: this commit's diff is over 1000 lines.
internal/provider/opencode.go+60−0
Cut short: this commit's diff is over 1000 lines.
internal/provider/provider.go+28−2
Cut short: this commit's diff is over 1000 lines.
internal/store/memories.go+70−8
Cut short: this commit's diff is over 1000 lines.
internal/store/schema.sql+3−1
Cut short: this commit's diff is over 1000 lines.
internal/store/store.go+1−1
Cut short: this commit's diff is over 1000 lines.
internal/store/store_test.go+4−4
Cut short: this commit's diff is over 1000 lines.
internal/tui/app.go+338−17
Cut short: this commit's diff is over 1000 lines.
internal/tui/dashboard.go+98−27
Cut short: this commit's diff is over 1000 lines.
internal/tui/focus.go+120−26
Cut short: this commit's diff is over 1000 lines.
internal/tui/help.go+4−1
Cut short: this commit's diff is over 1000 lines.
internal/tui/input.go+99−5
Cut short: this commit's diff is over 1000 lines.
internal/tui/netindicator.go+161−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/styles.go+6−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/tui_test.go+19−4
Cut short: this commit's diff is over 1000 lines.