xonecas.io
64875
Mc

mini-coder / commit 2910efe

refactor: decompose agent and CLI modules for code health

- Split `src/agent/agent.ts` into modular files (`session-runner`, `subagent-runner`, `input-loop`, `undo-snapshot`, etc.).
- Extract rendering and formatting responsibilities from `src/cli/output.ts` into specialized modules (`tool-render`, `stream-render`, `spinner`, etc.).
- Consolidate raw TTY and terminal signal handling in `TerminalIO`.
- Split `src/session/db` logic into per-domain repositories (`message-repo`, `session-repo`, `snapshot-repo`, etc.).
- Centralize markdown config loading in `src/cli/load-markdown-configs.ts` and DRY up `agents`, `skills`, and `custom-commands`.
- Use `describe.skipIf` for cleaner TTY checks in tests.

Sean2026-03-01 2910efe32c4e8bca1aae7ad19d6fe51b4a50fcfc parent 6d66632

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

TODO.md+32−0
@@ -1,5 +1,37 @@
11 # TODO
22
3+## Fatal error when using grep:
4+
5+```
6+ ? grep export const PREFIX
7+✖ undefined is not an object (evaluating 'r.matches.length')
8+error: script "dev" exited with code 1
9+```
10+Session id: mm81zgi6
11+
12+```
13+ ? grep process\.std i
14+✖ undefined is not an object (evaluating 'r.matches.length')
15+error: script "dev" exited with code 1
16+```
17+Session id: mm82xtos
18+
19+## Mini coder hanged after shell tool call:
20+
21+```
22+ $ $ rm src/session/db.ts && bun run test
23+⠇ shell
24+```
25+
26+Stayed spinning with shell label for well over the timeout time. I had to use ctrl+c to return to the prompt:
27+
28+```
29+ $ $ rm src/session/db.ts && bun run test
30+error: script "dev" exited with code 130
31+```
32+
33+App exited instead of returning to the prompt.
34+
335 ## Help agent edits error less:
436
537 - Agents sometimes include `|` at the end of the hash, this is because how we display the hashed to them, let's check if the anchor last char is `|` and strip it if it instead of letting it error.
src/agent/agent-helpers.ts+134−0
@@ -0,0 +1,134 @@
1+import { join } from "node:path";
2+import * as c from "yoctocolors";
3+import {
4+ type ImageAttachment,
5+ isImageFilename,
6+ loadImageFile,
7+} from "../cli/image-types.ts";
8+import { loadSkills } from "../cli/skills.ts";
9+import type { CoreMessage } from "../llm-api/turn.ts";
10+import type { AgentReporter } from "./reporter.ts";
11+
12+export function makeInterruptMessage(reason: "user" | "error"): CoreMessage {
13+ const text =
14+ reason === "user"
15+ ? "<system-message>Response was interrupted by the user.</system-message>"
16+ : "<system-message>Response was interrupted due to an error.</system-message>";
17+ return { role: "assistant", content: text };
18+}
19+
20+export function extractAssistantText(newMessages: CoreMessage[]): string {
21+ const parts: string[] = [];
22+ for (const msg of newMessages) {
23+ if (msg.role !== "assistant") continue;
24+ const content = msg.content;
25+ if (typeof content === "string") {
26+ parts.push(content);
27+ } else if (Array.isArray(content)) {
28+ for (const part of content as Array<{ type?: string; text?: string }>) {
29+ if (part?.type === "text" && part.text) parts.push(part.text);
30+ }
31+ }
32+ }
33+ return parts.join("\n");
34+}
35+
36+export function hasRalphSignal(text: string): boolean {
37+ return /\/ralph\b/.test(text);
38+}
39+
40+export async function resolveFileRefs(
41+ text: string,
42+ cwd: string,
43+): Promise<{ text: string; images: ImageAttachment[] }> {
44+ const atPattern = /@([\w./\-_]+)/g;
45+ let result = text;
46+ const matches = [...text.matchAll(atPattern)];
47+ const images: ImageAttachment[] = [];
48+
49+ const skills = loadSkills(cwd);
50+
51+ for (const match of [...matches].reverse()) {
52+ const ref = match[1];
53+ if (!ref) continue;
54+
55+ const skill = skills.get(ref);
56+ if (skill) {
57+ const replacement = `<skill name="${skill.name}">\n${skill.content}\n</skill>`;
58+ result =
59+ result.slice(0, match.index) +
60+ replacement +
61+ result.slice((match.index ?? 0) + match[0].length);
62+ continue;
63+ }
64+
65+ const filePath = ref.startsWith("/") ? ref : join(cwd, ref);
66+
67+ if (isImageFilename(ref)) {
68+ const attachment = await loadImageFile(filePath);
69+ if (attachment) {
70+ images.unshift(attachment);
71+ result =
72+ result.slice(0, match.index) +
73+ result.slice((match.index ?? 0) + match[0].length);
74+ continue;
75+ }
76+ }
77+
78+ try {
79+ const content = await Bun.file(filePath).text();
80+ const lines = content.split("\n");
81+ const preview =
82+ lines.length > 200
83+ ? `${lines.slice(0, 200).join("\n")}\n[truncated]`
84+ : content;
85+ const replacement = `\`${ref}\`:\n\`\`\`\n${preview}\n\`\`\``;
86+ result =
87+ result.slice(0, match.index) +
88+ replacement +
89+ result.slice((match.index ?? 0) + match[0].length);
90+ } catch {}
91+ }
92+
93+ return { text: result, images };
94+}
95+
96+export async function getGitBranch(cwd: string): Promise<string | null> {
97+ try {
98+ const proc = Bun.spawn(["git", "rev-parse", "--abbrev-ref", "HEAD"], {
99+ cwd,
100+ stdout: "pipe",
101+ stderr: "pipe",
102+ });
103+ const out = await new Response(proc.stdout).text();
104+ const code = await proc.exited;
105+ if (code !== 0) return null;
106+ return out.trim() || null;
107+ } catch {
108+ return null;
109+ }
110+}
111+
112+export async function runShellPassthrough(
113+ command: string,
114+ cwd: string,
115+ reporter: AgentReporter,
116+): Promise<string> {
117+ const proc = Bun.spawn(["bash", "-c", command], {
118+ cwd,
119+ stdout: "pipe",
120+ stderr: "pipe",
121+ });
122+ try {
123+ const [stdout, stderr] = await Promise.all([
124+ new Response(proc.stdout).text(),
125+ new Response(proc.stderr).text(),
126+ ]);
127+ await proc.exited;
128+ const out = [stdout, stderr].filter(Boolean).join("\n").trim();
129+ if (out) reporter.writeText(c.dim(out));
130+ return out;
131+ } finally {
132+ reporter.restoreTerminal();
133+ }
134+}
src/agent/agent.test.ts+1−1
@@ -4,7 +4,7 @@ import {
44 extractAssistantText,
55 hasRalphSignal,
66 makeInterruptMessage,
7-} from "./agent.ts";
7+} from "./agent-helpers.ts";
88
99 // ─── extractAssistantText ─────────────────────────────────────────────────────
1010
src/agent/agent.ts+74−671
@@ -11,19 +11,12 @@ import {
1111 import { readline, type InputResult, watchForInterrupt } from "../cli/input.ts";
1212 import {
1313 PREFIX,
14- Spinner,
1514 formatSubagentLabel,
16- renderError,
17- renderHook,
18- renderInfo,
19- renderStatusBar,
20- renderSubagentEvent,
21- renderTurn,
22- restoreTerminal,
2315 tildePath,
2416 writeln,
2517 } from "../cli/output.ts";
2618 import { loadSkills } from "../cli/skills.ts";
19+import type { AgentReporter } from "./reporter.ts";
2720
2821 import {
2922 getContextWindow,
@@ -49,7 +42,7 @@ import {
4942 listMcpServers,
5043 saveMessages,
5144 setPreferredModel,
52-} from "../session/db.ts";
45+} from "../session/db/index.ts";
5346
5447 import {
5548 type ActiveSession,
@@ -57,238 +50,47 @@ import {
5750 resumeSession,
5851 touchActiveSession,
5952 } from "../session/manager.ts";
53+import { createSubagentRunner } from "./subagent-runner.ts";
6054 import { buildReadOnlyToolSet, buildToolSet } from "./tools.ts";
55+import { undoLastTurn } from "./undo-snapshot.ts";
6156
62-// ─── Git branch detection ─────────────────────────────────────────────────────
63-
64-async function getGitBranch(cwd: string): Promise<string | null> {
65- try {
66- const proc = Bun.spawn(["git", "rev-parse", "--abbrev-ref", "HEAD"], {
67- cwd,
68- stdout: "pipe",
69- stderr: "pipe",
70- });
71- const out = await new Response(proc.stdout).text();
72- const code = await proc.exited;
73- if (code !== 0) return null;
74- return out.trim() || null;
75- } catch {
76- return null;
77- }
78-}
79-
80-// ─── Context file discovery (AGENTS.md / CLAUDE.md) ──────────────────────────
81-
82-function loadContextFile(cwd: string): string | null {
83- const candidates = [
84- join(cwd, "AGENTS.md"),
85- join(cwd, "CLAUDE.md"),
86- join(getConfigDir(), "AGENTS.md"),
87- ];
88- for (const p of candidates) {
89- if (existsSync(p)) {
90- try {
91- return readFileSync(p, "utf-8");
92- } catch {
93- // skip
94- }
95- }
96- }
97- return null;
98-}
99-
100-// ─── System prompt ────────────────────────────────────────────────────────────
101-
102-// Extra directives injected when the model is a Codex variant.
103-// Codex is RLHF-tuned to be collaborative and permission-seeking by default;
104-// without these overrides it will read a few files, describe what it *plans*
105-// to do, and then stop — even in ralph mode. The Responses API `instructions`
106-// field (used for all gpt-* models) is the authoritative channel for these.
107-const CODEX_AUTONOMY = `
108-# Autonomy and persistence
109-- You are an autonomous senior engineer. Once given a direction, proactively gather context, implement, test, and refine without waiting for additional prompts at each step.
110-- Persist until the task is fully handled end-to-end within the current turn: do not stop at analysis or partial work; carry changes through to implementation and verification.
111-- Bias to action: default to implementing with reasonable assumptions. Do not end your turn with clarifications or requests to "proceed" unless you are truly blocked on information only the user can provide.
112-- Do NOT output an upfront plan, preamble, or status update before working. Start making tool calls immediately.
113-- Do NOT ask "shall I proceed?", "shall I start?", "reply X to continue", or any equivalent. Just start.
114-- If something is ambiguous, pick the most reasonable interpretation, implement it, and note the assumption at the end.`;
115-
116-function isCodexModel(modelString: string): boolean {
117- const { modelId } = parseModelString(modelString);
118- return modelId.includes("codex");
119-}
120-
121-function buildSystemPrompt(cwd: string, modelString?: string): string {
122- const contextFile = loadContextFile(cwd);
123- const cwdDisplay = tildePath(cwd);
124- const now = new Date().toLocaleString(undefined, { hour12: false });
125-
126- let prompt = `You are mini-coder, a small and fast CLI coding agent.
127-You have access to tools to read files, search code, make edits, run shell commands, and spawn subagents.
128-
129-Current working directory: ${cwdDisplay}
130-Current date/time: ${now}
131-
132-Guidelines:
133-- Be concise and precise. Avoid unnecessary preamble.
134-- Prefer small, targeted edits over large rewrites.
135-- Always read a file before editing it.
136-- Use glob to discover files, grep to find patterns, read to inspect contents.
137-- Use shell for tests, builds, and git operations.`;
138-
139- if (modelString && isCodexModel(modelString)) {
140- prompt += CODEX_AUTONOMY;
141- }
142-
143- if (contextFile) {
144- prompt += `\n\n# Project context\n\n${contextFile}`;
145- }
146-
147- return prompt;
148-}
149-
150-// ─── Shell passthrough (! prefix) ─────────────────────────────────────────────
151-
152-async function runShellPassthrough(
153- command: string,
154- cwd: string,
155-): Promise<string> {
156- const proc = Bun.spawn(["bash", "-c", command], {
157- cwd,
158- stdout: "pipe",
159- stderr: "pipe",
160- });
161- try {
162- const [stdout, stderr] = await Promise.all([
163- new Response(proc.stdout).text(),
164- new Response(proc.stderr).text(),
165- ]);
166- await proc.exited;
167- const out = [stdout, stderr].filter(Boolean).join("\n").trim();
168- if (out) writeln(c.dim(out));
169- return out;
170- } finally {
171- restoreTerminal();
172- }
173-}
174-
175-// ─── Main agent run ───────────────────────────────────────────────────────────
57+import {
58+ extractAssistantText,
59+ getGitBranch,
60+ hasRalphSignal,
61+ makeInterruptMessage,
62+ resolveFileRefs,
63+ runShellPassthrough,
64+} from "./agent-helpers.ts";
65+import { buildSystemPrompt } from "./system-prompt.ts";
66+
67+import { runInputLoop } from "./input-loop.ts";
68+import { SessionRunner } from "./session-runner.ts";
17669
17770 export interface AgentOptions {
17871 model: string;
17972 cwd: string;
180- sessionId?: string; // resume existing
181- initialPrompt?: string; // non-interactive first message
73+ sessionId?: string;
74+ initialPrompt?: string;
75+ reporter: AgentReporter;
18276 }
18377
18478 export async function runAgent(opts: AgentOptions): Promise<void> {
18579 const cwd = opts.cwd;
18680 let currentModel = opts.model;
18781
188- // Session setup
189- let session: ActiveSession;
190- if (opts.sessionId) {
191- const resumed = resumeSession(opts.sessionId);
192- if (!resumed) {
193- renderError(`Session "${opts.sessionId}" not found.`);
194- process.exit(1);
195- }
196- session = resumed;
197- currentModel = session.model;
198- // Orphaned snapshot rows from a previous run can never be reached by the
199- // fresh in-memory snapshotStack — delete them so they don't accumulate.
200- deleteAllSnapshots(session.id);
201- renderInfo(`Resumed session ${session.id} (${c.cyan(currentModel)})`);
202- } else {
203- session = newSession(currentModel, cwd);
204- }
205-
206- // Turn counter — incremented each time processUserInput is called
207- // Used to group user + assistant messages for undo
208- let turnIndex = getMaxTurnIndex(session.id) + 1;
209-
210- // Raw AI SDK ModelMessage history — fed directly to streamText each turn.
211- // This is kept separate from session.messages (DB-persisted CoreMessages)
212- // so we can trim or rebuild without mutating the in-memory DB copy.
213- const coreHistory: CoreMessage[] = [...session.messages];
214-
215- let nextLaneId = 1;
216- const activeLanes = new Set<number>();
217-
218- // Subagent runner (recursive) — depth prevents infinite recursion.
219- // agentName: optional custom agent to run (looks up .agents/agents/<name>.md).
220- // modelOverride: explicit model to use (for /review and custom commands).
221- const runSubagent = async (
222- prompt: string,
223- depth = 0,
224- agentName?: string,
225- modelOverride?: string,
226- parentLabel?: string,
227- ): Promise<SubagentOutput> => {
228- // Resolve custom agent config if an agentName was specified
229- const allAgents = loadAgents(cwd);
230- const agentConfig = agentName ? allAgents.get(agentName) : undefined;
231- if (agentName && !agentConfig) {
232- throw new Error(
233- `Unknown agent "${agentName}". Available agents: ${[...allAgents.keys()].join(", ") || "(none)"}`,
234- );
235- }
236-
237- const model = modelOverride ?? agentConfig?.model ?? currentModel;
238- const systemPrompt =
239- agentConfig?.systemPrompt ?? buildSystemPrompt(cwd, model);
240-
241- const subMessages: CoreMessage[] = [{ role: "user", content: prompt }];
242- const laneId = nextLaneId++;
243- activeLanes.add(laneId);
244- const laneLabel = formatSubagentLabel(laneId, parentLabel);
245-
246- const subTools = buildToolSet({
247- cwd,
248- depth,
249- runSubagent,
250- onHook: renderHook,
251- availableAgents: allAgents,
252- parentLabel: laneLabel,
253- });
254-
255- const subLlm = resolveModel(model);
256-
257- let result = "";
258- let inputTokens = 0;
259- let outputTokens = 0;
260-
261- const events = runTurn({
262- model: subLlm,
263- modelString: model,
264- messages: subMessages,
265- tools: subTools,
266- systemPrompt,
267- });
268-
269- for await (const event of events) {
270- spinner.stop();
271- renderSubagentEvent(event, { laneId, parentLabel, activeLanes });
272- spinner.start("thinking");
273- if (event.type === "text-delta") result += event.delta;
274- if (event.type === "turn-complete") {
275- inputTokens = event.inputTokens;
276- outputTokens = event.outputTokens;
277- }
278- }
279-
280- activeLanes.delete(laneId);
281- return { result, inputTokens, outputTokens };
282- };
283-
284- // ── MCP: load persisted servers and connect them ───────────────────────────
82+ const runSubagent = createSubagentRunner(
83+ cwd,
84+ opts.reporter,
85+ () => currentModel,
86+ );
28587
28688 const agents = loadAgents(cwd);
28789 const tools: ToolDef[] = buildToolSet({
28890 cwd,
28991 depth: 0,
29092 runSubagent,
291- onHook: renderHook,
93+ onHook: (tool, path, ok) => opts.reporter.renderHook(tool, path, ok),
29294 availableAgents: agents,
29395 });
29496
@@ -311,493 +113,94 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
311113 mcpTools.push(...client.tools);
312114 }
313115
314- // Connect all persisted MCP servers at startup
315116 for (const row of listMcpServers()) {
316117 try {
317118 await connectAndAddMcp(row.name);
318- renderInfo(`MCP: connected ${c.cyan(row.name)}`);
119+ opts.reporter.info(`MCP: connected ${c.cyan(row.name)}`);
319120 } catch (e) {
320- renderError(`MCP: failed to connect ${row.name}: ${String(e)}`);
121+ opts.reporter.error(`MCP: failed to connect ${row.name}: ${String(e)}`);
321122 }
322123 }
323124
324- let planMode = false;
325- let ralphMode = false;
125+ const runner = new SessionRunner({
126+ cwd,
127+ reporter: opts.reporter,
128+ tools,
129+ mcpTools,
130+ initialModel: currentModel,
131+ sessionId: opts.sessionId,
132+ });
326133
327134 const cmdCtx: CommandContext = {
328135 get currentModel() {
329- return currentModel;
136+ return runner.currentModel;
330137 },
331138 setModel: (m) => {
332- currentModel = m;
333- session.model = m;
139+ runner.currentModel = m;
140+ runner.session.model = m;
334141 setPreferredModel(m);
142+ currentModel = m; // Update local reference for runSubagent
335143 },
336144 get planMode() {
337- return planMode;
145+ return runner.planMode;
338146 },
339147 get ralphMode() {
340- return ralphMode;
148+ return runner.ralphMode;
341149 },
342150 setRalphMode: (v) => {
343- ralphMode = v;
151+ runner.ralphMode = v;
344152 },
345153 setPlanMode: (v) => {
346- planMode = v;
154+ runner.planMode = v;
347155 },
348156 cwd,
349- // depth=0: custom commands are user-initiated, not LLM-initiated, so they
350- // don't consume the recursion depth guard (which only applies to the LLM
351- // subagent tool calling itself).
352- // model? is an optional override for /review and custom commands.
353157 runSubagent: (prompt, model?) => runSubagent(prompt, 0, undefined, model),
354158
355- undoLastTurn: async () => {
356- // Nothing to undo if there are no messages
357- if (session.messages.length === 0) return false;
358-
359- // Find the message index where the last turn starts (last user message)
360- let lastUserIdx = -1;
361- for (let i = session.messages.length - 1; i >= 0; i--) {
362- if (session.messages[i]?.role === "user") {
363- lastUserIdx = i;
364- break;
365- }
366- }
367- if (lastUserIdx === -1) return false;
368-
369- // Trim in-memory DB history
370- session.messages.splice(lastUserIdx);
371-
372- // Trim coreHistory to match — find last user message in coreHistory
373- let coreLastUserIdx = -1;
374- for (let i = coreHistory.length - 1; i >= 0; i--) {
375- if (coreHistory[i]?.role === "user") {
376- coreLastUserIdx = i;
377- break;
378- }
379- }
380- if (coreLastUserIdx !== -1) coreHistory.splice(coreLastUserIdx);
381-
382- // Delete from DB and decrement turn counter
383- const deleted = deleteLastTurn(session.id);
384- const poppedTurn = snapshotStack.pop() ?? null;
385- if (turnIndex > 0) turnIndex--;
386-
387- // Restore files from the SQLite snapshot for the turn being undone
388- if (poppedTurn !== null) {
389- const restoreResult: SnapshotRestoreResult = await restoreSnapshot(
390- cwd,
391- session.id,
392- poppedTurn,
393- );
394- if (
395- restoreResult.restored === false &&
396- restoreResult.reason === "error"
397- ) {
398- renderError(
399- "snapshot restore failed — some files may not have been reverted",
400- );
401- }
402- }
403-
404- return deleted;
405- },
159+ undoLastTurn: () =>
160+ undoLastTurn({
161+ session: runner.session,
162+ coreHistory: runner.coreHistory,
163+ snapshotStack: runner.snapshotStack,
164+ getTurnIndex: () => runner.turnIndex,
165+ setTurnIndex: (idx) => {
166+ runner.turnIndex = idx;
167+ },
168+ cwd,
169+ reporter: opts.reporter,
170+ }),
406171 connectMcpServer: connectAndAddMcp,
407- startNewSession: () => {
408- deleteAllSnapshots(session.id);
409- session = newSession(currentModel, cwd);
410- coreHistory.length = 0;
411- turnIndex = 1;
412- totalIn = 0;
413- totalOut = 0;
414- lastContextTokens = 0;
415- snapshotStack.length = 0;
416- },
172+ startNewSession: () => runner.startNewSession(),
417173 };
418- const spinner = new Spinner();
419- let totalIn = 0;
420- let totalOut = 0;
421- let lastContextTokens = 0;
422- // Stack aligned 1:1 with turns. Each processUserInput pushes the turn index
423- // when a snapshot was created, or null when the tree was clean. Each
424- // undoLastTurn pops the top so the indices always correspond to the right turn.
425- const snapshotStack: Array<number | null> = [];
426-
427- // ── Handle initial prompt (non-interactive) ────────────────────────────────
428- if (opts.initialPrompt) {
429- await processUserInput(opts.initialPrompt);
430- }
431-
432- // ── REPL ──────────────────────────────────────────────────────────────────
433- while (true) {
434- // Render the status bar to stdout before drawing the prompt so both are on
435- // the same stream, guaranteeing correct ordering (no stderr/stdout race).
436- await renderStatusBarForSession();
437-
438- let input: InputResult;
439- try {
440- input = await readline({ cwd, planMode, ralphMode });
441- } catch {
442- break;
443- }
444-
445- switch (input.type) {
446- case "eof":
447- writeln(c.dim("Goodbye."));
448- return;
449-
450- case "interrupt":
451- // Just go back to prompt
452- continue;
453-
454- case "command": {
455- const result = await handleCommand(input.command, input.args, cmdCtx);
456- if (result.type === "exit") {
457- writeln(c.dim("Goodbye."));
458- return;
459- }
460- if (result.type === "inject-user-message") {
461- await processUserInput(result.text);
462- }
463- continue;
464- }
465-
466- case "shell": {
467- const out = await runShellPassthrough(input.command, cwd);
468- if (out) {
469- const thisTurn = turnIndex++;
470- const msg: CoreMessage = {
471- role: "user",
472- content: `Shell output of \`${input.command}\`:\n\`\`\`\n${out}\n\`\`\``,
473- };
474- session.messages.push(msg);
475- saveMessages(session.id, [msg], thisTurn);
476- coreHistory.push(msg);
477- }
478- continue;
479- }
480-
481- case "submit": {
482- const RALPH_MAX_ITERATIONS = 20;
483- let ralphIteration = 1;
484- let lastText = await processUserInput(input.text, input.images);
485-
486- if (ralphMode) {
487- const goal = input.text;
488- const goalImages = input.images;
489- while (ralphMode) {
490- // If the LLM signalled done, stop before starting another iteration.
491- if (hasRalphSignal(lastText)) {
492- ralphMode = false;
493- writeln(`${PREFIX.info} ${c.dim("ralph mode off")}`);
494- break;
495- }
496- if (ralphIteration >= RALPH_MAX_ITERATIONS) {
497- writeln(
498- `${PREFIX.info} ${c.yellow("ralph")} ${c.dim("— max iterations reached, stopping")}`,
499- );
500- ralphMode = false;
501- break;
502- }
503- ralphIteration++;
504- cmdCtx.startNewSession();
505- lastText = await processUserInput(goal, goalImages);
506- }
507- }
508- continue;
509- }
510- }
511- }
512-
513- // ── Process a user message ─────────────────────────────────────────────────
514- async function processUserInput(
515- text: string,
516- pastedImages: ImageAttachment[] = [],
517- ): Promise<string> {
518- // Watch for Ctrl+C by reading raw stdin bytes. This is more reliable than
519- // SIGINT listeners in Bun: when stdin is in raw mode, the OS sends 0x03
520- // directly instead of raising a signal that Bun may intercept or swallow.
521- const abortController = new AbortController();
522- let wasAborted = false;
523- abortController.signal.addEventListener("abort", () => {
524- wasAborted = true;
525- });
526- const stopWatcher = watchForInterrupt(abortController);
527-
528- // Resolve @file/skill references (agent refs are left as-is for the LLM)
529- const { text: resolvedText, images: refImages } = await resolveFileRefs(
530- text,
531- cwd,
532- );
533-
534- // Merge pasted images with @-ref images
535- const allImages = [...pastedImages, ...refImages];
536-
537- // Capture turn index for this turn (user + response share the same index)
538- const thisTurn = turnIndex++;
539-
540- // Snapshot working tree before anything is persisted or sent to the LLM.
541- // Saves dirty file contents to SQLite so /undo can restore them without
542- // touching git stash or the user's working tree state.
543- const snapped = await takeSnapshot(cwd, session.id, thisTurn);
544-
545- const coreContent = planMode
546- ? `${resolvedText}\n\n<system-message>PLAN MODE ACTIVE: Help the user gather context for the plan -- READ ONLY</system-message>`
547- : ralphMode
548- ? `${resolvedText}\n\n<system-message>RALPH MODE: You are in an autonomous loop. You MUST make actual file changes (create, edit, or write files) to complete the requested task before outputting \`/ralph\`. Reading files, running tests, or exploring the codebase does NOT count as doing the work. Only output \`/ralph\` as your final message after all requested changes are implemented and tests pass.</system-message>`
549- : resolvedText;
550-
551- // Build the message content — multi-part when images are present
552- const userMsg: CoreMessage =
553- allImages.length > 0
554- ? {
555- role: "user",
556- content: [
557- { type: "text", text: coreContent },
558- ...allImages.map((img) => ({
559- type: "image" as const,
560- image: img.data,
561- mediaType: img.mediaType,
562- })),
563- ],
564- }
565- : { role: "user", content: coreContent };
566-
567- // If CTRL+C was pressed during the async preamble, still save the user
568- // message and a stub assistant reply so the turn stays in history.
569- // /undo is the only way to erase a turn.
570- if (wasAborted) {
571- stopWatcher();
572- const stubMsg = makeInterruptMessage("user");
573- session.messages.push(userMsg, stubMsg);
574- saveMessages(session.id, [userMsg, stubMsg], thisTurn);
575- coreHistory.push(userMsg, stubMsg);
576- snapshotStack.push(snapped ? thisTurn : null);
577- touchActiveSession(session);
578- return "";
579- }
580-
581- session.messages.push(userMsg);
582- saveMessages(session.id, [userMsg], thisTurn);
583- coreHistory.push(userMsg);
584-
585- const llm = resolveModel(currentModel);
586- const systemPrompt = buildSystemPrompt(cwd, currentModel);
587-
588- let lastAssistantText = "";
589- // Tracks whether the catch block stub has already been saved, to avoid
590- // double-appending if somehow both paths fire.
591- let errorStubSaved = false;
592-
593- try {
594- // Always push so the stack stays aligned 1:1 with turns. A null entry means
595- // the tree was clean at snapshot time — /undo will roll back conversation
596- // history but skip file restoration for that turn.
597- snapshotStack.push(snapped ? thisTurn : null);
598-
599- spinner.start("thinking");
600-
601- const events = runTurn({
602- model: llm,
603- modelString: currentModel,
604- messages: coreHistory,
605- tools: planMode
606- ? [...buildReadOnlyToolSet({ cwd }), ...mcpTools]
607- : tools,
608- systemPrompt,
609- signal: abortController.signal,
610- });
611-
612- const { inputTokens, outputTokens, contextTokens, newMessages } =
613- await renderTurn(events, spinner);
614174
615- // newMessages are raw ModelMessage objects — push directly into coreHistory
616- // so subsequent turns have the correct input/output fields.
617- if (newMessages.length > 0) {
618- coreHistory.push(...newMessages);
619- session.messages.push(...newMessages);
620- saveMessages(session.id, newMessages, thisTurn);
621- if (wasAborted) {
622- // Had partial content — append a system message block so the model
623- // knows the response was cut short. /undo is the only way to erase.
624- const note = makeInterruptMessage("user");
625- coreHistory.push(note);
626- session.messages.push(note);
627- saveMessages(session.id, [note], thisTurn);
628- }
629- } else {
630- // No messages returned — interrupted before any content. Save a
631- // synthetic assistant message. /undo is the only way to erase a turn.
632- const stubMsg = makeInterruptMessage("user");
633- coreHistory.push(stubMsg);
634- session.messages.push(stubMsg);
635- saveMessages(session.id, [stubMsg], thisTurn);
636- }
637-
638- // Collect all assistant text from this turn so the ralph loop can detect
639- // the /ralph signal even when the final action was a tool call.
640- lastAssistantText = extractAssistantText(newMessages);
641-
642- totalIn += inputTokens;
643- totalOut += outputTokens;
644- lastContextTokens = contextTokens;
645- touchActiveSession(session);
646- } catch (err) {
647- // Unexpected throw (network failure, etc.). Append a system message block
648- // so history stays valid. /undo is the only way to erase a turn.
649- if (!errorStubSaved) {
650- errorStubSaved = true;
651- const stubMsg = makeInterruptMessage("error");
652- coreHistory.push(stubMsg);
653- session.messages.push(stubMsg);
654- saveMessages(session.id, [stubMsg], thisTurn);
655- }
656- throw err;
657- } finally {
658- stopWatcher();
659- // Stop the ralph loop on Ctrl+C or any unexpected throw, so the user
660- // gets back to the prompt rather than resuming with a stale ralphMode=true.
661- if (wasAborted) ralphMode = false;
662- }
663-
664- return lastAssistantText;
665- }
666-
667- // ── Render status bar (called before each prompt) ──────────────────────────
668175 async function renderStatusBarForSession(): Promise<void> {
669176 const branch = await getGitBranch(cwd);
670- const provider = currentModel.split("/")[0] ?? "";
671- const modelShort = currentModel.split("/").slice(1).join("/");
177+ const provider = runner.currentModel.split("/")[0] ?? "";
178+ const modelShort = runner.currentModel.split("/").slice(1).join("/");
672179 const cwdDisplay = tildePath(cwd);
673180
674- renderStatusBar({
181+ opts.reporter.renderStatusBar({
675182 model: modelShort,
676183 provider,
677184 cwd: cwdDisplay,
678185 gitBranch: branch,
679- sessionId: session.id,
680- inputTokens: totalIn,
681- outputTokens: totalOut,
682- contextTokens: lastContextTokens,
683- contextWindow: getContextWindow(currentModel),
684- ralphMode,
186+ sessionId: runner.session.id,
187+ inputTokens: runner.totalIn,
188+ outputTokens: runner.totalOut,
189+ contextTokens: runner.lastContextTokens,
190+ contextWindow: getContextWindow(runner.currentModel) ?? 0,
191+ ralphMode: runner.ralphMode,
685192 });
686193 }
687-}
688-
689-// ─── Interrupt stub helpers ───────────────────────────────────────────────────
690-
691-/**
692- * Returns a synthetic assistant CoreMessage signalling that the turn was
693- * interrupted by the user (Ctrl+C) or by an error. Used in four places:
694- * 1. Preamble abort (Ctrl+C before LLM call starts)
695- * 2. Mid-stream abort with no partial content
696- * 3. Mid-stream abort with partial content (appended after real messages)
697- * 4. Unexpected throw in the catch block
698- */
699-export function makeInterruptMessage(reason: "user" | "error"): CoreMessage {
700- const text =
701- reason === "user"
702- ? "<system-message>Response was interrupted by the user.</system-message>"
703- : "<system-message>Response was interrupted due to an error.</system-message>";
704- return { role: "assistant", content: text };
705-}
706-
707-// ─── Ralph signal detection ───────────────────────────────────────────────────
708-
709-/**
710- * Collect all text from assistant messages in a turn's newMessages array.
711- * Scans every assistant message (not just the last) so that a trailing tool
712- * call doesn't mask a `/ralph` signal that appeared in earlier text.
713- */
714-export function extractAssistantText(newMessages: CoreMessage[]): string {
715- const parts: string[] = [];
716- for (const msg of newMessages) {
717- if (msg.role !== "assistant") continue;
718- const content = msg.content;
719- if (typeof content === "string") {
720- parts.push(content);
721- } else if (Array.isArray(content)) {
722- for (const part of content as Array<{ type?: string; text?: string }>) {
723- if (part?.type === "text" && part.text) parts.push(part.text);
724- }
725- }
726- }
727- return parts.join("\n");
728-}
729194
730-/**
731- * Returns true if the assistant text contains the `/ralph` stop signal.
732- * Matches `/ralph` as a word boundary so surrounding prose is allowed
733- * (e.g. "All done. /ralph" or "/ralph\n").
734- */
735-export function hasRalphSignal(text: string): boolean {
736- return /\/ralph\b/.test(text);
737-}
738-
739-// ─── Resolve @file/skill references in user input ────────────────────────────
740-// @agent references are left as-is — unrecognised @refs simply fall through to
741-// the file-inject path and are left unchanged when the file doesn't exist.
742-
743-async function resolveFileRefs(
744- text: string,
745- cwd: string,
746-): Promise<{ text: string; images: ImageAttachment[] }> {
747- const atPattern = /@([\w./\-_]+)/g;
748- let result = text;
749- const matches = [...text.matchAll(atPattern)];
750- const images: ImageAttachment[] = [];
751-
752- const skills = loadSkills(cwd);
753-
754- // Substitute skills, images, and files (right-to-left).
755- for (const match of [...matches].reverse()) {
756- const ref = match[1];
757- if (!ref) continue;
758-
759- // @skill-name — inject skill content inline
760- const skill = skills.get(ref);
761- if (skill) {
762- const replacement = `<skill name="${skill.name}">\n${skill.content}\n</skill>`;
763- result =
764- result.slice(0, match.index) +
765- replacement +
766- result.slice((match.index ?? 0) + match[0].length);
767- continue;
768- }
769-
770- const filePath = ref.startsWith("/") ? ref : join(cwd, ref);
771-
772- // @image-path — read as base64 attachment
773- if (isImageFilename(ref)) {
774- const attachment = await loadImageFile(filePath);
775- if (attachment) {
776- images.unshift(attachment); // reverse() + unshift = left-to-right order
777- result =
778- result.slice(0, match.index) +
779- result.slice((match.index ?? 0) + match[0].length);
780- continue;
781- }
782- }
783-
784- // @file-path — inject file contents inline
785- try {
786- const content = await Bun.file(filePath).text();
787- const lines = content.split("\n");
788- const preview =
789- lines.length > 200
790- ? `${lines.slice(0, 200).join("\n")}\n[truncated]`
791- : content;
792- const replacement = `\`${ref}\`:\n\`\`\`\n${preview}\n\`\`\``;
793- result =
794- result.slice(0, match.index) +
795- replacement +
Cut short: this commit's diff is over 1000 lines.
src/agent/input-loop.ts+101−0
Cut short: this commit's diff is over 1000 lines.
src/agent/reporter.ts+45−0
Cut short: this commit's diff is over 1000 lines.
src/agent/session-runner.ts+218−0
Cut short: this commit's diff is over 1000 lines.
src/agent/subagent-runner.ts+86−0
Cut short: this commit's diff is over 1000 lines.
src/agent/system-prompt.ts+66−0
Cut short: this commit's diff is over 1000 lines.
src/agent/undo-snapshot.ts+70−0
Cut short: this commit's diff is over 1000 lines.
src/cli/agents.ts+12−43
Cut short: this commit's diff is over 1000 lines.
src/cli/commands.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/cli/config-conflicts.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/cli/custom-commands.ts+12−66
Cut short: this commit's diff is over 1000 lines.
src/cli/error-render.ts+13−0
Cut short: this commit's diff is over 1000 lines.
src/cli/input.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/cli/load-markdown-configs.ts+125−0
Cut short: this commit's diff is over 1000 lines.
src/cli/output-reporter.ts+73−0
Cut short: this commit's diff is over 1000 lines.
src/cli/output.ts+26−866
Cut short: this commit's diff is over 1000 lines.
src/cli/skills.ts+15−68
Cut short: this commit's diff is over 1000 lines.
src/cli/spinner.ts+34−0
Cut short: this commit's diff is over 1000 lines.
src/cli/status-bar.ts+91−0
Cut short: this commit's diff is over 1000 lines.
src/cli/stream-render.ts+168−0
Cut short: this commit's diff is over 1000 lines.
src/cli/terminal-io.ts+70−0
Cut short: this commit's diff is over 1000 lines.
src/cli/tool-render.ts+475−0
Cut short: this commit's diff is over 1000 lines.
src/index.ts+7−2
Cut short: this commit's diff is over 1000 lines.
src/session/db.ts+0−397
Cut short: this commit's diff is over 1000 lines.
src/session/db/connection.ts+111−0
Cut short: this commit's diff is over 1000 lines.
src/session/db/index.ts+6−0
Cut short: this commit's diff is over 1000 lines.
src/session/db/mcp-repo.ts+44−0
Cut short: this commit's diff is over 1000 lines.
src/session/db/message-repo.ts+86−0
Cut short: this commit's diff is over 1000 lines.
src/session/db/session-repo.ts+61−0
Cut short: this commit's diff is over 1000 lines.
src/session/db/settings-repo.ts+26−0
Cut short: this commit's diff is over 1000 lines.
src/session/db/snapshot-repo.ts+65−0
Cut short: this commit's diff is over 1000 lines.
src/session/manager.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/tools/shell.test.ts+1−12
Cut short: this commit's diff is over 1000 lines.
src/tools/snapshot.test.ts+5−1
Cut short: this commit's diff is over 1000 lines.
src/tools/snapshot.ts+1−1
Cut short: this commit's diff is over 1000 lines.