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 three-layer compression mechanism — retaining critical information, freeing up precious space, and keeping the conversation unbroken.

LayerNameTriggerCompression GranularityCost
1MicrocompactTime intervalSingle tool resultZero
2Auto CompactToken count reaches thresholdA batch of messages → summaryOne LLM call
3Session Memory CompactWhen Auto Compact is triggeredSession memory → summaryZero

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.

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