@@ -25,7 +25,10 @@ function isZodSchema(s: unknown): boolean {
2525 return s !== null && typeof s === "object" && "_def" in (s as object);
2626 }
2727
28-function toCoreTool(def: ToolDef): ReturnType<typeof dynamicTool> {
28+function toCoreTool(
29+ def: ToolDef,
30+ claimWarning: () => boolean,
31+): ReturnType<typeof dynamicTool> {
2932 // MCP tools pass raw JSON Schema objects; the AI SDK requires them to be
3033 // wrapped with jsonSchema(). Zod schemas are passed through as-is.
3134 const schema = isZodSchema(def.schema)
@@ -36,7 +39,20 @@ function toCoreTool(def: ToolDef): ReturnType<typeof dynamicTool> {
3639 inputSchema: schema,
3740 execute: async (input: unknown) => {
3841 try {
39- return await def.execute(input);
42+ const result = await def.execute(input);
43+ // On the second-to-last step, append a system message to the first
44+ // tool result that completes. claimWarning() returns true exactly once
45+ // per step so parallel tool calls don't duplicate the warning.
46+ if (claimWarning()) {
47+ const warning =
48+ "\n\n<system-message>You have reached the maximum number of tool calls. " +
49+ "No more tools will be available after this result. " +
50+ "Respond with a status update and list what still needs to be done.</system-message>";
51+ const str =
52+ typeof result === "string" ? result : JSON.stringify(result);
53+ return str + warning;
54+ }
55+ return result;
4056 } catch (err) {
4157 throw err instanceof Error ? err : new Error(String(err));
4258 }
@@ -61,9 +77,28 @@ export async function* runTurn(options: {
6177 }): AsyncGenerator<TurnEvent> {
6278 const { model, messages, tools, systemPrompt, signal } = options;
6379
80+ // stepCount tracks completed steps (incremented in onStepFinish).
81+ // Used to detect the second-to-last step for the warning injection.
82+ let stepCount = 0;
83+ // warningClaimed resets to false at the start of each step and is flipped to
84+ // true by the first tool that completes on the second-to-last step, ensuring
85+ // the <system-message> warning appears exactly once even with parallel calls.
86+ let warningClaimed = false;
87+
88+ // Returns true exactly once on the second-to-last step, so parallel tool
89+ // calls in the same step only inject the <system-message> warning once.
90+ function claimWarning(): boolean {
91+ if (stepCount !== MAX_STEPS - 2 || warningClaimed) return false;
92+ warningClaimed = true;
93+ return true;
94+ }
95+
6496 const toolSet = {} as ToolSet;
6597 for (const def of tools) {
66- (toolSet as Record<string, ToolEntry>)[def.name] = toCoreTool(def);
98+ (toolSet as Record<string, ToolEntry>)[def.name] = toCoreTool(
99+ def,
100+ claimWarning,
101+ );
67102 }
68103
69104 let inputTokens = 0;
@@ -83,7 +118,18 @@ export async function* runTurn(options: {
83118 inputTokens += step.usage?.inputTokens ?? 0;
84119 outputTokens += step.usage?.outputTokens ?? 0;
85120 contextTokens = step.usage?.inputTokens ?? contextTokens;
121+ stepCount++;
122+ warningClaimed = false;
86123 },
124+ // On the last allowed step, strip all tools so the model is forced to
125+ // respond with text — no more tool calls are possible.
126+ prepareStep: ({ stepNumber }: { stepNumber: number }) => {
127+ if (stepNumber >= MAX_STEPS - 1) {
128+ return { activeTools: [] as Array<keyof typeof toolSet> };
129+ }
130+ return undefined;
131+ },
132+
87133 ...(systemPrompt ? { system: systemPrompt } : {}),
88134 ...(signal ? { abortSignal: signal } : {}),
89135 };