@@ -2,8 +2,6 @@ import { readdir } from "node:fs/promises";
22 import { homedir, platform } from "node:os";
33 import { join } from "node:path";
44 import {
5- type AssistantMessage,
6- type AssistantMessageEvent,
75 type Context,
86 type Message,
97 streamSimple,
@@ -12,7 +10,7 @@ import {
1210 } from "@mariozechner/pi-ai";
1311 import { type StatusResult, simpleGit } from "simple-git";
1412 import { parseSkillFrontmatter } from "./shared";
15-import type { CliOptions, ToolAndRunner } from "./types";
13+import type { AgentStreamEvent, CliOptions, ToolAndRunner } from "./types";
1614
1715 const IDENTITY_PROMPT = `# You are "mini-coder", an efficient, elite coding agent.
1816
@@ -26,6 +24,7 @@ const IDENTITY_PROMPT = `# You are "mini-coder", an efficient, elite coding agen
2624 - Be efficient, don't get lost with tangents or satisfying your curiosity, root yourself on the user request.
2725 - Narrate your edits with small commentary messages during long tasks.
2826 - Do not over-scope your work, or add more scope during implementation.
27+- Avoid over-enginnering, hacks or creative solutions. The boring, simple and repliable is always preffered.
2928 - Focus on the user's request requirements to answer accurately and efficiently.
3029 - Once you've gathered enough information to complete the request, stop exploring and complete it.
3130 - Ensure that you fulfill the user's expectation, requirements and contract **exactly**.
@@ -211,28 +210,26 @@ export function insertToolUsageReminder(
211210 const toolCalls: ToolCall[] = [];
212211 messages.forEach((m) => {
213212 if (m.role === "assistant") {
214- const toolCalls = m.content.filter((b) => b.type === "toolCall");
215- toolCalls.push(...toolCalls);
213+ const toolCallsBlocks = m.content.filter((b) => b.type === "toolCall");
214+ toolCalls.push(...toolCallsBlocks);
216215 }
217216 });
217+ const recentToolCalls = toolCalls.slice(-budget);
218+ const taskSeen = recentToolCalls.some((call) => call.name === "task");
218219
219- let taskSeen = 0;
220- let idx = toolCalls.length;
221-
222- while (idx--) {
223- const name = toolCalls[idx].name;
224- if (name === "task") taskSeen++;
225- if (idx > budget && taskSeen < 1) break;
226- }
227-
228- if (taskSeen < 1) {
220+ if (toolCalls.length >= budget && !taskSeen) {
229221 output = `# System reminder:
230222
231- > You are in a tool loop. Stop and use the task tool instead.
223+> You are in a shell or edit tool calling loop poluting your context.
232224
233- ---
225+- Remember your tool choice heuristic.
226+- Plan your next actions, and use the task tool to continue.
227+- If you have completed the user request, complete your answer.
228+
229+---
234230
235- ${output}`;
231+${output}
232+`;
236233 }
237234
238235 toolMessage.content = [{ type: "text", text: output }];
@@ -240,96 +237,113 @@ export function insertToolUsageReminder(
240237 return toolMessage;
241238 }
242239
243-export async function streamAgent(
240+export async function* streamAgent(
244241 apiKey: string,
245242 tools: ToolAndRunner[],
246243 systemPrompt: string,
247244 messages: Message[],
248245 options: CliOptions,
249246 abortController?: AbortController,
250- streamFn?: (ev: AssistantMessageEvent, context: Context) => void,
251- toolsFn?: (tool: ToolResultMessage, context: Context) => ToolResultMessage,
252- completeFn?: (msg: AssistantMessage, context: Context) => void,
253-) {
247+): AsyncGenerator<AgentStreamEvent> {
254248 const context: Context = {
255249 systemPrompt: await buildSystemPrompt(systemPrompt),
256250 messages,
257251 tools: tools.map((t) => t.tool),
258252 };
259253
260- let controller: AbortController;
261- const onAbort = () => {
262- controller?.abort();
263- };
264-
265- // Wire the global abort signal to each turn http requests
266- abortController?.signal.addEventListener("abort", onAbort);
254+ while (true) {
255+ const s = streamSimple(options.model, context, {
256+ apiKey,
257+ reasoning: options.effort,
258+ signal: abortController?.signal,
259+ });
267260
268- try {
269- while (true) {
270- controller = new AbortController();
271- const s = streamSimple(options.model, context, {
272- apiKey,
273- reasoning: options.effort,
274- signal: controller.signal,
275- });
276-
277- for await (const ev of s) {
278- streamFn?.(ev, context);
279- }
261+ for await (const ev of s) {
262+ yield { type: "assistant", event: ev, context };
263+ }
280264
281- const finalMessage = await s.result();
282- context.messages.push(finalMessage);
283-
284- // Check if the agent is done, or an error/abort happened before moving
285- // on towards tool calling.
286- if (
287- ["stop", "error", "aborted", "length"].includes(finalMessage.stopReason)
288- ) {
289- // Agent is done, send the final message, and current context.
290- completeFn?.(finalMessage, context);
291- break;
292- }
265+ const finalMessage = await s.result();
266+ context.messages.push(finalMessage);
267+
268+ // Check if the agent is done, or an error/abort happened before moving
269+ // on towards tool calling.
270+ if (
271+ ["stop", "error", "aborted", "length"].includes(finalMessage.stopReason)
272+ ) {
273+ // Agent is done, send the final message, and current context.
274+ yield { type: "complete", message: finalMessage, context };
275+ break;
276+ }
293277
294- // Call tolls and per tool result callback.
295- const toolCalls = finalMessage.content.filter(
296- (msg) => msg.type === "toolCall",
297- );
298-
299- for (const call of toolCalls) {
300- let output = "";
301- let isError = false;
302- const toolDef = tools.find((i) => i.tool.name === call.name);
303- if (toolDef) {
304- try {
305- output = await toolDef.runner(call.arguments);
306- } catch (err) {
307- const error = err instanceof Error ? err.message : "Unknown error";
308- output = `Tool call failed: ${error}`;
309- isError = true;
278+ // TODO: Extract into it's own function
279+ // Call tolls and per tool result callback.
280+ const toolCalls = finalMessage.content.filter(
281+ (msg) => msg.type === "toolCall",
282+ );
283+
284+ for (const call of toolCalls) {
285+ let output = "";
286+ let isError = false;
287+
288+ const toolDef = tools.find((item) => item.tool.name === call.name);
289+ let msg: ToolResultMessage = {
290+ role: "toolResult",
291+ toolCallId: call.id,
292+ toolName: call.name,
293+ content: [{ type: "text", text: output }],
294+ isError,
295+ timestamp: Date.now(),
296+ };
297+
298+ if (!toolDef) {
299+ output = `Unknown tool: ${call.name}`;
300+ isError = true;
301+ } else {
302+ try {
303+ for await (const event of toolDef.runner(call.arguments)) {
304+ switch (event.type) {
305+ case "output":
306+ output += event.text;
307+ msg = {
308+ ...msg,
309+ content: [{ type: "text", text: event.text }],
310+ };
311+ yield {
312+ type: "tool_output",
313+ message: msg,
314+ context,
315+ };
316+ break;
317+
318+ case "result":
319+ output = event.text;
320+ break;
321+ }
310322 }
311- } else {
312- output = `Unknown tool: ${call.name}`;
323+ } catch (err) {
324+ const error = err instanceof Error ? err.message : "Unknown error";
325+ output = `Tool call failed: ${error}`;
326+ isError = true;
313327 }
314-
315- let msg: ToolResultMessage = {
316- role: "toolResult",
317- toolCallId: call.id,
318- toolName: call.name,
319- content: [{ type: "text", text: output }],
320- isError,
321- timestamp: Date.now(),
322- };
323-
324- // Update with tool results. let the user make changes if they want
325- if (toolsFn) {
326- msg = toolsFn(msg, context);
327- }
328-
329- context.messages.push(msg);
330328 }
329+
330+ msg = {
331+ role: "toolResult",
332+ toolCallId: call.id,
333+ toolName: call.name,
334+ content: [{ type: "text", text: output }],
335+ isError,
336+ timestamp: Date.now(),
337+ };
338+
339+ // Update with tool results. let the user make changes if they want
340+ context.messages.push(msg);
341+
342+ yield {
343+ type: "tool_result",
344+ message: msg,
345+ context,
346+ };
331347 }
332- } finally {
333- abortController?.signal.removeEventListener("abort", onAbort);
334348 }
335349 }