Repository navigation
fix(llm): retry invalid tool call arguments - #5234
Conversation
* 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.
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. |
🦋 Changeset detectedLatest commit: 1d40a34 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 |
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1d40a34cdd
ℹ️ 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.
Document the dropped retry partials in the changeset
When a provider streams assistant text before a retryable failure, this commit changes CLI, desktop/web, and SDK-visible history by no longer appending that failed attempt in requestProgress (packages/core/src/loop/loop-actor.ts:1466-1473), but the release note mentions only invalid-tool retries. Users upgrading will therefore not be told that previously visible partial text and its usage disappear with no escape hatch; include this behavior in the changeset as well.
AGENTS.md reference: AGENTS.md:L169-L170
Useful? React with 👍 / 👎.
| content: { | ||
| ...request.content, |
There was a problem hiding this comment.
Recompute the token count after adding the correction
When content.usedTokens is already populated, as it is on the normal agent path, an invalid-call retry appends this system message but retains the token count from the original request. Kimi's output-cap calculation fills the remaining context using maxContextSize - usedTokens, so the retry can now request an output budget that omits the correction's tokens; near the context limit this turns the intended corrective retry into another context-overflow failure or unnecessary compaction. Clear or recompute usedTokens when constructing the corrected request.
Useful? React with 👍 / 👎.
| message: failure.error.kind === 'invalid_tool_arguments' | ||
| ? undefined | ||
| : usable === null ? undefined : assistantMessage(usable, 'salvaged'), |
There was a problem hiding this comment.
Reset streamed output when invalid retries are exhausted
When the last permitted attempt emits text or a tool-call delta and then fails validation, this branch removes the attempt from the final outcome, but no llm.retry event follows to trigger TurnStepStreamReset. TUI, KAP, desktop/web, and other streaming consumers therefore retain rejected text or a malformed tool card that is absent from persisted history and from the final REST view. Emit a terminal stream reset, or otherwise reconcile the discarded attempt, before ending an exhausted invalid-argument request.
Useful? React with 👍 / 👎.
7Sageer
left a comment
There was a problem hiding this comment.
这个版本还需覆盖 deferred schema 的载体和重试耗尽后的客户端状态。下面两项可以独立复现,请先补齐再 approve。
|
|
||
| const message = finishMessage(); | ||
| for (const toolCall of message.toolCalls) { | ||
| const error = invalidToolArgumentsError(toolCall, request.profile?.tools ?? []); |
There was a problem hiding this comment.
[P1] 这里仅校验 request.profile.tools。后续 resolver 会把通过 select_tools 加载的 deferred schema 放进 request.content.messages[].tools,顶层列表只保留 select_tools,因此这些 schema 不参与校验,缺少必填字段的调用仍会以 done 进入工具执行。我在本 PR 与 #5237 合并后的真实 runGenerate 路径复现:schema 为 { required: ['city'] }、调用参数为 {},outcome 是 done。请把已合法化的 system tool schema 纳入校验,并补对应回归测试。
| message: usable === null ? undefined : assistantMessage(usable, 'salvaged'), | ||
| message: failure.error.kind === 'invalid_tool_arguments' | ||
| ? undefined | ||
| : usable === null ? undefined : assistantMessage(usable, 'salvaged'), |
There was a problem hiding this comment.
[P1] 参数校验在重试耗尽后丢弃本次 assistant 输出,同时没有触发 llm.retry 对应的 TurnStepStreamReset。此前已发出的文本和工具卡片会继续留在 KAP live 项和客户端界面,最终 REST/持久化历史却删除了它们,重连前后的视图不一致。请在终态失败前清理这段 stream,并覆盖「最后一次 attempt 有 partial text/tool delta」的场景。
|
补充一个非阻塞的计数问题:追加 correction 后 |
Settlement validates each tool call against the request profile's schemas, suppresses the tool-call-end event for invalid calls and fails the attempt without a salvaged message; the policy appends a temporary system correction and retries immediately (bounded), logging reason invalid_tool_arguments (MoonshotAI#5234). The kind is mapped through the human error union, the adapter error conversion and request observation; settle 6 pass including a new invalid-arguments case.
Part 1/7 of the loop stack onto
main(base:main). Identical diff to #5101, previously reviewed and merged into the loop integration branch; rebased onto currentmain.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