Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
docs(orchestration): guide repeated agent wakes with CCR (#1871)
Rod Boev800ad31ab6ee
diff --git a/docs/content/docs/agent-orchestration.mdx b/docs/content/docs/agent-orchestration.mdxnew file mode 100644index 000000000..037cbe4a4--- /dev/null+++ b/docs/content/docs/agent-orchestration.mdx@@ -0,0 +1,125 @@+---+title: Agent Orchestration+description: Keep repeated agent wakes cache-friendly while using CCR for lossless memory digest retrieval.+---++Repeated agent wakes usually rebuild the same expensive prompt shape. The useful split is simple: keep the byte-stable prefix first, keep the volatile wake-specific digest later, and keep run-specific context at the end so the repeated prefix stays cacheable.++## Repeated wake anatomy++Each wake tends to carry four different layers:++- stable instructions, project rules, and tool contracts+- the current task and other instruction-bearing fields+- the volatile per-wake memory digest+- recent loop state, tool output, and child-agent context++The stable layers should stay byte-identical across wakes. The volatile layers should move to the live zone, where they can change without invalidating the cacheable prefix.++## CacheAligner is detector-only++CacheAligner does not rewrite messages. It inspects the prefix, emits warnings for volatile content, and records observability data so callers can fix their own assembly logic.++The detector reports:++| Field | What it tells you |+|---|---|+| `warnings` | Which parts of the prefix look unstable |+| `cache_metrics.stable_prefix_bytes` | Size of the stable prefix in bytes |+| `cache_metrics.stable_prefix_tokens_est` | Estimated token size of the stable prefix |+| `cache_metrics.stable_prefix_hash` | Hash of the stable prefix for repeated-wake comparison |+| `cache_metrics.prefix_changed` | Whether the stable prefix drifted since the last wake |+| `cache_metrics.previous_hash` | Hash from the previous wake, when available |+| `markers` | The emitted `stable_prefix_hash` marker for downstream observability |++If CacheAligner warns about drift, keep the prefix stable in the caller. The transform is a detector, not a repair pass.++## Stable prefix layout++Put the byte-stable prefix first, then the live wake digest, then any run-specific context.++That layout keeps the provider cache path predictable:++1. Stable instructions stay identical.+2. The wake digest changes without disturbing the cacheable prefix.+3. Recent tool output and child-agent context stay outside the repeatable prefix.++## Real wake measurements++Use the issue comment guidance when measuring real wakes:++| Field | Record |+|---|---|+| Prompt section id | Name the section that changed or repeated |+| Byte/token estimate | Capture the section size before and after curation |+| Digest version | Track which digest schema was used |+| Cache-hit expectation | Note whether the section should stay cacheable |+| Compressed size | Record the compacted payload size |+| Section type | Mark the section as instruction-bearing or safe to compress |++That checklist helps separate the repeated prefix from the volatile digest before you decide where CCR belongs.++## CCR digest curation++CCR keeps compression reversible. The compressed digest can stay compact while the original backing detail remains recoverable from the local store.++The pieces that matter here are:++- `headroom_retrieve` for on-demand recovery of stored originals+- `HEADROOM_CCR_TTL_SECONDS` for sizing the local store lifetime+- `compression_strategy` as the authoritative discriminator on stored CCR entries++For routing decisions, the same rule in plain terms is: headroom_retrieve recovers originals, HEADROOM_CCR_TTL_SECONDS sizes the local lifetime, compression_strategy identifies the producing path, and shape inference is not the routing authority.++When a stored original expires, regenerate the digest or re-read the source content. Do not infer routing from payload shape. Use the stored `compression_strategy` metadata to understand how the original was produced.++## Digest routing++Route fields by how much exact wording they need at wake time.++| Field | Suggested handling | Why |+|---|---|---|+| Current task | Verbatim | It is instruction-bearing and changes the next action |+| Hard constraints | Verbatim | These are safety and acceptance boundaries |+| Definitions of done | Verbatim | The wording needs to survive every wake intact |+| Irreversible decisions | Verbatim summary plus retrievable backing detail | The summary stays short, the backing detail stays exact |+| Open threads | Compact summary plus CCR-backed backing detail | The live thread can shrink while the source stays recoverable |+| Learnings | Compact summary | They inform the next wake without needing exact prose |+| File/search/tool outputs | CCR-backed compression | These are large backing details that should stay retrievable |+| Prose notes | Compact summary, CCR-backed when bulky | Keep the digest readable without losing source detail |+| Bulk JSON-ish arrays | SmartCrusher or ContentRouter, with CCR-backed backing detail when needed | Structured blobs are usually the first thing to explode in size |++The important boundary is simple: instruction-bearing fields stay verbatim, or they get a verbatim compact summary plus retrievable backing detail. CCR-backed content is the backing detail, not the instruction itself.++Hard constraints stay verbatim; current task text stays verbatim; file/search/tool outputs use CCR-backed backing detail when they are large enough to compress.++## Integration modes++Choose the integration mode by where the orchestrator controls message assembly.++| Mode | Use when | Notes |+|---|---|---|+| Proxy | You want spawned agents and normal client traffic to pass through a local provider endpoint | Good for `headroom proxy --mode cache` and provider base URL routing |+| Library | The orchestrator owns message assembly and wants to shape the digest before launch | Best when the caller can decide what becomes stable prefix versus live digest |+| MCP | Agents need on-demand compression and retrieval tools | Best when `headroom_retrieve` should be available as a tool |+| Proxy plus MCP | You need traffic shaping and tool-level retrieval together | Useful when both the provider edge and the agent toolset matter |++## Local-first deployment++Keep the deployment local to the user or session:++- run one local proxy or MCP process per user session+- do not assume a central proxy+- treat the local CCR store as process-local unless the deployment explicitly shares it+- size the TTL for the longest realistic autonomous run+- assume a store can expire before the run finishes, then regenerate or re-read the source content++That model keeps the data boundary obvious. The orchestrator can still recover backing detail, but the cacheable prefix stays small and stable.++## Source-backed caveats++- Prompt-cache hits require a byte-identical stable prefix.+- CacheAligner identifies drift, it does not repair prompt assembly.+- CCR retrieval depends on store lifetime and stored hashes.+- Provider-neutral guidance still applies, so keep the guide away from Orcha-specific runtime claims.+- Use `compression_strategy` to read stored CCR intent, not payload shape.diff --git a/docs/content/docs/architecture.mdx b/docs/content/docs/architecture.mdxindex 1c86bfaed..5a903b09d 100644--- a/docs/content/docs/architecture.mdx+++ b/docs/content/docs/architecture.mdx@@ -47,15 +47,16 @@ Messages flow through a sequence of transforms. Each transform is independent, s### Stage 1: Cache Aligner-Extracts dynamic content (dates, UUIDs, session tokens) from your system prompt and moves it to the end. This stabilizes the prefix so provider caches (Anthropic `cache_control`, OpenAI prefix caching) can hit on repeated calls.+Detects dynamic content (dates, UUIDs, session tokens) in your system prompt and reports prefix metrics. Keep the stable prefix and live context separated in the caller so provider caches (Anthropic `cache_control`, OpenAI prefix caching) can hit on repeated calls.```-Before: "You are helpful. Current Date: 2024-12-15"- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- Changes daily = cache miss every day+Observed: "You are helpful. Current Date: 2024-12-15"+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+ Changes daily = cache miss every day-After: "You are helpful." [stable prefix]- "[Context: Current Date: 2024-12-15]" [dynamic tail]+Caller layout:+ "You are helpful." [stable prefix]+ "[Context: Current Date: 2024-12-15]" [live context]```Overhead: sub-millisecond.@@ -108,12 +109,12 @@ After the pipeline, Headroom applies provider-specific cache hints:## CCR: Compress-Cache-Retrieve-When SmartCrusher compresses a tool output or Intelligent Context drops messages, the original content is stored in a local compression cache. If the LLM needs the full data, it can request retrieval via a `ccr_retrieve` tool call. This makes compression reversible.+When SmartCrusher compresses a tool output or Intelligent Context drops messages, the original content is stored in a local compression cache. If the LLM needs the full data, it can request retrieval via a `headroom_retrieve` tool call. This makes compression reversible.```Compress: 1000 items -> 15 items (stored original in CCR)Cache: Hash-indexed local store (SQLite)-Retrieve: LLM calls ccr_retrieve("abc123") -> original 1000 items+Retrieve: LLM calls headroom_retrieve("abc123") -> original 1000 items```## TOIN: Tool Output Intelligence Network@@ -125,7 +126,7 @@ Cold start: For new tool types, TOIN falls back to statistical heuristics. Patte## What Headroom Does NOT Touch- **User messages**: Never compressed (the user's intent must be preserved exactly)-- **System prompts**: Content preserved; only dynamic parts are relocated for caching+- **System prompts**: Content preserved; dynamic parts are reported so callers can keep them outside the stable prefix- **Code**: Passes through unchanged unless tree-sitter AST compression is explicitly enabled- **Model responses**: Returned unchanged from the provider- **Short content**: Tool outputs under 200 tokens pass through (overhead exceeds savings)diff --git a/docs/content/docs/cache-optimization.mdx b/docs/content/docs/cache-optimization.mdxindex 33c41e586..3f9f199d0 100644--- a/docs/content/docs/cache-optimization.mdx+++ b/docs/content/docs/cache-optimization.mdx@@ -3,24 +3,24 @@ title: Cache Optimizationdescription: Stabilize message prefixes for provider KV cache hits and configure provider-specific caching strategies.----LLM providers cache prompt prefixes to avoid reprocessing identical input on repeated calls. Headroom's **CacheAligner** stabilizes your message prefixes so these caches actually hit, and then applies provider-specific strategies to maximize savings.+LLM providers cache prompt prefixes to avoid reprocessing identical input on repeated calls. Headroom's **CacheAligner** is detector-only, so it surfaces prefix drift, reports observability data, and leaves message assembly to the caller.-## How CacheAligner works+## What CacheAligner reports-System prompts often contain dynamic content -- today's date, session IDs, timestamps -- that changes between requests. Even a single character difference at the start of a prompt invalidates the entire provider cache.+System prompts often contain dynamic content, such as dates, session IDs, and timestamps, that changes between requests. Even a single character difference at the start of a prompt invalidates the entire provider cache.-CacheAligner solves this by extracting dynamic content and moving it to the end of the message, keeping the prefix stable:+CacheAligner does not extract, move, normalize, reorder, strip, compress, or rewrite content. It detects volatile content and reports the stable prefix hash plus cache metrics so you can fix the prefix at the source:-```-Before:- "You are helpful. Current Date: 2025-04-06" <- changes daily, no cache hit--After:- "You are helpful." <- stable prefix, cache hit- "[Context: Current Date: 2025-04-06]" <- dynamic part moved to tail-```+| Signal | Meaning |+|---|---|+| `warnings` | The prefix contains unstable content |+| `cache_metrics.stable_prefix_bytes` | Stable prefix size in bytes |+| `cache_metrics.stable_prefix_tokens_est` | Stable prefix size in estimated tokens |+| `cache_metrics.stable_prefix_hash` | Stable prefix hash for repeated-wake comparison |+| `cache_metrics.prefix_changed` | The prefix drifted since the previous wake |+| `markers` | The emitted `stable_prefix_hash` marker for observability |-The prefix stays byte-identical across requests, so the provider's KV cache can reuse previously computed attention states.+The prefix must stay byte-identical across requests for provider KV caches to reuse previously computed attention states.## Provider-specific strategies@@ -30,7 +30,7 @@ Each LLM provider implements caching differently. Headroom applies the optimal sAnthropic supports explicit `cache_control` blocks that mark content as cacheable. Cached input tokens cost **90% less** than regular input tokens.-Headroom automatically inserts `cache_control` breakpoints at the right positions in your messages so that stable prefixes (system prompts, early conversation turns) are cached across requests.+Keep the stable prefix byte-identical, then place provider cache markers where your client or orchestrator already assembles the request. Headroom's job is to surface prefix instability, not repair it.| Metric | Value ||---|---|@@ -40,9 +40,9 @@ Headroom automatically inserts `cache_control` breakpoints at the right position### OpenAI-OpenAI uses automatic **prefix caching** -- if consecutive requests share the same message prefix, the provider reuses cached KV states. No explicit API markers are needed, but the prefix must be byte-identical.+OpenAI uses automatic **prefix caching**. If consecutive requests share the same message prefix, the provider reuses cached KV states. No explicit API markers are needed, but the prefix must be byte-identical.-CacheAligner ensures your prefixes remain stable by extracting dynamic content, which is the key requirement for OpenAI prefix caching to work.+CacheAligner tells you when the prefix changed, which is the only signal you need to keep OpenAI prefix caching effective.| Metric | Value ||---|---|@@ -54,7 +54,7 @@ CacheAligner ensures your prefixes remain stable by extracting dynamic content,Google provides the **CachedContent API**, which lets you explicitly cache large context (system instructions, documents, tools) and reference it across requests. Cached tokens cost **75% less**.-Headroom can manage CachedContent lifecycle automatically, creating and refreshing cached content objects as needed.+Keep the prefix stable in your integration layer; Headroom reports when the cacheable zone drifts. The CachedContent lifecycle itself also stays in your integration layer.| Metric | Value ||---|---|@@ -62,102 +62,8 @@ Headroom can manage CachedContent lifecycle automatically, creating and refreshi| Mechanism | Explicit CachedContent API objects || Min cache size | 32,768 tokens |-## Configuration--<Tabs groupId="lang" items={['TypeScript', 'Python']}>-<Tab value="TypeScript">-```ts twoslash-import { compress } from "headroom-ai";-import type {- CacheAlignerConfig,- CacheOptimizerConfig,- HeadroomConfig,-} from "headroom-ai";--// CacheAligner: stabilize prefixes for cache hits-const cacheAligner: CacheAlignerConfig = {- enabled: true,- datePatterns: [- "Today is \\w+ \\d+, \\d{4}",- "Current time: .*",- ],- normalizeWhitespace: true,- collapseBlankLines: true,-};--// CacheOptimizer: provider-level caching-const cacheOptimizer: CacheOptimizerConfig = {- enabled: true,- autoDetectProvider: true, // Detect Anthropic/OpenAI/Google automatically- minCacheableTokens: 1024,-};--// Full configuration-const config: HeadroomConfig = {- cacheAligner,- cacheOptimizer,-};--// Compress with cache optimization-const result = await compress(messages, {- model: "claude-sonnet-4-20250514",- config,-});-```-</Tab>-<Tab value="Python">-```python-from headroom import HeadroomClient, OpenAIProvider, AnthropicProvider, GoogleProvider-from headroom.transforms import CacheAlignerConfig-from openai import OpenAI--# CacheAligner configuration-aligner_config = CacheAlignerConfig(- enabled=True,- dynamic_patterns=[- r"Today is \w+ \d+, \d{4}",- r"Current time: .*",- r"Session ID: [a-f0-9-]+",- ],-)--# Provider-specific cache settings-# OpenAI: prefix caching (automatic, just keep prefixes stable)-client = HeadroomClient(- original_client=OpenAI(),- provider=OpenAIProvider(enable_prefix_caching=True),- enable_cache_optimizer=True,-)--# Anthropic: cache_control blocks (90% read discount)-from anthropic import Anthropic--client = HeadroomClient(- original_client=Anthropic(),- provider=AnthropicProvider(enable_cache_control=True),- enable_cache_optimizer=True,-)--# Google: CachedContent API (75% read discount)-client = HeadroomClient(- original_client=google_client,- provider=GoogleProvider(enable_context_caching=True),- enable_cache_optimizer=True,-)-```-</Tab>-</Tabs>--## How savings compound--CacheAligner and provider caching work together with Headroom's compression transforms:--1. **SmartCrusher** reduces token count by 70-90%-2. **CacheAligner** stabilizes prefixes so provider caches hit-3. **Provider caching** discounts the remaining input tokens by 50-90%--For example, with Anthropic:-- 100K input tokens compressed to 20K (80% savings from SmartCrusher)-- 18K of those 20K hit the cache (90% cache read discount)-- Effective cost: 2K full-price tokens + 18K at 10% = 3.8K equivalent tokens-- **Total savings: 96.2%** compared to the original 100K tokens+## What this means in practice++Keep the stable prefix first, keep volatile content out of it, and treat CacheAligner warnings as a signal that the caller needs to move assembly logic.++CacheAligner surfaces prefix instability, provider caches reward byte-identical prefixes, and the caller owns the actual message layout.diff --git a/docs/content/docs/how-compression-works.mdx b/docs/content/docs/how-compression-works.mdxindex 92e0ec557..aa1d23dea 100644--- a/docs/content/docs/how-compression-works.mdx+++ b/docs/content/docs/how-compression-works.mdx@@ -13,13 +13,13 @@ Every request flows through three stages:┌──────────────┐ ┌────────────────┐│ CacheAligner │────>│ ContentRouter ││ │ │ │-│ Stabilize │ │ Detect type & │-│ prefix for │ │ route to best │-│ cache hits │ │ compressor │+│ Report │ │ Detect type & │+│ prefix drift │ │ route to best │+│ for cache │ │ compressor │└──────────────┘ └────────────────┘```-1. **CacheAligner** extracts dynamic content (dates, user context) from your system prompt so the static prefix stays cacheable across requests.+1. **CacheAligner** detects dynamic content (dates, user context) in your system prompt and reports prefix drift so the caller can keep the static prefix cacheable across requests.2. **ContentRouter** inspects each tool output and routes it to the optimal compressor -- SmartCrusher for JSON arrays, CodeAwareCompressor for source code, LogCompressor for build output, and so on.## Content Type Detectiondiff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.jsonindex 6819047eb..567725068 100644--- a/docs/content/docs/meta.json+++ b/docs/content/docs/meta.json@@ -17,6 +17,7 @@"ccr","---Cache & Context---","cache-optimization",+ "agent-orchestration","context-management","---Memory---","memory",