Skip to content

fix(llm): retry invalid tool call arguments - #5234

Merged
sailist merged 1 commit into
mainfrom
loop-421-stack/01-retry-tool-call-args
Nov 23, 2026
Merged

sailist merged 1 commit into
mainfrom
loop-421-stack/01-retry-tool-call-args

Conversation

@sailist

@sailist sailist commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

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 current main.

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

  1. Return a tool call with truncated JSON such as {"city":, a valid JSON non-object such as null, [], or 42, or arguments rejected by the resolved tool schema.
  2. Before this PR, completed tool calls could pass through settlement without validation against the resolved tool descriptions and reach the tool-execution path.
  3. Return partial assistant text before a retryable failure. The retry path could append that attempt's partial assistant message to history, even when a later attempt succeeded.

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

runAttempts
  → apply recovery and resolvers
  → runAttempt with a fresh accumulator
      → validate completed tool calls against resolved schemas, including deferred tools
      → invalid: stop before execution and emit invalid_tool_arguments
      → valid: return the final outcome
  → recovery / retry events: diagnostics and UI stream reset only, no partial history
  → next attempt when allowed, otherwise return the final failure
  • Add shared argument parsing and schema validation. Empty arguments are accepted only when the resolved schema permits {}; schema-compilation failures remain non-retryable configuration errors.
  • Revalidate the finalized message so missing or interleaved tool-call-end events cannot bypass validation.
  • Emit each finalized valid tool call exactly once, preserving its original stream index when an early boundary was suppressed or absent.
  • Set toolArgumentCorrectionMessage only for invalid tool-call arguments. It is a temporary SystemMessage on the next outbound request, survives transient failures without salvaged output, and clears when another failure has output. It is never persisted to the journal.
  • Do not execute invalid calls, guess arguments, substitute {}, or retain text from an invalid-argument attempt.
  • Do not append partial assistant messages for any retry reason. Only the final outcome can enter history; final non-invalid failures and cancellations keep their existing salvage behavior.
  • Do not carry failed-attempt usage into a successful outcome or session usage. Retry/error events retain the original per-attempt usage for diagnostics.
  • Keep bounded invalid-argument retries immediate. With KIMI_CODE_INFINITE_RETRY, use Retry-After or exponential backoff instead of a zero-delay request loop.
  • Rename single-attempt execution to runAttempt and its control type to LlmRequestControl, and document the runAttempts responsibilities, invariants, state transitions, and correction-message lifecycle.
  • Keep existing journal/fold behavior, historical request handling, restore/replay/compaction, usedTokens behavior, and Anthropic lowering unchanged.
  • Update the English and Chinese LLM design documentation.

Start with packages/core/src/llm/tool-arguments.ts, then packages/core/src/llm/policy/settle.ts, packages/core/src/llm/policy/policy.ts, and packages/core/src/loop/loop-actor.ts. The remaining changes are retry consumers, focused tests, changeset, and documentation.

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
New malformed or schema-invalid tool calls Invalid calls can reach execution They are rejected before execution and retried with invalid_tool_arguments; exhausted attempts fail without executing the call CLI/TUI, desktop/web, and SDK-driven turns across providers Existing maxAttemptsPerStep, abort handling, and retry configuration
Correction feedback after an invalid response No structured correction path exists The next request contains a temporary system correction; invalid-argument attempts retain neither the call nor assistant text Models asked to regenerate a call and users inspecting session history No persistent correction message is introduced
Partial assistant output for any retry reason Retry partial messages can be appended to history No retry partial assistant message is appended; only the final outcome is written Users and clients that previously saw failed-attempt partial text in history Final non-invalid failures and cancellations keep their existing final-outcome salvage behavior
Failed-attempt usage Retry partial messages can persist their usage attributes in history Failed-attempt usage is not carried into successful results or session usage Users inspecting token usage after recovered requests Raw retry/error events still expose per-attempt usage for diagnostics
Invalid-argument retry delay No invalid-argument retry reason existed Bounded retries are immediate; infinite retries use Retry-After or exponential backoff Deployments enabling KIMI_CODE_INFINITE_RETRY Existing abort handling remains available
Prompt-cache prefix after a correction retry Conversation history continues append-only Removing the temporary correction on a later request causes one intentional prompt-cache prefix reset Provider prompt caching after an invalid-tool retry This is the explicit cost of keeping the correction temporary; the scenario verifies that the correction appears only on the retry request
Valid object arguments and unknown tools with object arguments Existing execution and request behavior Unchanged; lack of a tool description alone does not reject a JSON object Existing sessions, hosts, and tool executors Not needed
Empty arguments Some paths treat them as empty objects Accepted only when the resolved schema accepts {} No-argument tools and providers emitting empty arguments A schema that explicitly permits a no-argument call
Invalid calls already present in older sessions Existing restore/replay/compaction behavior, including possible repeated 400s Unchanged and intentionally not repaired by this PR Users continuing sessions that already contain invalid calls Create a new session or use the previous alternate-model compaction workaround
Valid journal history, token estimation, and Anthropic request lowering Existing encoding, estimation, and protocol behavior Unchanged Existing sessions and OpenAI-to-Anthropic conversion paths Not needed

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 commit 83e4dde93453 and 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, and tests/scenarios/tsconfig.json typechecks passed.
  • Standard pnpm lint passed on the exact PR worktree, including comments, oxlint, import boundaries, guards, test-doubles, quarantine, instructions, and ratchet checks.
  • pnpm run check:duplication 83e4dde93453 passed on the exact PR head.
  • Sensitive-information scan passed for all files in the final update.
  • GitHub Actions CI passed on final head 2d7b5e2989b2.

Checklist

  • I have read the CONTRIBUTING document.
  • No issue was provided; this PR includes the reproduction and root cause above.
  • I have added tests that prove the fix works.
  • The behavior-change table above is complete, including removed retry partial history, the intentional cache-prefix reset, and the explicitly excluded legacy-session behavior.
  • Added the required patch changeset for the invalid-tool retry behavior.
  • Updated the English and Chinese LLM design documentation for the new behavior.

* 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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T02:59:20.594093Z 1d40a34 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@changeset-bot

changeset-bot Bot commented Nov 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1d40a34

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@moonshot-ai/kimi-code Patch
@moonshot-ai/kimi-code-sdk Patch

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

@pkg-pr-new

pkg-pr-new Bot commented Nov 23, 2026

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@1d40a34
npx https://pkg.pr.new/@moonshot-ai/kimi-code@1d40a34

commit: 1d40a34

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment on lines +230 to +231
content: {
...request.content,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment on lines +220 to +222
message: failure.error.kind === 'invalid_tool_arguments'
? undefined
: usable === null ? undefined : assistantMessage(usable, 'salvaged'),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 7Sageer 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.

这个版本还需覆盖 deferred schema 的载体和重试耗尽后的客户端状态。下面两项可以独立复现,请先补齐再 approve。


const message = finishMessage();
for (const toolCall of message.toolCalls) {
const error = invalidToolArgumentsError(toolCall, request.profile?.tools ?? []);

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.

[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'),

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.

[P1] 参数校验在重试耗尽后丢弃本次 assistant 输出,同时没有触发 llm.retry 对应的 TurnStepStreamReset。此前已发出的文本和工具卡片会继续留在 KAP live 项和客户端界面,最终 REST/持久化历史却删除了它们,重连前后的视图不一致。请在终态失败前清理这段 stream,并覆盖「最后一次 attempt 有 partial text/tool delta」的场景。

@7Sageer

7Sageer commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

补充一个非阻塞的计数问题:追加 correction 后 content.usedTokens 仍是旧值;runLlmRequest 只在它 undefined 时估算,因此重试的输出预算不会计入新增 correction。建议在构造 corrected request 时清除或重新计算。另,移除失败 attempt 的 partial history/usage 是有意的行为变化,建议写进 changeset,便于升级用户理解。

@sailist
sailist merged commit 9492766 into main Nov 23, 2026
29 checks passed
@sailist
sailist deleted the loop-421-stack/01-retry-tool-call-args branch November 23, 2026 03:58
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants