Skip to content

fix(agent-core-v2): keep token counting and compaction anchored to usage - #4883

Merged
sailist merged 1 commit into
mainfrom
fix/token-counting-and-compaction-usage-anchor
Nov 13, 2026
Merged

sailist merged 1 commit into
mainfrom
fix/token-counting-and-compaction-usage-anchor

Conversation

@kimi-agent-bot

Copy link
Copy Markdown
Collaborator

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

  1. 在大窗口模型(例如 max_context_size = 1,000,000)会话早期执行一次带分页 note 的 Read(或带 isError、Wall time、空输出、ReadMediaFile 引用解析的工具调用)。
  2. 继续多轮对话直至上游真实输入 token 超过 1,000,000,而本地字符估算仍低于 850,000(1,000,000 * 0.85)。
  3. 发送新消息观察行为:修复前不会触发自动压缩,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)
Loading
  1. 工具消息双侧表示分离导致 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。
  2. AgentFullCompactionService 缺少历史真实 usage 锚点:
    • tokenCountWithPending() 仅读取 tokenCounting.get().size,未参考历史 assistant 消息已持久化的真实 usage;当存量会话缺少最新 token_counting.measured 记录且字符估算偏低时,无法在首步前触发自动压缩。
    • preShrinkHistoryToWindowBudget 与压缩请求预算同样只用本地字符估算(例如全量字符估算 74 万 < inputLimit 87.5 万),导致真实输入已超 100 万的存量会话在压缩阶段跳过预裁剪并超窗。

Code Changes

核心思路

保持 TokenCountingAgentModel 与 AgentLoopRequestObserver 在每一步稳定写入 token_counting.measured,同时让 AgentFullCompactionService 在判定自动压缩阈值与计算压缩预裁剪窗口预算时以历史 assistant 消息的真实 usage 作为下界锚点(与 core 请求侧 estimateUsedContextTokens 口径一致)。这样新会话每步都有精确锚点,已落盘的旧会话也能在下一条消息到来时立即自愈。

阅读指南

  1. packages/agent-core-v2/src/session/tokenCounting/tokenCountingAgentModel.ts:看 matchesToolMessage 如何对齐未渲染与经 renderToolResultForModel 渲染的工具消息。
  2. packages/agent-core-v2/src/agent/loop/requestObservation.ts:看未发生媒体降级恢复时如何向 tokenCounting.measured 传入 resolver 前的 request.messages。
  3. packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts:看 usageAnchoredRequestTokens 与 buildHistoryTokenProfile 如何驱动自动压缩触发和预裁剪预算。
  4. packages/agent-core-v2/test/agent/tokenCounting/tokenCounting.test.ts、packages/agent-core-v2/test/agent/fullCompaction/fullCompaction.test.ts:回归测试。

结构化变更大纲

 AgentLoopRequestObserver.completeRequest
   tokenCounting.measured(
-    recorded?.messages ?? request.messages.map(stripAttributes)
+    observation.media.previousMediaRecovery === undefined
+      ? request.messages
+      : (recorded?.messages ?? request.messages)
   )

 TokenCountingAgentModel.matchesContext
   for each (left, right)
+    if role === 'assistant': record call.id -> call.name
+    if role === 'tool':
+      verify toolCallId and explicit isError / note metadata do not conflict
+      accept unrendered ContextMessage / Loop history shapes (raw or note-appended)
+      accept renderToolResultForModel shapes (note, isError, optional Wall time, empty output)

 AgentFullCompactionService
   tokenCountWithPending()
-    return tokenCounting.get().size
+    return max(tokenCounting.get().size, usageAnchoredRequestTokens(history))

   compactionRound() / preShrinkHistoryToWindowBudget()
-    estimate input & per-message shrink budget purely via character heuristic
+    anchor total input and per-span message weights to historical assistant usage deltas
+    fall back to character estimates when usage is absent or smaller than char estimates

Behavior Changes and Affected Users

行为 修改前 修改后 依赖旧行为的人群 退路
含 note、isError、Wall time、空输出或正常媒体解析的工具调用后的 token_counting.measured 记录 matchesContext 返回 false,后续步骤停止写入 token_counting.measured,上下文大小退回本地字符估算 持续匹配并写入每步真实 token_counting.measured(发生 413/400 媒体降级/剥离重试的请求仍保持不写入未剥离上下文锚点) 全端长会话用户(TUI、print、desktop/web、VS Code、ACP、SDK):无合理依赖旧失配行为 无需(修复缺陷)
token_counting.measured 缺失或偏低但历史 assistant 消息带有真实 usage 时的自动压缩触发(tokenCountWithPending) 仅按 tokenCounting.get().size 判断,字符估算偏低时漏触发压缩并导致 maxOutputTokens 被压成 1 取 tokenCounting.get().size 与最新历史 assistant 真实 usage + 尾部估算的较大值,达阈值即在首步前自动压缩 旧版本写入的存量长会话用户、大窗口模型全端用户:无合理依赖旧卡死行为 无需(修复缺陷)
压缩请求预裁剪(preShrinkHistoryToWindowBudget)、压缩 usedContextTokens 与 tokensBefore 计算 仅按字符估算判断,真实 token 已超窗而字符估算未超 inputLimit 时不预裁剪 结合历史 assistant 真实 usage 锚点计算总输入与分段消息权重,超 inputLimit 时在首轮压缩请求前完成预裁剪并保留充足输出窗口;无 usage 或字符估算更高时保持原结果不变 全端触发自动压缩或手动 /compact 的用户 无需(修复缺陷)
  • 受影响模块:
    • packages/agent-core-v2/src/session/tokenCounting/tokenCountingAgentModel.ts
    • packages/agent-core-v2/src/agent/loop/requestObservation.ts
    • packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts
  • 契约检查:config-manifest.toml、wire-manifest.d.ts、state-manifest.d.ts、kap-server API 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

  • 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.

Requested by qer via Mira.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 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-12T16:52:50.148793Z b187334 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.

@changeset-bot

changeset-bot Bot commented Nov 12, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: b187334

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/kimi-code 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

@pkg-pr-new

pkg-pr-new Bot commented Nov 12, 2026

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

commit: b187334

@sailist
sailist merged commit 638c6ff into main Nov 13, 2026
17 checks passed
@sailist
sailist deleted the fix/token-counting-and-compaction-usage-anchor branch November 13, 2026 02:55
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.
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