xonecas.io
64875
Mc

mini-coder / commit 8968224

fix: consolidated both tui and headleass streams into common helper

xonecas2026-04-22 89682245b5d13f9eb8563233c44ca29dc0b59e35 parent 389cf10

6 files changed

biome.json+4−1
@@ -14,7 +14,10 @@
1414 "linter": {
1515 "enabled": true,
1616 "rules": {
17- "recommended": true
17+ "recommended": true,
18+ "suspicious": {
19+ "noExplicitAny": "off"
20+ }
1821 }
1922 },
2023 "files": {
src/agent.ts+78−0
@@ -1,3 +1,14 @@
1+import {
2+ type AssistantMessage,
3+ type AssistantMessageEvent,
4+ type Context,
5+ completeSimple,
6+ type Message,
7+ streamSimple,
8+ type ToolResultMessage,
9+} from "@mariozechner/pi-ai";
10+import type { CliOptions, ToolAndRunner } from "./types";
11+
112 export const TASK_PROMPT = `# You are "mini-coder", an elite coding agent.
213
314 Behaviour guidelines:
@@ -6,3 +17,70 @@ Behaviour guidelines:
617 - When completing a task, ensure that you fulfill the contract **exactly**.
718 - Tone: use a jovial but motivated colleague persona. Be less verbose and more concise. You are working with software engineers, act appropriate, no fluff, only direct talk.
819 `;
20+
21+export async function streamAgent(
22+ apiKey: string,
23+ tools: ToolAndRunner[],
24+ systemPrompt: string,
25+ messages: Message[],
26+ options: CliOptions,
27+ streamFn?: (ev: AssistantMessageEvent) => void,
28+ toolsFn?: (tool: ToolResultMessage) => void,
29+ completeFn?: (msg: AssistantMessage, duration: number) => void,
30+) {
31+ const startTs = Date.now();
32+ const context: Context = {
33+ systemPrompt,
34+ messages,
35+ tools: tools.map((t) => t.tool),
36+ };
37+
38+ while (true) {
39+ const s = streamSimple(options.model, context, {
40+ apiKey,
41+ reasoning: options.effort,
42+ });
43+
44+ for await (const ev of s) {
45+ streamFn?.(ev);
46+ }
47+
48+ const finalMessage = await s.result();
49+ context.messages.push(finalMessage);
50+ const toolCalls = finalMessage.content.filter(
51+ (msg) => msg.type === "toolCall",
52+ );
53+
54+ for (const call of toolCalls) {
55+ const toolDef = tools.find((i) => i.tool.name === call.name);
56+ const result = (await toolDef?.runner(call.arguments)) || "";
57+ const msg: Message = {
58+ role: "toolResult",
59+ toolCallId: call.id,
60+ toolName: call.name,
61+ content: [{ type: "text", text: result }],
62+ isError: false,
63+ timestamp: Date.now(),
64+ };
65+ context.messages.push(msg);
66+ toolsFn?.(msg);
67+ }
68+
69+ if (toolCalls.length > 0) {
70+ // TODO: Investigate why we get an error: `No output for tool call id XXXX...` when
71+ // we add { apiKey } in this call. And how does it work without it?
72+ const cont = await completeSimple(options.model, context, {
73+ reasoning: options.effort,
74+ });
75+ context.messages.push(cont);
76+ }
77+
78+ // TODO: usageFn?
79+
80+ if (["stop", "error", "aborted"].includes(finalMessage.stopReason)) {
81+ // TODO: Reason?
82+ completeFn?.(finalMessage, Date.now() - startTs);
83+ return;
84+ }
85+ }
86+}
src/headless.ts+34−66
@@ -1,38 +1,29 @@
1-import {
2- type Context,
3- completeSimple,
4- streamSimple,
5- type Tool,
6-} from "@mariozechner/pi-ai";
7-import { TASK_PROMPT } from "./agent";
1+import type { Message } from "@mariozechner/pi-ai";
2+import { streamAgent, TASK_PROMPT } from "./agent";
83 import { getApiKey } from "./oauth";
94 import { bash, runBashTool } from "./tool-bash";
10-import type { CliOptions } from "./types";
5+import type { CliOptions, ToolAndRunner } from "./types";
116
127 export async function streamHeadless(
138 options: CliOptions,
149 leave: (s: string) => void,
1510 ) {
1611 const apiKey = await getApiKey(options);
17- const tools: Tool[] = [bash];
18- const context: Context = {
19- systemPrompt: TASK_PROMPT,
20- messages: [
21- { content: options.prompt ?? "", role: "user", timestamp: Date.now() },
22- ],
23- tools,
24- };
12+ const tools: ToolAndRunner[] = [{ tool: bash, runner: runBashTool }];
13+ const messages: Message[] = [
14+ { role: "user", content: options.prompt || "", timestamp: Date.now() },
15+ ];
2516
2617 console.log("mini-coder headless");
2718 console.log("-------------------");
2819
29- while (true) {
30- const s = streamSimple(options.model, context, {
31- apiKey,
32- reasoning: options.effort,
33- });
34-
35- for await (const ev of s) {
20+ await streamAgent(
21+ apiKey,
22+ tools,
23+ TASK_PROMPT,
24+ messages,
25+ options,
26+ (ev) => {
3627 switch (ev.type) {
3728 case "text_start":
3829 console.log("> Answering...");
@@ -49,51 +40,28 @@ export async function streamHeadless(
4940 );
5041 break;
5142 case "error":
52- console.log(`Error ${ev.error}`);
43+ console.log(`Error ${ev.reason}\n${ev.error.content}`);
5344 break;
5445 }
55- }
56-
57- const finalMessage = await s.result();
58- context.messages.push(finalMessage);
59- const finalContent = finalMessage.content
60- .map((m) => m.type === "text" && m.text)
61- .filter((m) => Boolean(m));
62-
63- if (finalContent.length > 0) console.log(finalContent.join("\n"));
46+ },
47+ undefined,
48+ (msg, dur) => {
49+ const text = msg.content
50+ .filter((c) => c.type === "text")
51+ .map((c) => c.text)
52+ .join("\n");
53+ console.log(`\n${text}`);
54+ console.log(
55+ `\nTotal tokens: ${msg.usage.input} in, ${msg.usage.output} out`,
56+ );
57+ console.log(`Cost: $${msg.usage.cost.total.toFixed(4)}`);
6458
65- const toolCalls = finalMessage.content.filter((b) => b.type === "toolCall");
66- for (const call of toolCalls) {
67- const result = await runBashTool(call.arguments.command);
68-
69- context.messages.push({
70- role: "toolResult",
71- toolCallId: call.id,
72- toolName: call.name,
73- content: [{ type: "text", text: result }],
74- isError: false,
75- timestamp: Date.now(),
76- });
77- }
78-
79- if (toolCalls.length > 0) {
80- // TODO: Investigate why we get an error: `No output for tool call id XXXX...` when
81- // we add { apiKey } in this call. And how does it work without it?
82- const cont = await completeSimple(options.model, context, {
83- reasoning: options.effort,
84- });
85- context.messages.push(cont);
86- }
87-
88- console.log(
89- `Total tokens: ${finalMessage.usage.input} in, ${finalMessage.usage.output} out`,
90- );
91- console.log(`Cost: $${finalMessage.usage.cost.total.toFixed(4)}`);
59+ if (["stop", "error", "aborted"].includes(msg.stopReason)) {
60+ console.log(`Reason for stopping: "${msg.stopReason}"`);
61+ leave(`Done. Took ${dur / 1000}s`);
62+ }
63+ },
64+ );
9265
93- if (["stop", "error", "aborted"].includes(finalMessage.stopReason)) {
94- console.log(`Reason for stopping: "${finalMessage.stopReason}"`);
95- const dur = Date.now() - context.messages[0].timestamp;
96- leave(`Done. Took ${dur / 1000}s`);
97- }
98- }
66+ leave("Done.");
9967 }
src/tool-bash.ts+2−2
@@ -32,8 +32,8 @@ export const bash: Tool = {
3232 }),
3333 };
3434
35-export async function runBashTool(command: string) {
36- const proc = Bun.spawn(["bash", "-c", command], {
35+export async function runBashTool(args: Record<string, any>) {
36+ const proc = Bun.spawn(["bash", "-c", args.command], {
3737 stdout: "pipe",
3838 stderr: "pipe",
3939 });
src/tui.ts+7−4
@@ -206,16 +206,16 @@ export async function streamTUI(state: TUIState) {
206206 id: call.id,
207207 timestamp: Date.now(),
208208 };
209- let updated = false
209+ let updated = false;
210210 state.messages = state.messages.map((msg) => {
211211 if (call.id === msg.id) {
212- updated = true
212+ updated = true;
213213 return toolMessage;
214214 }
215215 return msg;
216216 });
217217 if (!updated) {
218- state.messages.push(toolMessage)
218+ state.messages.push(toolMessage);
219219 }
220220 }
221221
@@ -271,7 +271,10 @@ export async function streamTUI(state: TUIState) {
271271
272272 state.messages = state.messages.map((msg) => {
273273 if (call.id === msg.id) {
274- let truncated = result.length > 6000 ? `${result.substring(0, 6000)}...\n\nTruncated at 6000 chars` : result
274+ const truncated =
275+ result.length > 6000
276+ ? `${result.substring(0, 6000)}...\n\nTruncated at 6000 chars`
277+ : result;
275278
276279 return {
277280 ...msg,
src/types.ts+6−1
@@ -1,4 +1,4 @@
1-import type { Context, Model, ThinkingLevel } from "@mariozechner/pi-ai";
1+import type { Context, Model, ThinkingLevel, Tool } from "@mariozechner/pi-ai";
22 import type { OAuthCredentials } from "@mariozechner/pi-ai/oauth";
33
44 export type CliOptions = {
@@ -31,3 +31,8 @@ export type SavedOAuthAuth = OAuthCredentials & {
3131 };
3232
3333 export type SavedOAuthCreds = Record<string, SavedOAuthAuth>;
34+
35+export type ToolAndRunner = {
36+ tool: Tool;
37+ runner: (args: Record<string, any>) => string | Promise<string>;
38+};