Repository navigation
fix(ai-sdk-client): stop hidden SDK retries of a tool call with invalid JSON (#1855) - #1901
Conversation
…id JSON
When a native tool call's arguments weren't valid JSON (a typo, or a call
cut off at the output-token limit), the AI SDK answered it with an
automatic error and asked the model again, up to MAX_TOOL_STEPS (10)
times inside one chat() call. stopOnUnknownTool only stopped that for
unknown tools, so these requests were missing from steps and usage, and
the retry limits only applied after each hidden batch. The broken call
then came back with its raw text as the arguments, was executed as
"Invalid tool arguments" and was replayed to the provider double-encoded.
The step loop now stops on any call the SDK marks invalid
(stopOnInvalidToolCall). A call whose input isn't a JSON object is
converted with `{}` as its arguments and the parse error in a new
ToolCall.argumentsError. The shared partition used by the TUI, plain and
ACP loops rejects such a call like an unknown tool: it isn't run or
offered for approval, the model is told what was wrong, and the turn
counts toward maxRepeatedToolCalls. processToolUse and the subagent
executor refuse it too, so no path runs a tool with the `{}` placeholder.
Closes Nano-Collective#1855.
nc-review: comments — 2 nits@diyaavirmani — a few things worth a look, none blocking. The PR does what it claims and resolves both halves of #1855: ⚪ nit · The new stop condition is broader than the new rejection path. export const stopOnInvalidToolCall: StopCondition<ToolSet> = ({steps}) =>
steps.at(-1)?.toolCalls.some(call => call?.invalid === true) ?? false;The SDK also marks a call invalid when the parsed input fails the tool's ⚪ nit · The invalid-arguments branch sits outside const toolResult =
toolCall.argumentsError !== undefined
? {content: invalidArgumentsResult(toolCall).content}
: await runWithReadContentScope(agentId ?? 'subagent', () =>
this.executeToolCall(/* ... */),
);
🔴 blocking · 🟠 a reviewer would ask for a change · ⚪ optional Automated code review — correctness, security, design, tests, plus duplicates and scope. A human still decides; this is not a substitute for review and is not exhaustive. The required status checks separately cover lint, formatting, types, unused dependencies, the test suite and the build. This bot never merges. Maintainers can rerun with |
Resolves the conflict in the subagent tool loop with Nano-Collective#1904, which scopes a subagent's tool call ids and adds subagentRunId to its execution context: the refusal of a call with unparsable arguments is kept, and the call to executeToolCall takes upstream's id and context.
Since Nano-Collective#1904 a client that takes subagent tool calls (ACP) is shown every call, including one refused before it runs, so a bad call leaves a trace. The refusal of a call with unparsable arguments ran in the loop, before executeToolCall, so the client never saw that call. It now runs inside executeToolCall after the bridge is told the call began, and the call is settled as failed with the parse error.
|
Merged main to clear the conflict with #1904 (27d0c8e), plus one follow-up commit (6af1e73). Since #1904, a client that takes subagent tool calls (ACP) is shown every call, including one refused before it runs. This PR's refusal of a call with unparsable arguments ran in the loop before Testing on Node 22: @addyCooks could you take another look when you get a chance? |
addyCooks
left a comment
There was a problem hiding this comment.
Thanks @diyaavirmani, this is a thorough fix. I ran the touched specs locally (304 pass, tsc clean), and the new "comes back after one request" tests fail when I remove the stop condition and pass with it, so the regression coverage is real. CI is green on the head.
One thing blocks merge: the branch now conflicts with main (since #1922, "refuse tool calls the current mode did not offer"), in source/hooks/chat-handler/utils/tool-filters.ts and source/plain/conversation.ts. Could you merge main and:
- keep both checks in the partition (the "not available in the current mode" rejection and your
argumentsErrorrejection), and passavailableNamesthroughpartitionUnknownToolCallsinplain/conversation.ts - update the specs #1922 added to
tool-filters.spec.ts, which still useunknownToolCalls, to the newrejectedToolCallsname (they won't type-check otherwise) - re-run tsc and the touched specs
Smaller, non-blocking: in subagent-executor.ts the argumentsError check runs before the allow-list/handler checks, so a subagent sending broken JSON for a tool it isn't allowed to use gets "Invalid arguments" rather than "not available". Moving it after the allow-list would give the model the accurate reason.
Happy to re-review once it's updated.
Resolve the conflicts with Nano-Collective#1922 ("refuse tool calls the current mode did not offer") in tool-filters.ts and plain/conversation.ts, keeping both refusals in the shared partition: a registered tool the turn did not offer, and a call whose arguments could not be parsed. The plain runtime passes availableNames to partitionUnknownToolCalls again, and the Nano-Collective#1922 specs use the rejectedToolCalls name. The not-offered check runs before the arguments check, and the subagent executor now checks argumentsError after its allow-list and handler lookup. Fixing the JSON would not make a tool the model may not use usable, so the model is told the tool is not available instead of that its JSON was invalid. New specs cover both orders and the plain runtime refusing a registered tool it did not offer. Before, only the partition specs covered that check.
|
Thanks @addyCooks, done. I merged main in (a5f3b6a) and kept both checks in the partition, passed |
addyCooks
left a comment
There was a problem hiding this comment.
Thanks, this addresses the review: both checks are kept in the partition (the mode check first), availableNames is passed through in plain, the specs use rejectedToolCalls, and the subagent check now runs after the allow-list. The new tests fail without the change.
Approving 🎉
Description
Closes #1855.
When the model sent a native tool call whose arguments weren't valid JSON (a typo, or a call cut off at the output-token limit), the AI SDK answered it with an automatic error and asked the model again, up to
MAX_TOOL_STEPS(10) times inside onechat()call.stopOnUnknownToolonly stopped that loop for unknown tools (#1464). The extra requests were missing fromstepsandusage, and the retry limits only applied after each hidden batch. After the batch, the still-broken call came back with its raw text asarguments, was executed asInvalid tool argumentsand was replayed to the provider double-encoded.As proposed in the issue, the step loop now stops on these calls too, and the raw text is no longer passed on as the arguments.
Change:
chat-handler.ts:stopOnUnknownToolbecomesstopOnInvalidToolCalland stops on any call the SDK marksinvalid. That covers both an unknown tool (NoSuchToolError) and arguments it can't parse (InvalidToolInputError). Every such call gets an automatic error result and another hidden step, so none of them should continue inside the SDK.tool-converter.ts: when a call's input isn't a JSON object, itsargumentsbecome{}and a newToolCall.argumentsErrorholds the parse error (for examplenot valid JSON: Unterminated string in JSON at position 111). The raw text is never executed or replayed, andargumentskeeps theRecord<string, unknown>type it was declared with.tool-filters.ts: the shared partition used by the TUI,--plainand ACP loops rejects a call withargumentsErrorthe same way it rejects an unknown tool. It isn't run or offered for approval, and the model gets:The turn then counts toward
nanocoder.retries.maxRepeatedToolCalls, like an unknown-tool turn.unknownToolCallsis renamedrejectedToolCalls, since it now holds both kinds.subagent-executor.tsandprocessToolUse: both answer a call withargumentsErrorwith the same error, so no path runs a tool with the{}placeholder. Some tools would run with{}(git_status,list_directory). The subagent executor doesn't use the shared partition, and before this change it passed the raw string straight to the tool handler after the approval prompt.TUI: the notice for a rejected call says the arguments were invalid instead of "called an unavailable tool".
Docs: the
maxRepeatedToolCallsrow and the subagent loop-protection note now say that calls with invalid arguments count toward the streak.Valid calls and unknown-tool calls behave as before. Unknown tools still get the "does not exist" hint, even if their arguments are broken too.
Type of Change
Changeset
pnpm changeset) describing this change for the changelogTesting
Automated Tests
.spec.ts/tsxfilespnpm test:allcompletes successfully): 9,846 passed and 20 skipped on macOS. Format, lint, types, knip and audit pass. Semgrep isn't installed on my machine, so that scan was skipped.New tests, covering the ones asked for in the issue:
chat-handler.spec.ts:handleChatwith a real@ai-sdk/openai-compatiblemodel and a scriptedfetchthat always answers with the same call:{}and the parse error, and usage for that one requestwrite_filecut off withfinish_reason: "length"comes back after 1 requesttool-converter.spec.ts: unparsable text, and JSON that isn't an object, become{}plus the error. The error doesn't carry the raw text.tool-filters.spec.ts: both partitions reject the call with the error above. An unknown tool is still reported as unknown. The abandoned turn pairs every emitted call with a result and replays{}.plain/conversation.spec.ts: three broken turns stop at the repeated-call cap withsteps: 3andusage.totalTokens: 45. The handler never runs, even with approval required. A model that fixes its arguments goes on normally.conversation-loop.spec.ts(TUI): no approval prompt, the new notice, the error result in history, and the repeated-call prompt after 3 turns.subagent-executor.spec.ts: the call is neither approved nor run. Broken calls with different parse errors still trip the cap.message-handler.spec.ts:processToolUserefuses the call without running the handler.To check that each test depends on the change it covers, I undid each part of the fix in turn (stop condition, converter, partition,
processToolUse, subagent check). Each time, at least one of the new tests failed.Manual Testing
End to end through the real CLI on macOS with Node 22.23.3:
nanocoder --plain --json run "read hello.txt",The source of truth is the requests the server received and what was replayed to it.
stepsandusagein the JSON report are checked against them.f5d821796111c064)read_file, arguments missing the closing}steps: 3,usage.totalTokens: 45(450 served)steps: 3,usage.totalTokens: 45write_filecut off mid-string,finish_reason: "length"steps: 3,usage.totalTokens: 45steps: 3,usage.totalTokens: 45--mode normal(wherewrite_fileneeds approval)write_file(tool-approval-required, exit 2)read_file, then a valid one, then an answersteps: 2,usage.totalTokens: 30steps: 3,usage.totalTokens: 45, exit 0steps: 3steps: 2, exit 0How nanocoder replayed the first broken call to the provider, as
function.argumentson the wire:"{\"path\": \"hello.txt\"", a JSON string literal, paired withError: Error: Invalid tool arguments: …{}, paired with theInvalid arguments for tool "read_file": …resultNothing was written to disk in any
write_filecase. The fix applies cleanly onto the v1.32.0 release PR.Checklist