Skip to content

fix(llm): validate deferred tool arguments against the visible tool view - #5231

Merged
sailist merged 1 commit into
mainfrom
bug-422-11-23-settle-deferred-args
Nov 24, 2026
Merged

sailist merged 1 commit into
mainfrom
bug-422-11-23-settle-deferred-args

Conversation

@sailist

@sailist sailist commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

loop-refact 分支回归测试确认的 P1 回归:select_tools 加载的 deferred 工具失去非法参数的自动纠错。#5142 之后,模型对 deferred 工具返回 schema 非法参数(例如 city 应为 string 却给了 42)时,settle 不再拦截,也不会生成纠错重试;executor 仍会阻止非法副作用,但丢失了执行前的自动恢复能力,多一次无效调用并增加回合失败风险。本 PR 恢复 #5101 设计的纠错行为。

Bug Reproduction Steps

  1. 注册一个 deferred 工具,schema 要求 city 为 string。
  2. 模型调用 select_tools 加载它。
  3. 模型返回 {"city":42}。
  4. 观察下一次模型请求:预期包含"参数非法"的纠错 system message;实际没有,非法调用直接进入 executor 才被拒绝。

同一探针在 #5142 父提交通过,在 #5142 及之后的提交失败。

Root Cause

#5142 把 deferred 工具描述从顶层 profile.tools 移除、改为只通过历史 system message 披露,但 settle 的参数校验仍只读 request.profile.tools。找不到工具描述时校验跳过 schema 检查,参数只要是 JSON object 就放行,于是 invalid_tool_arguments 不再产生,纠错重试不触发。这是根本修复:让 settle 的校验输入与模型在该请求中实际可见的工具声明一致,而不是恢复旧的披露形状。

Code Changes

核心思路:提取共享的工具声明扫描,发件侧(legalize)与校验侧(settle)共用同一份合并规则,避免两侧各自演化再次跑偏。

 packages/core/src/llm/
+├── message.ts           # 新增 scanToolDeclarations:一次扫描产出模型可见工具视图 + legalize 所需丢弃位置/重复统计
 ├── protocol/rules/tools.ts  # legalizeTools 改为基于共享扫描重建,线上请求形状不变
 ├── policy/settle.ts     # 两处参数校验的输入从 request.profile.tools 换成可见视图(每个 attempt 惰性计算一次)
 ├── policy/policy.ts     # 临时纠错消息打 origin 标记
 └── tool-arguments.ts    # 校验函数签名从数组改为 ReadonlyMap 按名查找

可见视图的规则与发件侧完全一致:顶层声明优先,system 消息从最新到最旧去重,tool_lifecycle 的 unload 标记使旧 schema 不可见(重新 select 后按新 schema 校验)。

policy.ts 的标记配合 packages/agent-core-v2/test/harness/prompt-cache-guard.ts 的修复:纠错消息自 #5101 起就是临时的(不持久化),但此前没有 agent 层测试走到"纠错重试 + 后续 step",前缀守卫把带临时尾巴的重试请求当作基线会误判前缀断裂。本 PR 新增的组合测试首次走到这条路径并暴露了它。守卫现在比较前缀时剥离这个被标记的临时尾巴,其余重试(如 media 降级恢复)仍以最后一次 attempt 为基线。

建议阅读顺序:message.ts 的 scanToolDeclarations → policy/settle.ts → protocol/rules/tools.ts → 两个测试文件。tool-arguments.ts 仅为签名调整,可略读。

测试:

  • packages/core/test/llm/settle.test.ts 新增 4 个用例:system message 披露 schema 的校验与纠错、视图外工具行为(非空 object 放行、空参数 unknown_tool)、unload 边界按最新披露 schema 校验、已披露工具空参数按真实 schema 判定。
  • packages/agent-core-v2/test/agent/toolSelect/toolSelect.e2e.test.ts 新增组合测试(testkit 风格):select_tools 加载 → 返回 schema 非法参数 → 下一请求携带纠错消息且不含被拒绝的调用 → 模型重新生成合法调用并恰好执行一次。
  • 三个既有 core 测试夹具补上工具声明:新契约下"调用未声明工具"有了明确语义,这些夹具验证的是流式/回放语义,声明工具让夹具语义与意图一致。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
deferred 工具的 schema 非法参数(类型错误、缺必填、额外字段) settle 放行,executor 拒绝 settle 拦截并触发自动纠错重试 无——这是 #5101 的设计行为,#5142 后失效,本 PR 恢复 N/A
已披露 deferred 工具的空参数调用 误报 unknown_tool 纠错重试 按真实 schema 判定 无 N/A
被 unload 且未重新 select 的工具被调用 settle 可能按旧 schema 校验 不按旧 schema 校验;executor 拒绝并指引 select_tools 的既有路径不变 无 N/A
视图外工具(幻觉名、运行时新增 inline 工具)的非空 object 参数调用 settle 放行给 executor 校验执行 不变 依赖按名字直接调用运行时 inline 工具的流程(如 MCP needs-auth 的 authenticate 合成工具) N/A

受影响模块与测试覆盖:

  • packages/core(llm settle / legalize / policy):core 包 389/389 通过,其中 llm 目录 205/205。
  • packages/agent-core-v2(仅测试与测试基建):全量套件 367 个文件通过;3 个失败文件均为分支既有或负载抖动,与本 PR 无关——remote/session SSH probe 用例在未改动基线同败,3 条 no-deadline 子代理用例为既有登记问题,fullCompaction 单条在全量并发下超时、隔离运行 118/118 通过。
  • typecheck(core、agent-core-v2)、oxlint 全仓、import 边界、guards、ratchet、jscpd 新增重复检查均通过。
验证命令
  • corepack pnpm --filter @moonshot-ai/core test → 389/389
  • corepack pnpm exec vitest run (packages/agent-core-v2)→ 367 文件通过,失败项如上
  • corepack pnpm exec vitest run test/agent/fullCompaction/fullCompaction.test.ts(隔离复跑)→ 118/118
  • corepack pnpm exec tsc -p packages/core/tsconfig.json --noEmit、packages/agent-core-v2 同 → 通过
  • corepack pnpm exec oxlint --type-aware --deny-warnings → 0 违规
  • pnpm run check:duplication <base-sha>(干净 worktree)→ 0 新增重复

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).(内部 PR,回归由 loop-refact 分支回归测试发现,无对应 issue)
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.(已含 @moonshot-ai/core patch changeset)
  • Ran gen-docs skill, or this PR needs no doc update.(packages/agent-core-v2/docs/en/llm.md 本就写明 settle 校验"including deferred entries",本 PR 恢复实现与该契约一致,无需改文档)

@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-24T10:09:00.767279Z e820847 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.

@changeset-bot

changeset-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: e820847

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

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/core 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@e820847
npx https://pkg.pr.new/@moonshot-ai/kimi-code@e820847

commit: e820847

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

ℹ️ 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/message.ts Outdated
Comment on lines +281 to +283
for (const tool of message.tools) {
if (visible.has(tool.name) || unloaded.has(tool.name)) continue;
visible.set(tool.name, tool);

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 Honor last-wins order in the visible tool map

When one system message contains multiple declarations with the same name, this forward loop records the first schema, while the deduplication loop below scans backward and keeps the last schema for the actual provider request. Settlement can therefore reject arguments that match the schema shown to the model, or accept arguments that violate it. Iterate the message tools in reverse or build visible from the retained indexes so validation and legalization use the same declaration.

AGENTS.md reference: AGENTS.md:L191-L193

Useful? React with 👍 / 👎.

@@ -0,0 +1,5 @@
---
'@moonshot-ai/core': 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.

P1 Badge Add changesets for the affected products

This user-visible deferred-tool correction flows into the CLI and desktop through agent-core/node-sdk and into the VS Code extension through node-sdk, but the only changeset versions @moonshot-ai/core. Consequently the product changelogs omit the fix; add separate patch changesets for the affected shipped products as required for user-perceivable library changes.

AGENTS.md reference: AGENTS.md:L169-L170

Useful? React with 👍 / 👎.

@sailist
sailist force-pushed the bug-422-11-23-settle-deferred-args branch from eaae978 to b38e639 Compare November 23, 2026 02:43
@sailist

sailist commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

@codex

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: b38e6392fb

ℹ️ 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".

@sailist
sailist force-pushed the bug-422-11-23-settle-deferred-args branch from b38e639 to 5b81872 Compare November 23, 2026 12:57
@sailist
sailist changed the base branch from refact-421-11-23-loop to main November 23, 2026 12:58

@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: 5b818726d9

ℹ️ 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 +303 to +305
for (const part of message.content) {
const lifecycle = readToolLifecycleMeta(part);
if (lifecycle === undefined) continue;

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 Propagate real tool removals into the declaration scan

When a selected deferred tool is removed at runtime, this scan never observes the real removal announcement. toolSelectService.ts records removals in origin.disclosure and <tools_removed> text, and the history projection preserves those as attributes/text, but no production path creates the ContentPart.meta.kind === 'tool_lifecycle' expected here—the only such metadata is in the new unit test. Consequently an unloaded tool remains in visible, so calls can still be validated against its stale schema and trigger a pointless correction retry before the executor reports that the tool is unavailable. Convert the actual disclosure into lifecycle metadata or have the scan understand the persisted announcement shape.

Useful? React with 👍 / 👎.

Comment on lines +306 to +308
for (const name of lifecycle.removed) {
seen.delete(name);
if (!visible.has(name)) unloaded.add(name);

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 profile winners across lifecycle boundaries

When a lifecycle removal names a tool that is also declared in profile.tools, deleting it from seen allows an older system-message declaration with the same name to survive deduplication. legalizeTools then sends both declarations even though the documented rule is that the top-level declaration wins, while settlement still validates against the profile schema in visible; providers can therefore reject the duplicate or expose a different schema from the one used for validation. Lifecycle boundaries should reset only system-message declaration state, never the names already claimed by the profile.

Useful? React with 👍 / 👎.

Comment on lines +294 to +300
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index]!;
if (message.role === 'system' && message.tools !== undefined) {
for (let toolIndex = message.tools.length - 1; toolIndex >= 0; toolIndex -= 1) {
const tool = message.tools[toolIndex]!;
if (visible.has(tool.name) || unloaded.has(tool.name)) continue;
visible.set(tool.name, tool);

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 Ignore message schemas that the protocol does not expose

When this core request is sent through a protocol that does not serialize message-scoped tools, every SystemMessage.tools entry is still added to the validation view. For example, the generic OpenAI lowerer explicitly drops an empty system message whose only payload is tools (builtin/protocol/openai/lower.ts:355-365), and the Anthropic and Google lowerers likewise do not encode that field. A runtime or inline call with the same name can therefore be rejected against a schema that the model never received, contrary to the existing pass-through behavior for tools outside the visible view. Include message declarations only when the selected protocol actually exposes them, or derive validation from the legalized provider-visible request.

Useful? React with 👍 / 👎.

@sailist
sailist force-pushed the bug-422-11-23-settle-deferred-args branch from 5b81872 to e820847 Compare November 24, 2026 10:06
@sailist
sailist merged commit 29953c8 into main Nov 24, 2026
22 of 23 checks passed
@sailist
sailist deleted the bug-422-11-23-settle-deferred-args branch November 24, 2026 11:29
7Sageer pushed a commit that referenced this pull request Nov 25, 2026
…minal (#5345) (#5369)

* fix(agent-core-v2): initialize loop after profile and mode selection (#5141)

* docs: clarify tool registration and filtering

* fix(agent-core-v2): initialize loop after profile and mode selection

Start new agents on their first submission or operation while restoring
persisted agents immediately. Gate Tower activation after startup so its
tools enter the initial baseline.

* fix(agent-core-v2): restore deferred loop initialization

Derive startup state from the loop and its initialization promise, allow
failed starts to retry, and start source agents before forking. Preserve
initial tool baselines and align reminder and history initialization tests.

* test(desktop): initialize loops for browser reminder tests

Start loops before driving reminder hooks and seeding browser histories so
deferred initialization cannot leave reminder assertions empty.

* feat(agent-core-v2): toggle tower mode mid-session with deferred tools

* test(agent-core-v2): cover tower deferred tools end to end

* test(agent-core-v2): script tower tests with the testkit model

* refactor(core): replace loop.drained/loop.idle with loop end info on turn.ended (#5337)

* fix(llm): validate deferred tool arguments against the visible tool view (#5231)

* fix(desktop): resolve ssh.exe absolute path on Windows for remote terminal (#5345)

---------

Co-authored-by: Haozhe <[email protected]>
kimi-agent-bot pushed a commit that referenced this pull request Nov 25, 2026
…minal (#5345) (#5369)

* fix(agent-core-v2): initialize loop after profile and mode selection (#5141)

* docs: clarify tool registration and filtering

* fix(agent-core-v2): initialize loop after profile and mode selection

Start new agents on their first submission or operation while restoring
persisted agents immediately. Gate Tower activation after startup so its
tools enter the initial baseline.

* fix(agent-core-v2): restore deferred loop initialization

Derive startup state from the loop and its initialization promise, allow
failed starts to retry, and start source agents before forking. Preserve
initial tool baselines and align reminder and history initialization tests.

* test(desktop): initialize loops for browser reminder tests

Start loops before driving reminder hooks and seeding browser histories so
deferred initialization cannot leave reminder assertions empty.

* feat(agent-core-v2): toggle tower mode mid-session with deferred tools

* test(agent-core-v2): cover tower deferred tools end to end

* test(agent-core-v2): script tower tests with the testkit model

* refactor(core): replace loop.drained/loop.idle with loop end info on turn.ended (#5337)

* fix(llm): validate deferred tool arguments against the visible tool view (#5231)

* fix(desktop): resolve ssh.exe absolute path on Windows for remote terminal (#5345)

---------

Co-authored-by: Haozhe <[email protected]>
kimi-agent-bot pushed a commit that referenced this pull request Nov 25, 2026
…minal (#5345) (#5369)

* fix(agent-core-v2): initialize loop after profile and mode selection (#5141)

* docs: clarify tool registration and filtering

* fix(agent-core-v2): initialize loop after profile and mode selection

Start new agents on their first submission or operation while restoring
persisted agents immediately. Gate Tower activation after startup so its
tools enter the initial baseline.

* fix(agent-core-v2): restore deferred loop initialization

Derive startup state from the loop and its initialization promise, allow
failed starts to retry, and start source agents before forking. Preserve
initial tool baselines and align reminder and history initialization tests.

* test(desktop): initialize loops for browser reminder tests

Start loops before driving reminder hooks and seeding browser histories so
deferred initialization cannot leave reminder assertions empty.

* feat(agent-core-v2): toggle tower mode mid-session with deferred tools

* test(agent-core-v2): cover tower deferred tools end to end

* test(agent-core-v2): script tower tests with the testkit model

* refactor(core): replace loop.drained/loop.idle with loop end info on turn.ended (#5337)

* fix(llm): validate deferred tool arguments against the visible tool view (#5231)

* fix(desktop): resolve ssh.exe absolute path on Windows for remote terminal (#5345)

---------

Co-authored-by: Haozhe <[email protected]>
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
scanToolDeclarations merges profile tools with message-declared tools and
drops lifecycle-unloaded names; settlement validates every streamed and
final tool call through it, suppressing tool_call_end for invalid calls and
failing without salvage. The correction message carries the
tool_argument_correction origin (MoonshotAI#5231).
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