@@ -1,18 +1,12 @@
11 import { basename } from "node:path";
22 import type { Color } from "@cel-tui/core";
33 import { cel, HStack, ProcessTerminal, Text, VStack } from "@cel-tui/core";
4-import {
5- type Context,
6- completeSimple,
7- type Message,
8- streamSimple,
9- type Tool,
10-} from "@mariozechner/pi-ai";
11-import { TASK_PROMPT } from "./agent";
4+import type { Message } from "@mariozechner/pi-ai";
5+import { streamAgent, TASK_PROMPT } from "./agent";
126 import { getApiKey } from "./oauth";
137 import { bash, runBashTool } from "./tool-bash";
148 import { Editor } from "./tui-editor";
15-import type { TUIMessage, TUIState } from "./types";
9+import type { ToolAndRunner, TUIMessage, TUIState } from "./types";
1610
1711 const theme = {
1812 black: "color00" as Color,
@@ -121,38 +115,25 @@ export async function streamTUI(state: TUIState) {
121115 if (state.streaming) return;
122116 state.streaming = true;
123117
124- cel.render();
125-
126118 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,
119+ const tools: ToolAndRunner[] = [{ tool: bash, runner: runBashTool }];
120+ const userPrompt = {
140121 role: "user",
122+ content: state.prompt || "",
141123 timestamp: Date.now(),
142124 };
143- context.messages.push(message as Message);
144-
145- state.messages.push(message as TUIMessage);
125+ const messages: Message[] = [userPrompt as Message];
126+ state.messages.push(userPrompt as TUIMessage);
146127 state.prompt = "";
147128 cel.render();
148129
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) {
130+ await streamAgent(
131+ apiKey,
132+ tools,
133+ TASK_PROMPT,
134+ messages,
135+ state.options,
136+ (ev) => {
156137 switch (ev.type) {
157138 case "text_start":
158139 state.activeState = "answering";
@@ -229,48 +210,16 @@ export async function streamTUI(state: TUIState) {
229210 break;
230211
231212 case "error":
232- state.messages.push({
233- role: "tool",
234- content:
235- (ev.error.errorMessage as string) ?? ev.error.content ?? "",
236- timestamp: Date.now(),
237- });
238- state.activeState = "idle";
239- cel.render();
240- break;
241213 }
242- }
243-
244- const finalMessage = await s.result();
245- context.messages.push(finalMessage);
246- const finalContent = finalMessage.content
247- .map((m) => m.type === "text" && m.text)
248- .filter((m) => Boolean(m));
249-
250- if (finalContent.length > 0) {
251- state.messages.push({
252- role: "agent",
253- content: finalContent.join("\n"),
254- timestamp: Date.now(),
255- });
256- cel.render();
257- }
258-
259- const toolCalls = finalMessage.content.filter((b) => b.type === "toolCall");
260- for (const call of toolCalls) {
261- const result = await runBashTool(call.arguments.command);
262-
263- context.messages.push({
264- role: "toolResult",
265- toolCallId: call.id,
266- toolName: call.name,
267- content: [{ type: "text", text: result }],
268- isError: false,
269- timestamp: Date.now(),
270- });
214+ },
271215
216+ (tool) => {
272217 state.messages = state.messages.map((msg) => {
273- if (call.id === msg.id) {
218+ if (tool.toolCallId === msg.id) {
219+ const result = tool.content
220+ .map((c) => (c.type === "text" ? c.text : ""))
221+ .filter((c) => Boolean(c))
222+ .join("\n");
274223 const truncated =
275224 result.length > 6000
276225 ? `${result.substring(0, 6000)}...\n\nTruncated at 6000 chars`
@@ -278,37 +227,29 @@ export async function streamTUI(state: TUIState) {
278227
279228 return {
280229 ...msg,
281- content: `${call.name}\n${JSON.stringify(call.arguments, null, 4)}\n\n${truncated}`,
230+ content: `${tool.toolName}:\n\n${truncated}`,
282231 timestamp: Date.now(),
283232 };
284233 }
285234 return msg;
286235 });
287236 cel.render();
288- }
237+ },
289238
290- if (toolCalls.length > 0) {
291- // TODO: Investigate why we get an error: `No output for tool call id XXXX...` when
292- // we add { apiKey } in this call. And how does it work without it?
293- const cont = await completeSimple(state.options.model, context, {
294- reasoning: state.options.effort,
239+ (msg, context, dur) => {
240+ const text = msg.content
241+ .filter((c) => c.type === "text")
242+ .map((c) => c.text)
243+ .join("\n");
244+ state.messages.push({
245+ role: "agent",
246+ content: text,
247+ timestamp: Date.now(),
248+ durationMs: dur,
295249 });
296- context.messages.push(cont);
297- }
298-
299- // TODO: Update TUIMessages to include usage, so we can show in the UI?
300- // console.log(
301- // `Total tokens: ${finalMessage.usage.input} in, ${finalMessage.usage.output} out`,
302- // );
303- // console.log(`Cost: $${finalMessage.usage.cost.total.toFixed(4)}`);
304-
305- if (["stop", "error", "aborted"].includes(finalMessage.stopReason)) {
306250 state.streaming = false;
307- return;
308- // TODO: Update TUIMessages to include duration
309- // console.log(`Reason for stopping: "${finalMessage.stopReason}"`);
310- // const dur = Date.now() - context.messages[0].timestamp;
311- // console.log(`Done. Took ${dur / 1000}s`);
312- }
313- }
251+ state.context = context;
252+ cel.render();
253+ },
254+ );
314255 }