xonecas.io
60255
Zn

Zoea-Nova / files

Zoea-Nova / cmd / zoea / main.go

13.6 KB
1package main
2
3import (
4	"context"
5	"flag"
6	"fmt"
7	"os"
8	"os/signal"
9	"path/filepath"
10	"runtime"
11	"strings"
12	"syscall"
13	"time"
14
15	tea "github.com/charmbracelet/bubbletea"
16	"github.com/rs/zerolog"
17	"github.com/rs/zerolog/log"
18
19	"github.com/xonecas/zoea-nova/internal/config"
20	"github.com/xonecas/zoea-nova/internal/core"
21	"github.com/xonecas/zoea-nova/internal/mcp"
22	"github.com/xonecas/zoea-nova/internal/provider"
23	"github.com/xonecas/zoea-nova/internal/store"
24	"github.com/xonecas/zoea-nova/internal/tui"
25)
26
27// Version is set at build time via ldflags.
28var Version = "dev"
29
30// logFile is the global log file handle, closed on shutdown.
31var logFile *os.File
32
33func main() {
34	// Parse flags
35	var (
36		showVersion = flag.Bool("version", false, "Show version and exit")
37		configPath  = flag.String("config", "config.toml", "Path to config file")
38		debug       = flag.Bool("debug", false, "Enable debug logging")
39		testMCP     = flag.Bool("test-mcp", false, "Test MCP connection and tool calling, then exit")
40		offline     = flag.Bool("offline", false, "Run in offline mode with stub MCP server")
41		startSwarm  = flag.Bool("start-swarm", false, "Auto-start all idle myses on launch")
42	)
43	flag.Parse()
44
45	if *showVersion {
46		fmt.Printf("Zoea Nova %s\n", Version)
47		os.Exit(0)
48	}
49
50	if *testMCP {
51		runMCPTest(*configPath)
52		return
53	}
54
55	// Initialize logging
56	if err := initLogging(*debug); err != nil {
57		fmt.Fprintf(os.Stderr, "Failed to initialize logging: %v\n", err)
58		os.Exit(1)
59	}
60	defer func() {
61		if logFile != nil {
62			logFile.Close()
63		}
64	}()
65
66	log.Info().Str("version", Version).Msg("Starting Zoea Nova")
67
68	// Load configuration
69	cfg, err := config.Load(*configPath)
70	if err != nil {
71		log.Fatal().Err(err).Msg("Failed to load config")
72	}
73	log.Debug().Interface("config", cfg).Msg("Configuration loaded")
74
75	// Load credentials
76	creds, err := config.LoadCredentials()
77	if err != nil {
78		log.Warn().Err(err).Msg("Failed to load credentials")
79		creds = &config.Credentials{}
80	}
81
82	// Initialize store
83	s, err := store.New()
84	if err != nil {
85		log.Fatal().Err(err).Msg("Failed to initialize store")
86	}
87	defer s.Close()
88	log.Debug().Msg("Store initialized")
89
90	// Release all accounts on startup to clear stale in_use flags from crashes
91	if err := s.ReleaseAllAccounts(); err != nil {
92		log.Warn().Err(err).Msg("Failed to release accounts on startup")
93	} else {
94		log.Info().Msg("Released all accounts on startup")
95	}
96
97	// Initialize event bus
98	bus := core.NewEventBus(1000)
99	// Note: bus.Close() is called explicitly in onQuit callback and signal handler
100	// No defer needed here to avoid duplicate closes
101
102	// Initialize provider registry
103	registry := initProviders(cfg, creds)
104	log.Debug().Int("providers", len(registry.List())).Msg("Providers initialized")
105
106	// Determine MCP endpoint for myses
107	var mcpEndpoint string
108	if *offline {
109		log.Info().Msg("Running in offline mode - myses will use stub MCP client")
110		// Empty endpoint signals offline mode
111	} else if cfg.MCP.Upstream != "" {
112		mcpEndpoint = cfg.MCP.Upstream
113		log.Info().Str("endpoint", mcpEndpoint).Msg("MCP endpoint configured - each mysis will create its own client")
114	}
115
116	// Initialize commander with MCP endpoint
117	commander := core.NewCommander(s, registry, bus, cfg, mcpEndpoint)
118
119	// Load existing myses from database
120	if err := commander.LoadMyses(); err != nil {
121		log.Warn().Err(err).Msg("Failed to load existing myses")
122	}
123	log.Debug().Int("myses", commander.MysisCount()).Msg("Myses loaded")
124
125	// Auto-start all existing myses on launch
126	// Each mysis will create its own MCP client during Start()
127	for _, a := range commander.ListMyses() {
128		if err := a.Start(); err != nil {
129			log.Warn().Err(err).Str("mysis", a.Name()).Msg("Failed to start mysis")
130		}
131	}
132
133	// Log goroutine count at startup for leak detection
134	log.Info().Int("goroutines", runtime.NumGoroutine()).Msg("Application started")
135
136	// Set up signal handling for graceful shutdown
137	sigCh := make(chan os.Signal, 1)
138	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
139
140	// Subscribe to events for TUI
141	eventCh := bus.Subscribe()
142
143	// Create and run TUI
144	model := tui.New(commander, s, eventCh, *startSwarm, cfg)
145
146	// Set cleanup callback to close event bus before quit
147	model.SetOnQuit(func() {
148		bus.Close()
149	})
150
151	program := tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion())
152
153	// Handle shutdown in a goroutine
154	go func() {
155		<-sigCh
156		log.Info().Msg("Received shutdown signal")
157		// Don't call StopAll here - let main cleanup handle it after program.Run()
158		// This avoids stopping myses twice
159		bus.Close() // Close event bus to unblock TUI event listener
160		program.Quit()
161	}()
162
163	// Run the TUI
164	if _, err := program.Run(); err != nil {
165		log.Fatal().Err(err).Msg("TUI error")
166	}
167
168	// Clean shutdown
169	log.Info().Int("goroutines", runtime.NumGoroutine()).Msg("Shutdown initiated")
170	commander.StopAll()
171
172	// Close bus (idempotent if already closed by onQuit or signal handler)
173	bus.Close()
174
175	// Release all accounts
176	if err := s.ReleaseAllAccounts(); err != nil {
177		log.Warn().Err(err).Msg("Failed to release accounts on shutdown")
178	}
179
180	log.Info().Int("goroutines", runtime.NumGoroutine()).Msg("Zoea Nova shutdown complete")
181}
182
183func initLogging(debug bool) error {
184	// Ensure data directory exists
185	dataDir, err := config.EnsureDataDir()
186	if err != nil {
187		return fmt.Errorf("ensure data dir: %w", err)
188	}
189
190	// Open log file (truncate on startup)
191	logPath := filepath.Join(dataDir, "zoea.log")
192	var openErr error
193	logFile, openErr = os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
194	if openErr != nil {
195		return fmt.Errorf("open log file: %w", openErr)
196	}
197
198	// Configure zerolog
199	zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
200
201	if debug {
202		zerolog.SetGlobalLevel(zerolog.DebugLevel)
203	} else {
204		zerolog.SetGlobalLevel(zerolog.InfoLevel)
205	}
206
207	// Log to file only (TUI owns stdout/stderr)
208	log.Logger = zerolog.New(logFile).With().Timestamp().Logger()
209
210	return nil
211}
212
213func initProviders(cfg *config.Config, creds *config.Credentials) *provider.Registry {
214	registry := provider.NewRegistry()
215
216	for name, provCfg := range cfg.Providers {
217		// Detect provider type by endpoint
218		if strings.Contains(provCfg.Endpoint, "localhost:11434") || strings.Contains(provCfg.Endpoint, "/ollama") {
219			// Ollama-based provider
220			factory := provider.NewOllamaFactory(name, provCfg.Endpoint)
221			registry.RegisterFactory(name, factory)
222		} else if strings.Contains(provCfg.Endpoint, "opencode.ai") {
223			// OpenCode-based provider
224			// Use explicit api_key_name if provided, otherwise use provider config name
225			keyName := provCfg.APIKeyName
226			if keyName == "" {
227				keyName = name
228			}
229			apiKey := creds.GetAPIKey(keyName)
230			if apiKey != "" {
231				factory := provider.NewOpenCodeFactory(name, provCfg.Endpoint, apiKey)
232				registry.RegisterFactory(name, factory)
233			}
234		}
235	}
236
237	return registry
238}
239
240type accountStoreAdapter struct {
241	store *store.Store
242}
243
244func (a *accountStoreAdapter) CreateAccount(username, password string, mysisID ...string) (*mcp.Account, error) {
245	acc, err := a.store.CreateAccount(username, password, mysisID...)
246	if err != nil {
247		return nil, err
248	}
249	return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
250}
251
252func (a *accountStoreAdapter) GetAccountByMysisID(mysisID string) (*mcp.Account, error) {
253	acc, err := a.store.GetAccountByMysisID(mysisID)
254	if err != nil {
255		return nil, err
256	}
257	return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
258}
259
260func (a *accountStoreAdapter) AssignAccount(username, mysisID string) error {
261	return a.store.AssignAccount(username, mysisID)
262}
263
264func (a *accountStoreAdapter) ReleaseAccount(username string) error {
265	return a.store.ReleaseAccount(username)
266}
267
268func (a *accountStoreAdapter) ReleaseAccountByMysisID(mysisID string) error {
269	return a.store.ReleaseAccountByMysisID(mysisID)
270}
271
272func (a *accountStoreAdapter) ReleaseAllAccounts() error {
273	return a.store.ReleaseAllAccounts()
274}
275
276func (a *accountStoreAdapter) ClaimAccount(mysisID string) (*mcp.Account, error) {
277	acc, err := a.store.ClaimAccount(mysisID)
278	if err != nil {
279		return nil, err
280	}
281	return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
282}
283
284type commanderAdapter struct {
285	commander *core.Commander
286}
287
288func (a *commanderAdapter) MysisCount() int {
289	return a.commander.MysisCount()
290}
291
292func (a *commanderAdapter) MaxMyses() int {
293	return a.commander.MaxMyses()
294}
295
296func (a *commanderAdapter) GetStateCounts() map[string]int {
297	return a.commander.GetStateCounts()
298}
299
300func (a *commanderAdapter) SendMessageAsync(mysisID, message string) error {
301	return a.commander.SendMessageAsync(mysisID, message)
302}
303
304func (a *commanderAdapter) BroadcastAsync(message string) error {
305	return a.commander.BroadcastAsync(message)
306}
307
308func (a *commanderAdapter) BroadcastFrom(senderID, message string) error {
309	return a.commander.BroadcastFrom(senderID, message)
310}
311
312func (a *commanderAdapter) SearchMessages(mysisID, query string, limit int) ([]mcp.SearchResult, error) {
313	memories, err := a.commander.Store().SearchMemories(mysisID, query, limit)
314	if err != nil {
315		return nil, err
316	}
317
318	results := make([]mcp.SearchResult, len(memories))
319	for i, m := range memories {
320		results[i] = mcp.SearchResult{
321			Role:      string(m.Role),
322			Source:    string(m.Source),
323			Content:   m.Content,
324			CreatedAt: m.CreatedAt.Format("2006-01-02 15:04:05"),
325		}
326	}
327	return results, nil
328}
329
330func (a *commanderAdapter) SearchReasoning(mysisID, query string, limit int) ([]mcp.ReasoningResult, error) {
331	memories, err := a.commander.Store().SearchReasoning(mysisID, query, limit)
332	if err != nil {
333		return nil, err
334	}
335
336	results := make([]mcp.ReasoningResult, len(memories))
337	for i, m := range memories {
338		results[i] = mcp.ReasoningResult{
339			Role:      string(m.Role),
340			Source:    string(m.Source),
341			Content:   m.Content,
342			Reasoning: m.Reasoning,
343			CreatedAt: m.CreatedAt.Format("2006-01-02 15:04:05"),
344		}
345	}
346	return results, nil
347}
348
349// runMCPTest tests the MCP connection and tool calling.
350func runMCPTest(configPath string) {
351	fmt.Println("=== MCP Tool Test ===")
352	fmt.Println()
353
354	// Load config
355	cfg, err := config.Load(configPath)
356	if err != nil {
357		fmt.Printf("ERROR: Failed to load config: %v\n", err)
358		os.Exit(1)
359	}
360
361	// Create MCP proxy
362	fmt.Printf("Upstream MCP: %s\n", cfg.MCP.Upstream)
363	var upstreamClient mcp.UpstreamClient
364	if cfg.MCP.Upstream != "" {
365		upstreamClient = mcp.NewClient(cfg.MCP.Upstream)
366	}
367	mcpProxy := mcp.NewProxy(upstreamClient)
368
369	// Create a mock orchestrator for local tools
370	mockOrch := &mockOrchestrator{}
371	mcp.RegisterOrchestratorTools(mcpProxy, mockOrch)
372
373	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
374	defer cancel()
375
376	// Initialize upstream if configured
377	if mcpProxy.HasUpstream() {
378		fmt.Println("\nInitializing upstream MCP connection...")
379		if err := mcpProxy.Initialize(ctx); err != nil {
380			fmt.Printf("ERROR: Failed to initialize upstream: %v\n", err)
381			fmt.Println("(Continuing with local tools only)")
382		} else {
383			fmt.Println("OK: Upstream initialized")
384		}
385	} else {
386		fmt.Println("\nNo upstream configured - local tools only")
387	}
388
389	// List all tools
390	fmt.Println("\n--- Available Tools ---")
391	tools, err := mcpProxy.ListTools(ctx)
392	if err != nil {
393		fmt.Printf("ERROR: Failed to list tools: %v\n", err)
394		fmt.Println("(This may indicate the upstream server doesn't support tools/list or returned an error)")
395	}
396
397	if len(tools) == 0 {
398		fmt.Println("WARNING: No tools available!")
399	} else {
400		localCount := 0
401		upstreamCount := 0
402		for _, t := range tools {
403			prefix := "  "
404			if len(t.Name) > 5 && t.Name[:5] == "zoea_" {
405				prefix = "  [local] "
406				localCount++
407			} else {
408				prefix = "  [upstream] "
409				upstreamCount++
410			}
411			fmt.Printf("%s%s - %s\n", prefix, t.Name, t.Description)
412		}
413		fmt.Printf("\nTotal: %d tools (%d local, %d upstream)\n", len(tools), localCount, upstreamCount)
414	}
415
416	// Test calling a local tool - removed zoea_swarm_status as it has been deleted
417
418	// Test calling an upstream tool if available
419	if mcpProxy.HasUpstream() {
420		fmt.Println("\n--- Testing Upstream Tool Call ---")
421		// Try to find a non-zoea tool to call
422		var upstreamTool *mcp.Tool
423		for i := range tools {
424			if len(tools[i].Name) < 5 || tools[i].Name[:5] != "zoea_" {
425				upstreamTool = &tools[i]
426				break
427			}
428		}
429		if upstreamTool != nil {
430			fmt.Printf("Calling: %s\n", upstreamTool.Name)
431			result, err := mcpProxy.CallTool(ctx, mcp.CallerContext{}, upstreamTool.Name, nil)
432			if err != nil {
433				fmt.Printf("ERROR: %v\n", err)
434			} else if result.IsError {
435				fmt.Printf("TOOL ERROR: %s\n", result.Content[0].Text)
436			} else {
437				text := result.Content[0].Text
438				if len(text) > 200 {
439					text = text[:197] + "..."
440				}
441				fmt.Printf("OK: %s\n", text)
442			}
443		} else {
444			fmt.Println("No upstream tools found to test")
445		}
446	}
447
448	fmt.Println("\n=== Test Complete ===")
449}
450
451// mockOrchestrator is a simple orchestrator for testing.
452type mockOrchestrator struct{}
453
454func (m *mockOrchestrator) MysisCount() int {
455	return 0
456}
457
458func (m *mockOrchestrator) MaxMyses() int {
459	return 16
460}
461
462func (m *mockOrchestrator) GetStateCounts() map[string]int {
463	return map[string]int{
464		"running": 0,
465		"idle":    0,
466		"stopped": 0,
467		"errored": 0,
468	}
469}
470
471func (m *mockOrchestrator) SendMessageAsync(mysisID, message string) error {
472	return fmt.Errorf("not available in test mode")
473}
474
475func (m *mockOrchestrator) BroadcastAsync(message string) error {
476	return fmt.Errorf("not available in test mode")
477}
478
479func (m *mockOrchestrator) BroadcastFrom(senderID, message string) error {
480	return fmt.Errorf("not available in test mode")
481}
482
483func (m *mockOrchestrator) SearchMessages(mysisID, query string, limit int) ([]mcp.SearchResult, error) {
484	return []mcp.SearchResult{}, nil
485}
486
487func (m *mockOrchestrator) SearchReasoning(mysisID, query string, limit int) ([]mcp.ReasoningResult, error) {
488	return []mcp.ReasoningResult{}, nil
489}