xonecas.io
64875
Mc

mini-coder / commit 212f231

Initial commit

xonecas2026-02-20 212f23109725f9b1a37eb38d6e1802d3c49b8c6e parent 4a563e3

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

.gitignore+9−0
@@ -0,0 +1,9 @@
1+node_modules/
2+dist/
3+*.db
4+*.db-shm
5+*.db-wal
6+.env
7+.env.*
8+!.env.example
9+bun.lock
PLAN.md+200−0
@@ -0,0 +1,200 @@
1+# mini-coder — Implementation Plan
2+
3+A small, fast CLI coding agent built with Bun.js. Focused on developer flow,
4+elegant output, and a reliable core feature set.
5+
6+---
7+
8+## Setup
9+
10+- Runtime: Bun.js
11+- Language: TypeScript (strict mode)
12+- Binary: `mc` (globally installable via `bun install -g .`)
13+- Config + sessions: `~/.config/mini-coder/`
14+
15+---
16+
17+## Dependencies
18+
19+```
20+ai # AI SDK v6 core
21+@ai-sdk/anthropic # Claude via Zen or direct
22+@ai-sdk/openai # GPT via Zen or direct
23+@ai-sdk/google # Gemini via Zen or direct
24+@ai-sdk/openai-compatible # MiniMax, GLM, Kimi via Zen
25+ollama-ai-provider # Local Ollama
26+yoctocolors # ANSI colors (16-color safe, inherits terminal theme)
27+zod # Tool input schemas
28+```
29+
30+---
31+
32+## Provider Strategy
33+
34+Uses the correct AI SDK package per endpoint type, following the OpenCode Zen docs:
35+
36+| Provider | Package | Endpoint / Notes |
37+| ------------------------------- | -------------------------- | --------------------------------------------- |
38+| OpenCode Zen — Anthropic models | `@ai-sdk/anthropic` | `https://opencode.ai/zen/v1/messages` |
39+| OpenCode Zen — OpenAI models | `@ai-sdk/openai` | `https://opencode.ai/zen/v1/responses` |
40+| OpenCode Zen — Google models | `@ai-sdk/google` | `https://opencode.ai/zen/v1/models/<model>` |
41+| OpenCode Zen — OpenAI-compat | `@ai-sdk/openai-compatible`| `https://opencode.ai/zen/v1/chat/completions` |
42+| Ollama (local) | `ollama-ai-provider` | `http://localhost:11434` (auto-discovered) |
43+
44+### ENV Auto-discovery
45+
46+| ENV var | Effect |
47+| ------------------ | ----------------------------------------- |
48+| `OPENCODE_API_KEY` | Enables OpenCode Zen provider |
49+| `OLLAMA_BASE_URL` | Override Ollama URL (default: localhost) |
50+
51+---
52+
53+## Module Architecture
54+
55+```
56+src/
57+ index.ts # Entry point — CLI args, wires agent + session
58+ cli/
59+ input.ts # Raw-mode stdin reader
60+ # - Line editing (left/right/backspace/ctrl-keys)
61+ # - History (up/down arrows, SQLite-backed)
62+ # - @ prefix → file reference autocomplete
63+ # - ! prefix → shell passthrough
64+ output.ts # ANSI rendering
65+ # - Streaming text with cursor animation
66+ # - Tool call display (glob/grep/read → formatted args)
67+ # - Edit tool → unified diff output
68+ # - Shell tool → command + output block
69+ # - Status bar: model/provider/cwd/git branch/tokens
70+ commands.ts # Slash command registry + handlers
71+ # - /model → pick model from connected providers
72+ # - /plan → toggle read-only plan mode
73+ # - /mcp → list/add/remove MCP servers
74+ # - /review → subagent code review
75+ llm-api/
76+ providers.ts # Provider factory
77+ # - ENV-based auto-discovery
78+ # - Returns LanguageModel for a given model ID string
79+ # - Supports "zen/claude-sonnet-4-6", "ollama/llama3", etc.
80+ turn.ts # Single conversation turn
81+ # - streamText with tool loop (maxSteps)
82+ # - Yields streaming events: text delta, tool call, tool result
83+ # - Returns complete turn: messages + usage stats
84+ types.ts # Shared types: Message, Turn, ToolCall, ProviderConfig
85+ agent/
86+ agent.ts # Main agent REPL loop
87+ # - Reads input → calls turn → renders output → repeat
88+ # - Manages conversation history in memory + persists to DB
89+ # - Handles /plan mode (no tool execution)
90+ # - Abort on Ctrl+C mid-turn
91+ tools.ts # Tool registry + hook system
92+ # - Registers all built-in tools
93+ # - Runs post-tool hooks (e.g. auto-format after edit)
94+ tools/
95+ glob.ts # Glob pattern file discovery
96+ grep.ts # Regex content search across files
97+ read.ts # File read (with line range support)
98+ edit.ts # File edit — exact string replacement (old → new)
99+ shell.ts # Shell command execution with streaming stdout/stderr
100+ subagent.ts # Spawn a nested mini-coder agent instance
101+ mcp/
102+ client.ts # MCP server connection (stdio + HTTP transports)
103+ manager.ts # Add/remove/list MCP servers, persist to config
104+ session/
105+ db.ts # bun:sqlite schema + query helpers
106+ # - sessions table: id, title, cwd, created_at, updated_at
107+ # - messages table: id, session_id, role, content, created_at
108+ # - prompt_history table: id, text, created_at
109+ manager.ts # new / resume / list session operations
110+```
111+
112+---
113+
114+## Build Phases
115+
116+### Phase 1 — Foundation
117+
118+- [ ] `bun init` — project setup, `package.json`, `tsconfig.json`, `.gitignore`
119+- [ ] `session/db.ts` — SQLite schema and CRUD helpers
120+- [ ] `llm-api/types.ts` — shared type definitions
121+- [ ] `llm-api/providers.ts` — ENV-based provider factory
122+- [ ] `llm-api/turn.ts` — streaming turn with tool loop
123+
124+### Phase 2 — Tools
125+
126+- [ ] `tools/glob.ts` — glob file search
127+- [ ] `tools/grep.ts` — regex content search
128+- [ ] `tools/read.ts` — file read
129+- [ ] `tools/edit.ts` — file edit (string replace)
130+- [ ] `tools/shell.ts` — shell execution
131+- [ ] `tools/subagent.ts` — nested agent
132+
133+### Phase 3 — CLI
134+
135+- [ ] `cli/input.ts` — raw-mode line editor with history, `@`, `!`
136+- [ ] `cli/output.ts` — ANSI output, tool rendering, diffs, status bar
137+- [ ] `cli/commands.ts` — slash command handlers
138+
139+### Phase 4 — Agent Loop
140+
141+- [ ] `agent/tools.ts` — tool registry and hook system
142+- [ ] `agent/agent.ts` — main REPL loop
143+- [ ] `session/manager.ts` — session new/resume/list
144+- [ ] `src/index.ts` — entry point, CLI args (--new, --resume, --list)
145+
146+### Phase 5 — MCP
147+
148+- [ ] `mcp/client.ts` — MCP client (stdio + HTTP)
149+- [ ] `mcp/manager.ts` — `/mcp` command integration
150+
151+---
152+
153+## UI Design Notes
154+
155+- Use only the 16 ANSI colors — colors inherit from the user's terminal theme
156+- No heavy box-drawing unless it reads well in monospace
157+- Status bar (always visible below input):
158+ `[model] [provider] [cwd] [git-branch] [ctx%] [↑tokens ↓tokens]`
159+- Tool call output format:
160+ - `glob "**/*.ts"` → compact tree of matched paths
161+ - `read src/foo.ts:10-30` → file + line range
162+ - `edit src/foo.ts` → unified diff (- old / + new)
163+ - `shell git status` → command + scrollable output block
164+- Prompt animation: simple spinner (⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏) while LLM is running
165+
166+---
167+
168+## Configuration Schema
169+
170+`~/.config/mini-coder/config.json`:
171+
172+```json
173+{
174+ "defaultModel": "zen/claude-sonnet-4-6",
175+ "providers": {
176+ "zen": { "apiKey": "..." },
177+ "ollama": { "baseUrl": "http://localhost:11434" }
178+ },
179+ "mcpServers": [
180+ { "name": "exa", "transport": "http", "url": "https://..." }
181+ ]
182+}
183+```
184+
185+---
186+
187+## Out of Scope for v1
188+
189+- LSP integration
190+- Image / screenshot support
191+- Web search tool
192+
193+---
194+
195+## Conventions
196+
197+- Agent skill files: `.agents/` in project dir or `~/.config/mini-coder/agents/`
198+ (follows skills.sh convention)
199+- Context files: `AGENTS.md` or `CLAUDE.md` in project root (same as oh-my-pi / opencode)
200+- No mocked/offline tests — integration tests only against real providers
TODO.md+52−0
@@ -0,0 +1,52 @@
1+# Undo needs to restore working directory
2+
3+Besides undoing the conversation turn, it should restore some snapshot, using git?
4+
5+---
6+
7+Subagent needs visibity on the ui somehow... that accounts for multiple in parallel... Needs planning
8+
9+---
10+
11+# Plan mode changes
12+
13+- Allow read tools + mcp
14+- When plan mode is on, add a `<system-message>PLAN MODE ACTIVE -- READ ONLY</system-message>` suffix to the user messages.
15+
16+---
17+
18+# LLMs don't know their cwd:
19+
20+```
21+▶ create a readme file and introduce yourself
22+ ✎ create README.md
23+ ✖ EACCES: permission denied, mkdir '/root/src/mini-coder'
24+ ✎ create README.md
25+ ✖ EACCES: permission denied, mkdir '/home/sandbox'
26+ $ $ pwd
27+ ✔ 0
28+ │ /home/xonecas/src/mini-coder
29+ ✎ create README.md
30+```
31+
32+---
33+
34+claude-sonnet-4-6 ~/src/mini-coder ↑40.4k ↓125
35+▶ Where in the code is it setting the default model?
36+ ? grep default.*model|model.*default i
37+ PLAN.md:174 "defaultModel": "zen/claude-sonnet-4-6",
38+ src/tools/subagent.ts:13 "Defaults to the current model."
39+ src/llm-api/providers.ts:198 * Returns the first available (provider, defaultModel) pair.
40+ ← read src/llm-api/providers.ts:195–220
41+ · src/llm-api/providers.ts lines 195–220 of 288 (truncated)
42+◆ It's in **`src/llm-api/providers.ts`**, the `autoDiscoverModel()` function (line 200). It picks the default model based on which API key env vars are present, in priority order:
43+
44+| Env Var | Default Model |
45+|---|---|
46+| `OPENCODE_API_KEY` | `zen/claude-sonnet-4-6` |
47+| `ANTHROPIC_API_KEY` | `anthropic/claude-sonnet-4-5-20250929` |
48+| `OPENAI_API_KEY` | `openai/gpt-4o` |
49+| `GOOGLE_API_KEY` / `GEMINI_API_KEY` | `google/gemini-2.0-flash` |
50+| *(none)* | `ollama/llama3.2` (fallback) |
51+
52+---
mini-coder-idea.md+66−0
@@ -0,0 +1,66 @@
1+# mini-coder
2+
3+A coding agent via a augmented CLI, small and fast that doesn't get in the way
4+
5+## Inpirations:
6+
7+- Oh my pi: https://github.com/can1357/oh-my-pi amazing tool, like a swiss army knife of coding agents.
8+- Claude Code: https://claude.com/product/claude-code clean UI, propertary software
9+- Codex: https://github.com/openai/codex Powerful and open source, focused on heavy open-ai integration
10+- Opencode: https://opencode.ai/ The open source standard. Similar to oh-my-pi but with a different aesthetic
11+
12+## Philosophy:
13+
14+Very focused on dev flow, simple setup steps and fast to coding.
15+Elegant output that focus on the conversation with the agent and their actions.
16+Accurate and reliable core set of features.
17+Fast and performant
18+Community oriented, all of the inspirations have their own dotfile format, try to follow the existing
19+conventions and not introduce more specs. (skills.sh installs to `.agents` which could be a good one for us)
20+
21+## Features:
22+
23+- Auto discovery of providers via ENV (Example: OPENCODE_API_KEY), or local servers (Example: ollama)
24+- Session management and command to create new/resume/list with local sqlite file.
25+- Seamless shell integration with aliases and completions with `!` in prompt input.
26+- Reference files, skills, agents from the working directory and global configs with `@` in prompt input
27+- Cancel LLM request and undo last LLM turn
28+- `glob`, `grep`, `read`, `edit`, `shell`, and `subagent` tools for LLMs
29+- tool hooks support (do command automatically after certain tools)
30+- Commands in CLI prompt:
31+ - `/model` command allows the user to pick a model from connected providers. As well as thinking effort for the model if supported.
32+ - `/review` command sends a subagent with a specific prompt to review code well
33+ - `/mcp` list/add/remove mcp servers
34+ - `/plan` for a read-only mode (`/plan` again to turn off)
35+- Connect to streaming MCPs (Example: https://exa.ai/docs/reference/exa-mcp)
36+
37+## UI/Output
38+
39+- Use the 16 ANSII colors so the coloring is allways inherited from the terminal theme (https://jvns.ca/blog/2024/10/01/terminal-colours/)
40+- Use oh-my-pi and claude code as visual inspirations.
41+- history log (like a terminal output scrolls away, pushing the input prompt down)
42+ - Read tools (glob, grep, read) show the tool call with args fomatted for output
43+ - Edit tools show the diff applied
44+ - Shell tools show the command called and their output
45+- status bar under prompt, with current model/provider/cwd/git branch/unique context size/token ouput/token input
46+- some prompt animation when a turn is processing.
47+
48+## Tech stack
49+
50+- All things Bun.js, runtime, package manager. https://bun.com/docs
51+- Multiprovider support via https://ai-sdk.dev/docs/introduction
52+- Colored output with https://github.com/sindresorhus/yoctocolors limitted but fast!
53+
54+## Repo structure
55+
56+Clean separation of concerns, use modules to organize the app.
57+No mocked/offline-servers type of tests
58+
59+Core modules:
60+
61+- `llm-api`: Provides the api to intereact with the provider and process the full conversation turn + tool calling.
62+- `cli`: Output/UI
63+- `agent`: Main agent implementation
64+- `tools/subagent`: subagent tool implementation
65+- `tools/read-write-shell`: all of the tools that use the local filesystem/shell
66+- `mcp`: handles connecting to mcp servers
package.json+29−0
@@ -0,0 +1,29 @@
1+{
2+ "name": "mini-coder",
3+ "version": "0.1.0",
4+ "description": "A small, fast CLI coding agent",
5+ "module": "src/index.ts",
6+ "type": "module",
7+ "bin": {
8+ "mc": "./src/index.ts"
9+ },
10+ "scripts": {
11+ "dev": "bun run src/index.ts",
12+ "typecheck": "tsc --noEmit"
13+ },
14+ "dependencies": {
15+ "@ai-sdk/anthropic": "^3.0.46",
16+ "@ai-sdk/google": "^3.0.30",
17+ "@ai-sdk/openai": "^3.0.30",
18+ "@ai-sdk/openai-compatible": "^2.0.30",
19+ "@modelcontextprotocol/sdk": "^1.26.0",
20+ "ai": "^6.0.94",
21+ "ollama-ai-provider": "^1.2.0",
22+ "yoctocolors": "^2.1.1",
23+ "zod": "^4.3.6"
24+ },
25+ "devDependencies": {
26+ "@types/bun": "latest",
27+ "typescript": "^5.8.3"
28+ }
29+}
src/agent/agent.ts+465−0
@@ -0,0 +1,465 @@
1+import * as c from "yoctocolors";
2+import { resolveModel } from "../llm-api/providers.ts";
3+import { runTurn, userMessage } from "../llm-api/turn.ts";
4+import {
5+ writeln,
6+ renderTurn,
7+ renderError,
8+ renderStatusBar,
9+ renderInfo,
10+ restoreTerminal,
11+ Spinner,
12+ PREFIX,
13+} from "../cli/output.ts";
14+import { readline } from "../cli/input.ts";
15+import { handleCommand, type CommandContext } from "../cli/commands.ts";
16+import { buildToolSet } from "./tools.ts";
17+import { connectMcpServer } from "../mcp/client.ts";
18+import {
19+ newSession,
20+ resumeSession,
21+ touchActiveSession,
22+ type ActiveSession,
23+} from "../session/manager.ts";
24+import {
25+ saveMessages,
26+ deleteLastTurn,
27+ getMaxTurnIndex,
28+ addPromptHistory,
29+ getConfigDir,
30+ listMcpServers,
31+} from "../session/db.ts";
32+import { join } from "path";
33+import { existsSync, readFileSync } from "fs";
34+import { homedir } from "os";
35+import type { Message, ToolDef } from "../llm-api/types.ts";
36+
37+// ─── Git branch detection ─────────────────────────────────────────────────────
38+
39+async function getGitBranch(cwd: string): Promise<string | null> {
40+ try {
41+ const proc = Bun.spawn(["git", "rev-parse", "--abbrev-ref", "HEAD"], {
42+ cwd,
43+ stdout: "pipe",
44+ stderr: "pipe",
45+ });
46+ const out = await new Response(proc.stdout).text();
47+ const code = await proc.exited;
48+ if (code !== 0) return null;
49+ return out.trim() || null;
50+ } catch {
51+ return null;
52+ }
53+}
54+
55+// ─── Context file discovery (AGENTS.md / CLAUDE.md) ──────────────────────────
56+
57+function loadContextFile(cwd: string): string | null {
58+ const candidates = [
59+ join(cwd, "AGENTS.md"),
60+ join(cwd, "CLAUDE.md"),
61+ join(cwd, ".agents", "system.md"),
62+ join(getConfigDir(), "AGENTS.md"),
63+ ];
64+ for (const p of candidates) {
65+ if (existsSync(p)) {
66+ try {
67+ return readFileSync(p, "utf-8");
68+ } catch {
69+ // skip
70+ }
71+ }
72+ }
73+ return null;
74+}
75+
76+// ─── System prompt ────────────────────────────────────────────────────────────
77+
78+function buildSystemPrompt(cwd: string): string {
79+ const contextFile = loadContextFile(cwd);
80+ const cwdDisplay = cwd.startsWith(homedir())
81+ ? "~" + cwd.slice(homedir().length)
82+ : cwd;
83+
84+ let prompt = `You are mini-coder, a small and fast CLI coding agent.
85+You have access to tools to read files, search code, make edits, run shell commands, and spawn subagents.
86+
87+Current working directory: ${cwdDisplay}
88+
89+Guidelines:
90+- Be concise and precise. Avoid unnecessary preamble.
91+- Prefer small, targeted edits over large rewrites.
92+- Always read a file before editing it.
93+- Use glob to discover files, grep to find patterns, read to inspect contents.
94+- Use shell for tests, builds, and git operations.
95+- When in doubt, ask the user before making destructive changes.`;
96+
97+ if (contextFile) {
98+ prompt += `\n\n# Project context\n\n${contextFile}`;
99+ }
100+
101+ return prompt;
102+}
103+
104+// ─── DB messages → raw ModelMessages (for session resume) ────────────────────
105+// On resume, the DB has only simple text messages (user prompts + assistant
106+// text replies). Tool-call/result parts are intentionally not reconstructed
107+// because the complex output/input shapes are opaque. The conversation context
108+// is still preserved for the model via the text content.
109+// eslint-disable-next-line @typescript-eslint/no-explicit-any
110+function dbMessagesToCore(messages: Message[]): any[] {
111+ return messages.map((m) => {
112+ if (typeof m.content === "string") {
113+ return { role: m.role, content: m.content };
114+ }
115+ if (Array.isArray(m.content)) {
116+ // Filter to text-only parts to avoid feeding malformed tool parts
117+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
118+ const textParts = (m.content as any[]).filter((p) => p.type === "text");
119+ if (textParts.length > 0) return { role: m.role, content: textParts };
120+ return { role: m.role, content: "" };
121+ }
122+ return { role: m.role, content: String(m.content) };
123+ });
124+}
125+
126+// ─── Shell passthrough (! prefix) ─────────────────────────────────────────────
127+
128+async function runShellPassthrough(command: string, cwd: string): Promise<string> {
129+ const proc = Bun.spawn(["bash", "-c", command], {
130+ cwd,
131+ stdout: "pipe",
132+ stderr: "pipe",
133+ });
134+ try {
135+ const [stdout, stderr] = await Promise.all([
136+ new Response(proc.stdout).text(),
137+ new Response(proc.stderr).text(),
138+ ]);
139+ await proc.exited;
140+ const out = [stdout, stderr].filter(Boolean).join("\n").trim();
141+ if (out) writeln(c.dim(out));
142+ return out;
143+ } finally {
144+ restoreTerminal();
145+ }
146+}
147+
148+// ─── Main agent run ───────────────────────────────────────────────────────────
149+
150+export interface AgentOptions {
151+ model: string;
152+ cwd: string;
153+ sessionId?: string; // resume existing
154+ initialPrompt?: string; // non-interactive first message
155+}
156+
157+export async function runAgent(opts: AgentOptions): Promise<void> {
158+ const cwd = opts.cwd;
159+ let currentModel = opts.model;
160+
161+ // Session setup
162+ let session: ActiveSession;
163+ if (opts.sessionId) {
164+ const resumed = resumeSession(opts.sessionId);
165+ if (!resumed) {
166+ renderError(`Session "${opts.sessionId}" not found.`);
167+ process.exit(1);
168+ }
169+ session = resumed;
170+ currentModel = session.model;
171+ renderInfo(`Resumed session ${session.id} (${c.cyan(currentModel)})`);
172+ } else {
173+ session = newSession(currentModel, cwd);
174+ }
175+
176+ // Turn counter — incremented each time processUserInput is called
177+ // Used to group user + assistant messages for undo
178+ let turnIndex = getMaxTurnIndex(session.id) + 1;
179+
180+ // Raw AI SDK ModelMessage history — fed directly to streamText each turn.
181+ // This is kept separate from session.messages (which is DB-persisted text)
182+ // to avoid lossy round-trips through our internal Message type.
183+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
184+ const coreHistory: any[] = dbMessagesToCore(session.messages);
185+
186+ // Subagent runner (recursive) — depth prevents infinite recursion
187+ const runSubagent = async (
188+ prompt: string,
189+ model?: string,
190+ depth = 0
191+ ): Promise<{ result: string; inputTokens: number; outputTokens: number }> => {
192+ const subModel = model ?? currentModel;
193+ const subMessages: Message[] = [{ role: "user", content: prompt }];
194+ const subTools = buildToolSet({ cwd, depth, runSubagent });
195+ const subLlm = resolveModel(subModel);
196+ const systemPrompt = buildSystemPrompt(cwd);
197+
198+ let result = "";
199+ let inputTokens = 0;
200+ let outputTokens = 0;
201+
202+ const events = runTurn({
203+ model: subLlm,
204+ messages: dbMessagesToCore(subMessages),
205+ tools: subTools,
206+ systemPrompt,
207+ });
208+
209+ for await (const event of events) {
210+ if (event.type === "text-delta") result += event.delta;
211+ if (event.type === "turn-complete") {
212+ inputTokens = event.inputTokens;
213+ outputTokens = event.outputTokens;
214+ }
215+ }
216+
217+ return { result, inputTokens, outputTokens };
218+ };
219+
220+ // ── MCP: load persisted servers and connect them ───────────────────────────
221+ const tools: ToolDef[] = buildToolSet({ cwd, depth: 0, runSubagent });
222+
223+ async function connectAndAddMcp(name: string): Promise<void> {
224+ const rows = listMcpServers();
225+ const row = rows.find((r) => r.name === name);
226+ if (!row) throw new Error(`MCP server "${name}" not found in DB`);
227+ const cfg: Parameters<typeof connectMcpServer>[0] = {
228+ name: row.name,
229+ transport: row.transport as "http" | "stdio",
230+ ...(row.url ? { url: row.url } : {}),
231+ ...(row.command ? { command: row.command } : {}),
232+ ...(row.args ? { args: JSON.parse(row.args) } : {}),
233+ ...(row.env ? { env: JSON.parse(row.env) } : {}),
234+ };
235+ const client = await connectMcpServer(cfg);
236+ tools.push(...client.tools);
237+ }
238+
239+ // Connect all persisted MCP servers at startup
240+ for (const row of listMcpServers()) {
241+ try {
242+ await connectAndAddMcp(row.name);
243+ renderInfo(`MCP: connected ${c.cyan(row.name)}`);
244+ } catch (e) {
245+ renderError(`MCP: failed to connect ${row.name}: ${String(e)}`);
246+ }
247+ }
248+
249+ let planMode = false;
250+
251+ const cmdCtx: CommandContext = {
252+ get currentModel() { return currentModel; },
253+ setModel: (m) => { currentModel = m; session.model = m; },
254+ get planMode() { return planMode; },
255+ setPlanMode: (v) => { planMode = v; },
256+ cwd,
257+ runSubagent: (prompt, model) => runSubagent(prompt, model),
258+ undoLastTurn: () => {
259+ // Nothing to undo if there are no messages
260+ if (session.messages.length === 0) return false;
261+
262+ // Find the message index where the last turn starts (last user message)
263+ let lastUserIdx = -1;
264+ for (let i = session.messages.length - 1; i >= 0; i--) {
265+ if (session.messages[i]?.role === "user") {
266+ lastUserIdx = i;
267+ break;
268+ }
269+ }
270+ if (lastUserIdx === -1) return false;
271+
272+ // Trim in-memory DB history
273+ session.messages.splice(lastUserIdx);
274+
275+ // Trim coreHistory to match — find last user message in coreHistory
276+ let coreLastUserIdx = -1;
277+ for (let i = coreHistory.length - 1; i >= 0; i--) {
278+ if (coreHistory[i]?.role === "user") {
279+ coreLastUserIdx = i;
280+ break;
281+ }
282+ }
283+ if (coreLastUserIdx !== -1) coreHistory.splice(coreLastUserIdx);
284+
285+ // Delete from DB and decrement turn counter
286+ const deleted = deleteLastTurn(session.id);
287+ if (turnIndex > 0) turnIndex--;
288+ return deleted;
289+ },
290+ connectMcpServer: connectAndAddMcp,
291+ };
292+ const spinner = new Spinner();
293+ let totalIn = 0;
294+ let totalOut = 0;
295+
296+ // ── Handle initial prompt (non-interactive) ────────────────────────────────
297+ if (opts.initialPrompt) {
298+ await processUserInput(opts.initialPrompt);
299+ }
300+
301+ // ── REPL ──────────────────────────────────────────────────────────────────
302+ while (true) {
303+ let input;
304+ try {
305+ input = await readline({ cwd });
306+ } catch {
307+ break;
308+ }
309+
310+ switch (input.type) {
311+ case "eof":
312+ writeln(c.dim("Goodbye."));
313+ return;
314+
315+ case "interrupt":
316+ // Just go back to prompt
317+ continue;
318+
319+ case "command": {
320+ const result = await handleCommand(input.command, input.args, cmdCtx);
321+ if (result.type === "exit") {
322+ writeln(c.dim("Goodbye."));
323+ return;
324+ }
325+ continue;
326+ }
327+
328+ case "shell": {
329+ const out = await runShellPassthrough(input.command, cwd);
330+ if (out) {
331+ const thisTurn = turnIndex++;
332+ const msg: Message = {
333+ role: "user",
334+ content: `Shell output of \`${input.command}\`:\n\`\`\`\n${out}\n\`\`\``,
335+ };
336+ session.messages.push(msg);
337+ saveMessages(session.id, [msg], thisTurn);
338+ coreHistory.push({ role: "user", content: msg.content });
339+ }
340+ continue;
341+ }
342+
343+ case "submit":
344+ await processUserInput(input.text);
345+ continue;
346+ }
347+ }
348+
349+ // ── Process a user message ─────────────────────────────────────────────────
350+ async function processUserInput(text: string): Promise<void> {
351+ // Resolve @file references
352+ const resolvedText = await resolveFileRefs(text, cwd);
353+
354+ // Capture turn index for this turn (user + response share the same index)
355+ const thisTurn = turnIndex++;
356+
357+ const userMsg: Message = { role: "user", content: resolvedText };
358+ session.messages.push(userMsg);
359+ saveMessages(session.id, [userMsg], thisTurn);
360+
361+ // Also push into coreHistory as a raw ModelMessage
362+ coreHistory.push({ role: "user", content: resolvedText });
363+
364+ const llm = resolveModel(currentModel);
365+ const systemPrompt = buildSystemPrompt(cwd);
366+
367+ const abortController = new AbortController();
368+ const onSigInt = () => abortController.abort();
369+ process.once("SIGINT", onSigInt);
370+
371+ spinner.start("thinking");
372+
373+ const events = runTurn({
374+ model: llm,
375+ messages: coreHistory,
376+ tools: planMode ? [] : tools,
377+ systemPrompt,
378+ signal: abortController.signal,
379+ });
380+
381+ const { inputTokens, outputTokens, newMessages } = await renderTurn(events, spinner);
382+ process.removeListener("SIGINT", onSigInt);
383+
384+ // newMessages are raw ModelMessage objects — push directly into coreHistory
385+ // so subsequent turns have the correct input/output fields.
386+ if (newMessages.length > 0) {
387+ coreHistory.push(...newMessages);
388+ // For DB persistence, store a simplified version (text only is enough
389+ // for session resume context — tool call parts are not reconstructed).
390+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
391+ const dbMsgs: Message[] = newMessages.map((m: any) => {
392+ if (typeof m.content === "string") {
393+ return { role: m.role as Message["role"], content: m.content };
394+ }
395+ if (Array.isArray(m.content)) {
396+ // Collapse to text content only for DB storage
397+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
398+ const text = (m.content as any[])
399+ .filter((p) => p.type === "text")
400+ .map((p) => p.text as string)
401+ .join("");
402+ return { role: m.role as Message["role"], content: text };
403+ }
404+ return { role: m.role as Message["role"], content: String(m.content) };
405+ });
406+ session.messages.push(...dbMsgs);
407+ saveMessages(session.id, dbMsgs, thisTurn);
408+ }
409+
410+ totalIn += inputTokens;
411+ totalOut += outputTokens;
412+ touchActiveSession(session);
413+
414+ // Render status bar
415+ const branch = await getGitBranch(cwd);
416+ const provider = currentModel.split("/")[0] ?? "";
417+ const modelShort = currentModel.split("/").slice(1).join("/");
418+ const cwdDisplay = cwd.startsWith(homedir())
419+ ? "~" + cwd.slice(homedir().length)
420+ : cwd;
421+
422+ renderStatusBar({
423+ model: modelShort,
424+ provider,
425+ cwd: cwdDisplay,
426+ gitBranch: branch,
427+ inputTokens,
428+ outputTokens,
429+ contextPercent: null,
430+ });
431+ }
432+}
433+
434+// ─── Resolve @file references in user input ────────────────────────────────────
435+
436+async function resolveFileRefs(text: string, cwd: string): Promise<string> {
437+ // Find all @<path> tokens
438+ const atPattern = /@([\w./\-_]+)/g;
439+ let result = text;
440+ const matches = [...text.matchAll(atPattern)];
441+
442+ for (const match of matches.reverse()) {
443+ const ref = match[1];
444+ if (!ref) continue;
445+ const filePath = ref.startsWith("/") ? ref : join(cwd, ref);
446+
447+ try {
448+ const content = await Bun.file(filePath).text();
449+ const lines = content.split("\n");
450+ const preview =
451+ lines.length > 200
452+ ? lines.slice(0, 200).join("\n") + "\n[truncated]"
453+ : content;
454+ const replacement = `\`${ref}\`:\n\`\`\`\n${preview}\n\`\`\``;
455+ result =
456+ result.slice(0, match.index) +
457+ replacement +
458+ result.slice((match.index ?? 0) + match[0].length);
459+ } catch {
460+ // Leave the @ref as-is if file not found
461+ }
462+ }
463+
464+ return result;
465+}
src/agent/tools.ts+79−0
@@ -0,0 +1,79 @@
1+import type { ToolDef } from "../llm-api/types.ts";
2+import { globTool } from "../tools/glob.ts";
3+import { grepTool } from "../tools/grep.ts";
4+import { readTool } from "../tools/read.ts";
5+import { editTool } from "../tools/edit.ts";
6+import { shellTool } from "../tools/shell.ts";
7+import { createSubagentTool } from "../tools/subagent.ts";
8+
9+// ─── Hook types ────────────────────────────────────────────────────────────────
10+
11+export type ToolHook = (toolName: string, result: unknown) => Promise<void>;
12+
13+const _hooks: ToolHook[] = [];
14+
15+export function addToolHook(hook: ToolHook): void {
16+ _hooks.push(hook);
17+}
18+
19+export async function runToolHooks(
20+ toolName: string,
21+ result: unknown
22+): Promise<void> {
23+ for (const hook of _hooks) {
24+ try {
25+ await hook(toolName, result);
26+ } catch {
27+ // Hooks must not crash the agent
28+ }
29+ }
30+}
31+
32+// ─── Tool registry ────────────────────────────────────────────────────────────
33+
34+/**
35+ * Wrap a tool's execute function to inject a default cwd if not provided.
36+ */
37+function withCwdDefault(tool: ToolDef, cwd: string): ToolDef {
38+ const originalExecute = tool.execute;
39+ return {
40+ ...tool,
41+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
42+ execute: async (input: any) => {
43+ const withDefault = { cwd, ...(input as object) };
44+ return originalExecute(withDefault);
45+ },
46+ };
47+}
48+
49+export const MAX_SUBAGENT_DEPTH = 3;
50+
51+export function buildToolSet(opts: {
52+ cwd: string;
53+ depth?: number;
54+ runSubagent: (prompt: string, model?: string, depth?: number) => Promise<{
55+ result: string;
56+ inputTokens: number;
57+ outputTokens: number;
58+ }>;
59+}): ToolDef[] {
60+ const depth = opts.depth ?? 0;
61+ return [
62+ withCwdDefault(globTool as ToolDef, opts.cwd),
63+ withCwdDefault(grepTool as ToolDef, opts.cwd),
64+ withCwdDefault(readTool as ToolDef, opts.cwd),
65+ withCwdDefault(editTool as ToolDef, opts.cwd),
66+ withCwdDefault(shellTool as ToolDef, opts.cwd),
67+ createSubagentTool(
68+ async (prompt, model) => {
69+ if (depth >= MAX_SUBAGENT_DEPTH) {
70+ throw new Error(
71+ `Subagent depth limit reached (max ${MAX_SUBAGENT_DEPTH}). ` +
72+ `Cannot spawn another subagent from depth ${depth}.`
73+ );
74+ }
75+ return opts.runSubagent(prompt, model, depth + 1);
76+ }
77+ ) as ToolDef,
78+ ];
79+}
src/cli/commands.ts+298−0
@@ -0,0 +1,298 @@
1+import * as c from "yoctocolors";
2+import { writeln, renderInfo, renderError, PREFIX } from "./output.ts";
3+import { availableProviders, fetchAvailableModels } from "../llm-api/providers.ts";
4+import { listMcpServers, upsertMcpServer, deleteMcpServer } from "../session/db.ts";
5+
6+// ─── Types ────────────────────────────────────────────────────────────────────
7+
8+export interface CommandContext {
9+ currentModel: string;
10+ setModel: (model: string) => void;
11+ planMode: boolean;
12+ setPlanMode: (enabled: boolean) => void;
13+ undoLastTurn: () => boolean;
14+ connectMcpServer: (name: string) => Promise<void>;
15+ runSubagent: (prompt: string, model?: string) => Promise<{ result: string; inputTokens: number; outputTokens: number }>;
16+ cwd: string;
17+}
18+
19+export type CommandResult =
20+ | { type: "handled" }
21+ | { type: "unknown"; command: string }
22+ | { type: "exit" };
23+
24+// ─── Command handlers ─────────────────────────────────────────────────────────
25+
26+async function handleModel(ctx: CommandContext, args: string): Promise<void> {
27+ if (args) {
28+ // If the user passed a bare model name (no provider prefix), resolve it
29+ // against the live model list so we get the full "provider/model-id" form.
30+ let modelId = args;
31+ if (!args.includes("/")) {
32+ const models = await fetchAvailableModels();
33+ const match = models.find(
34+ (m) => m.id.split("/").slice(1).join("/") === args || m.id === args
35+ );
36+ if (match) {
37+ modelId = match.id;
38+ } else {
39+ writeln(`${PREFIX.error} unknown model ${c.cyan(args)} ${c.dim("— run /models for the full list")}`);
40+ return;
41+ }
42+ }
43+ ctx.setModel(modelId);
44+ writeln(`${PREFIX.success} model → ${c.cyan(modelId)}`);
45+ return;
46+ }
47+
48+ writeln(`${c.dim(" fetching models…")}`);
49+
50+ const models = await fetchAvailableModels();
51+
52+ // Clear the "fetching" line
53+ process.stdout.write("\x1B[1A\r\x1B[2K");
54+
55+ if (models.length === 0) {
56+ writeln(`${PREFIX.error} No models found. Check your API keys or Ollama connection.`);
57+ writeln(c.dim(" Set OPENCODE_API_KEY for Zen, or start Ollama for local models."));
58+ return;
59+ }
60+
61+ // Group by provider
62+ const byProvider = new Map<string, typeof models>();
63+ for (const m of models) {
64+ if (!byProvider.has(m.provider)) byProvider.set(m.provider, []);
65+ byProvider.get(m.provider)!.push(m);
66+ }
67+
68+ writeln();
69+ for (const [provider, list] of byProvider) {
70+ writeln(c.bold(` ${provider}`));
71+ for (const m of list) {
72+ const isCurrent = ctx.currentModel === m.id;
73+ const freeTag = m.free ? c.green(" free") : "";
74+ const ctxTag = m.context ? c.dim(` ${Math.round(m.context / 1000)}k`) : "";
75+ const cur = isCurrent ? c.cyan(" ◀") : "";
76+ writeln(` ${c.dim("·")} ${m.displayName}${freeTag}${ctxTag}${cur}`);
77+ writeln(` ${c.dim(m.id)}`);
78+ }
79+ }
80+
81+ writeln();
82+ writeln(c.dim(` /model <id> to switch · e.g. /model zen/claude-sonnet-4-6`));
83+}
84+
85+function handlePlan(ctx: CommandContext): void {
86+ ctx.setPlanMode(!ctx.planMode);
87+ if (ctx.planMode) {
88+ writeln(`${PREFIX.info} ${c.yellow("plan mode")} ${c.dim("— agent will describe without running tools")}`);
89+ } else {
90+ writeln(`${PREFIX.info} ${c.dim("plan mode off")}`);
91+ }
92+}
Cut short: this commit's diff is over 1000 lines.
src/cli/input.ts+373−0
Cut short: this commit's diff is over 1000 lines.
src/cli/output.ts+490−0
Cut short: this commit's diff is over 1000 lines.
src/index.ts+160−0
Cut short: this commit's diff is over 1000 lines.
src/llm-api/providers.ts+287−0
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn.ts+166−0
Cut short: this commit's diff is over 1000 lines.
src/llm-api/types.ts+104−0
Cut short: this commit's diff is over 1000 lines.
src/mcp/client.ts+105−0
Cut short: this commit's diff is over 1000 lines.
src/mcp/manager.ts+83−0
Cut short: this commit's diff is over 1000 lines.
src/session/db.ts+286−0
Cut short: this commit's diff is over 1000 lines.
src/session/manager.ts+71−0
Cut short: this commit's diff is over 1000 lines.
src/tools/edit.ts+166−0
Cut short: this commit's diff is over 1000 lines.
src/tools/glob.ts+64−0
Cut short: this commit's diff is over 1000 lines.
src/tools/grep.ts+129−0
Cut short: this commit's diff is over 1000 lines.
src/tools/read.ts+91−0
Cut short: this commit's diff is over 1000 lines.
src/tools/shell.ts+124−0
Cut short: this commit's diff is over 1000 lines.
src/tools/subagent.ts+48−0
Cut short: this commit's diff is over 1000 lines.
tsconfig.json+25−0
Cut short: this commit's diff is over 1000 lines.