xonecas.io
64875
Mc

mini-coder / commit 4b17f53

feat: TUI conversation loop

xonecas2026-04-22 4b17f53cebf8965149824b1e189b37fc674dca7d parent e423cf2

8 files changed

bun.lock+5−5
@@ -6,11 +6,11 @@
66 "name": "mini-coder-next",
77 "dependencies": {
88 "@cel-tui/core": "^0.8.1",
9- "@mariozechner/pi-ai": "^0.67.68",
9+ "@mariozechner/pi-ai": "^0.68.1",
1010 },
1111 "devDependencies": {
1212 "@biomejs/biome": "^2.4.12",
13- "@types/bun": "^1.3.12",
13+ "@types/bun": "^1.3.13",
1414 "prettier": "^3.8.3",
1515 "typescript": "^6.0.3",
1616 },
@@ -117,7 +117,7 @@
117117
118118 "@google/genai": ["@google/genai@1.50.1", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-YbkX7H9+1Pt8wOt7DDREy8XSoiL6fRDzZQRyaVBarFf8MR3zHGqVdvM4cLbDXqPhxqvegZShgfxb8kw9C7YhAQ=="],
119119
120- "@mariozechner/pi-ai": ["@mariozechner/pi-ai@0.67.68", "", { "dependencies": { "@anthropic-ai/sdk": "^0.90.0", "@aws-sdk/client-bedrock-runtime": "^3.1030.0", "@google/genai": "^1.40.0", "@mistralai/mistralai": "^2.2.0", "@sinclair/typebox": "^0.34.41", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "chalk": "^5.6.2", "openai": "6.26.0", "partial-json": "^0.1.7", "proxy-agent": "^6.5.0", "undici": "^7.19.1", "zod-to-json-schema": "^3.24.6" }, "bin": { "pi-ai": "dist/cli.js" } }, "sha512-DWWQmcb3 …
120+ "@mariozechner/pi-ai": ["@mariozechner/pi-ai@0.68.1", "", { "dependencies": { "@anthropic-ai/sdk": "^0.90.0", "@aws-sdk/client-bedrock-runtime": "^3.1030.0", "@google/genai": "^1.40.0", "@mistralai/mistralai": "^2.2.0", "@sinclair/typebox": "^0.34.41", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "chalk": "^5.6.2", "openai": "6.26.0", "partial-json": "^0.1.7", "proxy-agent": "^6.5.0", "undici": "^7.19.1", "zod-to-json-schema": "^3.24.6" }, "bin": { "pi-ai": "dist/cli.js" } }, "sha512-z52kMOZK1 …
121121
122122 "@mistralai/mistralai": ["@mistralai/mistralai@2.2.0", "", { "dependencies": { "ws": "^8.18.0", "zod": "^3.25.0 || ^4.0.0", "zod-to-json-schema": "^3.25.0" } }, "sha512-JQUGIXjFWnw/J9LpTSf/ZXwVW3Sh8FBAcfTo5QvAHqkl4CfSiIwnjRJhMoAFcP6ncCe84YPU1ncDGX+p3OXnfg=="],
123123
@@ -233,7 +233,7 @@
233233
234234 "@tootallnate/quickjs-emscripten": ["@tootallnate/quickjs-emscripten@0.23.0", "", {}, "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA=="],
235235
236- "@types/bun": ["@types/bun@1.3.12", "", { "dependencies": { "bun-types": "1.3.12" } }, "sha512-DBv81elK+/VSwXHDlnH3Qduw+KxkTIWi7TXkAeh24zpi5l0B2kUg9Ga3tb4nJaPcOFswflgi/yAvMVBPrxMB+A=="],
236+ "@types/bun": ["@types/bun@1.3.13", "", { "dependencies": { "bun-types": "1.3.13" } }, "sha512-9fqXWk5YIHGGnUau9TEi+qdlTYDAnOj+xLCmSTwXfAIqXr2x4tytJb43E9uCvt09zJURKXwAtkoH4nLQfzeTXw=="],
237237
238238 "@types/node": ["@types/node@25.6.0", "", { "dependencies": { "undici-types": "~7.19.0" } }, "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ=="],
239239
@@ -257,7 +257,7 @@
257257
258258 "buffer-equal-constant-time": ["buffer-equal-constant-time@1.0.1", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="],
259259
260- "bun-types": ["bun-types@1.3.12", "", { "dependencies": { "@types/node": "*" } }, "sha512-HqOLj5PoFajAQciOMRiIZGNoKxDJSr6qigAttOX40vJuSp6DN/CxWp9s3C1Xwm4oH7ybueITwiaOcWXoYVoRkA=="],
260+ "bun-types": ["bun-types@1.3.13", "", { "dependencies": { "@types/node": "*" } }, "sha512-QXKeHLlOLqQX9LgYaHJfzdBaV21T63HhFJnvuRCcjZiaUDpbs5ED1MgxbMra71CsryN/1dAoXuJJJwIv/2drVA=="],
261261
262262 "chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="],
263263
package.json+2−2
@@ -15,12 +15,12 @@
1515 },
1616 "devDependencies": {
1717 "@biomejs/biome": "^2.4.12",
18- "@types/bun": "^1.3.12",
18+ "@types/bun": "^1.3.13",
1919 "prettier": "^3.8.3",
2020 "typescript": "^6.0.3"
2121 },
2222 "dependencies": {
2323 "@cel-tui/core": "^0.8.1",
24- "@mariozechner/pi-ai": "^0.67.68"
24+ "@mariozechner/pi-ai": "^0.68.1"
2525 }
2626 }
src/headless.ts+4−2
@@ -1,8 +1,8 @@
11 import {
22 type Context,
3+ type Tool,
34 completeSimple,
45 streamSimple,
5- type Tool,
66 } from "@mariozechner/pi-ai";
77 import { TASK_PROMPT } from "./agent";
88 import { getApiKey } from "./oauth";
@@ -77,7 +77,9 @@ export async function streamHeadless(
7777 }
7878
7979 if (toolCalls.length > 0) {
80- const cont = await completeSimple(options.model, context);
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, {reasoning: options.effort});
8183 context.messages.push(cont);
8284 }
8385
src/index.ts+10−5
@@ -1,6 +1,7 @@
11 import { handleArgv } from "./args.ts";
22 import { streamHeadless } from "./headless.ts";
33 import { initTUI } from "./tui.ts";
4+import type { TUIActiveState } from "./types.ts";
45
56 function leave(msg: string) {
67 console.log(msg);
@@ -15,9 +16,13 @@ export async function main(): Promise<void> {
1516 process.exit(0);
1617 }
1718
18- initTUI({
19- onStop: () => {
20- leave("Done.");
21- },
22- });
19+ const state = {
20+ options,
21+ prompt: "",
22+ messages: [],
23+ activeState: "idle" as TUIActiveState,
24+ streaming: false,
25+ };
26+
27+ initTUI(state, leave);
2328 }
src/tool-bash.ts+10−3
@@ -33,9 +33,16 @@ export const bash: Tool = {
3333 };
3434
3535 export async function runBashTool(command: string) {
36- const proc = Bun.spawn(["bash", "-c", command]);
36+ const proc = Bun.spawn(["bash", "-c", command], {
37+ stdout: "pipe",
38+ stderr: "pipe",
39+ });
3740 await proc.exited;
38- const result = await proc.stdout.text();
41+ const out = await proc.stdout.text();
42+ const errorOut = await proc.stderr?.text();
3943
40- return result;
44+ if (proc.exitCode === 0) {
45+ return out;
46+ }
47+ return errorOut === "" ? `Exit code ${proc.exitCode}` : errorOut;
4148 }
src/tui-editor.ts+29−0
@@ -0,0 +1,29 @@
1+import { cel, Text, TextInput } from "@cel-tui/core";
2+import type { TUIState } from "./types";
3+
4+export function Editor(
5+ state: TUIState,
6+ onChange: (value: string) => void,
7+ onKeyPress: (key: string) => void,
8+) {
9+ let isEditorFocused = true;
10+ return TextInput({
11+ value: state.prompt,
12+ minHeight: 3,
13+ maxHeight: 10,
14+ padding: { x: 1 },
15+ placeholder: Text("Message...", { italic: true }),
16+ onChange,
17+ onKeyPress,
18+ // TODO: Update `cel-tui` with an autofocus prop to fix this pattern
19+ focused: isEditorFocused,
20+ onFocus: () => {
21+ isEditorFocused = true;
22+ cel.render();
23+ },
24+ onBlur: () => {
25+ isEditorFocused = false;
26+ cel.render();
27+ },
28+ });
29+}
src/tui.ts+203−75
@@ -1,51 +1,55 @@
11 import { basename } from "node:path";
22 import type { Color } from "@cel-tui/core";
3+import { cel, HStack, ProcessTerminal, Text, VStack } from "@cel-tui/core";
34 import {
4- cel,
5- HStack,
6- ProcessTerminal,
7- Text,
8- TextInput,
9- VStack,
10-} from "@cel-tui/core";
11-import type { TUIOptions } from "./types";
5+ type Context,
6+ completeSimple,
7+ type Message,
8+ streamSimple,
9+ type Tool,
10+} from "@mariozechner/pi-ai";
11+import { TASK_PROMPT } from "./agent";
12+import { getApiKey } from "./oauth";
13+import { bash, runBashTool } from "./tool-bash";
14+import { Editor } from "./tui-editor";
15+import type { TUIMessage, TUIState } from "./types";
1216
1317 const theme = {
14- black: "color00",
15- bblack: "color08",
18+ black: "color00" as Color,
19+ bblack: "color08" as Color,
1620
17- red: "color01",
18- bred: "color09",
21+ red: "color01" as Color,
22+ bred: "color09" as Color,
1923
20- green: "color02",
21- bgreen: "color10",
24+ green: "color02" as Color,
25+ bgreen: "color10" as Color,
2226
23- yellow: "color03",
24- byellow: "color11",
27+ yellow: "color03" as Color,
28+ byellow: "color11" as Color,
2529
26- blue: "color04",
27- bblue: "color12",
30+ blue: "color04" as Color,
31+ bblue: "color12" as Color,
2832
29- magenta: "color05",
30- bmagenta: "color13",
33+ magenta: "color05" as Color,
34+ bmagenta: "color13" as Color,
3135
32- cyan: "color06",
33- bcyan: "color14",
36+ cyan: "color06" as Color,
37+ bcyan: "color14" as Color,
3438
35- white: "color07",
36- bwhite: "color15",
39+ white: "color07" as Color,
40+ bwhite: "color15" as Color,
3741 };
3842
3943 // Examples:
4044 //
41-// TextPill("mini-coder", theme.bblack as Color, theme.black as Color),
42-// TextPill("mini-coder", theme.bred as Color, theme.red as Color),
43-// TextPill("mini-coder", theme.bgreen as Color, theme.green as Color),
44-// TextPill("mini-coder", theme.byellow as Color, theme.yellow as Color),
45-// TextPill("mini-coder", theme.bblue as Color, theme.blue as Color),
46-// TextPill("mini-coder", theme.bmagenta as Color, theme.magenta as Color),
47-// TextPill("mini-coder", theme.bcyan as Color, theme.cyan as Color),
48-// TextPill("mini-coder", theme.bwhite as Color, theme.white as Color),
45+// TextPill("mini-coder", theme.bblack, theme.black),
46+// TextPill("mini-coder", theme.bred, theme.red),
47+// TextPill("mini-coder", theme.bgreen, theme.green),
48+// TextPill("mini-coder", theme.byellow, theme.yellow),
49+// TextPill("mini-coder", theme.bblue, theme.blue),
50+// TextPill("mini-coder", theme.bmagenta, theme.magenta),
51+// TextPill("mini-coder", theme.bcyan, theme.cyan),
52+// TextPill("mini-coder", theme.bwhite, theme.white),
4953 function TextPill(content: string, fgColor: Color, bgColor: Color) {
5054 return HStack({ gap: 1 }, [
5155 HStack({ bgColor, padding: { x: 1 } }, [
@@ -54,44 +58,8 @@ function TextPill(content: string, fgColor: Color, bgColor: Color) {
5458 ]);
5559 }
5660
57-function Editor(state: { prompt: string; messages: string[] }) {
58- let isEditorFocused = true;
59- return TextInput({
60- value: state.prompt,
61- minHeight: 3,
62- maxHeight: 10,
63- padding: { x: 1 },
64- placeholder: Text("Message...", { italic: true }),
65- onChange: (value: string) => {
66- state.prompt = value;
67- cel.render();
68- },
69- onKeyPress: (key: string) => {
70- if (key === "enter") {
71- state.messages.push(state.prompt);
72- state.prompt = "";
73- cel.render();
74- return false;
75- }
76- },
77- focused: isEditorFocused,
78- onFocus: () => {
79- isEditorFocused = true;
80- cel.render();
81- },
82- onBlur: () => {
83- isEditorFocused = false;
84- cel.render();
85- },
86- });
87-}
88-
89-export function initTUI({ onStop }: TUIOptions) {
61+export function initTUI(state: TUIState, leave: (s: string) => void) {
9062 const cwd = basename(process.cwd());
91- const state = {
92- prompt: "",
93- messages: [],
94- };
9563
9664 cel.init(new ProcessTerminal());
9765 cel.setTitle(`mc | ${cwd}`);
@@ -101,27 +69,187 @@ export function initTUI({ onStop }: TUIOptions) {
10169 {
10270 height: "100%",
10371 gap: 1,
72+ padding: { x: 1, y: 1 },
10473 onKeyPress: (key) => {
105- if (key === "ctrl+q" || key === "ctrl+c") {
74+ if (key === "ctrl+q" || key === "ctrl+c" || key === "ctrl+d") {
10675 cel.stop();
107- onStop();
76+ leave("Done.");
10877 }
10978 },
11079 },
11180 [
11281 VStack({ flex: 1, gap: 1, overflow: "scroll" }, [
11382 ...state.messages.map((msg) => {
114- return Text(msg, { wrap: "word" });
83+ return VStack({ gap: 1 }, [
84+ TextPill(msg.role, theme.bwhite, theme.bblack),
85+ Text(msg.content, { wrap: "word" }),
86+ ]);
11587 }),
11688 ]),
11789
11890 HStack({ gap: 1 }, [
119- TextPill("mini-coder", theme.bblack as Color, theme.bwhite as Color),
120- TextPill(cwd, theme.bwhite as Color, theme.bblack as Color),
91+ TextPill(state.options.model.name, theme.bblack, theme.bwhite),
92+ TextPill(`../${cwd}`, theme.bwhite, theme.bblack),
93+ VStack({ flex: 1 }, []),
94+ TextPill(state.activeState, theme.bwhite, theme.bblack),
12195 ]),
12296
123- Editor(state),
97+ Editor(
98+ state,
99+ (value: string) => {
100+ // onChange
101+ state.prompt = value;
102+ cel.render();
103+ },
104+ (key: string) => {
105+ // onKeyPress
106+ if (key === "enter") {
107+ const submit = async () => {
108+ await streamTUI(state);
109+ };
110+ submit();
111+ return false;
112+ }
113+ },
114+ ),
124115 ],
125116 ),
126117 );
127118 }
119+
120+export async function streamTUI(state: TUIState) {
121+ if (state.streaming) return;
122+ state.streaming = true;
123+
124+ cel.render();
125+
126+ const apiKey = await getApiKey(state.options);
127+ const tools: Tool[] = [bash];
128+
129+ let context: Context;
130+ if (state.context) context = state.context;
131+ else {
132+ context = state.context = {
133+ systemPrompt: TASK_PROMPT,
134+ messages: [],
135+ tools,
136+ };
137+ }
138+ const message = {
139+ content: state.prompt,
140+ role: "user",
141+ timestamp: Date.now(),
142+ };
143+ context.messages.push(message as Message);
144+
145+ state.messages.push(message as TUIMessage);
146+ state.prompt = "";
147+ cel.render();
148+
149+ while (true) {
150+ const s = streamSimple(state.options.model, context, {
151+ apiKey,
152+ reasoning: state.options.effort,
153+ });
154+
155+ for await (const ev of s) {
156+ switch (ev.type) {
157+ case "text_start":
158+ state.activeState = "answering";
159+ cel.render();
160+ break;
161+ case "thinking_start":
162+ state.activeState = "thinking";
163+ cel.render();
164+ break;
165+ case "toolcall_start":
166+ state.activeState = "calling_tool";
167+ cel.render();
168+ // TODO: tool call id? So I can update the right state.
169+ // TUImessages.push({
170+ // role: "tool",
171+ // content: "Calling tool...",
172+ // });
173+ // cel.render()
174+ break;
175+ case "toolcall_end":
176+ // TODO: find pending tool call, update it's entry in TUImessages.
177+ break;
178+ case "done":
179+ state.activeState = "idle";
180+ cel.render();
181+ break;
182+ case "error":
183+ state.messages.push({
184+ role: "tool",
185+ content:
186+ (ev.error.errorMessage as string) ?? ev.error.content ?? "",
187+ timestamp: Date.now(),
188+ });
189+ state.activeState = "idle";
190+ cel.render();
191+ // TODO: find matching tool call if any and update that, or push the new error message.
192+ break;
193+ }
194+ }
195+
196+ const finalMessage = await s.result();
197+ context.messages.push(finalMessage);
198+ const finalContent = finalMessage.content
199+ .map((m) => m.type === "text" && m.text)
200+ .filter((m) => Boolean(m));
201+
202+ if (finalContent.length > 0) {
203+ state.messages.push({
204+ role: "agent",
205+ content: finalContent.join("\n"),
206+ timestamp: Date.now(),
207+ });
208+ cel.render();
209+ }
210+
211+ const toolCalls = finalMessage.content.filter((b) => b.type === "toolCall");
212+ for (const call of toolCalls) {
213+ const result = await runBashTool(call.arguments.command);
214+
215+ context.messages.push({
216+ role: "toolResult",
217+ toolCallId: call.id,
218+ toolName: call.name,
219+ content: [{ type: "text", text: result }],
220+ isError: false,
221+ timestamp: Date.now(),
222+ });
223+ state.messages.push({
224+ role: "tool",
225+ content: result.substring(0, result.length > 6000 ? 6000 : undefined),
226+ timestamp: Date.now(),
227+ });
228+ cel.render()
229+ }
230+
231+ if (toolCalls.length > 0) {
232+ // TODO: Investigate why we get an error: `No output for tool call id XXXX...` when
233+ // we add { apiKey } in this call. And how does it work without it?
234+ const cont = await completeSimple(state.options.model, context, {
235+ reasoning: state.options.effort,
236+ });
237+ context.messages.push(cont);
238+ }
239+
240+ // TODO: Update TUIMessages to include usage, so we can show in the UI?
241+ // console.log(
242+ // `Total tokens: ${finalMessage.usage.input} in, ${finalMessage.usage.output} out`,
243+ // );
244+ // console.log(`Cost: $${finalMessage.usage.cost.total.toFixed(4)}`);
245+
246+ if (["stop", "error", "aborted"].includes(finalMessage.stopReason)) {
247+ state.streaming = false;
248+ return;
249+ // TODO: Update TUIMessages to include duration
250+ // console.log(`Reason for stopping: "${finalMessage.stopReason}"`);
251+ // const dur = Date.now() - context.messages[0].timestamp;
252+ // console.log(`Done. Took ${dur / 1000}s`);
253+ }
254+ }
255+}
src/types.ts+18−3
@@ -1,4 +1,4 @@
1-import type { Model, ThinkingLevel } from "@mariozechner/pi-ai";
1+import type { Context, Model, ThinkingLevel } from "@mariozechner/pi-ai";
22 import type { OAuthCredentials } from "@mariozechner/pi-ai/oauth";
33
44 export type CliOptions = {
@@ -7,8 +7,23 @@ export type CliOptions = {
77 effort: ThinkingLevel;
88 };
99
10-export type TUIOptions = {
11- onStop: () => void;
10+export type TUIActiveState = "idle" | "thinking" | "answering" | "calling_tool";
11+
12+export type TUIMessage = {
13+ content: string;
14+ role: "agent" | "tool" | "reasoning" | "user";
15+ durationMs?: number;
16+ id?: string;
17+ timestamp: number;
18+};
19+
20+export type TUIState = {
21+ options: CliOptions;
22+ prompt: string;
23+ messages: TUIMessage[];
24+ context?: Context;
25+ activeState: TUIActiveState;
26+ streaming: boolean;
1227 };
1328
1429 export type SavedOAuthAuth = OAuthCredentials & {