xonecas.io
64875
Mc

mini-coder / commit 2dbe28d

Fix tool limit warning handling

xonecas2026-03-08 2dbe28d342c3acf593f2365f1e371a9c3a6d175b parent a26c55d

4 files changed

TODO.md+2−5
@@ -1,16 +1,13 @@
11 # TODO
22
3-## Disambiguiate CTRL+c to quit vs interrupt/return to prompt
4-
5-- Let's change it so we use ESC to interrupt gracefully the assistant (cancel)
6-
73 ---
84
9-## Weird prompt behaviours related to past
5+## Weird prompt behaviours related to paste
106
117 - Weird whitepace when reaching max line length in the terminal
128 - `PASTE` word appears verbatim sometimes
139 - Extra spaces at the end of the line, pushing the cursor away from the text
10+- Pressing two keys simultaneously triggers the paste styling
1411
1512 ---
1613
src/cli/tool-render.ts+1−1
@@ -79,7 +79,7 @@ export function toolCallLine(name: string, args: unknown): string {
7979 if (name === "shell") {
8080 const cmd = String(a.command ?? "");
8181 const shortCmd = cmd.length > 72 ? `${cmd.slice(0, 69)}…` : cmd;
82- return `${G.run} ${c.dim("$")} ${shortCmd}`;
82+ return `${G.run} ${shortCmd}`;
8383 }
8484 if (name === "subagent") {
8585 const prompt = String(a.prompt ?? "");
src/llm-api/turn.test.ts+99−1
@@ -1,5 +1,11 @@
11 import { describe, expect, test } from "bun:test";
2-import { isOpenAIGPT } from "./turn.ts";
2+import type { CoreMessage } from "./turn.ts";
3+import {
4+ createToolLimitWarningPatch,
5+ isOpenAIGPT,
6+ restoreToolLimitWarningResult,
7+ stripToolLimitWarningMessages,
8+} from "./turn.ts";
39
410 describe("isOpenAIGPT", () => {
511 test("matches openai/gpt-* models", () => {
@@ -24,3 +30,95 @@ describe("isOpenAIGPT", () => {
2430 expect(isOpenAIGPT("zen/claude-sonnet-4-6")).toBe(false);
2531 });
2632 });
33+
34+describe("tool limit warning patches", () => {
35+ test("restores warning-patched streamed tool results to their original values", () => {
36+ const jsonPatch = createToolLimitWarningPatch({ path: "foo.ts" });
37+ const textPatch = createToolLimitWarningPatch("exit 0");
38+
39+ expect(
40+ restoreToolLimitWarningResult(jsonPatch.injectedText, [
41+ jsonPatch,
42+ textPatch,
43+ ]),
44+ ).toEqual({ path: "foo.ts" });
45+ expect(
46+ restoreToolLimitWarningResult(textPatch.injectedText, [
47+ jsonPatch,
48+ textPatch,
49+ ]),
50+ ).toBe("exit 0");
51+ expect(restoreToolLimitWarningResult("plain output", [jsonPatch])).toBe(
52+ "plain output",
53+ );
54+ });
55+
56+ test("restores original text and json tool outputs for persisted messages", () => {
57+ const jsonPatch = createToolLimitWarningPatch({ lines: 2 });
58+ const textPatch = createToolLimitWarningPatch("exit 0");
59+ const toolMessage = {
60+ role: "tool",
61+ content: [
62+ {
63+ type: "tool-result",
64+ toolCallId: "1",
65+ toolName: "read",
66+ output: { type: "text", value: jsonPatch.injectedText },
67+ },
68+ ],
69+ } as CoreMessage;
70+ const assistantMessage = {
71+ role: "assistant",
72+ content: [
73+ { type: "text", text: "One last response." },
74+ {
75+ type: "tool-result",
76+ toolCallId: "2",
77+ toolName: "shell",
78+ output: { type: "text", value: textPatch.injectedText },
79+ },
80+ ],
81+ } as CoreMessage;
82+ const untouched: CoreMessage = { role: "assistant", content: "All done." };
83+
84+ const cleaned = stripToolLimitWarningMessages(
85+ [toolMessage, assistantMessage, untouched],
86+ [jsonPatch, textPatch],
87+ );
88+
89+ expect(cleaned).toEqual([
90+ {
91+ role: "tool",
92+ content: [
93+ {
94+ type: "tool-result",
95+ toolCallId: "1",
96+ toolName: "read",
97+ output: { type: "json", value: { lines: 2 } },
98+ },
99+ ],
100+ },
101+ {
102+ role: "assistant",
103+ content: [
104+ { type: "text", text: "One last response." },
105+ {
106+ type: "tool-result",
107+ toolCallId: "2",
108+ toolName: "shell",
109+ output: { type: "text", value: "exit 0" },
110+ },
111+ ],
112+ },
113+ untouched,
114+ ]);
115+ expect(cleaned[0]).not.toBe(toolMessage);
116+ expect(cleaned[1]).not.toBe(assistantMessage);
117+ expect(cleaned[2]).toBe(untouched);
118+ });
119+
120+ test("returns the original array when there are no warning patches", () => {
121+ const messages: CoreMessage[] = [{ role: "assistant", content: "hello" }];
122+ expect(stripToolLimitWarningMessages(messages, [])).toBe(messages);
123+ });
124+});
src/llm-api/turn.ts+103−15
@@ -23,6 +23,19 @@ type StreamTextResultFull = StreamTextResult & {
2323 };
2424
2525 const MAX_STEPS = 50;
26+const TOOL_LIMIT_WARNING =
27+ "\n\n<system-message>You have reached the maximum number of tool calls. " +
28+ "No more tools will be available after this result. " +
29+ "Respond with a status update and list what still needs to be done.</system-message>";
30+
31+export interface ToolLimitWarningPatch {
32+ injectedText: string;
33+ rawResult: unknown;
34+ restoredOutput: {
35+ type: "text" | "json";
36+ value: unknown;
37+ };
38+}
2639
2740 // ─── Helpers ──────────────────────────────────────────────────────────────────
2841
@@ -31,9 +44,75 @@ function isZodSchema(s: unknown): boolean {
3144 return s !== null && typeof s === "object" && "_def" in (s as object);
3245 }
3346
47+function stringifyToolResult(result: unknown): string {
48+ return typeof result === "string" ? result : String(JSON.stringify(result));
49+}
50+
51+export function createToolLimitWarningPatch(
52+ result: unknown,
53+): ToolLimitWarningPatch {
54+ return {
55+ injectedText: stringifyToolResult(result) + TOOL_LIMIT_WARNING,
56+ rawResult: result,
57+ restoredOutput:
58+ typeof result === "string"
59+ ? { type: "text", value: result }
60+ : { type: "json", value: result },
61+ };
62+}
63+
64+function findToolLimitWarningPatch(
65+ value: unknown,
66+ patches: readonly ToolLimitWarningPatch[],
67+): ToolLimitWarningPatch | undefined {
68+ if (typeof value !== "string") return undefined;
69+ return patches.find((candidate) => candidate.injectedText === value);
70+}
71+
72+export function restoreToolLimitWarningResult(
73+ result: unknown,
74+ patches: readonly ToolLimitWarningPatch[],
75+): unknown {
76+ return findToolLimitWarningPatch(result, patches)?.rawResult ?? result;
77+}
78+
79+export function stripToolLimitWarningMessages(
80+ messages: CoreMessage[],
81+ patches: readonly ToolLimitWarningPatch[],
82+): CoreMessage[] {
83+ if (patches.length === 0) return messages;
84+
85+ let anyChanged = false;
86+ const stripped = messages.map((message) => {
87+ if (!Array.isArray(message.content)) return message;
88+
89+ let contentChanged = false;
90+ const content = message.content.map((part) => {
91+ if (!part || typeof part !== "object" || !("output" in part)) return part;
92+
93+ const output = (part as { output?: unknown }).output;
94+ if (!output || typeof output !== "object" || !("value" in output))
95+ return part;
96+
97+ const value = (output as { value?: unknown }).value;
98+ const patch = findToolLimitWarningPatch(value, patches);
99+ if (!patch) return part;
100+
101+ contentChanged = true;
102+ anyChanged = true;
103+ return { ...part, output: patch.restoredOutput };
104+ });
105+
106+ return contentChanged ? ({ ...message, content } as CoreMessage) : message;
107+ });
108+
109+ return anyChanged ? stripped : messages;
110+}
111+
34112 function toCoreTool(
35113 def: ToolDef,
36114 claimWarning: () => boolean,
115+ recordWarningPatch: (patch: ToolLimitWarningPatch) => void,
37116 ): ReturnType<typeof dynamicTool> {
38117 // MCP tools pass raw JSON Schema objects; the AI SDK requires them to be
39118 // wrapped with jsonSchema(). Zod schemas are passed through as-is.
@@ -46,17 +125,13 @@ function toCoreTool(
46125 execute: async (input: unknown) => {
47126 try {
48127 const result = await def.execute(input);
49- // On the second-to-last step, append a system message to the first
50- // tool result that completes. claimWarning() returns true exactly once
51- // per step so parallel tool calls don't duplicate the warning.
128+ // On the second-to-last step, append a transient system message to the
129+ // first tool result that completes. claimWarning() returns true exactly
130+ // once per step so parallel tool calls don't duplicate the warning.
52131 if (claimWarning()) {
53- const warning =
54- "\n\n<system-message>You have reached the maximum number of tool calls. " +
55- "No more tools will be available after this result. " +
56- "Respond with a status update and list what still needs to be done.</system-message>";
57- const str =
58- typeof result === "string" ? result : JSON.stringify(result);
59- return str + warning;
132+ const patch = createToolLimitWarningPatch(result);
133+ recordWarningPatch(patch);
134+ return patch.injectedText;
60135 }
61136 return result;
62137 } catch (err) {
@@ -121,11 +196,15 @@ export async function* runTurn(options: {
121196 return true;
122197 }
123198
199+ const toolLimitWarningPatches: ToolLimitWarningPatch[] = [];
124200 const toolSet = {} as ToolSet;
125201 for (const def of tools) {
126202 (toolSet as Record<string, ToolEntry>)[def.name] = toCoreTool(
127203 def,
128204 claimWarning,
205+ (patch) => {
206+ toolLimitWarningPatches.push(patch);
207+ },
129208 );
130209 }
131210
@@ -252,19 +331,23 @@ export async function* runTurn(options: {
252331 }
253332
254333 case "tool-result": {
334+ const rawResult =
335+ "output" in c ? c.output : "result" in c ? c.result : undefined;
255336 yield {
256337 type: "tool-result",
257338 toolCallId: String(c.toolCallId ?? ""),
258339 toolName: String(c.toolName ?? ""),
259340 // AI SDK v6: property is `output`, not `result`
260- result:
261- "output" in c ? c.output : "result" in c ? c.result : undefined,
341+ result: restoreToolLimitWarningResult(
342+ rawResult,
343+ toolLimitWarningPatches,
344+ ),
262345 isError: "isError" in c ? Boolean(c.isError) : false,
263346 };
264347 break;
265348 }
266349
267- case "tool-error": {
350+ case "tool-error":
268351 yield {
269352 type: "tool-result",
270353 toolCallId: String(c.toolCallId ?? ""),
@@ -273,7 +356,6 @@ export async function* runTurn(options: {
273356 isError: true,
274357 };
275358 break;
276- }
277359
278360 case "error": {
279361 const err = c.error;
@@ -288,8 +370,14 @@ export async function* runTurn(options: {
288370 // across all steps. Accumulating from onStepFinish would cause duplicates
289371 // because step.response.messages includes all prior step messages PLUS the
290372 // current step's messages on each callback invocation.
373+ // The tool-limit warning is only meant to steer the final step of this turn.
374+ // Strip it back out before persisting messages into session history.
375+
291376 const finalResponse = await result.response;
292- const newMessages = finalResponse?.messages ?? [];
377+ const newMessages = stripToolLimitWarningMessages(
378+ finalResponse?.messages ?? [],
379+ toolLimitWarningPatches,
380+ );
293381
294382 logApiEvent("turn complete", {
295383 newMessagesCount: newMessages.length,