xonecas.io
64875
Mc

mini-coder / commit 81baffb

Remove max tool call warning

xonecas2026-03-08 81baffbb1b0bb5f3482588ddba456924fb5dd61f parent 8271267

2 files changed

src/llm-api/turn.test.ts+1−99
@@ -1,11 +1,5 @@
11 import { describe, expect, test } from "bun:test";
2-import type { CoreMessage } from "./turn.ts";
3-import {
4- createToolLimitWarningPatch,
5- isOpenAIGPT,
6- restoreToolLimitWarningResult,
7- stripToolLimitWarningMessages,
8-} from "./turn.ts";
2+import { isOpenAIGPT } from "./turn.ts";
93
104 describe("isOpenAIGPT", () => {
115 test("matches openai/gpt-* models", () => {
@@ -30,95 +24,3 @@ describe("isOpenAIGPT", () => {
3024 expect(isOpenAIGPT("zen/claude-sonnet-4-6")).toBe(false);
3125 });
3226 });
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+6−132
@@ -23,20 +23,6 @@ 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-}
39-
4026 // ─── Helpers ──────────────────────────────────────────────────────────────────
4127
4228 function isZodSchema(s: unknown): boolean {
@@ -44,76 +30,7 @@ function isZodSchema(s: unknown): boolean {
4430 return s !== null && typeof s === "object" && "_def" in (s as object);
4531 }
4632
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-
112-function toCoreTool(
113- def: ToolDef,
114- claimWarning: () => boolean,
115- recordWarningPatch: (patch: ToolLimitWarningPatch) => void,
116-): ReturnType<typeof dynamicTool> {
33+function toCoreTool(def: ToolDef): ReturnType<typeof dynamicTool> {
11734 // MCP tools pass raw JSON Schema objects; the AI SDK requires them to be
11835 // wrapped with jsonSchema(). Zod schemas are passed through as-is.
11936 const schema = isZodSchema(def.schema)
@@ -124,16 +41,7 @@ function toCoreTool(
12441 inputSchema: schema,
12542 execute: async (input: unknown) => {
12643 try {
127- const result = await def.execute(input);
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.
131- if (claimWarning()) {
132- const patch = createToolLimitWarningPatch(result);
133- recordWarningPatch(patch);
134- return patch.injectedText;
135- }
136- return result;
44+ return await def.execute(input);
13745 } catch (err) {
13846 throw err instanceof Error ? err : new Error(String(err));
13947 }
@@ -180,32 +88,10 @@ export async function* runTurn(options: {
18088 thinkingEffort,
18189 } = options;
18290
183- // stepCount tracks completed steps (incremented in onStepFinish).
184- // Used to detect the second-to-last step for the warning injection.
18591 let stepCount = 0;
186- // warningClaimed resets to false at the start of each step and is flipped to
187- // true by the first tool that completes on the second-to-last step, ensuring
188- // the <system-message> warning appears exactly once even with parallel calls.
189- let warningClaimed = false;
190-
191- // Returns true exactly once on the second-to-last step, so parallel tool
192- // calls in the same step only inject the <system-message> warning once.
193- function claimWarning(): boolean {
194- if (stepCount !== MAX_STEPS - 2 || warningClaimed) return false;
195- warningClaimed = true;
196- return true;
197- }
198-
199- const toolLimitWarningPatches: ToolLimitWarningPatch[] = [];
20092 const toolSet = {} as ToolSet;
20193 for (const def of tools) {
202- (toolSet as Record<string, ToolEntry>)[def.name] = toCoreTool(
203- def,
204- claimWarning,
205- (patch) => {
206- toolLimitWarningPatches.push(patch);
207- },
208- );
94+ (toolSet as Record<string, ToolEntry>)[def.name] = toCoreTool(def);
20995 }
21096
21197 let inputTokens = 0;
@@ -260,7 +146,6 @@ export async function* runTurn(options: {
260146 outputTokens += step.usage?.outputTokens ?? 0;
261147 contextTokens = step.usage?.inputTokens ?? contextTokens;
262148 stepCount++;
263- warningClaimed = false;
264149 },
265150 // On the last allowed step, strip all tools so the model is forced to
266151 // respond with text — no more tool calls are possible.
@@ -331,17 +216,13 @@ export async function* runTurn(options: {
331216 }
332217
333218 case "tool-result": {
334- const rawResult =
335- "output" in c ? c.output : "result" in c ? c.result : undefined;
336219 yield {
337220 type: "tool-result",
338221 toolCallId: String(c.toolCallId ?? ""),
339222 toolName: String(c.toolName ?? ""),
340223 // AI SDK v6: property is `output`, not `result`
341- result: restoreToolLimitWarningResult(
342- rawResult,
343- toolLimitWarningPatches,
344- ),
224+ result:
225+ "output" in c ? c.output : "result" in c ? c.result : undefined,
345226 isError: "isError" in c ? Boolean(c.isError) : false,
346227 };
347228 break;
@@ -370,14 +251,7 @@ export async function* runTurn(options: {
370251 // across all steps. Accumulating from onStepFinish would cause duplicates
371252 // because step.response.messages includes all prior step messages PLUS the
372253 // 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-
376- const finalResponse = await result.response;
377- const newMessages = stripToolLimitWarningMessages(
378- finalResponse?.messages ?? [],
379- toolLimitWarningPatches,
380- );
254+ const newMessages = (await result.response)?.messages ?? [];
381255
382256 logApiEvent("turn complete", {
383257 newMessagesCount: newMessages.length,