xonecas.io
64875
Mc

mini-coder / commit 2b79fbf

feat: no more vibes, lint installed

xonecas2026-02-20 2b79fbf31443bb6d53beebf265eaac82795173d0 parent d41f0e3

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

biome.json+18−0
@@ -0,0 +1,18 @@
1+{
2+ "$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
3+ "organizeImports": {
4+ "enabled": true
5+ },
6+ "formatter": {
7+ "enabled": true
8+ },
9+ "linter": {
10+ "enabled": true,
11+ "rules": {
12+ "recommended": true
13+ }
14+ },
15+ "files": {
16+ "ignore": ["node_modules", "dist"]
17+ }
18+}
package.json+4−1
@@ -9,7 +9,9 @@
99 },
1010 "scripts": {
1111 "dev": "bun run src/index.ts",
12- "typecheck": "tsc --noEmit"
12+ "typecheck": "tsc --noEmit",
13+ "lint": "biome check src",
14+ "format": "biome format --write src"
1315 },
1416 "dependencies": {
1517 "@ai-sdk/anthropic": "^3.0.46",
@@ -23,6 +25,7 @@
2325 "zod": "^4.3.6"
2426 },
2527 "devDependencies": {
28+ "@biomejs/biome": "^1.9.4",
2629 "@types/bun": "latest",
2730 "typescript": "^5.8.3"
2831 }
src/agent/agent.ts+432−420
@@ -1,87 +1,87 @@
1+import { existsSync, readFileSync } from "node:fs";
2+import { homedir } from "node:os";
3+import { join } from "node:path";
14 import * as c from "yoctocolors";
2-import { resolveModel } from "../llm-api/providers.ts";
3-import { runTurn, userMessage } from "../llm-api/turn.ts";
5+import { type CommandContext, handleCommand } from "../cli/commands.ts";
6+import { readline, type InputResult } from "../cli/input.ts";
47 import {
5- writeln,
6- renderTurn,
7- renderError,
8- renderStatusBar,
9- renderInfo,
10- restoreTerminal,
11- Spinner,
12- PREFIX,
8+ PREFIX,
9+ Spinner,
10+ renderError,
11+ renderInfo,
12+ renderStatusBar,
13+ renderTurn,
14+ restoreTerminal,
15+ writeln,
1316 } 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 { resolveModel } from "../llm-api/providers.ts";
18+import { type CoreMessage, runTurn, userMessage } from "../llm-api/turn.ts";
19+import type { Message, ToolDef } from "../llm-api/types.ts";
1720 import { connectMcpServer } from "../mcp/client.ts";
1821 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- setPreferredModel,
22+ addPromptHistory,
23+ deleteLastTurn,
24+ getConfigDir,
25+ getMaxTurnIndex,
26+ listMcpServers,
27+ saveMessages,
28+ setPreferredModel,
3229 } from "../session/db.ts";
33-import { join } from "path";
34-import { existsSync, readFileSync } from "fs";
35-import { homedir } from "os";
36-import type { Message, ToolDef } from "../llm-api/types.ts";
30+import {
31+ type ActiveSession,
32+ newSession,
33+ resumeSession,
34+ touchActiveSession,
35+} from "../session/manager.ts";
36+import { buildToolSet } from "./tools.ts";
3737
3838 // ─── Git branch detection ─────────────────────────────────────────────────────
3939
4040 async function getGitBranch(cwd: string): Promise<string | null> {
41- try {
42- const proc = Bun.spawn(["git", "rev-parse", "--abbrev-ref", "HEAD"], {
43- cwd,
44- stdout: "pipe",
45- stderr: "pipe",
46- });
47- const out = await new Response(proc.stdout).text();
48- const code = await proc.exited;
49- if (code !== 0) return null;
50- return out.trim() || null;
51- } catch {
52- return null;
53- }
41+ try {
42+ const proc = Bun.spawn(["git", "rev-parse", "--abbrev-ref", "HEAD"], {
43+ cwd,
44+ stdout: "pipe",
45+ stderr: "pipe",
46+ });
47+ const out = await new Response(proc.stdout).text();
48+ const code = await proc.exited;
49+ if (code !== 0) return null;
50+ return out.trim() || null;
51+ } catch {
52+ return null;
53+ }
5454 }
5555
5656 // ─── Context file discovery (AGENTS.md / CLAUDE.md) ──────────────────────────
5757
5858 function loadContextFile(cwd: string): string | null {
59- const candidates = [
60- join(cwd, "AGENTS.md"),
61- join(cwd, "CLAUDE.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;
59+ const candidates = [
60+ join(cwd, "AGENTS.md"),
61+ join(cwd, "CLAUDE.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;
7474 }
7575
7676 // ─── System prompt ────────────────────────────────────────────────────────────
7777
7878 function buildSystemPrompt(cwd: string): string {
79- const contextFile = loadContextFile(cwd);
80- const cwdDisplay = cwd.startsWith(homedir())
81- ? "~" + cwd.slice(homedir().length)
82- : cwd;
79+ const contextFile = loadContextFile(cwd);
80+ const cwdDisplay = cwd.startsWith(homedir())
81+ ? `~${cwd.slice(homedir().length)}`
82+ : cwd;
8383
84- let prompt = `You are mini-coder, a small and fast CLI coding agent.
84+ let prompt = `You are mini-coder, a small and fast CLI coding agent.
8585 You have access to tools to read files, search code, make edits, run shell commands, and spawn subagents.
8686
8787 Current working directory: ${cwdDisplay}
@@ -94,11 +94,11 @@ Guidelines:
9494 - Use shell for tests, builds, and git operations.
9595 - When in doubt, ask the user before making destructive changes.`;
9696
97- if (contextFile) {
98- prompt += `\n\n# Project context\n\n${contextFile}`;
99- }
97+ if (contextFile) {
98+ prompt += `\n\n# Project context\n\n${contextFile}`;
99+ }
100100
101- return prompt;
101+ return prompt;
102102 }
103103
104104 // ─── DB messages → raw ModelMessages (for session resume) ────────────────────
@@ -106,376 +106,388 @@ Guidelines:
106106 // text replies). Tool-call/result parts are intentionally not reconstructed
107107 // because the complex output/input shapes are opaque. The conversation context
108108 // 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- });
109+function isTextPart(part: unknown): part is { type: "text"; text: string } {
110+ return (
111+ typeof part === "object" &&
112+ part !== null &&
113+ (part as { type?: unknown }).type === "text" &&
114+ typeof (part as { text?: unknown }).text === "string"
115+ );
116+}
117+
118+function dbMessagesToCore(messages: Message[]): CoreMessage[] {
119+ return messages.map((m): CoreMessage => {
120+ if (typeof m.content === "string") {
121+ // DB messages only have "user" or "assistant" roles; cast is safe.
122+ return { role: m.role as "user" | "assistant", content: m.content };
123+ }
124+ if (Array.isArray(m.content)) {
125+ // Filter to text-only parts to avoid feeding malformed tool parts
126+ const textParts = m.content.filter(isTextPart);
127+ if (textParts.length > 0) {
128+ return {
129+ role: m.role as "user" | "assistant",
130+ content: textParts,
131+ };
132+ }
133+ return { role: m.role as "user" | "assistant", content: "" };
134+ }
135+ return { role: m.role as "user" | "assistant", content: String(m.content) };
136+ });
124137 }
125138
126139 // ─── Shell passthrough (! prefix) ─────────────────────────────────────────────
127140
128141 async function runShellPassthrough(
129- command: string,
130- cwd: string,
142+ command: string,
143+ cwd: string,
131144 ): Promise<string> {
132- const proc = Bun.spawn(["bash", "-c", command], {
133- cwd,
134- stdout: "pipe",
135- stderr: "pipe",
136- });
137- try {
138- const [stdout, stderr] = await Promise.all([
139- new Response(proc.stdout).text(),
140- new Response(proc.stderr).text(),
141- ]);
142- await proc.exited;
143- const out = [stdout, stderr].filter(Boolean).join("\n").trim();
144- if (out) writeln(c.dim(out));
145- return out;
146- } finally {
147- restoreTerminal();
148- }
145+ const proc = Bun.spawn(["bash", "-c", command], {
146+ cwd,
147+ stdout: "pipe",
148+ stderr: "pipe",
149+ });
150+ try {
151+ const [stdout, stderr] = await Promise.all([
152+ new Response(proc.stdout).text(),
153+ new Response(proc.stderr).text(),
154+ ]);
155+ await proc.exited;
156+ const out = [stdout, stderr].filter(Boolean).join("\n").trim();
157+ if (out) writeln(c.dim(out));
158+ return out;
159+ } finally {
160+ restoreTerminal();
161+ }
149162 }
150163
151164 // ─── Main agent run ───────────────────────────────────────────────────────────
152165
153166 export interface AgentOptions {
154- model: string;
155- cwd: string;
156- sessionId?: string; // resume existing
157- initialPrompt?: string; // non-interactive first message
167+ model: string;
168+ cwd: string;
169+ sessionId?: string; // resume existing
170+ initialPrompt?: string; // non-interactive first message
158171 }
159172
160173 export async function runAgent(opts: AgentOptions): Promise<void> {
161- const cwd = opts.cwd;
162- let currentModel = opts.model;
163-
164- // Session setup
165- let session: ActiveSession;
166- if (opts.sessionId) {
167- const resumed = resumeSession(opts.sessionId);
168- if (!resumed) {
169- renderError(`Session "${opts.sessionId}" not found.`);
170- process.exit(1);
171- }
172- session = resumed;
173- currentModel = session.model;
174- renderInfo(`Resumed session ${session.id} (${c.cyan(currentModel)})`);
175- } else {
176- session = newSession(currentModel, cwd);
177- }
178-
179- // Turn counter — incremented each time processUserInput is called
180- // Used to group user + assistant messages for undo
181- let turnIndex = getMaxTurnIndex(session.id) + 1;
182-
183- // Raw AI SDK ModelMessage history — fed directly to streamText each turn.
184- // This is kept separate from session.messages (which is DB-persisted text)
185- // to avoid lossy round-trips through our internal Message type.
186- // eslint-disable-next-line @typescript-eslint/no-explicit-any
187- const coreHistory: any[] = dbMessagesToCore(session.messages);
188-
189- // Subagent runner (recursive) — depth prevents infinite recursion
190- const runSubagent = async (
191- prompt: string,
192- model?: string,
193- depth = 0,
194- ): Promise<{ result: string; inputTokens: number; outputTokens: number }> => {
195- const subModel = model ?? currentModel;
196- const subMessages: Message[] = [{ role: "user", content: prompt }];
197- const subTools = buildToolSet({ cwd, depth, runSubagent });
198- const subLlm = resolveModel(subModel);
199- const systemPrompt = buildSystemPrompt(cwd);
200-
201- let result = "";
202- let inputTokens = 0;
203- let outputTokens = 0;
204-
205- const events = runTurn({
206- model: subLlm,
207- messages: dbMessagesToCore(subMessages),
208- tools: subTools,
209- systemPrompt,
210- });
211-
212- for await (const event of events) {
213- if (event.type === "text-delta") result += event.delta;
214- if (event.type === "turn-complete") {
215- inputTokens = event.inputTokens;
216- outputTokens = event.outputTokens;
217- }
218- }
219-
220- return { result, inputTokens, outputTokens };
221- };
222-
223- // ── MCP: load persisted servers and connect them ───────────────────────────
224- const tools: ToolDef[] = buildToolSet({ cwd, depth: 0, runSubagent });
225-
226- async function connectAndAddMcp(name: string): Promise<void> {
227- const rows = listMcpServers();
228- const row = rows.find((r) => r.name === name);
229- if (!row) throw new Error(`MCP server "${name}" not found in DB`);
230- const cfg: Parameters<typeof connectMcpServer>[0] = {
231- name: row.name,
232- transport: row.transport as "http" | "stdio",
233- ...(row.url ? { url: row.url } : {}),
234- ...(row.command ? { command: row.command } : {}),
235- ...(row.args ? { args: JSON.parse(row.args) } : {}),
236- ...(row.env ? { env: JSON.parse(row.env) } : {}),
237- };
238- const client = await connectMcpServer(cfg);
239- tools.push(...client.tools);
240- }
241-
242- // Connect all persisted MCP servers at startup
243- for (const row of listMcpServers()) {
244- try {
245- await connectAndAddMcp(row.name);
246- renderInfo(`MCP: connected ${c.cyan(row.name)}`);
247- } catch (e) {
248- renderError(`MCP: failed to connect ${row.name}: ${String(e)}`);
249- }
250- }
251-
252- let planMode = false;
253-
254- const cmdCtx: CommandContext = {
255- get currentModel() {
256- return currentModel;
257- },
258- setModel: (m) => {
259- currentModel = m;
260- session.model = m;
261- setPreferredModel(m);
262- },
263- get planMode() {
264- return planMode;
265- },
266- setPlanMode: (v) => {
267- planMode = v;
268- },
269- cwd,
270- runSubagent: (prompt, model) => runSubagent(prompt, model),
271- undoLastTurn: () => {
272- // Nothing to undo if there are no messages
273- if (session.messages.length === 0) return false;
274-
275- // Find the message index where the last turn starts (last user message)
276- let lastUserIdx = -1;
277- for (let i = session.messages.length - 1; i >= 0; i--) {
278- if (session.messages[i]?.role === "user") {
279- lastUserIdx = i;
280- break;
281- }
282- }
283- if (lastUserIdx === -1) return false;
284-
285- // Trim in-memory DB history
286- session.messages.splice(lastUserIdx);
287-
288- // Trim coreHistory to match — find last user message in coreHistory
289- let coreLastUserIdx = -1;
290- for (let i = coreHistory.length - 1; i >= 0; i--) {
291- if (coreHistory[i]?.role === "user") {
292- coreLastUserIdx = i;
293- break;
294- }
295- }
296- if (coreLastUserIdx !== -1) coreHistory.splice(coreLastUserIdx);
297-
298- // Delete from DB and decrement turn counter
299- const deleted = deleteLastTurn(session.id);
300- if (turnIndex > 0) turnIndex--;
301- return deleted;
302- },
303- connectMcpServer: connectAndAddMcp,
304- };
305- const spinner = new Spinner();
306- let totalIn = 0;
307- let totalOut = 0;
308-
309- // ── Handle initial prompt (non-interactive) ────────────────────────────────
310- if (opts.initialPrompt) {
311- await processUserInput(opts.initialPrompt);
312- }
313-
314- // ── REPL ──────────────────────────────────────────────────────────────────
315- while (true) {
316- let input;
317- try {
318- input = await readline({ cwd });
319- } catch {
320- break;
321- }
322-
323- switch (input.type) {
324- case "eof":
325- writeln(c.dim("Goodbye."));
326- return;
327-
328- case "interrupt":
329- // Just go back to prompt
330- continue;
331-
332- case "command": {
333- const result = await handleCommand(input.command, input.args, cmdCtx);
334- if (result.type === "exit") {
335- writeln(c.dim("Goodbye."));
336- return;
337- }
338- continue;
339- }
340-
341- case "shell": {
342- const out = await runShellPassthrough(input.command, cwd);
343- if (out) {
344- const thisTurn = turnIndex++;
345- const msg: Message = {
346- role: "user",
347- content: `Shell output of \`${input.command}\`:\n\`\`\`\n${out}\n\`\`\``,
348- };
349- session.messages.push(msg);
350- saveMessages(session.id, [msg], thisTurn);
351- coreHistory.push({ role: "user", content: msg.content });
352- }
353- continue;
354- }
355-
356- case "submit":
357- await processUserInput(input.text);
358- continue;
359- }
360- }
361-
362- // ── Process a user message ─────────────────────────────────────────────────
363- async function processUserInput(text: string): Promise<void> {
364- // Resolve @file references
365- const resolvedText = await resolveFileRefs(text, cwd);
366-
367- // Capture turn index for this turn (user + response share the same index)
368- const thisTurn = turnIndex++;
369-
370- const userMsg: Message = { role: "user", content: resolvedText };
371- session.messages.push(userMsg);
372- saveMessages(session.id, [userMsg], thisTurn);
373-
374- // Also push into coreHistory as a raw ModelMessage
375- coreHistory.push({ role: "user", content: resolvedText });
376-
377- const llm = resolveModel(currentModel);
378- const systemPrompt = buildSystemPrompt(cwd);
379-
380- const abortController = new AbortController();
381- const onSigInt = () => abortController.abort();
382- process.once("SIGINT", onSigInt);
383-
384- spinner.start("thinking");
385-
386- const events = runTurn({
387- model: llm,
388- messages: coreHistory,
389- tools: planMode ? [] : tools,
390- systemPrompt,
391- signal: abortController.signal,
392- });
393-
394- const { inputTokens, outputTokens, newMessages } = await renderTurn(
395- events,
396- spinner,
397- );
398- process.removeListener("SIGINT", onSigInt);
399-
400- // newMessages are raw ModelMessage objects — push directly into coreHistory
401- // so subsequent turns have the correct input/output fields.
402- if (newMessages.length > 0) {
403- coreHistory.push(...newMessages);
404- // For DB persistence, store a simplified version (text only is enough
405- // for session resume context — tool call parts are not reconstructed).
406- // eslint-disable-next-line @typescript-eslint/no-explicit-any
407- const dbMsgs: Message[] = newMessages.map((m: any) => {
408- if (typeof m.content === "string") {
409- return { role: m.role as Message["role"], content: m.content };
410- }
411- if (Array.isArray(m.content)) {
412- // Collapse to text content only for DB storage
413- // eslint-disable-next-line @typescript-eslint/no-explicit-any
414- const text = (m.content as any[])
415- .filter((p) => p.type === "text")
416- .map((p) => p.text as string)
417- .join("");
418- return { role: m.role as Message["role"], content: text };
419- }
420- return { role: m.role as Message["role"], content: String(m.content) };
421- });
422- session.messages.push(...dbMsgs);
423- saveMessages(session.id, dbMsgs, thisTurn);
424- }
425-
426- totalIn += inputTokens;
427- totalOut += outputTokens;
428- touchActiveSession(session);
429-
430- // Render status bar
431- const branch = await getGitBranch(cwd);
432- const provider = currentModel.split("/")[0] ?? "";
433- const modelShort = currentModel.split("/").slice(1).join("/");
434- const cwdDisplay = cwd.startsWith(homedir())
435- ? "~" + cwd.slice(homedir().length)
436- : cwd;
437-
438- renderStatusBar({
439- model: modelShort,
440- provider,
441- cwd: cwdDisplay,
442- gitBranch: branch,
443- inputTokens,
444- outputTokens,
445- contextPercent: null,
446- });
447- }
174+ const cwd = opts.cwd;
175+ let currentModel = opts.model;
176+
177+ // Session setup
178+ let session: ActiveSession;
179+ if (opts.sessionId) {
180+ const resumed = resumeSession(opts.sessionId);
181+ if (!resumed) {
182+ renderError(`Session "${opts.sessionId}" not found.`);
183+ process.exit(1);
184+ }
185+ session = resumed;
186+ currentModel = session.model;
187+ renderInfo(`Resumed session ${session.id} (${c.cyan(currentModel)})`);
188+ } else {
189+ session = newSession(currentModel, cwd);
190+ }
191+
192+ // Turn counter — incremented each time processUserInput is called
193+ // Used to group user + assistant messages for undo
194+ let turnIndex = getMaxTurnIndex(session.id) + 1;
195+
196+ // Raw AI SDK ModelMessage history — fed directly to streamText each turn.
197+ // This is kept separate from session.messages (which is DB-persisted text)
198+ // to avoid lossy round-trips through our internal Message type.
199+ const coreHistory: CoreMessage[] = dbMessagesToCore(session.messages);
200+
201+ // Subagent runner (recursive) — depth prevents infinite recursion
202+ const runSubagent = async (
203+ prompt: string,
204+ model?: string,
205+ depth = 0,
206+ ): Promise<{ result: string; inputTokens: number; outputTokens: number }> => {
207+ const subModel = model ?? currentModel;
208+ const subMessages: Message[] = [{ role: "user", content: prompt }];
209+ const subTools = buildToolSet({ cwd, depth, runSubagent });
210+ const subLlm = resolveModel(subModel);
211+ const systemPrompt = buildSystemPrompt(cwd);
212+
213+ let result = "";
214+ let inputTokens = 0;
215+ let outputTokens = 0;
216+
217+ const events = runTurn({
218+ model: subLlm,
219+ messages: dbMessagesToCore(subMessages),
220+ tools: subTools,
221+ systemPrompt,
222+ });
223+
224+ for await (const event of events) {
225+ if (event.type === "text-delta") result += event.delta;
226+ if (event.type === "turn-complete") {
227+ inputTokens = event.inputTokens;
228+ outputTokens = event.outputTokens;
229+ }
230+ }
231+
232+ return { result, inputTokens, outputTokens };
233+ };
234+
235+ // ── MCP: load persisted servers and connect them ───────────────────────────
236+ const tools: ToolDef[] = buildToolSet({ cwd, depth: 0, runSubagent });
237+
238+ async function connectAndAddMcp(name: string): Promise<void> {
239+ const rows = listMcpServers();
240+ const row = rows.find((r) => r.name === name);
241+ if (!row) throw new Error(`MCP server "${name}" not found in DB`);
242+ const cfg: Parameters<typeof connectMcpServer>[0] = {
243+ name: row.name,
244+ transport: row.transport as "http" | "stdio",
245+ ...(row.url ? { url: row.url } : {}),
246+ ...(row.command ? { command: row.command } : {}),
247+ ...(row.args ? { args: JSON.parse(row.args) } : {}),
248+ ...(row.env ? { env: JSON.parse(row.env) } : {}),
249+ };
250+ const client = await connectMcpServer(cfg);
251+ tools.push(...client.tools);
252+ }
253+
254+ // Connect all persisted MCP servers at startup
255+ for (const row of listMcpServers()) {
256+ try {
257+ await connectAndAddMcp(row.name);
258+ renderInfo(`MCP: connected ${c.cyan(row.name)}`);
259+ } catch (e) {
260+ renderError(`MCP: failed to connect ${row.name}: ${String(e)}`);
261+ }
262+ }
263+
264+ let planMode = false;
265+
266+ const cmdCtx: CommandContext = {
267+ get currentModel() {
268+ return currentModel;
269+ },
270+ setModel: (m) => {
271+ currentModel = m;
272+ session.model = m;
273+ setPreferredModel(m);
274+ },
275+ get planMode() {
276+ return planMode;
277+ },
278+ setPlanMode: (v) => {
279+ planMode = v;
280+ },
281+ cwd,
282+ runSubagent: (prompt, model) => runSubagent(prompt, model),
283+ undoLastTurn: () => {
284+ // Nothing to undo if there are no messages
285+ if (session.messages.length === 0) return false;
286+
287+ // Find the message index where the last turn starts (last user message)
288+ let lastUserIdx = -1;
289+ for (let i = session.messages.length - 1; i >= 0; i--) {
290+ if (session.messages[i]?.role === "user") {
291+ lastUserIdx = i;
292+ break;
293+ }
294+ }
295+ if (lastUserIdx === -1) return false;
296+
297+ // Trim in-memory DB history
298+ session.messages.splice(lastUserIdx);
299+
300+ // Trim coreHistory to match — find last user message in coreHistory
301+ let coreLastUserIdx = -1;
302+ for (let i = coreHistory.length - 1; i >= 0; i--) {
303+ if (coreHistory[i]?.role === "user") {
304+ coreLastUserIdx = i;
305+ break;
306+ }
307+ }
308+ if (coreLastUserIdx !== -1) coreHistory.splice(coreLastUserIdx);
309+
310+ // Delete from DB and decrement turn counter
311+ const deleted = deleteLastTurn(session.id);
312+ if (turnIndex > 0) turnIndex--;
313+ return deleted;
314+ },
315+ connectMcpServer: connectAndAddMcp,
316+ };
317+ const spinner = new Spinner();
318+ let totalIn = 0;
319+ let totalOut = 0;
320+
321+ // ── Handle initial prompt (non-interactive) ────────────────────────────────
322+ if (opts.initialPrompt) {
323+ await processUserInput(opts.initialPrompt);
324+ }
325+
326+ // ── REPL ──────────────────────────────────────────────────────────────────
327+ while (true) {
328+ let input: InputResult;
329+ try {
330+ input = await readline({ cwd });
331+ } catch {
332+ break;
333+ }
334+
335+ switch (input.type) {
336+ case "eof":
337+ writeln(c.dim("Goodbye."));
338+ return;
339+
340+ case "interrupt":
341+ // Just go back to prompt
342+ continue;
343+
344+ case "command": {
345+ const result = await handleCommand(input.command, input.args, cmdCtx);
346+ if (result.type === "exit") {
347+ writeln(c.dim("Goodbye."));
348+ return;
349+ }
350+ continue;
351+ }
352+
353+ case "shell": {
354+ const out = await runShellPassthrough(input.command, cwd);
355+ if (out) {
356+ const thisTurn = turnIndex++;
357+ const msg: Message = {
358+ role: "user",
359+ content: `Shell output of \`${input.command}\`:\n\`\`\`\n${out}\n\`\`\``,
360+ };
361+ session.messages.push(msg);
362+ saveMessages(session.id, [msg], thisTurn);
363+ coreHistory.push({ role: "user", content: String(msg.content) });
364+ }
365+ continue;
366+ }
367+
368+ case "submit":
369+ await processUserInput(input.text);
370+ continue;
371+ }
372+ }
373+
374+ // ── Process a user message ─────────────────────────────────────────────────
375+ async function processUserInput(text: string): Promise<void> {
376+ // Resolve @file references
377+ const resolvedText = await resolveFileRefs(text, cwd);
378+
379+ // Capture turn index for this turn (user + response share the same index)
380+ const thisTurn = turnIndex++;
381+
382+ const userMsg: Message = { role: "user", content: resolvedText };
383+ session.messages.push(userMsg);
384+ saveMessages(session.id, [userMsg], thisTurn);
385+
386+ // Also push into coreHistory as a raw ModelMessage
387+ coreHistory.push({ role: "user", content: resolvedText });
388+
389+ const llm = resolveModel(currentModel);
390+ const systemPrompt = buildSystemPrompt(cwd);
391+
392+ const abortController = new AbortController();
393+ const onSigInt = () => abortController.abort();
394+ process.once("SIGINT", onSigInt);
395+
396+ spinner.start("thinking");
397+
398+ const events = runTurn({
399+ model: llm,
400+ messages: coreHistory,
401+ tools: planMode ? [] : tools,
402+ systemPrompt,
403+ signal: abortController.signal,
404+ });
405+
406+ const { inputTokens, outputTokens, newMessages } = await renderTurn(
407+ events,
408+ spinner,
409+ );
410+ process.removeListener("SIGINT", onSigInt);
411+
412+ // newMessages are raw ModelMessage objects — push directly into coreHistory
413+ // so subsequent turns have the correct input/output fields.
414+ if (newMessages.length > 0) {
415+ coreHistory.push(...newMessages);
416+ // For DB persistence, store a simplified version (text only is enough
417+ // for session resume context — tool call parts are not reconstructed).
418+ const dbMsgs: Message[] = newMessages.map((m) => {
419+ const role = m.role as Message["role"];
420+ const content = m.content;
421+ if (typeof content === "string") {
422+ return { role, content };
423+ }
424+ if (Array.isArray(content)) {
425+ // Collapse to text content only for DB storage
426+ const text = content
427+ .filter(isTextPart)
428+ .map((p) => p.text)
429+ .join("");
430+ return { role, content: text };
431+ }
432+ return { role, content: String(content) };
433+ });
434+ session.messages.push(...dbMsgs);
435+ saveMessages(session.id, dbMsgs, thisTurn);
436+ }
437+
438+ totalIn += inputTokens;
439+ totalOut += outputTokens;
440+ touchActiveSession(session);
441+
442+ // Render status bar
443+ const branch = await getGitBranch(cwd);
444+ const provider = currentModel.split("/")[0] ?? "";
445+ const modelShort = currentModel.split("/").slice(1).join("/");
446+ const cwdDisplay = cwd.startsWith(homedir())
447+ ? `~${cwd.slice(homedir().length)}`
448+ : cwd;
449+
450+ renderStatusBar({
451+ model: modelShort,
452+ provider,
453+ cwd: cwdDisplay,
454+ gitBranch: branch,
455+ inputTokens,
456+ outputTokens,
457+ contextPercent: null,
458+ });
459+ }
448460 }
449461
450462 // ─── Resolve @file references in user input ────────────────────────────────────
451463
452464 async function resolveFileRefs(text: string, cwd: string): Promise<string> {
453- // Find all @<path> tokens
454- const atPattern = /@([\w./\-_]+)/g;
455- let result = text;
456- const matches = [...text.matchAll(atPattern)];
457-
458- for (const match of matches.reverse()) {
459- const ref = match[1];
460- if (!ref) continue;
461- const filePath = ref.startsWith("/") ? ref : join(cwd, ref);
462-
463- try {
464- const content = await Bun.file(filePath).text();
465- const lines = content.split("\n");
466- const preview =
467- lines.length > 200
468- ? lines.slice(0, 200).join("\n") + "\n[truncated]"
469- : content;
470- const replacement = `\`${ref}\`:\n\`\`\`\n${preview}\n\`\`\``;
471- result =
472- result.slice(0, match.index) +
473- replacement +
474- result.slice((match.index ?? 0) + match[0].length);
475- } catch {
476- // Leave the @ref as-is if file not found
477- }
478- }
479-
480- return result;
465+ // Find all @<path> tokens
466+ const atPattern = /@([\w./\-_]+)/g;
467+ let result = text;
468+ const matches = [...text.matchAll(atPattern)];
469+
470+ for (const match of matches.reverse()) {
471+ const ref = match[1];
472+ if (!ref) continue;
473+ const filePath = ref.startsWith("/") ? ref : join(cwd, ref);
474+
475+ try {
476+ const content = await Bun.file(filePath).text();
477+ const lines = content.split("\n");
478+ const preview =
479+ lines.length > 200
480+ ? `${lines.slice(0, 200).join("\n")}\n[truncated]`
481+ : content;
482+ const replacement = `\`${ref}\`:\n\`\`\`\n${preview}\n\`\`\``;
483+ result =
484+ result.slice(0, match.index) +
485+ replacement +
486+ result.slice((match.index ?? 0) + match[0].length);
487+ } catch {
488+ // Leave the @ref as-is if file not found
489+ }
490+ }
491+
492+ return result;
481493 }
src/agent/tools.ts+50−46
@@ -1,8 +1,8 @@
11 import type { ToolDef } from "../llm-api/types.ts";
2+import { editTool } from "../tools/edit.ts";
23 import { globTool } from "../tools/glob.ts";
34 import { grepTool } from "../tools/grep.ts";
45 import { readTool } from "../tools/read.ts";
5-import { editTool } from "../tools/edit.ts";
66 import { shellTool } from "../tools/shell.ts";
77 import { createSubagentTool } from "../tools/subagent.ts";
88
@@ -13,20 +13,20 @@ export type ToolHook = (toolName: string, result: unknown) => Promise<void>;
1313 const _hooks: ToolHook[] = [];
1414
1515 export function addToolHook(hook: ToolHook): void {
16- _hooks.push(hook);
16+ _hooks.push(hook);
1717 }
1818
1919 export async function runToolHooks(
20- toolName: string,
21- result: unknown
20+ toolName: string,
21+ result: unknown,
2222 ): 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- }
23+ for (const hook of _hooks) {
24+ try {
25+ await hook(toolName, result);
26+ } catch {
27+ // Hooks must not crash the agent
28+ }
29+ }
3030 }
3131
3232 // ─── Tool registry ────────────────────────────────────────────────────────────
@@ -35,45 +35,49 @@ export async function runToolHooks(
3535 * Wrap a tool's execute function to inject a default cwd if not provided.
3636 */
3737 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- },
Cut short: this commit's diff is over 1000 lines.
src/cli/commands.ts+297−225
Cut short: this commit's diff is over 1000 lines.
src/cli/input.ts+333−313
Cut short: this commit's diff is over 1000 lines.
src/cli/output.ts+474−392
Cut short: this commit's diff is over 1000 lines.
src/index.ts+143−134
Cut short: this commit's diff is over 1000 lines.
src/llm-api/providers.ts+190−181
Cut short: this commit's diff is over 1000 lines.
src/llm-api/turn.ts+155−143
Cut short: this commit's diff is over 1000 lines.
src/llm-api/types.ts+54−56
Cut short: this commit's diff is over 1000 lines.
src/mcp/client.ts+81−76
Cut short: this commit's diff is over 1000 lines.
src/mcp/manager.ts+56−47
Cut short: this commit's diff is over 1000 lines.
src/session/db.ts+154−141
Cut short: this commit's diff is over 1000 lines.
src/session/manager.ts+43−43
Cut short: this commit's diff is over 1000 lines.
src/tools/edit.ts+145−142
Cut short: this commit's diff is over 1000 lines.
src/tools/glob.ts+53−41
Cut short: this commit's diff is over 1000 lines.
src/tools/grep.ts+120−110
Cut short: this commit's diff is over 1000 lines.
src/tools/read.ts+71−67
Cut short: this commit's diff is over 1000 lines.
src/tools/shell.ts+108−100
Cut short: this commit's diff is over 1000 lines.
src/tools/subagent.ts+26−28
Cut short: this commit's diff is over 1000 lines.