xonecas.io
64875
Mc

mini-coder / commit 6e02ac7

fix: Tackle pending todo items, remove tests that performed git

operations... again

xonecas2026-04-15 6e02ac706dc141b53acd0c9f6ac6c45e5fa40e72 parent b3d06b8

11 files changed

TODO.md+2−5
@@ -7,11 +7,6 @@ The spec.md and code are the sources of truth, not this file, don't assume anyth
77
88 ## Open items
99
10-- [ ] Git status in prompt text should not change between turns! This breaks caching! Big bug! Spec specifically says it wrong, we should not the edit the system prompt after a session started. Git information should be updated at session start only, never during a session.
11-- [ ] Headless mode and json output should be separated, without --json headless mode outputs the final response only.
12-- [ ] Invalid `settings.json` is fatal instead of falling back to no saved settings (`src/settings.ts`)
13-- [ ] Providers should be readied lazily: on the first message for the selected provider, or for all providers when `/models` is used.
14-
1510 ## Forge comparison follow-ups (high-value gaps, highest priority first)
1611
1712 - [ ] Add first-class todo tools plus prompt/UI integration so the agent can track and complete work explicitly instead of relying only on a `/tmp` file (`src/tools.ts`, `src/agent.ts`, `src/prompt.ts`, `src/ui/conversation.ts`)
@@ -21,6 +16,8 @@ The spec.md and code are the sources of truth, not this file, don't assume anyth
2116
2217 ## Low priority (deferred until further notice)
2318
19+- [ ] Invalid `settings.json` is fatal instead of falling back to no saved settings (`src/settings.ts`)
20+- [ ] Providers should be readied lazily: on the first message for the selected provider, or for all providers when `/models` is used.
2421 - [ ] Escape-over-overlay behavior is not encoded in app code (`src/ui/commands.ts`, `src/ui.ts`)
2522 - [ ] Custom provider discovery ignores configured `apiKey` (`src/index.ts`)
2623 - [ ] Slash-command autocomplete does not preserve the draft (`src/ui/commands.ts`)
spec.md+14−8
@@ -204,7 +204,7 @@ The core runtime. Streaming is the default behavior throughout the turn: user-vi
204204
205205 1. **User submits a message** — the input text (plus any embedded images or skill bodies from `/skill:name`) becomes a pi-ai `UserMessage`. It is appended to the session's message history, rendered in the UI immediately, and persisted to the DB.
206206
207-2. **Build context** — construct a pi-ai `Context`: the system prompt (see [System prompt](#system-prompt)), the full message history, and the registered tool definitions (built-in + plugin tools). The dynamic environment values in the prompt are refreshed at session start and after each turn.
207+2. **Build context** — construct a pi-ai `Context`: the system prompt (see [System prompt](#system-prompt)), the full message history, and the registered tool definitions (built-in + plugin tools). The prompt context snapshot is loaded once at startup or another explicit reload boundary and then reused across turns so provider prompt caching stays effective. It is refreshed only at boundaries such as `/new` or CWD change.
208208
209209 3. **Stream to LLM** — call `streamSimple(model, context, options)` from pi-ai. Iterate over the event stream:
210210 - `text_delta` / `thinking_delta` / `toolcall_delta` → update the in-progress assistant message and the UI incrementally (stream raw markdown text, show thinking if enabled, accumulate tool call arguments as they arrive).
@@ -256,7 +256,7 @@ This is suggestive, not prescriptive. Files may split or merge as the code evolv
256256
257257 ## System prompt
258258
259-A single prompt, model-agnostic. Assembled from a static core prompt plus dynamic context.
259+A single prompt, model-agnostic. Assembled from a static core prompt plus prompt context captured at startup or another explicit reload boundary.
260260
261261 ### Prompt template
262262
@@ -346,9 +346,11 @@ Environment block notes:
346346 - Empty git fields are omitted.
347347 - The `Read Image` line is omitted when the active model does not support image input.
348348 - The OS value is normalized to `linux`, `mac`, or `docker`.
349-- The static core prompt text should remain identical across turns. AGENTS.md content, skills, and plugin suffixes are stable within a session, changing only on `/new` or CWD change. The dynamic environment values are refreshed as needed across turns.
349+- The static core prompt text should remain identical across turns.
350+- AGENTS.md content, skills, plugin suffixes, and the git snapshot are stable within a session, changing only on `/new` or CWD change.
351+- Rebuilding the prompt for later turns must reuse that same session-start snapshot so provider prompt caching keeps working.
350352
351-Git state is gathered once at session start and refreshed each turn via fast git commands:
353+Git state is gathered when the session prompt context is loaded (startup, `/new`, or CWD change), not after each turn, via fast git commands:
352354
353355 - `git rev-parse --show-toplevel` — repo root
354356 - `git branch --show-current` — current branch
@@ -737,7 +739,7 @@ Commands are discoverable when the input starts with `/`: pressing `Tab` in that
737739
738740 mini-coder also supports a non-interactive one-shot mode for scripting and benchmark harnesses.
739741
740-`-p, --prompt <text>` submits exactly one user prompt, runs the full agent loop for that turn, and exits after the loop ends. No TUI is started.
742+`-p, --prompt <text>` submits exactly one user prompt, runs the full agent loop for that turn, and exits after the loop ends. No TUI is started. `--json` switches headless stdout from final-text output to the raw NDJSON event stream.
741743
742744 Headless mode is selected when either:
743745
@@ -754,9 +756,13 @@ Prompt source in headless mode:
754756
755757 Input parsing in headless mode reuses the same rules as the interactive input area for plain text, `/skill:name`, and standalone image-file paths. Interactive slash commands such as `/model`, `/session`, `/new`, `/fork`, `/undo`, `/login`, `/logout`, `/effort`, and `/help` are not available in headless mode and should fail clearly rather than attempting to open interactive UI.
756758
759+### Headless text output
760+
761+In headless mode without `--json`, stdout contains only the final persisted assistant message's text content for the one-shot run. No intermediate streaming events, tool progress, status text, markdown rendering, or other TUI presentation output is written to stdout in this mode.
762+
757763 ### Headless JSON output
758764
759-In headless mode, stdout is a newline-delimited JSON stream (NDJSON). Each line is one JSON object with a `type` field.
765+With `--json`, stdout is a newline-delimited JSON stream (NDJSON). Each line is one JSON object with a `type` field.
760766
761767 This stream is intentionally raw and close to the internal agent event protocol rather than a flattened summary format. It carries the streaming event payloads needed to observe the full run, including text deltas, thinking deltas, tool-call progress, tool execution progress, persisted assistant/tool-result messages, and terminal events.
762768
@@ -776,7 +782,7 @@ At minimum, the streamed event types are:
776782 - `error`
777783 - `aborted`
778784
779-Event payload fields use the same JSON-serializable shapes as the in-process agent stream and persisted pi-ai message content where applicable. No terminal-only formatting, status bar text, markdown rendering, or other TUI presentation output is written to stdout in headless mode.
785+Event payload fields use the same JSON-serializable shapes as the in-process agent stream and persisted pi-ai message content where applicable. No terminal-only formatting, status bar text, markdown rendering, or other TUI presentation output is written to stdout in this mode.
780786
781787 A successful one-shot run continues through any assistant/tool loops and ends only when the agent loop emits `done` (with `stopReason: "stop"` or `"length"`). Errors and user interrupts terminate the stream with `error` or `aborted` respectively.
782788
@@ -809,7 +815,7 @@ On launch, mini-coder:
809815 7. In interactive mode, renders the UI with an empty conversation log, a minimal `mini-coder` empty-state banner (showing the packaged version when available, otherwise a simple dev label), and the status bar populated.
810816 8. Starts a new session only when a prompt is actually submitted (no 0-message sessions in the DB).
811817
812-The empty-state banner is only shown while the conversation log has no messages. In headless mode, stdout is reserved for NDJSON event output.
818+The empty-state banner is only shown while the conversation log has no messages. In headless mode, stdout is reserved for the final assistant text response by default, or NDJSON event output when `--json` is used.
813819
814820 ## User settings persistence
815821
src/cli.test.ts+21−10
@@ -6,15 +6,26 @@ import {
66 } from "./cli.ts";
77
88 describe("cli", () => {
9- test("parseCliArgs recognizes -p and --prompt", () => {
9+ test("parseCliArgs recognizes -p, --prompt, and --json", () => {
1010 expect(parseCliArgs(["-p", "fix the tests"])).toEqual({
1111 prompt: "fix the tests",
12+ json: false,
1213 });
1314 expect(parseCliArgs(["--prompt", "fix the tests"])).toEqual({
1415 prompt: "fix the tests",
16+ json: false,
1517 });
1618 expect(parseCliArgs(["--prompt=fix the tests"])).toEqual({
1719 prompt: "fix the tests",
20+ json: false,
21+ });
22+ expect(parseCliArgs(["--json"])).toEqual({
23+ prompt: null,
24+ json: true,
25+ });
26+ expect(parseCliArgs(["--json", "-p", "fix the tests"])).toEqual({
27+ prompt: "fix the tests",
28+ json: true,
1829 });
1930 });
2031
@@ -37,25 +48,25 @@ describe("cli", () => {
3748 test("shouldUseHeadlessMode selects prompt mode or missing TTYs", () => {
3849 expect(
3950 shouldUseHeadlessMode(
40- { prompt: null },
51+ { prompt: null, json: false },
4152 { stdinIsTTY: true, stdoutIsTTY: true },
4253 ),
4354 ).toBe(false);
4455 expect(
4556 shouldUseHeadlessMode(
46- { prompt: "fix the tests" },
57+ { prompt: "fix the tests", json: false },
4758 { stdinIsTTY: true, stdoutIsTTY: true },
4859 ),
4960 ).toBe(true);
5061 expect(
5162 shouldUseHeadlessMode(
52- { prompt: null },
63+ { prompt: null, json: false },
5364 { stdinIsTTY: false, stdoutIsTTY: true },
5465 ),
5566 ).toBe(true);
5667 expect(
5768 shouldUseHeadlessMode(
58- { prompt: null },
69+ { prompt: null, json: false },
5970 { stdinIsTTY: true, stdoutIsTTY: false },
6071 ),
6172 ).toBe(true);
@@ -63,7 +74,7 @@ describe("cli", () => {
6374
6475 test("resolveHeadlessPrompt prefers the CLI prompt and preserves whitespace", async () => {
6576 const prompt = await resolveHeadlessPrompt(
66- { prompt: " fix the tests " },
77+ { prompt: " fix the tests ", json: false },
6778 { stdinIsTTY: true, stdoutIsTTY: false },
6879 async () => {
6980 throw new Error("stdin should not be read");
@@ -75,7 +86,7 @@ describe("cli", () => {
7586
7687 test("resolveHeadlessPrompt reads piped stdin when no CLI prompt was provided", async () => {
7788 const prompt = await resolveHeadlessPrompt(
78- { prompt: null },
89+ { prompt: null, json: false },
7990 { stdinIsTTY: false, stdoutIsTTY: true },
8091 async () => "fix the tests\n",
8192 );
@@ -86,7 +97,7 @@ describe("cli", () => {
8697 test("resolveHeadlessPrompt rejects interactive stdin when stdout is not a TTY", async () => {
8798 await expect(
8899 resolveHeadlessPrompt(
89- { prompt: null },
100+ { prompt: null, json: false },
90101 { stdinIsTTY: true, stdoutIsTTY: false },
91102 async () => "",
92103 ),
@@ -96,7 +107,7 @@ describe("cli", () => {
96107 test("resolveHeadlessPrompt rejects empty headless input", async () => {
97108 await expect(
98109 resolveHeadlessPrompt(
99- { prompt: " \n\t" },
110+ { prompt: " \n\t", json: false },
100111 { stdinIsTTY: true, stdoutIsTTY: false },
101112 async () => "",
102113 ),
@@ -104,7 +115,7 @@ describe("cli", () => {
104115
105116 await expect(
106117 resolveHeadlessPrompt(
107- { prompt: null },
118+ { prompt: null, json: false },
108119 { stdinIsTTY: false, stdoutIsTTY: true },
109120 async () => " \n",
110121 ),
src/cli.ts+11−2
@@ -12,6 +12,8 @@
1212 export interface CliOptions {
1313 /** One-shot prompt text, or `null` when not provided. */
1414 prompt: string | null;
15+ /** Whether to stream headless output as NDJSON instead of final text. */
16+ json: boolean;
1517 }
1618
1719 /** TTY availability for stdin/stdout. */
@@ -29,7 +31,8 @@ export interface TtyState {
2931 /**
3032 * Parse supported CLI arguments.
3133 *
32- * Currently supports only `-p, --prompt <text>` for headless one-shot mode.
34+ * Supports `-p, --prompt <text>` for headless one-shot mode and `--json`
35+ * to stream NDJSON events instead of the default final-text output.
3336 * Unknown flags and positional arguments fail eagerly.
3437 *
3538 * @param argv - Process arguments excluding the Bun executable and script path.
@@ -37,6 +40,7 @@ export interface TtyState {
3740 */
3841 export function parseCliArgs(argv: readonly string[]): CliOptions {
3942 let prompt: string | null = null;
43+ let json = false;
4044
4145 for (let index = 0; index < argv.length; index += 1) {
4246 const arg = argv[index];
@@ -59,6 +63,11 @@ export function parseCliArgs(argv: readonly string[]): CliOptions {
5963 continue;
6064 }
6165
66+ if (arg === "--json") {
67+ json = true;
68+ continue;
69+ }
70+
6271 if (arg.startsWith("-")) {
6372 throw new Error(`Unknown argument: ${arg}`);
6473 }
@@ -66,7 +75,7 @@ export function parseCliArgs(argv: readonly string[]): CliOptions {
6675 throw new Error(`Unexpected positional argument: ${arg}`);
6776 }
6877
69- return { prompt };
78+ return { prompt, json };
7079 }
7180
7281 // ---------------------------------------------------------------------------
src/git.test.ts+0−215
@@ -1,215 +0,0 @@
1-import { describe, expect, test } from "bun:test";
2-import { getGitState, parseGitAheadBehind, parseGitStatus } from "./git.ts";
3-
4-describe("parseGitStatus", () => {
5- test("returns zero counts for empty output", () => {
6- expect(parseGitStatus("")).toEqual({
7- staged: 0,
8- modified: 0,
9- untracked: 0,
10- });
11- });
12-
13- test("counts mixed porcelain states", () => {
14- expect(
15- parseGitStatus(
16- [
17- "M staged-only.txt",
18- " M modified-only.txt",
19- "MM staged-and-modified.txt",
20- "?? new-file.txt",
21- ].join("\n"),
22- ),
23- ).toEqual({
24- staged: 2,
25- modified: 2,
26- untracked: 1,
27- });
28- });
29-
30- test("treats rename and delete statuses as tracked changes", () => {
31- expect(
32- parseGitStatus(
33- [
34- "R renamed.txt -> renamed-again.txt",
35- " D deleted.txt",
36- "A added.txt",
37- ].join("\n"),
38- ),
39- ).toEqual({
40- staged: 2,
41- modified: 1,
42- untracked: 0,
43- });
44- });
45-});
46-
47-describe("parseGitAheadBehind", () => {
48- test("parses ahead and behind counts from rev-list output", () => {
49- expect(parseGitAheadBehind("3\t2")).toEqual({ ahead: 3, behind: 2 });
50- });
51-
52- test("defaults missing or invalid values to zero", () => {
53- expect(parseGitAheadBehind("")).toEqual({ ahead: 0, behind: 0 });
54- expect(parseGitAheadBehind("nope nope")).toEqual({ ahead: 0, behind: 0 });
55- expect(parseGitAheadBehind("5")).toEqual({ ahead: 5, behind: 0 });
56- });
57-});
58-
59-describe("getGitState", () => {
60- test("returns null when git reports the cwd is not in a repo", async () => {
61- const state = await getGitState("/tmp/not-a-repo", {
62- run: async (args) => {
63- expect(args).toEqual(["rev-parse", "--show-toplevel"]);
64- return null;
65- },
66- });
67-
68- expect(state).toBeNull();
69- });
70-
71- test("returns null when git is not installed", async () => {
72- const missingGit = Object.assign(
73- new Error('Executable not found in $PATH: "git"'),
74- {
75- code: "ENOENT",
76- path: "git",
77- },
78- );
79-
80- const state = await getGitState("/tmp/no-git", {
81- run: async () => {
82- throw missingGit;
83- },
84- });
85-
86- expect(state).toBeNull();
87- });
88-
89- test("rethrows ENOENT errors that are not missing-git failures", async () => {
90- const invalidCwd = Object.assign(
91- new Error("ENOENT: no such file or directory, posix_spawn 'git'"),
92- {
93- code: "ENOENT",
94- path: "git",
95- },
96- );
97-
98- await expect(
99- getGitState("/tmp/missing-cwd", {
100- run: async () => {
101- throw invalidCwd;
102- },
103- }),
104- ).rejects.toThrow(invalidCwd.message);
105- });
106-
107- test("builds git state by parsing command output", async () => {
108- const calls: Array<{ args: string[]; cwd: string; trim: boolean }> = [];
109- const responses = new Map<string, string | null>([
110- ["rev-parse --show-toplevel", "/repo"],
111- ["branch --show-current", "main"],
112- [
113- "rev-parse --abbrev-ref --symbolic-full-name @{upstream}",
114- "origin/main",
115- ],
116- [
117- "status --porcelain",
118- [
119- "M staged-only.txt",
120- " M modified-only.txt",
121- "MM staged-and-modified.txt",
122- "?? new-file.txt",
123- ].join("\n"),
124- ],
125- ["rev-list --left-right --count HEAD...@{upstream}", "4\t1"],
126- ]);
127-
128- const state = await getGitState("/repo/subdir", {
129- run: async (args, cwd, trim = true) => {
130- calls.push({ args, cwd, trim });
131- const key = args.join(" ");
132- if (!responses.has(key)) {
133- throw new Error(`Unexpected git command: ${key}`);
134- }
135- return responses.get(key) ?? null;
136- },
137- });
138-
139- expect(state).toEqual({
140- root: "/repo",
141- branch: "main",
142- upstream: "origin/main",
143- staged: 2,
144- modified: 2,
145- untracked: 1,
146- ahead: 4,
147- behind: 1,
148- });
149- expect(calls).toEqual([
150- {
151- args: ["rev-parse", "--show-toplevel"],
152- cwd: "/repo/subdir",
153- trim: true,
154- },
155- {
156- args: ["branch", "--show-current"],
157- cwd: "/repo/subdir",
158- trim: true,
159- },
160- {
161- args: [
162- "rev-parse",
163- "--abbrev-ref",
164- "--symbolic-full-name",
165- "@{upstream}",
166- ],
167- cwd: "/repo/subdir",
168- trim: true,
169- },
170- {
171- args: ["status", "--porcelain"],
172- cwd: "/repo/subdir",
173- trim: false,
174- },
175- {
176- args: ["rev-list", "--left-right", "--count", "HEAD...@{upstream}"],
177- cwd: "/repo/subdir",
178- trim: true,
179- },
180- ]);
181- });
182-
183- test("falls back to empty branch, null upstream, and zero counts when optional commands fail", async () => {
184- const state = await getGitState("/repo", {
185- run: async (args) => {
186- const key = args.join(" ");
187- switch (key) {
188- case "rev-parse --show-toplevel":
189- return "/repo";
190- case "branch --show-current":
191- return null;
192- case "rev-parse --abbrev-ref --symbolic-full-name @{upstream}":
193- return null;
194- case "status --porcelain":
195- return null;
196- case "rev-list --left-right --count HEAD...@{upstream}":
197- return null;
198- default:
199- throw new Error(`Unexpected git command: ${key}`);
200- }
201- },
202- });
203-
204- expect(state).toEqual({
205- root: "/repo",
206- branch: "",
207- upstream: null,
208- staged: 0,
209- modified: 0,
210- untracked: 0,
211- ahead: 0,
212- behind: 0,
213- });
214- });
215-});
src/headless.test.ts+41−1
@@ -10,7 +10,7 @@ import {
1010 fauxToolCall,
1111 registerFauxProvider,
1212 } from "@mariozechner/pi-ai";
13-import { runHeadlessPrompt } from "./headless.ts";
13+import { runHeadlessPrompt, runHeadlessPromptText } from "./headless.ts";
1414 import type { AppState } from "./index.ts";
1515 import { listPromptHistory, loadMessages, openDatabase } from "./session.ts";
1616 import { DEFAULT_THEME } from "./theme.ts";
@@ -106,6 +106,46 @@ describe("headless", () => {
106106 expect(listPromptHistory(state.db, 1)[0]?.text).toBe("fix the tests");
107107 });
108108
109+ test("runHeadlessPromptText writes only the final assistant text", async () => {
110+ faux.setResponses([
111+ fauxAssistantMessage(
112+ [fauxToolCall("shell", { command: "printf intermediate" })],
113+ { stopReason: "toolUse" },
114+ ),
115+ fauxAssistantMessage([
116+ fauxThinking("Need to summarize the result."),
117+ fauxText("Done."),
118+ ]),
119+ ]);
120+ const state = createTestState();
121+ let output = "";
122+
123+ const stopReason = await runHeadlessPromptText(
124+ state,
125+ "run the shell command",
126+ {
127+ writeText: (text) => {
128+ output += text;
129+ },
130+ },
131+ );
132+
133+ expect(stopReason).toBe("stop");
134+ expect(output).toBe("Done.");
135+
136+ const sessionId = state.session?.id;
137+ if (!sessionId) {
138+ throw new Error("Expected a session to be created");
139+ }
140+
141+ expect(
142+ loadMessages(state.db, sessionId).map((message) => message.role),
143+ ).toEqual(["user", "assistant", "toolResult", "assistant"]);
144+ expect(listPromptHistory(state.db, 1)[0]?.text).toBe(
145+ "run the shell command",
146+ );
147+ });
148+
109149 test("runHeadlessPrompt rejects slash commands before creating a session", async () => {
110150 const state = createTestState();
111151 const lines: string[] = [];
src/headless.ts+165−46
@@ -4,6 +4,7 @@
44 * @module
55 */
66
7+import type { AssistantMessage, UserMessage } from "@mariozechner/pi-ai";
78 import type { AppState } from "./index.ts";
89 import {
910 resolveRawInput,
@@ -15,18 +16,37 @@ import {
1516 // Types
1617 // ---------------------------------------------------------------------------
1718
18-/** Options for a headless one-shot run. */
19+type HeadlessStopReason = "stop" | "length" | "error" | "aborted";
20+
21+/** Options for a headless NDJSON run. */
1922 export interface HeadlessRunOptions {
2023 /** Optional line writer for NDJSON event output. */
2124 writeLine?: (line: string) => void;
2225 }
2326
27+/** Options for a headless final-text run. */
28+export interface HeadlessTextRunOptions {
29+ /** Optional writer for the final assistant text output. */
30+ writeText?: (text: string) => void;
31+}
32+
33+interface HeadlessOutputController {
34+ /** Write text to stdout with broken-pipe handling. */
35+ write(text: string): void;
36+ /** Attach SIGINT/stdout error handlers for the active run. */
37+ attach(): void;
38+ /** Remove SIGINT/stdout error handlers after the run. */
39+ detach(): void;
40+ /** Resolve the final stop reason, converting broken pipes into quiet shutdowns. */
41+ finalize(stopReason: HeadlessStopReason): HeadlessStopReason;
42+}
43+
2444 // ---------------------------------------------------------------------------
2545 // Helpers
2646 // ---------------------------------------------------------------------------
2747
28-function defaultWriteLine(line: string): void {
29- process.stdout.write(`${line}\n`);
48+function defaultWrite(text: string): void {
49+ process.stdout.write(text);
3050 }
3151
3252 function isBrokenPipeError(error: unknown): boolean {
@@ -52,23 +72,10 @@ function buildCommandError(command: string): Error {
5272 );
5373 }
5474
55-/**
56- * Run a single headless prompt to completion and stream NDJSON events.
57- *
58- * The raw input is parsed with the same rules as interactive input. Slash
59- * commands are rejected in headless mode. Assistant/tool events are written as
60- * one JSON object per line.
61- *
62- * @param state - Mutable application state for the run.
63- * @param rawInput - Exact raw prompt text supplied by the user.
64- * @param options - Optional event-output overrides.
65- * @returns The terminal stop reason for the agent loop.
66- */
67-export async function runHeadlessPrompt(
75+function resolveHeadlessContent(
6876 state: AppState,
6977 rawInput: string,
70- options?: HeadlessRunOptions,
71-): Promise<"stop" | "length" | "error" | "aborted"> {
78+): UserMessage["content"] {
7279 const resolved = resolveRawInput(rawInput, state);
7380 switch (resolved.type) {
7481 case "empty":
@@ -78,11 +85,38 @@ export async function runHeadlessPrompt(
7885 case "command":
7986 throw buildCommandError(resolved.command);
8087 case "message":
81- break;
88+ return resolved.content;
89+ }
90+}
91+
92+function extractAssistantText(message: AssistantMessage | null): string {
93+ if (!message) {
94+ return "";
8295 }
8396
97+ return message.content
98+ .filter(
99+ (
100+ block,
101+ ): block is Extract<
102+ AssistantMessage["content"][number],
103+ { type: "text" }
104+ > => {
105+ return block.type === "text";
106+ },
107+ )
108+ .map((block) => block.text)
109+ .join("");
110+}
111+
112+function createHeadlessOutputController(
113+ state: AppState,
114+ writeImpl: (text: string) => void,
115+): HeadlessOutputController {
84116 let brokenPipe = false;
85117 let outputError: unknown = null;
118+ const sigintHandler = createSigintHandler(state);
119+
86120 const stopForBrokenPipe = (): void => {
87121 if (brokenPipe) {
88122 return;
@@ -90,51 +124,136 @@ export async function runHeadlessPrompt(
90124 brokenPipe = true;
91125 state.abortController?.abort();
92126 };
93- const writeLineImpl = options?.writeLine ?? defaultWriteLine;
94- const writeLine = (line: string): void => {
95- if (brokenPipe) {
127+
128+ const stdoutErrorHandler = (error: unknown): void => {
129+ if (isBrokenPipeError(error)) {
130+ stopForBrokenPipe();
96131 return;
97132 }
98133
99- try {
100- writeLineImpl(line);
101- } catch (error) {
102- if (!isBrokenPipeError(error)) {
103- throw error;
134+ outputError = error;
135+ state.abortController?.abort();
136+ };
137+
138+ return {
139+ write(text) {
140+ if (brokenPipe) {
141+ return;
104142 }
105- stopForBrokenPipe();
106- }
143+
144+ try {
145+ writeImpl(text);
146+ } catch (error) {
147+ if (!isBrokenPipeError(error)) {
148+ throw error;
149+ }
150+ stopForBrokenPipe();
151+ }
152+ },
153+ attach() {
154+ process.stdout.on("error", stdoutErrorHandler);
155+ process.on("SIGINT", sigintHandler);
156+ },
157+ detach() {
158+ process.stdout.off("error", stdoutErrorHandler);
159+ process.off("SIGINT", sigintHandler);
160+ },
161+ finalize(stopReason) {
162+ if (outputError) {
163+ throw outputError;
164+ }
165+ return brokenPipe ? "stop" : stopReason;
166+ },
107167 };
168+}
169+
170+/**
171+ * Run a single headless prompt to completion and stream NDJSON events.
172+ *
173+ * The raw input is parsed with the same rules as interactive input. Slash
174+ * commands are rejected in headless mode. Assistant/tool events are written as
175+ * one JSON object per line.
176+ *
177+ * @param state - Mutable application state for the run.
178+ * @param rawInput - Exact raw prompt text supplied by the user.
179+ * @param options - Optional event-output overrides.
180+ * @returns The terminal stop reason for the agent loop.
181+ */
182+export async function runHeadlessPrompt(
183+ state: AppState,
184+ rawInput: string,
185+ options?: HeadlessRunOptions,
186+): Promise<HeadlessStopReason> {
187+ const content = resolveHeadlessContent(state, rawInput);
188+ const output = createHeadlessOutputController(
189+ state,
190+ options?.writeLine ?? ((line) => defaultWrite(`${line}\n`)),
191+ );
108192 const hooks: SubmitTurnHooks = {
109193 onEvent: (event) => {
110- writeLine(JSON.stringify(event));
194+ output.write(JSON.stringify(event));
111195 },
112196 };
113- const sigintHandler = createSigintHandler(state);
114- const stdoutErrorHandler = (error: unknown): void => {
115- if (isBrokenPipeError(error)) {
116- stopForBrokenPipe();
117- return;
118- }
119- outputError = error;
120- state.abortController?.abort();
197+
198+ output.attach();
199+ try {
200+ const stopReason = await submitResolvedInput(
201+ rawInput,
202+ content,
203+ state,
204+ hooks,
205+ );
206+ return output.finalize(stopReason);
207+ } finally {
208+ output.detach();
209+ }
210+}
211+
212+/**
213+ * Run a single headless prompt to completion and write only the final assistant text.
214+ *
215+ * The raw input is parsed with the same rules as interactive input. Slash
216+ * commands are rejected in headless mode. Only the final persisted assistant
217+ * message's text content is written to stdout.
218+ *
219+ * @param state - Mutable application state for the run.
220+ * @param rawInput - Exact raw prompt text supplied by the user.
221+ * @param options - Optional final-text output overrides.
222+ * @returns The terminal stop reason for the agent loop.
223+ */
224+export async function runHeadlessPromptText(
225+ state: AppState,
226+ rawInput: string,
227+ options?: HeadlessTextRunOptions,
228+): Promise<HeadlessStopReason> {
229+ const content = resolveHeadlessContent(state, rawInput);
230+ const output = createHeadlessOutputController(
231+ state,
232+ options?.writeText ?? defaultWrite,
233+ );
234+ let finalAssistantMessage: AssistantMessage | null = null;
235+ const hooks: SubmitTurnHooks = {
236+ onEvent: (event) => {
237+ if (event.type === "assistant_message") {
238+ finalAssistantMessage = event.message;
239+ }
240+ },
121241 };
122242
123- process.stdout.on("error", stdoutErrorHandler);
124- process.on("SIGINT", sigintHandler);
243+ output.attach();
125244 try {
126245 const stopReason = await submitResolvedInput(
127246 rawInput,
128- resolved.content,
247+ content,
129248 state,
130249 hooks,
131250 );
132- if (outputError) {
133- throw outputError;
251+ const finalText = extractAssistantText(finalAssistantMessage);
252+ if (finalText.length > 0) {
253+ output.write(finalText);
134254 }
135- return brokenPipe ? "stop" : stopReason;
255+ return output.finalize(stopReason);
136256 } finally {
137- process.stdout.off("error", stdoutErrorHandler);
138- process.off("SIGINT", sigintHandler);
257+ output.detach();
139258 }
140259 }
src/index.ts+7−6
@@ -542,8 +542,6 @@ export interface AppState {
542542 versionLabel: string;
543543 /** Current git state (null if not in a repo). */
544544 git: GitState | null;
545- /** Optional git state loader override used by tests. */
546- loadGitState?: (cwd: string) => Promise<GitState | null>;
547545 /** Available provider credentials (provider → API key). */
548546 providers: Map<string, string>;
549547 /** OAuth credentials on disk. */
@@ -671,8 +669,8 @@ function resolvePromptOs(): "linux" | "mac" | "docker" {
671669 /**
672670 * Build the system prompt for the current state.
673671 *
674- * Separated from `init` because it's called on every turn (git state
675- * may change between turns).
672+ * Separated from `init` because turns still rebuild the assembled prompt
673+ * from the session-stable prompt context plus the current runtime state.
676674 */
677675 export function buildPrompt(state: AppState): string {
678676 return buildSystemPrompt({
@@ -790,8 +788,11 @@ export async function main(): Promise<void> {
790788 const rawPrompt = await resolveHeadlessPrompt(cli, tty, async () => {
791789 return Bun.stdin.text();
792790 });
793- const { runHeadlessPrompt } = await import("./headless.ts");
794- const stopReason = await runHeadlessPrompt(state, rawPrompt);
791+ const { runHeadlessPrompt, runHeadlessPromptText } =
792+ await import("./headless.ts");
793+ const stopReason = cli.json
794+ ? await runHeadlessPrompt(state, rawPrompt)
795+ : await runHeadlessPromptText(state, rawPrompt);
795796 if (stopReason === "aborted") {
796797 process.exitCode = 130;
797798 } else if (stopReason === "error") {
src/submit.test.ts+0−37
@@ -1,37 +0,0 @@
1-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2-import { mkdtempSync, rmSync } from "node:fs";
3-import { tmpdir } from "node:os";
4-import { join } from "node:path";
5-import { resolveRawInput } from "./submit.ts";
6-
7-let tmp: string;
8-
9-beforeEach(() => {
10- tmp = mkdtempSync(join(tmpdir(), "mc-submit-"));
11-});
12-
13-afterEach(() => {
14- rmSync(tmp, { recursive: true, force: true });
15-});
16-
17-describe("submit", () => {
18- test("resolveRawInput returns a user-facing error when a referenced skill file cannot be read", () => {
19- const result = resolveRawInput("/skill:code-review audit the diff", {
20- model: null,
21- cwd: tmp,
22- skills: [
23- {
24- name: "code-review",
25- description: "Review code changes.",
26- path: join(tmp, "missing", "SKILL.md"),
27- },
28- ],
29- });
30-
31- expect(result.type).toBe("error");
32- if (result.type !== "error") {
33- throw new Error("Expected an error result");
34- }
35- expect(result.message).toContain("Failed to read skill code-review:");
36- });
37-});
src/submit.ts+0−5
@@ -9,7 +9,6 @@ import type { UserMessage } from "@mariozechner/pi-ai";
99 import type { AgentEvent } from "./agent.ts";
1010 import { runAgentLoop } from "./agent.ts";
1111 import { getErrorMessage } from "./errors.ts";
12-import { getGitState } from "./git.ts";
1312 import {
1413 type AppState,
1514 buildPrompt,
@@ -328,7 +327,6 @@ export async function submitResolvedInput(
328327 content,
329328 timestamp: Date.now(),
330329 } satisfies UserMessage;
331- const loadGitState = state.loadGitState ?? getGitState;
332330
333331 const turn = appendMessage(state.db, session.id, userMessage);
334332 state.messages.push(userMessage);
@@ -338,8 +336,6 @@ export async function submitResolvedInput(
338336 );
339337 hooks?.onUserMessage?.(state);
340338
341- state.git = await loadGitState(state.cwd);
342-
343339 const systemPrompt = buildPrompt(state);
344340 const { tools, toolHandlers } = buildToolList(state);
345341 const modelMessages = filterModelMessages(state.messages);
@@ -371,7 +367,6 @@ export async function submitResolvedInput(
371367 },
372368 });
373369 stopReason = result.stopReason;
374- state.git = await loadGitState(state.cwd);
375370 return result.stopReason;
376371 } finally {
377372 state.running = false;
src/ui.test.ts+0−63
@@ -1363,69 +1363,6 @@ describe("ui rendering", () => {
13631363 }
13641364 });
13651365
1366- test("git status refreshes after a completed turn mutates the repo", async () => {
1367- const faux = registerFauxProvider();
1368- const state = createTestState();
1369- const repo = createTempDir();
1370- const gitRefreshes: string[] = [];
1371- const cleanGitState = {
1372- root: repo,
1373- branch: "main",
1374- upstream: "origin/main",
1375- staged: 0,
1376- modified: 0,
1377- untracked: 0,
1378- ahead: 0,
1379- behind: 0,
1380- };
1381- const dirtyGitState = {
1382- ...cleanGitState,
1383- modified: 1,
1384- };
1385- const gitStates = [cleanGitState, dirtyGitState];
1386-
1387- writeFileSync(join(repo, "tracked.txt"), "initial\n", "utf-8");
1388-
1389- state.cwd = repo;
1390- state.canonicalCwd = repo;
1391- state.model = faux.getModel();
1392- state.git = cleanGitState;
1393- state.loadGitState = async (cwd) => {
1394- gitRefreshes.push(cwd);
1395- const next = gitStates.shift();
1396- if (!next) {
1397- throw new Error("Unexpected extra git refresh");
1398- }
1399- return next;
1400- };
1401- faux.setResponses([
1402- fauxAssistantMessage(
1403- [
1404- fauxToolCall("shell", {
1405- command: "printf 'updated\\n' >> tracked.txt",
1406- }),
1407- ],
1408- { stopReason: "toolUse" },
1409- ),
1410- fauxAssistantMessage("Done."),
1411- ]);
1412-
1413- try {
1414- expect(state.git?.modified).toBe(0);
1415-
1416- handleInput("update the repo", state);
1417-
1418- await waitFor(() => state.running);
1419- await waitFor(() => !state.running);
1420- expect(state.git?.modified).toBe(1);
1421- expect(gitRefreshes).toEqual([repo, repo]);
1422- } finally {
1423- await stopRunningTurn(state);
1424- faux.unregister();
1425- state.db.close();
1426- }
1427- });
1428-
14291366 test("streamed tool call arguments stay visible before execution begins", async () => {
14301367 const api = "ui-streaming-toolcall-test";
14311368 const sourceId = "ui-streaming-toolcall-test-source";