@@ -7,6 +7,7 @@ import {
77 type Context,
88 type Message,
99 streamSimple,
10+ type ToolCall,
1011 type ToolResultMessage,
1112 } from "@mariozechner/pi-ai";
1213 import { type StatusResult, simpleGit } from "simple-git";
@@ -194,6 +195,51 @@ export async function buildSystemPrompt(systemPrompt: string) {
194195 return complete;
195196 }
196197
198+export function insertToolUsageReminder(
199+ messages: Message[],
200+ toolMessage: ToolResultMessage,
201+) {
202+ // check for the last 5 tool call assistant messages
203+ // if they are non-`task` tool calls insert the reminder
204+ // as a prefix.
205+ let output = toolMessage.content
206+ .filter((b) => b.type === "text")
207+ .map((b) => b.text)
208+ .join("\n");
209+
210+ const budget = 5;
211+ const toolCalls: ToolCall[] = [];
212+ messages.forEach((m) => {
213+ if (m.role === "assistant") {
214+ const toolCalls = m.content.filter((b) => b.type === "toolCall");
215+ toolCalls.push(...toolCalls);
216+ }
217+ });
218+
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) {
229+ output = `# System reminder:
230+
231+ > You are in a tool loop. Stop and use the task tool instead.
232+
233+ ---
234+
235+ ${output}`;
236+ }
237+
238+ toolMessage.content = [{ type: "text", text: output }];
239+
240+ return toolMessage;
241+}
242+
197243 export async function streamAgent(
198244 apiKey: string,
199245 tools: ToolAndRunner[],
@@ -202,7 +248,7 @@ export async function streamAgent(
202248 options: CliOptions,
203249 abortController?: AbortController,
204250 streamFn?: (ev: AssistantMessageEvent, context: Context) => void,
205- toolsFn?: (tool: ToolResultMessage, context: Context) => void,
251+ toolsFn?: (tool: ToolResultMessage, context: Context) => ToolResultMessage,
206252 completeFn?: (msg: AssistantMessage, context: Context) => void,
207253 ) {
208254 const context: Context = {
@@ -266,7 +312,7 @@ export async function streamAgent(
266312 output = `Unknown tool: ${call.name}`;
267313 }
268314
269- const msg: ToolResultMessage = {
315+ let msg: ToolResultMessage = {
270316 role: "toolResult",
271317 toolCallId: call.id,
272318 toolName: call.name,
@@ -274,10 +320,13 @@ export async function streamAgent(
274320 isError,
275321 timestamp: Date.now(),
276322 };
277- context.messages.push(msg);
278323
279- // Update with tool results.
280- toolsFn?.(msg, context);
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);
281330 }
282331 }
283332 } finally {