Repository navigation
Conversation
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.
🦋 Changeset detectedLatest commit: a327572 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 👍 / 👎.
Requirement or Bug
Sessions containing malformed, truncated, or non-object tool-call arguments can become stuck in repeated provider 400 errors, including after session restore and
/compact. This PR rejects invalid arguments before tool execution, retries with clean feedback, and removes invalid historical calls from model requests so affected sessions can continue.No issue was provided; the problem, reproduction, and root cause are documented below.
Bug Reproduction Steps
{"command":, or a valid JSON non-object such asnull,[], or42.JSON.stringifyon the saved value. Empty strings and truncated fragments therefore lose their original wire form.{}and accepts valid JSON non-objects without an object guard. Requests and restored history can therefore carry invalidtool_use.input, causing persistent provider 400 responses that/compactcannot repair.The included TUI e2e play scripts a truncated Bash call, a valid retry, and two consecutive invalid responses. The candidate retries with
invalid_tool_arguments, executes only the valid call, and stops after the configured second failed attempt.Root Cause
There are two independent root causes:
This is a fundamental fix across the shared LLM, journal, and protocol paths, not an Anthropic-only workaround.
Code Changes
Core flow:
tool-call-end, return retryableinvalid_tool_arguments, and retry with assistant-only failure text rather than the rejected call.argsError, and share restore behavior between both folds.{}.@moonshot-ai/kimi-code.Start with
packages/core/src/llm/tool-arguments.ts, thenpolicy/settle.ts,policy/policy.ts, and the two journal fold implementations.Behavior Changes and Affected Users
invalid_tool_argumentstriggers a clean retry; exhausted attempts fail without executing the callmaxAttemptsPerStep, abort, and explicit infinite-retry configuration{}unconditionally{}{}; valid non-objects may reach the providertool_use.inputis always an objectCoverage includes deferred schemas, truncated JSON, non-objects, empty-argument acceptance/rejection, mixed valid/invalid history, retry request contents, non-streaming replay, journal restore, replay fold, compaction, Anthropic lowering, and resume consistency.
Screenshots / Recordings
TUI e2e
invalid-tool-argumentswas run against the candidate and the installed baseline. Captured frames show:Retrying (2/2) · invalid_tool_argumentswith “Bash was not executed”.RECOVERY_REPLY.The candidate completes five main requests; the baseline completes six through the old tool-error path. Both plays and the intentional diff pass.
Verification
@moonshot-ai/coreand@moonshot-ai/agent-core-v2typechecks passed.pnpm lintpassed, including comments, oxlint, import boundaries, guards, instructions, and ratchet checks.Checklist