xonecas.io
64875
Mc

mini-coder / commit aad5296

feat: align headless and tool behavior with spec

xonecas2026-04-19 aad52966400ed7a8764e7c8e1cfbdf68d04aa8ec parent cf86477

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

AGENTS.md+3−1
@@ -96,4 +96,6 @@
9696 - TUI changes need real terminal validation in `tmux`; passing tests is not enough.
9797 - Stay within the agreed TODO scope. Do not pull in adjacent items without discussion.
9898 - Don't write tests that call real git commands.
99-- Don't add brittle tests that pin incidental wording, formatting, colors, layout, or other implementation-shaped output unless that exact output is the actual contract.
99+- For test work, read and follow the `testing-practices` skill, not just the generic coding guidance.
100+- Don't add brittle tests that pin incidental wording, formatting, colors, layout, render-tree plumbing, tokenizer scopes, or other implementation-shaped output unless that exact output is the actual contract.
101+- In UI tests, prefer real input paths and user-visible outcomes over poking `props.onKeyPress`, focus internals, or syntax-theme objects directly.
PROGRESS.md+1−2
@@ -1,5 +1,4 @@
11 # CURRENT TASK PROGRESS
22
3-- Benchmark loop stopped.
4-- In-progress experiment changes reverted.
53 - Progress reset for a fresh benchmark restart.
4+- Benchmark for baseline is running (command in `benchmark-baseline.sh`)
README.md+1−0
@@ -105,6 +105,7 @@ $ printf '%s\n' 'fix the failing tests' | mc
105105 - Starts when `-p/--prompt` is provided or when stdin or stdout is not a TTY.
106106 - If stdout is redirected but stdin is still interactive, pass `-p`; headless mode will not fall back to an interactive prompt.
107107 - Uses the same parser as the TUI for plain text, `/skill:name`, and standalone image paths.
108+- Without `--json`, keeps stdout script-friendly by writing only the final assistant text there, while lightweight assistant commentary snippets from tool-use turns go to stderr.
108109 - With `--json`, writes NDJSON events for completed assistant/tool-result messages plus `done` / `error` / `aborted` outcomes; queued `user_message` events may also appear. Streaming deltas are omitted.
109110 - Headless runs still persist like normal sessions and show up in `/session` history for that working directory.
110111 - Interactive slash commands such as `/model`, `/session`, and `/help` are not available in headless mode.
TODO.md+1−20
@@ -7,25 +7,8 @@ The spec and code are the sources of truth; this file is just the verified backl
77
88 ## Open issues:
99
10-- [ ] Fix headless `mc` not exiting after one-shot runs complete; explicit process exit after shutdown may be the missing piece (`src/index.ts`, `src/headless.ts`)
11-- [ ] Consolidate syntax-highlighting themes and fix `SyntaxHighlight` usage so markdown/code/tool rendering stays consistent (`src/ui/conversation.ts`, `src/theme.ts`)
12-
13-## UI render scheduling fix plan (completed)
14-
15-- [x] Centralize UI-triggered renders behind a scheduler in `src/ui.ts` so streaming, tool, and divider updates coalesce instead of calling `cel.render()` blindly
16-- [x] Stop redundant synchronous render requests from cel-managed input, scroll, and overlay paths while keeping their state mutations intact
17-- [x] Route async agent/runtime updates through the scheduler with lower-priority streaming/animation requests and normal-priority committed-state updates
18-- [x] Add focused UI tests for render coalescing/priorities, then remove the frozen-streaming open issue after verification
19-
2010 ## Spec-alignment backlog
2111
22-- [ ] Make invalid `settings.json` non-fatal at startup. Per spec, invalid or missing settings content should behave like "no saved settings" instead of aborting launch (`src/settings.ts`, `src/index.ts`)
23-- [ ] Clear queued steering messages on reset boundaries so they cannot leak across `/new`, `/undo`, `/session`, or aborted/replaced runs (`src/submit.ts`, `src/ui/commands.ts`, `src/agent.ts`)
24-- [ ] Encode Escape-over-overlay behavior in app code instead of relying on overlay blur side effects. The first `Escape` should dismiss the overlay, preserve the draft, and not interrupt the run (`src/ui.ts`, `src/ui/commands.ts`)
25-- [ ] Omit empty git fields from the system-prompt git line. Detached HEAD should not render `Git: branch ` (`src/prompt.ts`, `src/git.ts`)
26-- [ ] Return structured `shell` results that preserve stdout, stderr, and exit code instead of flattening everything into one text blob (`src/tool-shell.ts`, `src/tools.ts`, `src/ui/conversation.ts`)
27-- [ ] Escape skill catalog values before injecting them into the `<available_skills>` XML block (`src/skills.ts`, `src/prompt.ts`)
28-
2912 ## Verified UX / behavior debt
3013
3114 - [ ] Prevent `/session` from switching sessions mid-run (`src/ui/commands.ts`, `src/ui/agent.ts`)
@@ -33,10 +16,8 @@ The spec and code are the sources of truth; this file is just the verified backl
3316
3417 ## Product backlog
3518
36-- [ ] Add loop safeguards that fit the no-step-limit spec: retry policy, tool-failure/request budgets, and doom-loop detection/reminders without introducing a hard step cap (`src/agent.ts`, `src/submit.ts`, `src/prompt.ts`)
37-- [ ] Add dedicated read/search tools so the model relies less on `shell` for code discovery (`src/tools.ts`, `src/prompt.ts`, `src/ui/conversation.ts`)
3819 - [ ] Add first-class delegation/subagent support instead of relying on shell-level `mc -p` delegation (`src/agent.ts`, `src/tools.ts`, `src/prompt.ts`, `src/headless.ts`)
39-- [ ] Improve headless output when `--json` is not passed so it shows lightweight activity updates before the final answer (simple assistant commentary/snippets only; no tool-call details or reasoning) (`src/headless.ts`, `src/index.ts`)
20+- [ ] Add loop safeguards that fit the no-step-limit spec: retry policy, tool-failure/request budgets, and doom-loop detection/reminders without introducing a hard step cap (`src/agent.ts`, `src/submit.ts`, `src/prompt.ts`)
4021
4122 ## Plugin debt (verified, deferred)
4223
benchmark-baseline.sh+15−0
@@ -0,0 +1,15 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+
4+cd -- "$(dirname -- "${BASH_SOURCE[0]}")"
5+
6+PYTHONPATH="$PWD/terminal-bench" harbor run -y \
7+ --job-name benchmark-baseline-full-$(date +%F__%H-%M-%S) \
8+ --jobs-dir "$PWD/terminal-bench/jobs" \
9+ --agent-import-path mini_coder_agent:MiniCoderAgent \
10+ --ak version=0.5.12 \
11+ --model openai-codex/gpt-5.4 \
12+ --dataset terminal-bench@2.0 \
13+ --n-attempts 2 \
14+ --n-concurrent 2 \
15+ --max-retries 0
package.json+6−6
@@ -18,17 +18,17 @@
1818 "test": "bun test"
1919 },
2020 "dependencies": {
21- "@cel-tui/components": "^0.7.2",
22- "@cel-tui/core": "^0.7.2",
23- "@cel-tui/types": "^0.7.2",
24- "@mariozechner/pi-ai": "^0.66.1"
21+ "@cel-tui/components": "^0.8.0",
22+ "@cel-tui/core": "^0.8.0",
23+ "@cel-tui/types": "^0.8.0",
24+ "@mariozechner/pi-ai": "^0.67.68"
2525 },
2626 "devDependencies": {
2727 "@biomejs/biome": "^2.4.12",
2828 "@types/bun": "^1.3.12",
29- "lefthook": "^2.1.5",
29+ "lefthook": "^2.1.6",
3030 "prettier": "^3.8.3",
31- "typescript": "^6.0.2"
31+ "typescript": "^6.0.3"
3232 },
3333 "license": "MIT"
3434 }
spec.md+5−3
@@ -856,7 +856,7 @@ Commands are discoverable when the input starts with `/`: pressing `Tab` in that
856856
857857 mini-coder also supports a non-interactive one-shot mode for scripting and benchmark harnesses.
858858
859-`-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.
859+`-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 default text mode (final answer on stdout plus lightweight activity snippets on stderr) to the raw NDJSON event stream.
860860
861861 Headless mode is selected when either:
862862
@@ -875,7 +875,9 @@ Input parsing in headless mode reuses the same rules as the interactive input ar
875875
876876 ### Headless text output
877877
878-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.
878+In headless mode without `--json`, stdout contains only the final persisted assistant message's text content for the one-shot run. This preserves scriptability for stdout consumers.
879+
880+Lightweight activity updates may be written to stderr before that final answer, but only as compact assistant-text snippets from tool-use turns. No tool-call details, tool progress, reasoning/thinking text, markdown rendering, status text, or other TUI presentation output is written in this mode.
879881
880882 ### Headless JSON output
881883
@@ -926,7 +928,7 @@ On launch, mini-coder:
926928 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.
927929 8. Starts a new session only when a prompt is actually submitted (no 0-message sessions in the DB).
928930
929-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.
931+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, with any lightweight non-JSON activity snippets going to stderr, or NDJSON event output when `--json` is used.
930932
931933 ## User settings persistence
932934
src/agent.test.ts+68−0
@@ -982,6 +982,74 @@ describe("agent loop", () => {
982982 expect(deltaIndex).toBeLessThan(endIndex);
983983 });
984984
985+ test("preserves structured tool details on tool_end events and persisted tool results", async () => {
986+ faux.setResponses([
987+ fauxAssistantMessage([fauxToolCall("shell", { command: "echo test" })], {
988+ stopReason: "toolUse",
989+ }),
990+ fauxAssistantMessage("Done."),
991+ ]);
992+
993+ const shellDetails = {
994+ stdout: "out",
995+ stderr: "err",
996+ exitCode: 7,
997+ };
998+ const events: AgentEvent[] = [];
999+ const toolHandlers = new Map<string, ToolHandler>([
1000+ [
1001+ "shell",
1002+ async () => ({
1003+ content: [
1004+ { type: "text", text: "Exit code: 7\nout\n\n[stderr]\nerr" },
1005+ ],
1006+ details: shellDetails,
1007+ isError: true,
1008+ }),
1009+ ],
1010+ ]);
1011+
1012+ const session = createSession(db, { cwd: tmp });
1013+ const userMsg = makeUser("go");
1014+ const turn = appendMessage(db, session.id, userMsg);
1015+
1016+ const result = await runAgentLoop({
1017+ db,
1018+ sessionId: session.id,
1019+ turn,
1020+ model: faux.getModel(),
1021+ systemPrompt: "Test",
1022+ tools: builtinToolDefs(),
1023+ toolHandlers,
1024+ messages: [userMsg],
1025+ cwd: tmp,
1026+ onEvent: (event) => events.push(event),
1027+ });
1028+
1029+ const toolEnd = expectEvent(events, "tool_end");
1030+ const toolResultEvent = expectEvent(events, "tool_result");
1031+ expect(toolEnd.result.details).toEqual(shellDetails);
1032+ expect(toolResultEvent.message.details).toEqual(shellDetails);
1033+
1034+ const toolResult = result.messages.find(
1035+ (message) => message.role === "toolResult",
1036+ );
1037+ expect(toolResult?.role).toBe("toolResult");
1038+ if (!toolResult || toolResult.role !== "toolResult") {
1039+ throw new Error("Expected tool result message");
1040+ }
1041+ expect(toolResult.details).toEqual(shellDetails);
1042+
1043+ const dbToolResult = loadMessages(db, session.id).find(
1044+ (message) => message.role === "toolResult",
1045+ );
1046+ expect(dbToolResult?.role).toBe("toolResult");
1047+ if (!dbToolResult || dbToolResult.role !== "toolResult") {
1048+ throw new Error("Expected persisted tool result message");
1049+ }
1050+ expect(dbToolResult.details).toEqual(shellDetails);
1051+ });
1052+
9851053 test("interrupt preserves partial response", async () => {
9861054 faux.setResponses([
9871055 fauxAssistantMessage("This response will be interrupted"),
src/agent.ts+1−0
@@ -596,6 +596,7 @@ function appendToolResultMessage(
596596 toolCallId: toolCall.id,
597597 toolName: toolCall.name,
598598 content: result.content,
599+ ...(result.details !== undefined ? { details: result.details } : {}),
599600 isError: result.isError,
600601 timestamp: Date.now(),
601602 };
src/cli.ts+2−1
@@ -32,7 +32,8 @@ export interface TtyState {
3232 * Parse supported CLI arguments.
3333 *
3434 * Supports `-p, --prompt <text>` for headless one-shot mode and `--json`
35- * to stream NDJSON events instead of the default final-text output.
35+ * to stream NDJSON events instead of the default final-text mode
36+ * (stdout final answer plus stderr activity snippets).
3637 * Unknown flags and positional arguments fail eagerly.
3738 *
3839 * @param argv - Process arguments excluding the Bun executable and script path.
src/headless.test.ts+57−2
@@ -145,6 +145,46 @@ describe("headless", () => {
145145 );
146146 });
147147
148+ test("runHeadlessPromptText emits only assistant commentary snippets as activity output", async () => {
149+ faux.setResponses([
150+ fauxAssistantMessage(
151+ [
152+ fauxThinking("Need to inspect the tests first."),
153+ fauxText("I'll inspect the tests first."),
154+ fauxToolCall("shell", { command: "printf hidden-tool-call" }),
155+ ],
156+ { stopReason: "toolUse" },
157+ ),
158+ fauxAssistantMessage([
159+ fauxThinking("Need to summarize the result."),
160+ fauxText("Done."),
161+ ]),
162+ ]);
163+ const state = createTestState();
164+ let activity = "";
165+ let output = "";
166+
167+ const stopReason = await runHeadlessPromptText(
168+ state,
169+ "run the shell command",
170+ {
171+ writeActivity: (text) => {
172+ activity += text;
173+ },
174+ writeText: (text) => {
175+ output += text;
176+ },
177+ },
178+ );
179+
180+ expect(stopReason).toBe("stop");
181+ expect(activity).toBe("I'll inspect the tests first.\n");
182+ expect(activity).not.toContain("Need to inspect the tests first.");
183+ expect(activity).not.toContain("hidden-tool-call");
184+ expect(activity).not.toContain("Done.");
185+ expect(output).toBe("Done.");
186+ });
187+
148188 test("runHeadlessPrompt waits for async NDJSON writers before returning", async () => {
149189 faux.setResponses([fauxAssistantMessage("Done.")]);
150190 const state = createTestState();
@@ -164,12 +204,26 @@ describe("headless", () => {
164204 ]);
165205 });
166206
167- test("runHeadlessPromptText waits for async writers before returning", async () => {
168- faux.setResponses([fauxAssistantMessage("Done.")]);
207+ test("runHeadlessPromptText waits for async activity and final-text writers before returning", async () => {
208+ faux.setResponses([
209+ fauxAssistantMessage(
210+ [
211+ fauxText("I'll inspect the tests first."),
212+ fauxToolCall("shell", { command: "printf intermediate" }),
213+ ],
214+ { stopReason: "toolUse" },
215+ ),
216+ fauxAssistantMessage("Done."),
217+ ]);
169218 const state = createTestState();
219+ let activity = "";
170220 let output = "";
171221
172222 const stopReason = await runHeadlessPromptText(state, "reply once", {
223+ writeActivity: async (text) => {
224+ await new Promise((resolve) => setTimeout(resolve, 10));
225+ activity += text;
226+ },
173227 writeText: async (text) => {
174228 await new Promise((resolve) => setTimeout(resolve, 10));
175229 output += text;
@@ -177,6 +231,7 @@ describe("headless", () => {
177231 });
178232
179233 expect(stopReason).toBe("stop");
234+ expect(activity).toBe("I'll inspect the tests first.\n");
180235 expect(output).toBe("Done.");
181236 });
182237
src/headless.ts+97−24
@@ -12,6 +12,11 @@ import {
1212 type SubmitTurnHooks,
1313 submitResolvedInput,
1414 } from "./submit.ts";
15+import {
16+ collapseWhitespaceToNull,
17+ joinTextBlocks,
18+ truncateText,
19+} from "./text.ts";
1520
1621 // ---------------------------------------------------------------------------
1722 // Types
@@ -27,31 +32,47 @@ export interface HeadlessRunOptions {
2732
2833 /** Options for a headless final-text run. */
2934 export interface HeadlessTextRunOptions {
35+ /** Optional writer for lightweight assistant-activity snippets. */
36+ writeActivity?: (text: string) => void | Promise<void>;
3037 /** Optional writer for the final assistant text output. */
3138 writeText?: (text: string) => void | Promise<void>;
3239 }
3340
3441 interface HeadlessOutputController {
35- /** Queue text for stdout with broken-pipe handling. */
42+ /** Queue text for one output stream with broken-pipe handling. */
3643 write(text: string): void;
37- /** Attach SIGINT/stdout error handlers for the active run. */
44+ /** Attach error handlers for the active run. */
3845 attach(): void;
39- /** Remove SIGINT/stdout error handlers after the run. */
46+ /** Remove error handlers after the run. */
4047 detach(): void;
4148 /** Wait for queued writes and resolve the final stop reason. */
4249 finalize(stopReason: HeadlessStopReason): Promise<HeadlessStopReason>;
4350 }
4451
52+interface HeadlessProcessStream {
53+ /** Register an output-stream error handler. */
54+ on(event: "error", listener: (error: unknown) => void): void;
55+ /** Remove an output-stream error handler. */
56+ off(event: "error", listener: (error: unknown) => void): void;
57+ /** Write a text chunk to the stream. */
58+ write(text: string, callback?: () => void): boolean;
59+}
60+
61+const HEADLESS_ACTIVITY_MAX_CHARS = 160;
62+
4563 // ---------------------------------------------------------------------------
4664 // Helpers
4765 // ---------------------------------------------------------------------------
4866
49-function defaultWrite(text: string): Promise<void> {
67+function defaultWrite(
68+ stream: HeadlessProcessStream,
69+ text: string,
70+): Promise<void> {
5071 return new Promise((resolve, reject) => {
5172 let settled = false;
5273
5374 const cleanup = (): void => {
54- process.stdout.off("error", handleError);
75+ stream.off("error", handleError);
5576 };
5677
5778 const settle = (callback: () => void): void => {
@@ -69,9 +90,9 @@ function defaultWrite(text: string): Promise<void> {
6990 });
7091 };
7192
72- process.stdout.on("error", handleError);
93+ stream.on("error", handleError);
7394 try {
74- process.stdout.write(text, () => {
95+ stream.write(text, () => {
7596 settle(resolve);
7697 });
7798 } catch (error) {
@@ -142,6 +163,17 @@ function extractAssistantText(message: AssistantMessage | null): string {
142163 .join("");
143164 }
144165
166+function extractAssistantActivitySnippet(
167+ message: AssistantMessage,
168+): string | null {
169+ if (!message.content.some((block) => block.type === "toolCall")) {
170+ return null;
171+ }
172+
173+ const text = collapseWhitespaceToNull(joinTextBlocks(message.content));
174+ return text ? truncateText(text, HEADLESS_ACTIVITY_MAX_CHARS) : null;
175+}
176+
145177 function shouldWriteHeadlessJsonEvent(event: AgentEvent): boolean {
146178 switch (event.type) {
147179 case "user_message":
@@ -158,12 +190,17 @@ function shouldWriteHeadlessJsonEvent(event: AgentEvent): boolean {
158190
159191 function createHeadlessOutputController(
160192 state: AppState,
193+ stream: HeadlessProcessStream,
161194 writeImpl: (text: string) => void | Promise<void>,
195+ options?: {
196+ attachSigint?: boolean;
197+ },
162198 ): HeadlessOutputController {
163199 let brokenPipe = false;
164200 let outputError: unknown = null;
165201 let pendingWrite = Promise.resolve();
166202 const sigintHandler = createSigintHandler(state);
203+ const attachSigint = options?.attachSigint ?? true;
167204
168205 const stopForBrokenPipe = (): void => {
169206 if (brokenPipe) {
@@ -183,7 +220,7 @@ function createHeadlessOutputController(
183220 state.abortController?.abort();
184221 };
185222
186- const stdoutErrorHandler = (error: unknown): void => {
223+ const streamErrorHandler = (error: unknown): void => {
187224 failOutput(error);
188225 };
189226
@@ -206,12 +243,16 @@ function createHeadlessOutputController(
206243 });
207244 },
208245 attach() {
209- process.stdout.on("error", stdoutErrorHandler);
210- process.on("SIGINT", sigintHandler);
246+ stream.on("error", streamErrorHandler);
247+ if (attachSigint) {
248+ process.on("SIGINT", sigintHandler);
249+ }
211250 },
212251 detach() {
213- process.stdout.off("error", stdoutErrorHandler);
214- process.off("SIGINT", sigintHandler);
252+ stream.off("error", streamErrorHandler);
253+ if (attachSigint) {
254+ process.off("SIGINT", sigintHandler);
255+ }
215256 },
216257 async finalize(stopReason) {
217258 await pendingWrite;
@@ -244,7 +285,8 @@ export async function runHeadlessPrompt(
244285 const content = resolveHeadlessContent(state, rawInput);
245286 const output = createHeadlessOutputController(
246287 state,
247- options?.writeLine ?? ((line) => defaultWrite(`${line}\n`)),
288+ process.stdout,
289+ options?.writeLine ?? ((line) => defaultWrite(process.stdout, `${line}\n`)),
248290 );
249291 const hooks: SubmitTurnHooks = {
250292 onEvent: (event) => {
@@ -270,11 +312,12 @@ export async function runHeadlessPrompt(
270312 }
271313
272314 /**
273- * Run a single headless prompt to completion and write only the final assistant text.
315+ * Run a single headless prompt to completion and write the final assistant text.
274316 *
275317 * The raw input is parsed with the same rules as interactive input. Slash
276- * commands are rejected in headless mode. Only the final persisted assistant
277- * message's text content is written to stdout.
318+ * commands are rejected in headless mode. The final assistant text is written
319+ * to stdout, while lightweight assistant commentary snippets from tool-use
320+ * turns are written to stderr.
278321 *
279322 * @param state - Mutable application state for the run.
280323 * @param rawInput - Exact raw prompt text supplied by the user.
@@ -287,20 +330,43 @@ export async function runHeadlessPromptText(
287330 options?: HeadlessTextRunOptions,
288331 ): Promise<HeadlessStopReason> {
289332 const content = resolveHeadlessContent(state, rawInput);
290- const output = createHeadlessOutputController(
333+ const finalOutput = createHeadlessOutputController(
334+ state,
335+ process.stdout,
336+ options?.writeText ?? ((text) => defaultWrite(process.stdout, text)),
337+ );
338+ const activityOutput = createHeadlessOutputController(
291339 state,
292- options?.writeText ?? defaultWrite,
340+ process.stderr,
341+ options?.writeActivity ?? ((text) => defaultWrite(process.stderr, text)),
342+ { attachSigint: false },
293343 );
294344 let finalAssistantMessage: AssistantMessage | null = null;
295345 const hooks: SubmitTurnHooks = {
296346 onEvent: (event) => {
297- if (event.type === "assistant_message") {
298- finalAssistantMessage = event.message;
347+ switch (event.type) {
348+ case "assistant_message": {
349+ const activitySnippet = extractAssistantActivitySnippet(
350+ event.message,
351+ );
352+ if (activitySnippet) {
353+ activityOutput.write(`${activitySnippet}\n`);
354+ }
355+ return;
356+ }
357+ case "done":
358+ case "error":
359+ case "aborted":
360+ finalAssistantMessage = event.message;
361+ return;
362+ default:
363+ return;
299364 }
300365 },
301366 };
302367
303- output.attach();
368+ finalOutput.attach();
369+ activityOutput.attach();
304370 try {
305371 const stopReason = await submitResolvedInput(
306372 rawInput,
@@ -310,10 +376,17 @@ export async function runHeadlessPromptText(
310376 );
311377 const finalText = extractAssistantText(finalAssistantMessage);
312378 if (finalText.length > 0) {
313- output.write(finalText);
379+ finalOutput.write(finalText);
314380 }
315- return await output.finalize(stopReason);
381+ const [finalStopReason, activityStopReason] = await Promise.all([
382+ finalOutput.finalize(stopReason),
383+ activityOutput.finalize(stopReason),
384+ ]);
385+ return finalStopReason === "stop" || activityStopReason === "stop"
386+ ? "stop"
387+ : stopReason;
316388 } finally {
317- output.detach();
389+ activityOutput.detach();
390+ finalOutput.detach();
318391 }
319392 }
src/index.test.ts+45−0
@@ -165,6 +165,51 @@ test("bin/mc.ts reports headless command errors without a stack trace", async ()
165165 expect(result.stderr.trim().split("\n")).toHaveLength(1);
166166 });
167167
168+test("init treats invalid settings.json as no saved settings", async () => {
169+ const home = createTempDir();
170+ const configDir = join(home, ".config", "mini-coder");
171+ mkdirSync(configDir, { recursive: true });
172+ writeFileSync(join(configDir, "settings.json"), "{not json", "utf-8");
173+
174+ const result = await runChild(
175+ [
176+ process.execPath,
177+ "--eval",
178+ [
179+ `const { init } = await import(${JSON.stringify(INDEX_MODULE_URL)});`,
180+ "const state = await init();",
181+ "try {",
182+ " process.stdout.write(JSON.stringify({",
183+ " settings: state.settings,",
184+ " effort: state.effort,",
185+ " showReasoning: state.showReasoning,",
186+ " verbose: state.verbose,",
187+ " modelId: state.model ? state.model.provider + '/' + state.model.id : null,",
188+ " }));",
189+ "} finally {",
190+ " state.db.close();",
191+ "}",
192+ ].join("\n"),
193+ ],
194+ {
195+ HOME: home,
196+ PATH: process.env.PATH,
197+ SHELL: process.env.SHELL,
198+ TERM: process.env.TERM,
199+ },
200+ );
201+
202+ expect(result.exitCode).toBe(0);
203+ expect(result.stderr).toBe("");
204+ expect(JSON.parse(result.stdout)).toEqual({
205+ settings: {},
206+ effort: "medium",
207+ showReasoning: true,
208+ verbose: false,
209+ modelId: null,
210+ });
211+});
212+
168213 test("runHeadlessCli uses final-text mode by default in non-TTY environments", async () => {
169214 const state = createTestState();
170215 const calls: string[] = [];
src/index.ts+4−3
@@ -61,7 +61,7 @@ import {
6161 } from "./session.ts";
6262 import {
6363 type CustomProvider,
64- loadSettings,
64+ loadStartupSettings,
6565 resolveStartupSettings,
6666 type UserSettings,
6767 } from "./settings.ts";
@@ -588,7 +588,7 @@ export async function init(): Promise<AppState> {
588588 const { providers, oauthCredentials } = await discoverProviders();
589589
590590 // Load user settings and resolve startup defaults
591- const settings = loadSettings(SETTINGS_PATH);
591+ const settings = loadStartupSettings(SETTINGS_PATH);
592592
593593 // Discover custom providers from settings
594594 const builtInProviderNames = new Set(providers.keys());
@@ -776,7 +776,8 @@ type HeadlessCliStopReason = "stop" | "length" | "error" | "aborted";
776776 *
777777 * Non-TTY detection only decides whether headless mode should run at all.
778778 * Once headless mode is selected, `--json` is the only switch that chooses
779- * NDJSON streaming versus final-text output.
779+ * NDJSON streaming versus the default text mode (stdout final answer plus
780+ * stderr activity snippets).
780781 *
781782 * @param state - Initialized application state for the run.
782783 * @param cli - Parsed CLI options.
src/settings.test.ts+9−0
@@ -10,6 +10,7 @@ import { tmpdir } from "node:os";
1010 import { join } from "node:path";
1111 import {
1212 loadSettings,
13+ loadStartupSettings,
1314 resolveStartupSettings,
1415 saveSettings,
1516 type UserSettings,
@@ -53,6 +54,14 @@ describe("settings", () => {
5354 expect(() => loadSettings(path)).toThrow(/Failed to read settings .*:/);
5455 });
5556
57+ test("loadStartupSettings treats invalid JSON as no saved settings", () => {
58+ const dir = createTempDir();
59+ const path = join(dir, "settings.json");
60+ writeFileSync(path, "{not json", "utf-8");
61+
62+ expect(loadStartupSettings(path)).toEqual({});
63+ });
64+
5665 test("updateSettings preserves an invalid settings file instead of overwriting it", () => {
5766 const dir = createTempDir();
5867 const path = join(dir, "settings.json");
src/settings.ts+38−5
@@ -80,12 +80,34 @@ export function loadSettings(path: string): UserSettings {
8080 }
8181
8282 try {
83- const raw = JSON.parse(readFileSync(path, "utf-8")) as unknown;
84- return sanitizeSettings(raw);
83+ return parseSettingsFile(path);
8584 } catch (error) {
86- throw new Error(
87- `Failed to read settings ${path}: ${getErrorMessage(error)}`,
88- );
85+ throw createSettingsReadError(path, error);
86+ }
87+}
88+
89+/**
90+ * Load settings for startup without aborting on invalid JSON.
91+ *
92+ * Missing files and invalid JSON content are treated as empty settings so
93+ * startup behaves like there are no saved settings. Other filesystem errors
94+ * still fail with the same descriptive read error as {@link loadSettings}.
95+ *
96+ * @param path - Absolute path to `settings.json`.
97+ * @returns The validated settings object, or `{}` when startup should ignore invalid JSON.
98+ */
99+export function loadStartupSettings(path: string): UserSettings {
100+ if (!existsSync(path)) {
101+ return {};
102+ }
103+
104+ try {
105+ return parseSettingsFile(path);
106+ } catch (error) {
107+ if (error instanceof SyntaxError) {
108+ return {};
109+ }
110+ throw createSettingsReadError(path, error);
89111 }
90112 }
91113
@@ -156,6 +178,17 @@ export function resolveStartupSettings(
156178 };
157179 }
158180
181+function parseSettingsFile(path: string): UserSettings {
182+ const raw = JSON.parse(readFileSync(path, "utf-8")) as unknown;
183+ return sanitizeSettings(raw);
184+}
185+
186+function createSettingsReadError(path: string, error: unknown): Error {
187+ return new Error(
188+ `Failed to read settings ${path}: ${getErrorMessage(error)}`,
189+ );
190+}
191+
159192 /**
160193 * Validate and normalize a parsed settings object.
161194 *
src/skills.test.ts+21−1
@@ -8,7 +8,7 @@ import {
88 } from "node:fs";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
11-import { discoverSkills } from "./skills.ts";
11+import { buildSkillCatalog, discoverSkills } from "./skills.ts";
1212
1313 // ---------------------------------------------------------------------------
1414 // Helpers
@@ -93,3 +93,23 @@ describe("discoverSkills", () => {
9393 }
9494 });
9595 });
96+
97+describe("buildSkillCatalog", () => {
98+ test("XML-escapes skill values before injecting them into the catalog", () => {
99+ const catalog = buildSkillCatalog([
100+ {
101+ name: `lint<&>"'`,
102+ description: `Checks <xml> & "quotes" and 'apostrophes'`,
103+ path: `/tmp/skill<&>"'`,
104+ },
105+ ]);
106+
107+ expect(catalog).toContain("<name>lint&lt;&amp;&gt;&quot;&apos;</name>");
108+ expect(catalog).toContain(
109+ "<description>Checks &lt;xml&gt; &amp; &quot;quotes&quot; and &apos;apostrophes&apos;</description>",
110+ );
111+ expect(catalog).toContain(
112+ "<location>/tmp/skill&lt;&amp;&gt;&quot;&apos;</location>",
113+ );
114+ });
115+});
src/skills.ts+12−3
@@ -226,6 +226,15 @@ export function discoverSkills(scanPaths: string[]): Skill[] {
226226 // Catalog generation
227227 // ---------------------------------------------------------------------------
228228
229+function escapeXml(value: string): string {
230+ return value
231+ .replaceAll("&", "&amp;")
232+ .replaceAll("<", "&lt;")
233+ .replaceAll(">", "&gt;")
234+ .replaceAll('"', "&quot;")
235+ .replaceAll("'", "&apos;");
236+}
237+
229238 /**
230239 * Build the XML skill catalog for the system prompt.
231240 *
@@ -243,9 +252,9 @@ export function buildSkillCatalog(skills: Skill[]): string {
243252 .map(
244253 (s) =>
245254 ` <skill>\n` +
246- ` <name>${s.name}</name>\n` +
247- ` <description>${s.description}</description>\n` +
248- ` <location>${s.path}</location>\n` +
255+ ` <name>${escapeXml(s.name)}</name>\n` +
256+ ` <description>${escapeXml(s.description)}</description>\n` +
257+ ` <location>${escapeXml(s.path)}</location>\n` +
249258 ` </skill>`,
250259 )
251260 .join("\n");
src/submit.ts+17−0
@@ -215,6 +215,20 @@ function recordRawPromptHistory(
215215 truncatePromptHistory(state.db, MAX_PROMPT_HISTORY);
216216 }
217217
218+/**
219+ * Drop any resolved steering messages still queued on the active app state.
220+ *
221+ * Raw prompt-history rows are intentionally left untouched because queue resets
222+ * must not rewrite global input-history behavior.
223+ *
224+ * @param state - Mutable application state containing the queued steering list.
225+ */
226+export function clearQueuedUserMessages(
227+ state: Pick<AppState, "queuedUserMessages">,
228+): void {
229+ state.queuedUserMessages.length = 0;
230+}
231+
218232 /**
219233 * Queue resolved user content for the next model-request boundary of an active run.
220234 *
@@ -301,6 +315,8 @@ export async function submitResolvedInput(
301315 throw new Error("Cannot submit empty input.");
302316 }
303317
318+ clearQueuedUserMessages(state);
319+
304320 const session = ensureSession(state);
305321 recordRawPromptHistory(rawInput, state, session.id);
306322
@@ -347,6 +363,7 @@ export async function submitResolvedInput(
347363 stopReason = result.stopReason;
348364 return result.stopReason;
349365 } finally {
366+ clearQueuedUserMessages(state);
350367 state.running = false;
351368 state.abortController = null;
352369 hooks?.onTurnEnd?.(state, stopReason);
src/theme.test.ts+17−0
@@ -0,0 +1,17 @@
1+import { describe, expect, test } from "bun:test";
2+import { DEFAULT_THEME, getSyntaxHighlightTheme } from "./theme.ts";
3+
4+describe("theme", () => {
5+ test("getSyntaxHighlightTheme reuses registrations per variant and keeps code distinct from shell", () => {
6+ const markdown = getSyntaxHighlightTheme(DEFAULT_THEME, "markdown");
7+ const markdownAgain = getSyntaxHighlightTheme(DEFAULT_THEME, "markdown");
8+ const code = getSyntaxHighlightTheme(DEFAULT_THEME, "code");
9+ const shell = getSyntaxHighlightTheme(DEFAULT_THEME, "shell");
10+
11+ expect(markdownAgain).toBe(markdown);
12+ expect(markdown.name).toBe("mini-coder-markdown");
13+ expect(code.name).toBe("mini-coder-code");
14+ expect(shell.name).toBe("mini-coder-shell");
15+ expect(code).not.toBe(shell);
16+ });
17+});
src/theme.ts+184−0
@@ -12,11 +12,47 @@
1212 * @module
1313 */
1414
15+import type { SyntaxHighlightTheme } from "@cel-tui/components";
1516 import type { Color } from "@cel-tui/types";
1617
1718 /** A cel-tui palette color or the terminal default when undefined. */
1819 type ThemeColor = Color | undefined;
1920
21+type SyntaxThemeRegistration = Exclude<SyntaxHighlightTheme, string>;
22+type SyntaxThemeTokenColor = NonNullable<
23+ SyntaxThemeRegistration["tokenColors"]
24+>[number];
25+type SyntaxThemeVariant = "markdown" | "code" | "shell";
26+
27+/** ANSI16 fallback hex values for syntax-highlighter theme overrides. */
28+const ANSI_COLOR_HEX: Readonly<Record<Color, string>> = {
29+ color00: "#000000",
30+ color01: "#cd3131",
31+ color02: "#0dbc79",
32+ color03: "#e5e510",
33+ color04: "#2472c8",
34+ color05: "#bc3fbc",
35+ color06: "#11a8cd",
36+ color07: "#e5e5e5",
37+ color08: "#666666",
38+ color09: "#f14c4c",
39+ color10: "#23d18b",
40+ color11: "#f5f543",
41+ color12: "#3b8eea",
42+ color13: "#d670d6",
43+ color14: "#29b8db",
44+ color15: "#ffffff",
45+};
46+
47+const syntaxThemeCache: Record<
48+ SyntaxThemeVariant,
49+ WeakMap<Theme, SyntaxThemeRegistration>
50+> = {
51+ markdown: new WeakMap(),
52+ code: new WeakMap(),
53+ shell: new WeakMap(),
54+};
55+
2056 // ---------------------------------------------------------------------------
2157 // Types
2258 // ---------------------------------------------------------------------------
@@ -145,3 +181,151 @@ export function mergeThemes(
145181 }
146182 return merged;
147183 }
184+
185+function colorToHex(color: ThemeColor): string | undefined {
186+ return color ? ANSI_COLOR_HEX[color] : undefined;
187+}
188+
189+function pushSyntaxTokenColor(
190+ tokenColors: SyntaxThemeTokenColor[],
191+ scope: string | readonly string[],
192+ foreground: ThemeColor,
193+ fontStyle?: string,
194+): void {
195+ const foregroundHex = colorToHex(foreground);
196+ if (!foregroundHex && !fontStyle) {
197+ return;
198+ }
199+
200+ tokenColors.push({
201+ scope,
202+ settings: {
203+ ...(foregroundHex ? { foreground: foregroundHex } : {}),
204+ ...(fontStyle ? { fontStyle } : {}),
205+ },
206+ });
207+}
208+
209+function pushCodeSyntaxTokenColors(
210+ tokenColors: SyntaxThemeTokenColor[],
211+ theme: Theme,
212+): void {
213+ pushSyntaxTokenColor(
214+ tokenColors,
215+ ["comment", "quote", "doctag", "markup.quote"],
216+ theme.mutedText,
217+ "italic",
218+ );
219+ pushSyntaxTokenColor(
220+ tokenColors,
221+ ["keyword", "operator"],
222+ theme.secondaryAccentText,
223+ );
224+ pushSyntaxTokenColor(
225+ tokenColors,
226+ ["command", "function_", "function", "title"],
227+ theme.accentText,
228+ );
229+ pushSyntaxTokenColor(
230+ tokenColors,
231+ ["builtin", "built_in", "class_", "class", "inherited__", "type"],
232+ theme.accentText,
233+ );
234+ pushSyntaxTokenColor(
235+ tokenColors,
236+ ["escape", "literal", "number", "symbol"],
237+ theme.secondaryAccentText ?? theme.accentText,
238+ );
239+ pushSyntaxTokenColor(
240+ tokenColors,
241+ ["code", "string", "markup.code"],
242+ theme.diffAdded,
243+ );
244+ pushSyntaxTokenColor(tokenColors, "regexp", theme.diffRemoved);
245+ pushSyntaxTokenColor(
246+ tokenColors,
247+ ["attr", "attribute", "params", "property", "selector-attr"],
248+ theme.accentText,
249+ );
250+ pushSyntaxTokenColor(
251+ tokenColors,
252+ [
253+ "name",
254+ "tag",
255+ "selector-class",
256+ "selector-id",
257+ "selector-pseudo",
258+ "selector-tag",
259+ ],
260+ theme.accentText,
261+ );
262+}
263+
264+function pushMarkdownSyntaxTokenColors(
265+ tokenColors: SyntaxThemeTokenColor[],
266+ theme: Theme,
267+): void {
268+ pushSyntaxTokenColor(
269+ tokenColors,
270+ ["quote", "markup.quote"],
271+ theme.mutedText,
272+ "italic",
273+ );
274+ pushSyntaxTokenColor(
275+ tokenColors,
276+ ["section", "markup.heading"],
277+ theme.accentText,
278+ "bold",
279+ );
280+ pushSyntaxTokenColor(
281+ tokenColors,
282+ ["bullet", "markup.list"],
283+ theme.secondaryAccentText,
284+ "bold",
285+ );
286+ pushSyntaxTokenColor(
287+ tokenColors,
288+ ["code", "string", "markup.code"],
289+ theme.diffAdded,
290+ );
291+ pushSyntaxTokenColor(tokenColors, "link", theme.accentText, "underline");
292+ pushSyntaxTokenColor(tokenColors, "strong", undefined, "bold");
293+ pushSyntaxTokenColor(tokenColors, "emphasis", undefined, "italic");
294+}
295+
296+/**
297+ * Build the shared syntax-highlight theme registration for a UI theme variant.
298+ *
299+ * Markdown, read/code blocks, and shell/tool previews all flow through this
300+ * helper so active-theme overrides stay consistent in one place. Variant names
301+ * are included in the registration so cel-tui's internal SyntaxHighlight cache
302+ * does not collapse code and shell renders onto the same custom-theme key.
303+ *
304+ * @param theme - Active UI theme.
305+ * @param variant - Semantic highlighting variant for the rendered content.
306+ * @returns A cached cel-tui syntax-highlight theme registration.
Cut short: this commit's diff is over 1000 lines.
src/tool-common.ts+2−0
Cut short: this commit's diff is over 1000 lines.
src/tool-shell.ts+138−6
Cut short: this commit's diff is over 1000 lines.
src/tools.test.ts+37−10
Cut short: this commit's diff is over 1000 lines.
src/tools.ts+4−0
Cut short: this commit's diff is over 1000 lines.
src/ui.test.ts+507−0
Cut short: this commit's diff is over 1000 lines.
src/ui.ts+42−3
Cut short: this commit's diff is over 1000 lines.
src/ui/agent.ts+7−0
Cut short: this commit's diff is over 1000 lines.
src/ui/commands.test.ts+76−0
Cut short: this commit's diff is over 1000 lines.
src/ui/commands.ts+12−0
Cut short: this commit's diff is over 1000 lines.
src/ui/conversation.test.ts+68−27
Cut short: this commit's diff is over 1000 lines.
src/ui/conversation.ts+88−171
Cut short: this commit's diff is over 1000 lines.