@@ -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,