xonecas.io
64875
Mc

mini-coder / commit db0be01

feat: add headless one-shot CLI mode

xonecas2026-04-09 db0be01eabeb0a4b4b162d6adc0b19b16babcd49 parent 9ee5927

13 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+0−1
@@ -25,6 +25,5 @@ The spec.md and code are the sources of truth, not this file, don't assume anyth
2525
2626 ## Future ideas
2727
28-- [ ] Headless one-shot CLI mode for non-interactive runs and benchmark harnesses like Harbor/Terminal-Bench (https://www.tbench.ai/)
2928 - [ ] Divider theme plugin — customizable divider animations (scanning pulse, breathing, flowing dots, wave)
3029 - [ ] Backward-compatibility and migration policy for 1.0 (session/app data versioning, explicit migration strategy)
bin/mc.ts+1−1
@@ -9,6 +9,6 @@
99 import { main } from "../src/index.ts";
1010
1111 main().catch((err) => {
12- console.error(err);
12+ console.error(err instanceof Error ? err.message : String(err));
1313 process.exit(1);
1414 });
spec.md+60−4
@@ -584,6 +584,59 @@ Supports:
584584
585585 Commands are discoverable when the input starts with `/`: pressing `Tab` in that state switches from file-path autocomplete to interactive command select/filter.
586586
587+### Headless one-shot mode
588+
589+mini-coder also supports a non-interactive one-shot mode for scripting and benchmark harnesses.
590+
591+`-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.
592+
593+Headless mode is selected when either:
594+
595+- `-p` / `--prompt` is provided, or
596+- `stdin` is not a TTY, or
597+- `stdout` is not a TTY.
598+
599+Prompt source in headless mode:
600+
601+- If `-p` / `--prompt` is provided, that value is the raw submitted prompt.
602+- Otherwise, mini-coder reads the raw submitted prompt from `stdin` until EOF.
603+- If headless mode was selected because `stdout` is not a TTY but `stdin` is still interactive, startup fails with a clear error unless `-p` was provided. Headless mode does not fall back to an interactive prompt.
604+- Empty or whitespace-only headless input is an error.
605+
606+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.
607+
608+### Headless JSON output
609+
610+In headless mode, stdout is a newline-delimited JSON stream (NDJSON). Each line is one JSON object with a `type` field.
611+
612+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.
613+
614+At minimum, the streamed event types are:
615+
616+- `text_delta`
617+- `thinking_delta`
618+- `toolcall_start`
619+- `toolcall_delta`
620+- `toolcall_end`
621+- `assistant_message`
622+- `tool_start`
623+- `tool_delta`
624+- `tool_end`
625+- `tool_result`
626+- `done`
627+- `error`
628+- `aborted`
629+
630+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.
631+
632+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.
633+
634+### Headless persistence semantics
635+
636+Headless runs persist exactly like interactive runs. A normal session is created lazily when the prompt is submitted, messages are stored with the usual conversational turn numbering, and the raw submitted prompt is recorded in `prompt_history` before any `/skill:name` expansion or image conversion.
637+
638+This means headless one-shot runs appear in normal `/session` history for that working directory and are included in the same session/message retention rules as interactive use.
639+
587640 ### Startup
588641
589642 On launch, mini-coder:
@@ -596,10 +649,13 @@ On launch, mini-coder:
596649 - `showReasoning`: if present, use it; otherwise fall back to `true`.
597650 - `verbose`: if present, use it; otherwise fall back to `false`.
598651 4. Loads AGENTS.md files, skills, plugins.
599-5. Renders the UI with an empty conversation log and the status bar populated.
600-6. Starts a new session when the user sends a message (no 0-message sessions in the DB).
652+5. Selects the launch mode:
653+ - Interactive TUI when `stdin` and `stdout` are both TTYs and `-p` was not provided.
654+ - Headless one-shot mode otherwise.
655+6. In interactive mode, renders the UI with an empty conversation log and the status bar populated.
656+7. Starts a new session only when a prompt is actually submitted (no 0-message sessions in the DB).
601657
602-No banner or splash screen. The status bar already shows all the context the user needs.
658+No banner or splash screen. In headless mode, stdout is reserved for NDJSON event output; in interactive mode, the status bar already shows all the context the user needs.
603659
604660 ## User settings persistence
605661
@@ -679,7 +735,7 @@ CREATE INDEX idx_prompt_history_created_at ON prompt_history(created_at, id);
679735
680736 **Session truncation**: sessions are truncated per cwd to keep only the 20 most recently updated sessions (`updated_at DESC`), deleting older sessions and their messages via cascade.
681737
682-**Raw input history is global and append-only**: submitted prompt text is also recorded separately in `prompt_history` as the exact raw input the user entered before any `/skill:name` expansion or image conversion. This history is global across sessions and working directories, ordered newest first for `Ctrl+R` search, and is independent from conversational turn state — `/undo` does not remove entries from it. To bound storage, only the 1000 most recent prompt-history rows are kept.
738+**Raw input history is global and append-only**: submitted prompt text is also recorded separately in `prompt_history` as the exact raw input the user entered (interactive mode) or supplied (headless mode) before any `/skill:name` expansion or image conversion. This history is global across sessions and working directories, ordered newest first for `Ctrl+R` search, and is independent from conversational turn state — `/undo` does not remove entries from it. To bound storage, only the 1000 most …
683739
684740 ### Operations
685741
src/cli.test.ts+113−0
@@ -0,0 +1,113 @@
1+import { describe, expect, test } from "bun:test";
2+import {
3+ parseCliArgs,
4+ resolveHeadlessPrompt,
5+ shouldUseHeadlessMode,
6+} from "./cli.ts";
7+
8+describe("cli", () => {
9+ test("parseCliArgs recognizes -p and --prompt", () => {
10+ expect(parseCliArgs(["-p", "fix the tests"])).toEqual({
11+ prompt: "fix the tests",
12+ });
13+ expect(parseCliArgs(["--prompt", "fix the tests"])).toEqual({
14+ prompt: "fix the tests",
15+ });
16+ expect(parseCliArgs(["--prompt=fix the tests"])).toEqual({
17+ prompt: "fix the tests",
18+ });
19+ });
20+
21+ test("parseCliArgs rejects a missing prompt value", () => {
22+ expect(() => parseCliArgs(["-p"])).toThrow(
23+ "Missing value for -p/--prompt.",
24+ );
25+ expect(() => parseCliArgs(["--prompt"])).toThrow(
26+ "Missing value for -p/--prompt.",
27+ );
28+ });
29+
30+ test("parseCliArgs rejects unknown arguments", () => {
31+ expect(() => parseCliArgs(["--wat"])).toThrow("Unknown argument: --wat");
32+ expect(() => parseCliArgs(["extra"])).toThrow(
33+ "Unexpected positional argument: extra",
34+ );
35+ });
36+
37+ test("shouldUseHeadlessMode selects prompt mode or missing TTYs", () => {
38+ expect(
39+ shouldUseHeadlessMode(
40+ { prompt: null },
41+ { stdinIsTTY: true, stdoutIsTTY: true },
42+ ),
43+ ).toBe(false);
44+ expect(
45+ shouldUseHeadlessMode(
46+ { prompt: "fix the tests" },
47+ { stdinIsTTY: true, stdoutIsTTY: true },
48+ ),
49+ ).toBe(true);
50+ expect(
51+ shouldUseHeadlessMode(
52+ { prompt: null },
53+ { stdinIsTTY: false, stdoutIsTTY: true },
54+ ),
55+ ).toBe(true);
56+ expect(
57+ shouldUseHeadlessMode(
58+ { prompt: null },
59+ { stdinIsTTY: true, stdoutIsTTY: false },
60+ ),
61+ ).toBe(true);
62+ });
63+
64+ test("resolveHeadlessPrompt prefers the CLI prompt and preserves whitespace", async () => {
65+ const prompt = await resolveHeadlessPrompt(
66+ { prompt: " fix the tests " },
67+ { stdinIsTTY: true, stdoutIsTTY: false },
68+ async () => {
69+ throw new Error("stdin should not be read");
70+ },
71+ );
72+
73+ expect(prompt).toBe(" fix the tests ");
74+ });
75+
76+ test("resolveHeadlessPrompt reads piped stdin when no CLI prompt was provided", async () => {
77+ const prompt = await resolveHeadlessPrompt(
78+ { prompt: null },
79+ { stdinIsTTY: false, stdoutIsTTY: true },
80+ async () => "fix the tests\n",
81+ );
82+
83+ expect(prompt).toBe("fix the tests\n");
84+ });
85+
86+ test("resolveHeadlessPrompt rejects interactive stdin when stdout is not a TTY", async () => {
87+ await expect(
88+ resolveHeadlessPrompt(
89+ { prompt: null },
90+ { stdinIsTTY: true, stdoutIsTTY: false },
91+ async () => "",
92+ ),
93+ ).rejects.toThrow("Headless mode requires -p/--prompt or piped stdin.");
94+ });
95+
96+ test("resolveHeadlessPrompt rejects empty headless input", async () => {
97+ await expect(
98+ resolveHeadlessPrompt(
99+ { prompt: " \n\t" },
100+ { stdinIsTTY: true, stdoutIsTTY: false },
101+ async () => "",
102+ ),
103+ ).rejects.toThrow("Headless input is empty.");
104+
105+ await expect(
106+ resolveHeadlessPrompt(
107+ { prompt: null },
108+ { stdinIsTTY: false, stdoutIsTTY: true },
109+ async () => " \n",
110+ ),
111+ ).rejects.toThrow("Headless input is empty.");
112+ });
113+});
src/cli.ts+124−0
@@ -0,0 +1,124 @@
1+/**
2+ * CLI argument parsing and launch-mode selection.
3+ *
4+ * @module
5+ */
6+
7+// ---------------------------------------------------------------------------
8+// Types
9+// ---------------------------------------------------------------------------
10+
11+/** Parsed CLI options for the current launch. */
12+export interface CliOptions {
13+ /** One-shot prompt text, or `null` when not provided. */
14+ prompt: string | null;
15+}
16+
17+/** TTY availability for stdin/stdout. */
18+export interface TtyState {
19+ /** Whether stdin is attached to a TTY. */
20+ stdinIsTTY: boolean;
21+ /** Whether stdout is attached to a TTY. */
22+ stdoutIsTTY: boolean;
23+}
24+
25+// ---------------------------------------------------------------------------
26+// Argument parsing
27+// ---------------------------------------------------------------------------
28+
29+/**
30+ * Parse supported CLI arguments.
31+ *
32+ * Currently supports only `-p, --prompt <text>` for headless one-shot mode.
33+ * Unknown flags and positional arguments fail eagerly.
34+ *
35+ * @param argv - Process arguments excluding the Bun executable and script path.
36+ * @returns The parsed CLI options.
37+ */
38+export function parseCliArgs(argv: readonly string[]): CliOptions {
39+ let prompt: string | null = null;
40+
41+ for (let index = 0; index < argv.length; index += 1) {
42+ const arg = argv[index];
43+ if (!arg) {
44+ continue;
45+ }
46+
47+ if (arg === "-p" || arg === "--prompt") {
48+ const value = argv[index + 1];
49+ if (value == null) {
50+ throw new Error("Missing value for -p/--prompt.");
51+ }
52+ prompt = value;
53+ index += 1;
54+ continue;
55+ }
56+
57+ if (arg.startsWith("--prompt=")) {
58+ prompt = arg.slice("--prompt=".length);
59+ continue;
60+ }
61+
62+ if (arg.startsWith("-")) {
63+ throw new Error(`Unknown argument: ${arg}`);
64+ }
65+
66+ throw new Error(`Unexpected positional argument: ${arg}`);
67+ }
68+
69+ return { prompt };
70+}
71+
72+// ---------------------------------------------------------------------------
73+// Mode selection
74+// ---------------------------------------------------------------------------
75+
76+/**
77+ * Return whether the current launch should run in headless mode.
78+ *
79+ * Headless mode is selected when a one-shot prompt was provided or when
80+ * either stdin or stdout is not attached to a TTY.
81+ *
82+ * @param options - Parsed CLI options.
83+ * @param tty - Current TTY availability.
84+ * @returns `true` when headless mode should be used.
85+ */
86+export function shouldUseHeadlessMode(
87+ options: CliOptions,
88+ tty: TtyState,
89+): boolean {
90+ return options.prompt !== null || !tty.stdinIsTTY || !tty.stdoutIsTTY;
91+}
92+
93+/**
94+ * Resolve the raw prompt text for headless mode.
95+ *
96+ * Prefers the explicit CLI prompt. Otherwise reads all of stdin. Empty or
97+ * whitespace-only input is rejected.
98+ *
99+ * @param options - Parsed CLI options.
100+ * @param tty - Current TTY availability.
101+ * @param readStdin - Callback that returns the full stdin contents.
102+ * @returns The raw prompt text to submit.
103+ */
104+export async function resolveHeadlessPrompt(
105+ options: CliOptions,
106+ tty: TtyState,
107+ readStdin: () => Promise<string>,
108+): Promise<string> {
109+ const rawPrompt =
110+ options.prompt !== null
111+ ? options.prompt
112+ : tty.stdinIsTTY
113+ ? null
114+ : await readStdin();
115+
116+ if (rawPrompt === null) {
117+ throw new Error("Headless mode requires -p/--prompt or piped stdin.");
118+ }
119+ if (rawPrompt.trim().length === 0) {
120+ throw new Error("Headless input is empty.");
121+ }
122+
123+ return rawPrompt;
124+}
src/headless.test.ts+172−0
@@ -0,0 +1,172 @@
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 type { FauxProviderRegistration } from "@mariozechner/pi-ai";
6+import {
7+ fauxAssistantMessage,
8+ fauxText,
9+ fauxThinking,
10+ fauxToolCall,
11+ registerFauxProvider,
12+} from "@mariozechner/pi-ai";
13+import { runHeadlessPrompt } from "./headless.ts";
14+import type { AppState } from "./index.ts";
15+import { listPromptHistory, loadMessages, openDatabase } from "./session.ts";
16+import { DEFAULT_THEME } from "./theme.ts";
17+
18+let tmp: string;
19+let faux: FauxProviderRegistration;
20+const states: AppState[] = [];
21+
22+beforeEach(() => {
23+ tmp = mkdtempSync(join(tmpdir(), "mc-headless-"));
24+ faux = registerFauxProvider();
25+});
26+
27+afterEach(() => {
28+ faux.unregister();
29+ for (const state of states.splice(0)) {
30+ state.db.close();
31+ }
32+ rmSync(tmp, { recursive: true, force: true });
33+});
34+
35+function createTestState(): AppState {
36+ const state: AppState = {
37+ db: openDatabase(":memory:"),
38+ session: null,
39+ model: faux.getModel(),
40+ effort: "medium",
41+ messages: [],
42+ stats: { totalInput: 0, totalOutput: 0, totalCost: 0 },
43+ agentsMd: [],
44+ skills: [],
45+ plugins: [],
46+ theme: DEFAULT_THEME,
47+ git: null,
48+ providers: new Map(),
49+ oauthCredentials: {},
50+ settings: {},
51+ settingsPath: join(tmp, "settings.json"),
52+ cwd: tmp,
53+ canonicalCwd: tmp,
54+ running: false,
55+ abortController: null,
56+ activeTurnPromise: null,
57+ showReasoning: true,
58+ verbose: false,
59+ };
60+ states.push(state);
61+ return state;
62+}
63+
64+function parseEventLines(lines: string[]): Array<Record<string, unknown>> {
65+ return lines.map((line) => JSON.parse(line) as Record<string, unknown>);
66+}
67+
68+describe("headless", () => {
69+ test("runHeadlessPrompt streams NDJSON events and persists the completed turn", async () => {
70+ faux.setResponses([
71+ fauxAssistantMessage([
72+ fauxThinking("Need to inspect the failing test."),
73+ fauxText("Done."),
74+ ]),
75+ ]);
76+ const state = createTestState();
77+ const lines: string[] = [];
78+
79+ const stopReason = await runHeadlessPrompt(state, "fix the tests", {
80+ writeLine: (line) => {
81+ lines.push(line);
82+ },
83+ });
84+
85+ const events = parseEventLines(lines);
86+ expect(stopReason).toBe("stop");
87+ expect(events.some((event) => event.type === "thinking_delta")).toBe(true);
88+ expect(events.some((event) => event.type === "assistant_message")).toBe(
89+ true,
90+ );
91+ expect(events.at(-1)?.type).toBe("done");
92+
93+ const sessionId = state.session?.id;
94+ if (!sessionId) {
95+ throw new Error("Expected a session to be created");
96+ }
97+
98+ expect(
99+ loadMessages(state.db, sessionId).map((message) => message.role),
100+ ).toEqual(["user", "assistant"]);
101+ expect(listPromptHistory(state.db, 1)[0]?.text).toBe("fix the tests");
102+ });
103+
104+ test("runHeadlessPrompt rejects slash commands before creating a session", async () => {
105+ const state = createTestState();
106+ const lines: string[] = [];
107+
108+ await expect(
109+ runHeadlessPrompt(state, "/help", {
110+ writeLine: (line) => {
111+ lines.push(line);
112+ },
113+ }),
114+ ).rejects.toThrow("Headless mode does not support slash commands: /help");
115+
116+ expect(lines).toEqual([]);
117+ expect(state.session).toBeNull();
118+ expect(listPromptHistory(state.db, 1)).toEqual([]);
119+ });
120+
121+ test("runHeadlessPrompt streams tool execution events for tool-use turns", async () => {
122+ faux.setResponses([
123+ fauxAssistantMessage(
124+ [fauxToolCall("shell", { command: "printf tool-output" })],
125+ { stopReason: "toolUse" },
126+ ),
127+ fauxAssistantMessage("Done."),
128+ ]);
129+ const state = createTestState();
130+ const lines: string[] = [];
131+
132+ const stopReason = await runHeadlessPrompt(state, "run the shell command", {
133+ writeLine: (line) => {
134+ lines.push(line);
135+ },
136+ });
137+
138+ const events = parseEventLines(lines);
139+ expect(stopReason).toBe("stop");
140+ expect(events.some((event) => event.type === "tool_start")).toBe(true);
141+ expect(events.some((event) => event.type === "tool_delta")).toBe(true);
142+ expect(events.some((event) => event.type === "tool_end")).toBe(true);
143+ expect(events.some((event) => event.type === "tool_result")).toBe(true);
144+
145+ const sessionId = state.session?.id;
146+ if (!sessionId) {
147+ throw new Error("Expected a session to be created");
148+ }
149+
150+ expect(
151+ loadMessages(state.db, sessionId).map((message) => message.role),
152+ ).toEqual(["user", "assistant", "toolResult", "assistant"]);
153+ });
154+
155+ test("runHeadlessPrompt treats broken stdout pipes as a quiet shutdown", async () => {
156+ faux.setResponses([fauxAssistantMessage("Done.")]);
157+ const state = createTestState();
158+ const brokenPipe = Object.assign(new Error("broken pipe"), {
159+ code: "EPIPE",
160+ });
161+
162+ const stopReason = await runHeadlessPrompt(state, "reply once", {
163+ writeLine: () => {
164+ throw brokenPipe;
165+ },
166+ });
167+
168+ expect(stopReason).toBe("stop");
169+ expect(state.running).toBe(false);
170+ expect(state.abortController).toBeNull();
171+ });
172+});
src/headless.ts+140−0
@@ -0,0 +1,140 @@
1+/**
2+ * Headless one-shot execution.
3+ *
4+ * @module
5+ */
6+
7+import type { AppState } from "./index.ts";
8+import {
9+ resolveRawInput,
10+ type SubmitTurnHooks,
11+ submitResolvedInput,
12+} from "./submit.ts";
13+
14+// ---------------------------------------------------------------------------
15+// Types
16+// ---------------------------------------------------------------------------
17+
18+/** Options for a headless one-shot run. */
19+export interface HeadlessRunOptions {
20+ /** Optional line writer for NDJSON event output. */
21+ writeLine?: (line: string) => void;
22+}
23+
24+// ---------------------------------------------------------------------------
25+// Helpers
26+// ---------------------------------------------------------------------------
27+
28+function defaultWriteLine(line: string): void {
29+ process.stdout.write(`${line}\n`);
30+}
31+
32+function isBrokenPipeError(error: unknown): boolean {
33+ return (
34+ typeof error === "object" &&
35+ error !== null &&
36+ (("code" in error && error.code === "EPIPE") ||
37+ ("message" in error &&
38+ typeof error.message === "string" &&
39+ error.message.includes("broken pipe")))
40+ );
41+}
42+
43+function createSigintHandler(state: AppState): () => void {
44+ return () => {
45+ state.abortController?.abort();
46+ };
47+}
48+
49+function buildCommandError(command: string): Error {
50+ return new Error(
51+ `Headless mode does not support slash commands: /${command}`,
52+ );
53+}
54+
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(
68+ state: AppState,
69+ rawInput: string,
70+ options?: HeadlessRunOptions,
71+): Promise<"stop" | "length" | "error" | "aborted"> {
72+ const resolved = resolveRawInput(rawInput, state);
73+ switch (resolved.type) {
74+ case "empty":
75+ throw new Error("Headless input is empty.");
76+ case "error":
77+ throw new Error(resolved.message);
78+ case "command":
79+ throw buildCommandError(resolved.command);
80+ case "message":
81+ break;
82+ }
83+
84+ let brokenPipe = false;
85+ let outputError: unknown = null;
86+ const stopForBrokenPipe = (): void => {
87+ if (brokenPipe) {
88+ return;
89+ }
90+ brokenPipe = true;
91+ state.abortController?.abort();
92+ };
93+ const writeLineImpl = options?.writeLine ?? defaultWriteLine;
94+ const writeLine = (line: string): void => {
95+ if (brokenPipe) {
96+ return;
97+ }
98+
99+ try {
100+ writeLineImpl(line);
101+ } catch (error) {
102+ if (!isBrokenPipeError(error)) {
103+ throw error;
104+ }
105+ stopForBrokenPipe();
106+ }
107+ };
108+ const hooks: SubmitTurnHooks = {
109+ onEvent: (event) => {
110+ writeLine(JSON.stringify(event));
111+ },
112+ };
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();
121+ };
122+
123+ process.stdout.on("error", stdoutErrorHandler);
124+ process.on("SIGINT", sigintHandler);
125+ try {
126+ const stopReason = await submitResolvedInput(
127+ rawInput,
128+ resolved.content,
129+ state,
130+ hooks,
131+ );
132+ if (outputError) {
133+ throw outputError;
134+ }
135+ return brokenPipe ? "stop" : stopReason;
136+ } finally {
137+ process.stdout.off("error", stdoutErrorHandler);
138+ process.off("SIGINT", sigintHandler);
139+ }
140+}
src/index.test.ts+43−16
@@ -75,31 +75,27 @@ afterEach(() => {
7575 }
7676 });
7777
78-async function importIndexInChild(): Promise<{
78+async function runChild(
79+ command: string[],
80+ env: Record<string, string | undefined> = process.env,
81+): Promise<{
7982 exitCode: number;
8083 stdout: string;
8184 stderr: string;
8285 }> {
83- const proc = Bun.spawn(
84- [
85- process.execPath,
86- "--eval",
87- `await import(${JSON.stringify(INDEX_MODULE_URL)}); process.stdout.write("imported\\n");`,
88- ],
89- {
90- cwd: REPO_ROOT,
91- stdin: "ignore",
92- stdout: "pipe",
93- stderr: "pipe",
94- env: process.env,
95- },
96- );
86+ const proc = Bun.spawn(command, {
87+ cwd: REPO_ROOT,
88+ stdin: "ignore",
89+ stdout: "pipe",
90+ stderr: "pipe",
91+ env,
92+ });
9793
9894 let timeoutId: ReturnType<typeof setTimeout> | null = null;
9995 const timeout = new Promise<never>((_, reject) => {
10096 timeoutId = setTimeout(() => {
10197 proc.kill();
102- reject(new Error("Timed out waiting for index import to exit"));
98+ reject(new Error("Timed out waiting for child process to exit"));
10399 }, 1_000);
104100 });
105101
@@ -118,6 +114,18 @@ async function importIndexInChild(): Promise<{
118114 return { exitCode, stdout, stderr };
119115 }
120116
117+async function importIndexInChild(): Promise<{
118+ exitCode: number;
119+ stdout: string;
120+ stderr: string;
121+}> {
122+ return runChild([
123+ process.execPath,
124+ "--eval",
125+ `await import(${JSON.stringify(INDEX_MODULE_URL)}); process.stdout.write("imported\\n");`,
126+ ]);
127+}
128+
121129 test("importing index.ts does not start the CLI", async () => {
122130 const result = await importIndexInChild();
123131
@@ -126,6 +134,25 @@ test("importing index.ts does not start the CLI", async () => {
126134 expect(result.stderr).toBe("");
127135 });
128136
137+test("bin/mc.ts reports headless command errors without a stack trace", async () => {
138+ const home = createTempDir();
139+ const result = await runChild(
140+ [process.execPath, "run", "bin/mc.ts", "--", "-p", "/help"],
141+ {
142+ HOME: home,
143+ PATH: process.env.PATH,
144+ SHELL: process.env.SHELL,
145+ TERM: process.env.TERM,
146+ },
147+ );
148+
149+ expect(result.exitCode).toBe(1);
150+ expect(result.stdout).toBe("");
151+ expect(result.stderr).toBe(
152+ "Headless mode does not support slash commands: /help\n",
153+ );
154+});
155+
129156 test("didOAuthCredentialsChange compares refreshed credentials structurally", () => {
130157 const current = {
131158 refresh: "refresh-token",
src/index.ts+69−2
@@ -23,6 +23,11 @@ import type {
2323 import { getEnvApiKey, getModels, getProviders } from "@mariozechner/pi-ai";
2424 import { getOAuthApiKey, getOAuthProviders } from "@mariozechner/pi-ai/oauth";
2525 import type { ToolHandler } from "./agent.ts";
26+import {
27+ parseCliArgs,
28+ resolveHeadlessPrompt,
29+ shouldUseHeadlessMode,
30+} from "./cli.ts";
2631 import { type GitState, getGitState } from "./git.ts";
2732 import { canonicalizePath } from "./paths.ts";
2833 import {
@@ -40,12 +45,15 @@ import {
4045 resolveAgentsScanRoot,
4146 } from "./prompt.ts";
4247 import {
48+ appendMessage,
4349 computeStats,
50+ createSession,
4451 filterModelMessages,
4552 type loadMessages,
4653 openDatabase,
4754 type Session,
4855 type SessionStats,
56+ truncateSessions,
4957 } from "./session.ts";
5058 import {
5159 loadSettings,
@@ -523,6 +531,40 @@ export function buildToolList(state: AppState): {
523531 return buildTools(state.model, state.plugins);
524532 }
525533
534+/**
535+ * Ensure the app has an active persisted session.
536+ *
537+ * Creates the session lazily on the first submitted prompt and backfills any
538+ * already-present messages into the new session.
539+ *
540+ * @param state - Application state.
541+ * @returns The active persisted session.
542+ */
543+export function ensureSession(
544+ state: AppState,
545+): NonNullable<AppState["session"]> {
546+ if (state.session) {
547+ return state.session;
548+ }
549+
550+ const modelLabel = state.model
551+ ? `${state.model.provider}/${state.model.id}`
552+ : undefined;
553+ const session = createSession(state.db, {
554+ cwd: state.canonicalCwd,
555+ model: modelLabel,
556+ effort: state.effort,
557+ });
558+ truncateSessions(state.db, state.canonicalCwd, MAX_SESSIONS_PER_CWD);
559+ state.session = session;
560+
561+ for (const message of state.messages) {
562+ appendMessage(state.db, session.id, message);
563+ }
564+
565+ return session;
566+}
567+
526568 /**
527569 * Get all models from authenticated providers.
528570 *
@@ -560,19 +602,44 @@ export {
560602 /**
561603 * Start the mini-coder CLI.
562604 *
563- * Initializes application state and launches the TUI.
605+ * Initializes application state and launches either the interactive TUI or
606+ * the headless one-shot runner based on CLI flags and TTY availability.
564607 *
565608 * @returns A promise that resolves once startup is complete.
566609 */
567610 export async function main(): Promise<void> {
611+ const cli = parseCliArgs(process.argv.slice(2));
612+ const tty = {
613+ stdinIsTTY: process.stdin.isTTY ?? false,
614+ stdoutIsTTY: process.stdout.isTTY ?? false,
615+ };
568616 const state = await init();
617+
618+ if (shouldUseHeadlessMode(cli, tty)) {
619+ try {
620+ const rawPrompt = await resolveHeadlessPrompt(cli, tty, async () => {
621+ return Bun.stdin.text();
622+ });
623+ const { runHeadlessPrompt } = await import("./headless.ts");
624+ const stopReason = await runHeadlessPrompt(state, rawPrompt);
625+ if (stopReason === "aborted") {
626+ process.exitCode = 130;
627+ } else if (stopReason === "error") {
628+ process.exitCode = 1;
629+ }
630+ return;
631+ } finally {
632+ await shutdown(state);
633+ }
634+ }
635+
569636 const { startUI } = await import("./ui.ts");
570637 startUI(state);
571638 }
572639
573640 if (import.meta.main) {
574641 main().catch((err) => {
575- console.error(err);
642+ console.error(err instanceof Error ? err.message : String(err));
576643 process.exit(1);
577644 });
578645 }
src/submit.test.ts+37−0
@@ -0,0 +1,37 @@
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+323−0
@@ -0,0 +1,323 @@
1+/**
2+ * Shared raw-input resolution and turn submission logic.
3+ *
4+ * @module
5+ */
6+
7+import { readFileSync } from "node:fs";
8+import type { UserMessage } from "@mariozechner/pi-ai";
9+import type { AgentEvent } from "./agent.ts";
10+import { runAgentLoop } from "./agent.ts";
11+import { getGitState } from "./git.ts";
12+import {
13+ type AppState,
14+ buildPrompt,
15+ buildToolList,
16+ ensureSession,
17+ MAX_PROMPT_HISTORY,
18+} from "./index.ts";
19+import { parseInput } from "./input.ts";
20+import {
21+ addMessageToStats,
22+ appendMessage,
23+ appendPromptHistory,
24+ filterModelMessages,
25+ truncatePromptHistory,
26+} from "./session.ts";
27+import { executeReadImage } from "./tools.ts";
28+
29+// ---------------------------------------------------------------------------
30+// Types
31+// ---------------------------------------------------------------------------
32+
33+/** Result of resolving raw user input into a command, message, or error. */
34+export type ResolvedInput =
35+ | {
36+ /** Empty/whitespace-only input that should be ignored. */
37+ type: "empty";
38+ }
39+ | {
40+ /** Parsed slash command. */
41+ type: "command";
42+ /** Command name without the leading slash. */
43+ command: string;
44+ /** Raw command arguments after trimming. */
45+ args: string;
46+ }
47+ | {
48+ /** Validation or resolution error for the raw input. */
49+ type: "error";
50+ /** User-facing error message. */
51+ message: string;
52+ }
53+ | {
54+ /** Model-visible message content ready for submission. */
55+ type: "message";
56+ /** Fully resolved user content. */
57+ content: UserMessage["content"];
58+ };
59+
60+/** Hooks used by UI and headless mode around a submitted turn. */
61+export interface SubmitTurnHooks {
62+ /** Called after the user message is persisted and added to state. */
63+ onUserMessage?: (state: AppState) => void;
64+ /** Called after the run switches into the active streaming state. */
65+ onTurnStart?: (state: AppState) => void;
66+ /** Called for each agent event emitted during the turn. */
67+ onEvent?: (event: AgentEvent, state: AppState) => void;
68+ /** Called after the turn finishes or aborts its active state. */
69+ onTurnEnd?: (
70+ state: AppState,
71+ stopReason: "stop" | "length" | "error" | "aborted" | null,
72+ ) => void;
73+}
74+
75+// ---------------------------------------------------------------------------
76+// Input resolution helpers
77+// ---------------------------------------------------------------------------
78+
79+/**
80+ * Strip YAML frontmatter from a skill file.
81+ *
82+ * @param content - Raw `SKILL.md` file content.
83+ * @returns The content without a leading frontmatter block.
84+ */
85+export function stripSkillFrontmatter(content: string): string {
86+ const frontmatter = content.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);
87+ return frontmatter ? content.slice(frontmatter[0].length) : content;
88+}
89+
90+/**
91+ * Check whether user content contains any meaningful model-visible payload.
92+ *
93+ * @param content - User message content to inspect.
94+ * @returns `true` when the content is empty or whitespace-only.
95+ */
96+export function isEmptyUserContent(content: UserMessage["content"]): boolean {
97+ if (typeof content === "string") {
98+ return content.trim().length === 0;
99+ }
100+
101+ return content.every(
102+ (block) => block.type === "text" && block.text.trim().length === 0,
Cut short: this commit's diff is over 1000 lines.
src/ui.ts+2−44
Cut short: this commit's diff is over 1000 lines.
src/ui/agent.ts+43−204
Cut short: this commit's diff is over 1000 lines.