Skip to content

Context Management

Context Management is the key to sustaining long conversations. As conversations grow longer and tool outputs accumulate, the system intelligently manages the context window through a five-layer compression mechanism — retaining critical information, freeing up precious space, and keeping the conversation unbroken.

LayerNameTriggerCompression GranularityCost
0Manual CompactUser sends /compact commandFull → summaryOne LLM call
1MicrocompactTime intervalSingle tool resultZero
2Auto CompactToken count reaches thresholdA batch of messages → summaryOne LLM call
3Reactive CompactStill over limit after Auto CompactProgressive multi-level compressionZero ~ one LLM
4Session Memory CompactWhen Auto Compact is triggeredSession memory → summaryZero

Users can trigger context compression manually via the /compact command, useful for proactively cleaning context or adjusting summary direction.

RPC: v1.session.compact

{
"session_id": "uuid",
"custom_instruction": "Focus on retaining API design decisions and code snippets"
}
ParameterDescription
session_idTarget session ID
custom_instructionOptional, custom summary instruction overriding the default compression prompt

💡 Manual compression uses force mode, bypassing the token threshold check — compression is performed even if the context is not over the limit. The compression LLM call disables thinking/reasoning to save tokens.

Microcompact is the lightest form of compression — it doesn’t generate summaries, it simply cleans up old tool results that take up a lot of space.

Only tools that produce large outputs are cleaned:

ToolTypical Output
📖 readFile contents
✏️ writeWrite results
🔍 grepSearch results
🔎 findFile listings
⚡ scriptScript execution results
StrategyTriggerMechanism
🕐 Time-basedLast assistant message > 60 minutes agoDirectly replace old tool results with placeholders, keep most recent 5

💡 The time-based strategy retains at least 5 recent tool results to prevent the model from completely losing its working context.

Auto Compact — Automatic Summary Compression

Section titled “Auto Compact — Automatic Summary Compression”

When microcompact isn’t enough, Auto Compact kicks in — compressing a batch of old messages into a concise summary.

ConfigurationDefaultDescription
contextTokensLimit25,000Context token limit
autoCompactBufferTokens13,000Safety buffer
Trigger threshold12,000contextTokensLimit - autoCompactBufferTokens

Auto Compact uses a 9-part structured prompt to ensure the summary covers all critical dimensions:

#SectionContent
1Primary Request and IntentThe user’s core request and intent
2Key Technical ConceptsKey technical concepts involved
3Files and Code SectionsRelevant files and code snippets (including full code)
4Errors and FixesErrors encountered and their fixes
5Problem SolvingProblem-solving process
6All User MessagesAll user messages (excluding tool results)
7Pending TasksTasks awaiting completion
8Current WorkWhat is currently being worked on
9Optional Next StepOptional next action

Compression doesn’t discard all old messages — it retains recent messages:

ConfigurationValueDescription
minTokens10,000Minimum tokens to retain
minTextBlockMessages5Minimum messages with text blocks to retain
maxTokens40,000Maximum tokens to retain

📌 API invariant protection: tool_result entries in retained messages must have corresponding tool_use entries. During compression, the retention range is extended backwards to ensure pairs remain complete.

When Memory System has Session Memory entries, compression can be completed at zero cost:

This is exactly the convergence point of the memory system and context management — Session Memory, continuously accumulated during the conversation, becomes a high-quality summary at compression time without requiring an additional LLM call.

Reactive Compact — Progressive Emergency Compression

Section titled “Reactive Compact — Progressive Emergency Compression”

When tokens are still over the limit after Auto Compact, the system activates Reactive Compact — a progressive multi-level compression strategy that frees up as much space as possible without increasing LLM cost.

LevelStrategyDescription
Level 1Light compressionMore aggressive tool result cleanup + reduced message retention
Level 2Medium compressionFurther message trimming + shorter attachment injection
Level 3Aggressive compressionAggressive microcompact + minimal retention configuration

💡 Reactive Compact persists across process restarts — even after a Server restart, the system detects the current token state and continues executing the required compression level.

Individual tool outputs are limited to 10K tokens to prevent any single tool result from monopolizing the context window:

StrategyRatioDescription
Head retention60%Keep the first 6,000 tokens of the output
Tail retention20%Keep the last 2,000 tokens of the output
Middle truncation20%Middle section replaced with [...truncated...]

Truncation uses a UTF-8 safe algorithm to ensure no character is split in the middle.

Cache breakpoints are set at key positions in the message list so that the LLM’s prompt cache maintains a high hit rate even after compression:

BreakpointPositionTTLDescription
BP1After summary message1hCompressed summaries rarely change, long TTL
BP2After recent messages5mActive area, short TTL for freshness
EffectData
Cache hit rate0% → 75% (after microcompact)
Input cost reduction~69%

💡 Configurable via worker.enable_strategic_cache_breakpoints (default true). This feature works with Anthropic’s prompt caching mechanism to reuse previous caches even after context compression.

After compression, the system automatically re-injects recently read files to help the model quickly return to its working state:

ConfigurationValueDescription
Max files to recover5The 5 most recently read files
Total token budget10,000Total limit for all recovered files
Per-file token limit2,000Maximum tokens per file

The system prompt is provided via the SystemPrompt configuration item and passed as the Agent’s Instruction. When an agent definition exists, the agent’s system prompt is used; otherwise, the default system prompt is used.

Before each API call, messages go through a complete assembly pipeline:

The attachment system dynamically injects contextual information during conversations:

Attachment TypeInjection TimingDescription
📋 AgentPromptEvery turnAGENT.md snapshot, containing agent capability description
📝 TodoListEvery turnPending task list
🧠 SessionMemoryEvery turnLatest 5 session memories (up to 5,000 tokens)
🗂️ UserMemoryEvery turnUser memories filtered by importance
📎 File AttachmentsEvery turnFiles uploaded by the user with the message (images and text)

💡 File attachments: Images are injected via MultiContent (vision channel); text files are XML-wrapped and appended to Content. Token consumption depends on file type — images consume tokens based on resolution, while text files consume tokens based on character count.

The following Session model fields reflect compression status in real-time, displayed by the frontend via the rtc-token-usage component:

FieldDescriptionCalculation
compression_progressCompression progress (0-100)current tokens / compression_threshold * 100
compression_thresholdCompression trigger thresholdcontextTokensLimit - autoCompactBufferTokens
rounds_until_compressionRounds until compressionEWMA-based prediction, -1 means threshold exceeded
estimated_next_round_tokensNext round token estimateBased on EWMA (Exponentially Weighted Moving Average)
Progress RangeMeaningUser Guidance
0-50%Context is ampleNormal usage
50-80%Context gradually fillingContinue conversation, monitor progress
80-100%Compression approachingPrepare for compression
> 100%Threshold exceeded, compression triggeredrounds_until_compression becomes -1

💡 rounds_until_compression is estimated using the EWMA (Exponentially Weighted Moving Average) algorithm, which considers historical token consumption trends across rounds. The prediction becomes more accurate as conversation rounds increase.