xonecas.io
6119
My

mysis / commit 8df4e1a

feat: initial TUI implementation

Add Bubbletea-based terminal UI with conversation viewport, status bar,
and input field. Includes support for scrolling, autoplay, and session
management.

xonecas2026-02-11 8df4e1a80ab2aa0b7ed7c1dd561248b7f0271639 parent 120cdf3

23 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+29−30
@@ -14,60 +14,59 @@ The agent maintains conversation history and calls SpaceMolt game tools (login,
1414
1515 **Provider** (`internal/provider/`): OpenAI-compatible LLM client interface. Supports Ollama (local) and OpenCode Zen (cloud). Factory pattern for creating providers with model/temperature params.
1616
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.
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.
1818
19-**Styles** (`internal/styles/`): Brand colors for terminal output.
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.
2030
2131 ## Implementation Status
2232
23-**Working pipes**:
24-- Config loading from TOML
33+**Fully implemented**:
34+
35+- Config loading from TOML with default provider support
2536 - Multiple LLM provider support (Ollama, OpenCode Zen)
2637 - MCP client with upstream game server connection
2738 - Tool call retry with rate limiting
28-- Credential management (JSON with 0600 permissions)
29-
30-**Not implemented**:
31-- CLI conversation loop
32-- Message history storage
39+- Credential management (session-scoped, SQLite storage)
40+- CLI conversation loop with stdin input
41+- Message history storage (SQLite with compression)
3342 - Agent state management
34-- Terminal UI rendering
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
3547
3648 ## Design Decisions
3749
38-**Single agent focus**: No multi-agent coordination, no account pooling, no broadcast messaging. One user, one agent, direct communication.
39-
40-**MCP proxy simplicity**: Pass-through to upstream tools with retry logic. Local tool registration available but unused initially.
50+**MCP proxy simplicity**: Pass-through to upstream tools with retry logic. Local tool registration available but unused initially. ** DO NOT CHANGE UPSTREAM RESPONSES **
4151
4252 **Config-driven**: Provider selection via config file. No runtime provider switching.
4353
44-**Data directory**: `~/.config/mysis` for config, credentials, future message history.
54+**Data directory**: `~/.config/mysis` for config, credentials, database (sessions, messages, game credentials).
4555
4656 ## Where to Find Things
4757
4858 - Config: `config.toml` and `~/.config/mysis/`
49-- Credentials: `~/.config/mysis/credentials.json` (auto-created with 0600)
59+- Database: `~/.config/mysis/mysis.db` (SQLite with sessions, messages, credentials)
60+- Credentials (LLM providers): `~/.config/mysis/credentials.json` (auto-created with 0600)
5061 - Logs: stderr (zerolog)
5162 - Main entry: `cmd/mysis/main.go`
5263 - Provider registry: `internal/provider/registry.go`
5364 - MCP proxy: `internal/mcp/proxy.go`
5465 - 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`
5569
5670 ## Agent Rules
5771
5872 **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.
59-
60-## Next Steps
61-
62-Implement CLI conversation loop in `cmd/mysis/main.go`:
63-1. Load config and create provider
64-2. Initialize MCP proxy
65-3. Read user input from stdin
66-4. Build LLM messages from history
67-5. Call LLM with available tools
68-6. Execute tool calls via MCP
69-7. Display response
70-8. Store in history
71-9. Loop
72-
73-See `documentation/architecture/DESIGN.md` for CLI feature spec.
cmd/mysis/main.go+173−1
@@ -1,19 +1,191 @@
11 package main
22
33 import (
4+ "context"
45 "fmt"
56 "os"
67
8+ "github.com/rs/zerolog"
9+ "github.com/rs/zerolog/log"
710 "github.com/xonecas/mysis/internal/cli"
11+ "github.com/xonecas/mysis/internal/config"
12+ "github.com/xonecas/mysis/internal/mcp"
13+ "github.com/xonecas/mysis/internal/provider"
14+ "github.com/xonecas/mysis/internal/session"
15+ "github.com/xonecas/mysis/internal/store"
816 "github.com/xonecas/mysis/internal/styles"
17+ "github.com/xonecas/mysis/internal/tui"
918 )
1019
1120 // Version is set at build time via ldflags.
1221 var Version = "dev"
1322
1423 func main() {
15- if err := cli.Run(Version); err != nil {
24+ if err := run(); err != nil {
1625 fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
1726 os.Exit(1)
1827 }
1928 }
29+
30+func run() error {
31+ ctx := context.Background()
32+
33+ // Parse flags
34+ flags := cli.ParseFlags(Version)
35+
36+ // Initialize logging
37+ if err := setupLogging(flags); err != nil {
38+ return err
39+ }
40+
41+ // Check config path
42+ if flags.ConfigPath == "" {
43+ fmt.Fprintln(os.Stderr, styles.Error.Render("Error: config file not found"))
44+ fmt.Fprintln(os.Stderr, "Tried: ./config.toml and ~/.config/mysis/config.toml")
45+ return fmt.Errorf("config file not found")
46+ }
47+
48+ log.Info().
49+ Str("version", Version).
50+ Str("config", flags.ConfigPath).
51+ Msg("Starting Mysis")
52+
53+ // Load config
54+ cfg, err := config.Load(flags.ConfigPath)
55+ if err != nil {
56+ return fmt.Errorf("failed to load config: %w", err)
57+ }
58+
59+ // Open database
60+ db, err := store.Open()
61+ if err != nil {
62+ return fmt.Errorf("failed to open database: %w", err)
63+ }
64+ defer db.Close()
65+
66+ // Create session manager
67+ sessionMgr := session.NewManager(db)
68+
69+ // Handle special commands
70+ if flags.ListSessions {
71+ return cli.ListSessionsCmd(sessionMgr)
72+ }
73+ if flags.DeleteSession != "" {
74+ return cli.DeleteSessionCmd(sessionMgr, flags.DeleteSession)
75+ }
76+
77+ // Load credentials
78+ creds, err := config.LoadCredentials()
79+ if err != nil {
80+ log.Warn().Err(err).Msg("Failed to load credentials, using empty credentials")
81+ creds = &config.Credentials{}
82+ }
83+
84+ // Initialize provider registry
85+ registry := cli.InitializeProviders(cfg, creds)
86+
87+ // Select provider and model
88+ providerResult, err := sessionMgr.SelectProvider(cfg, flags.SessionName, flags.ProviderName)
89+ if err != nil {
90+ return err
91+ }
92+ selectedProvider := providerResult.Provider
93+ selectedModel := providerResult.Model
94+
95+ // Verify provider exists in config
96+ providerCfg, ok := cfg.Providers[selectedProvider]
97+ if !ok {
98+ return fmt.Errorf("provider '%s' not found in config", selectedProvider)
99+ }
100+
101+ // Create provider instance
102+ prov, err := registry.Create(selectedProvider, selectedModel, providerCfg.Temperature)
103+ if err != nil {
104+ return fmt.Errorf("failed to create provider: %w", err)
105+ }
106+ defer prov.Close()
107+ log.Info().Str("provider", selectedProvider).Str("model", selectedModel).Msg("Provider initialized")
108+
109+ // Initialize MCP client and proxy
110+ mcpClient := mcp.NewClient(cfg.MCP.Upstream)
111+ proxy := mcp.NewProxy(mcpClient)
112+ if err := proxy.Initialize(ctx); err != nil {
113+ log.Warn().Err(err).Msg("Failed to initialize MCP - continuing without game tools")
114+ } else {
115+ log.Info().Str("upstream", cfg.MCP.Upstream).Msg("MCP proxy initialized")
116+ }
117+ defer proxy.Close()
118+
119+ // Initialize or resume session
120+ sessionResult, err := sessionMgr.Initialize(flags.SessionName, selectedProvider, selectedModel)
121+ if err != nil {
122+ return err
123+ }
124+ sessionID := sessionResult.SessionID
125+ sessionInfo := sessionResult.SessionInfo
126+
127+ // Register credential tools (session-scoped)
128+ proxy.RegisterTool(
129+ mcp.NewSaveCredentialsTool(),
130+ mcp.MakeSaveCredentialsHandler(db, sessionID),
131+ )
132+ proxy.RegisterTool(
133+ mcp.NewGetCredentialsTool(),
134+ mcp.MakeGetCredentialsHandler(db, sessionID),
135+ )
136+ log.Debug().
137+ Str("session_id", sessionID).
138+ Int("local_tools", proxy.LocalToolCount()).
139+ Msg("Registered local credential tools")
140+
141+ // Get available tools
142+ tools, err := proxy.ListTools(ctx)
143+ if err != nil {
144+ log.Warn().Err(err).Msg("Failed to list tools - continuing without tools")
145+ tools = []mcp.Tool{}
146+ } else {
147+ log.Info().Int("count", len(tools)).Msg("Tools available")
148+ }
149+
150+ // Load message history
151+ history, err := sessionMgr.LoadHistory(sessionID)
152+ if err != nil {
153+ return err
154+ }
155+
156+ // Load system prompt if provided
157+ if flags.SystemFile != "" {
158+ systemPrompt, err := cli.LoadSystemPromptFromFile(flags.SystemFile)
159+ if err != nil {
160+ return err
161+ }
162+ if !cli.HistoryHasSystemPrompt(history, systemPrompt) {
163+ history = cli.PrependSystemPrompt(history, systemPrompt)
164+ }
165+ }
166+
167+ // Delegate to CLI or TUI
168+ if flags.TUI {
169+ return tui.Run(ctx, sessionMgr, sessionID, prov, proxy, tools, history, flags.Autoplay)
170+ }
171+
172+ return cli.RunCLI(ctx, sessionMgr, sessionID, sessionInfo, prov, proxy, tools, history, flags.Autoplay, selectedProvider, selectedModel)
173+}
174+
175+func setupLogging(flags *cli.Flags) error {
176+ zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
177+
178+ if flags.TUI {
179+ // TUI mode: log to file to avoid collision with UI
180+ return cli.SetupFileLogging(flags.Debug)
181+ }
182+
183+ // CLI mode: log to stderr
184+ log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
185+ if flags.Debug {
186+ zerolog.SetGlobalLevel(zerolog.DebugLevel)
187+ } else {
188+ zerolog.SetGlobalLevel(zerolog.InfoLevel)
189+ }
190+ return nil
191+}
config.toml+3−0
@@ -1,3 +1,6 @@
1+# Default provider (optional - if not set, first provider in map is used)
2+default_provider = "zen-nano"
3+
14 # Ollama providers (local)
25 [providers.ollama-qwen]
36 endpoint = "http://localhost:11434"
documentation/TODO.md+3−273
@@ -1,274 +1,4 @@
1-# TODO: Critical Bugs
1+# TODO:
22
3-## CRITICAL: Agent Repeating Tool Calls
4-
5-Multiple critical bugs cause agents to repeat the same tool calls indefinitely. Root cause identified through comprehensive audit (2026-02-10).
6-
7----
8-
9-### ~~BUG #1: History Snapshot Never Updated in Multi-Round Loop~~ [FIXED]
10-
11-**Status:** ✅ FIXED (2026-02-10)
12-
13-**Priority:** P0 - PRIMARY CAUSE of repeated tool calls
14-
15-**Location:**
16-
17-- `internal/cli/cli.go:266-282`
18-- `internal/llm/loop.go:40-107`
19-
20-**Problem:**
21-`processTurn()` creates a snapshot of conversation history and passes it to `ProcessTurn()`. Inside the loop, `ProcessTurn()` iterates up to 20 rounds for tool calls. Each round uses the **same original snapshot** for compression.
22-
23-When tool results are added via `OnMessage` callback, they update `app.history` but `opts.History` (the snapshot passed to ProcessTurn) never sees these new messages. The LLM repeatedly receives history without its own tool results.
24-
25-**Example Flow:**
26-
27-1. Round 0: LLM gets initial history, calls tool `get_status`
28-2. Tool result added to `app.history` via OnMessage
29-3. Round 1: `compressedHistory` regenerated from original snapshot (doesn't include tool result from round 0)
30-4. LLM receives history WITHOUT the tool result from round 0
31-5. LLM doesn't know it already called `get_status`, calls it again
32-6. Infinite loop until MaxToolRounds limit (20 rounds)
33-
34-**Evidence:**
35-
36-- `loop.go:43`: `compressedHistory := store.CompressHistory(opts.History, opts.HistoryKeepLast)` - always uses same snapshot
37-- `cli.go:269-271`: History snapshot made once, never updated during turn
38-- `loop.go:86-99, 142-146, 159-179`: Tool results added to `app.history`, but `opts.History` unchanged
39-
40-**Fix Applied:** Option A - Update `opts.History` after each round
41-
42-**Changes Made:**
43-
44-1. Modified `internal/llm/loop.go:86-91` - Update `opts.History` after adding assistant response (no tool calls)
45-2. Modified `internal/llm/loop.go:96-103` - Update `opts.History` after adding assistant message with tool calls
46-3. Modified `internal/llm/loop.go:106-110` - Collect tool results and append to `opts.History`
47-4. Modified `executeToolCalls()` signature to return `([]provider.Message, error)` so tool results can be collected
48-5. Modified `executeToolCalls()` implementation to collect and return all tool result messages
49-
50-**How It Works Now:**
51-
52-- After each `OnMessage()` callback, the corresponding message is also appended to `opts.History`
53-- On the next loop iteration, `CompressHistory()` sees the complete history including all tool calls and results from previous rounds
54-- LLM receives compressed history that includes its own previous tool calls and results
55-- LLM no longer repeats tool calls because it can see the results in history
56-
57----
58-
59-### BUG #2: Race Condition in History Append [CRITICAL]
60-
61-**Priority:** P0 - Race condition with autoplay
62-
63-**Location:**
64-
65-- `internal/cli/cli.go:246` (manual input - NO LOCK)
66-- `internal/cli/autoplay.go:190` (autoplay - HAS LOCK)
67-
68-**Problem:**
69-Manual user input appends to `app.history` WITHOUT mutex lock:
70-
71-```go
72-// cli.go:246 - NO LOCK
73-app.history = append(app.history, userMsg)
74-```
75-
76-But autoplay DOES lock:
77-
78-```go
79-// autoplay.go:190 - HAS LOCK
80-app.mu.Lock()
81-app.history = append(app.history, userMsg)
82-app.mu.Unlock()
83-```
84-
85-**Race Scenario:**
86-
87-```
88-Time Main Loop (manual input) Autoplay Goroutine
89----- --------------------------- --------------------
90-T1 mu.Lock()
91-T2 app.history = append(...)
92-T3 app.history = append(...)
93-T4 mu.Unlock()
94-```
95-
96-At T2, main loop appends without lock while autoplay holds lock. Violates mutex semantics.
97-
98-**Impact:**
99-
100-- Slice corruption: append may resize backing array while another goroutine accesses it
101-- Lost messages: concurrent appends may overwrite each other
102-- Panic: possible slice index out of range
103-
104-**Fix:**
105-
106-```go
107-// cli.go:246 - Add mutex protection
108-app.mu.Lock()
109-app.history = append(app.history, userMsg)
110-app.mu.Unlock()
111-```
112-
113----
114-
115-### BUG #3: Shallow Copy in Compression Mutates Backing Arrays [CRITICAL]
116-
117-**Priority:** P0 - Silent data corruption
118-
119-**Location:**
120-
121-- `internal/store/compression.go:132-134`
122-- `internal/store/compression.go:140-142`
123-
124-**Problem:**
125-
126-```go
127-// Line 132-134
128-compressedMsg := msg // SHALLOW COPY - shares backing arrays!
129-compressedMsg.Content = compressedToolResult
130-compressed = append(compressed, compressedMsg)
131-
132-// Line 140-142
133-compressedMsg := msg // SHALLOW COPY - shares backing arrays!
134-compressedMsg.Content = msg.Content[:200] + "... [truncated]"
135-compressed = append(compressed, compressedMsg)
136-```
137-
138-`compressedMsg := msg` creates shallow copy. The `ToolCalls` slice in both `msg` and `compressedMsg` point to the **same backing array**. Later append operations can mutate the backing array visible to both original and compressed history.
139-
140-**Impact:**
141-
142-- Messages in compressed history can have their `ToolCalls` mutated
143-- Database saves may contain corrupted ToolCalls data
144-- LLM may receive inconsistent history across rounds
145-
146-**Fix:**
147-
148-```go
149-// Deep copy the message struct
150-compressedMsg := provider.Message{
151- Role: msg.Role,
152- Content: compressedToolResult,
153- ToolCallID: msg.ToolCallID,
154- ToolCalls: append([]provider.ToolCall(nil), msg.ToolCalls...),
155-}
156-```
157-
158----
159-
160-### BUG #4: Naive Truncation Loses Critical Information [HIGH]
161-
162-**Priority:** P1 - Can cause LLM to miss important game events
163-
164-**Location:** `internal/store/compression.go:139-142`
165-
166-**Problem:**
167-Truncation simply takes first 200 characters of action tool results. If critical information appears later in the response (common in verbose API responses), it gets lost.
168-
169-```go
170-if len(msg.Content) > 500 {
171- compressedMsg := msg
172- compressedMsg.Content = msg.Content[:200] + "... [truncated]"
173- compressed = append(compressed, compressedMsg)
174-}
175-```
176-
177-**Real-world scenario:**
178-
179-- SpaceMolt travel response: 1198 characters
180-- First 200 chars: Headers and departure info
181-- Lost content: "CRITICAL: Base commander requests immediate meeting for urgent mission!"
182-- Result: LLM misses quest hooks and important notifications
183-
184-**Why this causes repeated tool calls:**
185-If truncation removes success confirmation or critical state changes, LLM may think action didn't complete and try again.
186-
187-**Fix Options:**
188-
189-Option A: Smart truncation (keep beginning and end)
190-
191-```go
192-if len(msg.Content) > 500 {
193- compressedMsg := msg
194- start := msg.Content[:150]
195- end := msg.Content[len(msg.Content)-50:]
196- compressedMsg.Content = start + "... [middle truncated] ..." + end
197- compressed = append(compressed, compressedMsg)
198-}
199-```
200-
201-Option B: Configurable truncation
202-
203-```go
204-const truncateKeepFirst = 150
205-const truncateKeepLast = 50
206-
207-if len(msg.Content) > 500 {
208- compressedMsg := msg
209- start := msg.Content[:truncateKeepFirst]
210- end := msg.Content[len(msg.Content)-truncateKeepLast:]
211- compressedMsg.Content = start + "..." + end + " [truncated]"
212- compressed = append(compressed, compressedMsg)
213-}
214-```
215-
216----
217-
218-## Additional Issues Found During Audit
219-
220-### BUG #5: Missing ToolCalls Field in No-Tool-Call Response [MEDIUM]
221-
222-**Priority:** P2 - Data consistency issue
223-
224-**Location:** `internal/llm/loop.go:86-89`
225-
226-**Problem:**
227-When LLM responds with text only (no tool calls), assistant message is added without preserving the ToolCalls field:
228-
229-```go
230-opts.OnMessage(provider.Message{
231- Role: "assistant",
232- Content: resp.Content,
233- // ToolCalls field missing - defaults to nil
234-})
235-```
236-
237-**Fix:**
238-
239-```go
240-opts.OnMessage(provider.Message{
241- Role: "assistant",
242- Content: resp.Content,
243- ToolCalls: resp.ToolCalls, // Include even if empty
244-})
245-```
246-
247----
248-
249-### BUG #6: ProcessTurn Non-Blocking Allows Concurrent Autoplay [HIGH]
250-
251-**Priority:** P1 - Autoplay timing bug
252-
253-**Location:** `internal/cli/autoplay.go:198-206`
254-
255-**Problem:**
256-After calling `processTurn()`, the function returns immediately without waiting for turn completion. The ticker continues and can fire again.
257-
258-```go
259-if err := app.processTurn(ctx); err != nil {
260- fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
261- log.Warn().Err(err).Msg("Autoplay turn failed, continuing...")
262-}
263-
264-fmt.Println()
265-return nil // Returns immediately
266-```
267-
268-Autoplay interval: 100 seconds (10 tools × 10s/tick). But `processTurn()` can take longer if there are delays, retries, or >10 tool calls. Timer fires at fixed intervals regardless of whether previous turn finished.
269-
270-**Impact:**
271-If turn takes >100 seconds, ticker fires again before previous turn completes, causing concurrent `processTurn()` executions.
272-
273-**Fix:**
274-Add synchronization to block next autoplay message until current turn completes.
3+- Blinking cursor in TUI
4+- Mouse selection in TUI
documentation/architecture/DESIGN.md+92−7
@@ -5,6 +5,7 @@
55 A fully featured agentic interface for Spacemolt, themed like a mysis from [Zoea Nova](//TODO).
66
77 **Spacemolt Game docs:**
8+
89 - https://www.spacemolt.com/skill.md
910 - https://www.spacemolt.com/api.md
1011
@@ -14,10 +15,10 @@ A fully featured agentic interface for Spacemolt, themed like a mysis from [Zoea
1415
1516 **In-conversation commands:**
1617
17-- `/autoplay [-t number of ticks to play] [Repeated response]`
18- - Autoplay sends the repeated message every X ticks in game (we need to poll for tick info every tick time of the server, see docs on how to get updates)
18+- `/autoplay [Repeated response]`
19+ - Autoplay sends the repeated message every `game tick time * max tool calls * .75` seconds
1920
20-- `/verbose`
21+- `/verbose` ** NOT IMPLEMENTED YET **
2122 - Verbose truncates some outputs. For now simple truncations
2223
2324 **Config file and CLI arguments:**
@@ -27,14 +28,98 @@ A fully featured agentic interface for Spacemolt, themed like a mysis from [Zoea
2728
2829 **MCP tools:**
2930
30-- `save_credentials(username, password)` / `get_credentials` - Simple tools to save username/password to a local file in the home directory. Get takes username, save them as text
31+- `save_credentials(username, password)` / `get_credentials` - Simple tools to save username/password to a local sqlite database in the config file folder.
3132 - The session id for the mysis saving the pair, we inject, **DO NOT MAKE IT AN ARGUMENT FOR THE AGENTS**
3233
33-**Basic controls on the input:**
34+# TUI - Not a replacement, an augmentation.
35+
36+Same UI as CLI: simple, with a permanent input line and the conversation log.
37+
38+- Simple drawing:
39+
40+```
41+┌─────────────────────────────────┐
42+│ │
43+│ Conversation Log │
44+│ (scrollable viewport) │
45+│ │
46+│ I'm going to mine now! │
47+│ [00:00:00] Agent │
48+│ │
49+│ Ok! Tell me when you're │
50+│ you are done! │
51+│ [00:00:00] You │
52+│ │
53+├─────────────────────────────────┤
54+│ > Input line___ │
55+├─────────────────────────────────┤
56+│ [A][I][W][E] Status text [L][M] │
57+└─────────────────────────────────┘
58+```
59+
60+Uses our colors from internal/style.
61+Elegant but retro-futuristic in the same style as `assets/logo.svg`.
62+One background color: deep purple (ColorBg or ColorBgAlt, to be tested with both).
63+
64+### Log:
65+
66+- Same conversation log, no log messages. Pure agent conversation with truncated reasoning shown.
67+ - Reasoning is truncated from the end, showing the last portion of the text.
68+- No word wrap for reasoning, user messages, or agent replies.
69+- The rest (tools, tool calls) is truncated like CLI now.
70+
71+### Input:
72+
73+- Permanent input box with same functionality as CLI stdin currently.
74+- Commands: `/autoplay` `exit` `quit`
75+
76+- Adds keybinds:
77+ - `ESC` stop autoplay if autoplay is on
3478
3579 - Up/down arrows: message history
3680 - Left/right: edit the current line
3781
38-## TUI
82+### Status:
83+
84+- Shows a series of animated icons:
85+ - [E]: When an error is logged, animate the error icon and show error text (only system errors, not in-game).
86+ - [W]: When a warning is logged, animate the warning icon and show warning text.
87+ - [I]: When info is logged, nimate the info icon.
88+ - [A]: When autoplay is enabled, shows the truncated auto message.
89+
90+- Shows the text related to the animated icon from above.
91+
92+- Shows connection status with animated icons for LLM and MCP connections.
93+ - Animate when a request is fired.
94+
95+Animation:
96+
97+- items are always on the "empty" or "thinest" frame.
98+- When an event happens, the animation starts becomes quick for a few iterations, slowing down back to normal and stop.
99+- Subsequent events reset the slowdown.
100+
101+Animation Sequences:
102+
103+- Autoplay: ◔ ◑ ◕ ● → ends at ◔ (quarter circle)
104+- Info: ● ◉ ◎ ○ ◌ → ends at ◌ (empty circle)
105+- Warning: ◆ ◈ ◇ → ends at ◇ (hollow diamond)
106+- Error: ✖ ✕ → ends at (empty/space)
107+- LLM: ◉ ◎ ○ ◌ → ends at ◌ (empty circle)
108+- MCP: ◐ ◓ ◑ ◒ → ends at ○ (circle/dot)
109+
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+
121+# TODO:
39122
40-Coming soon. Once the pipes are tested with the CLI.
123+- blinking cursor?
124+- Session setup screen
125+- Game state sidebar, pretty, game like, retro.
go.mod+18−7
@@ -4,6 +4,8 @@ go 1.25.6
44
55 require (
66 github.com/BurntSushi/toml v1.6.0
7+ github.com/charmbracelet/bubbles v1.0.0
8+ github.com/charmbracelet/bubbletea v1.3.10
79 github.com/charmbracelet/lipgloss v1.1.0
810 github.com/google/uuid v1.6.0
911 github.com/mattn/go-sqlite3 v1.14.33
@@ -12,17 +14,26 @@ require (
1214 )
1315
1416 require (
17+ github.com/atotto/clipboard v0.1.4 // indirect
1518 github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
16- github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
17- github.com/charmbracelet/x/ansi v0.8.0 // indirect
18- github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
19- github.com/charmbracelet/x/term v0.2.1 // indirect
20- github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
19+ github.com/charmbracelet/colorprofile v0.4.1 // indirect
20+ github.com/charmbracelet/x/ansi v0.11.6 // indirect
21+ github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
22+ github.com/charmbracelet/x/term v0.2.2 // indirect
23+ github.com/clipperhouse/displaywidth v0.9.0 // indirect
24+ github.com/clipperhouse/stringish v0.1.1 // indirect
25+ github.com/clipperhouse/uax29/v2 v2.5.0 // indirect
26+ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
27+ github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
2128 github.com/mattn/go-colorable v0.1.13 // indirect
2229 github.com/mattn/go-isatty v0.0.20 // indirect
23- github.com/mattn/go-runewidth v0.0.16 // indirect
30+ github.com/mattn/go-localereader v0.0.1 // indirect
31+ github.com/mattn/go-runewidth v0.0.19 // indirect
32+ github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
33+ github.com/muesli/cancelreader v0.2.2 // indirect
2434 github.com/muesli/termenv v0.16.0 // indirect
2535 github.com/rivo/uniseg v0.4.7 // indirect
2636 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
27- golang.org/x/sys v0.30.0 // indirect
37+ golang.org/x/sys v0.38.0 // indirect
38+ golang.org/x/text v0.3.8 // indirect
2839 )
go.sum+39−17
@@ -1,37 +1,56 @@
11 github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
22 github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
3+github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
4+github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
35 github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
46 github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
5-github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
6-github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
7+github.com/charmbracelet/bubbles v1.0.0 h1:12J8/ak/uCZEMQ6KU7pcfwceyjLlWsDLAxB5fXonfvc=
8+github.com/charmbracelet/bubbles v1.0.0/go.mod h1:9d/Zd5GdnauMI5ivUIVisuEm3ave1XwXtD1ckyV6r3E=
9+github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
10+github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
11+github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk=
12+github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk=
713 github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
814 github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
9-github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE=
10-github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q=
11-github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8=
12-github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
13-github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
14-github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
15+github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF7ihZW8=
16+github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ=
17+github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI=
18+github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q=
19+github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
20+github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
21+github.com/clipperhouse/displaywidth v0.9.0 h1:Qb4KOhYwRiN3viMv1v/3cTBlz3AcAZX3+y9OLhMtAtA=
22+github.com/clipperhouse/displaywidth v0.9.0/go.mod h1:aCAAqTlh4GIVkhQnJpbL0T/WfcrJXHcj8C0yjYcjOZA=
23+github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
24+github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
25+github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U=
26+github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
1527 github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
28+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
29+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
1630 github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
1731 github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
1832 github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
19-github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
20-github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
33+github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
34+github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
2135 github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
2236 github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
2337 github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
2438 github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
2539 github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
2640 github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
27-github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
28-github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
41+github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
42+github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
43+github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
44+github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
2945 github.com/mattn/go-sqlite3 v1.14.33 h1:A5blZ5ulQo2AtayQ9/limgHEkFreKj1Dv226a1K73s0=
3046 github.com/mattn/go-sqlite3 v1.14.33/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
47+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
48+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
49+github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
50+github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
3151 github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
3252 github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
3353 github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
34-github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
3554 github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
3655 github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
3756 github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
@@ -41,10 +60,13 @@ github.com/sashabaranov/go-openai v1.41.2 h1:vfPRBZNMpnqu8ELsclWcAvF19lDNgh1t6TV
4160 github.com/sashabaranov/go-openai v1.41.2/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
4261 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
4362 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
44-golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
45-golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
63+golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
64+golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
65+golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
4666 golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
4767 golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
4868 golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
49-golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
50-golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
69+golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
70+golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
71+golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
72+golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
internal/cli/cli.go+82−8
@@ -4,6 +4,7 @@ import (
44 "bufio"
55 "context"
66 "fmt"
7+ "io"
78 "os"
89 "path/filepath"
910 "strings"
@@ -42,11 +43,20 @@ func Run(version string) error {
4243
4344 // Initialize logging
4445 zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
45- log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
46- if flags.Debug {
47- zerolog.SetGlobalLevel(zerolog.DebugLevel)
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+ }
4852 } else {
49- zerolog.SetGlobalLevel(zerolog.InfoLevel)
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+ }
5060 }
5161
5262 // Check config path
@@ -183,10 +193,16 @@ func Run(version string) error {
183193 }
184194 }
185195
186- // Print welcome message
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+ }
201+
202+ // Print welcome message (CLI mode only)
187203 printWelcome(selectedProvider, selectedModel, len(tools), sessionInfo)
188204
189- // Start conversation loop
205+ // Start conversation loop (CLI mode)
190206 app := &App{
191207 provider: prov,
192208 proxy: proxy,
@@ -252,8 +268,9 @@ func (app *App) runLoop(ctx context.Context) error {
252268
253269 // Add user message to history
254270 userMsg := provider.Message{
255- Role: "user",
256- Content: input,
271+ Role: "user",
272+ Content: input,
273+ CreatedAt: time.Now(),
257274 }
258275 app.history = append(app.history, userMsg)
259276
@@ -437,3 +454,60 @@ func prependSystemPrompt(history []provider.Message, content string) []provider.
437454 systemMsg := provider.Message{Role: "system", Content: content}
438455 return append([]provider.Message{systemMsg}, history...)
439456 }
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/flags.go+4−0
@@ -21,6 +21,7 @@ type Flags struct {
2121 DeleteSession string
2222 Autoplay string
2323 SystemFile string
24+ TUI bool
2425 }
2526
2627 // ParseFlags parses command-line flags and returns the result.
@@ -47,6 +48,8 @@ func ParseFlags(version string) *Flags {
4748 flag.StringVar(&f.Autoplay, "a", "", "Start autoplay immediately (shorthand)")
4849 flag.StringVar(&f.SystemFile, "file", "", "Load system prompt from markdown file")
4950 flag.StringVar(&f.SystemFile, "f", "", "Load system prompt from markdown file (shorthand)")
51+ flag.BoolVar(&f.TUI, "tui", false, "Use terminal UI mode instead of CLI")
52+ flag.BoolVar(&f.TUI, "t", false, "Use terminal UI mode (shorthand)")
5053
5154 flag.Usage = func() {
5255 printHelp(version)
@@ -99,6 +102,7 @@ func printHelp(version string) {
99102 fmt.Println(" " + styles.Secondary.Render("-s, --session") + " NAME Session name (resume or create)")
100103 fmt.Println(" " + styles.Secondary.Render("-a, --autoplay") + " MSG Start autoplay immediately with message")
101104 fmt.Println(" " + styles.Secondary.Render("-f, --file") + " PATH Load system prompt from markdown file")
105+ fmt.Println(" " + styles.Secondary.Render("-t, --tui") + " Use terminal UI mode")
102106 fmt.Println(" " + styles.Secondary.Render("-l, --list-sessions") + " List recent sessions and exit")
103107 fmt.Println(" " + styles.Secondary.Render("-D, --delete-session") + " N Delete session by name and exit")
104108 fmt.Println()
internal/cli/tui.go+35−0
@@ -0,0 +1,35 @@
1+package cli
2+
3+import (
4+ "context"
5+
6+ "github.com/xonecas/mysis/internal/mcp"
7+ "github.com/xonecas/mysis/internal/provider"
8+ "github.com/xonecas/mysis/internal/session"
9+ "github.com/xonecas/mysis/internal/tui"
10+)
11+
12+// runTUI starts the TUI mode.
13+func runTUI(
14+ ctx context.Context,
15+ sessionMgr *session.Manager,
16+ sessionID string,
17+ prov provider.Provider,
18+ proxy *mcp.Proxy,
19+ tools []mcp.Tool,
20+ history []provider.Message,
21+) error {
22+ // Create TUI runner
23+ runner := tui.NewRunner(
24+ ctx,
25+ sessionMgr,
Cut short: this commit's diff is over 1000 lines.
internal/config/config.go+10−2
Cut short: this commit's diff is over 1000 lines.
internal/constants/constants.go+5−2
Cut short: this commit's diff is over 1000 lines.
internal/llm/loop.go+53−19
Cut short: this commit's diff is over 1000 lines.
internal/provider/provider.go+3−0
Cut short: this commit's diff is over 1000 lines.
internal/session/session.go+9−4
Cut short: this commit's diff is over 1000 lines.
internal/store/store.go+25−4
Cut short: this commit's diff is over 1000 lines.
internal/styles/styles.go+6−6
Cut short: this commit's diff is over 1000 lines.
internal/tui/app.go+358−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/conversation.go+236−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/input.go+191−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/runner.go+411−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/statusbar.go+345−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/styles.go+161−0
Cut short: this commit's diff is over 1000 lines.