xonecas.io
64875
Mc

mini-coder / commit da86847

feat: clean rewrite — add spec.md, reset repo for v2

Remove all v1 source code, docs, and build scripts.
Add spec.md as the single source of truth for the rewrite.
Reset AGENTS.md, README.md, TODO.md, package.json, and tsconfig.json.
Minimal src/index.ts placeholder. Clean dependency slate.

Key decisions in the spec:
- pi-ai for LLM providers, cel-tui for terminal UI
- Tools: shell, edit, readImage
- Plugin interface for MCP and extensions
- agentskills.io + AGENTS.md community standards
- SQLite session persistence via bun:sqlite
- Model-agnostic system prompt informed by Codex and Claude guides

xonecas2026-04-04 da86847e54a829aba36ccab3f1f33febfb7ce99e parent 616484b

155 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.

.npmignore+7−20
@@ -1,23 +1,10 @@
1-# Source & tests
21 src/
3-scripts/
4-
5-# Config & tooling
2+spec.md
3+AGENTS.md
4+TODO.md
5+.agents/
66 biome.json
7+lefthook.yml
78 tsconfig.json
8-*.db
9-*.db-shm
10-*.db-wal
11-.env
12-.env.*
13-.DS_Store
14-
15-# Dev/repo files
16-.agents/
17-assets/
18-TODO.md
19-SHARE.md
20-mini-coder-idea.md
21-AGENTS.md
22-bun.lock
23-node_modules/
9+.prettierignore
10+.codex
AGENTS.md+4−18
@@ -1,20 +1,6 @@
1-# Mini Coder repo for agents:
1+# Mini Coder — Agent Instructions
22
3-- App data folder is in `~/.config/mini-coder/`. It includes sqlite db file and logs.
4-- README.md is cosmetic for users, don't edit unless asked to.
5-- `docs/KNOWN_ISSUES.md` tracks known issues. `docs/mini-coder.1.md` is the man page.
6-- Create or reuse the `TODO.md` file to track your progress in long tasks. Remove completed items, keep it clean, concise, and up to date at all times. Track it in git.
7-- Write minimal tests, focused on our code's logic. Never test dependencies. Never use mocks or stubs.
8-- Keep the repo pristine: no failing tests, no lint, no build issues, no `ignore`-style comments. No failing hooks.
9-- Verify your changes, you can use the shell tool and `tmux` to test as needed.
10-- **tmux send-keys rules**: always use `-l` for text (`tmux send-keys -t s -l 'text'`), then send `Enter` separately without `-l` (`tmux send-keys -t s Enter`). Without `-l`, words like `Enter`, `Escape`, `Tab`, `Space` are interpreted as key presses.
11-- Use `bun run format` to fix formatting issues.
12-- We care about performance.
13-- Do not inline `import` calls. Don't duplicate code. Don't leave dead code behind.
14-- Don't re-implement helpers/functionality that already exists, always consolidate.
15-- Don't add complexity for backwards compatibility, it's preferable to break compatibility and keep the code simple.
16-- Don't make random test files, if you need to test something, write a proper unit test.
17-- If you make temp files, clean them up when you are done.
18-- Before committing, run `git status` and ensure every modified and untracked file produced during the session is included. Do not leave files behind.
3+- **Spec-driven development**: `spec.md` is the single source of truth for design and behavior. Read it before making changes. Do not deviate from the spec without discussion.
4+- **TDD**: write tests first, then implement. Tests validate the spec's defined behaviors.
195 - Use Conventional Commits formatting for commit messages.
20-- Before committing code changes, review the diff with the user and get approval for the commit. Treat direct user requests to commit or to do repository tasks as approval.
6+- Before committing code changes, review the diff with the user and get approval for the commit.
README.md+19−66
@@ -1,80 +1,33 @@
1-<p align="center">
2- <img src="assets/icon-5-community-badge.svg" alt="mini-coder logo" width="100" height="100"/>
3-</p>
1+# mini-coder
42
5-# 👾 mini-coder
3+A CLI coding agent. Small, fast, focused.
64
7-> _Small. Fast. Gets out of your way._
5+## What is it?
86
9-[📖 Read the Full Manual](docs/mini-coder.1.md)
7+mini-coder (`mc`) is a terminal-based coding agent that reads your codebase, makes changes, and verifies them — all through natural conversation. It runs in your terminal, connects to your preferred LLM provider, and gets work done.
108
11-A terminal coding agent for developers who want a sharp tool, not a bloated IDE plugin. Shell-first, multi-provider, minimal tool surface. Just you, your terminal, and an AI that keeps up.
9+## Features
1210
13-<p align="center">
14- <img src="./assets/preview.gif" alt="Minicoder Preview"/>
15-</p>
11+- **Two core tools**: `shell` and `edit` — inspect, mutate, verify.
12+- **Multi-provider**: Anthropic, OpenAI, Google, and many more via [pi-ai](https://github.com/badlogic/pi-mono/tree/main/packages/ai).
13+- **Rich TUI**: Streamed markdown, scrollable conversation log, status bar — powered by [cel-tui](https://github.com/sacenox/cel-tui).
14+- **Sessions**: Persistent conversation history, fork, undo.
15+- **Community standards**: [AGENTS.md](https://agents.md) and [Agent Skills](https://agentskills.io) support.
16+- **Plugins**: Extend with custom tools, MCP servers, and more.
1617
17----
18-
19-## ⚡ Quick Start
20-
21-I run on [Bun](https://bun.com) — install me via bun or npm, but Bun needs to be on your machine.
18+## Install
2219
2320 ```bash
24-# Install
25-bun add -g mini-coder # or: npm install -g mini-coder
26-
27-# Set one API key (pick any)
28-export OPENCODE_API_KEY=your-key # recommended
29-export ANTHROPIC_API_KEY=your-key # direct Anthropic
30-export OPENAI_API_KEY=your-key # direct OpenAI
31-export GOOGLE_API_KEY=your-key # direct Gemini (or GEMINI_API_KEY)
21+# coming soon
22+bun install -g mini-coder
23+```
3224
33-# Optional
34-export OLLAMA_BASE_URL=http://localhost:11434 # local models
35-export EXA_API_KEY=your-key # web search tools
25+## Usage
3626
37-# Go
27+```bash
3828 mc
3929 ```
4030
41-One-shot mode: `mc "refactor auth to use async/await"` — runs once, then exits.
42-
43-Useful flags: `-c` continue last session, `-r <id>` resume, `-l` list sessions, `-m <model>` pick a model, `-h` help.
44-
45----
46-
47-## 🔑 OAuth Login
48-
49-Use `/login` inside the REPL to authenticate via browser-based OAuth. Currently supported: `openai` (`/login openai` uses the Codex / ChatGPT Plus/Pro flow). No need to manage API keys manually.
50-
51----
52-
53-## 🛠️ Features
54-
55-- **Multi-provider** — supports Anthropic, OpenAI (direct + OAuth), Gemini, and Ollama
56-- **Session memory** — SQLite-backed. Resume with `-c` or `-r <id>`
57-- **Shell integration** — `!` prefix for inline commands, `@` to reference files with tab completion
58-- **Web search** — `webSearch` + `webContent` tools when `EXA_API_KEY` is set
59-- **MCP support** — connect external tool servers over HTTP or stdio
60-- **Skills** — `.agents/skills/<name>/SKILL.md`, invoke with `/skill-name` in the prompt
61-- **`mc-edit`** — safe, exact-text file editing (no full-file rewrites)
62-- **16 ANSI colors** — inherits your terminal theme. Always looks right.
63-
64----
65-
66-## 📚 Getting Deeper
67-
68-The README is the highlight reel. For the full story — slash commands, config folders, context files, app data, and everything else:
69-
70-**[📖 Read the Full Manual](docs/mini-coder.1.md)**
71-
72----
73-
74-## 🔮 Tech Stack
75-
76-[Bun.js](https://bun.com) · [AI SDK](https://ai-sdk.dev) · [yoctocolors](https://github.com/sindresorhus/yoctocolors)
77-
78-## 📄 License
31+## License
7932
80-MIT — [github.com/sacenox/mini-coder](https://github.com/sacenox/mini-coder)
33+MIT
SHARE.md+0−21
@@ -1,21 +0,0 @@
1-# 👾 mini-coder — small, fast CLI coding agent
2-
3-> A terminal-native AI coding agent that stays out of your way.
4-
5-```bash
6-bun add -g mini-coder
7-# or: npm install -g mini-coder
8-mc
9-```
10-
11-- **Multi-provider** — Anthropic, OpenAI, Google, Ollama, auto-detected from env vars
12-- **Session memory** — local SQLite, resume with `mc -c`
13-- **Shell integration** — `!command` inline, `@file` references with tab completion
14-- **Built-in web search** — enable Exa-backed `webSearch`/`webContent` with `EXA_API_KEY`
15-- **MCP support** — connect external tools and servers
16-- **Shell-first editing** — inspect with shell, make targeted edits with `mc-edit`, verify with shell
17-- **16 ANSI colors** — inherits your terminal theme, always
18-
19-No telemetry. No cloud accounts. No bloat.
20-
21-🔗 https://github.com/sacenox/mini-coder
TODO.md+0−17
@@ -1,17 +0,0 @@
1-# mini-coder TODO
2-
3-Before anything else, read mini-coder-spec.md first.
4-
5-We want to start working on the migration from the current mvp code to the state described in the spec. This is a major refactor and we should treat existing code as reference only, and focus on implementing the spec accurately by re-writting it correctly from scratch.
6-
7-We need to take this systematically:
8-
9-1. Remove the existing tests, all of them.
10-2. Remove all extra features that are not in the spec from the mvp code in src.
11-3. Create the packages file tree and packages bootstrap. Ensure the monorepo is well configured with scripts and pre-commit hook like we have today. Code freeze the src directory.
12-4. Start re-writting each package using the mvp src folder as reference, but focus on the spec as the source of truth. Do not mix the existing mvp features with the intended design in the spec. Use test driven development. First make the test based on the intended behaviour from the spec, then implement the new code. Do not import from the mvp code in src from the new packages, this is an intended clean re-write.
13-5. Loop step 4 until completion.
14-
15-During this task, act as the orchestrator of subagents, and coordinate them to complete the whole refactor. Avoid making edits and changes yourself to keep your context usage at a minimum since it's a long task.
16-
17-** TRACK YOUR PROGRESS BELLOW; DO NOT EDIT ABOVE THIS LINE **
docs/KNOWN_ISSUES.md+0−22
@@ -1,22 +0,0 @@
1-# KNOWN ISSUES
2-
3-## Bugs
4-
5-- AI SDK expands `claude-3-5-haiku` → dated variant that Zen doesn't serve (404).
6-- Shell tool output truncation only stops reading stdout/stderr; it does not terminate the underlying process yet. Commands that emit a lot of output and then keep running can still block until they exit or hit timeout.
7-- Cancel watcher cleanup starts before model resolution but is only torn down later in the turn flow. If model resolution fails first, interactive terminal/input state may be left inconsistent.
8-- MCP runtime state is not reconciled live: removing a server only deletes its DB row, and re-adding/updating can leave stale or duplicate live MCP tools until `/new` or a session switch reconnects everything.
9-- Switching or resuming a session does not update the active working directory. Shell passthrough, file refs, prompt context, and status UI keep using the process startup `cwd`, so a session from another repo can run against the wrong project.
10-- SQLite schema version mismatches rotate the existing DB aside and start from a fresh empty DB instead of migrating or warning clearly. Upgrades can make session history, MCP config, OAuth state, and cached model info appear lost unless the user manually recovers the backup.
11-- Persist `/model` changes to the session row immediately so resume/switch sees the new model even before another turn completes.
12-- Stop trimming submitted prompt text in interactive and piped flows; preserve leading indentation and trailing newlines while keeping blank-input detection.
13-- Rebuild/reset activated skill state on `/undo` and resume so `readSkill` matches actual remaining session history.
14-- Align OpenAI OAuth callback binding and redirect host so `localhost`/IPv6 resolution cannot miss the local callback server.
15-- Fix Windows browser launch for `/login` by using a real cross-platform opener or `cmd /c start`.
16-- Parse `/mcp add ... stdio ...` arguments with shell-style quoting so paths and args with spaces work.
17-
18-## Features
19-
20-- Conversation summary on max context instead of just an error with `/new` suggestion.
21-
22-## Refactors
docs/design-decisions.md+0−31
@@ -1,31 +0,0 @@
1-# Design Decisions
2-
3-Documenting why mini-coder makes certain architectural choices — especially where we intentionally diverge from common patterns.
4-
5-## Why no tool-call permissions?
6-
7-**Decision:** No approval prompts, no blacklists, no whitelists. Every tool call executes immediately.
8-
9-Our inspirations (Claude Code, OpenCode) require user approval for tool calls — shell commands, file writes, etc. We intentionally skip this.
10-
11-### Permission systems provide a false sense of security
12-
13-- **Shell bypasses everything.** An LLM with shell access can `curl`, `eval`, pipe through `bash`, encode payloads, or chain commands in ways no static blacklist can anticipate. Any permission scheme that allows shell but blocks specific patterns is playing whack-a-mole.
14-- **Blacklists and whitelists always have gaps.** Block `rm -rf /`? The model uses `find -delete`. Block `git push --force`? It uses `git push origin +main`. The surface area is unbounded.
15-- **Approval fatigue degrades security.** After the 20th "Allow shell command?" prompt, users auto-approve everything. The permission system trains the user to click "yes" reflexively — the opposite of its intent.
16-
17-### Permissions are cumbersome
18-
19-A coding agent runs dozens of shell commands per task. Requiring approval for each one destroys the flow that makes a CLI agent useful. The whole point of mini-coder is: small, fast, stays out of the way.
20-
21-### Isolation is a separate concern
22-
23-Sandboxing is a real need, but it belongs at the OS/container level — not inside the agent. Tools like [Anthropic Sandbox Runtime (`srt`)](https://github.com/anthropic-experimental/sandbox-runtime) and [nono](https://nono.sh/) provide proper filesystem and network isolation that the LLM cannot circumvent. This is defense in depth done right: the agent runs unrestricted inside a sandbox that enforces actual boundaries.
24-
25-### Our approach
26-
27-- The system prompt includes safety rules (no secrets, confirm destructive actions, no unauthorized reverts).
28-- The user can interrupt at any time with ESC (preserve context) or Ctrl+C (hard exit).
29-- For real isolation, run mini-coder inside a sandboxed environment.
30-
31-**Summary:** Permission dialogs give the appearance of safety without the substance. Real security comes from sandboxing the environment, not gatekeeping individual tool calls. Mini-coder codes — isolating it is a job for the right tool.
docs/mini-coder.1.md+0−1
@@ -1 +0,0 @@
1-TODO: Make a markdown based man page here once the mini-coder-spec.md is fully implemented.
mini-coder-spec.md+0−108
@@ -1,108 +0,0 @@
1-## Core idea: treat this as the source of truth for the design and implementation.
2-
3-mini-coder - `mc`
4-
5-An augmented shell-prompt coding agent: small, fast, and out of the way.
6-
7-### Inspirations
8-
9-- Pi agent: https://github.com/badlogic/pi-mono/tree/main/packages/coding-agent
10-- Claude Code: https://claude.com/product/claude-code
11-- Codex: https://github.com/openai/codex
12-- Opencode: https://opencode.ai/
13-
14-### Philosophy
15-
16-**Performance first, style second.**
17-
18-Core features must be correct and fast before adding new ones.
19-Community-oriented: support `AGENTS.md` and `agentskills.io` specs, and do not introduce new config formats.
20-
21-### Features
22-
23-- Auto-discover and load community config standards on startup:
24- - `AGENTS.md` -> https://agents.md/
25- - Skills -> https://agentskills.io/client-implementation/adding-skills-support
26-
27-- Auto-discovery of providers via env vars (example: `OPENCODE_API_KEY`) or local servers (example: Ollama).
28- - `/login` shows OAuth login status. `/login <provider>` starts browser-based OAuth login. `/logout <provider>` clears saved tokens. support OpenAI (`openai` uses the Codex / ChatGPT Plus/Pro flow) and Anthropic (Claude Max/Pro). Use Pi coding agent source code as a reference for this.
29- - `/model` picks a model from connected providers. The selection persists across sessions and uses an interactive selector.
30- - `/effort [args]` sets the model effort.
31-
32-- Connect to MCP servers over Streamable HTTP / SSE fallback or stdio.
33- - Auto-discover keys like `EXA_AI_API_KEY` to auto-connect to their MCP server.
34- - `/mcp` lists, adds, and removes MCP servers. Servers are stored in SQLite.
35-
36-- Session management and commands to create, resume, and list sessions using a local SQLite file.
37- - `/session` interactively manages sessions. Sessions are scoped to the CWD to avoid cross-project session pollution.
38- - `/new` starts a new session with an empty message history, clears the screen, and redraws the banner.
39- - `/fork` forks the conversation into a new session.
40- - `/undo` removes the last turn from history (does not restore filesystem).
41- - Sessions should also track errors and logs in a separate table from messages, mostly for debugging purposes, and should not affect the user session.
42-
43-- Enriched user prompt:
44- - Rich line editing, history, and paste support. Enter submits; Shift+Enter adds new lines.
45- - Reference skills from the working directory and global configs with `/skill:...` in the prompt input, plus interactive autocomplete for skills to include in the prompt.
46- - Press `Esc` at any point during an assistant response to interrupt it. The partial response is preserved in history with an interrupt stub appended (so the LLM retains context), and the user is returned to the prompt. `Ctrl+C` and `Ctrl+D` (EOF) gracefully exit. `Ctrl+Z` suspends/backgrounds the process and returns the user to the shell prompt.
47- - Reference files with `@`, which embeds a file path into the prompt and autocompletes interactively. It also supports adding images to the prompt if the referenced file is an image.
48- - On error, display a one-line summary to the user, and return to the input prompt.
49-
50-- Context handling:
51- - Stop with a conversation summary at max context. This must not break prompt caching.
52- - No max steps or tool call limits — user can interrupt.
53- - Clear, accurate token and cost tracking. Use `models.dev` as the source for model metadata and costs.
54-
55-- Minimal tool surface: `shell`, `edit`, `listSkills`, `readSkill`.
56- - Inspect with `shell` -> mutate with `edit` -> verify with `shell`.
57- - Auto-truncate large shell outputs for the LLM to avoid context explosions.
58- - `edit`: exact-text edits only, deterministic failures on stale/ambiguous state. Based on industry standard edit/apply patch tools.
59- - A single system prompt that works across all supported models (no provider-specific branches). It is constructed based on our inspirations and provider resources such as:
60- - https://developers.openai.com/cookbook/examples/gpt-5/codex_prompting_guide
61- - https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices
62-
63-- Other commands in the CLI prompt:
64- - `/reasoning` toggles display of model reasoning output.
65- - `/verbose` toggles output truncation. When off, large outputs keep the start/end sections and truncate the middle. This is a UI-only visibility concern.
66-
67-- Internal skill (hidden from the user) that teaches the agent how to use minicoder and help the user configure it and use it well. Should be compliant with the agentskills.io specification.
68-
69-- App data folder in `~/.config/mini-coder/` in linux, or the respective app data folder in other OS. It includes sqlite db file and logs.
70-
71-### UI/Output
72-
73-- Use the 16 ANSI colors so coloring is always inherited from the terminal theme (https://jvns.ca/blog/2024/10/01/terminal-colours/). Keep a `theme.json` file in the app data directory with the palette used so users can customize colors, italics, bold, and glyphs.
74-- Never use ambiguous-width characters; stick with single-width Unicode characters for maximum cross-terminal compatibility.
75-- Minimal banner at app start showing loaded context files, skills, connected providers, and configured MCP servers.
76-- Scrolling conversation log (new output pushes the input prompt down):
77- - Skill tools: one-line name + description, no body content.
78- - Shell tool: the command, then its stdout/stderr.
79- - Edit tool: a clean diff of the change applied.
80- - MCP tools: prefixed with server name to distinguish from built-in tools.
81-- Status bar below the input prompt showing model, model effort, provider, session ID, git branch, context usage %, and concise token and cost counts.
82-- Clear boundary around the user input area. The area expands as new lines are added.
83-- Inline spinner with an activity label (e.g. "thinking", "running shell") when a turn is in flight for all actions and while waiting for the LLM to complete its work. It must not interfere with scrollback or leave artifacts on interrupt.
84-
85-### Tech stack
86-
87-- Bun.js for runtime and package management. https://bun.com/docs
88-- Multiprovider support via Pi's: https://github.com/badlogic/pi-mono/tree/main/packages/ai (it saves us a lot of headaches by already having oauth baked in.)
89-- MCP via the official SDK: `@modelcontextprotocol/sdk`
90-- Colored output with https://github.com/sindresorhus/yoctocolors - limited but fast.
91-- Our own helper packages: `@yoctomarkdown` for streamed Markdown rendering and `@yoctoselect` for a simple, fully featured interactive selector.
92-- sqlite for sql storage
93-
94-### Repo structure
95-
96-We want to break everything down into workspaces as internal packages. This will force us to have clear boundaries for each package and improve maintainability.
97-
98-Suggested core packages:
99-
100-- `terminal-ui`: the UI implementation and all output concerns, isolated from the rest of the project so we can more easily support other output formats going forward.
101-- `agent`: the agent implementation, which is the core of the project.
102-- `providers`: the unified provider implementation/sdk usage.
103-- `storage`: implements the storage interface using SQLite for persistence.
104-- `types`: shared types.
105-
106-### Extensibility (NOT IN SCOPE! DO NOT IMPLEMENT)
107-
108-Users should be able to extend mini-coder easily with a plugin format. This should enable custom commands, providers, context handling, etc. While this is currently out of scope and not fully defined, it should be kept in mind during development so we avoid unnecessary complexity when we do add it.
package.json+5−29
@@ -1,52 +1,28 @@
11 {
22 "name": "mini-coder",
3- "version": "0.4.1",
3+ "version": "0.5.0",
44 "description": "A small, fast CLI coding agent",
55 "module": "src/index.ts",
66 "type": "module",
77 "bin": {
8- "mc": "dist/mc.js",
9- "mc-edit": "dist/mc-edit.js"
8+ "mc": "dist/mc.js"
109 },
1110 "scripts": {
1211 "prepare": "lefthook install",
13- "build": "bun run scripts/build.ts",
1412 "dev": "bun run src/index.ts",
1513 "format": "prettier --write --log-level warn .",
16- "check": "bun run prettier -c . && bun run typecheck && bun run lint && bun run knip && bun run jscpd && bun run test",
14+ "check": "bun run prettier -c . && bun run typecheck && bun run lint",
1715 "typecheck": "tsc --noEmit",
1816 "lint": "biome check src",
19- "knip": "knip",
20- "test": "bun test --only-failures",
21- "test:verbose": "bun test",
22- "jscpd": "jscpd -s src"
23- },
24- "dependencies": {
25- "@ai-sdk/anthropic": "^3.0.60",
26- "@ai-sdk/google": "^3.0.51",
27- "@ai-sdk/openai": "^3.0.45",
28- "@ai-sdk/openai-compatible": "^2.0.36",
29- "@modelcontextprotocol/sdk": "^1.27.1",
30- "ai": "^6.0.127",
31- "diff": "^8.0.3",
32- "yoctocolors": "^2.1.2",
33- "yoctomarkdown": "^0.0.7",
34- "yoctoselect": "0.0.3",
35- "zod": "^4.3.6"
17+ "test": "bun test"
3618 },
19+ "dependencies": {},
3720 "devDependencies": {
3821 "@biomejs/biome": "^2.4.6",
3922 "@types/bun": "latest",
40- "jscpd": "^4.0.8",
41- "knip": "^5.86.0",
4223 "lefthook": "^2.1.4",
4324 "prettier": "^3.8.1",
4425 "typescript": "^5.9.3"
4526 },
46- "knip": {
47- "entry": [
48- "src/mc-edit.ts"
49- ]
50- },
5127 "license": "MIT"
5228 }
scripts/build.ts+0−24
@@ -1,24 +0,0 @@
1-import pkg from "../package.json";
2-
3-async function buildEntrypoint(entrypoint: string, outputName: string) {
4- const result = await Bun.build({
5- entrypoints: [entrypoint],
6- target: "bun",
7- outdir: "dist",
8- naming: outputName,
9- packages: "external",
10- define: {
11- __PACKAGE_VERSION__: JSON.stringify(pkg.version),
12- },
13- });
14-
15- if (!result.success) {
16- for (const log of result.logs) {
17- console.error(log);
18- }
19- process.exit(1);
20- }
21-}
22-
23-await buildEntrypoint("src/index.ts", "mc.js");
24-await buildEntrypoint("src/mc-edit.ts", "mc-edit.js");
spec.md+586−0
@@ -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.
src/agent/agent-helpers.ts+0−57
Cut short: this commit's diff is over 1000 lines.
src/agent/agent.test.ts+0−210
Cut short: this commit's diff is over 1000 lines.
src/agent/agent.ts+0−143
Cut short: this commit's diff is over 1000 lines.
src/agent/context-files.test.ts+0−47
Cut short: this commit's diff is over 1000 lines.
src/agent/context-files.ts+0−112
Cut short: this commit's diff is over 1000 lines.
src/agent/reporter.ts+0−40
Cut short: this commit's diff is over 1000 lines.
src/agent/run-with-teardown.test.ts+0−93
Cut short: this commit's diff is over 1000 lines.
src/agent/run-with-teardown.ts+0−36
Cut short: this commit's diff is over 1000 lines.
src/agent/session-runner.test.ts+0−176
Cut short: this commit's diff is over 1000 lines.
src/agent/session-runner.ts+0−279
Cut short: this commit's diff is over 1000 lines.
src/agent/system-prompt.ts+0−96
Cut short: this commit's diff is over 1000 lines.
src/agent/tools.test.ts+0−54
Cut short: this commit's diff is over 1000 lines.
src/agent/tools.ts+0−43
Cut short: this commit's diff is over 1000 lines.
src/agent/undo-turn.ts+0−32
Cut short: this commit's diff is over 1000 lines.
src/cli/args.ts+0−103
Cut short: this commit's diff is over 1000 lines.
src/cli/commands-help.test.ts+0−22
Cut short: this commit's diff is over 1000 lines.
src/cli/commands-help.ts+0−68
Cut short: this commit's diff is over 1000 lines.
src/cli/commands-login.ts+0−139
Cut short: this commit's diff is over 1000 lines.
src/cli/commands-mcp.ts+0−112
Cut short: this commit's diff is over 1000 lines.
src/cli/commands-model.ts+0−182
Cut short: this commit's diff is over 1000 lines.
src/cli/commands-session.ts+0−62
Cut short: this commit's diff is over 1000 lines.
src/cli/commands.ts+0−248
Cut short: this commit's diff is over 1000 lines.
src/cli/completions.test.ts+0−71
Cut short: this commit's diff is over 1000 lines.
src/cli/completions.ts+0−128
Cut short: this commit's diff is over 1000 lines.
src/cli/error-parse.test.ts+0−200
Cut short: this commit's diff is over 1000 lines.
src/cli/error-parse.ts+0−143
Cut short: this commit's diff is over 1000 lines.
src/cli/file-refs.test.ts+0−40
Cut short: this commit's diff is over 1000 lines.
src/cli/file-refs.ts+0−46
Cut short: this commit's diff is over 1000 lines.
src/cli/frontmatter.test.ts+0−97
Cut short: this commit's diff is over 1000 lines.
src/cli/frontmatter.ts+0−149
Cut short: this commit's diff is over 1000 lines.
src/cli/image-types.test.ts+0−55
Cut short: this commit's diff is over 1000 lines.
src/cli/image-types.ts+0−53
Cut short: this commit's diff is over 1000 lines.
src/cli/input-buffer.ts+0−101
Cut short: this commit's diff is over 1000 lines.
src/cli/input-completion.ts+0−46
Cut short: this commit's diff is over 1000 lines.
src/cli/input-control.ts+0−17
Cut short: this commit's diff is over 1000 lines.
src/cli/input-editing.test.ts+0−35
Cut short: this commit's diff is over 1000 lines.
src/cli/input-editing.ts+0−35
Cut short: this commit's diff is over 1000 lines.
src/cli/input-images.test.ts+0−49
Cut short: this commit's diff is over 1000 lines.
src/cli/input-images.ts+0−38
Cut short: this commit's diff is over 1000 lines.
src/cli/input-loop.ts+0−138
Cut short: this commit's diff is over 1000 lines.
src/cli/input.test.ts+0−141
Cut short: this commit's diff is over 1000 lines.
src/cli/input.ts+0−572
Cut short: this commit's diff is over 1000 lines.
src/cli/output.test.ts+0−46
Cut short: this commit's diff is over 1000 lines.
src/cli/output.ts+0−216
Cut short: this commit's diff is over 1000 lines.
src/cli/reasoning.ts+0−32
Cut short: this commit's diff is over 1000 lines.
src/cli/skills.test.ts+0−324
Cut short: this commit's diff is over 1000 lines.
src/cli/skills.ts+0−362
Cut short: this commit's diff is over 1000 lines.
src/cli/spinner.test.ts+0−42
Cut short: this commit's diff is over 1000 lines.
src/cli/spinner.ts+0−40
Cut short: this commit's diff is over 1000 lines.
src/cli/status-bar.test.ts+0−93
Cut short: this commit's diff is over 1000 lines.
src/cli/status-bar.ts+0−92
Cut short: this commit's diff is over 1000 lines.
src/cli/stdin-prompt.test.ts+0−41
Cut short: this commit's diff is over 1000 lines.
src/cli/stdin-prompt.ts+0−33
Cut short: this commit's diff is over 1000 lines.
src/cli/stream-render.test.ts+0−434
Cut short: this commit's diff is over 1000 lines.
src/cli/stream-render.ts+0−331
Cut short: this commit's diff is over 1000 lines.
src/cli/structured-output.test.ts+0−51
Cut short: this commit's diff is over 1000 lines.
src/cli/structured-output.ts+0−120
Cut short: this commit's diff is over 1000 lines.
src/cli/terminal-io.test.ts+0−37
Cut short: this commit's diff is over 1000 lines.
src/cli/terminal-io.ts+0−115
Cut short: this commit's diff is over 1000 lines.
src/cli/test-helpers.ts+0−72
Cut short: this commit's diff is over 1000 lines.
src/cli/tool-render.test.ts+0−231
Cut short: this commit's diff is over 1000 lines.
src/cli/tool-render.ts+0−178
Cut short: this commit's diff is over 1000 lines.
src/cli/tool-result-renderers.ts+0−368
Cut short: this commit's diff is over 1000 lines.
src/cli/types.ts+0−20
Cut short: this commit's diff is over 1000 lines.
src/index.ts+2−182
Cut short: this commit's diff is over 1000 lines.
src/internal/ansi.ts+0−10
Cut short: this commit's diff is over 1000 lines.
src/internal/file-edit/cli.test.ts+0−123
Cut short: this commit's diff is over 1000 lines.
src/internal/file-edit/cli.ts+0−144
Cut short: this commit's diff is over 1000 lines.
src/internal/file-edit/command.test.ts+0−48
Cut short: this commit's diff is over 1000 lines.
src/internal/file-edit/command.ts+0−75
Cut short: this commit's diff is over 1000 lines.
src/internal/file-edit/exact-text.test.ts+0−106
Cut short: this commit's diff is over 1000 lines.
src/internal/file-edit/exact-text.ts+0−109
Cut short: this commit's diff is over 1000 lines.
src/internal/file-edit/path.ts+0−38
Cut short: this commit's diff is over 1000 lines.
src/internal/text.test.ts+0−24
Cut short: this commit's diff is over 1000 lines.
src/internal/text.ts+0−6
Cut short: this commit's diff is over 1000 lines.
src/internal/version.ts+0−9
Cut short: this commit's diff is over 1000 lines.
src/llm-api/error-utils.test.ts+0−30
Cut short: this commit's diff is over 1000 lines.
src/llm-api/error-utils.ts+0−48
Cut short: this commit's diff is over 1000 lines.
src/llm-api/history-transforms.ts+0−13
Cut short: this commit's diff is over 1000 lines.
src/llm-api/history/gemini.ts+0−140
Cut short: this commit's diff is over 1000 lines.
src/llm-api/history/openai.ts+0−159
Cut short: this commit's diff is over 1000 lines.
src/llm-api/history/reasoning.ts+0−13
Cut short: this commit's diff is over 1000 lines.
src/llm-api/history/shared.ts+0−106
Cut short: this commit's diff is over 1000 lines.
src/llm-api/model-info-cache.ts+0−225
Cut short: this commit's diff is over 1000 lines.
src/llm-api/model-info-fetch.ts+0−280
Cut short: this commit's diff is over 1000 lines.
src/llm-api/model-info-normalize.ts+0−150
Cut short: this commit's diff is over 1000 lines.
src/llm-api/model-info.test.ts+0−329
Cut short: this commit's diff is over 1000 lines.
src/llm-api/model-info.ts+0−359
Cut short: this commit's diff is over 1000 lines.
src/llm-api/model-routing.test.ts+0−66
Cut short: this commit's diff is over 1000 lines.
src/llm-api/model-routing.ts+0−72
Cut short: this commit's diff is over 1000 lines.
src/llm-api/provider-discovery.test.ts+0−81
Cut short: this commit's diff is over 1000 lines.
src/llm-api/provider-discovery.ts+0−139
Cut short: this commit's diff is over 1000 lines.
src/llm-api/provider-options.ts+0−150
Cut short: this commit's diff is over 1000 lines.
src/llm-api/providers-resolve.test.ts+0−104
Cut short: this commit's diff is over 1000 lines.
src/llm-api/providers.test.ts+0−83
Cut short: this commit's diff is over 1000 lines.
src/llm-api/providers.ts+0−287
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn-context.ts+0−387
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn-execution.test.ts+0−263
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn-execution.ts+0−418
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn-prepare-messages.test.ts+0−98
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn-prepare-messages.ts+0−116
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn-provider-options.ts+0−57
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn-request.test.ts+0−224
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn-request.ts+0−141
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn-stream-events.test.ts+0−158
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn-stream-events.ts+0−107
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn.test.ts+0−1141
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn.ts+0−155
Cut short: this commit's diff is over 1000 lines.
src/llm-api/types.ts+0−97
Cut short: this commit's diff is over 1000 lines.
src/logging/context.ts+0−42
Cut short: this commit's diff is over 1000 lines.
src/mc-edit.ts+0−5
Cut short: this commit's diff is over 1000 lines.
src/mcp/client-registry.test.ts+0−44
Cut short: this commit's diff is over 1000 lines.
src/mcp/client-registry.ts+0−17
Cut short: this commit's diff is over 1000 lines.
src/mcp/client.ts+0−109
Cut short: this commit's diff is over 1000 lines.
src/mcp/tool-sync.test.ts+0−83
Cut short: this commit's diff is over 1000 lines.
src/mcp/tool-sync.ts+0−42
Cut short: this commit's diff is over 1000 lines.
src/session/db/connection.test.ts+0−115
Cut short: this commit's diff is over 1000 lines.
src/session/db/connection.ts+0−223
Cut short: this commit's diff is over 1000 lines.
src/session/db/index.ts+0−7
Cut short: this commit's diff is over 1000 lines.
src/session/db/logs-repo.ts+0−103
Cut short: this commit's diff is over 1000 lines.
src/session/db/mcp-repo.ts+0−45
Cut short: this commit's diff is over 1000 lines.
src/session/db/message-repo.test.ts+0−67
Cut short: this commit's diff is over 1000 lines.
src/session/db/message-repo.ts+0−128
Cut short: this commit's diff is over 1000 lines.
src/session/db/model-info-repo.ts+0−125
Cut short: this commit's diff is over 1000 lines.
src/session/db/session-repo.ts+0−69
Cut short: this commit's diff is over 1000 lines.
src/session/db/settings-repo.test.ts+0−20
Cut short: this commit's diff is over 1000 lines.
src/session/db/settings-repo.ts+0−75
Cut short: this commit's diff is over 1000 lines.
src/session/manager.ts+0−88
Cut short: this commit's diff is over 1000 lines.
src/session/oauth/auth-storage.test.ts+0−21
Cut short: this commit's diff is over 1000 lines.
src/session/oauth/auth-storage.ts+0−132
Cut short: this commit's diff is over 1000 lines.
src/session/oauth/openai.test.ts+0−29
Cut short: this commit's diff is over 1000 lines.
src/session/oauth/openai.ts+0−207
Cut short: this commit's diff is over 1000 lines.
src/session/oauth/pkce.test.ts+0−26
Cut short: this commit's diff is over 1000 lines.
src/session/oauth/pkce.ts+0−22
Cut short: this commit's diff is over 1000 lines.
src/session/oauth/types.ts+0−18
Cut short: this commit's diff is over 1000 lines.
src/session/resume-command.test.ts+0−25
Cut short: this commit's diff is over 1000 lines.
src/session/resume-command.ts+0−16
Cut short: this commit's diff is over 1000 lines.
src/tools/exa.ts+0−70
Cut short: this commit's diff is over 1000 lines.
src/tools/shell.test.ts+0−62
Cut short: this commit's diff is over 1000 lines.
src/tools/shell.ts+0−197
Cut short: this commit's diff is over 1000 lines.
src/tools/skills.test.ts+0−64
Cut short: this commit's diff is over 1000 lines.
src/tools/skills.ts+0−84
Cut short: this commit's diff is over 1000 lines.
tsconfig.json+1−6
Cut short: this commit's diff is over 1000 lines.