Repository navigation
fix(agent-core-v2): restore loop tool baseline from session journal - #5635
Conversation
🦋 Changeset detectedLatest commit: 21c6ebf 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 |
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. |
commit: |
There was a problem hiding this comment.
💡 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".
| } else if (restoredTools !== undefined) { | ||
| tools = this.toolSelect.restoreBaselineTools(restoredTools); |
There was a problem hiding this comment.
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 👍 / 👎.
d324fdb to
9821301
Compare
6ab5044 to
7e97318
Compare
7e97318 to
21c6ebf
Compare
`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.
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.
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
lookup工具(v1 schema),创建会话并完成至少一轮对话(或 fork 一个子代理)。description/inputSchema修改为 v2(或子代理 fork 后不发起任何请求直接退出)。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
这是根本修复,断点分布在持久化写入、链路筛选与恢复初始化三处:
tools.settled(packages/core/src/loop/turn/create-turn.ts),但agent-core-v2的LoopJournal.append没有处理该事件,直接落入default丢弃,从未写入wire.jsonl。WireService的isLoopProfileRecordType只放行profile.bind/config.update/tools.set_active_tools/tools.reset_active_tools,导致readLoopChain()既读不到工具基线,也读不到存量会话的tool_select.initialized。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/<agentId>/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把基线恢复放在 Loop 初始化层、把策略与模型能力投影保留在各自既有层,是因为
profile.tools需要保持会话级稳定事实来源,而 deferred 披露与媒体门控都是每次请求按当前能力计算的视图;把初始 MCP 等待放在initializeLoop与reconcileForRequest,则保证任何恢复或目录查询都不会在pending窗口把慢启动工具误判为删除。profile.tools(tools.settled)llm.tools_snapshotllm.tools_snapshot已剥离deferred与source,直接当基线会破坏动态披露与跨模型切换tools.settled时落盘并去重;仅显式initialTools的 fork 子代理在初始化时主动落盘wire/resume.test.ts),否则多客户端同开会误报session.stale;fork 子代理需在首请求前消除崩溃窗口tools.settled时经initialTools()回放同链tool_select.initialized并按会话策略推导一次基线(保留deferred)tools.settled原样恢复,不因后续新增禁用而改写基线;禁用工具在执行期被策略拒绝reconcile前等待与卸载时机initializeLoop与reconcileForRequest按剩余startup_wait_ms等待初始 MCP;pending服务器不从current中剔除removed/unload;只有服务器确定失败/移除,或连上后真实缺少该工具时才卸载关键改动位置(建议阅读顺序):
packages/agent-core-v2/src/agent/loop/turnOps.ts:声明 durableToolsSettled(tools.settled,不广播 RPC),注册到turnKey空 reducer 以纳入事件注册表与 wire manifest。packages/agent-core-v2/src/agent/loop/journal.ts:restoreLoopJournal归约tools.settled(无记录时返回undefined,交由initialTools()回放存量tool_select.initialized);LoopJournal.settleTools做规范化 JSON 去重,snapshot()同步已持久化基线,append接住 Coretools.settled。packages/agent-core-v2/src/wire/wireService.ts:isLoopProfileRecordType放行tools.settled与tool_select.initialized。packages/agent-core-v2/src/agent/toolSelect/toolSelectService.ts:reconcileForRequest在reconcile前调用awaitInitialMcp按剩余预算等待初始 MCP;reconcile计算removed时保留仍处于pending的 MCP 服务器工具。packages/agent-core-v2/src/agent/loop/loopService.ts:baselineTools()在未启动时读取恢复基线;initializeLoop在基线选择前统一做startup_wait_ms有界等待,再按「显式initialTools> 原样恢复的tools.settled基线 > 现算initialTools()(含存量目录回放与策略过滤)」选择基线,仅显式传入initialTools时立即落盘。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
tools.settled的会话恢复时 Loop 初始化基线startupWaitMs后用当前进程注册表initialTools()重算tools.settled还原description/parameters/deferred,不按新策略二次过滤reconcile时的初始 MCP 同步reconcile,把pending服务器的工具当作已删除从current剔除initializeLoop与reconcileForRequest按剩余startup_wait_ms等待初始 MCP 落定;超过预算仍pending的服务器不发移除,待连上(按真实tools/listdiff)或确定失败后再增删[mcp] startup_wait_ms(设为 0 则不阻塞前台等待,但仍不误卸载pending服务器)tools.settled但含tool_select.initialized的存量会话恢复initialTools()回放tool_select.initialized推导基线(还原deferred: true并按会话策略过滤);基线未变时不追加tools.settledinitialTools()回退activeToolNames/disallowedTools/[tools] disabled/ 会话级禁用 / 受管策略)与基线交互tools.settled原样保留在baselineTools()与出站请求中,不因后续禁用/解禁改写;被禁用工具在实际调用时被策略拦截报错;无tools.settled的存量会话仍按会话策略过滤[tools] disabled/activeToolNames裁剪冻结基线的调用方wire.jsonl写入一条继承的tools.settled,冷恢复保持一致wire.jsonl新增记录类型tools.settledtools.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 全部通过。已执行的检查命令与结果
packages/agent-core-v2、apps/vis/server、apps/vis/web三个 tsconfigtsc --noEmit0 错误;toolSelect/loop/wire/mcp定向单测通过。main@originda8bdbb8a5ed,head=21c6ebfcc28a):agent-core-v2tsc --noEmit0 错误;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:duplication0 新增重复。custom-e2e/mcp-startup-lifecycle/run.mts:6/6 通过;custom-e2e/loop-tool-schema-restore/run.mts:6/9 通过(上述 3 个旧策略裁剪断言待按新契约审批更新)。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.