[Bug] Auto-compaction trigger ignores the system prompt and tool schemas when the provider omits cached-token counts
What version of Kimi Code is running?
2.6.3 (source main snapshot, 2026-11-18). Confirmed by reading the code paths below and running packages/agent-core-v2/test/agent/tokenCounting/tokenCounting.test.ts (19 tests pass).
Which open platform/subscription were you using?
None involved (code-level audit).
Which model were you using?
Any provider whose streaming usage does not report cached prompt tokens (for example Gemini without context caching, or an OpenAI-compatible proxy that omits cached_tokens).
What platform is your computer?
Windows 11 x64.
What issue are you seeing?
For providers that do not report cached prompt tokens, automatic compaction is triggered from a count that includes only the conversation messages and silently omits the system prompt and tool schemas. Compaction therefore fires later than the configured threshold, and the real request can exceed the model window before compaction runs.
The chain:
packages/core/src/llm/usage.ts:13-16:inputTotal()returnsundefinedwheninputCacheRead === undefined, sograndTotal()is alsoundefined.packages/core/src/llm/builtin/protocol/openai/decode.ts:192-196: whencached_tokensis absent,inputCacheReadstaysundefined. Forgoogle-genai,decode.ts:155-160leaves itundefinedwhenevercachedContentTokenCountis absent (no explicit context caching).packages/agent-core-v2/src/session/tokenCounting/tokenCountingAgentModel.ts:110-118:measured()computesgrandTotal(usage)and returns early when it isundefined, so no measured anchor is ever recorded.packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts:287-295:usageAnchoredRequestTokens()also requiresgrandTotal(usage)and returnsundefinedfor every assistant message.fullCompactionService.ts:951-955: with both sources unavailable,tokenCountWithPending()falls back tothis.tokenCounting.get().size.
TokenCountingAgentModel.get() (tokenCountingAgentModel.ts:89-102) estimates readHistory() only. The system prompt and the tools[] block are not part of that array, so they are never counted by the fallback.
By contrast, requestTokens() / historyRequestTokens() (fullCompactionService.ts:281-303, used for tokensBefore and for validateCompactionStart) do include the system prompt and tools. So the trigger condition and the reported pre-compaction size are computed from different bases.
Concrete impact: with a 256K window and compaction_trigger_ratio = 0.85, a typical MCP tool set can add tens of thousands of tokens of schema. The gate sees messages only and compacts around 0.85 * 256K of messages, while the actual request is already beyond the model window. The turn then goes through the context-overflow recovery path (or fails), and the reported tokensBefore/context size under-reports.
What steps can reproduce the bug?
- Use a provider that does not return cached prompt tokens (e.g. Gemini without context caching, or an OpenAI-compatible proxy that omits
cached_tokens). - Configure a large tool set (many MCP tools) so the system prompt plus tool schemas are a significant fraction of the window.
- Run a multi-step tool session until the context approaches the window.
- Compare
tokenCounting.get().size/ the compaction trigger count withhistoryRequestTokens(history): the trigger count does not include the system prompt or tools. - Observe that compaction starts at the wrong threshold and that the real request can hit a provider context-overflow error first.
A unit-level observation is already pinned by packages/agent-core-v2/test/agent/tokenCounting/tokenCounting.test.ts:201-207: calling measured() with inputCacheRead: undefined leaves the anchor ledger empty. No test covers the downstream effect on the compaction gate.
What is the expected behavior?
When neither a measured anchor nor a usage-anchored count is available, the compaction trigger and block checks should fall back to a request-level estimate that includes the system prompt and tool schemas (the same basis as historyRequestTokens), instead of a message-only estimate.
Additional information
Suggested fix (does not require changing the conservative inputTotal semantics): in tokenCountWithPending(), when usageAnchored === undefined and no measured anchor covers the current length, return Math.max(counted, this.requestTokens(this.loopService.history())) or add this.requestTokens([]) (prompt + tools) to counted. A regression test could construct an agent with a large system prompt/tool list and assert that the auto-compaction threshold is crossed at the expected size for a provider that omits cached tokens.
Contribution
- [x] I am willing to submit a PR for this bug fix myself (please wait for maintainer approval in this issue first)
I confirmed the two counting bases with a temporary test against this snapshot, then reverted it:
const usageWithoutCache = { inputOther: 1234, output: 56, inputCacheCreation: 0 };
grandTotal(usageWithoutCache); // undefined
ctx.appendUserMessage([{ type: 'text', text: 'hello' }]);
const counted = ctx.tokenCounting.get().size; // 3
const withPrompt = ctx.tokenCounting.requestSize({
systemPrompt: ctx.get(IAgentLoopService).getSystemPrompt(),
tools: [],
messages: ctx.get(IAgentLoopService).history(),
}); // 12
expect(withPrompt).toBe(counted);
Observed:
GRAND_TOTAL_WITHOUT_CACHE undefined
TOKEN_BASES {"counted":3,"withPrompt":12,"promptTokens":9}
AssertionError: expected 12 to be 3
The test harness system prompt is tiny, so the absolute gap is small here. The point is qualitative: once both anchored sources return undefined, tokenCountWithPending() falls back to counted (messages only), while the compaction request is built from historyRequestTokens() (system prompt + tools + messages). In a real session the prompt and the tool schemas are thousands of tokens, so the trigger can cross 85% of the window only after the actual request has already exceeded it.
A realistic regression test would install a large system prompt and tool list, drive beforeStep with usage that omits cached_tokens, and assert that compaction triggers at the requestTokens(history) level rather than the estimateTokensForMessages(history) level. I will add that to the PR.
Live reproduction with a real provider (no mocks). I configured the google-genai protocol against a gateway's Google endpoint (model gemini-4-argon, 1M context) and ran the same one-line prompt through two providers in real sessions, then inspected each session's agents/main/wire.jsonl.
google-genai / Gemini session:
{"type":"usage.record","model":"opencode-go/gemini-4-argon","usage":{"inputOther":12950,"output":5,"inputCacheCreation":0},"usageScope":"turn"}
{"type":"token_counting.turn_recorded","turnId":0,"length":4,"tokens":197}
There is no token_counting.measured record. The provider reported 12,950 input tokens, but no inputCacheRead, so grandTotal() is undefined and measured() bails. The session therefore reports tokens: 197 for the same conversation.
anthropic / DeepSeek session, same prompt, for contrast:
{"type":"usage.record","model":"opencode-go/deepseek-v4.1-flash","usage":{"inputOther":13781,"output":2,"inputCacheRead":0,"inputCacheCreation":0},"usageScope":"turn"}
{"type":"token_counting.measured","length":4,"tokens":13783}
{"type":"token_counting.turn_recorded","turnId":0,"length":4,"tokens":13783}
inputCacheRead: 0 is enough to make grandTotal() defined, so measured accounting works.
The Gemini model has a 1,048,576-token context. The reported 197 tokens is the message-only estimate, and it is also the value tokenCountWithPending() feeds into shouldCompact / shouldBlock. On a real session this means auto-compaction sees roughly 1.5% of the true context and will not trigger until the provider rejects the request.
This also matches the provider's response shape: the Gemini generateContent response contains usageMetadata.promptTokenCount but no cachedContentTokenCount.
I am keeping the wire snippets as evidence and will add a regression test in the PR.