Context Overflow 3-Tier Recovery Pattern
OpenClaw implements a sophisticated 3-tier recovery strategy for handling context overflow errors during agent execution.
Location
src/agents/pi-embedded-runner/run.ts:684-845
Constants
Recovery Tiers
Tier 1: Detection
Detects overflow errors from:
- Provider error responses
- SDK automatic compaction failures
- Token limit exceeded messages
Tier 2: Auto-Compaction
Maximum 3 attempts to compact the session:
Compaction Strategy:
- Calls
compactEmbeddedPiSessionDirect()withtrigger: "overflow" - Increments global attempt counter
- On success: retries the prompt
- On failure: proceeds to Tier 3
Tier 3: Tool Result Truncation
For sessions with oversized tool results:
Truncation Strategy:
- Identifies tool results exceeding a significant portion of context window
- Truncates oversized results while preserving metadata
- Does not reset
overflowCompactionAttempts(global cap remains enforced)
Tier 4: Abort with Error
If all recovery attempts fail:
User-Facing Message:
- Clear explanation of the issue
- Actionable suggestions:
/reset,/new, or larger model - Preserves error metadata for debugging
Diagnostic Logging
Each overflow event generates a diagnostic ID: