Repository navigation
fix(llm): retry invalid tool call arguments - #5101
Conversation
🦋 Changeset detectedLatest commit: 2d7b5e2 The changes in this PR will be included in the next version bump. This PR includes changesets to release 2 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 735675bb7e
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const tool = tools.find((entry) => entry.name === call.name); | ||
| const issue = parseLlmToolArguments(call.arguments, tool).issue; |
There was a problem hiding this comment.
Preserve historical calls across tool-schema changes
For MCP users resuming a session after a tool is updated, removed, or disconnected, this validates previously successful calls against the current tool definition rather than the schema under which they executed. A newly required parameter makes an old call fail schema validation, while a no-argument call becomes unknown_tool when its definition is absent; cleanToolCallHistory then removes both the call and its real result and replaces them with misleading failure text. Restrict historical cleanup to schema-independent malformed/non-object checks unless the original schema snapshot is available.
AGENTS.md reference: AGENTS.md:L190-L192
Useful? React with 👍 / 👎.
| @@ -0,0 +1,5 @@ | |||
| --- | |||
| '@moonshot-ai/kimi-code': patch | |||
There was a problem hiding this comment.
Add changesets for every affected package
This changeset records only @moonshot-ai/kimi-code, although the commit changes source in @moonshot-ai/core and @moonshot-ai/agent-core-v2; the repository's changeset rules require an entry for each changed library, plus entries for user-facing products reached by the change. Without those entries, the release process does not record the actual library changes or the affected desktop/SDK-driven products in their package changelogs.
AGENTS.md reference: AGENTS.md:L184-L188
Useful? React with 👍 / 👎.
| if (recoveryUsesResolved) { | ||
| recoveryRequest = resolvedRequest; |
There was a problem hiding this comment.
Keep recovery snapshots ahead of media resolution
For requests containing stored kimi-file:// media, an earlier resolver has already set recoveryUsesResolved, so this assignment replaces the intended recovery snapshot with the final request after the media resolver has converted those references to inline or uploaded URLs. createMediaDegradeRecovery consequently records keys for the converted URLs, but its rewrite is later applied to the original request where the keys are still kimi-file://; it matches nothing, and a request_too_large or image-format retry resends the same media instead of degrading it. Clean the snapshot captured by the last resolver that opted into recoveryRequest: 'resolved' rather than assigning the final resolved request here.
Useful? React with 👍 / 👎.
| messages: [...request.content.messages, retryMessage], | ||
| }, | ||
| }; | ||
| retryMessage = undefined; |
There was a problem hiding this comment.
Retain correction feedback across transient retries
When the first response has invalid tool arguments and the corrective attempt then receives a retryable transport or status error such as a 429, this clears retryMessage before that attempt's outcome is known. The following retry is therefore rebuilt from the original history without the validation feedback, even though no model response consumed it, so the model can repeat the same invalid call. Preserve the correction message across non-model failures and clear or replace it only after receiving another completed model response.
Useful? React with 👍 / 👎.
| const toolCall = inner.toolCallEnd(event.index); | ||
| if (toolCall !== undefined) { | ||
| const error = invalidToolArgumentsError(toolCall, request.profile?.tools ?? []); | ||
| if (error !== null) { | ||
| failure = { error }; |
There was a problem hiding this comment.
Validate only after the complete tool-call message
For streaming OpenAI-compatible providers, tool_call_end is not a reliable completion boundary: when a gateway omits tool_calls[].index, the decoder emits the call but never emits this event, while interleaved parallel indexes cause the first call to be ended as soon as the second index appears, before its later argument deltas arrive. Because validation occurs only here and an early failure is never reconsidered, the former case still executes malformed arguments and the latter rejects valid calls as truncated. Validate every finalized tool call after message accumulation rather than relying exclusively on decoder boundary events.
AGENTS.md reference: AGENTS.md:L190-L192
Useful? React with 👍 / 👎.
| kind: 'invalid_tool_arguments', | ||
| message: `${invalidToolCallText(call.name, result.issue.message)} Generate a new tool call with valid arguments.`, | ||
| retryable: true, |
There was a problem hiding this comment.
Treat schema compilation failures as configuration errors
For an MCP or plugin tool whose JSON schema AJV cannot compile, schemaError turns the compiler failure into an argument issue and this code marks it retryable. No regenerated arguments can satisfy an uncompileable schema, so the default policy wastes every configured attempt asking the model to correct its call, and KIMI_CODE_INFINITE_RETRY can repeat this indefinitely. Surface schema compilation as a deterministic, non-retryable tool-configuration error instead of invalid_tool_arguments.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 13ea7bbb7e
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| } | ||
| if (invalid.length === 0) return { messages, invalid }; | ||
|
|
||
| const invalidIds = new Set(invalid.map(({ call }) => call.id)); |
There was a problem hiding this comment.
Pair cleanup with the specific reused call occurrence
When resumed or imported history contains sequential completed calls that reuse the same tool-call ID, and only one occurrence has invalid arguments, this global ID set removes every tool result bearing that ID while leaving valid assistant occurrences untouched. The resulting request contains an orphaned valid call that strict providers can reject, so the cleanup intended to recover the session instead leaves it stuck; associate each invalid call with its corresponding result occurrence rather than deleting results globally by ID.
AGENTS.md reference: AGENTS.md:L190-L192
Useful? React with 👍 / 👎.
| const invalidToolArguments = result.error.kind === 'invalid_tool_arguments'; | ||
| const delayMs = invalidToolArguments | ||
| ? 0 | ||
| : (readRetryAfterMs(result.error) ?? retryBackoffDelay(attempt - 1)); | ||
| const retrying: LlmRunEvent = { | ||
| type: 'llm.retrying', | ||
| reason: 'backoff', | ||
| reason: invalidToolArguments ? 'invalid_tool_arguments' : 'backoff', |
There was a problem hiding this comment.
Account for usage from rejected tool-call attempts
When a provider reports token usage for an invalid-tool-arguments response, this new zero-delay retry path exposes that usage only on llm.retrying and then discards it when the loop continues. Agent-core's retry observer does not record event.usage, its turn projection clears the current attempt on retry, and successful completion records only the final outcome's usage, so up to nine rejected attempts under the default limit disappear from session usage and token accounting. Record each failed attempt's usage before continuing or accumulate it into the completed outcome.
Useful? React with 👍 / 👎.
| const cleaned = cleanToolCallHistory( | ||
| resolvedRequest.content.messages, | ||
| resolvedRequest.profile?.tools ?? [], | ||
| ); |
There was a problem hiding this comment.
Clean history before strict structural projection
When an older history contains an invalid tool-call exchange followed by a normal assistant reply, the strict structure resolver runs while the call and result still separate those assistants; this later cleanup then removes the exchange and appends correction text to the first assistant, leaving two consecutive assistant messages. Because strict recovery has already been consumed and cannot run again, gateways that require alternating roles can reject the repaired request as well, so perform cleanup before structural projection or project the cleaned messages again.
AGENTS.md reference: AGENTS.md:L190-L192
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a32757202f
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (result.error.kind === 'invalid_tool_arguments') { | ||
| if (result.usage !== undefined) { | ||
| rejectedUsage = rejectedUsage === undefined ? result.usage : addUsage(rejectedUsage, result.usage); |
There was a problem hiding this comment.
Avoid counting the final rejected attempt twice
When the last permitted attempt returns invalid_tool_arguments with usage, this adds that attempt to rejectedUsage, and the non-retry path then passes the same result to withRejectedUsage, which adds result.usage again. The final failed outcome therefore overstates token usage for the last attempt, affecting session usage and cost accounting; only add an invalid attempt to the accumulator when another attempt will actually run, or exclude the current result when combining totals.
Useful? React with 👍 / 👎.
| content: { | ||
| ...request.content, | ||
| messages: [...request.content.messages, retryMessage], | ||
| }, |
There was a problem hiding this comment.
Recompute used tokens after appending retry feedback
On an invalid-argument retry, this preserves request.content.usedTokens while appending a new assistant correction message. For Kimi and other model rules whose output cap is computed from usedTokens, a request near the context limit therefore reserves output space as if the correction were absent and can exceed the context window or receive another provider rejection. Recalculate or invalidate usedTokens whenever the retry message is appended.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 29103ddedd
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| for (const toolCall of message.toolCalls) { | ||
| const error = invalidToolArgumentsError(toolCall, request.profile?.tools ?? []); | ||
| if (error !== null) return failed({ error }, message); |
There was a problem hiding this comment.
Discard text from rejected tool-call attempts
When a completed response contains visible text alongside an invalid tool call, failed() preserves that text as result.message; the emitted llm.retrying event is then handled by LoopActor.requestProgress, which appends the message to durable history as a partial response. After the corrected attempt succeeds, its response is appended as well, leaving rejected-attempt text—often duplicated or contradictory—in the conversation even though the retry itself was generated without that text. Return no salvageable message for invalid_tool_arguments, or otherwise prevent this retry reason from persisting the rejected attempt.
AGENTS.md reference: AGENTS.md:L190-L192
Useful? React with 👍 / 👎.
| if (shouldRetry(policy.retry, attempt, result.error, listOf(policy.retryables))) { | ||
| const delayMs = readRetryAfterMs(result.error) ?? retryBackoffDelay(attempt - 1); | ||
| const invalidToolArguments = result.error.kind === 'invalid_tool_arguments'; | ||
| const delayMs = invalidToolArguments | ||
| ? 0 | ||
| : (readRetryAfterMs(result.error) ?? retryBackoffDelay(attempt - 1)); |
There was a problem hiding this comment.
Back off infinite invalid-argument retries
When KIMI_CODE_INFINITE_RETRY is enabled and the model keeps producing schema-invalid arguments, shouldRetry ignores the attempt limit, while this branch forces every retry delay to zero. The resulting loop can issue unbounded paid LLM requests as quickly as responses arrive, contrary to the exponential backoff promised for this environment variable in docs/en/configuration/env-vars.md:188; retain immediate correction for bounded retries, but apply backoff or a finite correction limit in infinite mode.
AGENTS.md reference: AGENTS.md:L190-L192
Useful? React with 👍 / 👎.
| const withRejectedUsage = (outcome: LlmOutcome): LlmOutcome => { | ||
| if (rejectedUsage === undefined) return outcome; | ||
| const usage = outcome.usage === undefined ? rejectedUsage : addUsage(rejectedUsage, outcome.usage); |
There was a problem hiding this comment.
Keep aggregate retry usage out of context measurement
After any invalid-argument retry succeeds, this replaces the final outcome's per-request usage with the sum of every rejected and successful attempt. AgentLoopRequestObserver.completeRequest passes that value to tokenCounting.measured, where grandTotal(usage) is stored as the token size of the single durable conversation context; because the measured input does not contain the rejected responses or temporary correction message, even one retry can nearly double the context anchor and repeated corrections can trigger premature compaction or context-limit behavior. Preserve cumulative usage for billing separately while exposing the final attempt's usage to context measurement.
AGENTS.md reference: AGENTS.md:L190-L192
Useful? React with 👍 / 👎.
29103dd to
464a47f
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a9c69f2224
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| expect(drainPromptCacheViolations()).toEqual([ | ||
| expect.stringContaining('next step request does not extend the last turn request'), | ||
| ]); |
There was a problem hiding this comment.
Preserve the prompt-cache prefix after correction retries
When an invalid call is corrected successfully and the tool result triggers the next LLM step, the temporary trailing system message disappears from history, so that next request no longer extends the corrected attempt's prompt-cache prefix and long conversations must resend and reprocess the full context. This assertion explicitly drains the guard violation instead of preventing it; fix the request layout so the prefix remains stable and leave the guard expecting no violations.
AGENTS.md reference: AGENTS.md:L93-L98
Useful? React with 👍 / 👎.
| const error = invalidToolArgumentsError(toolCall, request.profile?.tools ?? []); | ||
| if (error === null) { | ||
| onEvent?.({ type: 'llm.delta.tool_call_end', index, toolCall }); |
There was a problem hiding this comment.
Emit tool-call completion after final validation
When an OpenAI-compatible stream interleaves indexed calls, an early decoder boundary can see temporarily incomplete arguments and this branch suppresses llm.delta.tool_call_end; if later deltas complete the call, final validation accepts and executes it, but no second boundary callback occurs. The final outcome is therefore valid while streamLlmRequest consumers never receive the completion event promised by packages/core/test/llm/delta/tool-calls.test.ts:19-56; emit each finalized valid call once after accumulation or otherwise defer suppression until settlement. This is fresh evidence beyond the earlier validation finding: the current final-validation loop fixes outcome rejection but does not restore the suppressed event.
AGENTS.md reference: AGENTS.md:L191-L193
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b535e55614
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| '@moonshot-ai/kimi-code-sdk': patch | ||
| --- | ||
|
|
||
| Retry when a provider returns an invalid tool call. |
There was a problem hiding this comment.
Preserve partial output from ordinary retries
When an ordinary retryable transport, status, or recovery attempt emits usable text before failing and a later attempt succeeds, this changeset also causes that text to disappear from durable history; the updated normal-retry test explicitly reverses the previous persistence assertion. The changeset only announces invalid-tool-call retries, so users resuming or exporting these sessions silently lose previously retained output without an escape hatch; restrict suppression to invalid_tool_arguments, or document the broader loss and provide the required compatibility path.
AGENTS.md reference: AGENTS.md:L195-L197
Useful? React with 👍 / 👎.
Validate completed tool calls before execution and retry with clean feedback. Remove invalid historical calls and preserve raw journal argument strings. Guard Anthropic tool inputs against non-object arguments.
- keep realtime validation and correction retries for newly received tool calls - leave legacy session history and Anthropic lowering unchanged - honor explicit journal argument error markers only
Stop persisting partial assistant messages from retries. Count usage only from the final successful attempt. Document retry constraints and rename single-attempt execution.
Replace legacy model responses with a real KAP scenario.
b535e55 to
c4515ae
Compare
Preserve stream indexes and emit each valid tool call once.
* fix(llm): retry invalid tool call arguments Validate completed tool calls before execution and retry with clean feedback. Remove invalid historical calls and preserve raw journal argument strings. Guard Anthropic tool inputs against non-object arguments. * chore: add changeset for tool argument retry * test(agent-core-v2): preserve rejected tool repeat coverage * fix(llm): preserve request recovery semantics * fix(llm): scope tool argument retries to new calls - keep realtime validation and correction retries for newly received tool calls - leave legacy session history and Anthropic lowering unchanged - honor explicit journal argument error markers only * fix(llm): keep retry attempts independent Stop persisting partial assistant messages from retries. Count usage only from the final successful attempt. Document retry constraints and rename single-attempt execution. * test(llm): move invalid tool retry coverage to testkit Replace legacy model responses with a real KAP scenario. * test(llm): fix scenario step usage typing * fix(llm): emit finalized tool call completions Preserve stream indexes and emit each valid tool call once.
Requirement or Bug
Provider responses containing malformed, truncated, non-object, or schema-invalid tool-call arguments can reach tool execution. Retries can also leak partial assistant output from failed attempts into conversation history. This PR validates newly received tool calls, gives the model a temporary correction signal, and keeps every attempt isolated while explicitly leaving existing session history unchanged.
No issue was provided; the reproduction and root cause are documented below.
Bug Reproduction Steps
{"city":, a valid JSON non-object such asnull,[], or42, or arguments rejected by the resolved tool schema.Root Cause
The settlement path did not validate completed tool-call arguments against resolved tool descriptions, including deferred tools. The retry path also lacked a correction signal for invalid arguments and persisted retry partial messages instead of treating each attempt as independent.
This is a fundamental fix for newly received provider output and new retry attempts. It is intentionally not a migration or cleanup of existing session history.
Code Changes
{}; schema-compilation failures remain non-retryable configuration errors.tool-call-endevents cannot bypass validation.toolArgumentCorrectionMessageonly for invalid tool-call arguments. It is a temporarySystemMessageon the next outbound request, survives transient failures without salvaged output, and clears when another failure has output. It is never persisted to the journal.{}, or retain text from an invalid-argument attempt.KIMI_CODE_INFINITE_RETRY, use Retry-After or exponential backoff instead of a zero-delay request loop.runAttemptand its control type toLlmRequestControl, and document therunAttemptsresponsibilities, invariants, state transitions, and correction-message lifecycle.usedTokensbehavior, and Anthropic lowering unchanged.Start with
packages/core/src/llm/tool-arguments.ts, thenpackages/core/src/llm/policy/settle.ts,packages/core/src/llm/policy/policy.ts, andpackages/core/src/loop/loop-actor.ts. The remaining changes are retry consumers, focused tests, changeset, and documentation.Behavior Changes and Affected Users
invalid_tool_arguments; exhausted attempts fail without executing the callmaxAttemptsPerStep, abort handling, and retry configurationKIMI_CODE_INFINITE_RETRY{}Coverage includes deferred schemas, truncated JSON, non-objects, empty-argument acceptance and rejection, schema failures, missing/interleaved call boundaries, correction request contents, non-streaming replay, successful-attempt usage, bounded and infinite retry delays, and attempt isolation for backoff and recovery. Legacy journal, token-estimation, and protocol behavior remain outside the changed surface.
Verification
packages/core/test/llm/settle.test.ts: 5/5 passed.packages/agent-core-v2/test/agent/llmRequester/llmRequester.test.ts: 17/17 passed.tests/scenarios/conversation.test.ts: the new invalid-argument scenario passed, including temporary correction, no rejected text in successful history, one legal tool execution, and successful-attempt usage. The full file has 17/18 passing; the remaining approval scenario fails identically on base commit83e4dde93453and is unrelated to this PR.packages/agent-core-v2/test/agent/loop/loop.test.ts: 70/70 passed, including attempt isolation for backoff and recovery, final failure, cancellation, and resume consistency.packages/agent-core-v2/test/agent/toolDedupe/toolDedupe.test.ts: 47/47 passed locally. A remote install was also attempted but exceeded npm download timeouts.@moonshot-ai/core,@moonshot-ai/agent-core-v2, andtests/scenarios/tsconfig.jsontypechecks passed.pnpm lintpassed on the exact PR worktree, including comments, oxlint, import boundaries, guards, test-doubles, quarantine, instructions, and ratchet checks.pnpm run check:duplication 83e4dde93453passed on the exact PR head.2d7b5e2989b2.Checklist