Repository navigation
fix(llm): validate deferred tool arguments against the visible tool view - #5231
Conversation
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: e820847 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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: 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".
| for (const tool of message.tools) { | ||
| if (visible.has(tool.name) || unloaded.has(tool.name)) continue; | ||
| visible.set(tool.name, tool); |
There was a problem hiding this comment.
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 | |||
There was a problem hiding this comment.
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 👍 / 👎.
eaae978 to
b38e639
Compare
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
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". |
b38e639 to
5b81872
Compare
There was a problem hiding this comment.
💡 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".
| for (const part of message.content) { | ||
| const lifecycle = readToolLifecycleMeta(part); | ||
| if (lifecycle === undefined) continue; |
There was a problem hiding this comment.
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 👍 / 👎.
| for (const name of lifecycle.removed) { | ||
| seen.delete(name); | ||
| if (!visible.has(name)) unloaded.add(name); |
There was a problem hiding this comment.
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 👍 / 👎.
| 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); |
There was a problem hiding this comment.
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 👍 / 👎.
5b81872 to
e820847
Compare
…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]>
…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]>
…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]>
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).
Requirement or Bug
loop-refact 分支回归测试确认的 P1 回归:
select_tools加载的 deferred 工具失去非法参数的自动纠错。#5142 之后,模型对 deferred 工具返回 schema 非法参数(例如city应为 string 却给了42)时,settle 不再拦截,也不会生成纠错重试;executor 仍会阻止非法副作用,但丢失了执行前的自动恢复能力,多一次无效调用并增加回合失败风险。本 PR 恢复 #5101 设计的纠错行为。Bug Reproduction Steps
city为 string。select_tools加载它。{"city":42}。同一探针在 #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 非法参数 → 下一请求携带纠错消息且不含被拒绝的调用 → 模型重新生成合法调用并恰好执行一次。Behavior Changes and Affected Users
unknown_tool纠错重试select_tools的既有路径不变受影响模块与测试覆盖:
packages/core(llm settle / legalize / policy):core 包 389/389 通过,其中 llm 目录 205/205。packages/agent-core-v2(仅测试与测试基建):全量套件 367 个文件通过;3 个失败文件均为分支既有或负载抖动,与本 PR 无关——remote/sessionSSH probe 用例在未改动基线同败,3 条 no-deadline 子代理用例为既有登记问题,fullCompaction单条在全量并发下超时、隔离运行 118/118 通过。验证命令
corepack pnpm --filter @moonshot-ai/core test→ 389/389corepack pnpm exec vitest run(packages/agent-core-v2)→ 367 文件通过,失败项如上corepack pnpm exec vitest run test/agent/fullCompaction/fullCompaction.test.ts(隔离复跑)→ 118/118corepack 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
/approve).(内部 PR,回归由 loop-refact 分支回归测试发现,无对应 issue)gen-changesetsskill, or this PR needs no changeset.(已含@moonshot-ai/corepatch changeset)gen-docsskill, or this PR needs no doc update.(packages/agent-core-v2/docs/en/llm.md本就写明 settle 校验"including deferred entries",本 PR 恢复实现与该契约一致,无需改文档)