@@ -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+}