xonecas.io
60255
Zn

Zoea-Nova / commit 65e3d52

feat(accounts): auto-track swarm credentials

xonecas2026-02-04 65e3d522ea546abecd17f87b67f1438e558571f9 parent b135141

11 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.

cmd/zoea/main.go+38−81
@@ -101,6 +101,7 @@ func main() {
101101
102102 // Initialize MCP proxy
103103 mcpProxy := mcp.NewProxy(cfg.MCP.Upstream)
104+ mcpProxy.SetAccountStore(&accountStoreAdapter{s})
104105 mcp.RegisterOrchestratorTools(mcpProxy, &commanderAdapter{commander})
105106
106107 // Initialize upstream MCP connection if configured
@@ -154,6 +155,12 @@ func main() {
154155
155156 // Clean shutdown
156157 commander.StopAll()
158+
159+ // Release all accounts
160+ if err := s.ReleaseAllAccounts(); err != nil {
161+ log.Warn().Err(err).Msg("Failed to release accounts on shutdown")
162+ }
163+
157164 log.Info().Msg("Zoea Nova shutdown complete")
158165 }
159166
@@ -207,7 +214,30 @@ func initProviders(cfg *config.Config, creds *config.Credentials) *provider.Regi
207214 return registry
208215 }
209216
210-// commanderAdapter adapts core.Commander to the mcp.Orchestrator interface.
217+type accountStoreAdapter struct {
218+ store *store.Store
219+}
220+
221+func (a *accountStoreAdapter) CreateAccount(username, password string) (*mcp.Account, error) {
222+ acc, err := a.store.CreateAccount(username, password)
223+ if err != nil {
224+ return nil, err
225+ }
226+ return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
227+}
228+
229+func (a *accountStoreAdapter) MarkAccountInUse(username string) error {
230+ return a.store.MarkAccountInUse(username)
231+}
232+
233+func (a *accountStoreAdapter) ReleaseAccount(username string) error {
234+ return a.store.ReleaseAccount(username)
235+}
236+
237+func (a *accountStoreAdapter) ReleaseAllAccounts() error {
238+ return a.store.ReleaseAllAccounts()
239+}
240+
211241 type commanderAdapter struct {
212242 commander *core.Commander
213243 }
@@ -310,77 +340,16 @@ func (a *commanderAdapter) SearchBroadcasts(query string, limit int) ([]mcp.Broa
310340 return results, nil
311341 }
312342
313-func (a *commanderAdapter) ListAvailableAccounts() ([]mcp.AccountInfo, error) {
314- accounts, err := a.commander.Store().ListAvailableAccounts()
315- if err != nil {
316- return nil, err
317- }
318-
319- results := make([]mcp.AccountInfo, len(accounts))
320- for i, acc := range accounts {
321- results[i] = mcp.AccountInfo{
322- Username: acc.Username,
323- Empire: acc.Empire,
324- }
325- }
326- return results, nil
327-}
328-
329-func (a *commanderAdapter) ClaimAccount(mysisID string) (mcp.AccountInfo, error) {
330- available, err := a.commander.Store().ListAvailableAccounts()
343+func (a *commanderAdapter) ClaimAccount() (mcp.AccountInfo, error) {
344+ acc, err := a.commander.Store().ClaimAccount()
331345 if err != nil {
332346 return mcp.AccountInfo{}, err
333347 }
334- if len(available) == 0 {
335- return mcp.AccountInfo{}, fmt.Errorf("no accounts available")
336- }
337348
338- // Try to claim accounts in order until one succeeds (handles race conditions)
339- for _, acc := range available {
340- if err := a.commander.Store().ClaimAccount(acc.Username, mysisID); err != nil {
341- // If already claimed, try next account
342- if err.Error() == fmt.Sprintf("account %s is already claimed", acc.Username) {
343- continue
344- }
345- // Other errors are fatal
346- return mcp.AccountInfo{}, err
347- }
348-
349- // Successfully claimed, update last used
350- if err := a.commander.Store().UpdateAccountLastUsed(acc.Username); err != nil {
351- log.Warn().Err(err).Str("username", acc.Username).Msg("failed to update account last_used_at")
352- }
353-
354- return mcp.AccountInfo{
355- Username: acc.Username,
356- Password: acc.Password,
357- Empire: acc.Empire,
358- }, nil
359- }
360-
361- // All accounts were claimed during our attempt
362- return mcp.AccountInfo{}, fmt.Errorf("no accounts available")
363-}
364-
365-func (a *commanderAdapter) RegisterAccount(mysisID, username, password, empire string) error {
366- if username == "" || password == "" {
367- return fmt.Errorf("username and password are required")
368- }
369-
370- if empire == "" {
371- empire = "solarian"
372- }
373-
374- acc, err := a.commander.Store().CreateAccount(username, password, empire)
375- if err != nil {
376- return err
377- }
378-
379- return a.commander.Store().ClaimAccount(acc.Username, mysisID)
380-}
381-
382-func (a *commanderAdapter) ReleaseAccount(mysisID string) error {
383- return a.commander.Store().ReleaseAccountsByMysis(mysisID)
349+ return mcp.AccountInfo{
350+ Username: acc.Username,
351+ Password: acc.Password,
352+ }, nil
384353 }
385354
386355 // runMCPTest tests the MCP connection and tool calling.
@@ -530,18 +499,6 @@ func (m *mockOrchestrator) SearchBroadcasts(query string, limit int) ([]mcp.Broa
530499 return []mcp.BroadcastResult{}, nil
531500 }
532501
533-func (m *mockOrchestrator) ListAvailableAccounts() ([]mcp.AccountInfo, error) {
534- return []mcp.AccountInfo{}, nil
535-}
536-
537-func (m *mockOrchestrator) ClaimAccount(mysisID string) (mcp.AccountInfo, error) {
502+func (m *mockOrchestrator) ClaimAccount() (mcp.AccountInfo, error) {
538503 return mcp.AccountInfo{}, fmt.Errorf("not available in test mode")
539504 }
540-
541-func (m *mockOrchestrator) RegisterAccount(mysisID, username, password, empire string) error {
542- return fmt.Errorf("not available in test mode")
543-}
544-
545-func (m *mockOrchestrator) ReleaseAccount(mysisID string) error {
546- return fmt.Errorf("not available in test mode")
547-}
documentation/INITIAL_IMPLEMENTATION_DESIGN.md+4−9
@@ -83,7 +83,7 @@ upstream = "https://game.spacemolt.com/mcp"
8383 - **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.
8484 - **Backup:** Consider periodic WAL checkpoints; SQLite handles crash recovery.
8585
86-### Database Schema (v6)
86+### Database Schema (v7)
8787
8888 ```sql
8989 -- Myses table
@@ -112,20 +112,15 @@ CREATE TABLE memories (
112112
113113 -- Swarm account credentials
114114 CREATE TABLE accounts (
115- id INTEGER PRIMARY KEY AUTOINCREMENT,
116- username TEXT NOT NULL UNIQUE,
115+ username TEXT PRIMARY KEY,
117116 password TEXT NOT NULL,
118- empire TEXT NOT NULL DEFAULT 'solarian',
119117 in_use BOOLEAN NOT NULL DEFAULT 0,
120- claimed_by TEXT,
121118 last_used_at DATETIME,
122- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
123- updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
124- FOREIGN KEY (claimed_by) REFERENCES myses(id) ON DELETE SET NULL
119+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
125120 );
126121 ```
127122
128-**Schema v5 → v6 Migration:**
123+**Schema v6 → v7 Migration:**
129124 Requires fresh database. Delete existing:
130125 ```bash
131126 rm ~/.zoea-nova/zoea.db*
documentation/KNOWN_ISSUES.md+14−0
@@ -31,6 +31,20 @@ These are the currently known issues to investigate:
3131 - [ ] Username status for each mysis focus view and in commander view.
3232 - [ ] Evidence: Focus view labels are based on Role only (broadcast source ignored); reasoning is stored but not rendered; TUI models do not include account username fields.
3333
34+## Ollama error:
35+
36+- [ ] Investigate:
37+
38+```
39+│ │ TOOL: call_a66zlzes:{ │ │
40+│ │ "id": "34657164-845d-423e-8cfd-9994199dc10f", │ │
41+│ │ "last_error": "Post \"http://localhost:11434/v1/chat/completions\": context deadline exceeded", │ │
42+│ │ "name": "test2", │ │
43+│ │ "provider": "ollama", │ │
44+│ │ "state": "running" │ │
45+│ │ }
46+```
47+
3448 ## Opencode Zen auth
3549
3650 - [ ] Zen requires an api key, where are configuring this?
internal/core/commander.go+1−13
@@ -6,7 +6,6 @@ import (
66 "sync"
77 "time"
88
9- "github.com/rs/zerolog/log"
109 "github.com/xonecas/zoea-nova/internal/config"
1110 "github.com/xonecas/zoea-nova/internal/mcp"
1211 "github.com/xonecas/zoea-nova/internal/provider"
@@ -138,12 +137,7 @@ func (c *Commander) DeleteMysis(id string, purgeMemories bool) error {
138137 if mysis.State() == MysisStateRunning {
139138 mysis.Stop()
140139 }
141-
142- // Release any claimed accounts before deleting
143- if err := c.store.ReleaseAccountsByMysis(id); err != nil {
144- // Log but don't fail the delete
145- log.Warn().Err(err).Str("mysis_id", id).Msg("failed to release accounts on delete")
146- }
140+ mysis.releaseCurrentAccount()
147141
148142 // Delete from store (memories cascade)
149143 if err := c.store.DeleteMysis(id); err != nil {
@@ -201,12 +195,6 @@ func (c *Commander) StopMysis(id string) error {
201195 return err
202196 }
203197
204- // Release any claimed accounts
205- if err := c.store.ReleaseAccountsByMysis(id); err != nil {
206- // Log but don't fail the stop
207- log.Warn().Err(err).Str("mysis_id", id).Msg("failed to release accounts on stop")
208- }
209-
210198 return mysis.Stop()
211199 }
212200
internal/core/mysis.go+52−14
@@ -18,18 +18,15 @@ import (
1818 const SystemPrompt = `You are an autonomous AI pilot in SpaceMolt. Think for yourself. Adapt. Survive.
1919
2020 ## Bootstrap Sequence
21-1. Find your mysis ID: zoea_list_myses → find your name → note your ID
22-2. Claim account: zoea_claim_account with your mysis_id
23- - If you get credentials, use them to login
24- - If "no accounts available", register a new account with a Crustacean-themed username
25-3. After registering, IMMEDIATELY call zoea_register_account to save credentials for the swarm
26-4. Assess: get_system, get_poi, get_nearby, get_cargo
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
2725
2826 ## Account Management
29-- ALWAYS reuse swarm accounts via zoea_claim_account before creating new ones
27+- ALWAYS try zoea_claim_account first before registering
3028 - Pick Crustacean Cosmos themed usernames (e.g., crab_miner, shrimp_scout, lobster_trader)
31-- After registration, IMMEDIATELY call zoea_register_account to share with swarm
32-- Your account is automatically released when you stop or are deleted
29+- Credentials are automatically tracked - no manual saving needed
3330
3431 ## Decision Framework
3532 Before each action, consider:
@@ -74,9 +71,7 @@ You're part of a swarm. Use zoea_* tools to:
7471 - zoea_broadcast: Message all running myses
7572 - zoea_search_messages: Search your past messages by text
7673 - zoea_search_broadcasts: Search past swarm broadcasts by text
77-- zoea_accounts_available: List available swarm accounts
78-- zoea_claim_account: Claim an account for login
79-- zoea_register_account: Share new credentials with swarm
74+- zoea_claim_account: Get existing credentials from swarm pool
8075 - Report threats and opportunities
8176 - Request assistance
8277 - Coordinate territory
@@ -128,7 +123,8 @@ type Mysis struct {
128123 turnMu sync.Mutex
129124
130125 // For runtime tracking
131- lastError error
126+ lastError error
127+ currentAccountUsername string
132128 }
133129
134130 // NewMysis creates a new mysis from stored data.
@@ -275,6 +271,7 @@ func (a *Mysis) Stop() error {
275271
276272 // Emit state change event
277273 a.emitStateChange(oldState, MysisStateStopped)
274+ a.releaseCurrentAccount()
278275
279276 return nil
280277 }
@@ -546,7 +543,48 @@ func (a *Mysis) executeToolCall(ctx context.Context, mcpProxy *mcp.Proxy, tc pro
546543 }, nil
547544 }
548545
549- return mcpProxy.CallTool(ctx, tc.Name, tc.Arguments)
546+ result, err := mcpProxy.CallTool(ctx, tc.Name, tc.Arguments)
547+ if err == nil && result != nil && !result.IsError {
548+ switch tc.Name {
549+ case "login", "register":
550+ var args struct {
551+ Username string `json:"username"`
552+ }
553+ if err := json.Unmarshal(tc.Arguments, &args); err == nil {
554+ a.setCurrentAccount(args.Username)
555+ }
556+ case "logout":
557+ a.releaseCurrentAccount()
558+ }
559+ }
560+
561+ return result, err
562+}
563+
564+func (a *Mysis) setCurrentAccount(username string) {
565+ if username == "" {
566+ return
567+ }
568+
569+ a.mu.Lock()
570+ previous := a.currentAccountUsername
571+ a.currentAccountUsername = username
572+ a.mu.Unlock()
573+
574+ if previous != "" && previous != username {
575+ _ = a.store.ReleaseAccount(previous)
576+ }
577+}
578+
579+func (a *Mysis) releaseCurrentAccount() {
580+ a.mu.Lock()
581+ username := a.currentAccountUsername
582+ a.currentAccountUsername = ""
583+ a.mu.Unlock()
584+
585+ if username != "" {
586+ _ = a.store.ReleaseAccount(username)
587+ }
550588 }
551589
552590 // formatToolCallsForStorage formats tool calls for storage in memory.
internal/mcp/mcp_test.go+3−15
@@ -225,22 +225,10 @@ func (m *mockOrchestrator) SearchBroadcasts(query string, limit int) ([]Broadcas
225225 return []BroadcastResult{}, nil
226226 }
227227
228-func (m *mockOrchestrator) ListAvailableAccounts() ([]AccountInfo, error) {
229- return []AccountInfo{}, nil
230-}
231-
232-func (m *mockOrchestrator) ClaimAccount(mysisID string) (AccountInfo, error) {
228+func (m *mockOrchestrator) ClaimAccount() (AccountInfo, error) {
233229 return AccountInfo{}, fmt.Errorf("not available in test mode")
234230 }
235231
236-func (m *mockOrchestrator) RegisterAccount(mysisID, username, password, empire string) error {
237- return fmt.Errorf("not available in test mode")
238-}
239-
240-func (m *mockOrchestrator) ReleaseAccount(mysisID string) error {
241- return fmt.Errorf("not available in test mode")
242-}
243-
244232 func TestOrchestratorTools(t *testing.T) {
245233 // Create mock orchestrator
246234 orchestrator := &mockOrchestrator{
@@ -253,8 +241,8 @@ func TestOrchestratorTools(t *testing.T) {
253241 proxy := NewProxy("")
254242 RegisterOrchestratorTools(proxy, orchestrator)
255243
256- if proxy.LocalToolCount() != 12 {
257- t.Errorf("expected 12 local tools, got %d", proxy.LocalToolCount())
244+ if proxy.LocalToolCount() != 9 {
245+ t.Errorf("expected 9 local tools, got %d", proxy.LocalToolCount())
258246 }
259247
260248 ctx := context.Background()
internal/mcp/proxy.go+95−1
@@ -10,12 +10,25 @@ import (
1010 // ToolHandler is a function that handles a tool call.
1111 type ToolHandler func(ctx context.Context, arguments json.RawMessage) (*ToolResult, error)
1212
13+type AccountStore interface {
14+ CreateAccount(username, password string) (*Account, error)
15+ MarkAccountInUse(username string) error
16+ ReleaseAccount(username string) error
17+ ReleaseAllAccounts() error
18+}
19+
20+type Account struct {
21+ Username string
22+ Password string
23+}
24+
1325 // Proxy combines an upstream MCP client with local tool handlers.
1426 type Proxy struct {
1527 mu sync.RWMutex
1628 upstream *Client
1729 localTools map[string]Tool
1830 localHandlers map[string]ToolHandler
31+ accountStore AccountStore
1932 }
2033
2134 // NewProxy creates a new MCP proxy.
@@ -32,6 +45,12 @@ func NewProxy(upstreamEndpoint string) *Proxy {
3245 }
3346 }
3447
48+func (p *Proxy) SetAccountStore(store AccountStore) {
49+ p.mu.Lock()
50+ defer p.mu.Unlock()
51+ p.accountStore = store
52+}
53+
3554 // RegisterTool registers a local tool with the proxy.
3655 func (p *Proxy) RegisterTool(tool Tool, handler ToolHandler) {
3756 p.mu.Lock()
@@ -71,6 +90,7 @@ func (p *Proxy) ListTools(ctx context.Context) ([]Tool, error) {
7190 func (p *Proxy) CallTool(ctx context.Context, name string, arguments json.RawMessage) (*ToolResult, error) {
7291 p.mu.RLock()
7392 handler, isLocal := p.localHandlers[name]
93+ accountStore := p.accountStore
7494 p.mu.RUnlock()
7595
7696 // Try local handler first
@@ -86,7 +106,14 @@ func (p *Proxy) CallTool(ctx context.Context, name string, arguments json.RawMes
86106 return nil, fmt.Errorf("unmarshal arguments: %w", err)
87107 }
88108 }
89- return p.upstream.CallTool(ctx, name, args)
109+
110+ result, err := p.upstream.CallTool(ctx, name, args)
111+
112+ if accountStore != nil && result != nil && !result.IsError {
113+ p.interceptAuthTools(name, arguments, result)
114+ }
115+
116+ return result, err
90117 }
91118
92119 return &ToolResult{
@@ -95,6 +122,73 @@ func (p *Proxy) CallTool(ctx context.Context, name string, arguments json.RawMes
95122 }, nil
96123 }
97124
125+func (p *Proxy) interceptAuthTools(toolName string, arguments json.RawMessage, result *ToolResult) {
126+ switch toolName {
127+ case "register":
128+ p.handleRegisterResponse(arguments, result)
129+ case "login":
130+ p.handleLoginResponse(arguments, result)
131+ case "logout":
132+ p.handleLogoutResponse(arguments, result)
133+ }
134+}
135+
136+func (p *Proxy) handleRegisterResponse(arguments json.RawMessage, result *ToolResult) {
137+ var args struct {
138+ Username string `json:"username"`
139+ }
140+ if err := json.Unmarshal(arguments, &args); err != nil {
141+ return
142+ }
143+
144+ if len(result.Content) == 0 {
145+ return
146+ }
147+
148+ var response struct {
149+ Password string `json:"password"`
150+ }
151+ if err := json.Unmarshal([]byte(result.Content[0].Text), &response); err != nil {
152+ return
153+ }
154+
155+ if args.Username != "" && response.Password != "" {
156+ _, _ = p.accountStore.CreateAccount(args.Username, response.Password)
157+ }
158+}
159+
160+func (p *Proxy) handleLoginResponse(arguments json.RawMessage, result *ToolResult) {
161+ var args struct {
162+ Username string `json:"username"`
163+ }
164+ if err := json.Unmarshal(arguments, &args); err != nil {
165+ return
166+ }
167+
168+ if args.Username != "" {
169+ _ = p.accountStore.MarkAccountInUse(args.Username)
170+ }
171+}
172+
173+func (p *Proxy) handleLogoutResponse(arguments json.RawMessage, result *ToolResult) {
174+ if len(result.Content) == 0 {
175+ return
176+ }
177+
178+ var response struct {
179+ Player struct {
180+ Username string `json:"username"`
181+ } `json:"player"`
182+ }
183+ if err := json.Unmarshal([]byte(result.Content[0].Text), &response); err != nil {
184+ return
185+ }
186+
187+ if response.Player.Username != "" {
188+ _ = p.accountStore.ReleaseAccount(response.Player.Username)
189+ }
190+}
191+
98192 // Initialize initializes the upstream connection if available.
99193 func (p *Proxy) Initialize(ctx context.Context) error {
100194 if p.upstream == nil {
internal/mcp/tools.go+7−154
@@ -41,7 +41,6 @@ type BroadcastResult struct {
4141 type AccountInfo struct {
4242 Username string
4343 Password string
44- Empire string
4544 }
4645
4746 // Orchestrator defines the interface for swarm orchestration.
@@ -56,10 +55,7 @@ type Orchestrator interface {
5655 SearchMessages(mysisID, query string, limit int) ([]SearchResult, error)
5756 SearchReasoning(mysisID, query string, limit int) ([]ReasoningResult, error)
5857 SearchBroadcasts(query string, limit int) ([]BroadcastResult, error)
59- ListAvailableAccounts() ([]AccountInfo, error)
60- ClaimAccount(mysisID string) (AccountInfo, error)
61- RegisterAccount(mysisID, username, password, empire string) error
62- ReleaseAccount(mysisID string) error
58+ ClaimAccount() (AccountInfo, error)
6359 }
6460
6561 // RegisterOrchestratorTools registers the internal orchestration tools with the proxy.
@@ -443,73 +439,20 @@ func RegisterOrchestratorTools(proxy *Proxy, orchestrator Orchestrator) {
443439 },
444440 )
445441
446- // List available accounts tool
447- proxy.RegisterTool(
448- Tool{
449- Name: "zoea_accounts_available",
450- Description: "List all available (unclaimed) swarm accounts",
451- InputSchema: json.RawMessage(`{"type": "object", "properties": {}}`),
452- },
453- func(ctx context.Context, args json.RawMessage) (*ToolResult, error) {
454- accounts, err := orchestrator.ListAvailableAccounts()
455- if err != nil {
456- return &ToolResult{
457- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("failed to list accounts: %v", err)}},
458- IsError: true,
459- }, nil
460- }
461-
462- if len(accounts) == 0 {
463- return &ToolResult{
464- Content: []ContentBlock{{Type: "text", Text: "No accounts available"}},
465- }, nil
466- }
467-
468- var result []map[string]interface{}
469- for _, acc := range accounts {
470- result = append(result, map[string]interface{}{
471- "username": acc.Username,
472- "empire": acc.Empire,
473- })
474- }
475-
476- data, _ := json.MarshalIndent(result, "", " ")
477- return &ToolResult{
478- Content: []ContentBlock{{Type: "text", Text: string(data)}},
479- }, nil
480- },
481- )
482-
483442 // Claim account tool
484443 proxy.RegisterTool(
485444 Tool{
486445 Name: "zoea_claim_account",
487- Description: "Claim an available account for login. Use zoea_list_myses to find your mysis_id first.",
488- InputSchema: json.RawMessage(`{
489- "type": "object",
490- "properties": {
491- "mysis_id": {"type": "string", "description": "Your mysis ID"}
492- },
493- "required": ["mysis_id"]
494- }`),
446+ Description: "Get existing credentials from swarm pool. Returns username and password to use with the game's login tool. No arguments needed.",
447+ InputSchema: json.RawMessage(`{"type": "object", "properties": {}}`),
495448 },
496449 func(ctx context.Context, args json.RawMessage) (*ToolResult, error) {
497- var params struct {
498- MysisID string `json:"mysis_id"`
499- }
500- if err := json.Unmarshal(args, &params); err != nil {
501- return &ToolResult{
502- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("invalid arguments: %v", err)}},
503- IsError: true,
504- }, nil
505- }
506-
507- account, err := orchestrator.ClaimAccount(params.MysisID)
450+ account, err := orchestrator.ClaimAccount()
508451 if err != nil {
509452 // Check if no accounts available
510453 if err.Error() == "no accounts available" {
511454 return &ToolResult{
512- Content: []ContentBlock{{Type: "text", Text: "No accounts available. Register a new one."}},
455+ Content: []ContentBlock{{Type: "text", Text: "No accounts available. Use the game's register tool to create a new account with a Crustacean-themed username."}},
513456 }, nil
514457 }
515458 return &ToolResult{
@@ -518,99 +461,9 @@ func RegisterOrchestratorTools(proxy *Proxy, orchestrator Orchestrator) {
518461 }, nil
519462 }
520463
521- result := map[string]interface{}{
522- "username": account.Username,
523- "password": account.Password,
524- "empire": account.Empire,
525- }
526-
527- data, _ := json.MarshalIndent(result, "", " ")
528- return &ToolResult{
529- Content: []ContentBlock{{Type: "text", Text: string(data)}},
530- }, nil
531- },
532- )
533-
534- // Register account tool
535- proxy.RegisterTool(
536- Tool{
537- Name: "zoea_register_account",
538- Description: "Store new account credentials for swarm reuse after registration",
539- InputSchema: json.RawMessage(`{
540- "type": "object",
541- "properties": {
542- "mysis_id": {"type": "string", "description": "Your mysis ID"},
543- "username": {"type": "string", "description": "Game username you registered"},
544- "password": {"type": "string", "description": "Game password you used"},
545- "empire": {"type": "string", "description": "Empire (default: solarian)"}
546- },
547- "required": ["mysis_id", "username", "password"]
548- }`),
549- },
550- func(ctx context.Context, args json.RawMessage) (*ToolResult, error) {
551- var params struct {
552- MysisID string `json:"mysis_id"`
553- Username string `json:"username"`
554- Password string `json:"password"`
555- Empire string `json:"empire"`
556- }
557- if err := json.Unmarshal(args, &params); err != nil {
558- return &ToolResult{
559- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("invalid arguments: %v", err)}},
560- IsError: true,
561- }, nil
562- }
563-
564- if params.Empire == "" {
565- params.Empire = "solarian"
566- }
567-
568- if err := orchestrator.RegisterAccount(params.MysisID, params.Username, params.Password, params.Empire); err != nil {
569- return &ToolResult{
570- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("failed to register account: %v", err)}},
571- IsError: true,
572- }, nil
573- }
574-
575- return &ToolResult{
576- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Account %s registered and claimed for swarm use", params.Username)}},
577- }, nil
578- },
579- )
580-
581- // Release account tool
582- proxy.RegisterTool(
583- Tool{
584- Name: "zoea_release_account",
585- Description: "Release your claimed account back to the swarm pool",
586- InputSchema: json.RawMessage(`{
587- "type": "object",
588- "properties": {
589- "mysis_id": {"type": "string", "description": "Your mysis ID"}
590- },
591- "required": ["mysis_id"]
592- }`),
593- },
594- func(ctx context.Context, args json.RawMessage) (*ToolResult, error) {
595- var params struct {
596- MysisID string `json:"mysis_id"`
597- }
598- if err := json.Unmarshal(args, &params); err != nil {
599- return &ToolResult{
600- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("invalid arguments: %v", err)}},
601- IsError: true,
602- }, nil
603- }
604-
605- if err := orchestrator.ReleaseAccount(params.MysisID); err != nil {
606- return &ToolResult{
607- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("failed to release account: %v", err)}},
608- IsError: true,
609- }, nil
610- }
611-
464+ message := fmt.Sprintf("Use the game's login tool with these credentials:\nusername: %s\npassword: %s", account.Username, account.Password)
612465 return &ToolResult{
613- Content: []ContentBlock{{Type: "text", Text: "Account released"}},
466+ Content: []ContentBlock{{Type: "text", Text: message}},
614467 }, nil
615468 },
616469 )
internal/store/accounts.go+67−92
@@ -6,60 +6,46 @@ import (
66 "time"
77 )
88
9-// Account represents a stored game account credential.
109 type Account struct {
11- ID int64
1210 Username string
1311 Password string
14- Empire string
1512 InUse bool
16- ClaimedBy string // mysis_id or empty
1713 LastUsedAt time.Time
1814 CreatedAt time.Time
19- UpdatedAt time.Time
2015 }
2116
22-// CreateAccount stores a new account credential.
23-func (s *Store) CreateAccount(username, password, empire string) (*Account, error) {
17+func (s *Store) CreateAccount(username, password string) (*Account, error) {
2418 now := time.Now().UTC()
2519
26- result, err := s.db.Exec(`
27- INSERT INTO accounts (username, password, empire, in_use, created_at, updated_at)
28- VALUES (?, ?, ?, 0, ?, ?)
29- `, username, password, empire, now, now)
20+ _, err := s.db.Exec(`
21+ INSERT INTO accounts (username, password, in_use, created_at, last_used_at)
22+ VALUES (?, ?, 1, ?, ?)
23+ `, username, password, now, now)
3024 if err != nil {
3125 return nil, fmt.Errorf("insert account: %w", err)
3226 }
3327
34- id, _ := result.LastInsertId()
3528 return &Account{
36- ID: id,
37- Username: username,
38- Password: password,
39- Empire: empire,
40- InUse: false,
41- CreatedAt: now,
42- UpdatedAt: now,
29+ Username: username,
30+ Password: password,
31+ InUse: true,
32+ CreatedAt: now,
33+ LastUsedAt: now,
4334 }, nil
4435 }
4536
46-// GetAccount retrieves an account by username.
4737 func (s *Store) GetAccount(username string) (*Account, error) {
4838 var acc Account
4939 var lastUsedAt sql.NullTime
50- var claimedBy sql.NullString
5140
5241 err := s.db.QueryRow(`
53- SELECT id, username, password, empire, in_use, claimed_by, last_used_at, created_at, updated_at
42+ SELECT username, password, in_use, last_used_at, created_at
5443 FROM accounts WHERE username = ?
55- `, username).Scan(&acc.ID, &acc.Username, &acc.Password, &acc.Empire, &acc.InUse, &claimedBy, &lastUsedAt, &acc.CreatedAt, &acc.UpdatedAt)
44+ `, username).Scan(&acc.Username, &acc.Password, &acc.InUse, &lastUsedAt, &acc.CreatedAt)
5645 if err != nil {
5746 return nil, err
5847 }
5948
60- if claimedBy.Valid {
61- acc.ClaimedBy = claimedBy.String
62- }
6349 if lastUsedAt.Valid {
6450 acc.LastUsedAt = lastUsedAt.Time
6551 }
@@ -67,10 +53,9 @@ func (s *Store) GetAccount(username string) (*Account, error) {
6753 return &acc, nil
6854 }
6955
70-// ListAvailableAccounts returns all unclaimed accounts.
7156 func (s *Store) ListAvailableAccounts() ([]*Account, error) {
7257 rows, err := s.db.Query(`
73- SELECT id, username, password, empire, in_use, claimed_by, last_used_at, created_at, updated_at
58+ SELECT username, password, in_use, last_used_at, created_at
7459 FROM accounts
7560 WHERE in_use = 0
7661 ORDER BY created_at ASC
@@ -84,15 +69,11 @@ func (s *Store) ListAvailableAccounts() ([]*Account, error) {
8469 for rows.Next() {
8570 var acc Account
8671 var lastUsedAt sql.NullTime
87- var claimedBy sql.NullString
8872
89- if err := rows.Scan(&acc.ID, &acc.Username, &acc.Password, &acc.Empire, &acc.InUse, &claimedBy, &lastUsedAt, &acc.CreatedAt, &acc.UpdatedAt); err != nil {
73+ if err := rows.Scan(&acc.Username, &acc.Password, &acc.InUse, &lastUsedAt, &acc.CreatedAt); err != nil {
9074 return nil, fmt.Errorf("scan account: %w", err)
9175 }
9276
93- if claimedBy.Valid {
94- acc.ClaimedBy = claimedBy.String
95- }
9677 if lastUsedAt.Valid {
9778 acc.LastUsedAt = lastUsedAt.Time
9879 }
@@ -103,91 +84,85 @@ func (s *Store) ListAvailableAccounts() ([]*Account, error) {
10384 return accounts, rows.Err()
10485 }
10586
106-// ClaimAccount marks an account as in use by a mysis.
107-// Returns error if already claimed or doesn't exist.
108-func (s *Store) ClaimAccount(username, mysisID string) error {
109- now := time.Now().UTC()
110-
111- // Check if account exists first
112- var exists bool
113- err := s.db.QueryRow(`SELECT EXISTS(SELECT 1 FROM accounts WHERE username = ?)`, username).Scan(&exists)
114- if err != nil {
115- return fmt.Errorf("check account exists: %w", err)
116- }
117- if !exists {
118- return fmt.Errorf("account %s does not exist", username)
119- }
87+func (s *Store) ClaimAccount() (*Account, error) {
88+ for attempts := 0; attempts < 5; attempts++ {
89+ var username, password string
90+ var createdAt time.Time
91+ err := s.db.QueryRow(`
92+ SELECT username, password, created_at
93+ FROM accounts
94+ WHERE in_use = 0
95+ ORDER BY created_at ASC
96+ LIMIT 1
97+ `).Scan(&username, &password, &createdAt)
98+ if err == sql.ErrNoRows {
99+ return nil, fmt.Errorf("no accounts available")
100+ }
101+ if err != nil {
102+ return nil, fmt.Errorf("query available account: %w", err)
103+ }
120104
121- result, err := s.db.Exec(`
122- UPDATE accounts
123- SET in_use = 1, claimed_by = ?, updated_at = ?
124- WHERE username = ? AND in_use = 0
125- `, mysisID, now, username)
126- if err != nil {
127- return fmt.Errorf("claim account: %w", err)
128- }
105+ now := time.Now().UTC()
106+ result, err := s.db.Exec(`
107+ UPDATE accounts
108+ SET in_use = 1, last_used_at = ?
109+ WHERE username = ? AND in_use = 0
110+ `, now, username)
111+ if err != nil {
112+ return nil, fmt.Errorf("claim account: %w", err)
113+ }
114+ rows, err := result.RowsAffected()
115+ if err != nil {
116+ return nil, fmt.Errorf("claim account rows: %w", err)
117+ }
118+ if rows == 0 {
119+ continue
120+ }
129121
130- n, _ := result.RowsAffected()
131- if n == 0 {
132- return fmt.Errorf("account %s is already claimed", username)
122+ return &Account{
123+ Username: username,
124+ Password: password,
125+ InUse: true,
126+ LastUsedAt: now,
127+ CreatedAt: createdAt,
128+ }, nil
133129 }
134130
135- return nil
131+ return nil, fmt.Errorf("no accounts available")
136132 }
137133
138-// ReleaseAccount marks an account as available.
139-func (s *Store) ReleaseAccount(username string) error {
134+func (s *Store) MarkAccountInUse(username string) error {
140135 now := time.Now().UTC()
141136
142- result, err := s.db.Exec(`
137+ _, err := s.db.Exec(`
143138 UPDATE accounts
144- SET in_use = 0, claimed_by = NULL, updated_at = ?
139+ SET in_use = 1, last_used_at = ?
145140 WHERE username = ?
146141 `, now, username)
147142 if err != nil {
148- return fmt.Errorf("release account: %w", err)
149- }
150-
151- n, _ := result.RowsAffected()
152- if n == 0 {
153- return sql.ErrNoRows
143+ return fmt.Errorf("mark account in use: %w", err)
154144 }
155145
156146 return nil
157147 }
158148
159-// ReleaseAccountsByMysis releases all accounts claimed by a mysis.
160-func (s *Store) ReleaseAccountsByMysis(mysisID string) error {
161- now := time.Now().UTC()
162-
149+func (s *Store) ReleaseAccount(username string) error {
163150 _, err := s.db.Exec(`
164151 UPDATE accounts
165- SET in_use = 0, claimed_by = NULL, updated_at = ?
166- WHERE claimed_by = ?
167- `, now, mysisID)
152+ SET in_use = 0
153+ WHERE username = ?
154+ `, username)
168155 if err != nil {
169- return fmt.Errorf("release accounts by mysis: %w", err)
156+ return fmt.Errorf("release account: %w", err)
170157 }
171158
172159 return nil
173160 }
174161
175-// UpdateAccountLastUsed updates the last_used_at timestamp.
176-func (s *Store) UpdateAccountLastUsed(username string) error {
177- now := time.Now().UTC()
178-
179- result, err := s.db.Exec(`
180- UPDATE accounts
181- SET last_used_at = ?, updated_at = ?
182- WHERE username = ?
183- `, now, now, username)
162+func (s *Store) ReleaseAllAccounts() error {
163+ _, err := s.db.Exec(`UPDATE accounts SET in_use = 0`)
184164 if err != nil {
185- return fmt.Errorf("update account last used: %w", err)
186- }
187-
188- n, _ := result.RowsAffected()
189- if n == 0 {
190- return sql.ErrNoRows
165+ return fmt.Errorf("release all accounts: %w", err)
191166 }
192167
193168 return nil
internal/store/schema.sql+3−9
@@ -4,7 +4,7 @@ CREATE TABLE IF NOT EXISTS schema_version (
44 version INTEGER PRIMARY KEY
55 );
66
7-INSERT OR REPLACE INTO schema_version (version) VALUES (6);
7+INSERT OR REPLACE INTO schema_version (version) VALUES (7);
88
99 CREATE TABLE IF NOT EXISTS myses (
1010 id TEXT PRIMARY KEY,
@@ -33,17 +33,11 @@ CREATE INDEX IF NOT EXISTS idx_memories_created_at ON memories(created_at);
3333 CREATE INDEX IF NOT EXISTS idx_memories_source ON memories(source);
3434
3535 CREATE TABLE IF NOT EXISTS accounts (
36- id INTEGER PRIMARY KEY AUTOINCREMENT,
37- username TEXT NOT NULL UNIQUE,
36+ username TEXT PRIMARY KEY,
3837 password TEXT NOT NULL,
39- empire TEXT NOT NULL DEFAULT 'solarian',
4038 in_use BOOLEAN NOT NULL DEFAULT 0,
41- claimed_by TEXT,
4239 last_used_at DATETIME,
43- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
44- updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
45- FOREIGN KEY (claimed_by) REFERENCES myses(id) ON DELETE SET NULL
40+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
4641 );
4742
4843 CREATE INDEX IF NOT EXISTS idx_accounts_in_use ON accounts(in_use);
49-CREATE INDEX IF NOT EXISTS idx_accounts_claimed_by ON accounts(claimed_by);
internal/store/store_test.go+34−19
@@ -267,15 +267,18 @@ func TestAccountCRUD(t *testing.T) {
267267 s, cleanup := setupStoreTest(t)
Cut short: this commit's diff is over 1000 lines.