xonecas.io
64875
Mc

mini-coder / commit 6476db5

feat: add /ralph autonomous loop command

- Toggle with /ralph; magenta ↻ prompt + status bar indicator
- Loops processUserInput with fresh context each iteration until the
  LLM outputs /ralph anywhere in its response (hasRalphSignal)
- extractAssistantText scans all assistant messages in a turn so a
  trailing tool call cannot mask the stop signal
- Cap at 20 total iterations; Ctrl+C breaks the loop via wasAborted
- /ralph and /plan are mutually exclusive — enabling one clears the other
- 14 tests covering signal detection and text extraction

Sean2026-02-23 6476db52fd00eb95db7c80678f82291b2472eb0b parent 2832b6d

5 files changed

src/agent/agent.test.ts+105−0
@@ -0,0 +1,105 @@
1+import { describe, expect, test } from "bun:test";
2+import type { CoreMessage } from "../llm-api/turn.ts";
3+import { extractAssistantText, hasRalphSignal } from "./agent.ts";
4+
5+// ─── extractAssistantText ─────────────────────────────────────────────────────
6+
7+describe("extractAssistantText", () => {
8+ test("returns empty string for empty message list", () => {
9+ expect(extractAssistantText([])).toBe("");
10+ });
11+
12+ test("returns empty string when no assistant messages present", () => {
13+ const msgs: CoreMessage[] = [{ role: "user", content: "hello" }];
14+ expect(extractAssistantText(msgs)).toBe("");
15+ });
16+
17+ test("extracts string content from an assistant message", () => {
18+ const msgs: CoreMessage[] = [
19+ { role: "assistant", content: "All done. /ralph" },
20+ ];
21+ expect(extractAssistantText(msgs)).toBe("All done. /ralph");
22+ });
23+
24+ test("extracts text parts from array content", () => {
25+ const msgs: CoreMessage[] = [
26+ {
27+ role: "assistant",
28+ content: [
29+ { type: "text", text: "I will run the tests." },
30+ { type: "tool-call", toolCallId: "1", toolName: "shell", input: {} },
31+ ],
32+ },
33+ ];
34+ expect(extractAssistantText(msgs)).toBe("I will run the tests.");
35+ });
36+
37+ test("concatenates text across multiple assistant messages", () => {
38+ const msgs: CoreMessage[] = [
39+ { role: "user", content: "go" },
40+ { role: "assistant", content: "Fixing the bug." },
41+ { role: "assistant", content: "All done. /ralph" },
42+ ];
43+ expect(extractAssistantText(msgs)).toBe(
44+ "Fixing the bug.\nAll done. /ralph",
45+ );
46+ });
47+
48+ test("returns empty string when assistant message has no text parts", () => {
49+ const msgs: CoreMessage[] = [
50+ {
51+ role: "assistant",
52+ content: [
53+ { type: "tool-call", toolCallId: "1", toolName: "shell", input: {} },
54+ ],
55+ },
56+ ];
57+ expect(extractAssistantText(msgs)).toBe("");
58+ });
59+
60+ test("captures /ralph even when the last content part is a tool call", () => {
61+ // Typical agentic pattern: text block followed by a trailing tool call
62+ const msgs: CoreMessage[] = [
63+ {
64+ role: "assistant",
65+ content: [
66+ { type: "text", text: "Tests pass. /ralph" },
67+ { type: "tool-call", toolCallId: "1", toolName: "shell", input: {} },
68+ ],
69+ },
70+ ];
71+ expect(extractAssistantText(msgs)).toBe("Tests pass. /ralph");
72+ });
73+});
74+
75+// ─── hasRalphSignal ───────────────────────────────────────────────────────────
76+
77+describe("hasRalphSignal", () => {
78+ test("returns false for empty string", () => {
79+ expect(hasRalphSignal("")).toBe(false);
80+ });
81+
82+ test("returns true for bare /ralph", () => {
83+ expect(hasRalphSignal("/ralph")).toBe(true);
84+ });
85+
86+ test("returns true when /ralph has trailing whitespace", () => {
87+ expect(hasRalphSignal("/ralph \n")).toBe(true);
88+ });
89+
90+ test("returns true when /ralph is preceded by prose", () => {
91+ expect(hasRalphSignal("All tests pass. /ralph")).toBe(true);
92+ });
93+
94+ test("returns true when /ralph appears mid-text", () => {
95+ expect(hasRalphSignal("Done. /ralph\nSee you.")).toBe(true);
96+ });
97+
98+ test("returns false when /ralphy (not a word boundary)", () => {
99+ expect(hasRalphSignal("/ralphy")).toBe(false);
100+ });
101+
102+ test("returns false for unrelated text", () => {
103+ expect(hasRalphSignal("I finished the task.")).toBe(false);
104+ });
105+});
src/agent/agent.ts+85−5
@@ -276,6 +276,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
276276 }
277277
278278 let planMode = false;
279+ let ralphMode = false;
279280
280281 const cmdCtx: CommandContext = {
281282 get currentModel() {
@@ -289,6 +290,12 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
289290 get planMode() {
290291 return planMode;
291292 },
293+ get ralphMode() {
294+ return ralphMode;
295+ },
296+ setRalphMode: (v) => {
297+ ralphMode = v;
298+ },
292299 setPlanMode: (v) => {
293300 planMode = v;
294301 },
@@ -380,7 +387,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
380387
381388 let input: InputResult;
382389 try {
383- input = await readline({ cwd, planMode });
390+ input = await readline({ cwd, planMode, ralphMode });
384391 } catch {
385392 break;
386393 }
@@ -421,14 +428,38 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
421428 continue;
422429 }
423430
424- case "submit":
425- await processUserInput(input.text);
431+ case "submit": {
432+ const RALPH_MAX_ITERATIONS = 20;
433+ let ralphIteration = 1;
434+ let lastText = await processUserInput(input.text);
435+ if (ralphMode) {
436+ const goal = input.text;
437+ while (ralphMode) {
438+ // If the LLM signalled done, stop before starting another iteration.
439+ if (hasRalphSignal(lastText)) {
440+ ralphMode = false;
441+ writeln(`${PREFIX.info} ${c.dim("ralph mode off")}`);
442+ break;
443+ }
444+ if (ralphIteration >= RALPH_MAX_ITERATIONS) {
445+ writeln(
446+ `${PREFIX.info} ${c.yellow("ralph")} ${c.dim("— max iterations reached, stopping")}`,
447+ );
448+ ralphMode = false;
449+ break;
450+ }
451+ ralphIteration++;
452+ cmdCtx.startNewSession();
453+ lastText = await processUserInput(goal);
454+ }
455+ }
426456 continue;
457+ }
427458 }
428459 }
429460
430461 // ── Process a user message ─────────────────────────────────────────────────
431- async function processUserInput(text: string): Promise<void> {
462+ async function processUserInput(text: string): Promise<string> {
432463 // Resolve @file references
433464 const resolvedText = await resolveFileRefs(text, cwd);
434465
@@ -442,7 +473,9 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
442473
443474 const coreContent = planMode
444475 ? `${resolvedText}\n\n<system-message>PLAN MODE ACTIVE: Help the user gather context for the plan -- READ ONLY</system-message>`
445- : resolvedText;
476+ : ralphMode
477+ ? `${resolvedText}\n\n<system-message>RALPH MODE: You are in an autonomous loop. When the task is fully complete (all tests pass, no outstanding issues), output exactly \`/ralph\` as your final message to exit the loop. Otherwise, keep working.</system-message>`
478+ : resolvedText;
446479 const userMsg: CoreMessage = { role: "user", content: coreContent };
447480 session.messages.push(userMsg);
448481 saveMessages(session.id, [userMsg], thisTurn);
@@ -452,12 +485,15 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
452485 const systemPrompt = buildSystemPrompt(cwd);
453486
454487 const abortController = new AbortController();
488+ let wasAborted = false;
455489 const onSigInt = () => {
490+ wasAborted = true;
456491 abortController.abort();
457492 process.removeListener("SIGINT", onSigInt);
458493 };
459494 process.on("SIGINT", onSigInt);
460495
496+ let lastAssistantText = "";
461497 try {
462498 // Always push so the stack stays aligned 1:1 with turns. A null entry means
463499 // the tree was clean at snapshot time — /undo will roll back conversation
@@ -487,13 +523,22 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
487523 saveMessages(session.id, newMessages, thisTurn);
488524 }
489525
526+ // Collect all assistant text from this turn so the ralph loop can detect
527+ // the /ralph signal even when the final action was a tool call.
528+ lastAssistantText = extractAssistantText(newMessages);
529+
490530 totalIn += inputTokens;
491531 totalOut += outputTokens;
492532 lastContextTokens = contextTokens;
493533 touchActiveSession(session);
494534 } finally {
495535 process.removeListener("SIGINT", onSigInt);
536+ // Stop the ralph loop on Ctrl+C or any unexpected throw, so the user
537+ // gets back to the prompt rather than resuming with a stale ralphMode=true.
538+ if (wasAborted) ralphMode = false;
496539 }
540+
541+ return lastAssistantText;
497542 }
498543
499544 // ── Render status bar (called before each prompt) ──────────────────────────
@@ -515,10 +560,45 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
515560 outputTokens: totalOut,
516561 contextTokens: lastContextTokens,
517562 contextWindow: getContextWindow(currentModel),
563+ ralphMode,
518564 });
519565 }
520566 }
521567
568+// ─── Ralph signal detection ───────────────────────────────────────────────────
569+
570+/**
571+ * Collect all text from assistant messages in a turn's newMessages array.
572+ * Scans every assistant message (not just the last) so that a trailing tool
573+ * call doesn't mask a `/ralph` signal that appeared in earlier text.
574+ */
575+export function extractAssistantText(
576+ newMessages: import("../llm-api/turn.ts").CoreMessage[],
577+): string {
578+ const parts: string[] = [];
579+ for (const msg of newMessages) {
580+ if (msg.role !== "assistant") continue;
581+ const content = msg.content;
582+ if (typeof content === "string") {
583+ parts.push(content);
584+ } else if (Array.isArray(content)) {
585+ for (const part of content as Array<{ type?: string; text?: string }>) {
586+ if (part?.type === "text" && part.text) parts.push(part.text);
587+ }
588+ }
589+ }
590+ return parts.join("\n");
591+}
592+
593+/**
594+ * Returns true if the assistant text contains the `/ralph` stop signal.
595+ * Matches `/ralph` as a word boundary so surrounding prose is allowed
596+ * (e.g. "All done. /ralph" or "/ralph\n").
597+ */
598+export function hasRalphSignal(text: string): boolean {
599+ return /\/ralph\b/.test(text);
600+}
601+
522602 // ─── Resolve @file references in user input ────────────────────────────────────
523603
524604 async function resolveFileRefs(text: string, cwd: string): Promise<string> {
src/cli/commands.ts+23−0
@@ -25,6 +25,8 @@ export interface CommandContext {
2525 setModel: (model: string) => void;
2626 planMode: boolean;
2727 setPlanMode: (enabled: boolean) => void;
28+ ralphMode: boolean;
29+ setRalphMode: (enabled: boolean) => void;
2830 undoLastTurn: () => Promise<boolean>;
2931 startNewSession: () => void;
3032
@@ -122,6 +124,7 @@ async function handleModel(ctx: CommandContext, args: string): Promise<void> {
122124 function handlePlan(ctx: CommandContext): void {
123125 ctx.setPlanMode(!ctx.planMode);
124126 if (ctx.planMode) {
127+ if (ctx.ralphMode) ctx.setRalphMode(false);
125128 writeln(
126129 `${PREFIX.info} ${c.yellow("plan mode")} ${c.dim("— read-only tools + MCP, no writes or shell")}`,
127130 );
@@ -130,6 +133,18 @@ function handlePlan(ctx: CommandContext): void {
130133 }
131134 }
132135
136+function handleRalph(ctx: CommandContext): void {
137+ ctx.setRalphMode(!ctx.ralphMode);
138+ if (ctx.ralphMode) {
139+ if (ctx.planMode) ctx.setPlanMode(false);
140+ writeln(
141+ `${PREFIX.info} ${c.magenta("ralph mode")} ${c.dim("— loops until done, fresh context each iteration")}`,
142+ );
143+ } else {
144+ writeln(`${PREFIX.info} ${c.dim("ralph mode off")}`);
145+ }
146+}
147+
133148 async function handleUndo(ctx: CommandContext): Promise<void> {
134149 const ok = await ctx.undoLastTurn();
135150 if (ok) {
@@ -327,6 +342,10 @@ function handleHelp(): void {
327342 ["/model [id]", "list or switch models (fetches live list)"],
328343 ["/undo", "remove the last turn from conversation history"],
329344 ["/plan", "toggle plan mode (read-only tools + MCP)"],
345+ [
346+ "/ralph",
347+ "toggle ralph mode (autonomous loop, fresh context each iteration)",
348+ ],
330349 ["/review [focus]", "run a structured code review on recent changes"],
331350 ["/mcp list", "list MCP servers"],
332351 ["/mcp add <n> <t> [u]", "add an MCP server"],
@@ -373,6 +392,10 @@ export async function handleCommand(
373392 handlePlan(ctx);
374393 return { type: "handled" };
375394
395+ case "ralph":
396+ handleRalph(ctx);
397+ return { type: "handled" };
398+
376399 case "mcp":
377400 await handleMcp(ctx, args);
378401 return { type: "handled" };
src/cli/input.ts+9−1
@@ -120,11 +120,14 @@ export function pasteLabel(text: string): string {
120120
121121 const PROMPT = c.green("▶ ");
122122 const PROMPT_PLAN = c.yellow("⬢ ");
123+const PROMPT_RALPH = c.magenta("↻ ");
124+
123125 const PROMPT_RAW_LEN = 2; // both prompts are 2 visible chars
124126
125127 export async function readline(opts: {
126128 cwd?: string;
127129 planMode?: boolean;
130+ ralphMode?: boolean;
128131 }): Promise<InputResult> {
129132 const cwd = opts.cwd ?? process.cwd();
130133
@@ -164,7 +167,12 @@ export async function readline(opts: {
164167 ? `…${visualBuf.slice(-(cols - PROMPT_RAW_LEN - 3))}`
165168 : visualBuf;
166169
167- const prompt = opts.planMode ? PROMPT_PLAN : PROMPT;
170+ const prompt = opts.planMode
171+ ? PROMPT_PLAN
172+ : opts.ralphMode
173+ ? PROMPT_RALPH
174+ : PROMPT;
175+
168176 process.stdout.write(
169177 `${CLEAR_LINE}${prompt}${display}${CSI}${PROMPT_RAW_LEN + visualCursor + 1}G`,
170178 );
src/cli/output.ts+2−0
@@ -771,6 +771,7 @@ export function renderStatusBar(opts: {
771771 outputTokens: number;
772772 contextTokens: number;
773773 contextWindow: number | null;
774+ ralphMode?: boolean;
774775 }): void {
775776 const cols = (process.stdout as NodeJS.WriteStream).columns ?? 80;
776777
@@ -778,6 +779,7 @@ export function renderStatusBar(opts: {
778779 const left: string[] = [c.cyan(opts.model)];
779780 if (opts.provider && opts.provider !== "zen") left.push(c.dim(opts.provider));
780781 left.push(c.dim(opts.sessionId.slice(0, 8)));
782+ if (opts.ralphMode) left.push(c.magenta("↻ ralph"));
781783
782784 const right: string[] = [];
783785 if (opts.inputTokens > 0 || opts.outputTokens > 0) {