@@ -7,7 +7,7 @@ import type { CliOptions, ToolAndRunner } from "./types";
77
88 export async function streamHeadless(
99 options: CliOptions,
10- leave: (s: string) => void,
10+ leave: (s?: string) => void,
1111 ) {
1212 const lastTs = Date.now();
1313 const apiKey = await getApiKey(options);
@@ -19,8 +19,13 @@ export async function streamHeadless(
1919 { role: "user", content: options.prompt || "", timestamp: Date.now() },
2020 ];
2121
22- console.log("mini-coder headless");
23- console.log("-------------------");
22+ function log(msg: string) {
23+ if (options.jsonOutput) return;
24+ console.log(msg);
25+ }
26+
27+ log("mini-coder headless");
28+ log("-------------------");
2429
2530 await streamAgent(
2631 apiKey,
@@ -31,21 +36,19 @@ export async function streamHeadless(
3136 (ev) => {
3237 switch (ev.type) {
3338 case "text_start":
34- console.log("> Answering...");
39+ log("> Answering...");
3540 break;
3641 case "thinking_start":
37- console.log("> Thinking...");
42+ log("> Thinking...");
3843 break;
3944 case "toolcall_start":
40- console.log(`> Calling tool...`);
45+ log(`> Calling tool...`);
4146 break;
4247 case "toolcall_end":
43- console.log(
44- `> ${ev.toolCall.name}: ${ev.toolCall.arguments.command}`,
45- );
48+ log(`> ${ev.toolCall.name}: ${ev.toolCall.arguments.command}`);
4649 break;
4750 case "error":
48- console.log(`Error ${ev.reason}\n${ev.error.content}`);
51+ log(`Error ${ev.reason}\n${ev.error.content}`);
4952 break;
5053 }
5154 },
@@ -55,15 +58,22 @@ export async function streamHeadless(
5558 .filter((c) => c.type === "text")
5659 .map((c) => c.text)
5760 .join("\n");
58- console.log(`\n${text}`);
59- console.log(
60- `\nTotal tokens: ${msg.usage.input} in, ${msg.usage.output} out`,
61- );
62- console.log(`Cost: $${msg.usage.cost.total.toFixed(4)}`);
61+
62+ log(`\n${text}`);
63+ log(`\nTotal tokens: ${msg.usage.input} in, ${msg.usage.output} out`);
64+ log(`Cost: $${msg.usage.cost.total.toFixed(4)}`);
65+
66+ if (options.jsonOutput) {
67+ console.log(JSON.stringify(msg, null, 4));
68+ }
6369
6470 if (["stop", "error", "aborted"].includes(msg.stopReason)) {
65- console.log(`Reason for stopping: "${msg.stopReason}"`);
66- leave(`Done. Took ${(Date.now() - lastTs) / 1000}s`);
71+ log(`Reason for stopping: "${msg.stopReason}"`);
72+ leave(
73+ !options.jsonOutput
74+ ? `Done. Took ${(Date.now() - lastTs) / 1000}s`
75+ : undefined,
76+ );
6777 }
6878 },
6979 );