xonecas.io
64875
Mc

mini-coder / commit 97da703

Handle max tool calls: warn on second-to-last step, force text on last

On the second-to-last step (step 48 of 50), the first tool result that
completes gets a <system-message> appended telling the LLM no more tools
will be available and to give a status update. claimWarning() ensures
parallel tool calls in the same step only inject the message once.

On the last step (step 49), prepareStep returns activeTools:[] so the
model has no tools available and is forced to respond with plain text.

Sean2026-03-01 97da70379d7b1fae30e3ceec14bceb65d1023318 parent 3e7fdda

3 files changed

TODO.md+6−5
@@ -3,8 +3,13 @@
33 ## Handle reaching max tool calls better:
44
55 - Force the LLM to respond with a status update if tool calls are exhausted.
6-- On the last toolcall before max append a `<system-message>` block telling the llm to give a status update and list
6+- On the last toolcall before max append a `<system-message>` block to the tool response telling the llm to give a status update and list
77 what is left todo.
8+- Don't include tools in the last round trip to force the LLM to respond.
9+
10+## Help agent edits error less:
11+
12+- Agents sometimes include `|` at the end of the hash, this is because how we display the hashed to them, let's check if the anchor last char is `|` and strip it if it instead of letting it error.
813
914 ## DB error after thinking for a long time?
1015
@@ -16,10 +21,6 @@ what is left todo.
1621
1722 Please investigate and report back with evidence of the root cause.
1823
19-## Help agent edits error less:
20-
21-- Agents sometimes include `|` at the end of the hash, this is because how we display the hashed to them, let's check if the anchor last char is `|` and strip it if it instead of letting it error.
22-
2324 ## Agent get's stuck on thinking
2425
2526 - When using Google models, there is a rare occurence where the LLM seems to be stuck on thinking. There is no output for several minutes, and the only solution is to use CTRL+c to interrupt.
src/agent/agent.ts+1−1
@@ -661,7 +661,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
661661
662662 /**
663663 * Returns a synthetic assistant CoreMessage signalling that the turn was
664- * interrupted by the user (Ctrl+C) or by an error. Used in three places:
664+ * interrupted by the user (Ctrl+C) or by an error. Used in four places:
665665 * 1. Preamble abort (Ctrl+C before LLM call starts)
666666 * 2. Mid-stream abort with no partial content
667667 * 3. Mid-stream abort with partial content (appended after real messages)
src/llm-api/turn.ts+49−3
@@ -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 };