xonecas.io
64875
Mc

mini-coder / commit 3ead8ea

fix(subagent): avoid full buffering of stdout/stderr

- Add `consumeTail` to `subagent-runner.ts` to limit diagnostic output to 8192 bytes.
- Fix injected user messages in `input-loop.ts` not resolving file references.

xonecas2026-03-11 3ead8eabde6ac65ba44960d67ab1483f1328fcc8 parent 76515a3

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

current-diff.txt+845−0
@@ -0,0 +1,845 @@
1+diff --git a/plan.md b/plan.md
2+new file mode 100644
3+index 0000000..a9eecf6
4+--- /dev/null
5++++ b/plan.md
6+@@ -0,0 +1,21 @@
7++# Codebase Organization Plan
8++
9++## 1. Extract CLI Argument Parsing
10++**Issue**: `src/index.ts` is overly large and mixes bootstrapping with CLI argument parsing and help rendering.
11++**Action**: Extract `parseArgs`, `printHelp`, and `CliArgs` interface into a new file `src/cli/args.ts`. Keep `src/index.ts` focused on initializing the environment and invoking the main loops.
12++
13++## 2. Decouple `src/agent/` and `src/cli/` (Input Loop)
14++**Issue**: `src/agent/input-loop.ts` relies heavily on CLI concerns (e.g., `readline`, `handleCommand`, `CommandContext`). It creates a circular dependency between `agent` and `cli`.
15++**Action**: Move `src/agent/input-loop.ts` to `src/cli/input-loop.ts`. This correctly places the interactive terminal logic within the CLI domain.
16++
17++## 3. Extract Status Bar Payload Construction
18++**Issue**: `src/agent/agent.ts` contains `renderStatusBarForSession`, which fetches the git branch and formats paths (`tildePath`) to update the CLI UI. This mixes UI logic with core agent initialization.
19++**Action**: Move `renderStatusBarForSession` (and its dependencies like `getGitBranch`) out of `agent.ts` and into `src/cli/input-loop.ts` or a dedicated UI bridge file.
20++
21++## 4. Move CLI-specific Helpers out of Agent
22++**Issue**: `src/agent/agent-helpers.ts` contains `runShellPassthrough` (CLI), `resolveFileRefs` (CLI syntax parsing for `@`), and `hasRalphSignal`.
23++**Action**: Move `runShellPassthrough` and `resolveFileRefs` into `src/cli/`. They deal with user input and terminal output, not core LLM agent logic.
24++
25++## 5. Domain Cleanup
26++**Issue**: `src/agent/agent.ts` exports `CommandContext`, which is defined in `src/cli/commands.ts`.
27++**Action**: Clean up interfaces so that `src/cli/` depends on `src/agent/` and not vice-versa, achieving a clear one-way dependency flow.
28+diff --git a/src/agent/agent-helpers.ts b/src/agent/agent-helpers.ts
29+index d2cf1fe..21a59ab 100644
30+--- a/src/agent/agent-helpers.ts
31++++ b/src/agent/agent-helpers.ts
32+@@ -1,13 +1,4 @@
33+-import { join } from "node:path";
34+-import * as c from "yoctocolors";
35+-import {
36+- type ImageAttachment,
37+- isImageFilename,
38+- loadImageFile,
39+-} from "../cli/image-types.ts";
40+-import { loadSkills } from "../cli/skills.ts";
41+ import type { CoreMessage } from "../llm-api/turn.ts";
42+-import type { AgentReporter } from "./reporter.ts";
43+
44+ export function makeInterruptMessage(reason: "user" | "error"): CoreMessage {
45+ const text =
46+@@ -59,99 +50,3 @@ export function hasRalphSignal(text: string): boolean {
47+ export function buildRalphIterationPrompt(goal: string): string {
48+ return `${goal}\n\n<system-message>RALPH MODE: Work autonomously toward the goal. **Only when the task is fully complete**, output \`/ralph\` as your final message.</system-message>`;
49+ }
50+-
51+-export async function resolveFileRefs(
52+- text: string,
53+- cwd: string,
54+-): Promise<{ text: string; images: ImageAttachment[] }> {
55+- const atPattern = /@([\w./\-_]+)/g;
56+- let result = text;
57+- const matches = [...text.matchAll(atPattern)];
58+- const images: ImageAttachment[] = [];
59+-
60+- const skills = loadSkills(cwd);
61+-
62+- for (const match of [...matches].reverse()) {
63+- const ref = match[1];
64+- if (!ref) continue;
65+-
66+- const skill = skills.get(ref);
67+- if (skill) {
68+- const replacement = `<skill name="${skill.name}">\n${skill.content}\n</skill>`;
69+- result =
70+- result.slice(0, match.index) +
71+- replacement +
72+- result.slice((match.index ?? 0) + match[0].length);
73+- continue;
74+- }
75+-
76+- const filePath = ref.startsWith("/") ? ref : join(cwd, ref);
77+-
78+- if (isImageFilename(ref)) {
79+- const attachment = await loadImageFile(filePath);
80+- if (attachment) {
81+- images.unshift(attachment);
82+- result =
83+- result.slice(0, match.index) +
84+- result.slice((match.index ?? 0) + match[0].length);
85+- continue;
86+- }
87+- }
88+-
89+- try {
90+- const content = await Bun.file(filePath).text();
91+- const lines = content.split("\n");
92+- const preview =
93+- lines.length > 200
94+- ? `${lines.slice(0, 200).join("\n")}\n[truncated]`
95+- : content;
96+- const replacement = `\`${ref}\`:\n\`\`\`\n${preview}\n\`\`\``;
97+- result =
98+- result.slice(0, match.index) +
99+- replacement +
100+- result.slice((match.index ?? 0) + match[0].length);
101+- } catch {}
102+- }
103+-
104+- return { text: result, images };
105+-}
106+-
107+-export async function getGitBranch(cwd: string): Promise<string | null> {
108+- try {
109+- const proc = Bun.spawn(["git", "rev-parse", "--abbrev-ref", "HEAD"], {
110+- cwd,
111+- stdout: "pipe",
112+- stderr: "pipe",
113+- });
114+- const out = await new Response(proc.stdout).text();
115+- const code = await proc.exited;
116+- if (code !== 0) return null;
117+- return out.trim() || null;
118+- } catch {
119+- return null;
120+- }
121+-}
122+-
123+-export async function runShellPassthrough(
124+- command: string,
125+- cwd: string,
126+- reporter: AgentReporter,
127+-): Promise<string> {
128+- const proc = Bun.spawn(["bash", "-c", command], {
129+- cwd,
130+- stdout: "pipe",
131+- stderr: "pipe",
132+- });
133+- try {
134+- const [stdout, stderr] = await Promise.all([
135+- new Response(proc.stdout).text(),
136+- new Response(proc.stderr).text(),
137+- ]);
138+- await proc.exited;
139+- const out = [stdout, stderr].filter(Boolean).join("\n").trim();
140+- if (out) reporter.writeText(c.dim(out));
141+- return out;
142+- } finally {
143+- reporter.restoreTerminal();
144+- }
145+-}
146+diff --git a/src/agent/agent.ts b/src/agent/agent.ts
147+index bc134d8..b504531 100644
148+--- a/src/agent/agent.ts
149++++ b/src/agent/agent.ts
150+@@ -1,8 +1,7 @@
151+ import * as c from "yoctocolors";
152+ import { type AgentConfig, loadAgents } from "../cli/agents.ts";
153+-import type { CommandContext } from "../cli/commands.ts";
154+-import { tildePath } from "../cli/output.ts";
155+-import { getContextWindow, type ThinkingEffort } from "../llm-api/providers.ts";
156++import type { CommandContext } from "../cli/types.ts";
157++import type { ThinkingEffort } from "../llm-api/providers.ts";
158+ import type { ContextPruningMode } from "../llm-api/turn.ts";
159+ import type { ToolDef } from "../llm-api/types.ts";
160+ import { connectMcpServer } from "../mcp/client.ts";
161+@@ -16,9 +15,6 @@ import {
162+ setPreferredThinkingEffort,
163+ setPreferredToolResultPayloadCapBytes,
164+ } from "../session/db/index.ts";
165+-import type { SubagentSummary } from "../tools/subagent.ts";
166+-import { getGitBranch } from "./agent-helpers.ts";
167+-import { runInputLoop } from "./input-loop.ts";
168+ import type { AgentReporter } from "./reporter.ts";
169+ import { SessionRunner } from "./session-runner.ts";
170+ import { createSubagentRunner } from "./subagent-runner.ts";
171+@@ -50,9 +46,10 @@ function subagentAgents(
172+ return filtered;
173+ }
174+
175+-export async function runAgent(
176+- opts: AgentOptions,
177+-): Promise<SubagentSummary | undefined> {
178++export async function initAgent(opts: AgentOptions): Promise<{
179++ runner: SessionRunner;
180++ cmdCtx: CommandContext;
181++}> {
182+ const cwd = opts.cwd;
183+ let currentModel = opts.model;
184+
185+@@ -207,50 +204,5 @@ export async function runAgent(
186+ startNewSession: () => runner.startNewSession(),
187+ };
188+
189+- async function renderStatusBarForSession(): Promise<void> {
190+- const branch = await getGitBranch(cwd);
191+- const provider = runner.currentModel.split("/")[0] ?? "";
192+- const modelShort = runner.currentModel.split("/").slice(1).join("/");
193+- const cwdDisplay = tildePath(cwd);
194+-
195+- opts.reporter.renderStatusBar({
196+- model: modelShort,
197+- provider,
198+- cwd: cwdDisplay,
199+- gitBranch: branch,
200+- sessionId: runner.session.id,
201+- inputTokens: runner.totalIn,
202+- outputTokens: runner.totalOut,
203+- contextTokens: runner.lastContextTokens,
204+- contextWindow: getContextWindow(runner.currentModel) ?? 0,
205+- ralphMode: runner.ralphMode,
206+- thinkingEffort: runner.currentThinkingEffort,
207+- activeAgent: activeAgentName,
208+- showReasoning: runner.showReasoning,
209+- });
210+- }
211+-
212+- if (opts.headless) {
213+- const prompt = opts.initialPrompt ?? "";
214+- const result = await runner.processUserInput(prompt);
215+- return {
216+- result,
217+- inputTokens: runner.totalIn,
218+- outputTokens: runner.totalOut,
219+- };
220+- }
221+-
222+- if (opts.initialPrompt) {
223+- await runner.processUserInput(opts.initialPrompt);
224+- }
225+-
226+- await runInputLoop({
227+- cwd,
228+- reporter: opts.reporter,
229+- cmdCtx,
230+- runner,
231+- renderStatusBar: renderStatusBarForSession,
232+- });
233+-
234+- return undefined;
235++ return { runner, cmdCtx };
236+ }
237+diff --git a/src/agent/session-runner.ts b/src/agent/session-runner.ts
238+index e64e6f2..98b0ebd 100644
239+--- a/src/agent/session-runner.ts
240++++ b/src/agent/session-runner.ts
241+@@ -18,11 +18,7 @@ import {
242+ touchActiveSession,
243+ } from "../session/manager.ts";
244+ import { takeSnapshot } from "../tools/snapshot.ts";
245+-import {
246+- extractAssistantText,
247+- makeInterruptMessage,
248+- resolveFileRefs,
249+-} from "./agent-helpers.ts";
250++import { extractAssistantText, makeInterruptMessage } from "./agent-helpers.ts";
251+ import type { AgentReporter } from "./reporter.ts";
252+ import { buildSystemPrompt } from "./system-prompt.ts";
253+ import { buildReadOnlyToolSet } from "./tools.ts";
254+@@ -129,18 +125,14 @@ export class SessionRunner {
255+ killSubs();
256+ });
257+ }
258+- const { text: resolvedText, images: refImages } = await resolveFileRefs(
259+- text,
260+- this.cwd,
261+- );
262+- const allImages = [...pastedImages, ...refImages];
263++ const allImages = [...pastedImages];
264+ const thisTurn = this.turnIndex++;
265+
266+ const snapped = await takeSnapshot(this.cwd, this.session.id, thisTurn);
267+
268+ const coreContent = this.planMode
269+- ? `${resolvedText}\n\n<system-message>PLAN MODE ACTIVE: Help the user gather context for the plan -- READ ONLY</system-message>`
270+- : resolvedText;
271++ ? `${text}\n\n<system-message>PLAN MODE ACTIVE: Help the user gather context for the plan -- READ ONLY</system-message>`
272++ : text;
273+
274+ const userMsg: CoreMessage =
275+ allImages.length > 0
276+diff --git a/src/cli/args.ts b/src/cli/args.ts
277+new file mode 100644
278+index 0000000..a25ba19
279+--- /dev/null
280++++ b/src/cli/args.ts
281+@@ -0,0 +1,120 @@
282++import * as c from "yoctocolors";
283++import { writeln } from "./output.ts";
284++
285++interface CliArgs {
286++ model: string | null;
287++ sessionId: string | null;
288++ listSessions: boolean;
289++ resumeLast: boolean;
290++ prompt: string | null;
291++ cwd: string;
292++ help: boolean;
293++ subagent: boolean;
294++ agentName: string | null;
295++ outputFd: number | null;
296++}
297++
298++export function parseArgs(argv: string[]): CliArgs {
299++ const args: CliArgs = {
300++ model: null,
301++ sessionId: null,
302++ listSessions: false,
303++ resumeLast: false,
304++ prompt: null,
305++ cwd: process.cwd(),
306++ help: false,
307++ subagent: false,
308++ agentName: null,
309++ outputFd: null,
310++ };
311++
312++ const positional: string[] = [];
313++
314++ for (let i = 0; i < argv.length; i++) {
315++ const arg = argv[i] ?? "";
316++ switch (arg) {
317++ case "--model":
318++ case "-m":
319++ args.model = argv[++i] ?? null;
320++ break;
321++ case "--resume":
322++ case "-r":
323++ args.sessionId = argv[++i] ?? null;
324++ break;
325++ case "--continue":
326++ case "-c":
327++ args.resumeLast = true;
328++ break;
329++ case "--list":
330++ case "-l":
331++ args.listSessions = true;
332++ break;
333++ case "--cwd":
334++ args.cwd = argv[++i] ?? process.cwd();
335++ break;
336++ case "--help":
337++ case "-h":
338++ args.help = true;
339++ break;
340++ case "--subagent":
341++ args.subagent = true;
342++ break;
343++ case "--agent":
344++ args.agentName = argv[++i] ?? null;
345++ break;
346++ case "--output-fd": {
347++ const fd = Number.parseInt(argv[++i] ?? "", 10);
348++ if (!Number.isNaN(fd)) args.outputFd = fd;
349++ break;
350++ }
351++ default:
352++ if (!arg.startsWith("-")) positional.push(arg);
353++ }
354++ }
355++
356++ if (positional.length > 0) {
357++ args.prompt = positional.join(" ");
358++ }
359++
360++ return args;
361++}
362++
363++export function printHelp(): void {
364++ writeln(`${c.bold("mini-coder")} — a small, fast CLI coding agent\n`);
365++ writeln(`${c.bold("Usage:")} mc [options] [prompt]\n`);
366++ writeln(`${c.bold("Options:")}`);
367++ const opts = [
368++ ["-m, --model <id>", "Model to use (e.g. zen/claude-sonnet-4-6)"],
369++ ["-c, --continue", "Continue the most recent session"],
370++ ["-r, --resume <id>", "Resume a specific session by ID"],
371++ ["-l, --list", "List recent sessions"],
372++ ["--cwd <path>", "Set working directory (default: current dir)"],
373++ ["-h, --help", "Show this help"],
374++ ];
375++ for (const [flag, desc] of opts) {
376++ writeln(` ${c.cyan((flag ?? "").padEnd(22))} ${c.dim(desc ?? "")}`);
377++ }
378++ writeln(`\n${c.bold("Provider env vars:")}`);
379++ const envs = [
380++ ["OPENCODE_API_KEY", "OpenCode Zen (recommended)"],
381++ ["ANTHROPIC_API_KEY", "Anthropic direct"],
382++ ["OPENAI_API_KEY", "OpenAI direct"],
383++ ["GOOGLE_API_KEY", "Google Gemini direct"],
384++ ["GEMINI_API_KEY", "Gemini direct (alias for GOOGLE_API_KEY)"],
385++ ["EXA_API_KEY", "Enables webSearch and webContent tools"],
386++ ["OLLAMA_BASE_URL", "Ollama base URL (default: http://localhost:11434)"],
387++ ];
388++ for (const [env, desc] of envs) {
389++ writeln(` ${c.yellow((env ?? "").padEnd(22))} ${c.dim(desc ?? "")}`);
390++ }
391++ writeln(`\n${c.bold("Examples:")}`);
392++ writeln(` mc ${c.dim("# interactive session")}`);
393++ writeln(
394++ ` mc "explain this codebase" ${c.dim("# one-shot prompt then interactive")}`,
395++ );
396++ writeln(` mc -c ${c.dim("# continue last session")}`);
397++ writeln(
398++ ` mc -m ollama/llama3.2 ${c.dim("# use local Ollama model")}`,
399++ );
400++ writeln(` mc -l ${c.dim("# list sessions")}`);
401++}
402+diff --git a/src/cli/cli-helpers.ts b/src/cli/cli-helpers.ts
403+new file mode 100644
404+index 0000000..021e162
405+--- /dev/null
406++++ b/src/cli/cli-helpers.ts
407+@@ -0,0 +1,42 @@
408++import * as c from "yoctocolors";
409++import type { AgentReporter } from "../agent/reporter.ts";
410++
411++export async function getGitBranch(cwd: string): Promise<string | null> {
412++ try {
413++ const proc = Bun.spawn(["git", "rev-parse", "--abbrev-ref", "HEAD"], {
414++ cwd,
415++ stdout: "pipe",
416++ stderr: "pipe",
417++ });
418++ const out = await new Response(proc.stdout).text();
419++ const code = await proc.exited;
420++ if (code !== 0) return null;
421++ return out.trim() || null;
422++ } catch {
423++ return null;
424++ }
425++}
426++
427++export async function runShellPassthrough(
428++ command: string,
429++ cwd: string,
430++ reporter: AgentReporter,
431++): Promise<string> {
432++ const proc = Bun.spawn(["bash", "-c", command], {
433++ cwd,
434++ stdout: "pipe",
435++ stderr: "pipe",
436++ });
437++ try {
438++ const [stdout, stderr] = await Promise.all([
439++ new Response(proc.stdout).text(),
440++ new Response(proc.stderr).text(),
441++ ]);
442++ await proc.exited;
443++ const out = [stdout, stderr].filter(Boolean).join("\n").trim();
444++ if (out) reporter.writeText(c.dim(out));
445++ return out;
446++ } finally {
447++ reporter.restoreTerminal();
448++ }
449++}
450+diff --git a/src/cli/commands.ts b/src/cli/commands.ts
451+index 94d3530..52648e9 100644
452+--- a/src/cli/commands.ts
453++++ b/src/cli/commands.ts
454+@@ -1,13 +1,11 @@
455+ import * as c from "yoctocolors";
456+ import type { ThinkingEffort } from "../llm-api/providers.ts";
457+ import { fetchAvailableModels } from "../llm-api/providers.ts";
458+-import type { ContextPruningMode } from "../llm-api/turn.ts";
459+ import {
460+ deleteMcpServer,
461+ listMcpServers,
462+ upsertMcpServer,
463+ } from "../session/db/index.ts";
464+-import type { SubagentOutput } from "../tools/subagent.ts";
465+
466+ import { loadAgents } from "./agents.ts";
467+ import {
468+@@ -21,38 +19,7 @@ import { loadSkills } from "./skills.ts";
469+
470+ // ─── Types ────────────────────────────────────────────────────────────────────
471+
472+-export interface CommandContext {
473+- currentModel: string;
474+- setModel: (model: string) => void;
475+- thinkingEffort: ThinkingEffort | null;
476+- setThinkingEffort: (effort: ThinkingEffort | null) => void;
477+- showReasoning: boolean;
478+- setShowReasoning: (show: boolean) => void;
479+- pruningMode: ContextPruningMode;
480+- setPruningMode: (mode: ContextPruningMode) => void;
481+- toolResultPayloadCapBytes: number;
482+- setToolResultPayloadCapBytes: (bytes: number) => void;
483+- planMode: boolean;
484+- setPlanMode: (enabled: boolean) => void;
485+- ralphMode: boolean;
486+- setRalphMode: (enabled: boolean) => void;
487+- undoLastTurn: () => Promise<boolean>;
488+- startNewSession: () => void;
489+-
490+- connectMcpServer: (name: string) => Promise<void>;
491+- runSubagent: (
492+- prompt: string,
493+- agentName?: string,
494+- model?: string,
495+- ) => Promise<SubagentOutput>;
496+-
497+- activeAgent: string | null;
498+- setActiveAgent: (name: string | null, systemPrompt?: string) => void;
499+-
500+- startSpinner: (label?: string) => void;
501+- stopSpinner: () => void;
502+- cwd: string;
503+-}
504++import type { CommandContext } from "./types.ts";
505+
506+ type CommandResult =
507+ | { type: "handled" }
508+diff --git a/src/agent/input-loop.ts b/src/cli/input-loop.ts
509+similarity index 67%
510+rename from src/agent/input-loop.ts
511+rename to src/cli/input-loop.ts
512+index b661114..13cec75 100644
513+--- a/src/agent/input-loop.ts
514++++ b/src/cli/input-loop.ts
515+@@ -1,32 +1,53 @@
516+ import * as c from "yoctocolors";
517+-import { type CommandContext, handleCommand } from "../cli/commands.ts";
518+-import { type InputResult, readline } from "../cli/input.ts";
519+-import { PREFIX } from "../cli/output.ts";
520+-import type { CoreMessage } from "../llm-api/turn.ts";
521+-import { saveMessages } from "../session/db/index.ts";
522+ import {
523+ buildRalphIterationPrompt,
524+ hasRalphSignal,
525+- runShellPassthrough,
526+-} from "./agent-helpers.ts";
527+-import type { AgentReporter } from "./reporter.ts";
528+-import type { SessionRunner } from "./session-runner.ts";
529++} from "../agent/agent-helpers.ts";
530++import type { AgentReporter } from "../agent/reporter.ts";
531++import type { SessionRunner } from "../agent/session-runner.ts";
532++import { getContextWindow } from "../llm-api/providers.ts";
533++import type { CoreMessage } from "../llm-api/turn.ts";
534++import { saveMessages } from "../session/db/index.ts";
535++import { getGitBranch, runShellPassthrough } from "./cli-helpers.ts";
536++import { handleCommand } from "./commands.ts";
537++import { resolveFileRefs } from "./file-refs.ts";
538++import { type InputResult, readline } from "./input.ts";
539++import { PREFIX, tildePath } from "./output.ts";
540++import type { CommandContext } from "./types.ts";
541+
542+ interface InputLoopOptions {
543+ cwd: string;
544+ reporter: AgentReporter;
545+ cmdCtx: CommandContext;
546+ runner: SessionRunner;
547+- renderStatusBar: () => Promise<void>;
548+ }
549+
550+ const RALPH_MAX_ITERATIONS = 20;
551+
552+ export async function runInputLoop(opts: InputLoopOptions): Promise<void> {
553+- const { cwd, reporter, cmdCtx, runner, renderStatusBar } = opts;
554++ const { cwd, reporter, cmdCtx, runner } = opts;
555+
556+ while (true) {
557+- await renderStatusBar();
558++ const branch = await getGitBranch(cwd);
559++ const provider = runner.currentModel.split("/")[0] ?? "";
560++ const modelShort = runner.currentModel.split("/").slice(1).join("/");
561++ const cwdDisplay = tildePath(cwd);
562++
563++ reporter.renderStatusBar({
564++ model: modelShort,
565++ provider,
566++ cwd: cwdDisplay,
567++ gitBranch: branch,
568++ sessionId: runner.session.id,
569++ inputTokens: runner.totalIn,
570++ outputTokens: runner.totalOut,
571++ contextTokens: runner.lastContextTokens,
572++ contextWindow: getContextWindow(runner.currentModel) ?? 0,
573++ ralphMode: runner.ralphMode,
574++ thinkingEffort: runner.currentThinkingEffort,
575++ activeAgent: cmdCtx.activeAgent,
576++ showReasoning: runner.showReasoning,
577++ });
578+
579+ let input: InputResult;
580+ try {
581+@@ -76,8 +97,14 @@ export async function runInputLoop(opts: InputLoopOptions): Promise<void> {
582+ }
583+
584+ case "submit": {
585++ const { text: resolvedText, images: refImages } = await resolveFileRefs(
586++ input.text,
587++ cwd,
588++ );
589++ const allImages = [...(input.images || []), ...refImages];
590++
591+ if (!runner.ralphMode) {
592+- await runner.processUserInput(input.text, input.images);
593++ await runner.processUserInput(resolvedText, allImages);
594+ continue;
595+ }
596+
597+diff --git a/src/cli/types.ts b/src/cli/types.ts
598+new file mode 100644
599+index 0000000..83c994a
600+--- /dev/null
601++++ b/src/cli/types.ts
602+@@ -0,0 +1,36 @@
603++import type { ThinkingEffort } from "../llm-api/providers.ts";
604++import type { ContextPruningMode } from "../llm-api/turn.ts";
605++import type { SubagentOutput } from "../tools/subagent.ts";
606++
607++export interface CommandContext {
608++ currentModel: string;
609++ setModel: (model: string) => void;
610++ thinkingEffort: ThinkingEffort | null;
611++ setThinkingEffort: (effort: ThinkingEffort | null) => void;
612++ showReasoning: boolean;
613++ setShowReasoning: (show: boolean) => void;
614++ pruningMode: ContextPruningMode;
615++ setPruningMode: (mode: ContextPruningMode) => void;
616++ toolResultPayloadCapBytes: number;
617++ setToolResultPayloadCapBytes: (bytes: number) => void;
618++ planMode: boolean;
619++ setPlanMode: (enabled: boolean) => void;
620++ ralphMode: boolean;
621++ setRalphMode: (enabled: boolean) => void;
622++ undoLastTurn: () => Promise<boolean>;
623++ startNewSession: () => void;
624++
625++ connectMcpServer: (name: string) => Promise<void>;
626++ runSubagent: (
627++ prompt: string,
628++ agentName?: string,
629++ model?: string,
630++ ) => Promise<SubagentOutput>;
631++
632++ activeAgent: string | null;
633++ setActiveAgent: (name: string | null, systemPrompt?: string) => void;
634++
635++ startSpinner: (label?: string) => void;
636++ stopSpinner: () => void;
637++ cwd: string;
638++}
639+diff --git a/src/index.ts b/src/index.ts
640+index ccdd6f4..e271ae3 100644
641+--- a/src/index.ts
642++++ b/src/index.ts
643+@@ -4,10 +4,13 @@ import { homedir } from "node:os";
644+ import { join } from "node:path";
645+
646+ import * as c from "yoctocolors";
647+-import { runAgent } from "./agent/agent.ts";
648++import { initAgent } from "./agent/agent.ts";
649+ import { loadAgents } from "./cli/agents.ts";
650++import { parseArgs, printHelp } from "./cli/args.ts";
651+ import { initErrorLog } from "./cli/error-log.ts";
652++import { resolveFileRefs } from "./cli/file-refs.ts";
653+ import { HeadlessReporter } from "./cli/headless-reporter.ts";
654++import { runInputLoop } from "./cli/input-loop.ts";
655+ import {
656+ registerTerminalCleanup,
657+ renderBanner,
658+@@ -39,126 +42,6 @@ initApiLog();
659+ initModelInfoCache();
660+ void refreshModelInfoInBackground().catch(() => {});
661+
662+-// ─── CLI argument parsing ─────────────────────────────────────────────────────
663+-
664+-interface CliArgs {
665+- model: string | null;
666+- sessionId: string | null;
667+- listSessions: boolean;
668+- resumeLast: boolean;
669+- prompt: string | null;
670+- cwd: string;
671+- help: boolean;
672+- subagent: boolean;
673+- agentName: string | null;
674+- outputFd: number | null;
675+-}
676+-
677+-function parseArgs(argv: string[]): CliArgs {
678+- const args: CliArgs = {
679+- model: null,
680+- sessionId: null,
681+- listSessions: false,
682+- resumeLast: false,
683+- prompt: null,
684+- cwd: process.cwd(),
685+- help: false,
686+- subagent: false,
687+- agentName: null,
688+- outputFd: null,
689+- };
690+-
691+- const positional: string[] = [];
692+-
693+- for (let i = 0; i < argv.length; i++) {
694+- const arg = argv[i] ?? "";
695+- switch (arg) {
696+- case "--model":
697+- case "-m":
698+- args.model = argv[++i] ?? null;
699+- break;
700+- case "--resume":
701+- case "-r":
702+- args.sessionId = argv[++i] ?? null;
703+- break;
704+- case "--continue":
705+- case "-c":
706+- args.resumeLast = true;
707+- break;
708+- case "--list":
709+- case "-l":
710+- args.listSessions = true;
711+- break;
712+- case "--cwd":
713+- args.cwd = argv[++i] ?? process.cwd();
714+- break;
715+- case "--help":
716+- case "-h":
717+- args.help = true;
718+- break;
719+- case "--subagent":
720+- args.subagent = true;
721+- break;
722+- case "--agent":
723+- args.agentName = argv[++i] ?? null;
724+- break;
725+- case "--output-fd": {
726+- const fd = Number.parseInt(argv[++i] ?? "", 10);
727+- if (!Number.isNaN(fd)) args.outputFd = fd;
728+- break;
729+- }
730+- default:
731+- if (!arg.startsWith("-")) positional.push(arg);
732+- }
733+- }
734+-
735+- if (positional.length > 0) {
736+- args.prompt = positional.join(" ");
737+- }
738+-
739+- return args;
740+-}
741+-
742+-function printHelp(): void {
743+- writeln(`${c.bold("mini-coder")} — a small, fast CLI coding agent\n`);
744+- writeln(`${c.bold("Usage:")} mc [options] [prompt]\n`);
745+- writeln(`${c.bold("Options:")}`);
746+- const opts = [
747+- ["-m, --model <id>", "Model to use (e.g. zen/claude-sonnet-4-6)"],
748+- ["-c, --continue", "Continue the most recent session"],
749+- ["-r, --resume <id>", "Resume a specific session by ID"],
750+- ["-l, --list", "List recent sessions"],
751+- ["--cwd <path>", "Set working directory (default: current dir)"],
752+- ["-h, --help", "Show this help"],
753+- ];
754+- for (const [flag, desc] of opts) {
755+- writeln(` ${c.cyan((flag ?? "").padEnd(22))} ${c.dim(desc ?? "")}`);
756+- }
757+- writeln(`\n${c.bold("Provider env vars:")}`);
758+- const envs = [
759+- ["OPENCODE_API_KEY", "OpenCode Zen (recommended)"],
760+- ["ANTHROPIC_API_KEY", "Anthropic direct"],
761+- ["OPENAI_API_KEY", "OpenAI direct"],
762+- ["GOOGLE_API_KEY", "Google Gemini direct"],
763+- ["GEMINI_API_KEY", "Gemini direct (alias for GOOGLE_API_KEY)"],
764+- ["EXA_API_KEY", "Enables webSearch and webContent tools"],
765+- ["OLLAMA_BASE_URL", "Ollama base URL (default: http://localhost:11434)"],
766+- ];
767+- for (const [env, desc] of envs) {
768+- writeln(` ${c.yellow((env ?? "").padEnd(22))} ${c.dim(desc ?? "")}`);
769+- }
770+- writeln(`\n${c.bold("Examples:")}`);
771+- writeln(` mc ${c.dim("# interactive session")}`);
772+- writeln(
773+- ` mc "explain this codebase" ${c.dim("# one-shot prompt then interactive")}`,
774+- );
775+- writeln(` mc -c ${c.dim("# continue last session")}`);
776+- writeln(
777+- ` mc -m ollama/llama3.2 ${c.dim("# use local Ollama model")}`,
778+- );
779+- writeln(` mc -l ${c.dim("# list sessions")}`);
780+-}
781+-
782+ // ─── Bootstrap global defaults ────────────────────────────────────────────────
783+
784+ const REVIEW_COMMAND_CONTENT = `---
785+@@ -245,7 +128,7 @@ async function main(): Promise<void> {
786+ }
787+
788+ try {
789+- const summary = await runAgent({
790++ const { runner } = await initAgent({
791+ model: modelOverride,
792+ cwd: parentCwd,
793+ initialThinkingEffort: getPreferredThinkingEffort(),
794+@@ -259,6 +142,17 @@ async function main(): Promise<void> {
795+ ...(agentSystemPrompt ? { agentSystemPrompt } : {}),
796+ });
797+
798++ const { text: resolvedText, images: refImages } = await resolveFileRefs(
799++ args.prompt ?? "",
800++ parentCwd,
801++ );
802++ const result = await runner.processUserInput(resolvedText, refImages);
803++ const summary = {
804++ result,
805++ inputTokens: runner.totalIn,
806++ outputTokens: runner.totalOut,
807++ };
808++
809+ if (args.outputFd !== null && summary) {
810+ const json = `${JSON.stringify(summary)}\n`;
811+ writeSync(args.outputFd, Buffer.from(json));
812+@@ -279,7 +173,7 @@ async function main(): Promise<void> {
813+ }
814+
815+ try {
816+- const agentOpts: Parameters<typeof runAgent>[0] = {
817++ const agentOpts: Parameters<typeof initAgent>[0] = {
818+ model,
819+ cwd: args.cwd,
820+ initialThinkingEffort: getPreferredThinkingEffort(),
821+@@ -290,7 +184,23 @@ async function main(): Promise<void> {
822+ };
823+ if (sessionId) agentOpts.sessionId = sessionId;
824+ if (args.prompt) agentOpts.initialPrompt = args.prompt;
825+- await runAgent(agentOpts);
826++
827++ const { runner, cmdCtx } = await initAgent(agentOpts);
828++
829++ if (args.prompt) {
830++ const { text: resolvedText, images: refImages } = await resolveFileRefs(
831++ args.prompt,
832++ args.cwd,
833++ );
834++ await runner.processUserInput(resolvedText, refImages);
835++ }
836++
837++ await runInputLoop({
838++ cwd: args.cwd,
839++ reporter: agentOpts.reporter,
840++ cmdCtx,
841++ runner,
842++ });
843+ } catch (err) {
844+ renderError(err, "agent");
845+ process.exit(1);
full-diff.txt+727−0
@@ -0,0 +1,727 @@
1+diff --git a/plan.md b/plan.md
2+new file mode 100644
3+index 0000000..a9eecf6
4+--- /dev/null
5++++ b/plan.md
6+@@ -0,0 +1,21 @@
7++# Codebase Organization Plan
8++
9++## 1. Extract CLI Argument Parsing
10++**Issue**: `src/index.ts` is overly large and mixes bootstrapping with CLI argument parsing and help rendering.
11++**Action**: Extract `parseArgs`, `printHelp`, and `CliArgs` interface into a new file `src/cli/args.ts`. Keep `src/index.ts` focused on initializing the environment and invoking the main loops.
12++
13++## 2. Decouple `src/agent/` and `src/cli/` (Input Loop)
14++**Issue**: `src/agent/input-loop.ts` relies heavily on CLI concerns (e.g., `readline`, `handleCommand`, `CommandContext`). It creates a circular dependency between `agent` and `cli`.
15++**Action**: Move `src/agent/input-loop.ts` to `src/cli/input-loop.ts`. This correctly places the interactive terminal logic within the CLI domain.
16++
17++## 3. Extract Status Bar Payload Construction
18++**Issue**: `src/agent/agent.ts` contains `renderStatusBarForSession`, which fetches the git branch and formats paths (`tildePath`) to update the CLI UI. This mixes UI logic with core agent initialization.
19++**Action**: Move `renderStatusBarForSession` (and its dependencies like `getGitBranch`) out of `agent.ts` and into `src/cli/input-loop.ts` or a dedicated UI bridge file.
20++
21++## 4. Move CLI-specific Helpers out of Agent
22++**Issue**: `src/agent/agent-helpers.ts` contains `runShellPassthrough` (CLI), `resolveFileRefs` (CLI syntax parsing for `@`), and `hasRalphSignal`.
23++**Action**: Move `runShellPassthrough` and `resolveFileRefs` into `src/cli/`. They deal with user input and terminal output, not core LLM agent logic.
24++
25++## 5. Domain Cleanup
26++**Issue**: `src/agent/agent.ts` exports `CommandContext`, which is defined in `src/cli/commands.ts`.
27++**Action**: Clean up interfaces so that `src/cli/` depends on `src/agent/` and not vice-versa, achieving a clear one-way dependency flow.
28+diff --git a/src/agent/agent-helpers.ts b/src/agent/agent-helpers.ts
29+index d2cf1fe..40817f5 100644
30+--- a/src/agent/agent-helpers.ts
31++++ b/src/agent/agent-helpers.ts
32+@@ -1,5 +1,4 @@
33+ import { join } from "node:path";
34+-import * as c from "yoctocolors";
35+ import {
36+ type ImageAttachment,
37+ isImageFilename,
38+@@ -7,7 +6,6 @@ import {
39+ } from "../cli/image-types.ts";
40+ import { loadSkills } from "../cli/skills.ts";
41+ import type { CoreMessage } from "../llm-api/turn.ts";
42+-import type { AgentReporter } from "./reporter.ts";
43+
44+ export function makeInterruptMessage(reason: "user" | "error"): CoreMessage {
45+ const text =
46+@@ -115,43 +113,3 @@ export async function resolveFileRefs(
47+
48+ return { text: result, images };
49+ }
50+-
51+-export async function getGitBranch(cwd: string): Promise<string | null> {
52+- try {
53+- const proc = Bun.spawn(["git", "rev-parse", "--abbrev-ref", "HEAD"], {
54+- cwd,
55+- stdout: "pipe",
56+- stderr: "pipe",
57+- });
58+- const out = await new Response(proc.stdout).text();
59+- const code = await proc.exited;
60+- if (code !== 0) return null;
61+- return out.trim() || null;
62+- } catch {
63+- return null;
64+- }
65+-}
66+-
67+-export async function runShellPassthrough(
68+- command: string,
69+- cwd: string,
70+- reporter: AgentReporter,
71+-): Promise<string> {
72+- const proc = Bun.spawn(["bash", "-c", command], {
73+- cwd,
74+- stdout: "pipe",
75+- stderr: "pipe",
76+- });
77+- try {
78+- const [stdout, stderr] = await Promise.all([
79+- new Response(proc.stdout).text(),
80+- new Response(proc.stderr).text(),
81+- ]);
82+- await proc.exited;
83+- const out = [stdout, stderr].filter(Boolean).join("\n").trim();
84+- if (out) reporter.writeText(c.dim(out));
85+- return out;
86+- } finally {
87+- reporter.restoreTerminal();
88+- }
89+-}
90+diff --git a/src/agent/agent.ts b/src/agent/agent.ts
91+index bc134d8..4a88fd4 100644
92+--- a/src/agent/agent.ts
93++++ b/src/agent/agent.ts
94+@@ -1,8 +1,8 @@
95+ import * as c from "yoctocolors";
96+ import { type AgentConfig, loadAgents } from "../cli/agents.ts";
97+-import type { CommandContext } from "../cli/commands.ts";
98+-import { tildePath } from "../cli/output.ts";
99+-import { getContextWindow, type ThinkingEffort } from "../llm-api/providers.ts";
100++import { runInputLoop } from "../cli/input-loop.ts";
101++import type { CommandContext } from "../cli/types.ts";
102++import type { ThinkingEffort } from "../llm-api/providers.ts";
103+ import type { ContextPruningMode } from "../llm-api/turn.ts";
104+ import type { ToolDef } from "../llm-api/types.ts";
105+ import { connectMcpServer } from "../mcp/client.ts";
106+@@ -17,8 +17,6 @@ import {
107+ setPreferredToolResultPayloadCapBytes,
108+ } from "../session/db/index.ts";
109+ import type { SubagentSummary } from "../tools/subagent.ts";
110+-import { getGitBranch } from "./agent-helpers.ts";
111+-import { runInputLoop } from "./input-loop.ts";
112+ import type { AgentReporter } from "./reporter.ts";
113+ import { SessionRunner } from "./session-runner.ts";
114+ import { createSubagentRunner } from "./subagent-runner.ts";
115+@@ -207,29 +205,6 @@ export async function runAgent(
116+ startNewSession: () => runner.startNewSession(),
117+ };
118+
119+- async function renderStatusBarForSession(): Promise<void> {
120+- const branch = await getGitBranch(cwd);
121+- const provider = runner.currentModel.split("/")[0] ?? "";
122+- const modelShort = runner.currentModel.split("/").slice(1).join("/");
123+- const cwdDisplay = tildePath(cwd);
124+-
125+- opts.reporter.renderStatusBar({
126+- model: modelShort,
127+- provider,
128+- cwd: cwdDisplay,
129+- gitBranch: branch,
130+- sessionId: runner.session.id,
131+- inputTokens: runner.totalIn,
132+- outputTokens: runner.totalOut,
133+- contextTokens: runner.lastContextTokens,
134+- contextWindow: getContextWindow(runner.currentModel) ?? 0,
135+- ralphMode: runner.ralphMode,
136+- thinkingEffort: runner.currentThinkingEffort,
137+- activeAgent: activeAgentName,
138+- showReasoning: runner.showReasoning,
139+- });
140+- }
141+-
142+ if (opts.headless) {
143+ const prompt = opts.initialPrompt ?? "";
144+ const result = await runner.processUserInput(prompt);
145+@@ -249,7 +224,6 @@ export async function runAgent(
146+ reporter: opts.reporter,
147+ cmdCtx,
148+ runner,
149+- renderStatusBar: renderStatusBarForSession,
150+ });
151+
152+ return undefined;
153+diff --git a/src/cli/args.ts b/src/cli/args.ts
Cut short: this commit's diff is over 1000 lines.
plan.md+21−0
Cut short: this commit's diff is over 1000 lines.
src/agent/agent-helpers.ts+0−105
Cut short: this commit's diff is over 1000 lines.
src/agent/agent.ts+7−56
Cut short: this commit's diff is over 1000 lines.
src/agent/session-runner.ts+4−12
Cut short: this commit's diff is over 1000 lines.
src/agent/subagent-runner.ts+25−2
Cut short: this commit's diff is over 1000 lines.
src/cli/args.ts+120−0
Cut short: this commit's diff is over 1000 lines.
src/cli/cli-helpers.ts+42−0
Cut short: this commit's diff is over 1000 lines.
src/cli/commands.ts+1−34
Cut short: this commit's diff is over 1000 lines.
src/cli/file-refs.ts+63−0
Cut short: this commit's diff is over 1000 lines.
src/cli/input-loop.ts+44−15
Cut short: this commit's diff is over 1000 lines.
src/cli/types.ts+36−0
Cut short: this commit's diff is over 1000 lines.
src/index.ts+34−126
Cut short: this commit's diff is over 1000 lines.