@@ -0,0 +1,586 @@
1+# mini-coder — spec
2+
3+A CLI coding agent. Small, fast, focused.
4+
5+## Motivation for rewrite
6+
7+The previous version tried to own too much: custom UI rendering, a provider
8+abstraction layer, markdown streaming, interactive widgets. Maintaining all of
9+that alongside the actual agent logic was too much scope. This rewrite narrows
10+the focus to **being a good coding agent** by leaning on two solid external
11+packages for the hard parts (LLM providers and terminal UI).
12+
13+## Principles
14+
15+1. **Lean on proven dependencies** — don't reimplement what a library does well.
16+2. **Flat, simple codebase** — no workspace packages, no internal abstraction layers beyond what the code naturally needs.
17+3. **Agent-first** — every decision serves the goal of reading code, making changes, and verifying them via the shell.
18+4. **Performance** — startup and turn latency matter more than features.
19+
20+## Core dependencies
21+
22+### `@mariozechner/pi-ai` — LLM provider layer
23+
24+Unified LLM API that handles everything we used to struggle with:
25+
26+- **Multi-provider**: Anthropic, OpenAI, Google, Bedrock, Mistral, Groq, xAI, OpenRouter, Ollama, and many more.
27+- **Streaming**: Rich event protocol (`text_delta`, `thinking_delta`, `toolcall_start/delta/end`, `done`, `error`).
28+- **Tool calling**: TypeBox schemas, validated arguments, streaming partial JSON.
29+- **Context**: Simple `{ systemPrompt, messages, tools }` structure. Serializable. Supports cross-provider handoffs.
30+- **Token/cost tracking**: Built into every `AssistantMessage.usage`.
31+- **OAuth**: OpenAI Codex, GitHub Copilot, Google Gemini CLI, Antigravity — browser-based login flows.
32+- **Model registry**: Auto-discovery from env vars, curated model metadata (context windows, costs, capabilities).
33+- **Thinking/reasoning**: Unified `ThinkingLevel` across providers.
34+
35+This replaces: `ai`, `@ai-sdk/anthropic`, `@ai-sdk/openai`, `@ai-sdk/google`, `@ai-sdk/openai-compatible`, and all the provider glue code.
36+
37+### `cel-tui` — terminal UI
38+
39+Declarative TUI framework with flexbox layout, built for exactly the kind of UI we need:
40+
41+- **Primitives**: `VStack`, `HStack`, `Text`, `TextInput` — composable, flexbox-based.
42+- **Components**: `Markdown` (streaming-aware), `Button`, `Select`, `Divider`, `Spacer`.
43+- **Input**: Kitty keyboard protocol, proper key handling, mouse scroll/click.
44+- **Rendering**: Differential cell-buffer rendering, synchronized output (no flicker).
45+- **Scroll**: Controlled/uncontrolled scroll with stick-to-bottom support.
46+- **Focus**: Tab/Shift+Tab traversal, controlled/uncontrolled focus.
47+
48+The chat example (`cel-tui/examples/chat.ts`) is essentially a skeleton of our UI. Markdown streaming, TextInput, scroll — it's all there.
49+
50+This replaces: `yoctocolors`, `yoctomarkdown`, `yoctoselect`, and all our custom widget/rendering code.
51+
52+### Other dependencies
53+
54+- **Runtime**: Bun — for runtime, bundling, testing, and `bun:sqlite`.
55+- **Schema validation**: TypeBox (re-exported from pi-ai) for tool schemas.
56+
57+## Tools
58+
59+Two built-in tools, plus a read-only image tool. Plugins may add more (see [Plugins](#plugins)).
60+
61+### `shell`
62+
63+Runs a command in the user's shell. Returns stdout, stderr, and exit code.
64+
65+Implementation details:
66+
67+- Large outputs are truncated (keeping head + tail with a middle marker) to avoid context explosion.
68+- The truncation threshold is configurable, tuned to keep useful output while staying well within context limits.
69+- Commands run via `$SHELL -c "<command>"` (falling back to `/bin/sh` if `$SHELL` is unset) with the CWD set to the session's working directory.
70+- Timeout: no default timeout. The user can interrupt via `Escape`.
71+
72+### `edit`
73+
74+Exact-text replacement in a single file.
75+
76+Implementation details:
77+
78+- Takes a file path (absolute, or relative to the session CWD), the old text to find, and the new text to replace it with.
79+- Fails deterministically if the old text is not found or matches multiple locations. Returns the error message so the model can self-correct.
80+- Create new files by passing empty old text and the full file content as new text. Parent directories are created automatically.
81+- Returns a confirmation or error message — no diff output (the agent already knows what it wrote).
82+- Encoding: reads and writes UTF-8. Preserves the file's existing line endings.
83+
84+### `readImage`
85+
86+Reads an image file and returns it as `ImageContent` (base64 + mimeType). This lets the model inspect screenshots, diagrams, or any image in the repo without the user explicitly attaching it.
87+
88+Implementation details:
89+
90+- Accepts a file path. Supports common formats: PNG, JPEG, GIF, WebP.
91+- Returns `ImageContent` in the tool result (pi-ai's `ToolResultMessage.content` supports images natively).
92+- Only registered when the current model supports image input. Hidden from models that don't.
93+
94+## Community standards
95+
96+### AGENTS.md
97+
98+Reference: https://agents.md
99+
100+There is no formal spec — AGENTS.md is a de facto convention established by Codex, Claude Code, pi, and others. The common behavior across implementations is to walk the directory tree toward root, collecting every `AGENTS.md` found.
101+
102+Our discovery:
103+
104+- Walk from CWD toward the **scan root**, collecting every `AGENTS.md` (and `CLAUDE.md`) found.
105+- Scan root, in priority order: **git root** (if in a repo) → **home directory** (fallback) → filesystem root (only if `MC_AGENTS_ROOT=/` is set).
106+- Also check `~/.agents/` for global agent instructions (cross-client convention).
107+- All files are additive, ordered root-to-leaf (general → specific).
108+
109+This avoids walking to filesystem root on deep paths. In practice, the scan root is almost always the git root.
110+
111+Contents are appended to the system prompt after the base instructions as project-specific context.
112+
113+### Agent Skills (agentskills.io)
114+
115+Reference: https://agentskills.io/specification — full format spec.
116+Reference: https://agentskills.io/client-implementation/adding-skills-support — client implementation guide.
117+
118+We follow the spec's progressive disclosure model:
119+
120+1. **Discovery** — at session start, scan for directories containing `SKILL.md` in:
121+ - `<project>/.mini-coder/skills/`
122+ - `<project>/.agents/skills/`
123+ - `~/.mini-coder/skills/`
124+ - `~/.agents/skills/`
125+
126+ The spec does not mandate discovery paths — these are our client-specific choices, following the convention from the client implementation guide. Project-level skills override user-level skills on name collision.
127+
128+2. **Catalog** — skill names + descriptions are disclosed in the system prompt so the model knows what's available. Low token cost (~50-100 per skill).
129+
130+3. **Activation** — the model activates skills by reading the `SKILL.md` file via the shell tool. No dedicated activation tool needed — the model already has file access. The catalog includes the absolute path to each `SKILL.md`.
131+
132+4. **User activation** — users can reference skills with `/skill:skill-name` in the prompt input. The skill body is injected into the user message directly.
133+
134+Relative paths in skills are resolved against the skill's directory. The system prompt instructions explain this to the model.
135+
136+## Plugins
137+
138+Plugins extend mini-coder with new tools and context. They are the mechanism for optional capabilities that don't belong in the core — MCP servers, custom tools, integrations.
139+
140+### Interface
141+
142+A plugin is a module that exports a function conforming to a simple interface:
143+
144+```ts
145+interface Plugin {
146+ name: string;
147+ description: string;
148+
149+ /** Called once at startup. Returns tools to register and/or context to add. */
150+ init(
151+ agent: AgentContext,
152+ config?: Record<string, unknown>,
153+ ): Promise<PluginResult>;
154+
155+ /** Called on shutdown for cleanup. */
156+ destroy?(): Promise<void>;
157+}
158+
159+interface PluginResult {
160+ /** Additional tools the agent can use. */
161+ tools?: Tool[];
162+ /** Additional context to append to the system prompt. */
163+ systemPromptSuffix?: string;
164+}
165+
166+interface AgentContext {
167+ /** The working directory. */
168+ cwd: string;
169+ /** Read-only access to the current session's messages. */
170+ messages: readonly Message[];
171+ /** The app data directory (~/.config/mini-coder/). */
172+ dataDir: string;
173+}
174+```
175+
176+### Discovery
177+
178+Plugins are declared in a config file (`~/.config/mini-coder/plugins.json` or similar). Each entry points to a module path or package name:
179+
180+```json
181+{
182+ "plugins": [
183+ { "name": "mcp", "module": "@mini-coder/plugin-mcp", "config": { ... } },
184+ { "name": "custom", "module": "./my-plugin.ts" }
185+ ]
186+}
187+```
188+
189+Built-in plugins (like MCP) can ship with mini-coder and be enabled by default.
190+
191+### MCP as a plugin
192+
193+MCP support is implemented as a plugin, not baked into the core. The MCP plugin:
194+
195+- Connects to configured MCP servers (stdio or HTTP).
196+- Converts MCP tools into mini-coder tools, prefixed with the server name.
197+- Adds server descriptions to the system prompt.
198+- Manages server lifecycle (connect on init, disconnect on destroy).
199+
200+This keeps the core agent loop clean — it only knows about `Tool[]`, regardless of where tools come from.
201+
202+### Why plugins
203+
204+- **Separation of concerns**: the agent loop doesn't know about MCP, OAuth flows, or any specific integration.
205+- **Optional complexity**: users who don't need MCP don't pay for it in startup time or code complexity.
206+- **Extensibility without bloat**: third-party tools, custom integrations, project-specific helpers — all through the same interface.
207+
208+## Agent loop
209+
210+The core runtime. This is what happens on each turn:
211+
212+1. **User submits a message** — the input text (plus any embedded images or skill bodies from `/skill:name`) becomes a pi-ai `UserMessage`. It is appended to the session's message history and persisted to the DB.
213+
214+2. **Build context** — construct a pi-ai `Context`: the system prompt (see [System prompt](#system-prompt)), the full message history, and the registered tool definitions (built-in + plugin tools). Git state in the session footer is refreshed before each turn.
215+
216+3. **Stream to LLM** — call `streamSimple(model, context, options)` from pi-ai. Iterate over the event stream:
217+ - `text_delta` / `thinking_delta` → update the UI (stream markdown, show thinking if enabled).
218+ - `toolcall_end` → execute the tool call (see below), append the `ToolResultMessage` to history and DB.
219+ - `done` → append the `AssistantMessage` to history and DB. Update cumulative stats. If `stopReason` is `"toolUse"`, go to step 4. If `"stop"` or `"length"`, return to the input prompt.
220+ - `error` → display error in the log, return to the input prompt.
221+
222+4. **Tool execution** — when the LLM requests tool calls:
223+ - Execute each tool call. For `shell`: run the command, capture output, truncate if needed. For `edit`: perform the replacement. For `readImage`: read and base64-encode the file. For plugin tools: delegate to the plugin.
224+ - Each result becomes a `ToolResultMessage` appended to history and DB (same turn number).
225+ - After all tool results are appended, loop back to step 2 (re-stream with the updated context).
226+
227+5. **Interrupt** — if the user presses `Escape` during streaming:
228+ - Abort the stream via `AbortSignal`.
229+ - The partial `AssistantMessage` (with `stopReason: "aborted"`) is appended to history and DB as-is. This preserves context so the LLM knows what it was doing when interrupted.
230+ - Return to the input prompt. The user can continue the conversation or `/undo` the interrupted turn.
231+
232+**No step limit** — the loop runs until the model stops (`stopReason: "stop"`) or the user interrupts. There is no maximum number of tool calls per turn.
233+
234+**Context limit** — when the cumulative token count approaches `Model.contextWindow`, the agent must handle it before the provider rejects the request. Strategy: when context usage exceeds a threshold (e.g., 90%), trigger a compaction step — summarize the conversation history into a condensed form and replace the older messages. The summary is generated by the model itself (a separate, non-streamed call). The compacted history must preserve the system prompt prefix unchanged to maintain prom …
235+
236+## Architecture
237+
238+Flat `src/` directory. No workspaces, no internal packages. Files are grouped by concern but there's no enforced module boundary beyond what TypeScript imports naturally provide.
239+
240+```
241+src/
242+ index.ts — entry point, CLI setup
243+ agent.ts — the core agent loop
244+ tools.ts — shell and edit tool implementations
245+ skills.ts — agentskills.io discovery, parsing, catalog
246+ prompt.ts — system prompt construction (base + AGENTS.md + skills + plugins + git)
247+ session.ts — SQLite session persistence
248+ plugins.ts — plugin loader and lifecycle
249+ git.ts — git state gathering
250+ ui.ts — cel-tui UI (layout, rendering, state)
251+ types.ts — shared types
252+```
253+
254+This is suggestive, not prescriptive. Files may split or merge as the code evolves.
255+
256+## System prompt
257+
258+A single prompt, model-agnostic. Assembled at session start from static parts and dynamic context.
259+
260+### Construction order
261+
262+1. **Base instructions** (static) — the core prompt below.
263+2. **AGENTS.md content** — project-specific instructions, injected as-is.
264+3. **Skills catalog** — names + descriptions + paths in XML format.
265+4. **Plugin suffixes** — any `systemPromptSuffix` returned by plugins.
266+5. **Session metadata** — current date, working directory.
267+
268+Prompt caching: the static prefix (1) should remain identical across turns. Dynamic sections (2–5) are appended and stable within a session, changing only on `/new` or CWD change.
269+
270+The `readImage` tool is **not** mentioned in the base instructions — it is conditionally registered (only for vision-capable models) and the model discovers it through the tool definitions, not the prompt text. This avoids confusing models that don't have image support.
271+
272+### Base instructions
273+
274+```
275+You are mini-coder, a coding agent running in the user's terminal.
276+
277+# Role
278+
279+You are an autonomous, senior-level coding assistant. When the user gives a direction, proactively gather context, plan, implement, and verify without waiting for additional prompts at each step. Bias toward action: make reasonable assumptions and deliver working code rather than asking clarifying questions, unless you are genuinely blocked.
280+
281+# Tools
282+
283+You have these core tools:
284+
285+- `shell` — run commands in the user's shell. Use this to explore the codebase (rg, find, ls, cat), run tests, build, git, and any other command. Prefer `rg` over `grep` for speed.
286+- `edit` — make exact-text replacements in files. Provide the file path, the exact text to find, and the replacement text. The old text must match exactly one location in the file. To create a new file, use an empty old text and the full file content as new text.
287+
288+You may also have additional tools provided by plugins. Use them when they match the task.
289+
290+Workflow: **inspect with shell → mutate with edit → verify with shell**.
291+
292+# Code quality
293+
294+- Conform to the codebase's existing conventions: patterns, naming, formatting, language idioms.
295+- Write correct, clear, minimal code. Don't over-engineer, don't add abstractions for hypothetical futures.
296+- Reuse before creating. Search for existing helpers before writing new ones.
297+- Tight error handling: no broad try/catch, no silent failures, no swallowed errors.
298+- Keep type safety. Avoid `any` casts. Use proper types and guards.
299+- Only add comments where the logic isn't self-evident.
300+
301+# Editing discipline
302+
303+- Read enough context before editing. Batch logical changes together rather than making many small edits.
304+- Never revert changes you didn't make unless explicitly asked.
305+- Never use destructive git commands (reset --hard, checkout --, clean -fd) unless the user requests it.
306+- Default to ASCII. Only use non-ASCII characters when the file already uses them or there's clear justification.
307+
308+# Exploring the codebase
309+
310+- Think first: before any tool call, decide all files and information you need.
311+- Batch reads: if you need multiple files, read them together in parallel rather than one at a time.
312+- Only make sequential calls when a later call genuinely depends on an earlier result.
313+
314+# Communication
315+
316+- Be concise. Friendly coding teammate tone.
317+- After making changes: lead with a quick explanation of what changed and why, then suggest logical next steps if any.
318+- Don't dump large file contents you've written — reference file paths.
319+- When suggesting multiple options, use numbered lists so the user can reply with a number.
320+- If asked for a review, focus on bugs, risks, regressions, and missing tests. Findings first, ordered by severity.
321+
322+# Persistence
323+
324+- Carry work through to completion within the current turn. Don't stop at analysis or partial fixes.
325+- If you encounter an error, diagnose and fix it rather than reporting it and stopping.
326+- Avoid excessive looping: if you're re-reading or re-editing the same files without progress, stop and ask the user.
327+```
328+
329+### Dynamic sections
330+
331+Appended after the base instructions:
332+
333+**AGENTS.md** (when present):
334+
335+```
336+# Project Context
337+
338+Project-specific instructions and guidelines:
339+
340+## <file-path>
341+
342+<content>
343+```
344+
345+**Skills catalog** (when skills are discovered):
346+
347+```
348+The following skills provide specialized instructions for specific tasks.
349+Use the shell tool to read a skill's file when the task matches its description.
350+When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md) and use that absolute path in tool commands.
351+
352+<available_skills>
353+ <skill>
354+ <name>...</name>
355+ <description>...</description>
356+ <location>...</location>
357+ </skill>
358+</available_skills>
359+```
360+
361+**Session footer**:
362+
363+```
364+Current date: YYYY-MM-DD
365+Current working directory: /path/to/cwd
366+Git: branch main | 3 staged, 1 modified, 2 untracked | +5 −2 vs origin/main
367+```
368+
369+The git line is omitted when not inside a repository. Fields are omitted when empty (e.g., no staged files, no remote tracking). Gathered once at session start and refreshed each turn via fast git commands:
370+
371+- `git rev-parse --show-toplevel` — repo root
372+- `git branch --show-current` — current branch
373+- `git status --porcelain` — staged, modified, untracked counts
374+- `git rev-list --left-right --count HEAD...@{upstream}` — ahead/behind remote
375+
376+This gives the model the same situational awareness a developer gets from their shell prompt — which branch, whether the tree is dirty, and whether there's unpushed work.
377+
378+### Design rationale
379+
380+Key decisions informed by the Codex prompting guide and Claude prompting best practices:
381+
382+- **Autonomy and persistence**: both guides emphasize that coding agents should bias toward action, persist through errors, and complete work end-to-end. The prompt explicitly states this.
383+- **Inspect → mutate → verify**: the Codex guide's recommended workflow. Makes the two-tool surface sufficient.
384+- **Batch reads**: both guides stress parallel tool calling. The prompt instructs the model to think first and batch.
385+- **No plan dumping**: the Codex guide notes that prompting for upfront plans can cause models to stop prematurely. We ask for action, not plans.
386+- **Edit discipline**: derived from Codex's editing constraints (don't revert others' changes, no destructive git, ASCII default).
387+- **Concise communication**: both guides recommend against verbose summaries. The prompt asks for brief explanations focused on what changed.
388+- **Model-agnostic**: no provider-specific instructions. Works across Anthropic, OpenAI, Google, and others. Uses XML tags for structure (well-understood by all major models).
389+- **Single prompt**: no branching based on model family. Complexity in the prompt is complexity we maintain.
390+
391+## CLI UX
392+
393+### Layout
394+
395+Three zones, top to bottom:
396+
397+```
398+┌──────────────────────────────────────────────┐
399+│ │
400+│ Conversation log │
401+│ (scrollable, flex: 1) │
402+│ │
403+│ ▶ User: fix the tests │
404+│ │
405+│ ▷ Agent: I'll check the test suite... │
406+│ ┌─────────────────────────────┐ │
407+│ │ $ bun test │ │
408+│ │ 3 passed, 1 failed │ │
409+│ └─────────────────────────────┘ │
410+│ Fixed the assertion in... │
411+│ │
412+├──────────────────────────────────────────────┤
413+│ > fix the remaining lint warnings │
414+│ in the utils file too │
415+├──────────────────────────────────────────────┤
416+│ ~/src/mini-coder main +3 ~1 ▲ 2 │
417+│ anthropic/sonnet-4 · med in:1.2k out:0.8k 42% $0.03 │
418+└──────────────────────────────────────────────┘
419+```
420+
421+cel-tui structure:
422+
423+```ts
424+VStack({ height: "100%" }, [
425+ // Conversation log — takes all available space
426+ VStack({ flex: 1, overflow: "scroll", scrollbar: true }),
427+ Divider(),
428+ // Input area — intrinsic height, grows up to maxHeight
429+ HStack({ padding: { x: 1 } }, [
430+ Text(">"),
431+ TextInput({ flex: 1, maxHeight: 10 }),
432+ ]),
433+ Divider(),
434+ // Status bar — fixed 2 lines
435+ VStack({ height: 2 }, [
436+ HStack([Text(cwd), Spacer(), Text(gitStatus)]),
437+ HStack([Text(modelInfo), Spacer(), Text(usage)]),
438+ ]),
439+]);
440+```
441+
442+### Status bar
443+
444+Two lines, four corners:
445+
446+```
447+~/src/mini-coder main +3 ~1 ▲ 2
448+anthropic/sonnet-4 · med in:1.2k out:0.8k · 42% · $0.03
449+```
450+
451+**Line 1 — location:**
452+
453+- Left: CWD, abbreviated with `~` for home. Truncated from the left (`…/mini-coder`) on narrow terminals.
454+- Right: git branch, working tree counts (+ staged, ~ modified, ? untracked), ahead of remote (▲ N). Omitted outside a repo.
455+
456+**Line 2 — session:**
457+
458+- Left: `provider/model · effort`. Effort shown as `low`, `med`, `high`, `xhigh`.
459+- Right: `in:input out:output · context% · $cost`. All values are **cumulative for the session**.
460+
461+Token counts use human-friendly units (1.2k, 45k, 1.2M). Context % is computed from cumulative tokens vs `Model.contextWindow`. Cost is a running sum of `AssistantMessage.usage.cost.total` across all messages in the session, accumulated by us (pi-ai tracks per-message only). Reset on `/new`, restored from DB on session resume.
462+
463+### Conversation log
464+
465+Scrollable area that shows the full conversation history. Stick-to-bottom by default (new content auto-scrolls), user can scroll up to review, scrolling back to bottom re-enables auto-scroll.
466+
467+Message types and their rendering:
468+
469+- **User messages**: prefixed with a role indicator and displayed as plain text.
470+- **Assistant messages**: streamed markdown rendered via cel-tui's `Markdown` component. Thinking/reasoning content is collapsible (hidden by default, toggled with `/reasoning`).
471+- **Tool calls — shell**: show the command, then stdout/stderr. Output is truncated in the UI (head + tail) with a visual marker. Full output viewable with `/verbose`.
472+- **Tool calls — edit**: show the file path and a brief summary (e.g., "edited 3 lines in `src/agent.ts`"). No full diff in the log.
473+- **Tool calls — plugin tools**: prefixed with plugin/tool name.
474+- **Errors**: one-line summary, styled distinctly.
475+
476+While the agent is working, an inline spinner with an activity label ("thinking", "running shell", "editing") appears at the end of the log.
477+
478+### Input area
479+
480+Multi-line text input. Intrinsic height (1 line when empty, grows with content) up to `maxHeight: 10`, then scrolls internally. cel-tui's `TextInput` with `submitKey: "enter"` (Enter submits, Shift+Enter adds newlines).
481+
482+The `>` prompt glyph is styled to indicate state:
483+
484+- Ready for input (normal)
485+- Agent is working (dimmed/different color, input is not focused)
486+
487+Supports:
488+
489+- `Tab` for file path autocomplete.
490+- `/command` prefix for slash commands.
491+- `/skill:skill-name` prefix to inject a skill's body into the user message. The `/skill:name` prefix is stripped from the input and the skill's `SKILL.md` body is prepended to the user message content. The rest of the input becomes the user's instruction. Example: `/skill:code-review check the auth module` sends the code-review skill body + "check the auth module" as the user message.
492+- Image embedding: if the entire input (after trimming) is a file path ending in `.png`, `.jpg`, `.jpeg`, `.gif`, or `.webp`, and the file exists, it is embedded as `ImageContent` in the user message (base64-encoded). Only when the current model supports image input (`Model.input` includes `"image"`). If the model doesn't support images, or the file doesn't exist, or the input contains other text, the path is sent as plain text. This is intentionally simple — no inline detection within sentenc …
493+
494+### Key bindings
495+
496+| Key | Context | Action |
497+| ------------- | ------------- | ------------------------------------------------- |
498+| `Enter` | Input focused | Submit message |
499+| `Shift+Enter` | Input focused | Insert newline |
500+| `Escape` | Agent working | Interrupt current turn, preserve partial response |
501+| `Escape` | Input focused | Unfocus input |
502+| `Tab` | Input focused | File path autocomplete |
503+| `Ctrl+C` | Any | Graceful exit |
504+| `Ctrl+D` | Input empty | Graceful exit (EOF) |
505+| `Ctrl+Z` | Any | Suspend/background process |
506+| Mouse wheel | Log area | Scroll conversation history |
507+
508+### Commands
509+
510+| Command | Description |
511+| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
512+| `/model` | Interactive model selector (provider + model + effort). Switching models mid-session is allowed — pi-ai's context is model-agnostic. The `readImage` tool is re-evaluated (added/removed based on the new model's capabilities). The status bar updates immediately. The session record's `model` field is not updated (it reflects the initial choice). |
513+| `/session` | Interactive session manager (list, resume, delete). Sessions scoped to CWD. |
514+| `/new` | Start a new session. Clears conversation, resets cost/token counters. |
515+| `/fork` | Fork the current conversation into a new session. Copies the full message history, continues from here independently. The original session is preserved. |
516+| `/undo` | Remove the last turn from conversation history (the user message and all assistant/tool messages that followed). Context-only — does not revert filesystem changes. |
517+| `/reasoning` | Toggle display of model thinking/reasoning content in the log. |
518+| `/verbose` | Toggle full output display (disables truncation in the UI). |
519+| `/help` | List available commands, loaded AGENTS.md files, discovered skills, and active plugins. |
520+
521+Commands are discoverable via `/` + Tab autocomplete in the input area.
522+
523+### Startup
524+
525+On launch, mini-coder:
526+
527+1. Discovers providers (env vars, OAuth tokens).
528+2. Loads AGENTS.md files, skills, plugins.
529+3. Starts a new session.
530+4. Renders the UI with an empty conversation log and the status bar populated.
531+
532+No banner or splash screen. The status bar already shows all the context the user needs.
533+
534+## Session persistence
535+
536+Single SQLite file at `~/.config/mini-coder/mini-coder.db` via `bun:sqlite`.
537+
538+### Schema
539+
540+```sql
541+CREATE TABLE sessions (
542+ id TEXT PRIMARY KEY, -- nanoid or uuid
543+ cwd TEXT NOT NULL, -- working directory, indexed
544+ model TEXT, -- provider/model at creation
545+ effort TEXT, -- thinking effort level
546+ forked_from TEXT, -- session id this was forked from, nullable
547+ created_at INTEGER NOT NULL, -- unix ms
548+ updated_at INTEGER NOT NULL -- unix ms, updated on each new message
549+);
550+
551+CREATE INDEX idx_sessions_cwd ON sessions(cwd);
552+
553+CREATE TABLE messages (
554+ id INTEGER PRIMARY KEY AUTOINCREMENT,
Cut short: this commit's diff is over 1000 lines.