Context Management¶
PatchPal automatically manages the context window to prevent "input too long" errors during long coding sessions.
Overview¶
- Automatic token tracking: Monitors context usage in real-time
- Smart pruning: Removes old tool outputs (keeps last 40k tokens) before resorting to full compaction
- Auto-compaction: Summarizes conversation history when approaching 80% capacity
- Manual control: Check status with
/status, compact with/compact, prune with/prune
How It Works¶
- Phase 1 - Pruning: When context fills up, old tool outputs are pruned first
- Keeps last 40k tokens of tool outputs protected (only tool outputs, not conversation)
- Only prunes if it saves >20k tokens
- Pruning is transparent and fast
-
Requires at least 5 messages in history
-
Phase 2 - Compaction: If pruning isn't enough, full compaction occurs
- Requires at least 5 messages to be effective
- LLM summarizes the entire conversation
- Summary replaces old messages, keeping last 2 complete conversation turns
- Work continues seamlessly from the summary
- Preserves complete tool call/result pairs (important for Bedrock compatibility)
Example¶
======================================================================
Context Window Status
======================================================================
Model: anthropic/claude-sonnet-4-5
Context limit: 200,000 tokens (model default)
Messages in history: 47
System prompt: 735 tokens
Tools: 5,877 tokens (estimated)
Conversation: 121,388 tokens
Output reserve: 32,000 tokens
Total: 160,000 tokens
Usage: 80%
[████████████████████████████████████████░░░░░░░░░]
Auto-compaction: Enabled (triggers at 80%)
======================================================================
The system ensures you can work for extended periods without hitting context limits.
Commands¶
# Check context window usage
You: /status
# Output shows:
# - Messages in history
# - Token usage breakdown
# - Visual progress bar
# - Auto-compaction status
# - Session statistics:
# - Total LLM calls made
# - Cumulative input tokens (all requests combined)
# - Cumulative output tokens (all responses combined)
# - Total tokens (helps estimate API costs)
# Manually trigger compaction
You: /compact
# Useful when:
# - You want to free up context space before a large operation
# - Testing compaction behavior
# - Context is getting full but hasn't auto-compacted yet
# Note: Requires at least 5 messages; most effective when context >50% full
# Manually prune old tool outputs
You: /prune
# Useful when:
# - Large tool outputs (e.g., from grep, file reads) are filling context
# - You want to reclaim space without full compaction
# - Testing pruning behavior
# Note: Keeps last 2 conversational turns; prunes all older tool outputs
Session Statistics¶
The /status command shows cumulative token usage:
- Cumulative input tokens: Total tokens sent to the LLM across all calls
- Each LLM call resends the entire conversation history
-
Note on Anthropic models: PatchPal uses prompt caching
- System prompt and last 2 messages are cached
- Cached tokens cost much less than regular input tokens
- The displayed token counts show raw totals, not cache-adjusted costs
-
Cumulative output tokens: Total tokens generated by the LLM
- Usually much smaller than input (just the generated responses)
- Typically costs more per token than input
Important: The token counts shown are raw totals and don't reflect prompt caching discounts. For accurate cost information, check your provider's usage dashboard which shows cache hits and actual billing.
Configuration¶
See the Configuration section for context management settings including:
- PATCHPAL_DISABLE_AUTOCOMPACT - Disable auto-compaction
- PATCHPAL_COMPACT_THRESHOLD - Adjust compaction threshold
- PATCHPAL_CONTEXT_LIMIT - Override context limit (for testing, or to match a local server's window size; see Small Context Windows)
- PATCHPAL_PROACTIVE_PRUNING - Prune tool outputs proactively after calls (default: true, uses smart summarization)
- PATCHPAL_PRUNE_PROTECT / PATCHPAL_PRUNE_MINIMUM - Pruning controls
Testing Context Management¶
You can test the context management system with a small context limit to trigger compaction quickly. Since 64K or less selects TinyAgent, a small test limit exercises handoff compaction:
# Set up a small context window for testing
export PATCHPAL_CONTEXT_LIMIT=32768 # Force a 32K limit (selects TinyAgent)
export PATCHPAL_COMPACT_THRESHOLD=0.80 # Trigger at 80% (default, but shown for clarity)
patchpal --model ollama_chat/gemma4:e4b
# 🔧 Tiny agent (context window 32,768 ≤ 65,536): handoff compaction, selective reading
# Tools: read_file, read_lines, edit_file, write_file, web_search, web_fetch, run_shell
A fresh session already uses about 23% of the window before any conversation:
You: /status
⚠️ Context limit overridden: 32,768 tokens (PATCHPAL_CONTEXT_LIMIT=32768)
Messages in history: 0
System prompt: 1,115 tokens
Tools: 1,374 tokens (estimated)
Conversation: 0 tokens
Output reserve: 5,242 tokens
Total: 7,731 tokens
Usage: 23%
That leaves about 18,000 tokens of conversation before compaction triggers at 80%. Generate context with tool calls (tool outputs consume tokens):
You: read patchpal/context.py in full
You: read patchpal/agent/tiny.py in full
# When the context fills up, you should see something like:
# ⚠️ Context window at 83% capacity. Compacting (handoff)...
# Current: 27,300 / 32,768 tokens (system: 1,115, tools: 1,374, messages: 19,569, output reserve: 5,242)
# Generating handoff note...
# ✓ Compaction complete. Saved 17,060 tokens (83% → 31%)
# Full history saved to ~/.patchpal/repos/<repo>/history/handoff_<timestamp>.md
To test the standard agent's pruning and summary compaction instead, add PATCHPAL_TINY_MODE=false. The full tool set is about 5,900 tokens, so at 32K a fresh session starts at roughly 36%, leaving less room for conversation. PATCHPAL_PRUNE_PROTECT and PATCHPAL_PRUNE_MINIMUM (e.g., 500 and 100) make pruning trigger sooner in this mode.
Small Context Windows (TinyAgent)¶
Models with small context windows (64K tokens or less, e.g. many local models) use TinyAgent, a version of the standard agent built for small windows. Instead of trying to fit everything in the context, it compacts often into a short handoff note and reads only the parts of files it needs.
When it is used:
- Automatically, when the model's context limit is at or below
PATCHPAL_SMALL_CONTEXT_THRESHOLD(default: 65,536 tokens; set to0to disable) PATCHPAL_TINY_MODE=trueforces it on andPATCHPAL_TINY_MODE=falseforces it off, whatever the context size
Local models
PatchPal detects context limits from the model name, not from the server, so it can't see OLLAMA_CONTEXT_LENGTH or vLLM's --max-model-len. Most local models (Qwen, Llama, GLM, etc.) are detected as 128K or more. Set PATCHPAL_CONTEXT_LIMIT to the window size you're actually serving (e.g., export PATCHPAL_CONTEXT_LIMIT=32768 to match OLLAMA_CONTEXT_LENGTH=32768). That makes compaction trigger at the right point and selects TinyAgent for windows of 64K or less.
Choose a window that still shows 100% GPU in ollama ps. Some models' memory grows quickly with the window (Qwen3.5 4B spills to the CPU above about 32K on a 6GB GPU), and even models that fit a long window generate much more slowly once it fills.
What it does differently:
- Fewer tools by default: Only
read_file,read_lines,edit_file,write_file, andrun_shellare enabled (plusweb_search/web_fetchif web access is enabled), because full tool descriptions alone can fill much of a small window.PATCHPAL_ENABLED_TOOLSorenabled_toolsoverrides this. - Tool output capped to the window: One tool result can be at most about 15% of the context window (minimum 2,000 characters). When a file read is truncated, the result says which line it stopped at and gives the
read_linescall to continue from there. - Selective reading prompt: The system prompt tells the model to find the right lines first (with
grep,wc -l, orheadviarun_shell) and then read small ranges withread_lines. It also says not to dump whole files or re-read ranges it has already seen, and to summarize or ask for focus when a request needs more than fits. -
Handoff compaction: When the context fills up, the agent does not keep a summary plus the last turns. It replaces the whole conversation with:
- Project memory (
MEMORY.md) - The current request (marked as already in progress) plus a structured handoff note written by the LLM (capped at about 10% of the window)
- The last assistant reply, if the turn just ended (so a follow-up like "yes" still makes sense)
The full pre-compaction history is saved to
~/.patchpal/repos/<repo>/history/handoff_<timestamp>.md, so the agent can find details later withgreporread_lines. Only the newest 100handoff_*.mdfiles are kept; older ones are deleted automatically.If the handoff note can't be created, PatchPal falls back to pruning tool outputs and suggests running
/clear. If the result wouldn't be smaller than the current history, PatchPal prints "Handoff note isn't smaller than the history - keeping history" and leaves the conversation unchanged.If a turn needs more than
PATCHPAL_MAX_HANDOFFS_PER_TURNcompactions (default: 5), the agent stops and suggests a narrower request. This usually means the request can't fit in the window (e.g., reading a large file in full). Reply "continue" to keep going. - Project memory (
Python API:
from patchpal.agent import create_tiny_agent
agent = create_tiny_agent(model_id="ollama_chat/qwen3:8b")
response = agent.run("Fix the failing test in tests/test_utils.py")
Background: TinyAgent is based on You don't need long context (Belcak et al., 2026), which found that frequent compaction to a structured handoff note, combined with selective reading of long inputs, preserves task accuracy with little to no loss in 8K–48K context windows. TinyAgent's handoff prompt is adapted from the paper's Appendix G, and its selective-reading guidance from Appendix E.