Skip to content

fix(agent-core-v2): restore loop tool baseline from session journal - #5635

Merged
sailist merged 1 commit into
mainfrom
bug-476-11-27-loop-tool-schema-restore
Nov 28, 2026
Merged

sailist merged 1 commit into
mainfrom
bug-476-11-27-loop-tool-schema-restore

Conversation

@sailist

@sailist sailist commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

在 #5433 将 MCP 工具默认改为 deferred 并限制启动等待为 2s 之后,恢复历史会话时 Loop 不会从 wire.jsonl 还原初始化工具基线,而是在启动时用当前进程的工具注册表重新计算 profile.tools。这导致同名工具(尤其是 MCP 工具)在服务端升级 schema 或描述后,旧会话恢复时会混入新版定义、破坏 prompt cache 前缀连续性;fork 子代理继承的基线在冷恢复后也会丢失。本 PR 让 agent-core-v2 把 resolver 前的 Loop 初始化工具基线持久化到 wire.jsonl,并在恢复时以会话持久化的基线为准(已落盘的 tools.settled 原样恢复,禁用工具在执行期仍被策略拦截),请求期继续按模型能力投影(静态模型的基线绝对冻结由已合入的 #5638 保障)。

Bug Reproduction Steps

  1. 配置一个 stdio MCP 服务,提供 lookup 工具(v1 schema),创建会话并完成至少一轮对话(或 fork 一个子代理)。
  2. 退出进程,将同一 MCP 工具的 description / inputSchema 修改为 v2(或子代理 fork 后不发起任何请求直接退出)。
  3. 重新启动并恢复该会话,读取 baselineTools() / previewRequestContent().tools,或继续发起请求观察出站 tools;若在恢复后立即发起请求而 MCP 子进程尚未完成重连,观察首轮工具目录与调用。

修复前:恢复出的 profile.tools 来自当前进程注册表重算,lookup 被替换为 v2 schema(子代理首请求前退出时则完全丢失继承基线);且重启后首轮 reconcile 会把尚未重连完成的 MCP 工具误判为「已删除」,导致 select_tools 报 Unknown tool、直接调用报 Tool not found。修复后:恢复出的基线与出站请求均保持 jsonl 中记录的 v1 schema,请求前会按启动预算等待初始 MCP 落定,仍在连接中的服务器不会被误卸载。

Root Cause

这是根本修复,断点分布在持久化写入、链路筛选与恢复初始化三处:

  1. Core Loop 本身已在首个请求、任何 resolver 运行之前发射 tools.settled(packages/core/src/loop/turn/create-turn.ts),但 agent-core-v2 的 LoopJournal.append 没有处理该事件,直接落入 default 丢弃,从未写入 wire.jsonl。
  2. WireService 的 isLoopProfileRecordType 只放行 profile.bind / config.update / tools.set_active_tools / tools.reset_active_tools,导致 readLoopChain() 既读不到工具基线,也读不到存量会话的 tool_select.initialized。
  3. restoreLoopJournal 将 input.profile.tools 写死为 [],AgentLoopService.initializeLoop 在未显式传入 initialTools 时总是等待 MCP 后用当前环境的 toolSelect.initialTools() 覆盖基线;子代理自身 wire.jsonl 在首个 Turn 前没有任何基线记录,崩溃或退出后无法还原继承基线。此外,若恢复时跳过初始 MCP 等待,toolSelect.reconcile() 会在 MCP 子进程仍处于 pending 时读取空的实时注册表,把尚未连上的工具当作已移除写入 tool_select.tools_changed。

Code Changes

核心思路:复用 Core 已有的 tools.settled 事件表达「resolver 前的 Loop 初始化基线」,在首个请求前落盘并按规范化 JSON 去重;恢复时若存在 tools.settled 则原样(verbatim)作为 Loop 基线,不再按后续策略变化二次过滤或改写;存量无 tools.settled 的会话则通过回放 tool_select.initialized 后的 initialTools() 按会话策略推导一次基线。被禁用的工具在执行期仍由工具策略拦截。恢复与每次请求 reconcile 前均按剩余 startup_wait_ms 预算等待初始 MCP 连接落定,且对仍处于 pending(未成功也未失败)的服务器绝不误判卸载。出站请求仍走原有 tool-select、媒体门控等 resolver,不改变动态披露与跨模型切换;静态模型绝不追加基线外工具由已合入的 #5638 保证。

flowchart LR
    subgraph Write["写入路径(首请求前 / fork 初始化)"]
        Core["Core Loop<br/>tools.settled(resolver 前)"] --> Journal["LoopJournal.settleTools<br/>规范化 JSON 去重"]
        Fork["AgentLifecycleService.fork<br/>传入 initialTools"] --> Init["AgentLoopService.initializeLoop"]
        Init -->|显式 initialTools 立即落盘| Journal
        Journal --> Wire["agents/&lt;agentId&gt;/wire.jsonl"]
    end

    subgraph Restore["恢复与请求路径"]
        Wire --> Chain["WireService.readLoopChain<br/>放行 tools.settled / tool_select.initialized"]
        Chain --> Snapshot["restoreLoopJournal<br/>读取 tools.settled(无则由 initialTools 回放目录)"]
        Snapshot --> Wait["initializeLoop / reconcileForRequest<br/>按剩余 startup_wait_ms 等待初始 MCP 落定"]
        Wait --> Filter["原样采用已持久化基线 + reconcile<br/>pending 服务器不误判卸载;执行期策略拦截禁用工具"]
        Filter --> Loop["loop.state.profile.tools"]
        Loop --> Resolvers["请求 resolver:tool-select / media(静态模型严守冻结基线)"] --> Out["出站 LLM 请求"]
    end
Loading

把基线恢复放在 Loop 初始化层、把策略与模型能力投影保留在各自既有层,是因为 profile.tools 需要保持会话级稳定事实来源,而 deferred 披露与媒体门控都是每次请求按当前能力计算的视图;把初始 MCP 等待放在 initializeLoop 与 reconcileForRequest,则保证任何恢复或目录查询都不会在 pending 窗口把慢启动工具误判为删除。

决策 选择 没选 理由
恢复哪份工具定义 Core 发射的 resolver 前 profile.tools(tools.settled) resolver 后的 llm.tools_snapshot llm.tools_snapshot 已剥离 deferred 与 source,直接当基线会破坏动态披露与跨模型切换
主会话落盘时机 Core 首个实际请求发射 tools.settled 时落盘并去重;仅显式 initialTools 的 fork 子代理在初始化时主动落盘 所有 Loop 初始化/恢复时立即落盘 只读恢复已有会话必须零追加(wire/resume.test.ts),否则多客户端同开会误报 session.stale;fork 子代理需在首请求前消除崩溃窗口
存量会话兼容 无 tools.settled 时经 initialTools() 回放同链 tool_select.initialized 并按会话策略推导一次基线(保留 deferred) 强制迁移重写旧文件或直接回退当前注册表 旧文件无需重写即可恢复历史 schema 与 deferred 语义
已持久化基线与后续策略变化 已落盘 tools.settled 原样恢复,不因后续新增禁用而改写基线;禁用工具在执行期被策略拒绝 恢复时按新策略二次过滤并在下一轮覆盖落盘 保持会话冻结基线与 prompt cache 前缀稳定,策略在执行层生效而不篡改历史基线
reconcile 前等待与卸载时机 在 initializeLoop 与 reconcileForRequest 按剩余 startup_wait_ms 等待初始 MCP;pending 服务器不从 current 中剔除 在会话打开时无限等待,或启动窗口一过就把未连上服务器当作删除 避免慢启动/重启竞态产生假 removed/unload;只有服务器确定失败/移除,或连上后真实缺少该工具时才卸载

关键改动位置(建议阅读顺序):

  1. packages/agent-core-v2/src/agent/loop/turnOps.ts:声明 durable ToolsSettled(tools.settled,不广播 RPC),注册到 turnKey 空 reducer 以纳入事件注册表与 wire manifest。
  2. packages/agent-core-v2/src/agent/loop/journal.ts:restoreLoopJournal 归约 tools.settled(无记录时返回 undefined,交由 initialTools() 回放存量 tool_select.initialized);LoopJournal.settleTools 做规范化 JSON 去重,snapshot() 同步已持久化基线,append 接住 Core tools.settled。
  3. packages/agent-core-v2/src/wire/wireService.ts:isLoopProfileRecordType 放行 tools.settled 与 tool_select.initialized。
  4. packages/agent-core-v2/src/agent/toolSelect/toolSelectService.ts:reconcileForRequest 在 reconcile 前调用 awaitInitialMcp 按剩余预算等待初始 MCP;reconcile 计算 removed 时保留仍处于 pending 的 MCP 服务器工具。
  5. packages/agent-core-v2/src/agent/loop/loopService.ts:baselineTools() 在未启动时读取恢复基线;initializeLoop 在基线选择前统一做 startup_wait_ms 有界等待,再按「显式 initialTools > 原样恢复的 tools.settled 基线 > 现算 initialTools()(含存量目录回放与策略过滤)」选择基线,仅显式传入 initialTools 时立即落盘。
  6. apps/vis:agent-record-types.ts、context-projector.ts、renderers.tsx 补齐 tools.settled 类型、投影分支与 tools·baseline 渲染器。

其余改动为 wire-manifest.d.ts / state-manifest.d.ts 重新生成、中英文会话文档与 llm.md 同步、新增 .changeset/restore-loop-tool-baseline.md,以及单测快照补充 [wire] tools.settled 行,可略读。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
含 tools.settled 的会话恢复时 Loop 初始化基线 忽略历史基线,等待 startupWaitMs 后用当前进程注册表 initialTools() 重算 原样按 jsonl 中的 tools.settled 还原 description / parameters / deferred,不按新策略二次过滤 依赖「重启会话后自动拾取同名内置/MCP 工具新 schema」的 TUI、CLI、Desktop/Web、SDK、ACP 用户 无配置开关;该行为变更已经需求方明确确认(以持久化基线为准)
恢复会话及请求 reconcile 时的初始 MCP 同步 恢复后首轮可能在 MCP 重连完成前 reconcile,把 pending 服务器的工具当作已删除从 current 剔除 initializeLoop 与 reconcileForRequest 按剩余 startup_wait_ms 等待初始 MCP 落定;超过预算仍 pending 的服务器不发移除,待连上(按真实 tools/list diff)或确定失败后再增删 重启后立即发消息、或配置了慢启动(2s~30s)MCP 服务器的恢复会话用户 沿用现有 [mcp] startup_wait_ms(设为 0 则不阻塞前台等待,但仍不误卸载 pending 服务器)
无 tools.settled 但含 tool_select.initialized 的存量会话恢复 用当前注册表重算基线 经 initialTools() 回放 tool_select.initialized 推导基线(还原 deferred: true 并按会话策略过滤);基线未变时不追加 tools.settled 旧版本写入的存量会话恢复后曾拾取当前 schema 的用户 同上;两者皆不存在的更早会话仍走原 initialTools() 回退
当前策略(activeToolNames / disallowedTools / [tools] disabled / 会话级禁用 / 受管策略)与基线交互 每次重启按当时策略与注册表重算,解禁后重启即可恢复全部当前工具 已落盘 tools.settled 原样保留在 baselineTools() 与出站请求中,不因后续禁用/解禁改写;被禁用工具在实际调用时被策略拦截报错;无 tools.settled 的存量会话仍按会话策略过滤 依赖恢复时按最新 [tools] disabled / activeToolNames 裁剪冻结基线的调用方 无配置开关;禁用工具在执行期仍被拦截,不会真正执行
fork 子代理基线持久化 子代理首个请求前不落盘基线,冷恢复后退回当前环境重算 fork 初始化时立即在子代理自身 wire.jsonl 写入一条继承的 tools.settled,冷恢复保持一致 在子代理首请求前中断/重启进程并期望重算工具集的 SDK / Agent 调用方 无
wire.jsonl 新增记录类型 tools.settled 仅 69 种记录类型 新增第 70 种 durable 记录 tools.settled(observable = false,不广播 RPC),apps/vis 提供对应渲染器 解析 wire.jsonl 的外部调试/可视化工具(含 apps/vis) 向后兼容:旧版本按既有未知记录跳过策略忽略;不提升 min_protocol_version,无需迁移重写

受影响模块与测试覆盖:

  • agent-core-v2:journal.test.ts 与 coreLoopService.test.ts 覆盖 v1 schema 抗注册表篡改、存量 tool_select.initialized 回退过滤、tools.settled 跨策略变化原样恢复与去重、禁用工具执行期拦截、fork 子代理首请求前落盘恢复;toolSelect.e2e.test.ts 新增 4 个回归用例,覆盖动态/静态模型下恢复后首请求等待初始 MCP、pending 服务器超过启动预算不误卸载、连上缺工具或连接失败后再卸载。
  • apps/vis:renderers.test.ts 校验全部 70 种 durable 记录均有渲染器。
  • 端到端验证:tests/scenarios/prompt-cache.test.ts(重启 + 自动压缩后继续使用 inline/deferred MCP 工具)通过;工作区 custom-e2e/loop-tool-schema-restore/ 中存量回退、compaction、undo、主子代理冷恢复 6 个场景通过,3 个断言「恢复时按策略裁剪已持久化基线」的旧场景(static-cold-restore、disabled-filtered-baseline-persists、active-tools-filtered-baseline-persists)待按原样恢复语义更新;custom-e2e/mcp-startup-lifecycle/ 6/6 全部通过。
  • 未验证:Windows 实机与 Desktop Electron 端(改动位于引擎层,无 UI 源码变更)。
已执行的检查命令与结果
  • m0-dev:packages/agent-core-v2、apps/vis/server、apps/vis/web 三个 tsconfig tsc --noEmit 0 错误;toolSelect / loop / wire / mcp 定向单测通过。
  • 本地(base=main@origin da8bdbb8a5ed,head=21c6ebfcc28a):agent-core-v2 tsc --noEmit 0 错误;coreLoopService.test.ts / journal.test.ts / toolSelect 共 5 个测试文件、167 个用例全部通过。
  • lint-pool(base=da8bdbb8a5ed):完整 pnpm lint(oxlint 0 警告、test-doubles、app-boundaries、ratchet 等)与 pnpm run check:duplication 0 新增重复。
  • custom-e2e/mcp-startup-lifecycle/run.mts:6/6 通过;custom-e2e/loop-tool-schema-restore/run.mts:6/9 通过(上述 3 个旧策略裁剪断言待按新契约审批更新)。

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.

@changeset-bot

changeset-bot Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 21c6ebf

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/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 27, 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-27T06:54:56.073125Z 56cb8cf 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 27, 2026 •

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

commit: 21c6ebf

@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: 56cb8cfbc7

ℹ️ 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 +581 to +582
} else if (restoredTools !== undefined) {
tools = this.toolSelect.restoreBaselineTools(restoredTools);

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 Reconcile restored inline schemas with live executors

When an inline tool changes its required arguments while the process is stopped—such as an MCP tool configured with deferred: false—this branch restores the old persisted schema, but ToolExecutor still registers the current implementation from the live registry. ToolSelect only replaces changed entries when both versions are dynamically loadable, so the model continues generating arguments for the old schema and sends them to the new handler or MCP server, where calls can consistently fail. Restore the live schema for changed inline tools, or otherwise ensure that the persisted schema has a matching executable implementation.

AGENTS.md reference: AGENTS.md:L111-L113

Useful? React with 👍 / 👎.

@sailist
sailist force-pushed the bug-476-11-27-loop-tool-schema-restore branch 2 times, most recently from d324fdb to 9821301 Compare November 27, 2026 08:14
@sailist
sailist changed the base branch from main to bug-479-11-27-strict-loop-tool-baseline November 27, 2026 08:14
Base automatically changed from bug-479-11-27-strict-loop-tool-baseline to main November 27, 2026 08:17
@sailist
sailist force-pushed the bug-476-11-27-loop-tool-schema-restore branch 3 times, most recently from 6ab5044 to 7e97318 Compare November 27, 2026 10:26
@sailist
sailist force-pushed the bug-476-11-27-loop-tool-schema-restore branch from 7e97318 to 21c6ebf Compare November 27, 2026 12:25
@sailist
sailist merged commit a6ac07d into main Nov 28, 2026
23 checks passed
@sailist
sailist deleted the bug-476-11-27-loop-tool-schema-restore branch November 28, 2026 01:21
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
Port upstream 357a311 (MoonshotAI#5433) in the upstream-final shape: MCP server
tools are deferred by default; session initialization waits at most
startup_wait_ms (default 2000, KIMI_MCP_STARTUP_WAIT_MS, 0 skips) for
initial MCP discovery and then freezes the tool baseline; stdio servers
that fail their initial startup stay failed without background retries,
while HTTP/SSE startup failures and established-connection drops still
retry.

Fork adaptations: the capped wait also replaces the unconditional session
MCP ready wait in toolSelectService.prepareForRequest, using the remaining
budget from initialLoadDurationMs (upstream MoonshotAI#5635 shape), so the 2s cap is
not defeated; the late-MCP inline append from MoonshotAI#5433 is skipped because
upstream MoonshotAI#5638 reverted it to protect the prompt-cache prefix, and the
fork's existing runtime inline-tool behavior is unchanged.

Docs en/zh, the config manifest, a CLI changeset and the affected config,
connection-manager, loop, toolSelect and forkParity tests are updated; the
oxlint ratchet baseline moves down only.
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