Skip to content

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

Merged
sailist merged 9 commits into
loop-refactfrom
bug-395-11-18-tool-call-args-retry-release
Nov 21, 2026
Merged

sailist merged 9 commits into
loop-refactfrom
bug-395-11-18-tool-call-args-retry-release

Conversation

@sailist

@sailist sailist commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

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.

@changeset-bot

changeset-bot Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 2d7b5e2

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 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-21T06:25:45.053178Z 2d7b5e2 New commits
ℹ️ 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.

@pkg-pr-new

pkg-pr-new Bot commented Nov 19, 2026 •

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

commit: 2d7b5e2

@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: 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".

Comment thread packages/core/src/llm/tool-arguments.ts Outdated
Comment on lines +145 to +146
const tool = tools.find((entry) => entry.name === call.name);
const issue = parseLlmToolArguments(call.arguments, tool).issue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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

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

Comment thread packages/core/src/llm/policy/policy.ts Outdated
Comment on lines +251 to +252
if (recoveryUsesResolved) {
recoveryRequest = resolvedRequest;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread packages/core/src/llm/policy/policy.ts Outdated
messages: [...request.content.messages, retryMessage],
},
};
retryMessage = undefined;

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

Comment thread packages/core/src/llm/policy/settle.ts Outdated
Comment on lines +143 to +147
const toolCall = inner.toolCallEnd(event.index);
if (toolCall !== undefined) {
const error = invalidToolArgumentsError(toolCall, request.profile?.tools ?? []);
if (error !== null) {
failure = { error };

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment on lines +121 to +123
kind: 'invalid_tool_arguments',
message: `${invalidToolCallText(call.name, result.issue.message)} Generate a new tool call with valid arguments.`,
retryable: true,

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

@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: 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".

Comment thread packages/core/src/llm/tool-arguments.ts Outdated
}
if (invalid.length === 0) return { messages, invalid };

const invalidIds = new Set(invalid.map(({ call }) => call.id));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment on lines +329 to +335
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',

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

Comment thread packages/core/src/llm/policy/policy.ts Outdated
Comment on lines +241 to +244
const cleaned = cleanToolCallHistory(
resolvedRequest.content.messages,
resolvedRequest.profile?.tools ?? [],
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@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: 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".

Comment thread packages/core/src/llm/policy/policy.ts Outdated
Comment on lines +323 to +325
if (result.error.kind === 'invalid_tool_arguments') {
if (result.usage !== undefined) {
rejectedUsage = rejectedUsage === undefined ? result.usage : addUsage(rejectedUsage, result.usage);

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

Comment on lines +211 to +214
content: {
...request.content,
messages: [...request.content.messages, retryMessage],
},

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

@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: 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".

Comment on lines +268 to +270
for (const toolCall of message.toolCalls) {
const error = invalidToolArgumentsError(toolCall, request.profile?.tools ?? []);
if (error !== null) return failed({ error }, message);

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

Comment on lines 304 to +308
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));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread packages/core/src/llm/policy/policy.ts Outdated
Comment on lines +188 to +190
const withRejectedUsage = (outcome: LlmOutcome): LlmOutcome => {
if (rejectedUsage === undefined) return outcome;
const usage = outcome.usage === undefined ? rejectedUsage : addUsage(rejectedUsage, outcome.usage);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@sailist
sailist force-pushed the bug-395-11-18-tool-call-args-retry-release branch from 29103dd to 464a47f Compare November 20, 2026 14:31
@sailist
sailist changed the base branch from release/2026-11-19 to main November 20, 2026 14:32

@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: 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".

Comment on lines +511 to +513
expect(drainPromptCacheViolations()).toEqual([
expect.stringContaining('next step request does not extend the last turn request'),
]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread packages/core/src/llm/policy/settle.ts Outdated
Comment on lines +244 to +246
const error = invalidToolArgumentsError(toolCall, request.profile?.tools ?? []);
if (error === null) {
onEvent?.({ type: 'llm.delta.tool_call_end', index, toolCall });

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

@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: 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.

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 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.
@sailist
sailist force-pushed the bug-395-11-18-tool-call-args-retry-release branch from b535e55 to c4515ae Compare November 21, 2026 06:02
@sailist
sailist changed the base branch from main to loop-refact November 21, 2026 06:35
@sailist
sailist merged commit ff8e8b2 into loop-refact Nov 21, 2026
31 checks passed
@sailist
sailist deleted the bug-395-11-18-tool-call-args-retry-release branch November 21, 2026 06:43
sailist added a commit that referenced this pull request Nov 23, 2026
* 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.
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.

1 participant