Skip to content

fix(ai-sdk-client): stop hidden SDK retries of a tool call with invalid JSON (#1855) - #1901

Merged
addyCooks merged 4 commits into
Nano-Collective:mainfrom
diyaavirmani:fix/invalid-tool-args-hidden-steps
Nov 6, 2026
Merged

addyCooks merged 4 commits into
Nano-Collective:mainfrom
diyaavirmani:fix/invalid-tool-args-hidden-steps

Conversation

@diyaavirmani

Copy link
Copy Markdown
Contributor

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 one chat() call. stopOnUnknownTool only stopped that loop for unknown tools (#1464). The extra requests were missing from steps and usage, and the retry limits only applied after each hidden batch. After the batch, the still-broken call came back with its raw text as arguments, was executed as Invalid tool arguments and 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: stopOnUnknownTool becomes stopOnInvalidToolCall and stops on any call the SDK marks invalid. 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, its arguments become {} and a new ToolCall.argumentsError holds the parse error (for example not valid JSON: Unterminated string in JSON at position 111). The raw text is never executed or replayed, and arguments keeps the Record<string, unknown> type it was declared with.

  • tool-filters.ts: the shared partition used by the TUI, --plain and ACP loops rejects a call with argumentsError the same way it rejects an unknown tool. It isn't run or offered for approval, and the model gets:

    Invalid arguments for tool "write_file": not valid JSON: Unterminated string in JSON at position 111 (line 1 column 112). The call was not run. Send it again with complete, valid JSON arguments; if they were cut off at the output-token limit, make the call smaller.

    The turn then counts toward nanocoder.retries.maxRepeatedToolCalls, like an unknown-tool turn. unknownToolCalls is renamed rejectedToolCalls, since it now holds both kinds.

  • subagent-executor.ts and processToolUse: both answer a call with argumentsError with 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 maxRepeatedToolCalls row 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

  • Bug fix
  • New feature
  • Breaking change
  • Documentation update

Changeset

  • Added a changeset (pnpm changeset) describing this change for the changelog

Testing

Automated Tests

  • New features include passing tests in .spec.ts/tsx files
  • All existing tests pass (pnpm test:all completes 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.
  • Tests cover both success and error scenarios

New tests, covering the ones asked for in the issue:

  • chat-handler.spec.ts: handleChat with a real @ai-sdk/openai-compatible model and a scripted fetch that always answers with the same call:
    • an unparsable call to a real tool comes back after 1 request (10 before), with {} and the parse error, and usage for that one request
    • a write_file cut off with finish_reason: "length" comes back after 1 request
    • a valid call still comes back after 1 request with its arguments
    • the stop-condition spec now expects a stop for an unparsable call to a real tool. It used to assert the opposite ("not this condition's concern").
  • tool-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 with steps: 3 and usage.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: processToolUse refuses 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

  • Tested with Ollama
  • Tested with OpenRouter
  • Tested with OpenAI-compatible API
  • Tested MCP integration (if applicable)

End to end through the real CLI on macOS with Node 22.23.3:

  • nanocoder --plain --json run "read hello.txt",
  • a scripted local OpenAI-compatible server that answers every request with the same turn, as a stuck model does, and bills 15 tokens per request.

The source of truth is the requests the server received and what was replayed to it. steps and usage in the JSON report are checked against them.

Case v1.31.0 (npm, latest release) upstream main f5d82179 v1.32.0 release PR (6111c064) this branch release PR + this fix
read_file, arguments missing the closing } 30 requests, steps: 3, usage.totalTokens: 45 (450 served) same same 3 requests, steps: 3, usage.totalTokens: 45 same as this branch
write_file cut off mid-string, finish_reason: "length" 30 requests, steps: 3, usage.totalTokens: 45 same same 3 requests, steps: 3, usage.totalTokens: 45 same as this branch
The same in --mode normal (where write_file needs approval) 10 requests, then stops asking to approve the broken write_file (tool-approval-required, exit 2) same same 3 requests, then the repeated-call stop; never offered for approval same as this branch
One broken read_file, then a valid one, then an answer 3 requests but steps: 2, usage.totalTokens: 30 same same 3 requests, steps: 3, usage.totalTokens: 45, exit 0 same as this branch
Control: unknown tool 3 requests, steps: 3 same same same same
Control: valid call 2 requests, steps: 2, exit 0 same same same same

How nanocoder replayed the first broken call to the provider, as function.arguments on the wire:

  • before: "{\"path\": \"hello.txt\"", a JSON string literal, paired with Error: Error: Invalid tool arguments: …
  • after: {}, paired with the Invalid arguments for tool "read_file": … result

Nothing was written to disk in any write_file case. The fix applies cleanly onto the v1.32.0 release PR.

Checklist

  • If this was for an open issue, I was assigned to it
  • Code follows project style guidelines
  • Self-review completed
  • Documentation updated (if needed)
  • No breaking changes (or clearly documented)
  • Appropriate logging added using structured logging (no new runtime paths that need logging; the rejected call is reported to the model like an unknown tool)

…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.
@github-actions

Copy link
Copy Markdown
Contributor

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: stopOnInvalidToolCall ends the AI SDK's hidden step loop after one provider request for any call the SDK marks invalid, and convertAISDKToolCall now replaces unparsable arguments with {} plus an argumentsError instead of passing the raw text through to be executed and replayed double-encoded. The rejection is threaded consistently through the shared partition (TUI, --plain, ACP), processToolUse and the subagent executor, the tool-call/result 1:1 pairing invariant is preserved on every path, and the changeset, docs and regression tests are all present and meaningful (the new chat-handler test drives a real @ai-sdk/openai-compatible model with a scripted fetch and asserts the request count). I found no blocking, security or contract problems and no duplicate in the open-PR corpus; the two items below are worth a look but neither needs to change before merge.

⚪ nit · correctness · source/ai-sdk-client/chat/chat-handler.ts

The new stop condition is broader than the new rejection path. stopOnInvalidToolCall stops on any call with invalid === true, but convertAISDKToolCall only sets argumentsError when the call's input is not a plain object:

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 inputSchema. In that case input is a plain object, so no argumentsError is set and the call is treated as ordinary — it reaches the approval prompt and is executed (Nanocoder's own withValidation schema gate then rejects wrong-typed arguments, so the damage is bounded, and write_file still refuses null/undefined content). This is not a regression: on the base commit the same call was returned after 10 hidden SDK steps and executed the same way, and issue #1855 only asked for the invalid-JSON case. But the SDK's own invalid/error signal is dropped at the converter boundary, so a call the SDK itself rejected can still be offered for approval, and the PR description's "stops on any call the SDK marks invalid" reads as though the two conditions cover the same set. Threading invalid/error through convertAISDKToolCall and setting argumentsError from it would make the "never run, never offer for approval" guarantee uniform. I could not inspect the AI SDK internals to confirm the exact result.toolCalls shape (node_modules is not installed in this checkout), so I am flagging the coverage gap rather than asserting a specific SDK behaviour.

⚪ nit · correctness · source/subagents/subagent-executor.ts

The invalid-arguments branch sits outside executeToolCall, so it also bypasses that method's allow-list and handler-existence checks:

const toolResult =
	toolCall.argumentsError !== undefined
		? {content: invalidArgumentsResult(toolCall).content}
		: await runWithReadContentScope(agentId ?? 'subagent', () =>
				this.executeToolCall(/* ... */),
			);

executeToolCall checks the allow-list first ("Tool 'X' is not available to this subagent") and then the handler ("Tool 'X' not found"). A subagent that emits unparsable JSON for a tool it is not allowed to use, or that does not exist at all, now gets "Invalid arguments for tool 'X'" instead — a misleading message that invites it to retry the same unavailable tool with corrected JSON and burn another turn. Nothing is executed, so the allow-list is still enforced and there is no security impact; keeping the boundary check before the argument check (or returning the availability error when the tool is unknown) would give the model the accurate reason.


🔴 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 /re-review.

@github-actions github-actions Bot added the agent:comments nc-review left non-blocking findings label Oct 27, 2026
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.
@diyaavirmani

Copy link
Copy Markdown
Contributor Author

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 executeToolCall, so after the merge the client would never have seen that call. The refusal now runs inside executeToolCall, after bridge.begin, and the call is settled as failed with the parse error. A new spec covers it and fails without the change.

Testing on Node 22: tsc, Biome and the full AVA suite. The two failures in the full run don't involve this PR: trust-cli › a record from another fingerprint version needs re-approval also fails on an untouched main checkout here (macOS), and custom-tools › handler › runScript passes shellArgs argv into spawn timed out under load and passes on rerun.

@addyCooks could you take another look when you get a chance?

@addyCooks addyCooks left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 argumentsError rejection), and pass availableNames through partitionUnknownToolCalls in plain/conversation.ts
  • update the specs #1922 added to tool-filters.spec.ts, which still use unknownToolCalls, to the new rejectedToolCalls name (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.
@diyaavirmani

Copy link
Copy Markdown
Contributor Author

Thanks @addyCooks, done. I merged main in (a5f3b6a) and kept both checks in the partition, passed availableNames through in plain/conversation.ts, and renamed unknownToolCalls in the #1922 specs. I also took the subagent suggestion: argumentsError is now checked after the allow-list and handler lookup. The partition likewise reports "not available in the current mode" before the arguments, so a tool the model can't use is refused for that reason.
New specs cover both orders, plus the plain runtime refusing a tool it didn't offer. tsc and the touched specs pass (416 tests).

@addyCooks addyCooks left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 🎉

@addyCooks
addyCooks merged commit dd04d9f into Nano-Collective:main Nov 6, 2026
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent:comments nc-review left non-blocking findings area:docs Documentation area:tui Terminal UI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] A tool call with invalid JSON arguments makes up to 10 hidden provider requests, missing from steps and usage

2 participants