Skip to content

fix(agent-core-v2): unload only previously declared dynamic tools - #5438

Merged
sailist merged 1 commit into
mainfrom
bug-466-11-25-unload-declared-tools
Nov 26, 2026
Merged

sailist merged 1 commit into
mainfrom
bug-466-11-25-unload-declared-tools

Conversation

@sailist

@sailist sailist commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

使用支持动态工具加载(dynamically_loaded_tools)的 Kimi 模型时,如果某个工具只在 <tools_added> 目录公告里出现过名字、从未通过 select_tools 向模型声明过 schema,之后该工具从注册表消失(例如宿主在创建会话后收窄内置工具名单再重启恢复、未加载的 deferred MCP 被停用/删除、或 /tower off),Core 仍会在请求里发送 unload_tools。严格校验的网关会拒绝“卸载未声明工具”,导致恢复后的会话无法继续对话。本 PR 让 unload_tools 只与请求内此前同名的 system schema 声明消息配对,旧会话无需迁移即可恢复。

Bug Reproduction Steps

  1. 使用支持 dynamically_loaded_tools 的 Kimi 协议模型,并注册一个 deferred MCP 服务(或先全量注册内置工具、再通过策略禁用后重启恢复会话)。
  2. 发起一轮普通对话,模型只在 <tools_added> 中看到工具名,不调用 select_tools 加载其 schema。
  3. 停用/删除该 MCP 服务(或在重启恢复时让被禁用的内置工具不再注册),再发送下一条消息。
  4. 观察出站请求:变更公告后带上了 { "role": "system", "unload_tools": ["<从未声明的工具名>"] }。

Root Cause

根因是把“注册表/可加载目录变化”直接等同于“模型侧 schema 卸载”:

  • AgentToolSelectService.reconcile() 对比持久化账本与实时 toolRegistry.list(),把消失的工具记入 removed;renderDeltaAnnouncement() 不区分这些工具是否曾注入 system.tools,全部写入 tool_lifecycle meta 的 removed。
  • shapeActiveHistory() 虽然已经在按顺序维护 declaredDynamicTools(本次请求里实际保留的 system.tools 声明),但只用它做同名 schema 去重,没有过滤公告上的 meta.removed。
  • kimiOpenAIProtocol.message() 看到非空 meta.removed 就无条件追加 unload_tools,而后端按单次无状态请求判断工具是否声明过。

这是对“卸载声明生成规则”的根本修复(不针对特定工具加名单);宿主分步创建会话导致的注册表与账本不一致不在本 PR 重做。

Code Changes

只改请求出站视图整形的一处边界,不改 loop 持久化历史、不改 reconcile() 的目录公告逻辑,下游 Kimi 协议层与 legalize-tools 无需改动:

 shapeActiveHistory(messages, tools)
   for message of messages
     if isLoadableToolsAnnouncement(message)
-      delete meta.removed names from declaredDynamicTools
+      keep only names deleted from declaredDynamicTools in outbound meta.removed
     next = shapeActiveMessage(message, inlineNames, declaredDynamicTools)
  • 配对依据是 system.tools(自动排除当前请求顶层 inlineNames),而不是 <tools_added>。
  • 发送位置仍留在 <tools_removed> 公告之后,保证已加载工具同名更新的 旧 system.tools → unload_tools → 新 system.tools 时序,并避免改动历史前缀破坏缓存。
  • <tools_removed> 正文保持不变,模型仍能得知哪些名字不再可 select_tools;未发生过滤的消息保持原引用,落盘历史完全不改写。

阅读顺序:先看 packages/agent-core-v2/src/agent/toolSelect/toolSelectService.ts 的 shapeActiveHistory / shapeLifecycleAnnouncement,再看 packages/agent-core-v2/test/agent/toolSelect/toolSelectService.test.ts 的恢复与未加载更新回归用例;docs/en/llm.md 与 changeset 可略读。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
未声明 schema 的工具被移除(含恢复会话时已落盘的错误 removed) 在公告后发出 unload_tools 仅从出站 meta.removed 剔除,不发 unload_tools;<tools_removed> 正文与落盘历史保留 无(请求内此前未声明该工具) 无
同一工具已卸载后再次出现移除公告(未重新加载) 重复发出 unload_tools 不再重复发出,直到再次通过 system.tools 声明 无 无
当前仍在顶层 profile.tools 声明的 inline 工具出现在历史 removed 中 历史里仍发出 unload_tools 不发出,顶层声明保持有效 无 无
已通过 system.tools 加载的 MCP / deferred 工具被移除或同名 schema 更新 发出 unload_tools,同名更新按“旧定义 → unload → 新定义”发送 保持不变 使用动态工具加载的 Kimi 协议会话(TUI、CLI print/web、Desktop、SDK/KAP 宿主) 无需
非动态模型与非 Kimi 协议 不输出 unload_tools 保持不变 不支持 dynamically_loaded_tools 的模型及其他 provider 无需

受影响模块与测试覆盖:

  • packages/agent-core-v2/src/agent/toolSelect/toolSelectService.ts:新增出站公告的 removed 过滤。
  • packages/agent-core-v2/test/agent/toolSelect/toolSelectService.test.ts:新增恢复会话只卸载已声明 system.tools 工具的回归用例,并补强未加载同名更新不产出 unload_tools 的断言(修复前两条均失败,修复后通过)。
验证记录
  • m0-dev(Linux):
    • vitest run packages/agent-core-v2/test/agent/toolSelect packages/agent-core-v2/test/agent/loop/coreLoopService.test.ts packages/agent-core-v2/test/session/subagent/forkParity.test.ts:5 文件 162/162 通过。
    • @moonshot-ai/core 全量测试:37 文件 402/402 通过。
    • @moonshot-ai/agent-core-v2 全量测试:8230 通过 / 13 跳过 / 2 失败——失败均位于 test/app/git/gitService.test.ts(git sparse-checkout 读取 config.worktree 报 ENOENT,为测试机 git 版本行为差异,与本 PR 改动无交集)。
    • tsc -p packages/agent-core-v2/tsconfig.json --noEmit:通过。
  • 本地 git worktree:pnpm lint(含 check-comments、type-aware oxlint --deny-warnings、import-boundaries、guards、ratchet、instructions 等)0 warning / 0 error;pnpm run check:duplication 通过。
  • 未验证:真实网关端到端请求(网关对未声明 unload_tools 的协议校验属于独立配套项);Windows 专项(不涉及平台路径/进程行为)。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • 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.

Pair tool_lifecycle.removed with earlier system tool-schema declarations
when shaping request history so catalog-only removals and repeated deltas
do not emit native unload_tools, while preserving persisted history and
loaded MCP unload/reload ordering.
@changeset-bot

changeset-bot Bot commented Nov 25, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 44136f6

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

This PR includes changesets to release 3 packages
Name Type
@moonshot-ai/kimi-code Patch
kimi-code-app Patch
@moonshot-ai/agent-core-v2 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 25, 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-25T14:25:51.447372Z 44136f6 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.

@pkg-pr-new

pkg-pr-new Bot commented Nov 25, 2026

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

commit: 44136f6

@sailist
sailist merged commit 523bc8f into main Nov 26, 2026
22 checks passed
@sailist
sailist deleted the bug-466-11-25-unload-declared-tools branch November 26, 2026 02:48
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Dec 2, 2026
`bun scripts/upstream-ledger.mjs --refresh` at upstream/main 4eb2919
added 126 rows, so every open upstream commit and every PR it references
now has a ledger row: 0/596, down from 125 at 8bf8ba3 and 126 at the
fetched tip. The refresh only reads `upstream/main ^ main`, so the three
release-2.6.2 commits named by the mission (MoonshotAI#4875/MoonshotAI#4905/MoonshotAI#4922) gained
rows with the refresh's row shape.

Settled with live probes in this tree:

- ported: MoonshotAI#5533 (docs 2.8.1 changelog), MoonshotAI#4875 (registry search_url and
  feedback_url plus the feedback service), MoonshotAI#4905 (Kimi upload status
  validation in packages/core), MoonshotAI#4922 (swarm task events in
  sessionTaskFeed), MoonshotAI#5438 (unload only declared dynamic tools), MoonshotAI#5592
  (dynamic tool replacement order), MoonshotAI#5595 (append-log known length),
  MoonshotAI#5573 (skill roots for every work dir), MoonshotAI#5576 (date reminder cwd
  comparison), MoonshotAI#5618 (session titles for skill openers), MoonshotAI#5638 (frozen
  loop tool baseline), MoonshotAI#5626 (legacy turn-input origins)
- partial: MoonshotAI#5505 (processLiveness source and consumers present; the
  upstream unit test file was never carried), MoonshotAI#5571 (program-resume and
  OSC 7577 present; the upstream test helper was never carried), MoonshotAI#5532
  (gitService half present; fsService still leaks the environment lease
  at fsService.ts:1133 and :1267), MoonshotAI#5557 (app-client icon registry kept;
  the move to app-ui was never carried)
- not-applicable: MoonshotAI#4655 (upstream reverted auto review in MoonshotAI#5649), MoonshotAI#5333
  (PLAYBOOK:111 deliberate flat experimental flags)

M39's "likely present" list was checked, not trusted: MoonshotAI#5438 is present
(upstream test passes), MoonshotAI#5487 is not (nativeStartSettleMs/leg.nativeSettled
absent), MoonshotAI#5635 is not (ToolsSettled absent), MoonshotAI#5429 needs a visual probe.
The remaining 194 pending rows stay open with their reasons; no feature
was ported and no upstream-drift allowlist entry was added.

Verification: verify -> 332 closed rows, 332 carry every file of their
PR; 317 probes pass, 2 foreign-runner skips, 0 fail; a second verify is
byte-identical (ledger sha256 cbf53638...). Probe tests 29 pass; bun run
lint and node scripts/checks/ratchet.mjs green.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Dec 2, 2026
The upstream ledger reads `upstream/main ^main`, so a commit that only ever
existed on a `@moonshot-ai/kimi-code@<version>` release branch was never
enumerated: 89 commits reachable from 2.6.0-2.8.1 are absent from upstream/main,
20 of them are owned by an existing main-ledger row (by sha or PR), and the
other 69 had no row anywhere and no path into the ledger at all.

`.upstream/release-ledger.tsv` now carries one row per release-only commit the
main ledger does not own, in the main ledger's 11 columns plus a `tags` column
recording every version that reaches the commit.

`scripts/upstream-ledger.mjs` gains two entries that share
`scripts/lib/upstream-ledger-probes.mjs` with the existing tooling:

- `--release-refresh` fetches upstream main, enumerates the tag union, refreshes
  each row's tag list, and adds a pending row for every commit neither ledger
  owns. Rows whose commit is no longer release-only are reported, never deleted.
- `--release-verify` fails by name when a release tag commit has no row in
  either ledger, runs each release row's probe with the same runner-aware skip
  semantics as the main verify, holds `ported` rows to the shared per-commit
  file-completeness check, and re-runs the live probes of release commits the
  main ledger owns, so MoonshotAI#4875/MoonshotAI#4905/MoonshotAI#4922 stay on their probes instead of
  getting duplicate rows.

The initial classification is evidence-based: 15 release-metadata commits are
not-applicable with a written reason, 1 is ported (its patch reverse-applies),
16 are equivalent with live grep/test probes, 13 are partial with the present
and absent halves named, and 24 are pending with file and added-line evidence.
M39's "confirmed absent" list was partly stale: MoonshotAI#4995's Stop-hook code is in the
tree, MoonshotAI#5354's one-line change is fully present, MoonshotAI#5516 is the twin of the ported
MoonshotAI#5438, and MoonshotAI#5096/MoonshotAI#5191/MoonshotAI#5303 are present at source level, so those rows carry
the evidence that says so rather than an absence claim.

Verified: release verify -> 44 probes pass, 0 skipped, 0 fail, completeness 1/1,
0 missing rows, 0 hidden failures; main ledger verify -> 317 probes pass, 2
skipped, 0 fail, 332/332 closed rows complete; upstream-ledger-release fixture
test 16 pass; upstream-ledger-probes 29 pass; bun run lint 0 warnings 0 errors
and ratchet green on 6995 files.
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