6119
My
mysis / files
mysis / internal / cli / cli.go
6.9 KB
1package cli 2 3import ( 4 "bufio" 5 "context" 6 "fmt" 7 "os" 8 "strings" 9 "sync" 10 "time" 11 12 "github.com/rs/zerolog/log" 13 "github.com/xonecas/mysis/internal/features" 14 "github.com/xonecas/mysis/internal/llm" 15 "github.com/xonecas/mysis/internal/mcp" 16 "github.com/xonecas/mysis/internal/provider" 17 "github.com/xonecas/mysis/internal/session" 18 "github.com/xonecas/mysis/internal/styles" 19) 20 21// App holds the application state 22type App struct { 23 provider provider.Provider 24 proxy *mcp.Proxy 25 tools []mcp.Tool 26 history []provider.Message 27 sessionMgr *session.Manager 28 sessionID string 29 autoplayService *features.Service // Autoplay service (display-agnostic) 30 mu sync.Mutex // Protects history 31} 32 33// printWelcome displays the welcome banner. 34func printWelcome(provider, model string, toolCount int, sessionInfo string) { 35 fmt.Println(styles.Brand.Render("╔══════════════════════════════════════╗")) 36 fmt.Println(styles.Brand.Render("║") + " " + styles.BrandBold.Render("Mysis") + " - SpaceMolt Agent CLI " + styles.Brand.Render("║")) 37 fmt.Println(styles.Brand.Render("╚══════════════════════════════════════╝")) 38 fmt.Println() 39 fmt.Println(styles.Muted.Render(fmt.Sprintf("Provider: %s (%s)", provider, model))) 40 fmt.Println(styles.Muted.Render(fmt.Sprintf("Tools: %d available", toolCount))) 41 fmt.Println(styles.Muted.Render(sessionInfo)) 42 fmt.Println() 43} 44 45// Start initializes and starts the CLI application (without orchestration). 46// This is the main entry point for CLI mode after all initialization is done. 47func Start( 48 ctx context.Context, 49 sessionMgr *session.Manager, 50 sessionID string, 51 sessionInfo string, 52 prov provider.Provider, 53 proxy *mcp.Proxy, 54 tools []mcp.Tool, 55 history []provider.Message, 56 autoplayMsg string, 57 selectedProvider string, 58 selectedModel string, 59) error { 60 // Nil checks for required dependencies 61 if prov == nil { 62 return fmt.Errorf("provider cannot be nil") 63 } 64 if proxy == nil { 65 return fmt.Errorf("MCP proxy cannot be nil") 66 } 67 if sessionMgr == nil { 68 return fmt.Errorf("session manager cannot be nil") 69 } 70 71 // Input validation 72 if sessionID == "" { 73 return fmt.Errorf("sessionID cannot be empty") 74 } 75 if sessionInfo == "" { 76 return fmt.Errorf("sessionInfo cannot be empty") 77 } 78 79 // Print welcome message 80 printWelcome(selectedProvider, selectedModel, len(tools), sessionInfo) 81 82 // Start conversation loop 83 app := &App{ 84 provider: prov, 85 proxy: proxy, 86 tools: tools, 87 history: history, 88 sessionMgr: sessionMgr, 89 sessionID: sessionID, 90 } 91 92 // Initialize autoplay service 93 app.initAutoplayService() 94 95 // Start autoplay if requested 96 if autoplayMsg != "" { 97 if err := app.startAutoplayFromFlag(ctx, autoplayMsg); err != nil { 98 return fmt.Errorf("failed to start autoplay: %w", err) 99 } 100 } 101 102 return app.runLoop(ctx) 103} 104 105// runLoop runs the main conversation loop. 106func (app *App) runLoop(ctx context.Context) error { 107 scanner := bufio.NewScanner(os.Stdin) 108 109 for { 110 // Display prompt 111 fmt.Print(styles.Brand.Render("> ")) 112 113 // Read user input 114 if !scanner.Scan() { 115 break 116 } 117 118 input := strings.TrimSpace(scanner.Text()) 119 if input == "" { 120 continue 121 } 122 123 // Check for exit commands 124 if input == "exit" || input == "quit" { 125 fmt.Println(styles.Muted.Render("Goodbye!")) 126 break 127 } 128 129 // Handle /autoplay commands 130 if strings.HasPrefix(input, "/autoplay") { 131 if err := app.handleAutoplayCommand(ctx, input); err != nil { 132 fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error())) 133 } 134 continue 135 } 136 137 // Add user message to history 138 userMsg := provider.Message{ 139 Role: "user", 140 Content: input, 141 CreatedAt: time.Now(), 142 } 143 app.history = append(app.history, userMsg) 144 145 // Save user message 146 if err := app.sessionMgr.SaveMessage(app.sessionID, userMsg); err != nil { 147 log.Warn().Err(err).Msg("Failed to save user message") 148 } 149 150 // Process turn (may involve multiple LLM calls if tools are used) 151 if err := app.processTurn(ctx); err != nil { 152 fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error())) 153 continue 154 } 155 156 fmt.Println() // Blank line after response 157 } 158 159 return scanner.Err() 160} 161 162// processTurn handles one conversation turn, which may involve tool calls 163func (app *App) processTurn(ctx context.Context) error { 164 // Get a snapshot of history for this turn 165 app.mu.Lock() 166 historyCopy := make([]provider.Message, len(app.history)) 167 copy(historyCopy, app.history) 168 app.mu.Unlock() 169 170 return llm.ProcessTurn(ctx, llm.ProcessTurnOptions{ 171 Provider: app.provider, 172 Proxy: app.proxy, 173 Tools: app.tools, 174 History: historyCopy, 175 OnMessage: app.addMessage, 176 MaxToolRounds: 20, 177 HistoryKeepLast: 10, 178 }) 179} 180 181// addMessage adds a message to history and saves it to the database. 182func (app *App) addMessage(msg provider.Message) { 183 app.mu.Lock() 184 app.history = append(app.history, msg) 185 app.mu.Unlock() 186 187 if err := app.sessionMgr.SaveMessage(app.sessionID, msg); err != nil { 188 log.Warn().Err(err).Msg("Failed to save message to database") 189 } 190} 191 192// listSessionsCmd lists recent sessions. 193// ListSessionsCmd lists all recent sessions. 194func ListSessionsCmd(mgr *session.Manager) error { 195 sessions, err := mgr.List(20) 196 if err != nil { 197 return err 198 } 199 200 if len(sessions) == 0 { 201 fmt.Println("No sessions found") 202 return nil 203 } 204 205 fmt.Println(styles.Brand.Render("Recent Sessions:")) 206 fmt.Println() 207 208 for _, sess := range sessions { 209 fmt.Printf("%s ", styles.Muted.Render(sess.ID[:8])) 210 211 if sess.Name != nil { 212 fmt.Print(styles.BrandBold.Render(*sess.Name)) 213 } else { 214 fmt.Print(styles.Muted.Render("(anonymous)")) 215 } 216 217 fmt.Printf(" - %s (%s)\n", sess.Provider, sess.Model) 218 219 elapsed := time.Since(sess.LastActiveAt) 220 fmt.Printf(" %s\n", styles.Muted.Render(session.FormatDuration(elapsed)+" ago")) 221 fmt.Println() 222 } 223 224 return nil 225} 226 227// deleteSessionCmd deletes a session by name. 228// DeleteSessionCmd deletes a session by name. 229func DeleteSessionCmd(mgr *session.Manager, name string) error { 230 // Get session to show info before deletion 231 sess, err := mgr.GetByName(name) 232 if err != nil { 233 return err 234 } 235 if sess == nil { 236 return fmt.Errorf("session '%s' not found", name) 237 } 238 239 // Get message count 240 messages, err := mgr.LoadHistory(sess.ID) 241 if err != nil { 242 return err 243 } 244 245 // Confirm deletion 246 fmt.Printf("Delete session '%s'?\n", styles.BrandBold.Render(name)) 247 fmt.Printf(" ID: %s\n", sess.ID[:8]) 248 fmt.Printf(" Provider: %s (%s)\n", sess.Provider, sess.Model) 249 fmt.Printf(" Messages: %d\n", len(messages)) 250 fmt.Printf(" Created: %s\n", session.FormatDuration(time.Since(sess.CreatedAt))+" ago") 251 fmt.Println() 252 253 // Delete 254 if err := mgr.DeleteByName(name); err != nil { 255 return err 256 } 257 258 fmt.Println(styles.Success.Render(fmt.Sprintf("Deleted session '%s'", name))) 259 return nil 260} 261 262// initializeProviders creates and registers all configured providers