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