J12 · version 2.0
MYELIN: Budget Prompting for Persistent Memory Agents
Oscar Serra
An AI agent that runs all day with its own memory resends its whole context on every turn, so it can cost $50–200 a day on a metered API or use up a flat-rate plan's limits within hours. This paper describes Budget Prompting: 20 techniques that send work to cheaper models, keep the context small, cut needless output, spread work over time and use cheaper ways to pay. Thirteen run every day in TinkerClaw, a fork of OpenClaw, and cut the cost per turn 2–3×; seven more are designed, for a projected 3–5×. The central lesson is to keep the start of the prompt unchanged so the provider can serve it from its cache: in July the cache hit rate was 91.1%. Anthropic's Claude Code, seen through its leaked source, uses the same design. The evidence comes from one agent and one user, without a controlled study.
What you get from this paper
- A catalogue of 20 cost techniques for always-on agents, each with its saving, status and side effects.
- Why memory writes break the prompt cache, and how to lay out a prompt so they do not.
- A five-level scheme for cutting back as a rate-limited subscription fills up.
- How to measure cost per model call, and the gate bug that a per-turn total caused.
- Production figures from one agent, and what Claude Code's leaked source confirms.
Version 2.0 · 25 November 2026 · 15,810 words · 69 min read · 10 versions
Internal codename: MYELIN Keywords: budget prompting, token economics, persistent agents, prompt caching, context management, cost optimization, LLM billing, agent architecture
Open source: OpenClaw is available at https://github.com/openclaw/openclaw. TinkerClaw is a private fork implementing the Budget Prompting techniques described in this paper.
Abstract482 wordsSummaryKeeping a memory agent running around the clock is expensive: every turn resends the whole context as input, so one always-on agent can cost $50–200 a day at Anthropic's prices or use up a flat-rate plan's limits within hours. The paper presents Budget Prompting, 20 techniques in five groups (model routing, context economics, output economics, temporal amortization, billing arbitrage) that cut the cost per turn 2–3× in production and 3–5× once all are built, with no loss of intelligence or personality observed so far. Thirteen run daily in TinkerClaw, a fork of OpenClaw that has run a personal assistant since January 2026; seven are designed. Anthropic's own agent, Claude Code, whose source leaked, compacts context in the same three tiers the paper proposes.
show summary
Running a persistent memory agent around the clock is expensive. Every conversational turn reprocesses the entire accumulated context — system prompt, injected memories, conversation history, tool outputs — as fresh input tokens. For an agent with a 150K-token context window, each turn costs as much as a full document analysis, regardless of whether the user asked a complex question or the agent is responding to a silent heartbeat. At Anthropic's current pricing, a single always-on agent can consume $50–200/day in API costs alone, or exhaust a flat-rate subscription's rate limits within hours.
This paper presents Budget Prompting — a family of 20 techniques that together reduce the per-turn cost of persistent memory agents by 2–3× in production today (3–5× projected once the remaining designed techniques ship), with no degradation in agent intelligence or personality coherence that we have been able to observe. We organize these techniques into five categories: model routing (sending cheap work to cheap models), context economics (minimizing what enters the context window), output economics (minimizing what the model generates), temporal amortization (spreading expensive operations across many turns), and billing arbitrage (exploiting pricing structure discontinuities).
Thirteen of these techniques are implemented and in daily use in TinkerClaw, a fork of the OpenClaw agent framework running a personal assistant (Jarvis) 24/7 since January 2026. Seven are designed but not yet shipped, informed by analysis of the Hermes Agent architecture and our own continuous compaction research. We report real cost data, cache hit rates, and failure modes from three months of production operation.
We also draw on the March 2026 Claude Code source exposure — Anthropic shipped a 59.8 MB source map in @anthropic-ai/claude-code@2.1.88, exposing ~512,000 lines of TypeScript — examining the relevant compaction and budget code directly. The exposure is external validation: Anthropic's production agent independently arrived at the same three-tier compaction architecture MYELIN proposes, and ships several techniques (cache-pinned micro-compaction, forked-agent cache sharing, diminishing-returns budget tracking) that we had theorized but not confirmed at scale.
The biological metaphor is deliberate: myelin sheaths insulate nerve axons, enabling signals to propagate faster while consuming less energy. Budget Prompting insulates agent cognition from the cost of its own context, enabling persistent operation that would otherwise be financially unsustainable.
Contributions109 wordsSummaryThe paper offers five things: a taxonomy of 20 techniques in five categories, each with its status, expected savings and interactions; cost data from a real agent running around the clock; the prefix stabilization principle, which explains why prompt caching and memory writes pull against each other and how to resolve it; an evaluation framework with metrics for cache efficiency, context density and personality drift, computed from a per-call usage record; and an analysis of which techniques work well together and which conflict.
show summary
- A taxonomy of 20 Budget Prompting techniques, organized into five categories with implementation status, expected savings, and interaction effects.
- Production cost data from a real 24/7 agent deployment, including per-technique attribution where measurable.
- The prefix stabilization principle: a formalization of why prompt caching and memory writes are fundamentally in tension, and architectural patterns to resolve it.
- Evaluation framework for measuring cost reduction without quality degradation, including proposed metrics for cache efficiency, context density, and personality drift, all computed from a per-call usage record and a pre-call composition of the context.
- Composition analysis: how techniques interact, which combinations are synergistic, and which create conflicts.
1. Introduction — The Cost Problem Nobody Talks About662 wordsSummaryMost agent demos run for minutes; the overnight bill decides whether a persistent agent is viable. On Claude 3.5 Sonnet at $3 per million input tokens, an 80K-token context costs $0.24 a turn, $48 a day at 200 turns before any output. Flat-rate plans ($100–200 a month) trade this for rate limits that a large context uses up in hours; the paper's own agent, Jarvis, hit them daily in its first two weeks. The causes are structural: context only grows within a session, memory must be in every request, most turns need little of it, and caching breaks whenever memory changes. One faulty budget gate caused 29 needless compactions in seven days. The evidence is one agent and one user over three months.
show summary
Most agent demos run for minutes. Almost nobody publishes what happens when you leave the agent on overnight, and the overnight number is the one that decides whether a persistent agent is viable.
Consider the economics of a persistent agent built on Claude 3.5 Sonnet. The system prompt — personality, instructions, injected memories, tool definitions — occupies roughly 18K tokens. After a few conversational turns with tool use, the context window holds 40–80K tokens. Every new turn sends the entire context as input. At $3/MTok input, an 80K-token context costs $0.24 per turn. If the agent processes 200 turns per day (a modest load for a system handling cron jobs, user messages, and automated tasks), that's $48/day in input tokens alone — before counting output.
Flat-rate subscriptions (Anthropic's Max plan at $100–200/month) nominally solve the per-token problem but introduce rate limits: input tokens per minute (ITPM), requests per minute (RPM), and requests per day (RPD). A 150K context window hitting these limits can exhaust a day's budget in hours. The result is the same: the agent goes dark, waiting for rate limit resets, and the user experience degrades.
This is not a hypothetical. We have run a persistent memory agent (Jarvis, built on TinkerClaw/OpenClaw) continuously since January 2026. In the first two weeks of operation, we hit rate limits daily. The agent would go silent mid-afternoon, unable to process messages until the next rate limit window. Cron jobs that ran at night would consume tokens needed for interactive use during the day. A security scan that expanded context to 180K tokens would cascade into cache misses for hours afterward.
The problem is architectural, not incidental. Persistent memory agents are fundamentally at odds with per-token billing because:
- Context grows monotonically within a session. Every turn adds user message + assistant response + tool calls + tool results. Context only shrinks through explicit compaction or session restart.
- Memory injection is prefix-heavy. The agent's identity, memories, and instructions must be present in every request. This is the cost of persistence — the agent must re-read its own mind every time it thinks.
- Most turns don't need full context. A heartbeat check, a weather query, a "good morning" response — these don't require 150K tokens of context. But the billing model charges for them as if they do.
- Caching helps, but is fragile. Anthropic's prompt caching can reduce repeated prefix costs by 90%, but any change to the prefix — including memory writes the agent performs as part of normal operation — invalidates the cache.
Budget Prompting addresses each of these structural problems. It is not a single technique but a composition of 20 interlocking strategies that, together, transform persistent agent operation from financially ruinous to sustainable.
This is not only a theoretical risk. In one seven-day production window, a faulty budget gate initiated 29 compactions at a median of roughly 5.5% of the actual context window. Each attempt remained pending until a 540-second cap and was then discarded, although the compaction work itself took 19 ms. The failure was not expensive because summarization was computationally heavy; it was expensive because a false trigger disrupted a cache serving a large repeated prefix. A secondary analysis of the March 2026 Claude Code source exposure reported a much larger internal figure—roughly 250,000 wasted calls per day from autocompact failures—but that unverified figure is corroborating context, not evidence for our deployment.
1.1 Scope and Methodology92 wordsSummaryThe evidence comes from running one agent for one user over three months: production logs, cost data and operational lessons, but no ablation studies, significance tests or controlled comparisons. Measured numbers are given as such, estimates are labelled, and techniques that are designed but not built are marked. It is a single-deployment case study (N=1).
show summary
This paper describes a real system, not a controlled experiment. Our evidence comes from operating a single agent for a single user over three months. We have production logs, cost data, and hard-won operational lessons. We do not have ablation studies, statistical significance tests, or controlled comparisons against baseline systems.
Where we have numbers, we give them; where we estimate, we say so; where a technique is designed but unimplemented, we mark it. The paper documents the full taxonomy and architecture against production data from a longitudinal single-deployment case study (N=1).
2. Background — How LLM Billing Actually Works920 wordsSummaryThree ways of paying shape an always-on agent. Metered APIs charge per token, with output costing 3–5× more than input and cached input 10× less. Flat-rate plans ($100 or $200 a month) charge in rate limit instead: a 150K-token request uses 150× the limit of a 1K one, and only 30–50% of the nominal capacity is usable. Batch APIs cost 50% less and answer within minutes to 24 hours. Prompt caching is the biggest lever but strict: one changed token misses the cache, and a write costs 25% more than plain input. Since the agent's memory sits in its prompt, normal memory writes break its own cache. Claude Code's leaked source manages context in the same three tiers as this paper.
show summary
To understand Budget Prompting, you must understand the billing mechanics that make persistent agents expensive. This section covers the three billing models relevant to always-on agents and the caching mechanisms that create optimization opportunities.
2.1 Per-Token Billing (Metered APIs)177 wordsSummaryOn metered APIs you pay per input and per output token. Representative March 2026 prices per million tokens: Claude 3.5 Sonnet $3.00 in, $15.00 out and $0.30 for cached input; Claude 3.5 Haiku $0.80, $4.00 and $0.08; GPT-4o $2.50, $10.00 and $1.25; Claude 3.5 Opus $15.00, $75.00 and $1.50. Two things follow. Output costs 3–5× more than input, so needless output is expensive: 5,000 tokens of reasoning before a 50-token answer spend 99% of the output on work nobody sees. And cached input costs 10× less: caching a 15K-token system prompt saves $0.04 a turn, $8 a day at 200 turns.
show summary
The standard model: you pay per input token and per output token, at different rates. As of March 2026, representative pricing:
| Model | Input ($/MTok) | Output ($/MTok) | Cached Input ($/MTok) |
|---|---|---|---|
| Claude 3.5 Sonnet | $3.00 | $15.00 | $0.30 |
| Claude 3.5 Haiku | $0.80 | $4.00 | $0.08 |
| GPT-4o | $2.50 | $10.00 | $1.25 |
| Claude 3.5 Opus | $15.00 | $75.00 | $1.50 |
Two critical observations:
Output tokens cost 3–5× more than input tokens. This means generating unnecessary output (verbose responses, extended thinking chains, redundant explanations) is disproportionately expensive. A model that generates 5,000 tokens of chain-of-thought reasoning before producing a 50-token answer has spent 99% of its output budget on invisible work.
Cached input tokens cost 10× less than uncached. Anthropic's prompt caching stores the computed key-value (KV) representations of prompt prefixes. If the prefix hasn't changed since the last request, those tokens are served from cache at 1/10th the price. For a 15K-token system prompt, caching saves $0.04 per turn — which compounds to $8/day at 200 turns.
2.2 Flat-Rate Subscriptions (Rate-Limited)141 wordsSummaryAnthropic's Max plans charge a fixed monthly fee, $100 for Max 5× and $200 for Max 20×, but limit input tokens per minute (about 500K and 2M) and requests per minute (about 50 and 200). "Unlimited" is misleading: 2M tokens a minute would be 2.88B a day without a pause, yet bursts, cooldown penalties and a 5-hour lockout leave 30–50% of that in practice. On these plans cost is counted in rate limit, not dollars: a 150K-token request uses 150× more of it than a 1K-token request doing the same job.
show summary
Anthropic's Max plans offer unlimited* tokens for a fixed monthly fee, subject to rate limits:
| Plan | Price/mo | ITPM | RPM | RPD (approx) |
|---|---|---|---|---|
| Max 5× | $100 | ~500K | ~50 | Varies |
| Max 20× | $200 | ~2M | ~200 | Varies |
*"Unlimited" is misleading. The rate limits create an effective daily token budget. At 2M ITPM, you can process roughly 2M × 1,440 minutes = 2.88B tokens/day — but only if you never pause. In practice, bursty usage patterns, cooldown penalties for exceeding sustained rates, and the 5-hour lockout for aggressive utilization mean the effective budget is 30–50% of theoretical maximum.
The key insight for flat-rate plans: cost is measured in rate limit consumption, not dollars. Every token of context in every request depletes the same shared pool. A 150K-token request consumes 150× more rate limit than a 1K-token request, even if both accomplish the same task.
2.3 Batch APIs39 words
Most providers offer batch/async APIs at 50% discount with higher latency (up to 24 hours, typically minutes). These use separate rate limit pools. For non-interactive work (nightly summaries, bulk analysis, memory consolidation), batch APIs effectively double available capacity.
2.4 Prompt Caching Mechanics261 wordsSummaryPrompt caching is the biggest single saving for a persistent agent, and it has strict rules. The cache is keyed on a hash of the tokens up to a breakpoint the caller marks, so one changed token misses the whole cache. Entries expire after 5 minutes idle, or 1 hour with long retention. Prefixes under 1,024 tokens (2,048 for Claude 3.5 Opus) are not cached. Writing to the cache costs 25% more than plain input while hits save 90%, so a cache that keeps missing costs more than no cache. That is the core problem: the agent's memory files are part of the system prompt, so its normal memory writes keep breaking its own cache.
show summary
Anthropic's prompt caching is the single most important optimization lever for persistent agents. Understanding its mechanics is essential:
- Cache key = hash of the prefix. The cache stores KV representations keyed by the hash of the token sequence from the start of the prompt up to a cache breakpoint. If even one token changes in the cached prefix, the entire cache misses.
- Cache breakpoints are explicit. You mark where cache boundaries should be using
cache_controlmarkers in the API request. The system caches everything before the marker.
- TTL is 5 minutes (extended to 1 hour with
cacheRetention: "long"). The cache evicts after this period of inactivity. For a persistent agent processing requests every few minutes, the cache stays warm. For bursty usage with long gaps, caching provides less benefit.
- Minimum cacheable prefix is 1,024 tokens (2,048 for Claude 3.5 Opus). Shorter prefixes aren't cached.
- Cache write costs 25% more than uncached input. The first request that populates the cache pays a premium. Subsequent requests save 90%. This means cache misses are actively more expensive than no caching at all — a penalty for instability.
The fundamental tension: A persistent memory agent writes to its own memory files as part of normal operation. These memory files are injected into the system prompt. Every memory write changes the system prompt. Every system prompt change invalidates the prompt cache. The agent's normal behavior actively destroys its own cost optimization.
This tension — between persistence (writing memories) and efficiency (stable cache) — is the central architectural challenge that Budget Prompting addresses.
2.5 Industrial Convergence — Evidence from the Claude Code Source Exposure268 wordsSummaryIn March 2026 Anthropic accidentally published a 59.8 MB source map in the npm package @anthropic-ai/claude-code@2.1.88, exposing about 512,000 lines of TypeScript, and the paper reads its compaction, budget and prompt-assembly code. Claude Code splits context management into three tiers that match this paper's almost one to one: clearing old tool results during the conversation, summarizing the whole history with a forked agent, and consolidating memory when idle. Two teams with no contact reaching the same structure suggests the problem demands it. The code also settles open questions on cache-safe pruning, cache sharing during compaction and stopping when returns diminish. The caveat: it is leaked code, and two figures come only from secondary analysis.
show summary
@anthropic-ai/claude-code@2.1.88, exposing about 512,000 lines of TypeScript, and the paper reads its compaction, budget and prompt-assembly code. Claude Code splits context management into three tiers that match this paper's almost one to one: clearing old tool results during the conversation, summarizing the whole history with a forked agent, and consolidating memory when idle. Two teams with no contact reaching the same structure suggests the problem demands it. The code also settles open questions on cache-safe pruning, cache sharing during compaction and stopping when returns diminish. The caveat: it is leaked code, and two figures come only from secondary analysis.In March 2026 Anthropic accidentally published a 59.8 MB source map inside the npm package @anthropic-ai/claude-code@2.1.88, exposing roughly 512,000 lines of unobfuscated TypeScript. We read the compaction, budget, and prompt-assembly code directly (file paths cited below are from that tree). It is the closest thing the field has to a look inside a production agent at scale, and it independently confirms the core architecture MYELIN proposes.
The most striking finding is convergent design. Claude Code organizes context management into three tiers that map almost one-to-one onto MYELIN's:
| MYELIN tier | Claude Code equivalent | Source |
|---|---|---|
| Continuous indexing (B6) | MicroCompact — per-tool-result clearing during the conversation | services/compact/microCompact.ts |
| Per-turn / per-session retrieval (B4) | Session Compact — full-history summarization via a forked agent | services/compact/compact.ts, sessionMemoryCompact.ts |
| Sleep consolidation (idle-time memory consolidation) | autoDream — idle-triggered background consolidation | services/autoDream/autoDream.ts |
Two teams with no contact arriving at the same three-tier structure is evidence that the structure is demanded by the problem, not chosen by taste. The leaked code also resolves several questions MYELIN left open — cache-pinned micro-compaction (B1/B6), forked-agent cache sharing (B4), and a diminishing-returns budget tracker (Section 4) — each now grounded in shipping code rather than projection. We thread these into the relevant technique descriptions below and revisit them as validation in Section 6.5.
One caveat on provenance: this is leaked code, not documentation Anthropic stands behind, and a few figures (the daily-waste number and the default output cap) come from secondary analysis of the dump rather than a line we can point to. We mark those as reported-but-unconfirmed where they appear.
3. Taxonomy of Budget Prompting Techniques6,134 wordsSummaryThe paper sorts its 20 techniques into five categories by what they save, plus a security group; the table has 22 rows because C2 repeats A2 from the output side and B6a generalizes B6. Thirteen are in use and seven are designed. Model routing (A) sends work to the cheapest model that can do it and budgets thinking. Context economics (B), the largest group, keeps the prompt cached and the context small: new sessions, retrieval on demand, compaction, and designed steps such as frozen memory and tool-output pruning. Output economics (C) lets the agent stay silent. Temporal amortization (D) tiers cron jobs, staggers two accounts and paces requests. Billing arbitrage (E) uses the batch API and fresh sub-agents. Security (F) would scan memory writes.
show summary
We organize the 20 techniques into five categories based on what they optimize. Table 1 provides an overview; detailed descriptions follow.
Table 1. Budget Prompting Technique Summary
| # | Technique | Category | Status | Est. Savings |
|---|---|---|---|---|
| A1 | Model routing by complexity | Model Routing | [Y] | 25–40% automated |
| A2 | Extended thinking control | Model Routing | [Y] | $5–10/day equiv. |
| A3 | Cross-model delegation | Model Routing | [Y] | Variable |
| B1 | System prompt caching | Context Econ. | [Y] | $8–10/day |
| B2 | Aggressive session management | Context Econ. | [Y] | 2–4× per turn |
| B3 | Memory search over bulk loading | Context Econ. | [Y] | 80–95% context |
| B4 | Context compaction | Context Econ. | [Y] | 60–80% context |
| B5 | Frozen snapshot injection | Context Econ. | [ ] | Cache-stability insurance |
| B6 | Surgical tool output pruning | Context Econ. | [ ] | ~21% of audited Read bytes addressable |
| B6a | Content-type-specific compression | Context Econ. | [ ] | 60–95% in stateless benchmarks |
| B7 | Iterative summary compression | Context Econ. | [ ] | 5–15K tokens |
| B8 | Rolling window + vector retrieval | Context Econ. | [ ] | Fixed context cap |
| B9 | Mid-context reinjection | Context Econ. | [ ] | Indirect |
| C1 | Silent reply (NO_REPLY) | Output Econ. | [Y] | $5–8/day |
| C2 | Thinking control (output) — output-side view of A2 | Output Econ. | [Y] | (see A2) |
| D1 | Cron priority tiers | Temporal Amort. | [Y] | 15–20% automated |
| D2 | Background review agent | Temporal Amort. | [ ] | 80% reflection |
| D3 | Dual-account staggering | Temporal Amort. | [Y] | Eliminates outages |
| D4 | Token bucket pacing | Temporal Amort. | [Y] | Prevents lockouts |
| E1 | Batch API for non-interactive | Billing Arbitrage | [Y] | 50% on batch work |
| E2 | Sub-agent fresh context | Billing Arbitrage | [Y] | $1–3/delegation |
| F1 | Security scanning on mem writes | Security | [ ] | Indirect |
Each technique is described with its mechanism, expected savings, implementation status, and interaction effects. The table lists 22 rows but 20 distinct techniques: C2 is the output-cost view of A2 (extended thinking control), and B6a is the content-type-specific generalization of B6 (it subsumes B6 rather than adding an independent lever) — both are broken out separately so their categories read completely. Counting each once, 13 of the 20 are implemented and 7 are designed.
Category A: Model Routing — Right Brain for the Job549 wordsSummaryCategory A sends each piece of work to the cheapest model that can handle it. A1 routes by task: conversations that need personality go to Opus or Sonnet, cron jobs and heartbeats to Haiku, which cuts total cost by 25–40%. A2 sets a thinking budget per task, since reasoning is billed as output at 3–5× the input price; throttled turns use 50–90% fewer output tokens, about $7.50 a day. A3 keeps metered models such as GPT-4o for work only they add value to, such as heavy document analysis, and leaves the rest on the flat-rate plan. All three are in use.
show summary
The cheapest token is the one processed by the cheapest model that can handle the task.
A1. Model Routing by Task Complexity186 wordsSummaryEach task goes to the cheapest model that can do it. Conversations that need personality and memory go to capable models (Opus, Sonnet); cron jobs, heartbeats and rote work go to Haiku; metered models (GPT-4o, o3) are kept for cross-model review. The TinkerClaw gateway does this with a routing table. A Haiku cron job costs about 1/4 of the same job on Sonnet and 1/20 on Opus, so routing saves 60–80% on automated work, and with automated work at 40–60% of turns it cuts total cost by 25–40%. It has run since February 2026. Under budget pressure more work moves down: above 85% weekly utilization, interactive work drops to Sonnet; above 95%, to Haiku.
show summary
Mechanism: Classify incoming tasks by complexity and route to appropriate models. Interactive conversations requiring personality, nuance, and memory integration go to capable models (Opus, Sonnet). Automated cron jobs, heartbeat responses, and rote operations go to cheap models (Haiku). Metered models (GPT-4o, o3) are reserved for specific cross-model review tasks where a different architecture's perspective adds value.
Implementation: The TinkerClaw gateway maintains a routing table:
routing:
interactive: claude-sonnet # User-facing, personality-critical
cron-high: claude-sonnet # Morning briefing, security scans
cron-low: claude-haiku # Log rotation, cleanup tasks
sub-agent: claude-haiku # Delegated rote work
review: gpt-4o # Cross-model second opinion
batch: claude-haiku # Nightly consolidation via batch APISavings: 60–80% on automated work. A Haiku cron job costs roughly 1/4 of the same job on Sonnet, and 1/20 on Opus. Since automated work constitutes 40–60% of total turns in our deployment, model routing alone reduces total cost by 25–40%.
Status: [Y] Implemented. In production since February 2026.
Interaction effects: Interacts with A3 (cross-model delegation) and D1 (cron priority tiers). Budget pressure shifts more work to cheaper models — at >85% weekly utilization, even interactive work drops to Sonnet; at >95%, to Haiku.
A2. Extended Thinking Control211 wordsSummaryExtended thinking is reasoning the model writes before it answers. It is billed as output, which costs 3–5× more than input, and a hard question can produce 3,000–10,000 tokens of it for a 200-token reply. TinkerClaw sets the thinking budget per task: off for simple replies and heartbeats, low (~1,024 tokens) for moderate tasks and sub-agents, high for hard problems. Throttled turns use 50–90% fewer output tokens; if half of 200 daily turns drop 5,000 thinking tokens at $15 per million, that is about $7.50 a day. Sub-agents default to low and cron jobs to off. Some simple-looking tasks do need reasoning, so interactive work keeps thinking on.
show summary
Mechanism: Anthropic's extended thinking feature allows models to perform chain-of-thought reasoning before responding. This reasoning is generated as output tokens — which cost 3–5× more than input tokens. For a complex question, the model might generate 3,000–10,000 tokens of reasoning to produce a 200-token visible reply. That invisible reasoning can cost more than the entire rest of the turn.
Control thinking budget explicitly:
thinking: off— No extended thinking. Suitable for simple responses, heartbeats, formatting tasks.thinking: low— Minimal reasoning budget (~1,024 tokens). Suitable for moderately complex tasks, sub-agent work.thinking: high— Full reasoning budget. Reserved for genuinely hard problems.
Savings: 50–90% reduction in output tokens for turns where thinking is throttled. At $15/MTok output (Sonnet), eliminating 5,000 unnecessary thinking tokens saves $0.075 per turn. Across 200 daily turns, if half can use reduced thinking: ~$7.50/day.
Status: [Y] Implemented. Sub-agents default to thinking: low. Cron jobs default to thinking: off unless the task is flagged as requiring reasoning.
Interaction effects: Synergistic with A1 (model routing) — cheap models with thinking off is the cheapest possible configuration. Tension with quality: some tasks that appear simple benefit from reasoning. We err on the side of enabling thinking for interactive work and disabling for automated work.
A3. Cross-Model Delegation136 wordsSummaryMetered models (GPT-4o, o3) are used only where a different model adds something: heavy document analysis, a second opinion, or tasks Claude is known to handle poorly. Orchestration, routing and plumbing stay on the flat-rate plan. For example, Haiku runs a workflow, hands a 50-page document to GPT-4o through the oracle command-line tool, gets back a structured summary and carries on. The saving varies; the rule is that anything the flat-rate plan can do, it should do. It is in use, mainly for cross-model code review and document analysis, and low-priority jobs never use metered models.
show summary
oracle command-line tool, gets back a structured summary and carries on. The saving varies; the rule is that anything the flat-rate plan can do, it should do. It is in use, mainly for cross-model code review and document analysis, and low-priority jobs never use metered models.Mechanism: Use metered models (GPT-4o, o3) only for tasks where their different training or architecture provides genuine value — typically heavy document analysis, alternative perspective review, or tasks where Claude has known weaknesses. Use flat-rate models for orchestration, routing, and plumbing.
In practice: Haiku orchestrates a workflow, identifies that a 50-page document needs deep analysis, delegates to GPT-4o via the oracle CLI, receives a structured summary, and continues orchestrating. Only the hard thinking hits the metered API; everything else stays on flat-rate.
Savings: Variable. Prevents unnecessary metered API usage. Key principle: if it can be done on flat-rate, it should be.
Status: [Y] Implemented. The oracle CLI wraps ChatGPT API calls. Used primarily for cross-model code review and document analysis.
Interaction effects: Interacts with D1 (cron priority) — low-priority jobs never use metered models regardless of task complexity.
Category B: Context Economics — Minimize What Goes In3,791 wordsSummaryThe context is the agent's working memory and its largest cost, because every token in it is billed again each turn. Ten techniques shrink it. Four are in use: caching the fixed system prompt (B1, $9.72 a day), starting new sessions often (B2), fetching memory and skills on demand instead of loading them all (B3, 80–95% less injected context) and compacting long conversations (B4, 60–80% smaller). Six are designed, not built: freezing memory per session so writes stop breaking the cache (B5), pruning old tool output (B6), compressing it by content type (B6a), keeping one summary updated in place (B7), a rolling window that retrieves older turns (B8) and a personality reminder mid-conversation (B9).
show summary
The context window is both the agent's working memory and its largest cost driver. Every token in context is an input token billed every turn.
B1. System Prompt Caching655 wordsSummaryThe system prompt, about 18K tokens, is the same every turn, so it is cached for up to an hour at one tenth of the price: $0.054 a turn uncached against $0.0054 cached, or $9.72 a day over 200 turns. TinkerClaw already does this. It splits the prompt at a marker into a cached fixed part and an uncached part that changes each turn, the same split the leaked Claude Code source makes, and it uses three of Anthropic's four cache breakpoints: after the tool definitions, at the marker and on the last user message. The weak point is memory: each write to a memory file breaks the cache, and one write can mean 5–10 minutes of uncached requests. B5 is the insurance against it.
show summary
PartWhat caching saves per turn80 wordsSummaryThe system prompt (personality, instructions, memory files and tool definitions) is about 18K tokens and stays the same from turn to turn, so Anthropic's prompt cache can keep it for up to 1 hour after the last request, at one tenth of the normal price. For 18,000 tokens at $3 per million, that is $0.054 a turn uncached against $0.0054 cached: $9.72 a day saved over 200 turns.
show summary
Mechanism: The system prompt (personality, instructions, memory files, tool definitions) occupies ~18K tokens and is identical across turns within a session. With Anthropic's prompt caching and cacheRetention: "long", this prefix is cached for up to 1 hour after the last request. Cached tokens cost 1/10th of uncached tokens.
For a 18K-token system prompt:
- Uncached: 18,000 × $3/MTok = $0.054/turn
- Cached: 18,000 × $0.30/MTok = $0.0054/turn
- Savings: $0.049/turn × 200 turns = $9.72/day
PartIn use, but memory writes break it145 wordsSummaryTinkerClaw already sends the fixed part of the system prompt as a cached block and the part that changes each turn as a separate uncached block. The weak point is memory: the prompt includes the agent's memory files, so every write to memory makes the cache miss, and one write can mean 5–10 minutes of uncached requests. Technique B5 is meant as insurance against this, but July telemetry showed the cache is already reused well, so B5 is no longer the unbuilt technique with the most impact.
show summary
Status: [Y] Implemented. The static portion of the system prompt is emitted as a content block carrying cache_control: { type: "ephemeral" }, with extended (1-hour) retention requested where the API supports it; the per-turn portion is split off into a separate uncached block (see the boundary mechanism below).
Interaction effects: Critical tension with memory writes. This is the most important interaction in the entire taxonomy. The system prompt includes injected memory files. When the agent writes to memory (which it does regularly as part of learning and persistence), the system prompt hash changes, and the cache misses. A single memory write can cascade into 5–10 minutes of uncached requests before the new prefix stabilizes.
This tension motivates B5 (frozen snapshot injection) as insurance against prefix instability. July telemetry shows that the deployment already achieves high cache reuse, so B5 is no longer the highest-impact unimplemented technique.
PartWhere the cache line is drawn430 wordsSummaryTinkerClaw and the leaked Claude Code source both split the system prompt at a marker: what comes before it is cached, what comes after may change each turn. Anthropic builds the cached prefix in the order tools, system, messages and allows up to four cache breakpoints. TinkerClaw uses three, after the last tool definition, at the system-prompt marker and on the last user message, so slow-changing content sits above a breakpoint and per-turn content below it, as the figure shows.
show summary
The dynamic boundary, in two codebases. The prefix-discipline this technique depends on shows up as an explicit marker in both the system we run and the leaked Claude Code source. TinkerClaw splits every system prompt at a __PREFRONTAL_CACHE_BOUNDARY__ sentinel (src/fork/prompt-cache-boundary.ts): the text before the marker becomes a single content block carrying cache_control: { type: "ephemeral" }; everything after it is emitted as an uncached block that may change each turn. The split is the operational form of "keep the prefix static" — dynamic context is physically moved past the cache line rather than mixed into it. Claude Code does the same with a SYSTEM_PROMPT_DYNAMIC_BOUNDARY sentinel (constants/prompts.ts): everything before it is globally cacheable (shared across sessions when shouldUseGlobalCacheScope() is on), per-session content goes after, and the helper that emits an uncacheable section is named to warn — DANGEROUS_uncachedSystemPromptSection() (constants/systemPromptSections.ts). Two systems, the same line drawn in the same place: strong evidence that the principle in Section 8.1 matters, not that it is a matter of taste.
Three slabs, three breakpoints. Anthropic assembles the cached prefix in a fixed order — tools → system → messages — and allows up to four cache_control: { type: "ephemeral" } breakpoints. Each breakpoint marks the end of a stable span; everything before it is reused on a hit. The seam matters: slow-changing context (tool definitions, persona, skills, memory) belongs above a breakpoint and per-turn context (live turn, heartbeat, dynamic state) below it, because a single volatile token below the last breakpoint that is placed too high would invalidate everything after it. The tool-definitions array is the front slab — large, stable, and re-sent every turn — yet it is the one most often left uncached. TinkerClaw places a breakpoint on the last tool definition so the entire tool catalog is cached as one prefix: applyAnthropicCacheControlToTools attaches cache_control to tools[tools.length - 1] (src/agents/anthropic-payload-policy.ts), alongside the system-prefix breakpoint at the boundary marker and a breakpoint on the last user message. Three of the four available breakpoints are spent, each closing one stable slab.

B2. Aggressive Session Management204 wordsSummaryContext only grows within a session: a 30-turn conversation with tools can reach 100–150K tokens, and then every turn sends all of it, even to answer "what time is it?". So a new topic or a long context gets a new session, and the memory files carry what matters across. The cost of a turn follows the size of its context: 150K tokens against 18K for a fresh session, 8× less for the same reply. In this deployment the median session is 12 turns and the average context stays around 40–60K tokens instead of 150K+. Sessions restart with /new, and the agent suggests it when the topic changes. The cost is continuity: memory files can lose nuance.
show summary
/new, and the agent suggests it when the topic changes. The cost is continuity: memory files can lose nuance.Mechanism: Context grows monotonically within a session. Every turn adds tokens. A 30-turn conversation with tool use can easily reach 100–150K tokens. At that point, every subsequent turn processes 150K input tokens — even if the user asks "what time is it?"
The solution: start new sessions aggressively. New topic? New session. Context approaching threshold? New session. The agent's persistent memory files carry continuity across sessions — that's what they're for.
Rule of thumb: Context window size = cost per turn. A 150K context window means every turn costs 150K input tokens. A fresh session with an 18K system prompt costs 18K input tokens. That's an 8× cost reduction for the same response.
Savings: Highly variable. Prevents worst-case context bloat. In our deployment, the median session length is 12 turns (before auto-compaction or manual restart), keeping average context around 40–60K tokens instead of the 150K+ it would reach without intervention.
Status: [Y] Implemented. OpenClaw supports manual session restart via /new, and the agent is prompted to suggest new sessions when topics shift.
Interaction effects: Synergistic with B1 (caching) — shorter sessions mean less context change, more stable cache. Tension with conversational continuity — the agent must rely on memory files for cross-session context, which can lose nuance.
B3. On-Demand Retrieval over Bulk Loading501 wordsSummaryInstead of loading everything into the system prompt, the agent fetches only what the current turn needs. For memory, a search returns the 200 relevant tokens of a 5,000-token file, and the prompt shrinks from a possible 50K+ tokens to 15–20K; only the core identity, today's and yesterday's notes and the tool guidance are always loaded. The same idea applies to tool definitions and the skill catalog: replacing ~915 tokens of descriptions for 44 marketing skills with one ~130-token router skill cut that part about 7×, with every skill still reachable. Overall, injected context falls 80–95%. Both uses are live. The risk is that the search misses something relevant.
show summary
Mechanism: Instead of injecting an entire always-loaded surface into the system prompt, retrieve only the relevant snippet at the moment it is needed. The canonical instance is memory: rather than loading full memory files, use memory_search() to return only relevant snippets. A memory file might contain 5,000 tokens spanning months of notes; a search query returns the 200 tokens relevant to the current conversation.
But memory is not the only always-loaded surface. The system prompt of a tool-rich agent carries at least three independently evictable prefix slabs: memory files, the tool definitions array, and the skill/recipe catalog. Each is large, slow-changing, and re-sent every turn; each can be either cached (B1) or retrieved on demand (B3). The general principle is: any catalog that is always loaded but rarely fully used should be replaced by a code-side matcher that injects only the winning entry's body per turn.
Savings: Reduces injected context by 80–95% compared to loading the full surface. For memory, the system prompt shrinks from a potential 50K+ tokens (with all memory files loaded) to 15–20K (with selective retrieval).
Worked example — catalog eviction on the skill/recipe surface. We have a measured instantiation of this principle on a surface larger than memory. Applying eviction to a vendored 44-skill catalog (the coreyhaines31/marketingskills set, integrated via the marketing router skill) replaced ~915 tokens of always-loaded skill descriptions with a single ~130-token router skill — a roughly 7× reduction on that prefix slab with all 44 frameworks still reachable on demand. The design invariant that makes this safe to do uncapped: matching is code-side, and only the winning entry's body is injected for a given turn, so adding the 45th skill costs nothing at rest. This is exactly B3's "retrieve the relevant snippet instead of loading everything," generalized from memory files to the catalog surface.
Status: [Y] Implemented for both surfaces. Memory files are searchable via semantic search; the system prompt injects only a curated subset:
- Core identity (SOUL.md) — always loaded (~1K tokens)
- Today's memory file — always loaded (~1–3K tokens)
- Yesterday's memory file — always loaded (~1–3K tokens)
- Tool guidance (TOOLS.md) — always loaded (~2K tokens)
- Everything else — retrieved on demand via
memory_search()
The skill/recipe catalog uses the same pattern: a thin router skill holds one-line pointers; the matcher selects and injects only the chosen framework's full body. This router pattern is itself convergent with how external skill collections are increasingly packaged — addyosmani/agent-skills (56.8k★) ships a discipline plugin where a slim index points at heavier per-topic skill bodies loaded only when matched, rather than concatenating every skill into the prompt; the catalog-eviction win above is the cost-accounting view of that same load-on-demand discipline.
Interaction effects: Synergistic with B1 (caching) — smaller, more stable system prompt = better cache hit rate, and any slab not evicted is at least cacheable (the tools-array breakpoint and the system-prefix boundary in B1). Tension with completeness — the matcher might miss relevant context that wasn't selected, the same recall risk memory search carries.
B4. Context Compaction372 wordsSummaryWhen the context passes a threshold, OpenClaw's /compress replaces the conversation with a structured summary and cuts it by 60–80%; going from 120K to 30K tokens saves 90K on every later turn. It runs by hand or automatically from a per-call measure of the context, never from a usage field that may add up several calls. It is a blunt tool, which motivates B6 and B7. The Claude Code source suggests two improvements: pull exact facts out to a file before summarizing the rest, since a summary can drift while extraction can only omit; and let the summarizing agent share the parent's cache. The second probably needs API support the current stack does not offer.
show summary
/compress replaces the conversation with a structured summary and cuts it by 60–80%; going from 120K to 30K tokens saves 90K on every later turn. It runs by hand or automatically from a per-call measure of the context, never from a usage field that may add up several calls. It is a blunt tool, which motivates B6 and B7. The Claude Code source suggests two improvements: pull exact facts out to a file before summarizing the rest, since a summary can drift while extraction can only omit; and let the summarizing agent share the parent's cache. The second probably needs API support the current stack does not offer.Mechanism: When context exceeds a threshold, summarize the conversation history. OpenClaw's built-in /compress command replaces the full conversation with a structured summary, reducing context by 60–80%.
Savings: Prevents context from reaching maximum window size. A compaction from 120K to 30K tokens saves 90K tokens per subsequent turn.
Status: [Y] Implemented. OpenClaw's built-in feature. Triggered manually via /compress or automatically from a per-call context snapshot. A persisted per-message usage field is not a valid trigger input because it may aggregate multiple calls in one turn.
Interaction effects: Tension with B1 (caching) — compaction changes the conversation portion of the context, but the system prompt prefix remains stable. Compaction is a blunt instrument that motivates B6 (surgical tool output pruning) and B7 (iterative summary compression).
Two distinct operations, not one. Compaction is easy to treat as a single step, but the Claude Code source separates two operations whose distinction is worth importing. Summarization (lossy, broad) compresses a span of conversation into prose — Claude Code calls this Context Collapse, gated behind a CONTEXT_COLLAPSE feature flag in services/compact/autoCompact.ts. File extraction (lossless, selective) pulls exact facts out to a file that lives outside the summary — Claude Code's Session Memory (services/SessionMemory/) does this. The two have different failure modes: summarization can hallucinate or drift; extraction can only omit. A precise compaction tier should run both — extract the facts you must not lose, then summarize the rest — rather than forcing everything through one lossy pass. We recommend B4 implementations expose extraction and summarization as separate stages.
Forked-agent cache sharing. Claude Code's session compaction (services/compact/compact.ts) spawns a forked agent (runForkedAgent, CacheSafeParams) whose prompt cache is shared with the parent: the summary agent does not pay to re-read the conversation it is summarizing. It strips images first (stripImagesFromMessages) so they don't waste the summary budget, and on the way back restores up to 5 most-relevant files at ~5K tokens each plus skills under a 25K budget (POST_COMPACT_MAX_FILES_TO_RESTORE, POST_COMPACT_MAX_TOKENS_PER_FILE, POST_COMPACT_SKILLS_TOKEN_BUDGET). The cache-sharing trick makes compaction nearly free in cache terms and is the clearest argument that compaction should reuse, not rebuild, the prefix. It likely requires API-level support our current stack does not expose; we flag it as a target rather than a shipped technique.
B5. Frozen Snapshot Injection (Prefix Stabilization)356 wordsSummaryB5 would read all memory once at the start of a session and put that frozen copy in the prompt, so writes during the session reach the files on disk without changing the prompt and breaking the cache. It is designed, not built. July 25 telemetry measured a 91.1% cache hit rate (median 98.6%) and 10.6 cache reads per write, so the 65%→95% gap once assumed does not exist here, and B5 stays as insurance against regressions. The cost is that within a session the agent cannot see what it has just written.
show summary
PartFreeze memory at session start159 wordsSummaryThis technique targets the clash between memory writes and the cache: every write to a memory file changes the system prompt and so breaks the cache. The fix is to read all memory once when a session starts and put that frozen copy in the prompt. Writes during the session still reach the files on disk, but the prompt stays the same until the next session reads them.
show summary
Mechanism: This technique resolves the fundamental tension between memory writes and prompt caching (identified in B1).
The problem: The agent writes to memory files during normal operation. Memory files are injected into the system prompt. Every memory write changes the system prompt. Every change invalidates the prompt cache. The agent's own learning behavior destroys its cost optimization.
The solution: Capture a frozen snapshot of all memory at session start. Inject this snapshot into the system prompt. During the session, memory writes go to a staging area — they update the underlying files but do not change the injected snapshot. The next session starts with a fresh snapshot that includes the staged changes.
Session N starts:
1. Read memory files → create frozen snapshot
2. Inject snapshot into system prompt (cached)
3. Agent operates, writes to memory (staged)
4. System prompt unchanged → cache stable
Session N+1 starts:
1. Read memory files (includes Session N's staged writes)
2. Create new frozen snapshot
...PartExpected gain, algorithm and cost197 wordsSummaryJuly 25 telemetry measured a 91.1% aggregate cache hit rate (median 98.6%) and 10.6 cache reads per write, so the 65%→95% gap once assumed does not exist on this deployment, and B5 is kept as insurance against regressions after memory writes, not for a 2.8× saving. The method is written out as an algorithm; it is designed, not built, and needs changes to OpenClaw's memory pipeline. Its cost is stale memory: within a session the agent cannot see, say, a reminder it has just written.
show summary
Expected savings: July 25 telemetry measured a 91.1% aggregate prompt-cache hit rate (median 98.6%) and 10.6 cache reads per write. The formerly assumed 65%→95% gap therefore does not exist on this deployment. B5 remains useful as insurance: its success criterion is preserving reads per write and preventing regressions after memory mutations, not a projected 2.8× cache saving.
Formal definition:
ALGORITHM: FrozenSnapshotInjection(session_start)
-------------------------------------------------
On session_start:
snapshot ← {}
for each file f in memory_hierarchy:
snapshot[f.path] ← read(f)
system_prompt ← build_prompt(snapshot)
cache(system_prompt) # stable prefix for entire session
staging ← {} # empty write buffer
On memory_write(path, content):
write_to_disk(path, content) # persist immediately
staging[path] ← content # track for next session
# system_prompt unchanged → cache stable
On session_end:
# staging is already on disk; next session reads fresh
discard(staging)Status: [Designed], not implemented. Requires changes to OpenClaw's memory injection pipeline.
Interaction effects: Strongly synergistic with B1 (caching) — this technique exists specifically to maximize cache effectiveness. Tension with memory freshness: the agent operates with stale memory during a session. For most use cases this is acceptable (memory changes are incremental), but edge cases exist (e.g., agent writes a critical reminder, then can't "see" it in the same session).
B6. Surgical Tool Output Pruning536 wordsSummaryTool outputs (a 10K-token web page, a 5K-token file) stay in the context long after use and are billed again every turn. B6 would prune them in two stages: first replace old outputs with a one-line placeholder, at no cost; then, if the context is still too big, have Haiku summarize the large ones in 2–3 sentences. An audit of 890 sessions and 4,402 file reads found 21% of the 23,376,348 bytes of Read output removable by known compressors; Bash added another 20,916,377 bytes they do not touch. Claude Code ships a version that swaps old results for a fixed stub in the same position, so the cache still matches. B6 is designed, not built; today /compress summarizes everything.
show summary
/compress summarizes everything.Mechanism: Tool outputs are often the largest single source of context bloat. A web fetch returns 10K tokens. A file read returns 5K tokens. A search returns 3K tokens. After the agent has processed these outputs and responded, the raw outputs remain in context forever, consuming input tokens every subsequent turn despite being unlikely to be referenced again.
Surgical pruning operates in two stages:
- Stage 1 (free, rule-based): After N turns, replace tool outputs older than the threshold with 1-line placeholders:
[web_fetch: example.com — 10,234 tokens, summarized: article about prompt caching mechanics]. No LLM call needed; the original output's first line and token count provide sufficient placeholder. - Stage 2 (LLM-assisted, on budget pressure): If context still exceeds budget after Stage 1, use a cheap model (Haiku) to generate 2–3 sentence summaries of remaining large tool outputs, replacing them in context.
Expected savings: An audit of 890 sessions and 4,402 file-read calls measured 23,376,348 bytes of Read output. About 5,007,000 bytes (21%) were addressable by the known compressors: 3,374,879 stale-read bytes, 1,512,097 bytes of line-number scaffolding, 94,971 bytes of subset containment, and 25,042 bytes of identical repeats. This is an observed traffic-level ceiling for those mechanisms, not the earlier 30–50% context estimate. Bash produced another 20,916,377 bytes and was not addressed by a Read-oriented compressor.
Production validation — MicroCompact. Claude Code ships exactly this technique, and more surgically than the design above. Its microCompact.ts compacts only specific tool results — FileRead, Bash, Grep, Glob, WebSearch, WebFetch, FileEdit, FileWrite (eight tool types, confirmed in the imports). Old results are replaced in place with a stub — the literal constant is TIME_BASED_MC_CLEARED_MESSAGE = '[Old tool result content cleared]' — and clearing is time-gated (a configurable gap threshold; see timeBasedMCConfig.ts). Two refinements over our design are worth adopting: (1) restrict pruning to tool types whose output is large and rarely re-referenced, rather than pruning all messages; and (2) cache-pinning — the cleared stubs are kept at the original positions in the message list so the prompt-cache prefix up to that point still matches. This is the production answer to the cache-vs-pruning tension B6 raises in the abstract: you can prune content without moving anything, so the cache survives. Note microCompact.ts deliberately runs cached MC only on the main thread, to avoid forked agents corrupting the shared cache state — a subtlety our design had not anticipated.
Approach comparison. Our proposed B6 is embedding/summary-based (replace old output with an LLM-generated 2–3 sentence summary); Claude Code's is stub-replacement (replace with a fixed marker, no LLM call). The stub approach is free and cache-safe but loses the content entirely; ours preserves a gist at the cost of a cheap Haiku call. The right design is probably staged: stub-replace first (free, cache-pinned), summarize only the survivors under budget pressure — which is the two-stage pipeline B6 already describes.
Status: [Designed], not implemented. Currently we use blunt /compress which summarizes everything, not just tool outputs.
Interaction effects: Synergistic with B2 (session management) — pruning extends the useful life of a session before restart is needed. Complementary to B4 (compaction) — surgical pruning should run before full compaction, handling the low-hanging fruit first.
B6a. Content-Type-Specific Compression (Typed Compressors and Reversible Retrieval)568 wordsSummaryLarge tool outputs are usually structured (JSON, code, diffs, logs), and a compressor that understands the structure can shrink them much further than one that treats them as plain text. The open-source project headroom does this with one compressor per content type, and it keeps the original aside so the model can fetch it back in full when it turns out to matter. Seen this way, B6 is the fallback for text with no structure, and the proposed design picks a compressor by content type and keeps every original. headroom also offers a trained compression model, whose cost against its gain should be measured. B6a is designed, not built. Retrieved content has to go after the cache boundary.
show summary
Mechanism: B6 treats every tool output as opaque text — it stubs or summarizes a payload by its position and age, not its structure. This leaves savings on the table, because the largest tool outputs in an agent's context are usually highly structured: a JSON tool result, a code file, a diff, a log. A compressor that understands the structure can crush these far harder than a blind summarizer, and — crucially — can do so reversibly.
The most developed public instance is headroom (chopratejas, Apache-2.0, 24.7k★), a context-compression layer for agents whose core abstraction is CCR — Compress, Cache, Retrieve. CCR is convergent with B6 (surgical tool-output pruning) plus the "keep the original, retrieve on demand" half of B8, but it sharpens both. Two differences are mechanistically new for MYELIN:
- Reversible, lossless-on-recall. Where B6 replaces an old output with a fixed stub (lossy, content gone) or a Haiku summary (a lossy gist), CCR caches the original out of band and lets the model retrieve the full content on demand. Compression is therefore lossless when the content turns out to matter — the failure mode of B6's stub ("the agent needed the bytes we threw away") does not exist. This is the same reversibility Claude Code's cache-pinned MicroCompact gestures at, taken to its logical end: don't delete, displace-and-index.
- Per-content-type compressors. headroom ships a family of structure-aware compressors rather than one uniform replacement strategy — statistical JSON-array crushing (SmartCrusher), AST-aware code compression via tree-sitter, and dedicated log/diff/text handlers. This is a genuinely new dimension for us. Our B6 prunes by tool-type and age but compresses every payload as text; a typed compressor compresses by structure, which is why headroom can report much higher savings on JSON tool results and code than a text summarizer reaches.
The reframing: under this lens, B6 is the degenerate (text-only) case of a typed compressor — the handler you fall back to when the payload has no exploitable structure. The correct general design is a dispatch table keyed on content type (JSON → array crusher, code → AST compressor, diff/log → dedicated handler, everything else → B6's stub-then-summarize), with originals cached for reversible retrieval rather than discarded. We recommend B6 implementations expose this typed-dispatch interface and treat the text path as one branch among several.
An alternative to rule-based Stage 1. B6's Stage 1 is rule-based (fixed stub, no LLM). headroom also ships a trained compression model (Kompress-v2-base, on HuggingFace) and exposes itself as a proxy, an MCP server, and a library. A learned or LLM-judged compressor is a third option alongside our rule-based stub and Haiku-summary stages — a model that decides what to keep, rather than a regex. Whether the model's per-call cost is worth its higher compression ratio is exactly the kind of accuracy-vs-cost tradeoff our evaluation framework (Section 5, 9.2) should measure rather than assume.
Status: [Designed], not implemented. B6's text path is itself unimplemented (we still use blunt /compress); the typed-compressor generalization is a design target informed by headroom's shipping implementation.
Interaction effects: Strict generalization of B6 — every B6 interaction (fit with B2, complement to B4) carries over. Synergistic with B8 (rolling window): CCR's cached-original-plus-retrieve is the same shape as B8's vector store, and a typed compressor feeding a retrieval store is a natural unification of the two. Tension with caching (B1): retrieval injects variable content per turn, so retrieved spans must live after the cache boundary, exactly as B8's retrieved turns do.
B7. Iterative Summary Compression152 wordsSummaryEach compaction today adds a new summary on top of the earlier ones, and after 3–4 compactions the summaries alone take 10–15K tokens. B7 would update one summary in place and hold it to a fixed budget, for example 2,000 tokens, however many compactions happen. That saves 5–15K tokens in long sessions and lets them run longer before a restart. It is designed, not built, and needs changes to OpenClaw's compaction.
show summary
PartSummaries that pile up59 words
Mechanism: Current compaction appends a summary block to the context, then on subsequent compactions, appends another summary. This creates a stack of summaries that itself grows:
[Summary 1: turns 1-20]
[Summary 2: turns 1-30, including Summary 1]
[Summary 3: turns 1-50, including Summaries 1-2]Each layer adds tokens. After 3–4 compactions, the summaries themselves consume 10–15K tokens.
PartOne summary, updated in place38 words
Iterative compression instead updates the existing summary in place:
[Summary: turns 1-20] → [Summary: turns 1-30] → [Summary: turns 1-50]The summary evolves, maintaining a fixed budget (e.g., 2,000 tokens) regardless of how many compaction cycles have occurred.
PartSavings, status and fit55 words
Expected savings: Prevents summary accumulation. Saves 5–15K tokens in long-running sessions that undergo multiple compactions.
Status: [Designed], not implemented. Requires modification to OpenClaw's compaction logic.
Interaction effects: Complementary to B4 (compaction) — this is an improvement to the compaction mechanism itself. Synergistic with B2 (session management) — better compaction means sessions can run longer before restart.
B8. Rolling Window + Vector Retrieval232 wordsSummaryB8 would keep only the last 5–8 turns in the context, move older turns into a searchable store for the session, and before each reply bring back the few past turns most related to it. The context then stops at a fixed size: a conversation that would reach 150K tokens stays at about 40–50K, 2–3× cheaper per turn in long conversations, and long sessions no longer need a restart or compaction for cost reasons. It is designed, not built, and needs an embedding pipeline and a vector store. The retrieved turns change with every request, so the prompt prefix stays cached only if B5 is in place too.
show summary
Mechanism: Maintain only a small window of recent turns (e.g., last 5–8 turns) in the active context. As turns age out of the window, embed them into a per-session vector store. Before generating each response, retrieve the top-K most relevant past turns from the vector store and inject them alongside the recent window.
This creates a hybrid memory model:
- Working memory: Last 5–8 turns, always in context (recency)
- Episodic memory: All past turns, retrievable by relevance (semantic search)
- Context budget: Fixed, regardless of conversation length
Turn 1-5: [in context]
Turn 6: Turn 1 → vector store
Turn 7: Turn 2 → vector store
...
Turn 50: Turns 1-42 in vector store, turns 43-50 in context
+ top-3 retrieved turns injected before current turnExpected savings: Context grows to a fixed ceiling (recent window + system prompt + retrieved turns) rather than monotonically. For a conversation that would normally reach 150K tokens, the rolling window caps effective context at ~40–50K tokens. Savings: 2–3× per turn in long conversations.
Status: [Designed], not implemented (part of the continuous compaction project). Requires embedding pipeline and vector store integration.
Interaction effects: Replaces B2 (aggressive session management) and B4 (compaction) for long-running sessions. The session never needs to restart for cost reasons — context is automatically managed. Tension with B1 (caching) — retrieved turns change each request, but the system prompt prefix remains stable if B5 (frozen snapshot) is also implemented.
B9. Mid-Context Reinjection190 wordsSummaryOver a long conversation the agent drifts from its configured personality, as measured by SyncScore, a 0–1 score that compares its replies with that personality. When the score drops below a threshold, B9 would insert a condensed personality and memory block of about 2K tokens as a reminder, cheaper than a restart and more targeted than compaction. It saves nothing directly but lets sessions run longer and compaction wait. It is designed, not built, and needs SyncScore monitoring. The inserted block can break the cache for that part of the context.
show summary
Mechanism: Long conversations suffer from personality drift — the agent's behavior gradually diverges from its configured personality as the system prompt's influence is diluted by accumulated conversation context. We measure this with SyncScore, a 0–1 coherence score (described in Section 5.2) that compares an agent's live responses against its configured personality; it falls as conversation context dilutes the system prompt's influence.
When SyncScore drops below a threshold, reinject a condensed personality/memory block into the conversation as a system-level "reminder." This is cheaper than restarting the session (which would re-read all memory files and break conversational flow) and more targeted than full compaction.
[System prompt: 18K tokens]
[Turns 1-30: 80K tokens]
[Personality reinjection: 2K tokens] ← inserted here
[Turns 31-current]Expected savings: Prevents the need for premature session restarts due to personality drift. Not a direct cost reduction but enables other techniques (longer sessions, delayed compaction) that do reduce cost.
Status: [Designed], not implemented. Requires SyncScore monitoring integration.
Interaction effects: Complementary to B8 (rolling window) — reinjection ensures personality stability even with a small working memory window. Tension with B1 (caching) — the reinjection changes context, potentially invalidating cache for that portion.
Category C: Output Economics — Minimize What Comes Out306 wordsSummaryOutput tokens cost 3–5× more than input, so what the model writes matters as much as what it reads. C1 gives the agent short sentinel replies (NO_REPLY, HEARTBEAT_OK) for events that need no answer, which also skips extended thinking and saves about $6.90 a day. C2 is the output side of thinking control (A2): 5,000 thinking tokens at $15 per million cost $0.075, so reasoning gets an explicit budget. Both are in use.
show summary
NO_REPLY, HEARTBEAT_OK) for events that need no answer, which also skips extended thinking and saves about $6.90 a day. C2 is the output side of thinking control (A2): 5,000 thinking tokens at $15 per million cost $0.075, so reasoning gets an explicit budget. Both are in use.Output tokens are 3–5× more expensive than input tokens. Controlling what the model generates is as important as controlling what it reads.
C1. Silent Reply (NOREPLY / HEARTBEATOK)211 wordsSummaryMany events need no real answer: heartbeat checks, system notices, group messages the agent should ignore, duplicates. TinkerClaw gives the agent two short replies for these, NO_REPLY and HEARTBEAT_OK, in place of sentences like "Everything looks fine". The words saved are worth little, but a silent turn also skips extended thinking. Heartbeats run every 5 minutes (288 a day); at 230 silent turns a day, 2,000 avoided thinking tokens each and $15 per million, that is $6.90 a day. It is in use, and silent turns should also run with thinking off on the cheapest model.
show summary
NO_REPLY and HEARTBEAT_OK, in place of sentences like "Everything looks fine". The words saved are worth little, but a silent turn also skips extended thinking. Heartbeats run every 5 minutes (288 a day); at 230 silent turns a day, 2,000 avoided thinking tokens each and $15 per million, that is $6.90 a day. It is in use, and silent turns should also run with thinking off on the cheapest model.Mechanism: Not every incoming event requires a substantive response. Heartbeat checks, system notifications, group chat messages the agent shouldn't respond to, duplicate events — all of these can be handled with zero or minimal output.
TinkerClaw defines sentinel responses:
NO_REPLY— The agent has nothing to say. Zero meaningful output tokens.HEARTBEAT_OK— Acknowledgment of a heartbeat check. Minimal output.
The agent is prompted to use these when appropriate rather than generating "I don't have anything to add" or "Everything looks fine, no issues to report" — which waste output tokens on saying nothing.
Savings: A typical 50-token "nothing to report" response costs $0.00075 at $15/MTok. Trivial per-turn, but heartbeats run every 5 minutes (288/day). If 80% of heartbeats produce NO_REPLY instead of a verbose response: negligible per-turn, but significant in aggregate — and more importantly, these silent responses allow the model to avoid extended thinking entirely, saving 1,000–5,000 thinking tokens per turn. At 230 silent turns × 2,000 average avoided thinking tokens × $15/MTok: $6.90/day.
Status: [Y] Implemented. Sentinel tokens are recognized by the gateway and produce minimal API round-trips.
Interaction effects: Synergistic with A2 (thinking control) — NO_REPLY turns should have thinking disabled entirely. Synergistic with A1 (model routing) — heartbeat turns should use the cheapest available model.
C2. Extended Thinking Control (Output Dimension)72 wordsSummaryThinking tokens are billed as output: 5,000 of them at $15 per million cost $0.075, more than many whole input contexts. This entry is A2 seen from the output side, with one rule: reasoning is the most expensive thing a model does per token, so budget it explicitly.
show summary
This is the output-side of A2, listed separately to emphasize the output cost impact. The reasoning tokens generated by extended thinking are output tokens billed at the output rate. A model generating 5,000 thinking tokens at $15/MTok costs $0.075 — more than many entire input contexts.
See A2 for full description. The key output economics principle: reasoning is the most expensive thing an LLM does, per token. Budget it explicitly.
Category D: Temporal Amortization — Spread Cost Over Time671 wordsSummarySome work must happen, but not every turn. D1 ranks automated jobs as critical, standard or background and skips or downgrades the lower tiers when weekly use is high, saving 15–20% of the automated budget in those weeks. D2, not yet built, would batch the agent's reflection into a background call every 20 turns, with 80% fewer reflection tokens. D3 runs two accounts whose weekly resets fall on different days, so one always has budget and full outages end. D4 paces requests with a token bucket at about 80% use; lockouts fell from 3 in the first month to zero in 8 weeks.
show summary
Some operations must happen but don't need to happen every turn.
D1. Cron Priority Tiers150 wordsSummaryAutomated jobs get tiers by importance. Critical jobs (morning briefing, security scan) run on Sonnet with low thinking and are never skipped; standard jobs (email check, calendar sync) run on Haiku and are skipped above 85% weekly utilization; background jobs (log rotation, memory cleanup) run on Haiku and are skipped above 70%. When budget is tight, lower tiers get cheaper models or do not run, which saves 15–20% of the automated budget in those weeks. It is in use. The tiers decide which routing rules apply and take into account which account still has budget.
show summary
Mechanism: Not all automated jobs are equally important. A morning briefing that the user sees immediately is high-priority; a log cleanup that nobody notices is low-priority. Assign tiers and allocate budget accordingly:
cron-tiers:
critical: # Morning briefing, security scan
model: claude-sonnet
thinking: low
skip-when-budget: never
standard: # Email check, calendar sync
model: claude-haiku
thinking: off
skip-when-budget: >85% weekly utilization
background: # Log rotation, memory cleanup
model: claude-haiku
thinking: off
skip-when-budget: >70% weekly utilizationWhen budget is tight (high weekly utilization), lower-priority jobs get cheaper models or are skipped entirely. Critical jobs always run.
Savings: Prevents low-value work from consuming budget needed for high-value work. During budget pressure weeks, skipping background jobs saves 15–20% of automated budget.
Status: [Y] Implemented. Priority tiers defined in cron configuration.
Interaction effects: Synergistic with A1 (model routing) — priority tiers determine which routing rules apply. Interacts with D3 (dual-account staggering) — priority decisions consider which account has remaining budget.
D2. Background Review Agent (Amortized Reflection)173 wordsSummaryToday the agent reflects (writes down lessons, updates memory, improves skills) a little in every turn. D2 would move this to a cheap background call every N turns that reviews the recent conversation and updates memory in one go: 2,000 tokens every 20 turns (20K a day) instead of 500 every turn (100K a day at 200 turns). That is 80% fewer reflection tokens, about $1.20 a day at $15 per million. It is designed, not built. It would write to B5's staging area to keep the cache stable and could run through the batch API.
show summary
Mechanism: The agent's self-improvement loop (documenting lessons, updating memory, refining skills) is valuable but expensive if done every turn. Instead, batch reflection into a background process:
Every N turns (or on a timer), a cheap background LLM call:
- Reviews the last N turns of conversation
- Extracts lessons, patterns, and memory-worthy facts
- Updates memory files with consolidated insights
- Identifies skill improvements or prompt refinements
This amortizes the cost of reflection across many turns. Instead of spending 500 output tokens on reflection every turn (100K tokens/day at 200 turns), spend 2,000 tokens every 20 turns (20K tokens/day). 5× reduction in reflection cost.
Expected savings: 80% reduction in reflection-related output tokens. At $15/MTok output: saves ~$1.20/day.
Status: [Designed], not implemented. Currently, the agent reflects inline — every turn includes some self-monitoring overhead.
Interaction effects: Synergistic with B5 (frozen snapshot) — background reflection writes to staging area rather than live memory, preserving cache stability. Synergistic with E1 (batch API) — reflection jobs can use the batch API for additional savings.
D3. Dual-Account Pool Staggering168 wordsSummaryFlat-rate plans reset weekly, and one account runs out mid-week, leaving the agent degraded for 2–3 days. With two accounts that reset on different days (for example Sunday and Friday), one always has budget left, and the gateway sends each request to the account with more capacity. It cuts no cost per turn; it removes full outages from running out of budget. It is in use, the gateway tracks use per account, and pacing (D4) is set per account too.
show summary
Mechanism: Anthropic's flat-rate plans reset weekly. A single account hits its limit mid-week, leaving the agent degraded for 2–3 days. Two accounts with staggered reset days (e.g., one resetting Sunday, one resetting Friday) keep at least one account with budget at all times.
Week timeline:
Mon Tue Wed Thu Fri Sat Sun
[--- Account A (reset Sun) ----]
[--- Account B (reset Fri) ----]
If A is exhausted by Wednesday, B still has 2 days of budget.
If B is exhausted by Tuesday, A still has 5 days of budget.The gateway routes requests to whichever account has more remaining capacity.
Savings: Eliminates complete outages from budget exhaustion. Not a per-turn cost reduction but a reliability improvement that enables all other techniques to operate continuously.
Status: [Y] Implemented. Flat-rate subscriptions with staggered resets. Gateway tracks utilization per account.
Interaction effects: Interacts with D4 (token bucket pacing) — pacing targets are per-account. Interacts with D1 (priority tiers) — when one account is near exhaustion, the system shifts to the other for high-priority work.
D4. Token Bucket Pacing169 wordsSummaryRate limits punish bursts: staying above the limit brings a 5-hour cooldown. A token bucket smooths use. It refills at the account's input-tokens-per-minute limit, each request drains it, and when it would fall below 20% the request waits or goes to another account, aiming at about 80% sustained use. Before pacing, the first month saw 3 lockouts; since then, zero in 8 weeks. It is in use, per account, and the cost is a short delay in busy periods.
show summary
Mechanism: Anthropic's rate limits impose harsh penalties for bursts: sustained utilization above the limit triggers a 5-hour cooldown. The token bucket algorithm smooths utilization:
- Maintain a virtual "bucket" of tokens that refills at a constant rate (matching the account's ITPM limit)
- Each request drains the bucket by its token count
- If the bucket would go below 20% capacity, delay the request or route to a different account
- Target: ~80% sustained utilization, leaving headroom for bursts
This prevents the catastrophic 5-hour lockout that occurs when the agent processes several large-context requests in quick succession.
Savings: Prevents lockout events that create hours of zero availability. Each avoided lockout preserves 5 hours of agent availability. In our first month, we triggered 3 lockouts before implementing pacing. Since pacing: zero lockouts in 8 weeks.
Status: [Y] Implemented. Gateway tracks per-account token consumption and enforces pacing.
Interaction effects: Synergistic with D3 (dual-account staggering) — pacing operates per-account, and cross-account routing provides overflow capacity. Tension with responsiveness — paced requests may experience slight delays during high-utilization periods.
Category E: Billing Arbitrage — Exploit Pricing Structure300 wordsSummaryThese techniques use features of the billing itself. E1 sends work that needs no live answer, such as nightly memory consolidation, to the batch API at half price: if 20% of daily tokens qualify, total cost falls 10%. E2 hands big tasks to a sub-agent that starts from a clean context of about 15K tokens and returns a short result, so the parent's context does not grow; one code review saves about $1.80 on Sonnet. Both are in use.
show summary
These techniques exploit specific features of billing structures to reduce effective cost.
E1. Batch API for Non-Interactive Work112 wordsSummaryBatch APIs cost 50% less, answer later and have their own rate limits, so work that needs no live answer goes there: nightly memory consolidation, document summaries queued during the day, bulk analysis, memory file optimization. If 20% of daily tokens qualify, total cost falls 10%. It is in use, with a queue that collects work during the day for the night. Batch results come late, so they cannot inform a conversation in progress.
show summary
Mechanism: Batch APIs offer 50% cost reduction with higher latency and use separate rate limit pools. Any work that doesn't need real-time response can be routed to the batch API:
- Nightly memory consolidation
- Document summarization queued during the day
- Bulk analysis tasks
- Memory file optimization
Savings: 50% reduction on batch-eligible work. If 20% of daily tokens are batch-eligible: 10% overall cost reduction.
Status: [Y] Implemented. Nightly consolidation jobs use the batch API. A queue system stages work during the day for batch processing overnight.
Interaction effects: Synergistic with D2 (background reflection) — reflection is a prime candidate for batch processing. Tension with freshness — batch results are delayed, so they can't inform immediate conversations.
E2. Sub-Agent Fresh Context176 wordsSummaryBig tasks (code review, document analysis, multi-step research) go to a sub-agent that starts with a clean context of about 15K tokens, the system prompt only, instead of working inside the parent's 80K. It returns a short result of a few hundred tokens and ends. A code review that would have added 30K tokens to the parent, billed for 20 more turns, saves 600K input tokens, $1.80 on Sonnet per delegation. OpenClaw does this by default. Sub-agents can run on cheaper models and cache their own prompt; spawning them has its own overhead.
show summary
Mechanism: When a task requires significant work (code review, document analysis, multi-step research), spawn a sub-agent with a clean context instead of doing the work in the parent's bloated context.
Parent context: 80K tokens. Sub-agent starts at: ~15K tokens (system prompt only). The sub-agent does its work in a fresh context, returns a concise result, and terminates. The parent incorporates the result — a few hundred tokens instead of the 30K tokens the work would have added to the parent's context.
Savings: Dramatic for tool-heavy tasks. A code review that would add 30K tokens to parent context (and be billed every subsequent turn) instead adds only the 500-token summary. At 20 remaining turns in the parent session: saves 30K × 20 = 600K input tokens = $1.80 (Sonnet) per delegation.
Status: [Y] Implemented. OpenClaw's sub-agent spawning creates clean context by default.
Interaction effects: Synergistic with A1 (model routing) — sub-agents can use cheaper models than the parent. Synergistic with B1 (caching) — sub-agent's system prompt is cached independently. Tension with orchestration overhead — spawning and communicating with sub-agents has its own cost.
Category F: Security and Reliability197 wordsSummaryThis category protects the cost machinery itself. F1, designed but not built, would scan every write to memory for planted instructions (prompt-like strings, large base64 payloads, known injection patterns). Memory goes into every future system prompt, so a planted instruction could drive expensive output or corrupt the files the other techniques rely on.
show summary
Not directly about cost reduction, but about protecting the cost optimization infrastructure from compromise.
F1. Security Scanning on Memory Writes183 wordsSummaryMemory files go into the system prompt, so an attacker who gets text into memory, through a message, a tool output or a web page, plants instructions in every future session. F1 would scan every memory write with simple patterns: block prompt-like strings (<system>, [INST], you are, ignore previous), large base64 payloads and known injection patterns, and flag other suspicious writes. It matters for cost because injected memory can drive expensive output or corrupt the files the other techniques depend on. It is designed, not built; for now the agent's own judgment is the only guard. B5's staging area would be a natural place for the scan.
show summary
<system>, [INST], you are, ignore previous), large base64 payloads and known injection patterns, and flag other suspicious writes. It matters for cost because injected memory can drive expensive output or corrupt the files the other techniques depend on. It is designed, not built; for now the agent's own judgment is the only guard. B5's staging area would be a natural place for the scan.Mechanism: Memory files are injected into the system prompt. If an attacker can write to memory files (through prompt injection in user messages, tool outputs, or web content the agent processes), they can inject instructions into the system prompt of every future session. This is a persistent prompt injection — far more dangerous than a single-session attack.
Defense: regex-based scanning of all memory writes:
- Block strings matching system prompt patterns (
<system>,[INST],you are,ignore previous) - Block base64-encoded payloads above a size threshold
- Block known prompt injection patterns from public datasets
- Alert on suspicious writes that don't match known patterns
Cost relevance: A successful memory injection could cause the agent to generate expensive outputs (long responses, unnecessary API calls, data exfiltration attempts) or corrupt the memory files that other Budget Prompting techniques depend on. Security is a prerequisite for sustainable cost optimization.
Status: [Designed], not implemented. Currently relies on the agent's own judgment to avoid writing suspicious content to memory.
Interaction effects: Interacts with B5 (frozen snapshot) — staging area provides a natural checkpoint for scanning writes before they're incorporated into the next session's snapshot.
4. Architecture — How Techniques Compose in TinkerClaw1,352 wordsSummaryEach request is classified, given a context built from a frozen memory snapshot and search, pruned or compacted if too big, checked against the cache and the pacing, and run with its thinking budget; its memory writes are then staged and scanned. As use over the last 7 days climbs through five levels, from green below 50% to critical above 95%, work moves to cheaper models, thinking is cut and low-priority jobs are dropped. Everything sits in rings around one aim: keep the cached start of the prompt unchanged. Caching and the frozen snapshot reinforce each other most, but the snapshot hides the agent's own memory writes until the next session. Claude Code adds two stop rules: quit when returns diminish, and keep the output cap low at first.
show summary
The 20 techniques described above don't operate in isolation. They form an integrated system where each technique's effectiveness depends on others. This section describes how they compose in the TinkerClaw architecture.
4.1 The Request Lifecycle242 wordsSummaryEach request passes through seven steps that tie the techniques together. It is classified for model, thinking budget and priority (A1). Its context is built from a frozen memory snapshot and memory search (B5, B3), then pruned, compacted or moved to a new session if a per-call measure shows it is too big (B6, B4, B7, B2). The cached prompt is checked (B1), and pacing decides whether the request goes now, waits or moves to the other account (D4, D3). The model runs with its thinking budget and may answer silently (A2, C1). Afterwards, memory writes are staged and scanned (B5, F1), reflection is queued when due (D2) and the pacing count is updated. A figure shows the flow.
show summary
Every incoming request flows through the Budget Prompting pipeline:
1. REQUEST ARRIVES
↓
2. CLASSIFY (model routing: A1)
→ Determine: model, thinking budget, priority tier
↓
3. CONTEXT ASSEMBLY
a. Load frozen memory snapshot (B5, or live memory if B5 not implemented)
b. Inject via memory search, not bulk load (B3)
c. Check a per-call context snapshot (never a turn-aggregate `usage` field):
- If > threshold: trigger surgical pruning (B6)
- If still > threshold: trigger compaction (B4, B7)
- If > hard limit: start new session (B2)
↓
4. CACHE CHECK
a. System prompt prefix → check cache (B1)
b. If cache miss: absorb cost, cache for subsequent turns
↓
5. PACING CHECK (D4)
a. Token bucket has capacity? → proceed
b. Bucket low? → route to alternate account (D3) or delay
↓
6. MODEL INFERENCE
a. Apply thinking budget (A2)
b. Generate response
c. If NO_REPLY/HEARTBEAT_OK (C1) → minimal output
↓
7. POST-RESPONSE
a. Memory writes → staging area (B5) + security scan (F1)
b. Reflection counter++ → if threshold reached, queue background review (D2)
c. Update token accounting for pacing (D4)
4.2 Budget Pressure Cascade336 wordsSummaryAs use of the plan rises, cost cutting gets harsher in five levels, measured as a 7-day rolling average per account. Below 50% (green) everything runs normally. At 50–70% (yellow), background cron jobs move to Haiku and async work prefers the batch API. At 70–85% (orange), background jobs are skipped, standard cron jobs may be, and interactive work stays on Sonnet. At 85–95% (red), interactive work drops to Sonnet, automated work runs on Haiku and metered APIs stop. Above 95% (critical), everything runs on Haiku with thinking off and only critical jobs run. Each level keeps the limits of those below it, and the gateway picks the account with the lowest use. The paper gives this as pseudocode, a table and a figure.
show summary
When utilization rises, the system progressively activates more aggressive cost reduction. The following pseudocode formalizes the cascade:
ALGORITHM: BudgetPressureCascade(utilization, task)
-----------------------------------------------------
Input: utilization in [0, 1] (7-day rolling average across all accounts)
task: {type, priority, model_preference, thinking_budget}
Output: routed_task: {model, thinking, should_execute}
if utilization < 0.50: # GREEN — full capability
routed_task.model ← task.model_preference
routed_task.thinking ← task.thinking_budget
routed_task.should_execute ← true
elif utilization < 0.70: # YELLOW — conserve background
if task.type = "cron" AND task.priority = "background":
routed_task.model ← HAIKU
routed_task.thinking ← OFF
else:
routed_task.model ← task.model_preference
routed_task.should_execute ← true
elif utilization < 0.85: # ORANGE — skip low-priority
if task.priority = "background":
routed_task.should_execute ← false; return
if task.type = "cron":
routed_task.model ← HAIKU; routed_task.thinking ← OFF
else:
routed_task.model ← min(task.model_preference, SONNET)
elif utilization < 0.95: # RED — degrade interactive
routed_task.model ← SONNET if task.type = "interactive" else HAIKU
routed_task.thinking ← LOW if task.type = "interactive" else OFF
routed_task.should_execute ← task.priority >= "standard"
else: # CRITICAL — survival mode
routed_task.model ← HAIKU
routed_task.thinking ← OFF
routed_task.should_execute ← task.priority = "critical"
return routed_task| Utilisation | Level | Actions |
|---|---|---|
| < 50% | GREEN | Normal operation. All features enabled. |
| 50–70% | YELLOW | Background cron jobs use Haiku. Batch API preferred for async work. |
| 70–85% | ORANGE | Standard cron jobs may be skipped. Interactive stays on Sonnet. |
| 85–95% | RED | Interactive drops to Sonnet. All automated work on Haiku. No metered API calls. |
| > 95% | CRITICAL | Haiku for everything. Only critical cron jobs run. Extended thinking off globally. |
This cascade is monotonic — each level includes all actions from lower levels. The utilization metric is a 7-day rolling average computed per-account, with the gateway selecting the account with the lowest utilization for each request. Recovery happens when utilization drops (e.g., account reset, sustained lower usage).

4.3 The Caching Stability Core194 wordsSummaryThe whole design rests on prefix stability: keeping the start of the prompt unchanged so the cache keeps hitting. The techniques sit in rings around that core. Ring 0 builds the stable prefix: caching (B1) and the frozen memory snapshot (B5). Ring 1 shrinks the context without touching the prefix: on-demand retrieval, pruning, iterative compression and the rolling window. Ring 2 decides how requests are handled: model routing, account staggering and pacing. Ring 3 limits output: thinking control and silent replies. Ring 4 spreads cost over time: priority tiers, background reflection and the batch API. Ring 5 protects the system: security scanning and personality reinjection. A figure draws the rings.
show summary
The most important architectural principle is prefix stability. The entire cost optimization structure rests on maintaining high cache hit rates for the system prompt. Techniques are organized in concentric rings around this core:
Ring 0 (Cache Foundation): B1 (system prompt caching) + B5 (frozen snapshot injection). These establish the stable prefix.
Ring 1 (Context Management): B3 (on-demand catalog retrieval), B6/B6a (surgical and content-type-specific pruning), B7 (iterative compression), B8 (rolling window). These minimize context without disturbing the prefix.
Ring 2 (Request Routing): A1 (model routing), D3 (account staggering), D4 (pacing). These determine how requests are processed.
Ring 3 (Output Control): A2 (thinking control), C1 (silent reply). These minimize output cost.
Ring 4 (Temporal Smoothing): D1 (priority tiers), D2 (background reflection), E1 (batch API). These spread cost over time.
Ring 5 (Protection): F1 (security scanning), B9 (personality reinjection). These protect the system's integrity.

4.4 Interaction Matrix190 wordsSummarySome pairs of techniques do more together than apart. The strongest is caching with a frozen memory snapshot (B1 + B5). The others: a cheap model with thinking off and a silent reply give the cheapest possible turn; pruning, compaction and iterative summaries form one staged pipeline; sub-agents run on cheap models; and two accounts with pacing protect availability. Four pairs pull against each other: the frozen snapshot hides the agent's own memory writes until the next session, frequent session restarts disrupt the conversation, pacing can delay replies, and cheap models cost quality, since Haiku is noticeably weaker than Sonnet on complex tasks. A figure maps these links.
show summary
Some technique pairs are synergistic (combined effect > sum of parts), some are complementary (independent benefits), and some create tension (one undermines the other):
Strong synergies:
- B1 + B5: Frozen snapshots maximize cache hit rate. This is the highest-value pair.
- A1 + A2 + C1: Cheap model + no thinking + silent reply = minimum possible cost per turn.
- B6 + B4 + B7: Surgical pruning → compaction → iterative compression forms a staged cost reduction pipeline.
- E2 + A1: Sub-agents on cheap models — delegated work at minimum cost.
- D3 + D4: Dual accounts + pacing — availability insurance.
Tensions:
- B5 (frozen snapshot) vs. memory freshness: The agent can't see its own memory writes within a session.
- B2 (session restart) vs. conversational flow: Frequent restarts feel disruptive to users.
- D4 (pacing) vs. responsiveness: Paced requests may be delayed.
- A1 (cheap models) vs. quality: Haiku is noticeably less capable than Sonnet for complex tasks.

4.5 Knowing When to Stop — Budget Triggers from the Claude Code Source359 wordsSummaryThe cascade decides how to process a request; the Claude Code source adds when to stop generating. It stops continuing at 90% of the token target, or when successive continuations each produce under 500 tokens. The check is cheap, since it reads counters already kept, and the paper recommends adding it next to its size thresholds. Each counter needs a clear unit: a context threshold must use a per-call measure, never a turn total. Claude Code also starts with a low output cap, reportedly about 8K tokens against a p99 output near 5K (a figure from secondary analysis), and retries once at a higher ceiling, because a large cap reserves server capacity even for short replies.
show summary
MYELIN's budget cascade (4.2) decides how to process a request. The leaked Claude Code source adds a dimension we under-modeled: when to stop generating at all. Two mechanisms are worth importing.
Diminishing-returns detection. query/tokenBudget.ts tracks token consumption per agent turn and stops continuing when the agent stalls. The constants are explicit: COMPLETION_THRESHOLD = 0.9 (stop when 90% of the token target is reached) and DIMINISHING_THRESHOLD = 500 (when successive continuations each produce under 500 tokens, treat it as diminishing returns and stop). The continuation message even reports percentage used and instructs the agent to keep working rather than summarize prematurely. This is a productivity trigger, orthogonal to the token-count triggers in B4/B6: compact or stop not only when context is large, but when each additional turn is buying little. It is cheap — it reads counters already being tracked — and it directly attacks the wasted-call problem from Section 1. We recommend adding a diminishing-returns counter alongside MYELIN's existing size thresholds.
The counters must also carry clear semantics. A completion fraction can use a turn-level generation budget, but a context-pressure threshold must use a per-call context snapshot. Reusing a turn aggregate for both silently changes the unit while leaving the number plausible-looking—the metrology equivalent of measuring a doorway in kilograms.
Output-token capping (slot reservation). Requesting a large max_tokens is not free: the server reserves output slots up front, so an over-large cap reduces throughput even when the actual response is short. The Claude Code analysis reports a conservative default output cap (on the order of 8K tokens, against a p99 actual output near 5K) with a single clean retry at a larger ceiling when the cap is hit; the source confirms a MAX_NON_STREAMING_TOKENS = 64_000 constant and per-model resolution via getMaxOutputTokensForModel() for that escalation path. (The 8K default figure itself is from secondary analysis of the dump, not a line we verified, so we report it as such.) The principle is sound regardless of the exact number: start the output cap conservative, escalate on demand. This belongs in MYELIN's output economics (Category C) as a complement to thinking control — A2 limits reasoning tokens, output capping limits the reservation.
5. Evaluation Methodology984 wordsSummarySavings are measured per model call, not per turn, since one turn can hold many calls and a turn total misleads. Each call records fresh input, cache reads, cache writes and output separately, and a missing count stays missing, never zero. The cost metrics are cache hit rate, cache reads per write, compactions per day, tokens and cost per turn, daily cost, and useful work per rate-limit token. Quality is tracked with SyncScore (how well replies match the configured personality, target above 0.85), task completion, memory recall and latency. A controlled study is planned: a baseline week with everything off, categories switched on one at a time, then the full system, then high-impact techniques switched off one by one.
show summary
Measuring the effectiveness of Budget Prompting requires metrics that capture both cost reduction and quality preservation. We propose the following evaluation framework.
5.1 Cost Metrics741 wordsSummaryEvery cost metric is computed per model call, never from a total over a turn, because one turn can hold many calls. Each call's record keeps fresh input, cache read, cache write and output as four separate numbers, and a count the provider did not report is left out, never written as zero. Before each call the context is itemised by source, and budget and cache decisions are stored as rows beside the calls. The metrics are the cache hit rate (the main one on a flat-rate plan), cache reads per write (10.6× in July), compactions per day, tokens per turn, cost per turn and per day, and useful work per rate-limit token.
show summary
PartOne record per model call210 wordsSummaryAll cost metrics are counted per model call, because one turn can hold many calls (tool rounds, retries, sub-agent hand-offs) and a sum over them is neither the context in use nor the cost of any one request. Each call's record is written in three steps: when the request leaves; when the provider reports fresh input, cache read, cache write and output, kept as four separate numbers; and when the call ends. A count the provider did not report is left out, never written as zero.
show summary
The unit of measurement is the model call. A conversational turn can hold many internal calls (tool rounds, retries, sub-agent hand-offs), and a usage figure summed over them is neither the resident context nor the cost of any one request. Section 6.4 shows what goes wrong when a gate reads such a sum. Every metric below is therefore computed from a per-call record with three phases:
- Send. Written at the moment the request leaves, with the call's index within its lane and its provenance (which session, which run, which round).
- Usage. Written when the provider reports tokens. Fresh input, cache read, cache write and output are stored as four separate parts and never pre-summed, so cache share and fresh-input share can be recomputed later without guessing how a total was formed.
- End. Written when the call closes, with its outcome.
A count the provider did not report is left out of the record, never written as zero. A zero claims a measurement; an absence admits there was none, and every ratio below must be able to tell the two apart. An agent runtime that exposes no pre-request hook cannot write the send phase; its records start at usage, and latency metrics must skip it rather than fill the gap.
PartContext make-up and eviction savings295 wordsSummaryBefore each call, the context is listed by source (system prompt, the standing rules injected on every call, memories, history, tool results, the current request) and stored, including the first call of a session, the most expensive one. Budget decisions and cache reads and writes are stored as rows next to the call records, and the cache share counts only calls that measured their cache reads. The saving from dropping part of the context is its size summed over the calls that follow; an earlier formula overstated it and is not used.
show summary
Pre-call composition. Before each call, the context about to be sent is itemised by contributor: system prompt, standing rule pack (the agent's ethical rules and conventions, injected on every call), injected memories, conversation history, tool results, and the current request. The composition is stored per (run, round), so a revision can cite what the input of a given turn was made of, contributor by contributor, from rows written before the call rather than reconstructed after it. The rule pack gets its own line because it is fixed per session but large, and it is the slab an operator is most tempted to grow. The first call of a session must be itemised as well. It carries the coldest cache and the full prefix, and a sampler that skips it under-reports exactly the expensive case.
Ledgers as rows. The context-budget ledger (every eviction, compaction and trigger decision) and the prompt-cache ledger (every cache read and write) are written as structured outcome rows in the same store as the per-call record, with past log lines backfilled, so one query can join a budget decision to the calls before and after it. The cache-read share is computed only over calls that measured their cache reads; a call with no cache figure is excluded from both numerator and denominator instead of counting as a miss.
Savings from an eviction. When a slab is dropped from context, its saving is its size summed over the calls that follow the drop, for as long as the session would otherwise have carried it. An earlier formula (tokens evicted × turns in the session) also charged each drop against the turns before it and overstated the saving. Figures computed that way are not comparable with this definition and are not used in this paper.
PartCache and compaction counts79 wordsSummaryThree counts track how well the cache is reused: the cache hit rate, the main efficiency measure on a flat-rate plan; cache reads per write, which shows the prefix changing sooner than the hit rate does (10.6× in July); and compactions per day, with what triggered each, because a false compaction can wreck cache reuse even when the summary itself is cheap.
show summary
Cache hit rate (CHR). Percentage of prompt input served from cache across requests. Under a flat-rate subscription it is the primary efficiency metric because one prefix rebuild can dominate the small fresh-input slab.
Cache reads per write. Cache-read tokens divided by cache-creation tokens. This exposes prefix churn earlier than hit rate: the July measurement was 10.6×.
Compactions per day. Counted with trigger source and outcome. False compactions can destroy prefix reuse even when the summarization work is cheap.
PartTokens per turn and hit-rate formula80 wordsSummaryTokens per turn is kept to describe turns, not as the main cost measure, and is summed from the turn's call records, never read from a turn-level usage field. It splits into system prompt, standing rules, conversation and tool output on the input side, and thinking and visible reply on the output side. The cache hit rate is defined as cached input tokens over cached input plus uncached system-prompt tokens.
show summary
Tokens per turn (TPT). Average input + output tokens per conversational turn, retained as a descriptive metric rather than the primary cost proxy. It is the sum of the turn's per-call records, never a turn-aggregate usage field. Its input side is decomposed with the pre-call composition above:
- System prompt tokens (fixed per session)
- Standing rule pack tokens (fixed per session)
- Conversation context tokens (growing)
- Tool output tokens (variable)
- Thinking tokens (output, variable)
- Visible response tokens (output, variable)
CHR = cached_input_tokens / (cached_input_tokens + uncached_system_prompt_tokens)PartCost and efficiency per turn and day77 wordsSummaryCost per turn adds uncached input, cached input and output, each at its own price, and daily cost is the total spend per 24 hours. For flat-rate plans, utilization efficiency asks how much useful work each rate-limit token bought: 150K tokens to answer "yes" scores low, 20K tokens for the same answer scores high.
show summary
Cost per turn (CPT). Dollar cost per conversational turn, accounting for cached vs. uncached pricing, model tier, and output tokens.
CPT = (uncached_input × rate_uncached) + (cached_input × rate_cached) + (output × rate_output)Daily cost (DC). Total API cost per 24-hour period. The bottom-line metric.
Utilization efficiency (UE). For flat-rate plans: useful work accomplished per rate-limit token consumed. A turn that processes 150K tokens to answer "yes" has low UE; a turn that processes 20K tokens for the same answer has high UE.
5.2 Quality Metrics123 wordsSummarySavings count only if the agent stays as good, so four things are tracked. SyncScore measures how closely replies match the configured personality, on a 0–1 scale with a target above 0.85. Task completion rate comes from thumbs up or down and automated checks such as cron job success. Memory recall accuracy comes from periodic quizzes on earlier topics. Response latency, the time to the first token, is watched because pacing and model routing can raise it.
show summary
Cost reduction is worthless if it degrades the agent. We track:
SyncScore. A personality-coherence metric: it measures how well the agent's responses match its configured personality across sessions by scoring live output against the personality specification. Range 0–1, target >0.85.
Task completion rate (TCR). Percentage of user requests successfully fulfilled. Measured by user feedback (thumbs up/down) and automated checks (e.g., cron job success rate).
Memory recall accuracy (MRA). When the agent should reference a previously stored memory, does it retrieve and apply it correctly? Measured by periodic "memory tests" — asking the agent about previously discussed topics.
Response latency (RL). Time from request to first response token. Pacing (D4) and model routing (A1) can increase latency; this must be monitored.
5.3 Proposed Evaluation Protocol98 wordsSummaryA controlled study is planned for a later revision: a baseline week with every technique off, then one category switched on at a time, then the full system for two weeks, then single high-impact techniques (B5, B1, A1) switched off to measure each alone. With one user and a workload that varies by day, it would compare the same weekday across weeks and report confidence intervals.
show summary
A controlled study, planned for a future revision, will follow this protocol:
- Baseline week: Disable all Budget Prompting techniques. Record daily cost, TPT, CHR, and quality metrics.
- Incremental activation: Enable techniques one category at a time, measuring the delta.
- Full system: Enable all techniques for two weeks. Measure steady-state metrics.
- Ablation studies: Disable individual high-impact techniques (B5, B1, A1) to measure their isolated contribution.
Challenges: this is a single-user system. Workload varies day to day. Statistical significance requires careful design. We plan to use paired comparisons (same-day-of-week across different weeks) and report confidence intervals.
6. Results (Preliminary)1,085 wordsSummaryThe results are preliminary and come from production. Over 8 weeks in early 2026 the agent ran 180–220 turns a day at ~45K tokens of context, for $400 a month in flat-rate subscriptions plus ~$30 metered, and pacing ended rate-limit lockouts. In July the cache hit rate was 91.1%, so the frozen memory snapshot became insurance, and no combined gain is projected for the unbuilt techniques. Savings per technique are estimates. The worst failure was a gate that read a turn total as the context size and set off 29 needless compactions in seven days. Claude Code's leaked source matches six of the paper's design claims, which supports the architecture but not the size of the savings.
show summary
This section contains preliminary data from production operation. Controlled benchmarks are planned for a future revision.
6.1 Cost Overview88 wordsSummaryOver 8 weeks, February 1 to March 28, 2026, with most category A–E techniques on, the agent handled 180–220 turns a day with an average context of ~45K tokens and a median session of 12 turns. It cost $400 a month in flat-rate subscriptions plus ~$30 a month in metered GPT-4o calls. Rate-limit lockouts went from 3 in the first 2 weeks to 0 in 8 weeks once pacing was on. Measured on 2026-07-25, the cache hit rate was 91.1% aggregate (98.6% median), with 10.6 cache reads per write.
show summary
Over the period February 1 – March 28, 2026 (8 weeks of operation with most Category A–E techniques active):
| Metric | Value |
|---|---|
| Average daily turns | 180–220 |
| Average context at turn | ~45K tokens |
| Median session length | 12 turns |
| Prompt-cache hit rate (2026-07-25) | 91.1% aggregate; 98.6% median |
| Cache reads per write (2026-07-25) | 10.6× |
| Monthly flat-rate cost | $400/mo |
| Monthly metered API cost | ~$30/mo (GPT-4o for cross-model work) |
| Rate limit lockouts (since pacing) | 0 in 8 weeks |
| Rate limit lockouts (before pacing) | 3 in first 2 weeks |
6.2 Per-Technique Attribution (Estimated)98 wordsSummaryBecause the techniques interact, savings per technique are best estimates. With high confidence: model routing saves 25–40% of the cost of automated work, caching saves $8–10 a day at a full hit rate, two staggered accounts end 2–3 days a week of outage, and pacing ends the 5-hour lockouts. With medium confidence: thinking control saves $5–10 a day in output, session management 2–4× per turn, silent replies $5–8 a day, and sub-agents $1–3 per delegation at about 5 a day.
show summary
Precise per-technique attribution is difficult because techniques interact. These are best estimates:
| Technique | Estimated Savings | Confidence |
|---|---|---|
| A1. Model routing | 25–40% of automated work cost | High |
| A2. Thinking control | $5–10/day equivalent in output tokens | Medium |
| B1. System prompt caching | $8–10/day at full cache hit rate | High |
| B2. Session management | 2–4× per-turn cost reduction | Medium |
| C1. Silent reply | $5–8/day in avoided output | Medium |
| D3. Dual-account staggering | Eliminates 2–3 day/week outages | High |
| D4. Token bucket pacing | Eliminates 5-hour lockouts | High |
| E2. Sub-agent fresh context | $1–3/delegation event, ~5/day | Medium |
6.3 Projected Impact of Unimplemented Techniques108 wordsSummaryThe July measurements changed the order of the techniques still to build. The rolling window (B8) would give the context a fixed budget, iterative summaries (B7) would stop summaries growing, tool-output pruning (B6) could reach about 21% of the audited Read bytes and make sessions last longer, the frozen snapshot (B5) would protect a hit rate already at 91.1%, and background reflection (D2) would batch reflection every 20 turns for 80% savings. No combined multiplier is projected: the July audit undid the earlier premises for B5 and B6, and no controlled measurement of them together exists.
show summary
The July measurements reorder the unimplemented techniques (see Section 8.5 for limitations):
| Technique | Current | Projected | Expected Impact |
|---|---|---|---|
| B8 (rolling window) | Monotonic growth | Fixed budget | Bounds conversation and tool history |
| B7 (iterative summary) | One-pass summaries | Progressively smaller summaries | Bounds summary growth |
| B6 (surgical pruning) | Raw tool output retained | ~21% of audited Read bytes addressable | Extends session life |
| B5 (frozen snapshot) | CHR already 91.1% | Preserve high reuse | Prefix-instability insurance |
| D2 (background reflection) | Inline every turn | Batched every 20 turns | 80% reflection savings |
We do not project an aggregate multiplier from these techniques: the July audit invalidated the earlier B5 and B6 premises, and no controlled combined measurement exists.
6.4 Failure Modes Observed437 wordsSummaryMemory writes can break the cache, but with 91.1% hits the planned frozen snapshot (B5) is only a guard. Tool-heavy sessions can pass 150K tokens within 10 turns; even with low thinking, simple tasks sometimes produce 3,000–5,000 thinking tokens; switching accounts adds 2–5 seconds. The worst failure: a compaction gate read a turn total as the context size, saw impossible figures such as 6,448,106 tokens in a 1,000,000-token window, and in seven days set off 29 compactions at a median of about 5.5% of the window, each waiting 540 seconds before being discarded though the work took 19 ms. A related bug counted a ~15K-token system prompt as zero. After the fix, five sub-agent calls showed tool results at 28.0–51.9% of the context.
show summary
Cache instability from memory writes. Memory mutation can invalidate a cached prefix, but July telemetry measured 91.1% aggregate cache hits and 10.6 cache reads per write. We therefore treat B5 as a guard against regression rather than claiming an observed 5–15 daily cascades.
Context bloat from tool-heavy sessions. Sessions involving extensive web research or code review can hit 150K+ tokens within 10 turns. Each subsequent turn processes the full context. B6 (surgical pruning) and B8 (rolling window) address this.
Thinking budget overshoot. Even with thinking: low, some turns generate 3,000–5,000 thinking tokens for simple tasks. The model doesn't reliably honor thinking budget hints. Better heuristics for when to disable thinking entirely would help.
Cross-account routing latency. When switching between accounts due to rate limit pressure, there's a 2–5 second delay for connection setup. Minor but noticeable for interactive use.
The budget gate measured the wrong quantity. A compaction consumer compared persisted per-message usage against the context window even though that field was a turn aggregate across internal calls. It reported 6,448,106 tokens against a 1,000,000-token window and, in another event, 1,029,656 tokens (103%). Both are impossible as context snapshots. The original anatomy decoder for the second event reported 52,116 tokens, but it silently omitted every toolResult; 52,116 is therefore only a lower bound and the originally quoted 19.8× discrepancy is not a valid point estimate. The causal conclusion does not depend on that denominator: an aggregate larger than the window cannot be the resident context. In seven days this defect caused 29 compactions at a median roughly 5.5% of the independently estimated window; attempts waited 540 seconds and were discarded although compaction work took 19 ms.
The same class can under-count. A synthetic message role omitted from the estimator caused a 55,632–61,336-character system prompt (roughly 15K tokens) to score as zero. Budget gates must classify every message role, report unattributed bytes, and assert that measured totals are plausible before acting.
Corrected context anatomy. After the role classifier was fixed, five production sub-agent calls on July 28 recorded non-zero tool-result slabs. Total contexts ranged from 39,222 to 56,159 estimated tokens; tool results ranged from 11,117 to 29,122 tokens (28.0–51.9% of each context), while conversation history ranged from 4,778 to 6,336 tokens (8.5–16.0%). These are corrected measurements, but they are a five-call sub-agent sample—not a reconstruction of the earlier main-session event. The earlier 52,116-token composition and its percentages are retired rather than “corrected” by substitution.
6.5 Industrial Convergence as Validation338 wordsSummaryWith no controlled ablation, the best evidence available is that a second team, at the lab whose prices are being optimized against, built the same architecture independently. A table matches six claims to Claude Code's code: three-tier compaction, a static cached prefix, pruning tool output without breaking the cache, compaction that reuses the parent's cache, stopping when returns diminish (which the paper had under-modelled), and cheap gating of background consolidation. This supports the architecture, not the size of the savings. Claude Code's memory consolidation reads narrowly and writes little, where this paper's retrieval tries to miss nothing; the paper suggests finding candidates with embeddings and checking exact facts with grep.
show summary
We have no controlled ablation, so the strongest evidence available short of one is convergence: a second team, working independently at the lab that sets the pricing we are optimizing against, built the same architecture. The March 2026 Claude Code source exposure provides that evidence point by point.
| MYELIN claim | Claude Code shipping equivalent | Status of our claim |
|---|---|---|
| Three-tier compaction is the natural architecture (Sec 2.5) | MicroCompact / Session Compact / autoDream | Independently confirmed |
| Cache stability over a static prefix is the core lever (B1, 8.1) | SYSTEM_PROMPT_DYNAMIC_BOUNDARY, DANGEROUS_uncached… | Confirmed, enforced by API naming |
| Prune tool outputs without breaking cache (B6) | Cache-pinned MicroCompact, in-place stubs | Confirmed, more surgical than ours |
| Compaction can reuse the parent cache (B4) | runForkedAgent + CacheSafeParams | Confirmed; we had only theorized it |
| Stop spending when returns diminish (4.5) | DIMINISHING_THRESHOLD = 500, COMPLETION_THRESHOLD = 0.9 | New; we under-modeled this |
| Background consolidation gated cheaply (D2) | autoDream gates: time 24h → 5 sessions → lock | Confirmed gate ordering |
This is not proof that the techniques save what we claim — convergence validates the architecture, not the magnitudes. Two independent designs can be equally wrong about cost. But when the design space is large and two teams land in the same corner of it, the corner probably matters. We treat this as the next best thing to replication, and a direct prompt to run the ablations in Section 9.2.
A note on consolidation, relevant to any background memory-consolidation pass: autoDream's consolidation prompt (services/autoDream/consolidationPrompt.ts) runs an information diet we found instructive — "grep narrowly, don't read whole files," "look only for things you already suspect matter," convert relative dates to absolute, delete contradicted facts at the source, and keep the memory index under a hard line/byte cap with one-line entries. This is a precision-first stance (read little, write little) where MYELIN's embedding-based retrieval is recall-first. Neither is strictly better: grep-narrow risks missing context it didn't suspect; embedding-broad risks pulling in noise. A consolidation pass that uses embeddings to find candidates and grep to verify exact facts would combine the two.
7. Related Work1,314 wordsSummaryThe closest system is headroom, an open-source compression layer that keeps an index in the context and fetches the full content on demand, like the paper's pruning and retrieval designs; installed here it saw almost no traffic, but the paper plans to adopt its public benchmark test. Open skill collections load a skill only when it matches, as the paper does. Hermes Agent inspired three of the designed techniques but serves many users. MemGPT pages memory to fit more in, where this work cuts what the context costs. FrugalGPT routes single queries, not an agent's whole use. Caching research and ML cost work target the serving layer; this paper works one layer up. Claude Code is a parallel design for the same billing limits.
show summary
7.1 headroom (Closest Comparable System)301 wordsSummaryheadroom, an open-source context-compression layer for agents, is the system closest to this one. Its Compress, Cache, Retrieve design matches B6/B6a and part of B8: keep an index in the live context and fetch the full content when needed. It also has what this paper lacks, a reproducible test suite reporting 60–95% token savings at about zero accuracy loss on public benchmarks (GSM8K, TruthfulQA, SQuAD, BFCL); those benchmarks are stateless, while the paper's own traffic audit found about 21% of Read output compressible. Installed in this deployment, headroom recorded six lifetime requests and zero saved tokens, because live traffic ran through a subprocess that dropped the setting it needed. So every optimizer should count its requests and fail its health check at zero.
show summary
The single system most directly comparable to MYELIN is headroom (chopratejas, Apache-2.0, 24.7k★) — an open-source context-compression layer for agents. It is closer to our work than any other entry in this section, and we position against it directly.
What headroom shares with us. Its core abstraction, CCR (Compress, Cache, Retrieve), is convergent with our B6/B6a (surgical and typed compression) plus the retrieve-on-demand half of B8. It attacks the same problem we do — context that is paid for every turn but mostly unused — and it lands on the same answer: don't keep the raw payload in the live window, keep an index and fetch on demand.
What headroom has that we do not — and it is the right thing. headroom ships a reproducible stateless eval suite (python -m headroom.evals) reporting 60–95% token savings at ~0 accuracy delta on public benchmarks (GSM8K, TruthfulQA, SQuAD, BFCL). This is stronger quality evidence for its benchmark slice, but the saving is not a production-context estimate. Our stateful traffic audit found only about 21% of Read-output bytes addressable by all known compressors and a nearly equally large Bash-output slab outside their scope. We adopt headroom's accuracy-delta protocol while keeping its stateless compression ratio separate from our traffic-level measurement.
What deployment integration adds. We installed and enabled the compression layer, but its counter recorded only six lifetime requests and zero saved tokens because live traffic ran through a CLI subprocess that stripped the relevant environment variable. This null result does not contest the library benchmarks. It exposes a separate requirement: an optimizer must prove it is on the live traffic path. Installation, configuration, and registration are not liveness evidence. Every compressor and telemetry producer should publish a request counter and fail its health check when that counter remains zero over an active window.
7.2 Open Agent-Skill Collections (addyosmani/agent-skills, marketingskills, Journey)260 wordsSummaryOpen skill collections show the B3 idea spreading: load a short index and fetch a skill's full text only when it matches. addyosmani/agent-skills (56.8k stars) is built that way. The 44-framework coreyhaines31/marketingskills catalog is the paper's own measurement: a ~130-token router in place of ~915 tokens of descriptions, about 7× smaller. The Journey registry ships whole workflows, larger entries that gain even more from loading on demand. None of them deals with billing or caching; they confirm that the always-loaded prompt is made of separate catalogs that can each be dropped.
show summary
addyosmani/agent-skills (56.8k stars) is built that way. The 44-framework coreyhaines31/marketingskills catalog is the paper's own measurement: a ~130-token router in place of ~915 tokens of descriptions, about 7× smaller. The Journey registry ships whole workflows, larger entries that gain even more from loading on demand. None of them deals with billing or caching; they confirm that the always-loaded prompt is made of separate catalogs that can each be dropped.A second cluster of fresh open-source work is relevant not to compression but to B3 (on-demand catalog retrieval). These projects package agent capability as catalogs and increasingly converge on the load-on-demand discipline B3 formalizes for cost.
addyosmani/agent-skills(Addy Osmani, 56.8k★) is a discipline/skills plugin with substantial overlap (~70%) against the kind of skill libraries an agent like ours runs. Architecturally it is a slim index pointing at heavier per-topic skill bodies that load only when matched — the exact router pattern our catalog-eviction result (B3) quantifies in cost terms. It is the clearest external evidence that "don't concatenate every skill into the prompt" is becoming standard practice independent of any cost argument.coreyhaines31/marketingskills(44 frameworks) is the catalog we used as the measured anchor for B3's generalization: vendored and fronted by a ~130-token router skill in place of ~915 tokens of always-loaded descriptions, a ~7× reduction on that prefix slab with no loss of reach. It is both related work and a data point.- The Journey registry distributes complete agent workflows ("kits") rather than single skills. Its relevance to MYELIN is that a kit is a heavier always-loaded unit than a skill, which sharpens the case for B3-style on-demand loading: the larger the catalog entry, the more a code-side matcher that injects only the winning body saves per turn.
None of these projects address billing or caching directly; their contribution to this paper is empirical confirmation that the always-loaded prefix is composed of independently evictable catalog slabs, and that the router-over-bulk-load pattern is converging across the ecosystem.
7.3 Hermes Agent125 wordsSummaryHermes Agent (2025), aimed at enterprise deployments, shaped several proposals here: its "sealed prefix" is close to B5, its structured summaries of tool output inspired B6, and its background agents for reflection resemble D2. The setting differs: Hermes spreads cost across many users and runs as microservices, while this work serves one user who bears the whole cost, inside the single OpenClaw framework.
show summary
The Hermes Agent project (2025) explores similar territory with a focus on enterprise deployments. Their architecture influenced several of our proposed techniques:
- Prefix stabilization: Hermes documents the cache invalidation problem and proposes a "sealed prefix" approach similar to our frozen snapshot injection (B5). Their implementation uses a dedicated prefix manager service.
- Structured summarization: Hermes implements tool output replacement with structured summaries, inspiring our surgical pruning approach (B6).
- Background processing: Hermes uses asynchronous background agents for reflection and memory maintenance, similar to our amortized reflection proposal (D2).
Key differences: Hermes targets enterprise multi-user deployments where cost is spread across users. Our work targets single-user persistent agents where the full cost falls on one operator. Hermes uses a microservices architecture; we operate within the monolithic OpenClaw framework.
7.4 MemGPT100 wordsSummaryMemGPT (Packer et al., 2023) gives an agent a virtual memory hierarchy with load, save and search operations. Both keep the active context small, but MemGPT pages memory inside the context window to fit more in, while this paper manages context from outside (sessions, compaction, retrieval) to cut its cost. MemGPT does not cover prompt caching, model routing or billing, where much of the saving here comes from.
show summary
MemGPT (Packer et al., 2023) introduces the concept of a virtual memory hierarchy for LLM agents, with explicit memory management operations (load, save, search). Their approach shares our emphasis on keeping active context small, but differs in philosophy:
- MemGPT manages memory within the context window using virtual paging. We manage context externally through session management, compaction, and retrieval.
- MemGPT focuses on fitting more information into a fixed context window. We focus on minimizing the cost of the context window's contents.
- MemGPT doesn't address prompt caching, model routing, or billing arbitrage — the infrastructure-level techniques that provide much of our cost reduction.
7.5 OpenClaw67 wordsSummaryTinkerClaw is a fork of OpenClaw, which already provides compaction (B4), sub-agents with a clean context (E2), searchable memory files (B3) and session management (B2). This work adds model routing, caching, pacing and the proposed techniques (B5, B6, B7, B8, D2, F1).
show summary
TinkerClaw is a fork of OpenClaw, which provides the foundation for several Budget Prompting techniques:
- Built-in compaction (
/compress) — technique B4 - Sub-agent spawning with clean context — technique E2
- Memory file system with search — technique B3
- Session management — technique B2
Our contributions build on this foundation by adding model routing, caching optimization, pacing, and the proposed techniques (B5, B6, B7, B8, D2, F1) that address OpenClaw's remaining cost inefficiencies.
7.6 Prompt Caching Literature62 wordsSummaryAnthropic's caching documentation (2024) explains the mechanics, and Kwon et al. (2023) describe PagedAttention and vLLM's cache management at the serving level. The paper's addition sits one layer up: when an agent writes memory and how it lays out its prompt decide how well the cache works.
show summary
Anthropic's prompt caching documentation (2024) describes the mechanics but not the architectural implications for persistent agents. Kwon et al. (2023) describe PagedAttention and vLLM's approach to KV cache management at the serving level. Our contribution is identifying that agent-level architectural decisions (when to write memory, how to structure the prefix) have outsized impact on cache efficiency — a layer above the serving infrastructure.
7.7 FrugalGPT and LLM Cascades125 wordsSummaryFrugalGPT (Chen et al., 2023) cuts cost by passing a query to ever more expensive models until one is confident enough, close to A1 but per query. Budget Prompting covers an agent's whole use of the API: context, output, timing and billing. LangChain and LlamaIndex have early rolling windows and retrieval, related to B8, without a cost framework; AutoGPT and BabyAGI showed context bloat but answered it only with restarts.
show summary
FrugalGPT (Chen et al., 2023) addresses cost minimization for LLM APIs through model cascading — routing queries through progressively more expensive models until a confidence threshold is met. Their approach shares our emphasis on model routing (A1) but operates at the individual query level rather than the agent architecture level. Budget Prompting extends the cost optimization surface beyond model selection to include context management, output control, temporal amortization, and billing arbitrage — the full lifecycle of a persistent agent's interaction with the API.
LangChain and LlamaIndex implement early versions of rolling context windows and vector retrieval (related to our B8), but without the systematic cost-awareness framework we propose. AutoGPT and BabyAGI demonstrated the context bloat problem in autonomous agents but offered no architectural solutions beyond session restarts.
7.8 Process Supervision and Reasoning Economics69 wordsSummaryLightman et al. (2023) showed that checking each reasoning step can make models more accurate. Extended thinking produces such steps at 3–5× the input price, so the paper argues the reasoning budget should be set per task, not left to the model's default.
show summary
Lightman et al. (2023) showed that process-level supervision (verifying each reasoning step) can improve LLM accuracy. This is directly relevant to our thinking token economics (A2, C2): extended thinking generates verifiable reasoning steps, but at 3–5× the cost of input tokens. Budget Prompting's contribution is recognizing that reasoning budget should be explicitly managed per-task rather than left to model defaults — a cost-aware extension of the process supervision principle.
7.9 Cost Optimization in ML Systems67 wordsSummaryWork on ML cost such as ZeRO (Rajbhandari et al., 2020) and FlexGen (Sheng et al., 2023) targets training and serving. Budget Prompting works above both, in the prompts and agent design that decide how much of that infrastructure gets used, a layer where practitioner knowledge outweighs published research.
show summary
The broader literature on ML cost optimization (e.g., Rajbhandari et al., 2020 on ZeRO; Sheng et al., 2023 on FlexGen) focuses on training and serving infrastructure. Budget Prompting operates at the application layer — above the model, above the serving infrastructure, in the prompt engineering and agent architecture that determine how infrastructure resources are consumed. This is a less-studied layer where practitioner knowledge dominates over published research.
7.10 The Claude Code Source Exposure (March 2026)138 wordsSummaryThe closest system is Anthropic's own Claude Code, whose source became visible in the March 2026 exposure (@anthropic-ai/claude-code@2.1.88, ~512K lines of TypeScript). It is not published research, so the paper cites it as primary-source code. Unlike other related work, it is a parallel design built for the same billing limits. Its findings (clearing old tool results, the cache boundary, cache sharing in compaction, stopping on diminishing returns, the consolidation diet) are folded into Sections 2.5, 4.5 and 6.5 as evidence for the architecture. A few quoted figures come from secondary analysis.
show summary
@anthropic-ai/claude-code@2.1.88, ~512K lines of TypeScript). It is not published research, so the paper cites it as primary-source code. Unlike other related work, it is a parallel design built for the same billing limits. Its findings (clearing old tool results, the cache boundary, cache sharing in compaction, stopping on diminishing returns, the consolidation diet) are folded into Sections 2.5, 4.5 and 6.5 as evidence for the architecture. A few quoted figures come from secondary analysis.The most directly comparable system is Anthropic's own Claude Code agent, whose source became visible through the March 2026 source-map exposure (@anthropic-ai/claude-code@2.1.88, ~512K lines of TypeScript). It is not published research and was not meant to be read, so we cite it as primary-source code analysis rather than literature. Its relevance is unusual: most related work describes a different design; Claude Code describes a parallel one, built independently against the same billing constraints. Sections 2.5, 4.5, and 6.5 fold the specific findings — MicroCompact, the dynamic-boundary prefix discipline, forked-agent cache sharing, diminishing-returns budgeting, and autoDream's consolidation diet — into the relevant techniques. We treat it throughout as convergent evidence for the architecture, with the standing caveat that a few quoted figures come from secondary analysis of the dump rather than verified source lines.
8. Discussion1,075 wordsSummaryCaching the system prompt matters most: July showed about 7,728 cache-read tokens per fresh input token, so the agent should keep the start of its prompt fixed for the whole session and put anything that changes after it. The claimed savings come from combining techniques: four built ones multiply to 0.43 of the cost, a 2.3× reduction, and the unbuilt ones push toward 3–5×, at a price in complexity. Most techniques carry over to other providers. A cheaper agent ($100–150 a month instead of $400–500) would be within reach of more people and use less energy. The limits: one agent and one user, no ablation, projected figures for unbuilt techniques, second-hand figures from the leak, and no measured quality test yet.
show summary
8.1 The Surprising Dominance of Caching252 wordsSummaryIf one technique had to come first, it would be caching the system prompt (B1), because it affects every turn: in July the current subscription window showed 122,422,666 cache-read tokens against 15,841 fresh input tokens and 7,374,471 cache-creation tokens, about 7,728:1 read to fresh. So the agent should put cache stability above almost everything. The start of the prompt stays fixed for the whole session, and anything that changes, such as the time or recent events, goes in messages after it. Most agent frameworks put such details in the system prompt and break the cache each time. TinkerClaw and Claude Code both mark this line in their code, in the same place.
show summary
If we had to choose a single foundation from the 20 techniques, it would be B1: system-prompt caching. Caching affects every turn, and July telemetry measured 122,422,666 cache-read tokens against 15,841 fresh input tokens and 7,374,471 cache-creation tokens in the current subscription window—a roughly 7,728:1 cache-read-to-fresh-input ratio. B5 is now insurance for that foundation, not the primary source of further savings.
This has a counterintuitive implication: the agent should optimize for cache stability over almost everything else. Memory writes, dynamic system prompt components, per-turn injections — anything that changes the prefix is actively costly. The best architecture is one where the prefix is completely static within a session, and all dynamism happens in the conversation turns that follow it.
This is fundamentally at odds with how most agent frameworks are designed. They inject dynamic context (current time, recent events, user presence status) into the system prompt because it's convenient. Each dynamic injection breaks the cache. Budget Prompting argues that dynamic context should be injected as user-role messages after the cached prefix, not within it. Both systems we examined draw that line explicitly: TinkerClaw splits the prompt at a __PREFRONTAL_CACHE_BOUNDARY__ marker and caches only the static block, and Claude Code's SYSTEM_PROMPT_DYNAMIC_BOUNDARY (Section 2.5) does the same, with the only helper that writes past it named DANGEROUS_uncached…. When the principle is correct, the implementation has to draw that line somewhere; two independent systems drawing it in the same place is good evidence the line is real.
8.2 The Composition Problem128 wordsSummaryNo single technique gives the claimed 3–5×; the reduction comes from combining them, and the effects multiply. Routing takes 15% off overall, caching 20%, session management 30% and silent replies 10%: 0.85 × 0.80 × 0.70 × 0.90 = 0.43, a 2.3× reduction. The unbuilt B5, B6 and B8 would push it toward 3–5×. The price is complexity: twenty interacting techniques are hard to reason about, debug and maintain. The rings and pipeline of Section 4 are an attempt to manage that, and the paper admits the result is not simple.
show summary
No single technique provides the 3–5× cost reduction we claim. The reduction comes from composition:
- Model routing saves 30% on automated work → 15% overall
- Caching saves 80% on system prompt tokens → 20% overall
- Session management prevents 3× context bloat → 30% overall
- Silent replies save output tokens on 50% of turns → 10% overall
These multiply rather than add: 0.85 × 0.80 × 0.70 × 0.90 = 0.43, or a 2.3× reduction. Adding the unimplemented techniques (B5, B6, B8) pushes toward 3–5×.
But composition creates complexity. Twenty interacting techniques with synergies and tensions are hard to reason about, debug, and maintain. The architecture in Section 4 is our attempt to manage this complexity through layered rings and a clear pipeline, but we acknowledge it's not simple.
8.3 Generalizability100 wordsSummaryMost techniques carry over beyond TinkerClaw and Anthropic. Model routing fits any setup with several models. Caching (B1) needs provider support; B2–B9 work anywhere. Output control is universal, though thinking control needs provider support. D3 only applies to subscriptions; D1, D2 and D4 are universal. E1 needs a batch API; E2 works anywhere. Providers with other billing, such as Gemini with its different caching, would need adapted strategies, not different ones.
show summary
Our techniques are described in the context of TinkerClaw/OpenClaw and Anthropic's API, but most generalize:
- Model routing (A1–A3): Applies to any multi-model setup.
- Context economics (B1–B9): B1 requires provider-specific caching support; B2–B9 are universal.
- Output economics (C1–C2): Universal, though thinking control requires provider support.
- Temporal amortization (D1–D4): D3 is specific to subscription models; D1, D2, D4 are universal.
- Billing arbitrage (E1–E2): E1 requires batch API; E2 is universal.
Providers with different billing structures (e.g., Google's Gemini with different caching mechanics, or OpenAI's yet-to-be-released caching) would require adapted but not fundamentally different strategies.
8.4 Ethical Considerations103 wordsSummaryA persistent agent costs $400–500 a month in this deployment, affordable for a developer but not for most people. Cutting that 3–5×, to $100–150 a month, would put a personal assistant on a par with other subscriptions. Fewer tokens also mean less energy, which could add up if millions of people run persistent agents.
show summary
Budget Prompting has an accessibility dimension. Running a persistent AI agent is currently a luxury — $400–500/month in our case, affordable for a developer but not for most users. Techniques that reduce this cost by 3–5× lower the barrier to entry. At $100–150/month, a personal AI assistant becomes comparable to other subscription services.
There's also a sustainability argument. LLM inference consumes significant energy. Reducing token consumption by 3–5× proportionally reduces the energy footprint of persistent agents. If millions of users operate persistent agents (a plausible near-term future), the aggregate energy impact of Budget Prompting techniques could be substantial.
8.5 Limitations492 wordsSummaryThe 3–5× total is a projection: seven of the 20 techniques are not built, and the built ones achieve 2–3×. The evidence is one agent and one user with no controlled ablation, so savings per technique are estimates, and the evidence from industry supports the design, not the numbers. The corrected context breakdown covers only five sub-agent calls, the July cache figures should be measured again from per-call records, and old tool output is re-read often enough to argue for keeping it retrievable. Two Claude Code figures are second-hand, the techniques assume flat-rate plans and today's prices, and the claim of no quality loss has not yet been tested on public benchmarks.
show summary
PartWhat is projected, not measured109 wordsSummarySeven of the 20 techniques (B5, B6, B7, B8, B9, D2, F1) are not built yet, so the 3–5× total is a projection; the built ones achieve 2–3×. All data come from one agent, one user and one use case, with no controlled ablation, so the savings per technique are estimates. The evidence that industry reached the same design supports the architecture, not the size of the savings.
show summary
Unimplemented techniques. Seven of the 20 proposed techniques (B5, B6, B7, B8, B9, D2, F1) are designed but not yet implemented. The projected 3–5× total savings includes their estimated contributions; the achieved savings from implemented techniques are 2–3×. We distinguish clearly between measured and projected figures throughout.
Single-system evidence. All data comes from one agent, one user, one use case. We cannot claim generalizability without replication.
No controlled ablation. We haven't done rigorous ablation studies. Per-technique attribution is estimated, not measured. The industrial-convergence evidence (Section 6.5) validates the architecture but not the savings magnitudes — two independent designs can agree on structure and still both misjudge cost.
PartGaps in the measurements177 wordsSummaryThe corrected breakdown of what fills the context covers only five sub-agent calls from one short interval, and the earlier main-session breakdown cannot be repaired. The July cache figures predate the per-call record and should be measured again from it before being compared with later periods. Old tool output is not uniformly disposable (residency median 48, mean 139.6, p90 364, and one file re-read 34 times), which argues for keeping it retrievable over deleting it.
show summary
Context-anatomy sample. The corrected per-slab decomposition contains five production sub-agent calls from one short interval. It proves that tool results are resident and quantifies those calls, but it does not establish a deployment-wide distribution. The original main-session decomposition cannot be repaired retrospectively because the buggy classifier did not retain the omitted tool-result count.
Live stream versus history. The per-call record of Section 5.1 is published as a live stream for the operator's panel; nothing replays it. A study over dated windows must read the durable usage ledger, which keeps one row per call, and the pre-call composition rows, which are stored. The July cache figures in this paper were measured before the per-call record existed; they should be re-derived from per-call rows before they are compared with later windows.
Long residency tail. In the audit, context residency had median 48, mean 139.6, p90 364, and a maximum of 34 re-reads for one file. This fat tail weakens the assumption that old tool output is uniformly disposable and argues for reversible retrieval rather than aggressive deletion.
PartSource, pricing and quality caveats206 wordsSummaryThe Claude Code findings come from code exposed by accident; the cited constants and file paths were checked, but the ~250K daily-waste figure and the 8K default output cap come from secondary analysis. The techniques assume flat-rate plans and today's prices, which change quarterly. The claim of no quality loss is observed, not measured: the public-benchmark accuracy test that headroom uses is planned but has not been run.
show summary
Leaked-source provenance. The Claude Code findings rest on code that was exposed by accident, not documentation Anthropic endorses. We verified the cited constants and file paths directly, but a small number of quoted figures (the ~250K daily-waste number, the 8K default output cap) come from secondary analysis of the dump and are marked as such. Anthropic may change any of this without notice.
Flat-rate pricing assumption. Many techniques are optimized for flat-rate plans with rate limits. Pure metered usage would shift the priorities (caching becomes less important relative to context minimization).
Quality measurement is weak. We claim no quality degradation but haven't rigorously measured it. SyncScore and task completion rate are proxies, not ground truth. This is the gap headroom (§7.1) closes for stateless compression with a reproducible public-benchmark accuracy-delta suite; we have adopted that protocol as a future-work commitment (§9.2) but have not yet run it. Until we do, our quality claim is observational, not measured — headroom's is measured, and on the compression slice we should be held to the same bar.
Rapidly changing pricing. LLM pricing changes quarterly. Techniques optimized for current pricing may become irrelevant or more important as prices shift. The taxonomy is more durable than the specific savings estimates.
9. Future Work377 wordsSummaryFour unbuilt techniques come first: the rolling window (B8), one summary updated in place (B7), pruning of tool output (B6), and frozen memory (B5) kept as insurance. A later revision will add controlled ablations, confidence intervals, quality scores, repeated cache measurements, checks that every optimizer sees live traffic, and headroom's public-benchmark accuracy test for the compression techniques. Two problems stay open: sharing a budget when several agents use the same accounts, and letting the agent tune its own techniques from its cost and quality numbers.
show summary
9.1 Implementation of Proposed Techniques102 wordsSummaryFour unbuilt techniques come first. B8 would give the context a fixed budget and needs an embedding pipeline, a vector store and a recall test. B7 targets the history and summary parts of the context. B6 would first strip the line numbers added to file reads, then deal with stale reads and Bash output, keeping old output retrievable. B5 stays as insurance and should be judged by cache reads per write and hit-rate regressions, not by the retired 65%→95% projection.
show summary
The four highest-priority unimplemented techniques:
- B8 (Rolling Window + Vector Retrieval): Replaces monotonic context growth with fixed-budget context management. Requires an embedding pipeline, vector store, and recall evaluation.
- B7 (Iterative Summary Compression): Targets the conversation-history and summary slabs without depending on the disproven B5 savings gap.
- B6 (Surgical Tool Output Pruning): First, remove line-number scaffolding, then address stale Read output and the currently unclaimed Bash-output slab. Preserve reversible retrieval for the long residency tail.
- B5 (Frozen Snapshot Injection): Retain as prefix-instability insurance. Evaluate it by cache reads per write and cache-hit regressions, not by the retired 65%→95% projection.
9.2 Rigorous Evaluation194 wordsSummaryA later revision will add controlled ablations per category, confidence intervals, before-and-after quality scores, repeated cache measurements over dated periods, the context breakdown for main-session calls too, and a check that every optimizer actually sees traffic. It will also borrow headroom's benchmark test: run GSM8K, TruthfulQA, SQuAD and BFCL with and without each compression or retrieval technique (B3, B4, B6, B6a, B8) and report the change in accuracy, so that "no degradation observed" becomes a measured number. The billing and reliability techniques (B1, D3, D4, E1) cannot be tested that way and still rely on production data.
show summary
A future revision will add:
- Controlled ablation studies for each technique category
- Statistical analysis with confidence intervals
- Quality metrics (SyncScore, task completion) with before/after comparison
- Repeat cache-hit and reads-per-write measurements across dated windows, computed only over calls that measured their cache reads
- Repeat the context anatomy from pre-call composition rows across main-session calls, not only sub-agents, with the standing rule pack reported as its own slab
- Liveness assertions for every optimizer and telemetry producer (non-zero requests during active traffic)
- A public-benchmark accuracy-delta protocol, borrowed from headroom (§7.1). Our weakest claim is "no degradation we have been able to observe," resting on a single deployment. headroom demonstrates a concrete, reproducible alternative: run the candidate configuration against standard benchmarks (GSM8K, TruthfulQA, SQuAD, BFCL) with and without each context-economics technique, and report the accuracy delta directly. This converts our subjective "no degradation observed" into a measured number for the techniques where it applies (B3, B4, B6, B6a, B8) — the compression/retrieval levers whose quality risk is exactly what a benchmark can isolate. The billing and reliability techniques (B1, D3, D4, E1) are not benchmark-measurable in this way and remain the province of our production data.
9.3 Multi-Agent Budget Coordination35 words
When multiple agents share billing accounts or infrastructure, Budget Prompting becomes a coordination problem. Priority allocation, pacing, and model routing must account for multiple competing agents. This is an open problem relevant to enterprise deployments.
9.4 Automated Technique Selection46 words
Currently, Budget Prompting techniques are configured manually. An automated system could observe cost metrics, quality metrics, and usage patterns, then dynamically adjust which techniques are active and how aggressively they're applied. This is a meta-optimization problem: using the agent's own intelligence to optimize its own cost.
10. Conclusion264 wordsSummaryA persistent agent that knows its user and is always available is a different kind of assistant, but always on means always billing. The paper reports that its 20 techniques cut cost 2–3× in production, 3–5× projected, without harming the agent's intelligence or personality, insulating its thinking from the cost of its own context as myelin insulates a nerve. It draws two lessons: keeping the cached prompt stable matters more than any single technique, and the savings come from many small techniques multiplied together. It is offered as a working paper from a running system.
show summary
A persistent memory agent — one that knows you, learns from experience, and is always available — is a qualitatively different kind of assistant. But current LLM billing makes it prohibitively expensive for most users. "Always-on" means "always billing."
Budget Prompting offers a path forward. Through 20 techniques spanning model routing, context economics, output control, temporal amortization, and billing arbitrage, we've demonstrated 2–3× cost reduction in production (with 3–5× projected after implementing the remaining techniques). These techniques don't compromise the agent's intelligence or personality — they insulate cognition from the cost of its own context, much as biological myelin insulates neural signals for faster, more efficient propagation.
The most important insight is architectural: prompt cache stability is the foundation of cost-efficient persistent agents. Everything that changes the system prompt prefix is expensive. Everything that keeps it stable is valuable. This single principle, fully internalized, drives more cost reduction than any individual technique.
The second insight is compositional: no single technique provides large savings, but 20 techniques multiplied together do. Budget Prompting is not a silver bullet — it's a toolkit. The value is in the systematic application of many small optimizations that compound.
We release this as a working paper from a real system, not an academic exercise. The techniques run in daily operation. The numbers are real, the failures are documented, and the path to further improvement is clear. We hope this taxonomy is a practical guide for anyone building persistent agents who, like us, has stared at their API bill and wondered if there's a better way.
There is. It's just twenty techniques deep.
Appendix A: Technique Summary Table228 wordsSummaryOne row per technique, with category, status and estimated savings. Implemented: A1–A3, B1–B4, C1, C2, D1, D3, D4, E1 and E2. Designed: B5, B6, B6a, B7, B8, B9, D2 and F1.
show summary
| # | Technique | Category | Status | Est. Savings |
|---|---|---|---|---|
| A1 | Model routing by complexity | Model Routing | [Impl.] | 25–40% automated |
| A2 | Extended thinking control | Model Routing | [Impl.] | $5–10/day equiv. |
| A3 | Cross-model delegation | Model Routing | [Impl.] | Variable |
| B1 | System prompt caching | Context Econ. | [Impl.] | $8–10/day |
| B2 | Aggressive session management | Context Econ. | [Impl.] | 2–4× per turn |
| B3 | Memory search over bulk loading | Context Econ. | [Impl.] | 80–95% context |
| B4 | Context compaction | Context Econ. | [Impl.] | 60–80% context |
| B5 | Frozen snapshot injection | Context Econ. | [Designed] | Cache-stability insurance |
| B6 | Surgical tool output pruning | Context Econ. | [Designed] | ~21% of audited Read bytes addressable |
| B6a | Content-type-specific compression | Context Econ. | [Designed] | 60–95% in stateless benchmarks |
| B7 | Iterative summary compression | Context Econ. | [Designed] | 5–15K tokens |
| B8 | Rolling window + vector retrieval | Context Econ. | [Designed] | Fixed context cap |
| B9 | Mid-context reinjection | Context Econ. | [Designed] | Indirect |
| C1 | Silent reply (NO_REPLY) | Output Econ. | [Impl.] | $5–8/day |
| C2 | Thinking control (output) — output-side view of A2 | Output Econ. | [Impl.] | (see A2) |
| D1 | Cron priority tiers | Temporal Amort. | [Impl.] | 15–20% automated |
| D2 | Background review agent | Temporal Amort. | [Designed] | 80% reflection |
| D3 | Dual-account staggering | Temporal Amort. | [Impl.] | Eliminates outages |
| D4 | Token bucket pacing | Temporal Amort. | [Impl.] | Prevents lockouts |
| E1 | Batch API for non-interactive | Billing Arbitrage | [Impl.] | 50% on batch work |
| E2 | Sub-agent fresh context | Billing Arbitrage | [Impl.] | $1–3/delegation |
| F1 | Security scanning on mem writes | Security | [Designed] | Indirect |
Appendix B: Glossary112 wordsSummaryShort definitions of the terms used: Budget Prompting, cache hit rate, context window, input tokens per minute (ITPM), prefix stability, requests per day and per minute, SyncScore, token bucket and tokens per turn.
show summary
- Budget Prompting: A family of techniques that reduce the per-turn cost of persistent LLM agents without degrading quality.
- Cache hit rate (CHR): Percentage of system prompt tokens served from provider cache.
- Context window: The total token capacity of a single LLM request (input + output).
- ITPM: Input tokens per minute — a rate limit metric on flat-rate plans.
- Prefix stability: The property of a system prompt remaining unchanged across turns, enabling cache reuse.
- RPD: Requests per day.
- RPM: Requests per minute.
- SyncScore: Personality-coherence metric (0–1) comparing live agent output against its configured personality.
- Token bucket: Rate-limiting algorithm that smooths bursty usage.
- TPT: Tokens per turn — average total tokens (input + output) per conversational turn.
References (16)
- Anthropic (2026). Claude Code source analysis. Internal codebase exposed via npm source map,
@anthropic-ai/claude-codev2.1.88; ~512,000 lines of TypeScript. Compaction and budget code (services/compact/,services/autoDream/,query/tokenBudget.ts,constants/prompts.ts) analyzed April 2026. Cited as primary-source code, not endorsed documentation.
- Kwon, W., et al. (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. SOSP '23.
- Lewis, P., et al. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. NeurIPS 2020.
- Madaan, A., et al. (2023). Self-Refine: Iterative Refinement with Self-Feedback. NeurIPS 2023.
- Packer, C., et al. (2023). MemGPT: Towards LLMs as Operating Systems. arXiv:2310.08560.
- Rajbhandari, S., et al. (2020). ZeRO: Memory Optimizations Toward Training Trillion Parameter Models. SC '20.
- Sheng, Y., et al. (2023). FlexGen: High-Throughput Generative Inference of Large Language Models with a Single GPU. ICML 2023.
- Wei, J., et al. (2022). Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. NeurIPS 2022.
- Yao, S., et al. (2023). ReAct: Synergizing Reasoning and Acting in Language Models. ICLR 2023.
- Chen, L., et al. (2023). FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance. arXiv:2305.05176.
- Lightman, H., et al. (2023). Let's Verify Step by Step. arXiv:2305.20050.
- Park, J. S., et al. (2023). Generative Agents: Interactive Simulacra of Human Behavior. UIST 2023.
- Chopra, T. (2026). headroom: Reversible context compression for agents (CCR — Compress, Cache, Retrieve). Open-source project, Apache-2.0, ~24.7k★. https://github.com/chopratejas/headroom. Eval suite
python -m headroom.evals; trained compressor Kompress-v2-base on HuggingFace. Cited as the closest comparable system (§7.1).
- Osmani, A. (2026). agent-skills: Discipline and skills plugin for coding agents. Open-source project, ~56.8k★. https://github.com/addyosmani/agent-skills. Cited for load-on-demand skill-catalog packaging (§7.2).
- Haines, C. (2026). marketingskills: 44 marketing frameworks as agent skills. Open-source project. https://github.com/coreyhaines31/marketingskills. Used as the catalog-eviction measurement anchor for B3 (§7.2).
- Journey registry (2026). Distributed agent-workflow "kits." Cited for catalog-granularity on-demand loading (§7.2).
Acknowledgements33 words
The author used an LLM assistant for manuscript revision, consistency checking, and evidence tracing. The author remains responsible for the claims and interpretation.
MYELIN — TinkerClaw Working Paper © 2026 Oscar Serra. All rights reserved.