xonecas.io
64875
Mc

mini-coder / commit 646e27a

Resolve merge conflicts

xonecas2026-03-09 646e27a76db6f6ab8d5fa38d0ccc659c73601fce parent 8bf2c8cparent c0a0cf6

57 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

AGENTS.md+2−2
@@ -5,9 +5,9 @@
55 - README.md is cosmetic for users, don't edit unless asked to.
66 - Write minimal tests, focused on our code's logic. Never test dependencies. Never use mock servers or stubs.
77 - Keep the repo pristine: no failing tests, no lint, no build issues, no `nolint:` comments.
8-- Use `bun run typecheck && bun run format && bun run lint && bun test` to check your changes.
8+- Use `bun run jscpd && bun run knip && bun run typecheck && bun run format && bun run lint && bun test` to check your changes.
99 - We care about performance.
1010 - Don't worry about formatting issues, formatting happens automatically on mutations. (see .agents/hooks)
1111 - Do not inline `import` calls. Don't duplicate code. Don't leave dead code behind.
1212 - Don't make random test files, if you need to test something, write a propper unit test.
13-- If you make temp files, clean them up when you are done.
13+- If you make temp files, clean them up when you are done.
README.md+82−46
@@ -4,7 +4,7 @@
44
55 # 👾 mini-coder
66
7-> *Small. Fast. Gets out of your way.*
7+> _Small. Fast. Gets out of your way._
88
99 Hey there! I'm **mini-coder** — a CLI coding agent built for developers who want a sharp tool, not a bloated IDE plugin. Think of me as the pocket knife of AI coding assistants: lightweight, reliable, and always ready.
1010
@@ -31,41 +31,44 @@ $ mc
3131
3232 ## 🛠️ What Can I Do?
3333
34-I come equipped with a tight, reliable set of tools:
34+My toolkit is lean on purpose — every tool earns its spot, no passengers:
3535
36-| Tool | What it does |
37-|---|---|
38-| 🔍 `glob` | Find files by pattern across your project |
39-| 🧲 `grep` | Search file contents with regex |
40-| 📖 `read` | Read files (with line-range support) |
41-| 📝 `create` | Create a new file or fully overwrite an existing file |
42-| ✏️ `replace` | Replace or delete lines using hashline anchors |
43-| ➕ `insert` | Insert lines before/after an anchor without replacing |
44-| 🐚 `shell` | Run shell commands and see their output |
45-| 🤖 `subagent` | Spawn a focused mini-me for parallel subtasks |
36+| Tool | What it does |
37+| --------------- | ----------------------------------------------------------- |
38+| 🔍 `glob` | Find files by pattern across your project |
39+| 🧲 `grep` | Search file contents with regex |
40+| 📖 `read` | Read files (with line-range support) |
41+| 📝 `create` | Create a new file or fully overwrite an existing file |
42+| ✏️ `replace` | Replace or delete lines using hashline anchors |
43+| ➕ `insert` | Insert lines before/after an anchor without replacing |
44+| 🐚 `shell` | Run shell commands and see their output |
45+| 🤖 `subagent` | Spawn a focused mini-me for parallel subtasks |
46+| 🌐 `webSearch` | Search the web when `EXA_API_KEY` is set |
47+| 📄 `webContent` | Fetch full page content from URLs when `EXA_API_KEY` is set |
4648
47-I can also connect to **MCP servers** (like Exa for web search), giving you superpowers on demand.
49+Need more firepower? I connect to **MCP servers** over HTTP or stdio — bolt on external tools whenever the job calls for it.
4850
4951 ---
5052
5153 ## ⚡ Key Features
5254
53-- **Multi-provider** — set `OPENCODE_API_KEY` for Zen, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GOOGLE_API_KEY`, or just run Ollama locally. I auto-discover whatever's available.
55+- **Multi-provider** — set `OPENCODE_API_KEY` for Zen, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GOOGLE_API_KEY` or `GEMINI_API_KEY`, or just run Ollama locally (`OLLAMA_BASE_URL` optional). I auto-discover whatever's available.
56+- **Built-in web search** — set `EXA_API_KEY` and I expose `webSearch` + `webContent` tools.
5457 - **Session memory** — conversations are saved in a local SQLite database. Resume where you left off with `-c` or pick a specific session with `-r <id>`.
5558 - **Shell integration** — prefix with `!` to run shell commands inline. Use `@` to reference files in your prompt (with Tab completion).
56-- **Slash commands** — `/model` to switch models, `/plan` for read-only thinking mode, `/ralph` for autonomous looping, `/review` for a code review, `/undo` to roll back a turn, `/new` for a clean session, `/mcp` to manage MCP servers. See all with `/help`.
57-- **Custom commands** — drop a `.md` file in `.agents/commands/` and it becomes a `/command`. Supports argument placeholders (`$ARGUMENTS`, `$1`…`$9`) and shell interpolation (`` !`cmd` ``). Global commands live in `~/.agents/commands/`. Custom commands take precedence over built-ins. → [docs/custom-commands.md](docs/custom-commands.md)
59+- **Slash commands** — `/model` or `/models` to list/switch models, `/model effort <low|medium|high|xhigh|off>` for reasoning effort, `/plan` for read-only thinking mode, `/ralph` for autonomous looping, `/review` for a code review, `/undo` to roll back a turn, `/new` for a clean session, `/mcp list|add|remove` to manage MCP servers, and `/exit` (`/quit`, `/q`) to leave. See all with `/help`.
60+- **Custom commands** — drop a `.md` file in `.agents/commands/` and it becomes a `/command`. Claude-compatible `.claude/commands/` works too. Supports argument placeholders (`$ARGUMENTS`, `$1`…`$9`) and shell interpolation (`` !`cmd` ``). Global commands live in `~/.agents/commands/` and `~/.claude/commands/`. Custom commands take precedence over built-ins. → [docs/custom-commands.md](docs/custom-commands.md)
5861 - **Custom agents** — drop a `.md` file in `.agents/agents/` (or `~/.agents/agents/` globally) and reference it with `@agent-name` in your prompt. The agent runs in its own context window with a custom system prompt and optional model override. → [docs/custom-agents.md](docs/custom-agents.md)
59-- **Skills** — place a `SKILL.md` in `.agents/skills/<name>/` and inject it into any prompt with `@skill-name`. Skills are *never* auto-loaded — always explicit. → [docs/skills.md](docs/skills.md)
60-- **Post-tool hooks** — drop an executable at `.agents/hooks/post-<tool>` and I'll run it after every matching tool call.
62+- **Skills** — place a `SKILL.md` in `.agents/skills/<name>/` and inject it into any prompt with `@skill-name`. Claude-compatible `.claude/skills/<name>/SKILL.md` works too. Skills are _never_ auto-loaded — always explicit. → [docs/skills.md](docs/skills.md)
63+- **Post-tool hooks** — drop an executable at `.agents/hooks/post-<tool>` (or `~/.agents/hooks/post-<tool>` globally) and I'll run it after matching built-in tool calls. → [docs/tool-hooks.md](docs/tool-hooks.md)
6164 - **Beautiful, minimal output** — diffs for edits, formatted trees for file searches, a live status bar with model, git branch, and token counts.
62-- **16 ANSI colors only** — my output inherits *your* terminal theme. Dark mode, light mode, Solarized, Gruvbox — I fit right in.
65+- **16 ANSI colors only** — my output inherits _your_ terminal theme. Dark mode, light mode, Solarized, Gruvbox — I fit right in.
6366
6467 ---
6568
6669 ## 🧠 Interesting Things About Me
6770
68-- **I eat my own dog food.** I was built *by* a mini-coder agent. It's agents all the way down. 🐢
71+- **I eat my own dog food.** I was built _by_ a mini-coder agent. It's agents all the way down. 🐢
6972 - **I'm tiny but mighty.** The whole runtime is [Bun.js](https://bun.com) — fast startup, native TypeScript, and a built-in SQLite driver.
7073 - **I respect existing conventions.** Hook scripts live in `.agents/hooks/`, context in `AGENTS.md` or `CLAUDE.md`, commands in `.agents/commands/`, agents in `.agents/agents/`, skills in `.agents/skills/` — I follow the ecosystem instead of inventing new standards.
7174 - **I spin while I think.** ⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ (It's the little things.)
@@ -73,40 +76,51 @@ I can also connect to **MCP servers** (like Exa for web search), giving you supe
7376
7477 ---
7578
76-## 📁 The `.agents` folder
79+## 📁 Config folders
7780
78-mini-coder follows the [`.agents` convention](https://github.com/agentsmd/agents) used across the AI coding tool ecosystem. Drop files in `.agents/` to extend behaviour for the current repo, or `~/.agents/` to apply them globally.
81+I follow the [`.agents` convention](https://github.com/agentsmd/agents) — the shared standard across AI coding tools — and I also speak Claude Code's `.claude` format for **commands** and **skills**. Best of both worlds.
7982
80-| Path | What it does |
81-|---|---|
82-| `.agents/commands/*.md` | Custom slash commands (`/name`) |
83-| `.agents/agents/*.md` | Custom agents (`@name`) |
84-| `.agents/skills/<name>/SKILL.md` | Reusable skill instructions (`@name`) |
85-| `.agents/hooks/post-<tool>` | Scripts run after a tool call |
86-| `AGENTS.md` | Project context injected into every system prompt |
83+| Path | What it does |
84+| -------------------------------- | ------------------------------------------------- |
85+| `.agents/commands/*.md` | Custom slash commands (`/name`) |
86+| `.claude/commands/*.md` | Claude-compatible custom commands |
87+| `.agents/agents/*.md` | Custom agents (`@name`) |
88+| `.agents/skills/<name>/SKILL.md` | Reusable skill instructions (`@name`) |
89+| `.claude/skills/<name>/SKILL.md` | Claude-compatible skills |
90+| `.agents/hooks/post-<tool>` | Scripts run after supported built-in tool calls |
91+| `AGENTS.md` | Project context injected into every system prompt |
92+| `CLAUDE.md` | Fallback project context if `AGENTS.md` is absent |
93+| `~/.config/mini-coder/AGENTS.md` | Global fallback context |
8794
88-Local always overrides global. The same `~/.agents/` folder is shared with Claude Code, Opencode, and other compatible tools — skills and agents you write once work everywhere.
95+The pecking order is straightforward: local beats global, and `.agents` beats `.claude` at the same scope. Worth noting: custom agents are mini-coder-only — `.claude` compatibility is for commands and skills only. → [docs/configs.md](docs/configs.md)
8996
9097 ---
9198
92-
9399 ## 🚀 Getting Started
94100
101+One thing before you dive in: **I run on Bun**. You can install me via npm just fine, but [Bun](https://bun.com) still needs to be on your machine — no way around it.
102+
95103 ```bash
96-# Install from npm
104+# Install globally
97105 bun add -g mini-coder
98106 # or: npm install -g mini-coder
99107
100-# Set your provider key (pick one — or run Ollama locally)
108+# Set a provider key (pick one — or run Ollama locally)
101109 export OPENCODE_API_KEY=your-zen-key # recommended
102-export ANTHROPIC_API_KEY=your-key # or direct Anthropic
103-export OPENAI_API_KEY=your-key # or direct OpenAI
110+export ANTHROPIC_API_KEY=your-key # direct Anthropic
111+export OPENAI_API_KEY=your-key # direct OpenAI
112+export GOOGLE_API_KEY=your-key # direct Gemini
113+# or: export GEMINI_API_KEY=your-key
114+
115+# Optional extras
116+export OLLAMA_BASE_URL=http://localhost:11434
117+export EXA_API_KEY=your-exa-key # enables webSearch/webContent
104118
105-# Launch!
119+# Launch
106120 mc
107121 ```
108122
109-Or run directly for a quick task:
123+Or drop me a prompt straight away and stay in the session:
110124
111125 ```bash
112126 mc "Refactor the auth module to use async/await"
@@ -115,14 +129,37 @@ mc "Refactor the auth module to use async/await"
115129 Useful flags:
116130
117131 ```bash
118-mc -c # continue last session
119-mc -r <id> # resume a specific session
120-mc -l # list recent sessions
121-mc -m zen/claude-sonnet-4-6 # pick a model
132+mc -c # continue last session
133+mc -r <id> # resume a specific session
134+mc -l # list recent sessions
135+mc -m zen/claude-sonnet-4-6 # pick a model
136+mc --cwd ~/src/other-project # set working directory
137+mc -h # show help
122138 ```
123139
124140 ---
125141
142+## 🗃️ App data
143+
144+Everything I remember lives in `~/.config/mini-coder/` — here's what I'm holding onto:
145+
146+- `sessions.db` — your full session history, `/undo` snapshots, MCP server config, and model metadata, all in one tidy SQLite file
147+- `api.log` — a request/response log for every provider call this run, if you want to peek under the hood
148+- `errors.log` — anything that went sideways, caught and written down so you can actually debug it
149+- `AGENTS.md` — your global context fallback, quietly injected whenever a repo doesn't bring its own `AGENTS.md` or `CLAUDE.md`
150+
151+---
152+
153+## 📚 Go Deeper
154+
155+The README hits the highlights — the docs have the full story:
156+
157+- [docs/custom-commands.md](docs/custom-commands.md)
158+- [docs/custom-agents.md](docs/custom-agents.md)
159+- [docs/skills.md](docs/skills.md)
160+- [docs/configs.md](docs/configs.md)
161+- [docs/tool-hooks.md](docs/tool-hooks.md)
162+
126163 ## 🗂️ Project Structure
127164
128165 ```
@@ -132,7 +169,7 @@ src/
132169 cli/ # Input, output, slash commands, markdown rendering
133170 llm-api/ # Provider factory + streaming turn logic
134171 tools/ # glob, grep, read, create, replace, insert, shell, subagent
135- # + hashline anchors, diffs, hooks, snapshots
172+ # + webSearch, webContent, hashline anchors, diffs, hooks, snapshots
136173 mcp/ # MCP server connections
137174 session/ # SQLite-backed session & history management
138175 ```
@@ -154,16 +191,15 @@ src/
154191
155192 > Accurate. Fast. Focused on the conversation.
156193
157-I believe the best tools disappear into your workflow. I don't want to be the star of the show — I want *you* to ship great code, faster.
194+I believe the best tools disappear into your workflow. I don't want to be the star of the show — I want _you_ to ship great code, faster.
158195
159196 ---
160197
161198 ## 💬 What People Are Saying
162199
163200 > "sean this is fucking sick"
164-> — [vpr99](https://github.com/vpr99) (eric)
201+> — [vpr99](https://github.com/vpr99)
165202
166203 ---
167204
168-
169-*Built with ❤️ and a healthy obsession with terminal aesthetics.*
205+_Built with ❤️ and a healthy obsession with terminal aesthetics._
TODO.md+0−8
@@ -1,13 +1,5 @@
11 # TODO
22
3----
4-
5-## Subagents id/number/lane could be made more robust
6-
7-- Currently we use an incremental integer for this, but in a long session with several conversations (user uses /new) it can become confusing (seeing subagent number 16 after /new). Let's think of a better way to id subagents and their lanes/worktrees. Maybe with a UUID?
8-
9----
10-
113 ## Write blog posts
124
135 - Codex being big dumb and lazy without strong guidance in system prompt/instructions
biome.json+6−7
@@ -1,7 +1,9 @@
11 {
2- "$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
3- "organizeImports": {
4- "enabled": true
2+ "$schema": "https://biomejs.dev/schemas/2.4.6/schema.json",
3+ "vcs": {
4+ "enabled": true,
5+ "clientKind": "git",
6+ "useIgnoreFile": true
57 },
68 "formatter": {
79 "enabled": true
@@ -21,7 +23,7 @@
2123 "suspicious": {
2224 "noDebugger": "error",
2325 "noExplicitAny": "error",
24- "noConsoleLog": "error"
26+ "noConsole": "error"
2527 },
2628 "correctness": {
2729 "noUnusedVariables": "error",
@@ -32,8 +34,5 @@
3234 },
3335 "javascript": {
3436 "globals": ["Bun", "Timer"]
35- },
36- "files": {
37- "ignore": ["node_modules", "dist"]
3837 }
3938 }
docs/chatgpt-subscription-auth.md+68−0
@@ -0,0 +1,68 @@
1+# ChatGPT/Codex subscription auth notes
2+
3+mini-coder does **not** currently support logging in with a ChatGPT Plus/Pro/Codex subscription.
4+
5+## Why
6+
7+We looked at two implementations:
8+
9+- OpenCode in `/tmp/opencode-src`
10+- official Codex in `/tmp/openai-codex/codex-rs`
11+
12+Both rely on OpenAI **first-party/private** auth and backend APIs rather than a documented public developer API.
13+
14+## What those implementations do
15+
16+### Auth
17+
18+They use OAuth-like flows against `https://auth.openai.com`, including:
19+
20+- browser login with PKCE and a localhost callback server
21+- device-code / headless login
22+- refresh tokens via `POST /oauth/token`
23+
24+Both also rely on a hardcoded first-party client id embedded in their source trees.
25+
26+Examples:
27+
28+- official Codex: `/tmp/openai-codex/codex-rs/core/src/auth.rs`
29+- OpenCode: `/tmp/opencode-src/packages/opencode/src/plugin/codex.ts`
30+
31+### Runtime API
32+
33+After login, requests are sent to ChatGPT backend endpoints such as:
34+
35+- `https://chatgpt.com/backend-api/codex`
36+- `https://chatgpt.com/backend-api/codex/responses`
37+
38+with headers like:
39+
40+- `Authorization: Bearer <oauth access token>`
41+- `ChatGPT-Account-Id: <account id>`
42+
43+Examples:
44+
45+- official Codex: `/tmp/openai-codex/codex-rs/core/src/model_provider_info.rs`
46+- official Codex headers: `/tmp/openai-codex/codex-rs/backend-client/src/client.rs`
47+- OpenCode rewrite layer: `/tmp/opencode-src/packages/opencode/src/plugin/codex.ts`
48+
49+## Why mini-coder is not adopting this
50+
51+- It depends on undocumented/private auth endpoints.
52+- It depends on a hardcoded first-party client id.
53+- It depends on private ChatGPT backend routes.
54+- Browser login would require running a local callback server.
55+- Even the official Codex source does not expose a clean public API-based alternative here.
56+
57+## Future stance
58+
59+We may revisit support if OpenAI exposes a stable, documented path for:
60+
61+- ChatGPT subscription login for third-party tools, or
62+- a public Codex/ChatGPT backend API intended for external clients
63+
64+Until then, mini-coder only supports providers with clearer public integration paths.
65+
66+## Note
67+
68+If you want a supported hosted integration instead of ChatGPT subscription auth, mini-coder already supports OpenCode Zen via `OPENCODE_API_KEY`. See the existing `zen/<model>` provider path.
package.json+15−11
@@ -1,6 +1,6 @@
11 {
22 "name": "mini-coder",
3- "version": "0.0.14",
3+ "version": "0.0.15",
44 "description": "A small, fast CLI coding agent",
55 "module": "src/index.ts",
66 "type": "module",
@@ -13,23 +13,27 @@
1313 "typecheck": "tsc --noEmit",
1414 "lint": "biome check src",
1515 "format": "biome format --write src",
16- "test": "bun test"
16+ "knip": "knip",
17+ "test": "bun test",
18+ "jscpd": "jscpd src"
1719 },
1820 "dependencies": {
19- "@ai-sdk/anthropic": "^3.0.46",
20- "@ai-sdk/google": "^3.0.30",
21- "@ai-sdk/openai": "^3.0.30",
22- "@ai-sdk/openai-compatible": "^2.0.30",
23- "@modelcontextprotocol/sdk": "^1.26.0",
24- "ai": "^6.0.94",
21+ "@ai-sdk/anthropic": "^3.0.58",
22+ "@ai-sdk/google": "^3.0.43",
23+ "@ai-sdk/openai": "^3.0.41",
24+ "@ai-sdk/openai-compatible": "^2.0.35",
25+ "@modelcontextprotocol/sdk": "^1.27.1",
26+ "ai": "^6.0.116",
2527 "ignore": "^7.0.5",
26- "yoctocolors": "^2.1.1",
28+ "yoctocolors": "^2.1.2",
2729 "zod": "^4.3.6"
2830 },
2931 "devDependencies": {
30- "@biomejs/biome": "^1.9.4",
32+ "@biomejs/biome": "^2.4.6",
3133 "@types/bun": "latest",
32- "typescript": "^5.8.3"
34+ "jscpd": "^4.0.8",
35+ "knip": "^5.86.0",
36+ "typescript": "^5.9.3"
3337 },
3438 "license": "MIT"
3539 }
src/agent/agent.ts+6−10
@@ -2,27 +2,23 @@ import * as c from "yoctocolors";
22 import { loadAgents } from "../cli/agents.ts";
33 import type { CommandContext } from "../cli/commands.ts";
44 import { tildePath } from "../cli/output.ts";
5-import type { AgentReporter } from "./reporter.ts";
6-
7-import { type ThinkingEffort, getContextWindow } from "../llm-api/providers.ts";
5+import { getContextWindow, type ThinkingEffort } from "../llm-api/providers.ts";
86 import type { ToolDef } from "../llm-api/types.ts";
97 import { connectMcpServer } from "../mcp/client.ts";
10-
118 import {
129 listMcpServers,
1310 setPreferredModel,
1411 setPreferredThinkingEffort,
1512 } from "../session/db/index.ts";
16-import { createSubagentRunner } from "./subagent-runner.ts";
17-import { buildToolSet } from "./tools.ts";
18-import { undoLastTurn } from "./undo-snapshot.ts";
19-
2013 import { getGitBranch } from "./agent-helpers.ts";
21-
2214 import { runInputLoop } from "./input-loop.ts";
15+import type { AgentReporter } from "./reporter.ts";
2316 import { SessionRunner } from "./session-runner.ts";
17+import { createSubagentRunner } from "./subagent-runner.ts";
18+import { buildToolSet } from "./tools.ts";
19+import { undoLastTurn } from "./undo-snapshot.ts";
2420
25-export interface AgentOptions {
21+interface AgentOptions {
2622 model: string;
2723 cwd: string;
2824 initialThinkingEffort: ThinkingEffort | null;
src/agent/input-loop.ts+3−2
@@ -1,6 +1,6 @@
11 import * as c from "yoctocolors";
22 import { type CommandContext, handleCommand } from "../cli/commands.ts";
3-import { readline, type InputResult } from "../cli/input.ts";
3+import { type InputResult, readline } from "../cli/input.ts";
44 import { PREFIX } from "../cli/output.ts";
55 import type { CoreMessage } from "../llm-api/turn.ts";
66 import { saveMessages } from "../session/db/index.ts";
@@ -8,7 +8,7 @@ import { hasRalphSignal, runShellPassthrough } from "./agent-helpers.ts";
88 import type { AgentReporter } from "./reporter.ts";
99 import type { SessionRunner } from "./session-runner.ts";
1010
11-export interface InputLoopOptions {
11+interface InputLoopOptions {
1212 cwd: string;
1313 reporter: AgentReporter;
1414 cmdCtx: CommandContext;
@@ -64,6 +64,7 @@ export async function runInputLoop(opts: InputLoopOptions): Promise<void> {
6464 runner.session.messages.push(msg);
6565 saveMessages(runner.session.id, [msg], thisTurn);
6666 runner.coreHistory.push(msg);
67+ runner.snapshotStack.push(null);
6768 }
6869 continue;
6970 }
src/agent/reporter.ts+3−3
@@ -23,10 +23,10 @@ export interface StatusBarData {
2323 }
2424
2525 export interface SubagentEventData {
26- laneId: number;
26+ laneId: string;
2727 parentLabel?: string;
28- worktreeBranch?: string;
29- activeLanes: Set<number>;
28+ hasWorktree?: boolean;
29+ activeLanes: Set<string>;
3030 }
3131
3232 export interface AgentReporter {
src/agent/session-runner.ts+2−2
@@ -1,8 +1,8 @@
11 import * as c from "yoctocolors";
22 import type { ImageAttachment } from "../cli/image-types.ts";
33 import { watchForCancel } from "../cli/input.ts";
4-import { resolveModel } from "../llm-api/providers.ts";
54 import type { ThinkingEffort } from "../llm-api/providers.ts";
5+import { resolveModel } from "../llm-api/providers.ts";
66 import type { CoreMessage } from "../llm-api/turn.ts";
77 import { runTurn } from "../llm-api/turn.ts";
88 import type { ToolDef } from "../llm-api/types.ts";
@@ -27,7 +27,7 @@ import type { AgentReporter } from "./reporter.ts";
2727 import { buildSystemPrompt } from "./system-prompt.ts";
2828 import { buildReadOnlyToolSet } from "./tools.ts";
2929
30-export interface SessionRunnerOptions {
30+interface SessionRunnerOptions {
3131 cwd: string;
3232 reporter: AgentReporter;
3333 tools: ToolDef[];
src/agent/subagent-runner.ts+9−12
@@ -2,15 +2,16 @@ import { tmpdir } from "node:os";
22 import { join } from "node:path";
33 import { loadAgents } from "../cli/agents.ts";
44 import { formatSubagentLabel } from "../cli/output.ts";
5+import type { ThinkingEffort } from "../llm-api/providers.ts";
56 import { resolveModel } from "../llm-api/providers.ts";
67 import { type CoreMessage, runTurn } from "../llm-api/turn.ts";
78 import type { SubagentOutput } from "../tools/subagent.ts";
89 import {
9- MergeInProgressError,
1010 cleanupBranch,
1111 createWorktree,
1212 initializeWorktree,
1313 isGitRepo,
14+ MergeInProgressError,
1415 mergeWorktree,
1516 removeWorktree,
1617 syncDirtyStateToWorktree,
@@ -19,15 +20,12 @@ import type { AgentReporter } from "./reporter.ts";
1920 import { buildSystemPrompt } from "./system-prompt.ts";
2021 import { buildToolSet } from "./tools.ts";
2122
22-import type { ThinkingEffort } from "../llm-api/providers.ts";
23-
24-function makeWorktreeBranch(laneId: number): string {
25- return `mc-sub-${laneId}-${Date.now()}`;
23+function makeWorktreeBranch(laneId: string): string {
24+ return `mc-sub-${laneId}`;
2625 }
2726
28-function makeWorktreePath(laneId: number): string {
29- const suffix = crypto.randomUUID().replace(/-/g, "").slice(0, 10);
30- return join(tmpdir(), `mc-wt-${laneId}-${suffix}`);
27+function makeWorktreePath(laneId: string): string {
28+ return join(tmpdir(), `mc-wt-${laneId}`);
3129 }
3230
3331 export function createSubagentRunner(
@@ -36,8 +34,7 @@ export function createSubagentRunner(
3634 getCurrentModel: () => string,
3735 getThinkingEffort: () => ThinkingEffort | null,
3836 ) {
39- let nextLaneId = 1;
40- const activeLanes = new Set<number>();
37+ const activeLanes = new Set<string>();
4138 const worktreesEnabledPromise = isGitRepo(cwd);
4239
4340 let mergeLock: Promise<void> = Promise.resolve();
@@ -57,7 +54,7 @@ export function createSubagentRunner(
5754 modelOverride?: string,
5855 parentLabel?: string,
5956 ): Promise<SubagentOutput> => {
60- const laneId = nextLaneId++;
57+ const laneId = crypto.randomUUID().split("-")[0] as string;
6158 activeLanes.add(laneId);
6259
6360 let subagentCwd = cwd;
@@ -124,7 +121,7 @@ export function createSubagentRunner(
124121 reporter.renderSubagentEvent(event, {
125122 laneId,
126123 ...(parentLabel ? { parentLabel } : {}),
127- ...(worktreeBranch ? { worktreeBranch } : {}),
124+ hasWorktree: !!worktreeBranch,
128125 activeLanes,
129126 });
130127 reporter.startSpinner("thinking");
src/agent/system-prompt.ts+1−1
@@ -31,7 +31,7 @@ const CODEX_AUTONOMY = `
3131 - Do NOT ask "shall I proceed?", "shall I start?", "reply X to continue", or any equivalent. Just start.
3232 - If something is ambiguous, pick the most reasonable interpretation, implement it, and note the assumption at the end.`;
3333
34-export function isCodexModel(modelString: string): boolean {
34+function isCodexModel(modelString: string): boolean {
3535 const { modelId } = parseModelString(modelString);
3636 return modelId.includes("codex");
3737 }
src/agent/tools.ts+7−8
@@ -1,13 +1,7 @@
11 import type { ToolDef } from "../llm-api/types.ts";
2-import { webContentTool, webSearchTool } from "../tools/exa.ts";
3-import {
4- type SubagentOutput,
5- createSubagentTool,
6- getSubagentMergeError,
7-} from "../tools/subagent.ts";
8-
92 import type { CreateOutput } from "../tools/create.ts";
103 import { createTool } from "../tools/create.ts";
4+import { webContentTool, webSearchTool } from "../tools/exa.ts";
115 import type { GlobOutput } from "../tools/glob.ts";
126 import { globTool } from "../tools/glob.ts";
137 import type { GrepOutput } from "../tools/grep.ts";
@@ -31,6 +25,11 @@ import type { ReplaceOutput } from "../tools/replace.ts";
3125 import { replaceTool } from "../tools/replace.ts";
3226 import type { ShellOutput } from "../tools/shell.ts";
3327 import { shellTool } from "../tools/shell.ts";
28+import {
29+ createSubagentTool,
30+ getSubagentMergeError,
31+ type SubagentOutput,
32+} from "../tools/subagent.ts";
3433
3534 // ─── Tool wrappers ────────────────────────────────────────────────────────────
3635
@@ -87,7 +86,7 @@ function withHooks<TInput extends { cwd?: string }, TOutput>(
8786
8887 // ─── Tool registry ────────────────────────────────────────────────────────────
8988
90-export const MAX_SUBAGENT_DEPTH = 3;
89+const MAX_SUBAGENT_DEPTH = 3;
9190
9291 // Names of all local tools that support hooks (MCP tools are excluded).
9392 const HOOKABLE_TOOLS = [
src/agent/undo-snapshot.ts+13−26
@@ -1,13 +1,13 @@
11 import type { CoreMessage } from "../llm-api/turn.ts";
2-import { deleteLastTurn } from "../session/db/index.ts";
2+import { deleteLastTurn, loadMessages } from "../session/db/index.ts";
33 import type { ActiveSession } from "../session/manager.ts";
44 import {
5- type SnapshotRestoreResult,
65 restoreSnapshot,
6+ type SnapshotRestoreResult,
77 } from "../tools/snapshot.ts";
88 import type { AgentReporter } from "./reporter.ts";
99
10-export interface UndoContext {
10+interface UndoContext {
1111 session: ActiveSession;
1212 coreHistory: CoreMessage[];
1313 snapshotStack: Array<number | null>;
@@ -24,34 +24,21 @@ export async function undoLastTurn(ctx: UndoContext): Promise<boolean> {
2424 // Nothing to undo if there are no messages
2525 if (session.messages.length === 0) return false;
2626
27- // Find the message index where the last turn starts (last user message)
28- let lastUserIdx = -1;
29- for (let i = session.messages.length - 1; i >= 0; i--) {
30- if (session.messages[i]?.role === "user") {
31- lastUserIdx = i;
32- break;
33- }
34- }
35- if (lastUserIdx === -1) return false;
36-
37- // Trim in-memory DB history
38- session.messages.splice(lastUserIdx);
39-
40- // Trim coreHistory to match — find last user message in coreHistory
41- let coreLastUserIdx = -1;
42- for (let i = coreHistory.length - 1; i >= 0; i--) {
43- if (coreHistory[i]?.role === "user") {
44- coreLastUserIdx = i;
45- break;
46- }
47- }
48- if (coreLastUserIdx !== -1) coreHistory.splice(coreLastUserIdx);
49-
5027 // Delete from DB and decrement turn counter
5128 const deleted = deleteLastTurn(session.id);
29+ if (!deleted) return false;
30+
5231 const poppedTurn = snapshotStack.pop() ?? null;
5332 if (turnIndex > 0) ctx.setTurnIndex(turnIndex - 1);
5433
34+ // Sync in-memory history reliably with DB state
35+ const remaining = loadMessages(session.id);
36+ session.messages.length = 0;
37+ session.messages.push(...remaining);
38+
39+ coreHistory.length = 0;
40+ coreHistory.push(...remaining);
41+
5542 // Restore files from the SQLite snapshot for the turn being undone
5643 if (poppedTurn !== null) {
5744 const restoreResult: SnapshotRestoreResult = await restoreSnapshot(
src/cli/agents.ts+1−1
@@ -2,7 +2,7 @@
22
33 import { loadMarkdownConfigs } from "./load-markdown-configs.ts";
44
5-export interface AgentConfig {
5+interface AgentConfig {
66 name: string;
77 description: string;
88 /** Override model for this agent (optional) */
src/cli/commands.ts+6−7
@@ -1,16 +1,15 @@
11 import * as c from "yoctocolors";
2-import { fetchAvailableModels } from "../llm-api/providers.ts";
32 import type { ThinkingEffort } from "../llm-api/providers.ts";
4-import {
5- type SubagentOutput,
6- getSubagentMergeError,
7-} from "../tools/subagent.ts";
8-
3+import { fetchAvailableModels } from "../llm-api/providers.ts";
94 import {
105 deleteMcpServer,
116 listMcpServers,
127 upsertMcpServer,
138 } from "../session/db/index.ts";
9+import {
10+ getSubagentMergeError,
11+ type SubagentOutput,
12+} from "../tools/subagent.ts";
1413 import { loadAgents } from "./agents.ts";
1514 import {
1615 type CustomCommand,
@@ -41,7 +40,7 @@ export interface CommandContext {
4140 cwd: string;
4241 }
4342
44-export type CommandResult =
43+type CommandResult =
4544 | { type: "handled" }
4645 | { type: "unknown"; command: string }
4746 | { type: "exit" }
src/cli/image-types.ts+1−1
@@ -1,6 +1,6 @@
11 // ─── Shared image type constants ──────────────────────────────────────────────
22
3-export const IMAGE_EXTENSIONS = new Set([
3+const IMAGE_EXTENSIONS = new Set([
44 "png",
55 "jpg",
66 "jpeg",
src/cli/input.ts+24−21
@@ -276,29 +276,33 @@ export function pasteLabel(text: string): string {
276276 return `[pasted: "${preview}"${more}]`;
277277 }
278278
279-export function renderInputBuffer(
279+function processInputBuffer(
280280 buf: string,
281281 pasteTokens: ReadonlyMap<string, string>,
282+ replacer: (ch: string, pasted: string | undefined) => string,
282283 ): string {
283284 let out = "";
284285 for (let i = 0; i < buf.length; i++) {
285286 const ch = buf[i] ?? "";
286- const pasted = pasteTokens.get(ch);
287- out += pasted ? pasteLabel(pasted) : ch;
287+ out += replacer(ch, pasteTokens.get(ch));
288288 }
289289 return out;
290290 }
291291
292+export function renderInputBuffer(
293+ buf: string,
294+ pasteTokens: ReadonlyMap<string, string>,
295+): string {
296+ return processInputBuffer(buf, pasteTokens, (ch, pasted) =>
297+ pasted ? pasteLabel(pasted) : ch,
298+ );
299+}
300+
292301 export function expandInputBuffer(
293302 buf: string,
294303 pasteTokens: ReadonlyMap<string, string>,
295304 ): string {
296- let out = "";
297- for (let i = 0; i < buf.length; i++) {
298- const ch = buf[i] ?? "";
299- out += pasteTokens.get(ch) ?? ch;
300- }
301- return out;
305+ return processInputBuffer(buf, pasteTokens, (ch, pasted) => pasted ?? ch);
302306 }
303307
304308 export function pruneInputPasteTokens(
@@ -389,6 +393,15 @@ export async function readline(opts: {
389393 cursor += text.length;
390394 }
391395
396+ function deleteWordBackward(): void {
397+ const end = cursor;
398+ while (cursor > 0 && buf[cursor - 1] === " ") cursor--;
399+ while (cursor > 0 && buf[cursor - 1] !== " ") cursor--;
400+ buf = buf.slice(0, cursor) + buf.slice(end);
401+ prunePasteTokens();
402+ renderPrompt();
403+ }
404+
392405 function insertPasteToken(text: string): void {
393406 const token = createPasteToken(buf, pasteTokens);
394407 pasteTokens.set(token, text);
@@ -557,12 +570,7 @@ export async function readline(opts: {
557570 }
558571 // Alt+Backspace (delete word backward): ESC DEL
559572 if (raw === `${ESC}${BACKSPACE}`) {
560- const end = cursor;
561- while (cursor > 0 && buf[cursor - 1] === " ") cursor--;
562- while (cursor > 0 && buf[cursor - 1] !== " ") cursor--;
563- buf = buf.slice(0, cursor) + buf.slice(end);
564- prunePasteTokens();
565- renderPrompt();
573+ deleteWordBackward();
566574 continue;
567575 }
568576 if (raw === ESC) {
@@ -596,12 +604,7 @@ export async function readline(opts: {
596604
597605 if (raw === CTRL_W) {
598606 // Delete word before cursor
599- const end = cursor;
600- while (cursor > 0 && buf[cursor - 1] === " ") cursor--;
601- while (cursor > 0 && buf[cursor - 1] !== " ") cursor--;
602- buf = buf.slice(0, cursor) + buf.slice(end);
603- prunePasteTokens();
604- renderPrompt();
607+ deleteWordBackward();
605608 continue;
606609 }
607610
src/cli/load-markdown-configs.ts+2−2
@@ -1,10 +1,10 @@
1-import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
1+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
22 import { homedir } from "node:os";
33 import { basename, join } from "node:path";
44 import { warnConventionConflicts } from "./config-conflicts.ts";
55 import { type Frontmatter, parseFrontmatter } from "./frontmatter.ts";
66
7-export interface MarkdownConfigLoaderOptions<T> {
7+interface MarkdownConfigLoaderOptions<T> {
88 type: "commands" | "skills" | "agents";
99 /** Strategy for file discovery: 'flat' reads dir/*.md, 'nested' reads dir/<name>/SKILL.md */
1010 strategy: "flat" | "nested";
src/cli/markdown.ts+0−22
@@ -139,25 +139,3 @@ export function renderMarkdown(text: string): string {
139139 })
140140 .join("\n");
141141 }
142-
143-/**
144- * Render a multi-line chunk of markdown given an initial fence state.
145- * Returns the ANSI-coloured output and the fence state after the last line.
146- * Use this for chunk-based streaming where each chunk is a complete paragraph
147- * or block (delimited by blank lines).
148- */
149-export function renderChunk(
150- text: string,
151- inFence: boolean,
152-): { output: string; inFence: boolean } {
153- let fence = inFence;
154- const output = text
155- .split("\n")
156- .map((raw) => {
157- const r = renderLine(raw, fence);
158- fence = r.inFence;
159- return r.output;
160- })
161- .join("\n");
162- return { output, inFence: fence };
163-}
src/cli/output-reporter.ts+1−1
@@ -7,7 +7,6 @@ import type {
77 } from "../agent/reporter.ts";
88 import type { TurnEvent } from "../llm-api/types.ts";
99 import {
10- Spinner,
1110 renderError,
1211 renderHook,
1312 renderInfo,
@@ -15,6 +14,7 @@ import {
1514 renderSubagentEvent,
1615 renderTurn,
1716 restoreTerminal,
17+ Spinner,
1818 writeln,
1919 } from "./output.ts";
2020
src/cli/output.ts+3−5
@@ -82,15 +82,13 @@ export function renderInfo(msg: string): void {
8282 writeln(`${G.info} ${c.dim(msg)}`);
8383 }
8484
85+export { renderError } from "./error-render.ts";
8586 // Re-exports
8687 export { Spinner } from "./spinner.ts";
88+export { renderStatusBar } from "./status-bar.ts";
8789 export { renderTurn } from "./stream-render.ts";
8890 export {
8991 formatSubagentLabel,
90- renderSubagentEvent,
91- renderToolResult,
92- renderToolCall,
9392 renderHook,
93+ renderSubagentEvent,
9494 } from "./tool-render.ts";
95-export { renderStatusBar } from "./status-bar.ts";
96-export { renderError } from "./error-render.ts";
src/cli/skills.ts+1−1
@@ -2,7 +2,7 @@
22
33 import { loadMarkdownConfigs } from "./load-markdown-configs.ts";
44
5-export interface Skill {
5+interface Skill {
66 name: string;
77 description: string;
88 /** Full content of the SKILL.md (frontmatter + body) */
src/cli/status-bar.ts+3−1
@@ -56,7 +56,9 @@ export function renderStatusBar(opts: {
5656 const right: string[] = [];
5757 if (opts.inputTokens > 0 || opts.outputTokens > 0) {
5858 right.push(
59- c.dim(`↑${fmtTokens(opts.inputTokens)} ↓${fmtTokens(opts.outputTokens)}`),
59+ c.dim(
60+ `↑ ${fmtTokens(opts.inputTokens)} ↓ ${fmtTokens(opts.outputTokens)}`,
61+ ),
6062 );
6163 }
6264 if (opts.contextTokens > 0) {
src/cli/terminal-io.ts+1−4
@@ -1,7 +1,4 @@
1-export type SignalHandler = () => void;
2-
3-export class TerminalIO {
4- private cleanupHandlers: Set<() => void> = new Set();
1+class TerminalIO {
52 private rawModeEnabled = false;
63 private interruptHandler: (() => void) | null = null;
74
src/cli/tool-render.ts+44−55
@@ -8,7 +8,7 @@ import { G, writeln } from "./output.ts";
88 const HOME = homedir();
99
1010 /** Strip the `linenum:hash| ` prefix that hashline-formatted tool outputs include. */
11-export function stripHashlinePrefix(text: string): string {
11+function stripHashlinePrefix(text: string): string {
1212 return text.replace(/^\d+:[0-9a-f]{2}\| /, "");
1313 }
1414
@@ -25,7 +25,7 @@ function commonPrefix(paths: string[]): string {
2525 return prefix;
2626 }
2727
28-export function toolGlyph(name: string): string {
28+function toolGlyph(name: string): string {
2929 if (name === "glob" || name === "grep") return G.search;
3030 if (name === "read") return G.read;
3131 if (name === "create" || name === "replace" || name === "insert")
@@ -36,7 +36,7 @@ export function toolGlyph(name: string): string {
3636 return G.info;
3737 }
3838
39-export function toolCallLine(name: string, args: unknown): string {
39+function toolCallLine(name: string, args: unknown): string {
4040 const a =
4141 args && typeof args === "object" ? (args as Record<string, unknown>) : {};
4242
@@ -112,7 +112,7 @@ export function renderHook(
112112 }
113113 }
114114
115-export function renderDiff(diff: string): void {
115+function renderDiff(diff: string): void {
116116 if (!diff || diff === "(no changes)") return;
117117 for (const line of diff.split("\n")) {
118118 if (line.startsWith("+++") || line.startsWith("---")) {
@@ -129,30 +129,45 @@ export function renderDiff(diff: string): void {
129129 }
130130 }
131131
132-export function renderToolResultInline(
132+function formatErrorBadge(result: unknown): string {
133+ const msg =
134+ typeof result === "string"
135+ ? result
136+ : result instanceof Error
137+ ? result.message
138+ : JSON.stringify(result);
139+ const oneLiner = msg.split("\n")[0] ?? msg;
140+ return `${G.err} ${c.red(oneLiner)}`;
141+}
142+
143+function formatShellBadge(r: {
144+ timedOut: boolean;
145+ success: boolean;
146+ exitCode: number;
147+}): string {
148+ return r.timedOut
149+ ? c.yellow("timeout")
150+ : r.success
151+ ? c.green(`✔ ${r.exitCode}`)
152+ : c.red(`✖ ${r.exitCode}`);
153+}
154+function renderToolResultInline(
133155 toolName: string,
134156 result: unknown,
135157 isError: boolean,
136158 indent: string,
137159 ): void {
138160 if (isError) {
139- const msg =
140- typeof result === "string"
141- ? result
142- : result instanceof Error
143- ? result.message
144- : JSON.stringify(result);
145- const oneLiner = msg.split("\n")[0] ?? msg;
146- writeln(`${indent}${G.err} ${c.red(oneLiner)}`);
161+ writeln(`${indent}${formatErrorBadge(result)}`);
147162 return;
148163 }
149164
150165 if (toolName === "glob") {
151- const r = result as { files?: string[]; truncated?: boolean };
152- if (Array.isArray(r?.files)) {
153- const n = r.files.length;
166+ const res = result as { files?: string[]; truncated?: boolean };
167+ if (Array.isArray(res?.files)) {
168+ const n = res.files.length;
154169 writeln(
155- `${indent}${G.info} ${c.dim(n === 0 ? "no matches" : `${n} file${n === 1 ? "" : "s"}${r.truncated ? " (capped)" : ""}`)}`,
170+ `${indent}${G.info} ${c.dim(n === 0 ? "no matches" : `${n} file${n === 1 ? "" : "s"}${res.truncated ? " (capped)" : ""}`)}`,
156171 );
157172 return;
158173 }
@@ -198,11 +213,7 @@ export function renderToolResultInline(
198213 success: boolean;
199214 timedOut: boolean;
200215 };
201- const badge = r.timedOut
202- ? c.yellow("timeout")
203- : r.success
204- ? c.green(`✔ ${r.exitCode}`)
205- : c.red(`✖ ${r.exitCode}`);
216+ const badge = formatShellBadge(r);
206217 writeln(`${indent}${badge}`);
207218 return;
208219 }
@@ -260,15 +271,7 @@ export function renderToolResult(
260271 isError: boolean,
261272 ): void {
262273 if (isError) {
Cut short: this commit's diff is over 1000 lines.
src/index.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/llm-api/model-info.test.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/llm-api/model-info.ts+54−68
Cut short: this commit's diff is over 1000 lines.
src/llm-api/providers.ts+1−18
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn.ts+3−6
Cut short: this commit's diff is over 1000 lines.
src/mcp/client.ts+2−2
Cut short: this commit's diff is over 1000 lines.
src/session/db/index.ts+3−3
Cut short: this commit's diff is over 1000 lines.
src/session/db/mcp-repo.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/session/db/model-info-repo.ts+0−9
Cut short: this commit's diff is over 1000 lines.
src/session/db/settings-repo.ts+2−2
Cut short: this commit's diff is over 1000 lines.
src/session/manager.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/tools/create.ts+3−7
Cut short: this commit's diff is over 1000 lines.
src/tools/exa.ts+33−50
Cut short: this commit's diff is over 1000 lines.
src/tools/glob.test.ts+57−0
Cut short: this commit's diff is over 1000 lines.
src/tools/glob.ts+16−9
Cut short: this commit's diff is over 1000 lines.
src/tools/grep.test.ts+71−0
Cut short: this commit's diff is over 1000 lines.
src/tools/grep.ts+20−12
Cut short: this commit's diff is over 1000 lines.
src/tools/hooks.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/tools/insert.test.ts+15−34
Cut short: this commit's diff is over 1000 lines.
src/tools/insert.ts+5−45
Cut short: this commit's diff is over 1000 lines.
src/tools/read.ts+3−6
Cut short: this commit's diff is over 1000 lines.
src/tools/replace.test.ts+15−37
Cut short: this commit's diff is over 1000 lines.
src/tools/replace.ts+5−46
Cut short: this commit's diff is over 1000 lines.
src/tools/scan-path.ts+45−0
Cut short: this commit's diff is over 1000 lines.
src/tools/shared.ts+53−0
Cut short: this commit's diff is over 1000 lines.
src/tools/snapshot.test.ts+54−61
Cut short: this commit's diff is over 1000 lines.
src/tools/snapshot.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/tools/test-helpers.ts+38−0
Cut short: this commit's diff is over 1000 lines.
src/tools/worktree.test.ts+17−36
Cut short: this commit's diff is over 1000 lines.
src/tools/worktree.ts+1−1
Cut short: this commit's diff is over 1000 lines.
tsconfig.json+23−23
Cut short: this commit's diff is over 1000 lines.