Skip to content

fix(agent-core-v2): dedupe historical tool schemas - #4862

Merged
sailist merged 10 commits into
release/2026-11-12from
bug-356-11-12-duplicate-system-message-tools-release-2026-11-12
Nov 12, 2026
Merged

sailist merged 10 commits into
release/2026-11-12from
bug-356-11-12-duplicate-system-message-tools-release-2026-11-12

Conversation

@sailist

@sailist sailist commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

启用动态工具加载的 TUI、desktop/web、ACP 与 SDK 会话在同一个工具被移除并重新加载后,可能在多条历史 system message 中携带同名工具定义,导致 Kimi 协议请求被 duplicate tool name ... between message tools 拒绝,后续 turn 也无法继续。

本 PR 在 tool-select resolver 的历史投影阶段去除重复定义,使每次请求只保留第一次消息级声明;完全相同的后续重复定义会被过滤,schema 不同的后新增 message 会转换为提醒,说明当前会话暂不支持更新并指引新会话。没有单独关联 issue,问题、复现和回归验证均记录在本 PR 中。

本 PR 是 #4861 针对 release/2026-11-12 的独立交付版本;原 main PR 的基线与提交历史未被改写。修复与 changeset 已重放到 release/2026-11-12@origin 的 9ae2757d0385,并追加首次定义保留、变化提醒与预检拦截修正,最终 diff 仍仅包含实现、测试和 changeset。

Bug Reproduction Steps

  1. 启用动态工具加载,通过 select_tools 加载一个 deferred MCP 工具,使历史写入一条 content: []、tools: [schema] 的 system message。
  2. 移除并以同名定义替换该工具,再次加载,使历史同时保留旧、新两条同名 schema message。
  3. 发起下一次模型请求。修改前 resolver 将两条消息级定义同时投影到请求中,Kimi 服务端在校验阶段以 HTTP 400 duplicate tool name ... between message tools 拒绝。

回归测试使用中性构造工具和真实 resolver 调用复现该请求结构,不依赖线上模型或真实用户会话。

Root Cause

AgentToolSelectService.shapeActiveHistory() 只根据顶层 inline 工具名过滤历史 schema,没有处理不同 system message 之间的同名定义。每次 select_tools 加载都会追加一条 schema message,因此重载后旧、新定义会一起进入出站请求。

这是 resolver 请求投影层的修复,而不是在 serializer 中掩盖问题或改写持久化历史。为避免改变已有消息前缀并维护缓存,投影保留第一次出现的旧定义;完全相同的后续重复定义直接过滤,schema 不同的后新增 message 转换为更新提醒,明确当前会话暂不支持应用新 schema 并指引新会话。提醒只针对最新仍有效的 schema 更新,A→B→A 或工具移除后不提示重启。既有顶层 inline 优先规则保持不变。

Code Changes

 shapeActiveHistory
+  记录每个工具名第一次出现的 system message、tool 位置及首次 schema
 shapeActiveMessage
-  保留所有不与顶层 inline 重名的历史 schema
+  仅保留第一次消息级 schema,继续过滤顶层 inline 同名项
+  相同 schema 的重复项过滤后没有正文和剩余 tool 时,移除整条 system message
+  不同 schema 的后新增 message 转换为更新 reminder,保留正文并指引新会话
 toolExecutor
+  新增 validating 预检钩子,在参数校验前拒绝 pending schema 更新调用

带正文的重复消息只移除后出现的重复 tool,正文继续保留;不同 schema 的后新增 message 转换为更新提醒,说明当前会话不支持更新并指引新会话。原始 context history、registry、wire/state 契约和 Kimi serializer 均未修改。

主要阅读位置:packages/agent-core-v2/src/agent/toolSelect/toolSelectService.ts;回归位于现有 toolSelectService.test.ts 同名移除/替换用例,测试声明总数净零。

Behavior Changes and Affected Users

行为 修改前 修改后 依赖旧行为的人群 退路
多条 system message 中的同名工具定义 旧、新定义全部进入请求,可能被 provider 拒绝 只保留第一次消息级定义 开启动态工具的 TUI、desktop/web、ACP、SDK 会话,含旧版本已写入重复历史的会话 无需保留无法通过校验的重复请求
后出现的空重复 system message 空消息仍进入请求 相同 schema 时整条移除;不同 schema 时转换为更新提醒 同上 无需;消息正文和其他 tool 不受影响
带正文的重复 system message 正文和旧 tool 一起保留 保留正文,移除后出现的重复 tool 依赖历史正文上下文的会话 正文原样保留
pending schema 更新工具调用 旧 schema 可能进入新版参数校验或执行 预检返回当前会话不支持更新并指引新会话;回退到原 schema 后恢复 需要避免旧 schema 调用新实现的会话 新会话使用更新后的 schema
顶层 inline 去重、非重复定义和持久化历史 按既有规则处理 保持不变 所有 tool-select 会话及旧会话恢复 既有测试继续覆盖

受影响模块仅为 agent-core-v2 的 tool-select resolver 及其既有测试。回归覆盖首次定义和首条消息对象保留、相同 schema 的空重复消息删除、不同 schema 转更新提醒、正文保留、原始历史不变,以及既有 inline 去重行为;还覆盖 pending 调用预检拦截、A→B→A 后提醒消失与调用恢复。

未请求真实线上 provider,也未运行全仓测试;已执行本地修改测试、m0-dev 聚焦 tool-select 测试(含 E2E)、Core typecheck 和局部 type-aware lint。

验证命令与结果
  • 本地:corepack pnpm -C packages/agent-core-v2 exec vitest run test/agent/toolSelect/toolSelectService.test.ts --config vitest.config.ts,96/96 通过。
  • m0-dev(release/2026-11-12 基线):test/agent/toolSelect 三个文件,121/121 通过,包含 E2E。
  • m0-dev:corepack pnpm -C packages/agent-core-v2 typecheck,通过。
  • 两个实现/测试文件运行 type-aware oxlint:0 errors;7 条 warnings 均位于未修改代码行。
  • 交付 diff 只包含实现、既有测试和一份 patch changeset;安全审计未发现敏感信息或无关文件。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).(无单独 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.
  • Ran gen-docs skill, or this PR needs no doc update.(无配置、公开接口或用户文档变化。)

@changeset-bot

changeset-bot Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1f08a98

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/kimi-code 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 12, 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-12T06:40:35.585168Z 1f08a98 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 12, 2026 •

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

commit: 1f08a98

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

ℹ️ 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 +577 to +579
if (!firstToolDeclarations.has(name)) {
firstToolDeclarations.set(name, { message, toolIndex });
}

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 the current schema after a tool reload

When a deferred MCP tool is removed and re-registered under the same name with changed parameters, this first-write map preserves the original declaration and shapeActiveMessage drops the newly loaded one. However, collectLoadedDynamicTools treats the last declaration as active and execution uses the current registry implementation, so the model receives the old parameters while calling the new tool; changes such as a newly required field can make subsequent calls fail. Preserve the newest declaration, or otherwise ensure the projected schema matches the active tool.

AGENTS.md reference: AGENTS.md:L110-L112

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: 9a707192b6

ℹ️ 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 +140 to +142
if (validating !== undefined && 'args' in validating) {
const rewritten = await prepare(tool);
if (rewritten !== undefined) return control.returned(rewritten);

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 preparing rewritten validation calls twice

When a validating hook returns rewritten arguments for a non-synthetic tool, this branch calls prepare(tool) and then the unconditional call immediately below prepares it again, discarding the first prepared value. In the agent executor that means LegacyExecutableToolAdapter.prepare() invokes resolveExecution() twice, while other implementations may allocate resources or perform other preparation side effects twice. Validation rewrites occur before the normal preparation pass, so update the arguments here but let the existing unconditional call perform the single preparation.

Useful? React with 👍 / 👎.

let rewritten = false;
for (const hook of hooks) {
if (hook.validating === undefined) continue;
const decision = await hook.validating(current);

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 hook receivers during validation

When a composed validating hook is declared as an object method and reads this, this bare invocation loses the hook as its receiver, so the hook can throw or make a wrong decision. Every other composed hook is invoked with .call(hook, ...), and existing hook behavior supports receiver-dependent methods; invoke this callback the same way.

Useful? React with 👍 / 👎.

Comment on lines +200 to +202
validating?(
context: ToolDecisionContext<any, TContext, TPrepared>,
): ToolDecision | void | Promise<ToolDecision | void>;

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 Type validation hooks without prepared state

A validating hook runs before the first prepare(tool) call, but this signature gives it a ToolDecisionContext whose prepared field is typed as TPrepared; at runtime that field is still undefined. For example, an AgentToolHook is told it can safely inspect a LegacyToolPreparation, so accessing context.prepared.kind in this newly exposed phase crashes despite type-checking. Use a pre-prepare context type or explicitly make the prepared value optional for this hook.

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: f42be49391

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

this.states.contributeState(toolSelectKey);
this._register(toolExecutor.registerHook({
validating: (context) => {
if (!collectPendingSchemaUpdateNames(this.history(), this.toolRegistry.list()).has(context.call.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.

P1 Badge Skip schema rejection when dynamic disclosure is disabled

When a session contains A→B dynamic-schema history and then switches to a model without dynamic-tool support—or the feature flag is disabled—the resolver strips those historical schemas and advertises the current B schema as an ordinary top-level tool. This unconditional check still classifies B as pending and rejects every valid invocation, leaving the tool unusable until a new session is started; only reject when the active request actually retains the old schema.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

if (tool === undefined) {
throw new ToolStop(rejected('resolve', `Tool "${call.name}" not found`, undefined, 'resolve'));
}
await decide('validate', (ctx) => hook?.validating?.(ctx), false);

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 cancellation after validating hooks

If handler.stop() is called while an asynchronous validating hook is pending, disabling this abort check lets execution continue into prepare() after the hook resolves. For legacy tools that invokes resolveExecution() despite the cancellation, so preparation side effects or resource allocation still occur before the later signal check returns an aborted result; check the signal before preparing the tool.

Useful? React with 👍 / 👎.

@sailist
sailist merged commit 7980593 into release/2026-11-12 Nov 12, 2026
14 checks passed
@sailist
sailist deleted the bug-356-11-12-duplicate-system-message-tools-release-2026-11-12 branch November 12, 2026 06:39
@github-actions github-actions Bot mentioned this pull request Nov 12, 2026

@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: 1f08a98dfe

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

this.states.contributeState(toolSelectKey);
this._register(toolExecutor.registerHook({
validating: (context) => {
if (!this.enabled()) return 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.

P1 Badge Use the request's effective capabilities for validation

When dynamic-tool support comes from protocol inference rather than the profile's raw capability catalog, createToolSelectResolver retains the old schema and emits the update reminder, but this check calls this.enabled() with the raw profile capabilities and therefore skips rejection. A model configured without explicit capability flags can then call the tool using the retained schema while the updated registry implementation receives those stale arguments; use the same protocol-enriched capability decision that shaped the request. The existing protocol-inference test at toolSelectService.test.ts:1020-1036 demonstrates that these capability sources can differ.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

Grapedge added a commit that referenced this pull request Nov 12, 2026
* fix(agent-core-v2): truncate oversized skill content (#4834)

* fix(kap-server): bind the main agent when a session is created (#4839)

* fix(kap-server): bind the main agent when a session is created

* fix(kap-server): reject a profile on prompt submissions

* fix(kap-server): reject a profile change through the session profile

* fix(kap-server): wait for model configuration before binding a new session

* fix(agent-core-v2): deduplicate restored task notifications (#4836)

* fix(agent-core-v2): deduplicate restored task notifications

* chore: add notification replay fix changeset

* fix(agent-core-v2): preserve task notifications after prompt-only crashes

* fix(agent-core-v2): complete prompts before ending turns

* test: align lifecycle snapshots with prompt completion order

* fix(agent-core-v2): settle all prompts during turn finalization

* fix(kap-server): drop reserved metadata keys from session profile updates (#4842)

* fix(kap-server): drop reserved metadata keys from session profile updates

* fix(kap-server): keep stored reserved metadata keys on profile updates

* docs: split and rewrite the server API reference (#4841)

* docs: split and rewrite the server API reference

* docs: redirect old server API anchors to the split pages

* docs: describe profile metadata as a replacement

* docs: mark question responses as answered-only

* fix(kap-server): avoid heartbeat timeout after scheduling stalls (#4823)

* fix(kap-server): avoid heartbeat timeout reaping after stalls or clock jumps

* fix(kap-server): grace heartbeat window for short scheduling stalls

* fix(kap-server): treat only clearly late heartbeats as scheduling stalls

* fix(kap-server): time heartbeats on a monotonic clock and drain queued input before reaping

---------

Co-authored-by: Kimi Code (Grok Bot) <[email protected]>

* fix(kap-server): undo a turn only once when requests race (#4846)

* docs: describe heartbeat stall handling (#4849)

* docs: describe heartbeat stall handling

* docs: explain the monotonic clock in the heartbeat notes

* fix(agent-core-v2): acquire session lock before loop restoration (#4848)

* fix(agent-core-v2): acquire session lock before loop restoration

* chore: add session lock lifecycle changeset

* fix(agent-core-v2): hold session lock through loop restoration

- add an operation-scoped lease to the session run gate
- hold it across loop initialization, reset, and pending drains
- cover idle timeout and release ordering

* fix(agent-core-v2): keep the output of stopped tool calls (#4854)

* fix(kap-server): drop the partial reply of a retried step (#4855)

* fix(agent-core-v2): dedupe historical tool schemas (#4862)

* fix(agent-core-v2): dedupe historical tool schemas

* chore: add duplicate tool schema changeset

* fix(agent-core-v2): preserve first tool schema declaration

* fix(agent-core-v2): remind on changed tool schemas

* fix(agent-core-v2): block stale tool schema calls

* fix(agent-core-v2): normalize registry schemas in pending checks

* fix(agent-core-v2): import registry tool metadata type

* fix(agent-core-v2): preserve abort handling during validation

* fix(agent-core-v2): refine validation hook preparation

* fix(agent-core-v2): make validation hooks synchronous

* fix(agent-core-v2): preserve tool result notes on fork (#4867)

* fix(agent-core-v2): preserve tool result notes on fork

* chore: add fork tool result note changeset

* fix(agent-core-v2): scope tool result note restoration to forks

* fix(agent-core-v2): normalize inherited tool result notes

* fix(agent-core-v2): isolate fork note restoration

* feat(tui): sweep running titles toward text and add KIMI_CODE_TUI_ANIMATION_FPS (#4843) (#4870)

* chore: sync web dist from code-app (#4871)

code-app: 8ab17294e031323186d357d121c5360b8353900e

Co-authored-by: kimi-agent-bot <[email protected]>

* ci: release packages (#4835)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* chore: sync web dist from code-app

code-app: 5835391dac3a2b9e0c65ffbd418f0d6042a7adb2

---------

Co-authored-by: Haozhe <[email protected]>
Co-authored-by: qer <[email protected]>
Co-authored-by: Kimi Code (Grok Bot) <[email protected]>
Co-authored-by: grapedge <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
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