Repository navigation
fix(agent-core-v2): stop stripping dynamic tool context from compaction requests - #4410
Conversation
…on requests The compaction request ran stripDynamicToolContext() before handing the history to the LLM requester, while loop requests only go through toolSelect.shapeHistory(). With tool select enabled and any deferred tool configured, this removed the loadable-tools announcement (and the tools field of loaded schema messages), so the compaction request diverged from the previous loop request early in the history and lost almost all prompt cache reuse. Drop the extra strip so both requests share the single shaping point in the LLM requester. Add a harness helper that reports the first prefix break between two provider-visible requests, and a compaction test matrix (tool select off / announced / schema loaded x manual / auto) asserting the compaction request extends the last loop request. Resolve #4389
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
🦋 Changeset detectedLatest commit: 4ba3ed2 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 SummaryThis 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: 4ba3ed2e9d
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const maxAttempts = resolvedModel.compactionMaxAttempts ?? MAX_COMPACTION_RETRY_ATTEMPTS; | ||
| let attempt: CompactionAttemptResult | undefined; | ||
| let historyForModel: readonly ContextMessage[] = stripDynamicToolContext(originalHistory); | ||
| let historyForModel: readonly ContextMessage[] = originalHistory; |
There was a problem hiding this comment.
Shape disabled tool context before trimming the compaction history
For sessions that previously used tool-select but now have it disabled (or switched to a model without dynamic-tool support), canonical history still contains the old announcements. Passing that history directly into preShrinkHistoryToWindowBudget counts announcement text that llmRequester.shapeHistory() subsequently removes. Near the window budget, this can unnecessarily discard real conversation messages: previously, stripping the announcements first allowed those messages to fit. The summary then permanently replaces the original history without having seen the discarded content. This contradicts the declared unchanged behavior for disabled tool-select. Apply toolSelect.shapeHistory(originalHistory) before budgeting so enabled sessions retain their cache prefix while disabled sessions preserve the previous strip-before-trim behavior.
AGENTS.md reference: AGENTS.md:L112-L112
Useful? React with 👍 / 👎.
…on requests Port of upstream MoonshotAI#4410 (a9dc3a9). The compaction request stripped dynamic tool context while loop requests only go through toolSelect.shapeHistory(), so with tool select on the compaction request diverged early and lost prompt-cache reuse. Both requests now share the single shaping point in the LLM requester. The ported test used vitest's vi.stubEnv; this fork runs bun:test, so it uses the existing setEnv helper instead.
MoonshotAI#4410 MoonshotAI#4413 MoonshotAI#4431 MoonshotAI#4450 MoonshotAI#4451 MoonshotAI#4485 MoonshotAI#4524 were each implemented earlier — the compaction prefix suite, the media-recovery case, the OAuth callback socket drain, the split delivering-work section, the compaction wording, the reasoning-key order and the 10-step todo reminder are all in the tree and pinned by their own tests. Each row now carries that probe. Only MoonshotAI#4410 needed care: upstream patched paths that this fork renamed (`human/llm/builtin/protocol` versus `human/llm/requester/bases`), so the matching was done on the behaviour — stripDynamicToolContext is gone and extractEventUsage already reads usage only on terminal response events. Ledger: closed 22 -> 28, remaining 71.
Requirement or Bug
Resolve #4389
Bug Reproduction Steps
See linked issue
Root Cause
压缩请求比普通 loop 请求多做了一次历史裁剪:
llmRequesterService调用toolSelect.shapeHistory()。tool-select 开启时走shapeActiveHistory(),loadable-toolsannouncement 和已加载的 schema 消息原样保留。fullCompactionService先调用stripDynamicToolContext(originalHistory),删掉 announcement,并去掉 schema 消息上的tools(变成空壳的消息整条丢弃),然后再进入同一个shapeHistory()。announcement 在第一轮就写进历史。所以只要开启了 tool-select 且至少有一个 deferred 工具,压缩请求的 messages 就会在很靠前的位置和上一次 loop 请求分叉,后面的前缀缓存全部失效(issue 中命中率从 99.5% 降到 22.9%)。如果用户用
select_tools加载过工具,schema 消息处还会再分叉一次。这是根本修复:删掉压缩路径自带的裁剪,让所有请求只在
llmRequester一处整形。删掉是安全的,原因如下:applyCompaction会用摘要替换整个历史,announcement 和 schema 消息本来就会消失;CompactionCompleted会清空 pending 的加载记录,下一轮重新播报可加载工具。shapeHistory()的关闭分支仍会调用stripDynamicToolContext,provider 看不到消息上的tools。IAgentLLMRequesterService只有 loop 和 compaction 两个调用方,只有 compaction 会自己传入 messages。Code Changes
测试:
test/harness/snapshots.ts新增findGenerateCallPrefixBreak(previous, next)。它比较两次请求实际交给 provider 的 system prompt、tools 和 history,返回第一处分叉的位置和两边的内容,完全延伸则返回undefined。原有的私有函数isMessagePrefix改为复用同一个实现,行为不变。fullCompaction.test.ts新增FullCompaction prompt-cache prefix组合测试:tool-select 分为关闭、开启且有未加载的 deferred 工具、开启且已加载 schema 三种情况,各配手动/compact和自动压缩,共 6 个用例。每个用例先断言场景成立(announcement 和 schema 确实出现在请求里),再断言压缩请求是上一次 loop 请求的前缀延伸。{ at: 'history', index: 1, previous: <announcement>, ... };加上修复后 6 个全部通过。Behavior Changes and Affected Users
loadable-toolsannouncement,去掉已加载 schema 消息上的tools(空壳整条丢弃)KIMI_CODE_EXPERIMENTAL_TOOL_SELECTtools,这与 loop 请求的估算方式一致shrinkCompactionHistoryAfterOverflow)兜底stripDynamicToolContextshapeHistory()的关闭分支调用同一个函数受影响人群:开启了 experimental flag
tool-select的用户(通过KIMI_CODE_EXPERIMENTAL_TOOL_SELECT、[experimental]配置或KIMI_CODE_EXPERIMENTAL_FLAG),且使用了声明dynamically_loaded_tools的模型,并配置了 deferred MCP server 或 deferred user tool。TUI、print 模式、desktop 与 web、ACP、SDK 都走同一条压缩路径。flag 默认关闭,默认配置的用户不受影响。受影响模块:
packages/agent-core-v2/src/agent/fullCompaction/;测试辅助函数位于packages/agent-core-v2/test/harness/。测试覆盖:
FullCompaction prompt-cache prefix中 tool-select 开启的 4 个用例。FullCompaction pre-shrink等)。toolSelectService.test.ts中的 "shapeHistory strips dynamic-tool protocol context without touching the canonical history" 钉住关闭分支的裁剪行为。本地验证:agent-core-v2 的 compaction、toolSelect、llmRequester 测试共 295 个用例通过,
tsc和check-no-comments通过。全量测试中失败的用例与本改动无关:MCP OAuth 的几个超时用例单独运行时通过;tool.test.ts的 "returns the spawned agent id when a foreground subagent times out" 在 main 上同样失败。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.