Repository navigation
fix(agent-core-v2): keep token counting and compaction anchored to usage - #4883
Merged
Merged
Conversation
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. |
🦋 Changeset detectedLatest commit: b187334 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 |
commit: |
sailist
approved these changes
Nov 13, 2026
5 of 6 tasks
6 tasks done
7723qqq
pushed a commit
to 7723qqq/kimi-code
that referenced
this pull request
Nov 15, 2026
Port MoonshotAI#4901, MoonshotAI#4909 and MoonshotAI#4911: complete the task before asserting a zero-timeout wait sees the completed snapshot, restore the instructions reload spy after the failure assertion, poll the search index until it is ready before asserting the page, and run remote-session git probes through a host process that refuses gh. Record MoonshotAI#4840 as equivalent (the refresh path already rebuilds from the effective binding here) and pin it with a regression case, record MoonshotAI#4883 as ported with the compaction profile already present, and record MoonshotAI#4830 as blocked on the absent loop requester/request-attribution layering. Clear the generated-bundle, release-sync and working-notes rows with their applicable verdicts.
11 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Requirement or Bug
在长会话中调用带附加说明(
note,如Read分页提示、输出截断提示)、报错状态(isError)、耗时头(Wall time)或空输出的工具后,TokenCountingAgentModel会因工具消息形态不一致而停止记录真实的token_counting.measured锚点,退回偏低的本地字符估算。当真实输入超过模型max_context_size(如 1M 窗口)而字符估算仍低于 85% 自动压缩阈值时,自动压缩不会触发,请求合法化会将剩余输出预算钳制为maxOutputTokens = 1,导致后续每次发消息都在长时间预填充后仅生成 1 个空 token 即结束(界面表现为长时间转圈后无任何回复)。本 PR 修复工具消息在请求侧与历史折叠侧的上下文匹配,使每一步持续记录真实 token 用量;同时在
AgentFullCompactionService的自动压缩判定与压缩预裁剪预算中引入历史assistant消息的真实usage锚点,使存量失配会话在收到任意新消息或执行/compact时立即在首步前完成预裁剪与自动压缩并恢复正常回复。Bug Reproduction Steps
max_context_size = 1,000,000)会话早期执行一次带分页note的Read(或带isError、Wall time、空输出、ReadMediaFile引用解析的工具调用)。1,000,000,而本地字符估算仍低于850,000(1,000,000 * 0.85)。legalOutputCap因window - usedTokens <= 0(其中usedTokens由estimateUsedContextTokens读取assistant.attributes.usage得到真实超窗值)将maxOutputTokens钳制为1,每次请求耗时预填充全量上下文后以finishReason: max_tokens返回空内容。Root Cause
根本修复。
sequenceDiagram participant Loop as AgentLoop / RequestObserver participant TC as TokenCountingAgentModel participant FC as AgentFullCompactionService participant Legal as runLlmRequest / legalOutputCap Loop->>TC: measured(input, [response], usage) Note over TC: 工具消息含 note / isError / Wall time / 空输出转换<br/>JSON.stringify(left.content) !== JSON.stringify(right.content) TC-->>TC: matchesContext 返回 false,后续步骤不再写入 token_counting.measured Loop->>FC: beforeStep -> tokenCountWithPending() Note over FC: 仅读 tokenCounting.get().size(退回字符估算 74.1w < 85w) FC-->>Loop: 跳过自动压缩 Loop->>Legal: generate(messages, usedTokens=undefined) Note over Legal: estimateUsedContextTokens 读取历史 assistant.usage (100.3w)<br/>room = 100w - 100.3w < 0 -> maxOutputTokens = 1 Legal-->>Loop: 预填充 100w token 后仅生成 1 token (finishReason: max_tokens)matchesContext恒假:ContextMessage(turnProjection.ts、loopEventFold.ts、history.ts)将工具结果的note、isError、durationMs与基础content分离存储。Loop历史中会将note追加进content,而在投影后(projection.ts→renderToolResultForModel)又会将note、isError(<system>ERROR: ...</system>)、Wall time头与空输出占位(<system>Tool output is empty.</system>)渲染进content;此外#4820将requestObservation.ts传给tokenCounting.measured的输入改成了经过媒体引用解析与动态工具裁剪后的recorded.messages。TokenCountingAgentModel.matchesContext直接用JSON.stringify(left.content) !== JSON.stringify(right.content)逐项比对,一旦出现上述任一工具结果,后续所有步骤均无法记录token_counting.measured。AgentFullCompactionService缺少历史真实usage锚点:tokenCountWithPending()仅读取tokenCounting.get().size,未参考历史assistant消息已持久化的真实usage;当存量会话缺少最新token_counting.measured记录且字符估算偏低时,无法在首步前触发自动压缩。preShrinkHistoryToWindowBudget与压缩请求预算同样只用本地字符估算(例如全量字符估算 74 万 <inputLimit87.5 万),导致真实输入已超 100 万的存量会话在压缩阶段跳过预裁剪并超窗。Code Changes
核心思路
保持
TokenCountingAgentModel与AgentLoopRequestObserver在每一步稳定写入token_counting.measured,同时让AgentFullCompactionService在判定自动压缩阈值与计算压缩预裁剪窗口预算时以历史assistant消息的真实usage作为下界锚点(与core请求侧estimateUsedContextTokens口径一致)。这样新会话每步都有精确锚点,已落盘的旧会话也能在下一条消息到来时立即自愈。阅读指南
packages/agent-core-v2/src/session/tokenCounting/tokenCountingAgentModel.ts:看matchesToolMessage如何对齐未渲染与经renderToolResultForModel渲染的工具消息。packages/agent-core-v2/src/agent/loop/requestObservation.ts:看未发生媒体降级恢复时如何向tokenCounting.measured传入 resolver 前的request.messages。packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts:看usageAnchoredRequestTokens与buildHistoryTokenProfile如何驱动自动压缩触发和预裁剪预算。packages/agent-core-v2/test/agent/tokenCounting/tokenCounting.test.ts、packages/agent-core-v2/test/agent/fullCompaction/fullCompaction.test.ts:回归测试。结构化变更大纲
Behavior Changes and Affected Users
note、isError、Wall time、空输出或正常媒体解析的工具调用后的token_counting.measured记录matchesContext返回false,后续步骤停止写入token_counting.measured,上下文大小退回本地字符估算token_counting.measured(发生 413/400 媒体降级/剥离重试的请求仍保持不写入未剥离上下文锚点)token_counting.measured缺失或偏低但历史assistant消息带有真实usage时的自动压缩触发(tokenCountWithPending)tokenCounting.get().size判断,字符估算偏低时漏触发压缩并导致maxOutputTokens被压成1tokenCounting.get().size与最新历史assistant真实usage+ 尾部估算的较大值,达阈值即在首步前自动压缩preShrinkHistoryToWindowBudget)、压缩usedContextTokens与tokensBefore计算inputLimit时不预裁剪assistant真实usage锚点计算总输入与分段消息权重,超inputLimit时在首轮压缩请求前完成预裁剪并保留充足输出窗口;无usage或字符估算更高时保持原结果不变/compact的用户packages/agent-core-v2/src/session/tokenCounting/tokenCountingAgentModel.tspackages/agent-core-v2/src/agent/loop/requestObservation.tspackages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.tsconfig-manifest.toml、wire-manifest.d.ts、state-manifest.d.ts、kap-serverAPI surface 快照与node-sdk导出面均无变更。packages/agent-core-v2/test/agent/tokenCounting/tokenCounting.test.ts:新增端到端在线执行 + 持久化恢复回归测试(覆盖带note分页工具、isError + note工具、空输出工具、mcp__*计时工具),以及投影后工具消息匹配与错误note/ 缺失isError拒绝测试。packages/agent-core-v2/test/agent/fullCompaction/fullCompaction.test.ts:新增存量会话无measured锚点但历史assistant.usage超 1M 窗口时首步前自动压缩并恢复maxOutputTokens的端到端测试,以及字符估算远小于窗口但多段历史usage超窗时的预裁剪测试。验证明细
pnpm vitest run packages/agent-core-v2/test/agent/tokenCounting/tokenCounting.test.ts packages/agent-core-v2/test/agent/fullCompaction/ packages/agent-core-v2/test/agent/llmRequester/llmRequester.test.ts packages/agent-core-v2/test/lint/import-boundaries.test.ts:6 files, 195 passed。pnpm vitest run packages/agent-core-v2/test/agent/loop/ packages/agent-core-v2/test/session/ packages/agent-core-v2/test/wire/ packages/agent-core-v2/test/app/config/configManifest.test.ts packages/kap-server/test/apiSurface.snapshot.test.ts:41 files, 567 passed。pnpm vitest run packages/agent-core-v2/test/state/ packages/agent-core-v2/test/agent/media/ packages/agent-core-v2/test/agent/toolSelect/ packages/agent-core-v2/test/agent/toolExecutor/toolExecutor.test.ts:全部通过。pnpm run typecheck:全仓 packages + CLI + VS Code + vis-server + vis-web 0 errors。pnpm run lint(oxlint --type-aware)+pnpm run sherif+lint:imports:0 errors(变更文件 0 warnings / 0 errors)。pnpm run build && pnpm -C apps/kimi-code run smoke:通过。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.Requested by qer via Mira.