Skip to content

Context Window Compaction

Long conversations grow past the LLM’s context window. ContextWindowCompactionService auto-summarizes older messages to reclaim space while preserving conversational coherence.

Related: this is Layer 4 of Self-healing — the safety-net compaction that fires when other layers can’t prevent overflow.

graph TB A[Before each LLM call<br/>Estimate total tokens] --> B{Usage vs window?} B -->|< 80%| C[No action<br/>warningLevel: none] B -->|80–90%| D[Warning<br/>warningLevel: warning] B -->|> 90%| E[Auto-compact<br/>warningLevel: critical] E --> F[Run compaction pipeline]

Tried in order. First that fits wins.

TierNameStrategy
1Tool stripRemove large tool result content (> 200 chars) from older messages. No LLM call.
2Multi-chunkSplit older messages into chunks; summarize each via LLM; replace originals.
3PartialSummarize the oldest half of the conversation.
4Plain fallbackNo LLM available → plain-text conversation shape description.
  • 4 most recent messages — never summarized. Keeps latest request + most recent response intact.
  • System prompt — always preserved. Its tokens counted in the budget.
chunkTokens = min(contextWindow × 0.4, 12000)

Ratio decreases to a minimum of 0.15 for very large context windows. Each chunk includes structural wrapping (User:, Assistant:, Tool: labels). Individual messages capped at 10 000 chars before summarization.

Model familyWindow
Claude 3.5 / 4200 K
GPT-4o / mini128 K
o1200 K
Gemini 2.01.05 M
Gemini 1.5 Pro2.1 M
Llama 3.3 70B128 K
DeepSeek Chat64 K
Qwen Plus131 K
GLM-4 Plus128 K

Override with codebuddy.contextWindow setting ("4k", "8k", "16k", "32k", "128k").

Returned after compaction runs:

FieldMeaning
compactedWhether compaction was performed
originalCountMessages before
finalCountMessages after
originalTokensEstimated tokens before
finalTokensEstimated tokens after
tierWhich tier was used (0–4)
warningLevelnone / warning / critical
SettingDefaultPurpose
codebuddy.contextWindow"16k"Window cap: 4k, 8k, 16k, 32k, 128k
  • Self-healing §Layer 4 — where this sits in the safety layers
  • Chat history — auto-pruning that reduces the compaction burden