xonecas.io
6119
My

mysis / commit cc99361

feat: code organization before agents mess it up too bad

xonecas2026-02-10 cc99361aec077088856a68adc860ecc47b0d1f70 parent 241fd64

8 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/mysis/main.go+2−915
@@ -1,932 +1,19 @@
11 package main
22
33 import (
4- "bufio"
5- "context"
6- "encoding/json"
7- "flag"
84 "fmt"
95 "os"
10- "strings"
11- "sync"
12- "time"
136
14- "github.com/google/uuid"
15- "github.com/rs/zerolog"
16- "github.com/rs/zerolog/log"
17- "github.com/xonecas/mysis/internal/config"
18- "github.com/xonecas/mysis/internal/constants"
19- "github.com/xonecas/mysis/internal/mcp"
20- "github.com/xonecas/mysis/internal/provider"
21- "github.com/xonecas/mysis/internal/store"
7+ "github.com/xonecas/mysis/internal/cli"
228 "github.com/xonecas/mysis/internal/styles"
239 )
2410
2511 // Version is set at build time via ldflags.
2612 var Version = "dev"
2713
28-// printHelp displays usage information.
29-func printHelp() {
30- fmt.Println(styles.Brand.Render("╔══════════════════════════════════════╗"))
31- fmt.Println(styles.Brand.Render("║") + " " + styles.BrandBold.Render("Mysis") + " - SpaceMolt Agent CLI " + styles.Brand.Render("║"))
32- fmt.Println(styles.Brand.Render("╚══════════════════════════════════════╝"))
33- fmt.Println()
34- fmt.Println(styles.BrandBold.Render("USAGE:"))
35- fmt.Println(" mysis [flags]")
36- fmt.Println()
37- fmt.Println(styles.BrandBold.Render("FLAGS:"))
38- fmt.Println(" " + styles.Secondary.Render("-h, --help") + " Show this help message")
39- fmt.Println(" " + styles.Secondary.Render("-v, --version") + " Show version information")
40- fmt.Println(" " + styles.Secondary.Render("-c, --config") + " PATH Path to config file (default: config.toml)")
41- fmt.Println(" " + styles.Secondary.Render("-d, --debug") + " Enable debug logging")
42- fmt.Println(" " + styles.Secondary.Render("-p, --provider") + " NAME Provider name (overrides config default)")
43- fmt.Println(" " + styles.Secondary.Render("-s, --session") + " NAME Session name (resume or create)")
44- fmt.Println(" " + styles.Secondary.Render("-a, --autoplay") + " MSG Start autoplay immediately with message")
45- fmt.Println(" " + styles.Secondary.Render("-l, --list-sessions") + " List recent sessions and exit")
46- fmt.Println(" " + styles.Secondary.Render("-D, --delete-session") + " N Delete session by name and exit")
47- fmt.Println()
48- fmt.Println(styles.BrandBold.Render("EXAMPLES:"))
49- fmt.Println(" # Start anonymous session")
50- fmt.Println(" mysis")
51- fmt.Println()
52- fmt.Println(" # Resume or create named session")
53- fmt.Println(" mysis -s mybot")
54- fmt.Println()
55- fmt.Println(" # Start with autoplay enabled")
56- fmt.Println(" mysis -s mybot -a \"explore and mine resources\"")
57- fmt.Println()
58- fmt.Println(" # List all sessions")
59- fmt.Println(" mysis -l")
60- fmt.Println()
61- fmt.Println(" # Delete a session")
62- fmt.Println(" mysis -D mybot")
63- fmt.Println()
64- fmt.Println(styles.BrandBold.Render("IN-SESSION COMMANDS:"))
65- fmt.Println(" " + styles.Secondary.Render("/autoplay <message>") + " Start autonomous gameplay with given goal")
66- fmt.Println(" " + styles.Secondary.Render("/autoplay stop") + " Stop autonomous gameplay")
67- fmt.Println(" " + styles.Secondary.Render("exit, quit") + " Exit the session")
68- fmt.Println()
69- fmt.Println(styles.Muted.Render("Note: Running without -s/--session creates an anonymous session (not saved by name)."))
70- fmt.Println()
71-}
72-
7314 func main() {
74- // Parse flags
75- var (
76- showHelp bool
77- showVersion bool
78- configPath string
79- debug bool
80- providerName string
81- sessionName string
82- listSessions bool
83- deleteSession string
84- autoplay string
85- )
86- flag.BoolVar(&showHelp, "help", false, "Show help and exit")
87- flag.BoolVar(&showHelp, "h", false, "Show help and exit (shorthand)")
88- flag.BoolVar(&showVersion, "version", false, "Show version and exit")
89- flag.BoolVar(&showVersion, "v", false, "Show version and exit (shorthand)")
90- flag.StringVar(&configPath, "config", "", "Path to config file")
91- flag.StringVar(&configPath, "c", "", "Path to config file (shorthand)")
92- flag.BoolVar(&debug, "debug", false, "Enable debug logging")
93- flag.BoolVar(&debug, "d", false, "Enable debug logging (shorthand)")
94- flag.StringVar(&providerName, "provider", "", "Provider name (overrides default from config)")
95- flag.StringVar(&providerName, "p", "", "Provider name (shorthand)")
96- flag.StringVar(&sessionName, "session", "", "Session name (resume or create named session)")
97- flag.StringVar(&sessionName, "s", "", "Session name (shorthand)")
98- flag.BoolVar(&listSessions, "list-sessions", false, "List recent sessions and exit")
99- flag.BoolVar(&listSessions, "l", false, "List recent sessions and exit (shorthand)")
100- flag.StringVar(&deleteSession, "delete-session", "", "Delete a session by name")
101- flag.StringVar(&deleteSession, "D", "", "Delete a session by name (shorthand)")
102- flag.StringVar(&autoplay, "autoplay", "", "Start autoplay immediately with given message")
103- flag.StringVar(&autoplay, "a", "", "Start autoplay immediately (shorthand)")
104-
105- // Custom usage function
106- flag.Usage = func() {
107- printHelp()
108- }
109-
110- flag.Parse()
111-
112- if showHelp {
113- printHelp()
114- os.Exit(0)
115- }
116-
117- if showVersion {
118- fmt.Printf("Mysis %s\n", Version)
119- os.Exit(0)
120- }
121-
122- // Initialize logging
123- zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
124- log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
125- if debug {
126- zerolog.SetGlobalLevel(zerolog.DebugLevel)
127- } else {
128- zerolog.SetGlobalLevel(zerolog.InfoLevel)
129- }
130-
131- // Find config file
132- if configPath == "" {
133- // Try current directory first, then ~/.config/mysis/
134- if _, err := os.Stat("config.toml"); err == nil {
135- configPath = "config.toml"
136- } else {
137- dataDir, err := config.DataDir()
138- if err == nil {
139- configPath = dataDir + "/config.toml"
140- }
141- }
142- }
143-
144- if configPath == "" {
145- fmt.Fprintln(os.Stderr, styles.Error.Render("Error: config file not found"))
146- fmt.Fprintln(os.Stderr, "Tried: ./config.toml and ~/.config/mysis/config.toml")
147- os.Exit(1)
148- }
149-
150- log.Info().
151- Str("version", Version).
152- Str("config", configPath).
153- Msg("Starting Mysis")
154-
155- // Load config
156- cfg, err := config.Load(configPath)
157- if err != nil {
158- fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to load config: "+err.Error()))
159- os.Exit(1)
160- }
161-
162- // Open database
163- db, err := store.Open()
164- if err != nil {
165- fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to open database: "+err.Error()))
166- os.Exit(1)
167- }
168- defer db.Close()
169-
170- // Handle --list-sessions flag
171- if listSessions {
172- if err := listSessionsCmd(db); err != nil {
173- fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
174- os.Exit(1)
175- }
176- return
177- }
178-
179- // Handle --delete-session flag
180- if deleteSession != "" {
181- if err := deleteSessionCmd(db, deleteSession); err != nil {
182- fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
183- os.Exit(1)
184- }
185- return
186- }
187-
188- // Load credentials
189- creds, err := config.LoadCredentials()
190- if err != nil {
191- log.Warn().Err(err).Msg("Failed to load credentials, using empty credentials")
192- creds = &config.Credentials{}
193- }
194-
195- // Initialize provider registry
196- registry := initializeProviders(cfg, creds)
197-
198- // Determine provider and model - check if resuming session first
199- var selectedProvider string
200- var selectedModel string
201-
202- // Check if we're resuming a session to use its provider
203- if sessionName != "" && providerName == "" {
204- sess, err := db.GetSessionByName(sessionName)
205- if err != nil {
206- fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to check session: "+err.Error()))
207- os.Exit(1)
208- }
209- if sess != nil {
210- // Resuming existing session - use its provider
211- selectedProvider = sess.Provider
212- selectedModel = sess.Model
213- log.Debug().
214- Str("session", sessionName).
215- Str("provider", selectedProvider).
216- Str("model", selectedModel).
217- Msg("Using provider from existing session")
218- }
219- }
220-
221- // If provider not determined from session, use flag or default
222- if selectedProvider == "" {
223- selectedProvider = providerName
224- if selectedProvider == "" {
225- // Use default provider from config (first one)
226- for name := range cfg.Providers {
227- selectedProvider = name
228- break
229- }
230- }
231-
232- if selectedProvider == "" {
233- fmt.Fprintln(os.Stderr, styles.Error.Render("Error: no provider configured"))
234- os.Exit(1)
235- }
236-
237- // Get model from config
238- providerCfg, ok := cfg.Providers[selectedProvider]
239- if !ok {
240- fmt.Fprintln(os.Stderr, styles.Error.Render(fmt.Sprintf("Error: provider '%s' not found in config", selectedProvider)))
241- os.Exit(1)
242- }
243- selectedModel = providerCfg.Model
244- }
245-
246- // Verify provider exists in config
247- providerCfg, ok := cfg.Providers[selectedProvider]
248- if !ok {
249- fmt.Fprintln(os.Stderr, styles.Error.Render(fmt.Sprintf("Error: provider '%s' not found in config", selectedProvider)))
250- os.Exit(1)
251- }
252-
253- // Create provider instance
254- prov, err := registry.Create(selectedProvider, selectedModel, providerCfg.Temperature)
255- if err != nil {
256- fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to create provider: "+err.Error()))
257- os.Exit(1)
258- }
259- defer prov.Close()
260-
261- log.Info().
262- Str("provider", selectedProvider).
263- Str("model", selectedModel).
264- Msg("Provider initialized")
265-
266- // Initialize MCP client
267- ctx := context.Background()
268- mcpClient := mcp.NewClient(cfg.MCP.Upstream)
269- proxy := mcp.NewProxy(mcpClient)
270-
271- if err := proxy.Initialize(ctx); err != nil {
272- log.Warn().Err(err).Msg("Failed to initialize MCP - continuing without game tools")
273- } else {
274- log.Info().Str("upstream", cfg.MCP.Upstream).Msg("MCP proxy initialized")
275- }
276- defer proxy.Close()
277-
278- // Get available tools
279- tools, err := proxy.ListTools(ctx)
280- if err != nil {
281- log.Warn().Err(err).Msg("Failed to list tools - continuing without tools")
282- tools = []mcp.Tool{}
283- } else {
284- log.Info().Int("count", len(tools)).Msg("Tools available")
285- }
286-
287- // Initialize or resume session
288- var sessionID string
289- var sessionInfo string
290- if sessionName != "" {
291- // Try to resume by name
292- sess, err := db.GetSessionByName(sessionName)
293- if err != nil {
294- fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to load session: "+err.Error()))
295- os.Exit(1)
296- }
297- if sess != nil {
298- sessionID = sess.ID
299- sessionInfo = fmt.Sprintf("Resumed session: %s", sessionName)
300- log.Info().Str("session_id", sessionID).Str("name", sessionName).Msg("Resumed session")
301- } else {
302- // Create new named session
303- sessionID = uuid.New().String()
304- if err := db.CreateSession(sessionID, selectedProvider, selectedModel, &sessionName); err != nil {
305- fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to create session: "+err.Error()))
306- os.Exit(1)
307- }
308- sessionInfo = fmt.Sprintf("New session: %s", sessionName)
309- log.Info().Str("session_id", sessionID).Str("name", sessionName).Msg("Created named session")
310- }
311- } else {
312- // Create anonymous session
313- sessionID = uuid.New().String()
314- if err := db.CreateSession(sessionID, selectedProvider, selectedModel, nil); err != nil {
315- fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to create session: "+err.Error()))
316- os.Exit(1)
317- }
318- sessionInfo = fmt.Sprintf("Session: %s", sessionID[:8])
319- log.Info().Str("session_id", sessionID).Msg("Created anonymous session")
320- }
321-
322- // Load message history
323- history, err := db.LoadMessages(sessionID)
324- if err != nil {
325- fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to load history: "+err.Error()))
326- os.Exit(1)
327- }
328- if len(history) > 0 {
329- log.Info().Int("count", len(history)).Msg("Loaded message history")
330- }
331-
332- // Print welcome message
333- fmt.Println(styles.Brand.Render("╔══════════════════════════════════════╗"))
334- fmt.Println(styles.Brand.Render("║") + " " + styles.BrandBold.Render("Mysis") + " - SpaceMolt Agent CLI " + styles.Brand.Render("║"))
335- fmt.Println(styles.Brand.Render("╚══════════════════════════════════════╝"))
336- fmt.Println()
337- fmt.Println(styles.Muted.Render(fmt.Sprintf("Provider: %s (%s)", selectedProvider, selectedModel)))
338- fmt.Println(styles.Muted.Render(fmt.Sprintf("Tools: %d available", len(tools))))
339- fmt.Println(styles.Muted.Render(sessionInfo))
340- fmt.Println()
341-
342- // Start conversation loop
343- app := &App{
344- provider: prov,
345- proxy: proxy,
346- tools: tools,
347- history: history,
348- db: db,
349- sessionID: sessionID,
350- }
351-
352- // Start autoplay if flag provided
353- if autoplay != "" {
354- if err := app.startAutoplayFromFlag(ctx, autoplay); err != nil {
355- fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to start autoplay: "+err.Error()))
356- os.Exit(1)
357- }
358- }
359-
360- if err := app.Run(ctx); err != nil {
15+ if err := cli.Run(Version); err != nil {
36116 fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
36217 os.Exit(1)
36318 }
36419 }
365-
366-// App holds the application state
367-type App struct {
368- provider provider.Provider
369- proxy *mcp.Proxy
370- tools []mcp.Tool
371- history []provider.Message
372- db *store.Store
373- sessionID string
374- autoplayEnabled bool
375- autoplayMessage string
376- autoplayCancel context.CancelFunc
377- mu sync.Mutex // Protects autoplay state and history
378-}
379-
380-// Run starts the conversation loop
381-func (app *App) Run(ctx context.Context) error {
382- scanner := bufio.NewScanner(os.Stdin)
383-
384- for {
385- // Display prompt
386- fmt.Print(styles.Brand.Render("> "))
387-
388- // Read user input
389- if !scanner.Scan() {
390- break
391- }
392-
393- input := strings.TrimSpace(scanner.Text())
394- if input == "" {
395- continue
396- }
397-
398- // Check for exit commands
399- if input == "exit" || input == "quit" {
400- fmt.Println(styles.Muted.Render("Goodbye!"))
401- break
402- }
403-
404- // Handle /autoplay commands
405- if strings.HasPrefix(input, "/autoplay") {
406- if err := app.handleAutoplayCommand(ctx, input); err != nil {
407- fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
408- }
409- continue
410- }
411-
412- // Add user message to history
413- userMsg := provider.Message{
414- Role: "user",
415- Content: input,
416- }
417- app.history = append(app.history, userMsg)
418-
419- // Save user message
420- if err := app.db.SaveMessage(app.sessionID, userMsg); err != nil {
421- log.Warn().Err(err).Msg("Failed to save user message")
422- }
423-
424- // Process turn (may involve multiple LLM calls if tools are used)
425- if err := app.processTurn(ctx); err != nil {
426- fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
427- continue
428- }
429-
430- fmt.Println() // Blank line after response
431- }
432-
433- return scanner.Err()
434-}
435-
436-// processTurn handles one conversation turn, which may involve tool calls
437-func (app *App) processTurn(ctx context.Context) error {
438- maxToolRounds := 20 // Prevent infinite loops
439-
440- for round := 0; round < maxToolRounds; round++ {
441- // Get a snapshot of history for this round
442- app.mu.Lock()
443- historyCopy := make([]provider.Message, len(app.history))
444- copy(historyCopy, app.history)
445- app.mu.Unlock()
446-
447- // Compress history before sending to LLM
448- // Keep last 10 turns full, compress older state queries
449- compressedHistory := store.CompressHistory(historyCopy, 10)
450-
451- // Log compression stats
452- if len(compressedHistory) < len(historyCopy) {
453- originalTokens := store.EstimateTokenCount(historyCopy)
454- compressedTokens := store.EstimateTokenCount(compressedHistory)
455- log.Debug().
456- Int("original_msgs", len(historyCopy)).
457- Int("compressed_msgs", len(compressedHistory)).
458- Int("original_tokens", originalTokens).
459- Int("compressed_tokens", compressedTokens).
460- Int("saved_tokens", originalTokens-compressedTokens).
461- Msg("History compressed")
462- }
463-
464- // Convert MCP tools to provider format
465- providerTools := make([]provider.Tool, len(app.tools))
466- for i, t := range app.tools {
467- providerTools[i] = provider.Tool{
468- Name: t.Name,
469- Description: t.Description,
470- Parameters: t.InputSchema,
471- }
472- }
473-
474- // Call LLM with compressed history
475- resp, err := app.provider.ChatWithTools(ctx, compressedHistory, providerTools)
476- if err != nil {
477- return fmt.Errorf("LLM call failed: %w", err)
478- }
479-
480- // Display reasoning if present
481- if resp.Reasoning != "" {
482- // Trim excessive whitespace and collapse multiple spaces/newlines
483- reasoning := strings.TrimSpace(resp.Reasoning)
484- reasoning = strings.Join(strings.Fields(reasoning), " ")
485-
486- // Truncate if too long
487- if len(reasoning) > 200 {
488- reasoning = reasoning[:197] + "..."
489- }
490-
491- fmt.Println(styles.Muted.Render("∴ " + reasoning))
492- }
493-
494- // If no tool calls, display text response and we're done
495- if len(resp.ToolCalls) == 0 {
496- if resp.Content != "" {
497- fmt.Println(resp.Content)
498- }
499-
500- // Add assistant response to history
501- app.addMessage(provider.Message{
502- Role: "assistant",
503- Content: resp.Content,
504- })
505-
506- return nil
507- }
508-
509- // Tool calls present - add assistant message with tool calls to history
510- app.addMessage(provider.Message{
511- Role: "assistant",
512- Content: resp.Content,
513- ToolCalls: resp.ToolCalls,
514- })
515-
516- // Execute each tool call
517- for _, toolCall := range resp.ToolCalls {
518- fmt.Print(styles.Secondary.Render(fmt.Sprintf("⚙ %s", toolCall.Name)))
519-
520- // Show arguments (truncated if long)
521- var args map[string]interface{}
522- if err := json.Unmarshal(toolCall.Arguments, &args); err == nil {
523- argsStr, _ := json.Marshal(args)
524- if len(argsStr) > 60 {
525- argsStr = argsStr[:57]
526- argsStr = append(argsStr, '.', '.', '.')
527- }
528- fmt.Print(styles.Muted.Render(string(argsStr)))
529- }
530-
531- // Execute tool via MCP proxy
532- result, err := app.proxy.CallTool(ctx, toolCall.Name, toolCall.Arguments)
533-
534- if err != nil {
535- fmt.Println(styles.Error.Render(" ✗"))
536- fmt.Println(styles.Error.Render(" Error: " + err.Error()))
537-
538- // Add error result to history
539- app.addMessage(provider.Message{
540- Role: "tool",
541- Content: fmt.Sprintf("Error: %v", err),
542- ToolCallID: toolCall.ID,
543- })
544- continue
545- }
546-
547- // Check if result is an error
548- if result.IsError {
549- fmt.Println(styles.Error.Render(" ✗"))
550- // Extract error text from content blocks
551- var errText string
552- for _, block := range result.Content {
553- if block.Type == "text" {
554- errText += block.Text
555- }
556- }
557- if errText != "" {
558- fmt.Println(styles.Error.Render(" " + errText))
559- }
560-
561- // Add error result to history
562- app.addMessage(provider.Message{
563- Role: "tool",
564- Content: errText,
565- ToolCallID: toolCall.ID,
566- })
567- continue
568- }
569-
570- // Success
571- fmt.Println(styles.Success.Render(" ✓"))
572-
573- // Extract result content
574- var resultText string
575- for _, block := range result.Content {
576- if block.Type == "text" {
577- resultText += block.Text
578- }
579- }
580-
581- // Show result preview (truncated)
582- if len(resultText) > 100 {
583- preview := resultText[:97] + "..."
584- fmt.Println(styles.Muted.Render(" " + preview))
585- } else if resultText != "" {
586- fmt.Println(styles.Muted.Render(" " + resultText))
587- }
588-
589- // Add tool result to history
590- app.addMessage(provider.Message{
591- Role: "tool",
592- Content: resultText,
593- ToolCallID: toolCall.ID,
594- })
595- }
596-
597- // Continue loop to let LLM process tool results
598- }
599-
600- return fmt.Errorf("too many tool call rounds (limit: %d)", maxToolRounds)
601-}
602-
603-// addMessage adds a message to history and saves it to the database.
604-func (app *App) addMessage(msg provider.Message) {
605- app.mu.Lock()
606- app.history = append(app.history, msg)
607- app.mu.Unlock()
608-
609- if err := app.db.SaveMessage(app.sessionID, msg); err != nil {
610- log.Warn().Err(err).Msg("Failed to save message to database")
611- }
612-}
613-
614-// listSessionsCmd lists recent sessions.
615-func listSessionsCmd(db *store.Store) error {
616- sessions, err := db.ListSessions(20)
617- if err != nil {
618- return fmt.Errorf("list sessions: %w", err)
619- }
620-
621- if len(sessions) == 0 {
622- fmt.Println("No sessions found")
623- return nil
624- }
625-
626- fmt.Println(styles.Brand.Render("Recent Sessions:"))
627- fmt.Println()
628-
629- for _, sess := range sessions {
630- fmt.Printf("%s ", styles.Muted.Render(sess.ID[:8]))
631-
632- if sess.Name != nil {
633- fmt.Print(styles.BrandBold.Render(*sess.Name))
634- } else {
635- fmt.Print(styles.Muted.Render("(anonymous)"))
636- }
637-
638- fmt.Printf(" - %s (%s)\n", sess.Provider, sess.Model)
639-
640- elapsed := time.Since(sess.LastActiveAt)
641- fmt.Printf(" %s\n", styles.Muted.Render(formatDuration(elapsed)+" ago"))
642- fmt.Println()
643- }
644-
645- return nil
646-}
647-
648-// deleteSessionCmd deletes a session by name.
649-func deleteSessionCmd(db *store.Store, name string) error {
650- // Get session to show info before deletion
651- sess, err := db.GetSessionByName(name)
652- if err != nil {
653- return fmt.Errorf("get session: %w", err)
654- }
655- if sess == nil {
656- return fmt.Errorf("session '%s' not found", name)
657- }
658-
659- // Get message count
660- messages, err := db.LoadMessages(sess.ID)
661- if err != nil {
662- return fmt.Errorf("load messages: %w", err)
663- }
664-
665- // Confirm deletion
666- fmt.Printf("Delete session '%s'?\n", styles.BrandBold.Render(name))
667- fmt.Printf(" ID: %s\n", sess.ID[:8])
668- fmt.Printf(" Provider: %s (%s)\n", sess.Provider, sess.Model)
669- fmt.Printf(" Messages: %d\n", len(messages))
670- fmt.Printf(" Created: %s\n", formatDuration(time.Since(sess.CreatedAt))+" ago")
671- fmt.Println()
672-
673- // Delete
674- if err := db.DeleteSessionByName(name); err != nil {
675- return fmt.Errorf("delete session: %w", err)
676- }
677-
678- fmt.Println(styles.Success.Render(fmt.Sprintf("Deleted session '%s'", name)))
679- return nil
680-}
681-
682-// formatDuration formats a duration in human-readable form.
683-func formatDuration(d time.Duration) string {
684- if d < time.Minute {
685- return "just now"
686- }
687- if d < time.Hour {
688- mins := int(d.Minutes())
689- if mins == 1 {
690- return "1 minute"
691- }
692- return fmt.Sprintf("%d minutes", mins)
693- }
694- if d < 24*time.Hour {
695- hours := int(d.Hours())
696- if hours == 1 {
697- return "1 hour"
698- }
699- return fmt.Sprintf("%d hours", hours)
700- }
701- days := int(d.Hours() / 24)
702- if days == 1 {
703- return "1 day"
704- }
705- return fmt.Sprintf("%d days", days)
706-}
707-
708-// initializeProviders creates and registers all configured providers
709-func initializeProviders(cfg *config.Config, creds *config.Credentials) *provider.Registry {
710- registry := provider.NewRegistry()
711-
712- for name, provCfg := range cfg.Providers {
713- // Detect provider type based on endpoint
714- if strings.Contains(provCfg.Endpoint, "localhost:11434") || strings.Contains(provCfg.Endpoint, "/ollama") {
715- // Ollama provider
716- factory := provider.NewOllamaFactory(name, provCfg.Endpoint)
717- registry.RegisterFactory(name, factory)
718- log.Debug().Str("name", name).Str("endpoint", provCfg.Endpoint).Msg("Registered Ollama provider")
719- } else if strings.Contains(provCfg.Endpoint, "opencode.ai") {
720- // OpenCode Zen provider
721- keyName := provCfg.APIKeyName
722- if keyName == "" {
723- keyName = name
724- }
725- apiKey := creds.GetAPIKey(keyName)
726- if apiKey == "" {
727- log.Warn().Str("name", name).Str("key_name", keyName).Msg("No API key found for provider")
728- continue
729- }
730- factory := provider.NewOpenCodeFactory(name, provCfg.Endpoint, apiKey)
731- registry.RegisterFactory(name, factory)
732- log.Debug().Str("name", name).Str("endpoint", provCfg.Endpoint).Msg("Registered OpenCode provider")
733- } else {
734- log.Warn().Str("name", name).Str("endpoint", provCfg.Endpoint).Msg("Unknown provider type")
735- }
736- }
737-
738- return registry
739-}
740-
741-// startAutoplayFromFlag starts autoplay from CLI flag.
742-func (app *App) startAutoplayFromFlag(ctx context.Context, message string) error {
743- app.mu.Lock()
744- if app.autoplayEnabled {
745- app.mu.Unlock()
746- return fmt.Errorf("autoplay already running")
747- }
748-
749- app.autoplayEnabled = true
750- app.autoplayMessage = message
751-
752- // Create cancelable context for autoplay goroutine
753- autoplayCtx, cancel := context.WithCancel(ctx)
754- app.autoplayCancel = cancel
755- app.mu.Unlock()
756-
757- fmt.Println(styles.Secondary.Render(fmt.Sprintf("Autoplay started: \"%s\"", message)))
758- fmt.Println(styles.Muted.Render(fmt.Sprintf("Interval: %ds (%d avg tool calls × %ds/tick)",
759- int(constants.AutoplayInterval.Seconds()),
760- constants.AvgToolCallsPerTurn,
761- int(constants.GameTickDuration.Seconds()))))
762- fmt.Println(styles.Muted.Render("Type '/autoplay stop' to stop"))
763- fmt.Println()
764-
765- // Start autoplay loop in background
766- go app.runAutoplay(autoplayCtx)
767-
768- return nil
769-}
770-
771-// handleAutoplayCommand handles /autoplay commands
772-func (app *App) handleAutoplayCommand(ctx context.Context, input string) error {
773- parts := strings.Fields(input)
774-
775- if len(parts) == 1 {
776- // Just "/autoplay" - show status
777- app.mu.Lock()
778- enabled := app.autoplayEnabled
779- message := app.autoplayMessage
780- app.mu.Unlock()
781-
782- if enabled {
783- fmt.Println(styles.Secondary.Render(fmt.Sprintf("Autoplay active: \"%s\"", message)))
784- } else {
785- fmt.Println(styles.Muted.Render("Autoplay not active"))
786- fmt.Println(styles.Muted.Render("Usage: /autoplay <message>"))
787- }
788- return nil
789- }
790-
791- // Check for "stop" subcommand
792- if parts[1] == "stop" {
793- app.mu.Lock()
794- if app.autoplayEnabled {
795- app.autoplayEnabled = false
796- if app.autoplayCancel != nil {
797- app.autoplayCancel()
798- app.autoplayCancel = nil
799- }
800- app.mu.Unlock()
801- fmt.Println(styles.Success.Render("Autoplay stopped"))
802- } else {
803- app.mu.Unlock()
804- fmt.Println(styles.Muted.Render("Autoplay not active"))
805- }
806- return nil
807- }
808-
809- // Join all parts after /autoplay as the message
810- message := strings.Join(parts[1:], " ")
811-
812- if message == "" {
813- return fmt.Errorf("missing message for autoplay")
814- }
815-
816- // Start autoplay
817- app.mu.Lock()
818- if app.autoplayEnabled {
819- app.mu.Unlock()
820- return fmt.Errorf("autoplay already running - use '/autoplay stop' first")
821- }
822-
823- app.autoplayEnabled = true
824- app.autoplayMessage = message
825-
826- // Create cancelable context for autoplay goroutine
827- autoplayCtx, cancel := context.WithCancel(ctx)
828- app.autoplayCancel = cancel
829- app.mu.Unlock()
830-
831- fmt.Println(styles.Secondary.Render(fmt.Sprintf("Autoplay started: \"%s\"", message)))
832- fmt.Println(styles.Muted.Render(fmt.Sprintf("Interval: %ds (%d avg tool calls × %ds/tick)",
833- int(constants.AutoplayInterval.Seconds()),
834- constants.AvgToolCallsPerTurn,
835- int(constants.GameTickDuration.Seconds()))))
836- fmt.Println(styles.Muted.Render("Type '/autoplay stop' to stop"))
837-
838- // Start autoplay loop in background
839- go app.runAutoplay(autoplayCtx)
840-
841- return nil
842-}
843-
844-// runAutoplay sends the autoplay message at intervals based on expected tool call duration.
845-func (app *App) runAutoplay(ctx context.Context) {
846- log.Debug().Msg("Autoplay goroutine started")
847-
848- defer func() {
849- app.mu.Lock()
850- app.autoplayEnabled = false
851- app.autoplayCancel = nil
852- app.mu.Unlock()
853- fmt.Println(styles.Muted.Render("Autoplay stopped"))
854- log.Debug().Msg("Autoplay goroutine exiting")
855- }()
856-
857- // Send first message immediately
858- log.Debug().Msg("Sending first autoplay message")
859- if err := app.sendAutoplayMessage(ctx); err != nil {
860- log.Error().Err(err).Msg("Autoplay failed to send first message")
861- return
862- }
863- log.Debug().Msg("First autoplay message sent successfully")
864-
865- // Then wait and send subsequent messages
866- ticker := time.NewTicker(constants.AutoplayInterval)
867- defer ticker.Stop()
868-
869- for {
870- select {
871- case <-ctx.Done():
872- return
873- case <-ticker.C:
874- app.mu.Lock()
875- enabled := app.autoplayEnabled
876- app.mu.Unlock()
877-
878- if !enabled {
879- return
880- }
881-
882- if err := app.sendAutoplayMessage(ctx); err != nil {
883- return
884- }
885- }
886- }
887-}
888-
889-// sendAutoplayMessage sends the autoplay message and processes the turn
890-func (app *App) sendAutoplayMessage(ctx context.Context) error {
891- log.Debug().Msg("sendAutoplayMessage called")
892-
893- app.mu.Lock()
894- enabled := app.autoplayEnabled
895- message := app.autoplayMessage
896- app.mu.Unlock()
897-
898- log.Debug().Bool("enabled", enabled).Str("message", message).Msg("Autoplay state")
899-
900- if !enabled {
901- return fmt.Errorf("autoplay disabled")
902- }
903-
904- fmt.Println(styles.Muted.Render("─── Autoplay Turn ───"))
905- fmt.Println(styles.Brand.Render("> ") + message)
906- log.Debug().Msg("About to process turn")
907-
908- // Send autoplay message
909- userMsg := provider.Message{
910- Role: "user",
911- Content: message,
912- }
913-
914- app.mu.Lock()
915- app.history = append(app.history, userMsg)
916- app.mu.Unlock()
917-
918- if err := app.db.SaveMessage(app.sessionID, userMsg); err != nil {
919- log.Warn().Err(err).Msg("Failed to save autoplay message")
920- }
921-
922- // Process turn
923- if err := app.processTurn(ctx); err != nil {
924- fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
925- // Don't stop autoplay on errors - just log and continue
926- log.Warn().Err(err).Msg("Autoplay turn failed, continuing...")
927- }
928-
929- fmt.Println() // Blank line after response
930- log.Debug().Msg("Autoplay message sent successfully")
931- return nil
932-}
documentation/architecture/CREDENTIAL_TOOLS.md+36−4
@@ -123,13 +123,45 @@ All tests pass:
123123 - Cascade deletion verified
124124 - Session isolation verified
125125
126+## Integration Status
127+
128+✅ **Tools are registered in the CLI** (`internal/cli/cli.go:145-157`)
129+
130+The credential tools are automatically registered when the CLI starts:
131+
132+1. Session is initialized (gets unique sessionID)
133+2. Tools are registered with session-scoped handlers
134+3. Tools are included in the tool list sent to the LLM
135+4. Agent can call `save_credentials` and `get_credentials` automatically
136+
137+**Logs:**
138+- Debug log shows: `Registered local credential tools` with session_id and tool count
139+- Info log shows total tool count (upstream + local credentials)
140+
141+**How it works:**
142+
143+```go
144+// internal/cli/cli.go (lines 145-157)
145+proxy.RegisterTool(
146+ mcp.NewSaveCredentialsTool(),
147+ mcp.MakeSaveCredentialsHandler(db, sessionID),
148+)
149+proxy.RegisterTool(
150+ mcp.NewGetCredentialsTool(),
151+ mcp.MakeGetCredentialsHandler(db, sessionID),
152+)
153+```
154+
155+The sessionID is injected into the handlers via closure, never exposed to the agent.
156+
126157 ## Files Modified
127158
128159 1. `internal/store/store.go` - Added schema + store functions
129-2. `internal/mcp/tools.go` - Implemented MCP tools
130-3. `internal/mcp/tools_test.go` - Unit tests
131-4. `internal/mcp/integration_test.go` - Integration tests
132-5. `internal/store/credentials_test.go` - Store tests
160+2. `internal/mcp/tools.go` - Implemented MCP tools (144 lines)
161+3. `internal/mcp/tools_test.go` - Unit tests (213 lines)
162+4. `internal/store/credentials_test.go` - Store tests (153 lines)
163+5. `internal/cli/cli.go` - Tool registration in CLI
164+6. `Makefile` - Added `backup-credentials` command
133165
134166 ## Backup and Restore
135167
documentation/architecture/DESIGN.md+24−18
@@ -1,34 +1,40 @@
1-# Mysis design
1+# Mysis Design
22
3-## CLI - Lightweight, simpler output, lot's of raw (human readable) data.
3+## CLI - Lightweight, simpler output, lot's of raw (human readable) data
44
55 A fully featured agentic interface for Spacemolt, themed like a mysis from [Zoea Nova](//TODO).
66
7-Spacemolt Game docs:
7+**Spacemolt Game docs:**
8+- https://www.spacemolt.com/skill.md
9+- https://www.spacemolt.com/api.md
810
9-https://www.spacemolt.com/skill.md
Cut short: this commit's diff is over 1000 lines.
internal/cli/autoplay.go+207−0
Cut short: this commit's diff is over 1000 lines.
internal/cli/cli.go+394−0
Cut short: this commit's diff is over 1000 lines.
internal/cli/flags.go+124−0
Cut short: this commit's diff is over 1000 lines.
internal/llm/loop.go+217−0
Cut short: this commit's diff is over 1000 lines.
internal/session/session.go+212−0
Cut short: this commit's diff is over 1000 lines.