xonecas.io
6119
My

mysis / commit 7f9ec14

refactor: implement orchestrator pattern and fix critical TUI bugs

Architectural Changes:
- Move orchestration logic from cli.Run() to cmd/main.go
- Create internal/features package for display-agnostic code
- Separate CLI and TUI entry points (cli.Start, tui.Start)
- Extract autoplay service with callback pattern
- Remove cli/tui coupling (delete internal/cli/tui.go)

Bug Fixes:
- P0: Fix TUI data race by connecting model.historyMu to runner
- P1: Fix goroutine leak using context.Background() for autoplay
- P1: Add history trimming (100 msg limit) to prevent memory leak
- P1: Add circuit breaker to stop autoplay after 3 consecutive errors
- P2: Add nil checks for provider/proxy/sessionMgr at boundaries
- P2: Add input validation (empty message, nil context checks)
- P3: Remove dead code paths in TUI app.go

Code Quality:
- Reduce codebase by ~600 lines
- Move flags parsing to features (display-agnostic)
- Move shared helpers to features/app.go
- Simplify main.go from complex orchestrator
- Document all critical fixes with P0/P1/P2/P3 markers

Files Changed:
- New: internal/features/{autoplay.go,app.go,flags.go}
- New: internal/cli/help.go (CLI-specific help/version)
- Modified: cmd/main.go, cli/cli.go, cli/autoplay.go, tui/runner.go, tui/app.go
- Deleted: internal/cli/{flags.go,tui.go}

Both architecture and security reviews: APPROVED

xonecas2026-02-11 7f9ec14010e9001b8785e28747b51e1fcf1da33d parent 8df4e1a

13 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+10−66
@@ -1,72 +1,16 @@
1-# Mysis
1+# Project info for agents:
22
3-Single-agent CLI for playing SpaceMolt via MCP. Go 1.24.2, OpenAI-compatible LLM providers.
3+Design is at `documentation/architecture/DESIGN.md`. This is the USER's vision and is **only to be editted when explicitly asked**.
44
5-## Architecture Overview
5+If the code/comment/other document is contradictory to the design document stop and warn the USER.
66
7-**Simple CLI loop**: User types commands → LLM processes → Tools execute → Response displayed.
7+Use YAGNI **always**. When coding, when writting documentation.
88
9-The agent maintains conversation history and calls SpaceMolt game tools (login, navigate, mine, trade, etc.) via MCP proxy.
9+Keep documentation concise and factual. No documentation file should be more than 500 lines, most should be at around ~200.
1010
11-## Core Components
11+## Quick reference:
1212
13-**Config** (`internal/config/`): TOML file loading, provider configuration, credential management. Data directory: `~/.config/mysis`.
14-
15-**Provider** (`internal/provider/`): OpenAI-compatible LLM client interface. Supports Ollama (local) and OpenCode Zen (cloud). Factory pattern for creating providers with model/temperature params.
16-
17-**MCP** (`internal/mcp/`): Proxy between agent and SpaceMolt game server. Combines local tool handlers with upstream MCP tools. Automatic retry with rate limit respect (2s, 5s, 10s delays). Parses `Retry-After` headers. Includes credential management tools (`save_credentials`, `get_credentials`) with session-scoped storage.
18-
19-**Styles** (`internal/styles/`): Brand colors for terminal output (electric purple, bright teal, deep space backgrounds).
20-
21-**LLM Loop** (`internal/llm/`): Multi-round tool calling with reasoning display, streaming support, and history compression.
22-
23-**Session** (`internal/session/`): Session creation/resumption, provider selection, history loading.
24-
25-**Store** (`internal/store/`): SQLite-based message history with WAL mode, foreign key constraints, and tool call serialization.
26-
27-**CLI** (`internal/cli/`): Interactive terminal interface with stdin input, autoplay support, and branded output formatting.
28-
29-**TUI** (`internal/tui/`): Bubbletea-based terminal UI with scrollable conversation log, animated status bar, and concurrent message processing.
30-
31-## Implementation Status
32-
33-**Fully implemented**:
34-
35-- Config loading from TOML with default provider support
36-- Multiple LLM provider support (Ollama, OpenCode Zen)
37-- MCP client with upstream game server connection
38-- Tool call retry with rate limiting
39-- Credential management (session-scoped, SQLite storage)
40-- CLI conversation loop with stdin input
41-- Message history storage (SQLite with compression)
42-- Agent state management
43-- Terminal UI (TUI mode with bubbletea)
44-- Autoplay command (`/autoplay [message]`)
45-- Session management (create, resume, list, delete)
46-- Branded output with reasoning and tool call display
47-
48-## Design Decisions
49-
50-**MCP proxy simplicity**: Pass-through to upstream tools with retry logic. Local tool registration available but unused initially. ** DO NOT CHANGE UPSTREAM RESPONSES **
51-
52-**Config-driven**: Provider selection via config file. No runtime provider switching.
53-
54-**Data directory**: `~/.config/mysis` for config, credentials, database (sessions, messages, game credentials).
55-
56-## Where to Find Things
57-
58-- Config: `config.toml` and `~/.config/mysis/`
59-- Database: `~/.config/mysis/mysis.db` (SQLite with sessions, messages, credentials)
60-- Credentials (LLM providers): `~/.config/mysis/credentials.json` (auto-created with 0600)
61-- Logs: stderr (zerolog)
62-- Main entry: `cmd/mysis/main.go`
63-- Provider registry: `internal/provider/registry.go`
64-- MCP proxy: `internal/mcp/proxy.go`
65-- Game client: `internal/mcp/client.go`
66-- LLM loop: `internal/llm/loop.go`
67-- CLI: `internal/cli/cli.go`
68-- TUI: `internal/tui/app.go`
69-
70-## Agent Rules
71-
72-**Do not edit `documentation/architecture/DESIGN.md` unless explicitly instructed by the user.** This file contains the user's design vision and should only be modified when directly requested.
13+- The config, credentials, and database are in the app's data folder: `~/.config/mysis`.
14+- The app config is in `./config.toml`.
15+- `cmd/main.go` is the orchestrator and entrypoint. It can then run in interactive mode with TUI or non-interactive mode with cli.
16+- Project has a strict rule of separation of concerns. Shared functionality and data access is shared no matter what display mode the app is using. Ex: `llm/loop.go` is one core functionaly shared by both displays.
cmd/mysis/main.go+38−17
@@ -9,8 +9,8 @@ import (
99 "github.com/rs/zerolog/log"
1010 "github.com/xonecas/mysis/internal/cli"
1111 "github.com/xonecas/mysis/internal/config"
12+ "github.com/xonecas/mysis/internal/features"
1213 "github.com/xonecas/mysis/internal/mcp"
13- "github.com/xonecas/mysis/internal/provider"
1414 "github.com/xonecas/mysis/internal/session"
1515 "github.com/xonecas/mysis/internal/store"
1616 "github.com/xonecas/mysis/internal/styles"
@@ -31,7 +31,19 @@ func run() error {
3131 ctx := context.Background()
3232
3333 // Parse flags
34- flags := cli.ParseFlags(Version)
34+ flags := features.ParseFlags()
35+
36+ // Handle version flag
37+ if flags.ShowVersion {
38+ cli.PrintVersion(Version)
39+ os.Exit(0)
40+ }
41+
42+ // Handle help flag
43+ if flags.ShowHelp {
44+ cli.PrintHelp(Version)
45+ os.Exit(0)
46+ }
3547
3648 // Initialize logging
3749 if err := setupLogging(flags); err != nil {
@@ -66,10 +78,12 @@ func run() error {
6678 // Create session manager
6779 sessionMgr := session.NewManager(db)
6880
69- // Handle special commands
81+ // Handle --list-sessions flag
7082 if flags.ListSessions {
7183 return cli.ListSessionsCmd(sessionMgr)
7284 }
85+
86+ // Handle --delete-session flag
7387 if flags.DeleteSession != "" {
7488 return cli.DeleteSessionCmd(sessionMgr, flags.DeleteSession)
7589 }
@@ -82,9 +96,9 @@ func run() error {
8296 }
8397
8498 // Initialize provider registry
85- registry := cli.InitializeProviders(cfg, creds)
99+ registry := features.InitializeProviders(cfg, creds)
86100
87- // Select provider and model
101+ // Determine provider and model
88102 providerResult, err := sessionMgr.SelectProvider(cfg, flags.SessionName, flags.ProviderName)
89103 if err != nil {
90104 return err
@@ -104,11 +118,16 @@ func run() error {
104118 return fmt.Errorf("failed to create provider: %w", err)
105119 }
106120 defer prov.Close()
107- log.Info().Str("provider", selectedProvider).Str("model", selectedModel).Msg("Provider initialized")
108121
109- // Initialize MCP client and proxy
122+ log.Info().
123+ Str("provider", selectedProvider).
124+ Str("model", selectedModel).
125+ Msg("Provider initialized")
126+
127+ // Initialize MCP client
110128 mcpClient := mcp.NewClient(cfg.MCP.Upstream)
111129 proxy := mcp.NewProxy(mcpClient)
130+
112131 if err := proxy.Initialize(ctx); err != nil {
113132 log.Warn().Err(err).Msg("Failed to initialize MCP - continuing without game tools")
114133 } else {
@@ -138,7 +157,7 @@ func run() error {
138157 Int("local_tools", proxy.LocalToolCount()).
139158 Msg("Registered local credential tools")
140159
141- // Get available tools
160+ // Get available tools (includes upstream + local credential tools)
142161 tools, err := proxy.ListTools(ctx)
143162 if err != nil {
144163 log.Warn().Err(err).Msg("Failed to list tools - continuing without tools")
@@ -153,31 +172,33 @@ func run() error {
153172 return err
154173 }
155174
156- // Load system prompt if provided
175+ // Load system prompt from markdown file if provided
157176 if flags.SystemFile != "" {
158- systemPrompt, err := cli.LoadSystemPromptFromFile(flags.SystemFile)
177+ systemPrompt, err := features.LoadSystemPromptFromFile(flags.SystemFile)
159178 if err != nil {
160179 return err
161180 }
162- if !cli.HistoryHasSystemPrompt(history, systemPrompt) {
163- history = cli.PrependSystemPrompt(history, systemPrompt)
181+ if !features.HistoryHasSystemPrompt(history, systemPrompt) {
182+ history = features.PrependSystemPrompt(history, systemPrompt)
164183 }
165184 }
166185
167- // Delegate to CLI or TUI
186+ // Delegate to TUI or CLI based on flag
168187 if flags.TUI {
169- return tui.Run(ctx, sessionMgr, sessionID, prov, proxy, tools, history, flags.Autoplay)
188+ // Use TUI mode
189+ return tui.Start(ctx, sessionMgr, sessionID, prov, proxy, tools, history)
170190 }
171191
172- return cli.RunCLI(ctx, sessionMgr, sessionID, sessionInfo, prov, proxy, tools, history, flags.Autoplay, selectedProvider, selectedModel)
192+ // Use CLI mode
193+ return cli.Start(ctx, sessionMgr, sessionID, sessionInfo, prov, proxy, tools, history, flags.Autoplay, selectedProvider, selectedModel)
173194 }
174195
175-func setupLogging(flags *cli.Flags) error {
196+func setupLogging(flags *features.Flags) error {
176197 zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
177198
178199 if flags.TUI {
179200 // TUI mode: log to file to avoid collision with UI
180- return cli.SetupFileLogging(flags.Debug)
201+ return features.SetupFileLogging(flags.Debug)
181202 }
182203
183204 // CLI mode: log to stderr
documentation/TODO.md+37−0
@@ -1,4 +1,41 @@
11 # TODO:
22
3+- Session lost not refreshing with login:
4+
5+```
6+2:42AM INF OpenCode request started message_count=65 model=gpt-5-nano provider=zen-nano tool_count=121
7+2:43AM INF OpenCode request successful attempt=1 choice_count=1 message_count=65 model=gpt-5-nano provider=zen-nano status=200
8+⚙ get_cargo{"session_id":"9f3a930758852cb5ec92b254a36930fb"} ✓
9+ {
10+ "available": 36,
11+ "capacity": 50,
12+ "cargo": [
13+ {
14+ "item_id": "ore_nickel",
15+ "n...
16+2:43AM INF OpenCode request started message_count=67 model=gpt-5-nano provider=zen-nano tool_count=121
17+2:43AM INF OpenCode request successful attempt=1 choice_count=1 message_count=67 model=gpt-5-nano provider=zen-nano status=200
18+Mining continues.
19+- Cargo: 14/50 (Nickel 4, Iron 6, Copper 3, Trade Crystal 1)
20+- Space left: 36
21+- Location: Commerce Fields (haven_belt)
22+
23+Next: keep mining Iron Ore (priority) and return to Grand Exchange when near full (or set auto-return threshold).
24+Would you like me to scan nearby players or deploy drones before finishing?
25+
26+─── Autoplay Turn ───
27+> Mine away!
28+2:43AM INF OpenCode request started message_count=69 model=gpt-5-nano provider=zen-nano tool_count=121
29+2:44AM INF OpenCode request successful attempt=1 choice_count=1 message_count=69 model=gpt-5-nano provider=zen-nano status=200
30+⚙ mine{"session_id":"9f3a930758852cb5ec92b254a36930fb"} ✗
31+ Error: Session not initialized
32+2:44AM INF OpenCode request started message_count=71 model=gpt-5-nano provider=zen-nano tool_count=121
33+2:44AM INF OpenCode request successful attempt=1 choice_count=1 message_count=71 model=gpt-5-nano provider=zen-nano status=200
34+⚙ login{"password":"24ff43c10286496d746dc5934f750e767a3c9518e46c... ✗
35+ Error: Session not initialized
36+```
37+
338 - Blinking cursor in TUI
439 - Mouse selection in TUI
40+- User messages no visible in TUI
41+- Remove "All systems operational" with the dotted infinite loader icon when a message is sending.
documentation/architecture/DESIGN.md+8−16
@@ -1,7 +1,5 @@
11 # Mysis Design
22
3-## CLI - Lightweight, simpler output, lot's of raw (human readable) data
4-
53 A fully featured agentic interface for Spacemolt, themed like a mysis from [Zoea Nova](//TODO).
64
75 **Spacemolt Game docs:**
@@ -11,7 +9,7 @@ A fully featured agentic interface for Spacemolt, themed like a mysis from [Zoea
119
1210 ### Features
1311
14-**Agentic conversation:** Normal agent conversation. User types in stdin, agentic response is printed above. We should show thinking, tool calls (simplified, called, success, failure), and obviously replies. No advanced context management. Use brand coloring output for highlight.
12+**Agentic conversation:** Normal agent conversation. User types in, agentic response replies. We should show thinking, tool calls (simplified, called, success, failure), and obviously replies. Use brand coloring output for highlight. Context is truncated and compressed.
1513
1614 **In-conversation commands:**
1715
@@ -25,13 +23,19 @@ A fully featured agentic interface for Spacemolt, themed like a mysis from [Zoea
2523
2624 - `-p` `--p` for a provider from the config. If param is not there use default from config. If there is no config exit with error
2725 - Session management `-s`
26+- Launches with cli by default `-t` for TUI display
27+- `-f` specifies markdown file to use as system prompt
2828
2929 **MCP tools:**
3030
3131 - `save_credentials(username, password)` / `get_credentials` - Simple tools to save username/password to a local sqlite database in the config file folder.
3232 - The session id for the mysis saving the pair, we inject, **DO NOT MAKE IT AN ARGUMENT FOR THE AGENTS**
3333
34-# TUI - Not a replacement, an augmentation.
34+## CLI - Lightweight
35+
36+Simpler output, lot's of raw (human readable) data. Same functionality, runs with any terminal. Type in stdin your messages, output comes out above.
37+
38+# TUI - Not a replacement, an option.
3539
3640 Same UI as CLI: simple, with a permanent input line and the conversation log.
3741
@@ -107,19 +111,7 @@ Animation Sequences:
107111 - LLM: ◉ ◎ ○ ◌ → ends at ◌ (empty circle)
108112 - MCP: ◐ ◓ ◑ ◒ → ends at ○ (circle/dot)
109113
110-#### Bonus Features (Not in Spec originally)
111-
112-Implemented beyond specification:
113-
114-- History compression (saves tokens)
115-- TUI mode (1,670 lines - complete terminal UI)
116-- List sessions (--list-sessions)
117-- Delete sessions (--delete-session)
118-- System prompt from file (-f/--file)
119-- Debug logging (-d/--debug)
120-
121114 # TODO:
122115
123-- blinking cursor?
124116 - Session setup screen
125117 - Game state sidebar, pretty, game like, retro.
internal/cli/autoplay.go+58−153
@@ -9,38 +9,65 @@ import (
99
1010 "github.com/rs/zerolog/log"
1111 "github.com/xonecas/mysis/internal/constants"
12+ "github.com/xonecas/mysis/internal/features"
1213 "github.com/xonecas/mysis/internal/provider"
1314 "github.com/xonecas/mysis/internal/styles"
1415 )
1516
16-// startAutoplayFromFlag starts autoplay from CLI flag.
17-func (app *App) startAutoplayFromFlag(ctx context.Context, message string) error {
18- app.mu.Lock()
19- if app.autoplayEnabled {
20- app.mu.Unlock()
21- return fmt.Errorf("autoplay already running")
22- }
17+// initAutoplayService initializes the autoplay service with CLI-specific callbacks.
18+// This should be called once when creating the App.
19+func (app *App) initAutoplayService() {
20+ app.autoplayService = features.NewAutoplayService(features.AutoplayCallbacks{
21+ OnStarted: func(message string, interval time.Duration) {
22+ fmt.Println(styles.Secondary.Render(fmt.Sprintf("Autoplay started: \"%s\"", message)))
23+ fmt.Println(styles.Muted.Render(fmt.Sprintf("Interval: %ds (%d avg tool calls × %ds/tick)",
24+ int(interval.Seconds()),
25+ constants.AvgToolCallsPerTurn,
26+ int(constants.GameTickDuration.Seconds()))))
27+ fmt.Println(styles.Muted.Render("Type '/autoplay stop' to stop"))
28+ fmt.Println()
29+ },
30+ OnStopped: func() {
31+ fmt.Println(styles.Muted.Render("Autoplay stopped"))
32+ },
33+ OnTurn: func(ctx context.Context, message string) error {
34+ fmt.Println(styles.Muted.Render("─── Autoplay Turn ───"))
35+ fmt.Println(styles.Brand.Render("> ") + message)
36+ log.Debug().Msg("About to process turn")
37+
38+ // Send autoplay message
39+ userMsg := provider.Message{
40+ Role: "user",
41+ Content: message,
42+ }
2343
24- app.autoplayEnabled = true
25- app.autoplayMessage = message
44+ app.mu.Lock()
45+ app.history = append(app.history, userMsg)
46+ app.mu.Unlock()
2647
27- // Create cancelable context for autoplay goroutine
28- autoplayCtx, cancel := context.WithCancel(ctx)
29- app.autoplayCancel = cancel
30- app.mu.Unlock()
48+ if err := app.sessionMgr.SaveMessage(app.sessionID, userMsg); err != nil {
49+ log.Warn().Err(err).Msg("Failed to save autoplay message")
50+ }
3151
32- fmt.Println(styles.Secondary.Render(fmt.Sprintf("Autoplay started: \"%s\"", message)))
33- fmt.Println(styles.Muted.Render(fmt.Sprintf("Interval: %ds (%d avg tool calls × %ds/tick)",
34- int(constants.AutoplayInterval.Seconds()),
35- constants.AvgToolCallsPerTurn,
36- int(constants.GameTickDuration.Seconds()))))
37- fmt.Println(styles.Muted.Render("Type '/autoplay stop' to stop"))
38- fmt.Println()
52+ // Process turn
53+ if err := app.processTurn(ctx); err != nil {
54+ fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
55+ // Don't stop autoplay on errors - just log and continue
56+ log.Warn().Err(err).Msg("Autoplay turn failed, continuing...")
57+ }
3958
40- // Start autoplay loop in background
41- go app.runAutoplay(autoplayCtx)
59+ fmt.Println() // Blank line after response
60+ return nil
61+ },
62+ OnError: func(err error) {
63+ log.Error().Err(err).Msg("Autoplay error")
64+ },
65+ })
66+}
4267
43- return nil
68+// startAutoplayFromFlag starts autoplay from CLI flag.
69+func (app *App) startAutoplayFromFlag(ctx context.Context, message string) error {
70+ return app.autoplayService.Start(ctx, message)
4471 }
4572
4673 // handleAutoplayCommand handles /autoplay commands
@@ -49,13 +76,9 @@ func (app *App) handleAutoplayCommand(ctx context.Context, input string) error {
4976
5077 if len(parts) == 1 {
5178 // Just "/autoplay" - show status
52- app.mu.Lock()
53- enabled := app.autoplayEnabled
54- message := app.autoplayMessage
55- app.mu.Unlock()
56-
57- if enabled {
58- fmt.Println(styles.Secondary.Render(fmt.Sprintf("Autoplay active: \"%s\"", message)))
79+ status := app.autoplayService.Status()
80+ if status.Enabled {
81+ fmt.Println(styles.Secondary.Render(fmt.Sprintf("Autoplay active: \"%s\"", status.Message)))
5982 } else {
6083 fmt.Println(styles.Muted.Render("Autoplay not active"))
6184 fmt.Println(styles.Muted.Render("Usage: /autoplay <message>"))
@@ -65,18 +88,10 @@ func (app *App) handleAutoplayCommand(ctx context.Context, input string) error {
6588
6689 // Check for "stop" subcommand
6790 if parts[1] == "stop" {
68- app.mu.Lock()
69- if app.autoplayEnabled {
70- app.autoplayEnabled = false
71- if app.autoplayCancel != nil {
72- app.autoplayCancel()
73- app.autoplayCancel = nil
74- }
75- app.mu.Unlock()
76- fmt.Println(styles.Success.Render("Autoplay stopped"))
91+ if err := app.autoplayService.Stop(); err != nil {
92+ fmt.Println(styles.Muted.Render(err.Error()))
7793 } else {
78- app.mu.Unlock()
79- fmt.Println(styles.Muted.Render("Autoplay not active"))
94+ fmt.Println(styles.Success.Render("Autoplay stopped"))
8095 }
8196 return nil
8297 }
@@ -89,119 +104,9 @@ func (app *App) handleAutoplayCommand(ctx context.Context, input string) error {
89104 }
90105
91106 // Start autoplay
92- app.mu.Lock()
93- if app.autoplayEnabled {
94- app.mu.Unlock()
95- return fmt.Errorf("autoplay already running - use '/autoplay stop' first")
96- }
97-
98- app.autoplayEnabled = true
99- app.autoplayMessage = message
100-
101- // Create cancelable context for autoplay goroutine
102- autoplayCtx, cancel := context.WithCancel(ctx)
103- app.autoplayCancel = cancel
104- app.mu.Unlock()
105-
106- fmt.Println(styles.Secondary.Render(fmt.Sprintf("Autoplay started: \"%s\"", message)))
107- fmt.Println(styles.Muted.Render(fmt.Sprintf("Interval: %ds (%d avg tool calls × %ds/tick)",
108- int(constants.AutoplayInterval.Seconds()),
109- constants.AvgToolCallsPerTurn,
110- int(constants.GameTickDuration.Seconds()))))
111- fmt.Println(styles.Muted.Render("Type '/autoplay stop' to stop"))
112-
113- // Start autoplay loop in background
114- go app.runAutoplay(autoplayCtx)
115-
116- return nil
117-}
118-
119-// runAutoplay sends the autoplay message at intervals based on expected tool call duration.
120-func (app *App) runAutoplay(ctx context.Context) {
121- log.Debug().Msg("Autoplay goroutine started")
122-
123- defer func() {
124- app.mu.Lock()
125- app.autoplayEnabled = false
126- app.autoplayCancel = nil
127- app.mu.Unlock()
128- fmt.Println(styles.Muted.Render("Autoplay stopped"))
129- log.Debug().Msg("Autoplay goroutine exiting")
130- }()
131-
132- // Send first message immediately
133- log.Debug().Msg("Sending first autoplay message")
134- if err := app.sendAutoplayMessage(ctx); err != nil {
135- log.Error().Err(err).Msg("Autoplay failed to send first message")
136- return
137- }
138- log.Debug().Msg("First autoplay message sent successfully")
139-
140- // Then wait and send subsequent messages
141- ticker := time.NewTicker(constants.AutoplayInterval)
142- defer ticker.Stop()
143-
144- for {
145- select {
146- case <-ctx.Done():
147- return
148- case <-ticker.C:
149- app.mu.Lock()
150- enabled := app.autoplayEnabled
151- app.mu.Unlock()
152-
153- if !enabled {
154- return
155- }
156-
157- if err := app.sendAutoplayMessage(ctx); err != nil {
158- return
159- }
160- }
161- }
162-}
163-
164-// sendAutoplayMessage sends the autoplay message and processes the turn
165-func (app *App) sendAutoplayMessage(ctx context.Context) error {
166- log.Debug().Msg("sendAutoplayMessage called")
167-
168- app.mu.Lock()
169- enabled := app.autoplayEnabled
170- message := app.autoplayMessage
171- app.mu.Unlock()
172-
173- log.Debug().Bool("enabled", enabled).Str("message", message).Msg("Autoplay state")
174-
175- if !enabled {
176- return fmt.Errorf("autoplay disabled")
177- }
178-
179- fmt.Println(styles.Muted.Render("─── Autoplay Turn ───"))
180- fmt.Println(styles.Brand.Render("> ") + message)
181- log.Debug().Msg("About to process turn")
182-
183- // Send autoplay message
184- userMsg := provider.Message{
185- Role: "user",
186- Content: message,
187- }
188-
189- app.mu.Lock()
190- app.history = append(app.history, userMsg)
191- app.mu.Unlock()
192-
193- if err := app.sessionMgr.SaveMessage(app.sessionID, userMsg); err != nil {
194- log.Warn().Err(err).Msg("Failed to save autoplay message")
195- }
196-
197- // Process turn
198- if err := app.processTurn(ctx); err != nil {
199- fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
200- // Don't stop autoplay on errors - just log and continue
201- log.Warn().Err(err).Msg("Autoplay turn failed, continuing...")
107+ if err := app.autoplayService.Start(ctx, message); err != nil {
108+ return fmt.Errorf("%s - use '/autoplay stop' first", err.Error())
202109 }
203110
204- fmt.Println() // Blank line after response
205- log.Debug().Msg("Autoplay message sent successfully")
206111 return nil
207112 }
internal/cli/cli.go+60−311
@@ -4,21 +4,17 @@ import (
44 "bufio"
55 "context"
66 "fmt"
7- "io"
87 "os"
9- "path/filepath"
108 "strings"
119 "sync"
1210 "time"
1311
14- "github.com/rs/zerolog"
1512 "github.com/rs/zerolog/log"
16- "github.com/xonecas/mysis/internal/config"
13+ "github.com/xonecas/mysis/internal/features"
1714 "github.com/xonecas/mysis/internal/llm"
1815 "github.com/xonecas/mysis/internal/mcp"
1916 "github.com/xonecas/mysis/internal/provider"
2017 "github.com/xonecas/mysis/internal/session"
21- "github.com/xonecas/mysis/internal/store"
2218 "github.com/xonecas/mysis/internal/styles"
2319 )
2420
@@ -30,179 +26,60 @@ type App struct {
3026 history []provider.Message
3127 sessionMgr *session.Manager
3228 sessionID string
33- autoplayEnabled bool
34- autoplayMessage string
35- autoplayCancel context.CancelFunc
36- mu sync.Mutex // Protects autoplay state and history
29+ autoplayService *features.Service // Autoplay service (display-agnostic)
30+ mu sync.Mutex // Protects history
3731 }
3832
39-// Run initializes and starts the CLI application.
40-func Run(version string) error {
41- // Parse flags
42- flags := ParseFlags(version)
43-
44- // Initialize logging
45- zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
46-
47- // In TUI mode, log to file instead of stderr to avoid collision
48- if flags.TUI {
49- if err := setupFileLogging(flags.Debug); err != nil {
50- return fmt.Errorf("failed to setup file logging: %w", err)
51- }
52- } else {
53- // CLI mode: log to stderr
54- log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
55- if flags.Debug {
56- zerolog.SetGlobalLevel(zerolog.DebugLevel)
57- } else {
58- zerolog.SetGlobalLevel(zerolog.InfoLevel)
59- }
60- }
61-
62- // Check config path
63- if flags.ConfigPath == "" {
64- fmt.Fprintln(os.Stderr, styles.Error.Render("Error: config file not found"))
65- fmt.Fprintln(os.Stderr, "Tried: ./config.toml and ~/.config/mysis/config.toml")
66- return fmt.Errorf("config file not found")
67- }
68-
69- log.Info().
70- Str("version", version).
71- Str("config", flags.ConfigPath).
72- Msg("Starting Mysis")
73-
74- // Load config
75- cfg, err := config.Load(flags.ConfigPath)
76- if err != nil {
77- return fmt.Errorf("failed to load config: %w", err)
78- }
79-
80- // Open database
81- db, err := store.Open()
82- if err != nil {
83- return fmt.Errorf("failed to open database: %w", err)
84- }
85- defer db.Close()
86-
87- // Create session manager
88- sessionMgr := session.NewManager(db)
89-
90- // Handle --list-sessions flag
91- if flags.ListSessions {
92- return listSessionsCmd(sessionMgr)
93- }
94-
95- // Handle --delete-session flag
96- if flags.DeleteSession != "" {
97- return deleteSessionCmd(sessionMgr, flags.DeleteSession)
98- }
99-
100- // Load credentials
101- creds, err := config.LoadCredentials()
102- if err != nil {
103- log.Warn().Err(err).Msg("Failed to load credentials, using empty credentials")
104- creds = &config.Credentials{}
105- }
106-
107- // Initialize provider registry
108- registry := initializeProviders(cfg, creds)
109-
110- // Determine provider and model
111- providerResult, err := sessionMgr.SelectProvider(cfg, flags.SessionName, flags.ProviderName)
112- if err != nil {
113- return err
114- }
115- selectedProvider := providerResult.Provider
116- selectedModel := providerResult.Model
117-
118- // Verify provider exists in config
119- providerCfg, ok := cfg.Providers[selectedProvider]
120- if !ok {
121- return fmt.Errorf("provider '%s' not found in config", selectedProvider)
122- }
123-
124- // Create provider instance
125- prov, err := registry.Create(selectedProvider, selectedModel, providerCfg.Temperature)
126- if err != nil {
127- return fmt.Errorf("failed to create provider: %w", err)
128- }
129- defer prov.Close()
130-
131- log.Info().
132- Str("provider", selectedProvider).
133- Str("model", selectedModel).
134- Msg("Provider initialized")
135-
136- // Initialize MCP client
137- ctx := context.Background()
138- mcpClient := mcp.NewClient(cfg.MCP.Upstream)
139- proxy := mcp.NewProxy(mcpClient)
140-
141- if err := proxy.Initialize(ctx); err != nil {
142- log.Warn().Err(err).Msg("Failed to initialize MCP - continuing without game tools")
143- } else {
144- log.Info().Str("upstream", cfg.MCP.Upstream).Msg("MCP proxy initialized")
145- }
146- defer proxy.Close()
147-
148- // Initialize or resume session
149- sessionResult, err := sessionMgr.Initialize(flags.SessionName, selectedProvider, selectedModel)
150- if err != nil {
151- return err
152- }
153- sessionID := sessionResult.SessionID
154- sessionInfo := sessionResult.SessionInfo
155-
156- // Register credential tools (session-scoped)
157- proxy.RegisterTool(
158- mcp.NewSaveCredentialsTool(),
159- mcp.MakeSaveCredentialsHandler(db, sessionID),
160- )
161- proxy.RegisterTool(
162- mcp.NewGetCredentialsTool(),
163- mcp.MakeGetCredentialsHandler(db, sessionID),
164- )
165- log.Debug().
166- Str("session_id", sessionID).
167- Int("local_tools", proxy.LocalToolCount()).
168- Msg("Registered local credential tools")
169-
170- // Get available tools (includes upstream + local credential tools)
171- tools, err := proxy.ListTools(ctx)
172- if err != nil {
173- log.Warn().Err(err).Msg("Failed to list tools - continuing without tools")
174- tools = []mcp.Tool{}
175- } else {
176- log.Info().Int("count", len(tools)).Msg("Tools available")
177- }
178-
179- // Load message history
180- history, err := sessionMgr.LoadHistory(sessionID)
181- if err != nil {
182- return err
183- }
184-
185- // Load system prompt from markdown file if provided
186- if flags.SystemFile != "" {
187- systemPrompt, err := loadSystemPromptFromFile(flags.SystemFile)
188- if err != nil {
189- return err
190- }
191- if !historyHasSystemPrompt(history, systemPrompt) {
192- history = prependSystemPrompt(history, systemPrompt)
193- }
194- }
195-
196- // Check if TUI mode requested
197- if flags.TUI {
198- // Use TUI mode
199- return runTUI(ctx, sessionMgr, sessionID, prov, proxy, tools, history)
200- }
33+// printWelcome displays the welcome banner.
34+func 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+}
20144
202- // Print welcome message (CLI mode only)
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.
47+func 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
20380 printWelcome(selectedProvider, selectedModel, len(tools), sessionInfo)
20481
205- // Start conversation loop (CLI mode)
82+ // Start conversation loop
20683 app := &App{
20784 provider: prov,
20885 proxy: proxy,
@@ -212,9 +89,12 @@ func Run(version string) error {
21289 sessionID: sessionID,
21390 }
21491
215- // Start autoplay if flag provided
216- if flags.Autoplay != "" {
217- if err := app.startAutoplayFromFlag(ctx, flags.Autoplay); err != nil {
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 {
21898 return fmt.Errorf("failed to start autoplay: %w", err)
21999 }
220100 }
@@ -222,18 +102,6 @@ func Run(version string) error {
222102 return app.runLoop(ctx)
223103 }
224104
225-// printWelcome displays the welcome banner.
226-func printWelcome(provider, model string, toolCount int, sessionInfo string) {
227- fmt.Println(styles.Brand.Render("╔══════════════════════════════════════╗"))
228- fmt.Println(styles.Brand.Render("║") + " " + styles.BrandBold.Render("Mysis") + " - SpaceMolt Agent CLI " + styles.Brand.Render("║"))
229- fmt.Println(styles.Brand.Render("╚══════════════════════════════════════╝"))
230- fmt.Println()
231- fmt.Println(styles.Muted.Render(fmt.Sprintf("Provider: %s (%s)", provider, model)))
232- fmt.Println(styles.Muted.Render(fmt.Sprintf("Tools: %d available", toolCount)))
233- fmt.Println(styles.Muted.Render(sessionInfo))
234- fmt.Println()
235-}
236-
237105 // runLoop runs the main conversation loop.
238106 func (app *App) runLoop(ctx context.Context) error {
239107 scanner := bufio.NewScanner(os.Stdin)
@@ -322,7 +190,8 @@ func (app *App) addMessage(msg provider.Message) {
322190 }
323191
324192 // listSessionsCmd lists recent sessions.
325-func listSessionsCmd(mgr *session.Manager) error {
193+// ListSessionsCmd lists all recent sessions.
194+func ListSessionsCmd(mgr *session.Manager) error {
326195 sessions, err := mgr.List(20)
327196 if err != nil {
328197 return err
@@ -356,7 +225,8 @@ func listSessionsCmd(mgr *session.Manager) error {
356225 }
357226
358227 // deleteSessionCmd deletes a session by name.
359-func deleteSessionCmd(mgr *session.Manager, name string) error {
228+// DeleteSessionCmd deletes a session by name.
229+func DeleteSessionCmd(mgr *session.Manager, name string) error {
360230 // Get session to show info before deletion
361231 sess, err := mgr.GetByName(name)
362232 if err != nil {
@@ -390,124 +260,3 @@ func deleteSessionCmd(mgr *session.Manager, name string) error {
390260 }
391261
392262 // initializeProviders creates and registers all configured providers
393-func initializeProviders(cfg *config.Config, creds *config.Credentials) *provider.Registry {
394- registry := provider.NewRegistry()
395-
396- for name, provCfg := range cfg.Providers {
397- // Detect provider type based on endpoint
398- if strings.Contains(provCfg.Endpoint, "localhost:11434") || strings.Contains(provCfg.Endpoint, "/ollama") {
399- // Ollama provider
400- factory := provider.NewOllamaFactory(name, provCfg.Endpoint)
401- registry.RegisterFactory(name, factory)
402- log.Debug().Str("name", name).Str("endpoint", provCfg.Endpoint).Msg("Registered Ollama provider")
403- } else if strings.Contains(provCfg.Endpoint, "opencode.ai") {
404- // OpenCode Zen provider
405- keyName := provCfg.APIKeyName
406- if keyName == "" {
407- keyName = name
408- }
409- apiKey := creds.GetAPIKey(keyName)
410- if apiKey == "" {
411- log.Warn().Str("name", name).Str("key_name", keyName).Msg("No API key found for provider")
412- continue
413- }
414- factory := provider.NewOpenCodeFactory(name, provCfg.Endpoint, apiKey)
415- registry.RegisterFactory(name, factory)
416- log.Debug().Str("name", name).Str("endpoint", provCfg.Endpoint).Msg("Registered OpenCode provider")
417- } else {
418- log.Warn().Str("name", name).Str("endpoint", provCfg.Endpoint).Msg("Unknown provider type")
419- }
420- }
421-
422- return registry
423-}
424-
425-func loadSystemPromptFromFile(path string) (string, error) {
426- ext := strings.ToLower(filepath.Ext(path))
427- if ext != ".md" && ext != ".markdown" {
428- return "", fmt.Errorf("system prompt file must be markdown (.md or .markdown): %s", path)
429- }
430-
431- data, err := os.ReadFile(path)
432- if err != nil {
433- return "", fmt.Errorf("read system prompt file: %w", err)
434- }
435-
436- content := strings.TrimSpace(string(data))
437- if content == "" {
438- return "", fmt.Errorf("system prompt file is empty: %s", path)
439- }
440-
441- return content, nil
442-}
443-
444-func historyHasSystemPrompt(history []provider.Message, content string) bool {
445- for _, msg := range history {
446- if msg.Role == "system" && msg.Content == content {
447- return true
448- }
449- }
450- return false
451-}
452-
453-func prependSystemPrompt(history []provider.Message, content string) []provider.Message {
454- systemMsg := provider.Message{Role: "system", Content: content}
455- return append([]provider.Message{systemMsg}, history...)
456-}
457-
458-// setupFileLogging configures zerolog to write to a file in the config directory.
459-func setupFileLogging(debug bool) error {
460- // Get data directory
461- dataDir, err := config.DataDir()
462- if err != nil {
463- return fmt.Errorf("get data directory: %w", err)
464- }
465-
466- // Create logs directory
467- logDir := filepath.Join(dataDir, "logs")
468- if err := os.MkdirAll(logDir, 0755); err != nil {
469- return fmt.Errorf("create logs directory: %w", err)
470- }
471-
472- // Create log file with timestamp
473- logFile := filepath.Join(logDir, "mysis.log")
474- file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
475- if err != nil {
476- return fmt.Errorf("open log file: %w", err)
477- }
478-
479- // Set up multi-writer: file (JSON) + console writer for debugging
480- var writers []io.Writer
481-
482- // Always write JSON to file
483- writers = append(writers, file)
484-
485- // In debug mode, also write human-readable logs to a separate debug file
486- if debug {
487- debugFile := filepath.Join(logDir, "mysis-debug.log")
488- debugFileWriter, err := os.OpenFile(debugFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
489- if err != nil {
490- return fmt.Errorf("open debug log file: %w", err)
491- }
492- consoleWriter := zerolog.ConsoleWriter{Out: debugFileWriter, TimeFormat: time.RFC3339}
493- writers = append(writers, consoleWriter)
494- }
495-
496- // Configure logger
497- multi := io.MultiWriter(writers...)
498- log.Logger = zerolog.New(multi).With().Timestamp().Logger()
499-
500- // Set log level
501- if debug {
502- zerolog.SetGlobalLevel(zerolog.DebugLevel)
503- } else {
504- zerolog.SetGlobalLevel(zerolog.InfoLevel)
505- }
506-
507- log.Info().
508- Str("log_file", logFile).
509- Bool("debug", debug).
510- Msg("File logging initialized for TUI mode")
511-
512- return nil
513-}
internal/cli/help.go+5−78
@@ -1,91 +1,18 @@
11 package cli
22
33 import (
4- "flag"
54 "fmt"
6- "os"
Cut short: this commit's diff is over 1000 lines.
internal/cli/tui.go+0−35
Cut short: this commit's diff is over 1000 lines.
internal/features/app.go+143−0
Cut short: this commit's diff is over 1000 lines.
internal/features/autoplay.go+269−0
Cut short: this commit's diff is over 1000 lines.
internal/features/flags.go+72−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/app.go+6−14
Cut short: this commit's diff is over 1000 lines.
internal/tui/runner.go+128−195
Cut short: this commit's diff is over 1000 lines.