Claude Code · HooksUserPromptSubmit
cache-tax
Avisa del costo de una caché de prompts fría antes de pagarlo.
por Karan Bansal
UserPromptSubmitSessionStart
Licencia: MITVer original
Instalación
/plugin marketplace add karanb192/claude-code-hooks
/plugin install cache-tax@claude-code-hooksContenido
# cache-tax

> The comeback price of a cold prompt cache, shown before you pay it.
Claude Code's main conversation rides a 1-hour prompt cache. Come back at minute 59 and the next message costs cents. Come back at minute 61 and the whole context is re-written at the cache-write rate, which on Fable 5.1 is 80x a cache read ($20 against $0.25 per million tokens). A 500k-token session re-cached cold is $10 at list price, and the message that triggers it is usually "good morning". Claude Code computes all of this and shows none of it at the moment you press Enter. This plugin does.
## A cache countdown row in a status line you already have
No plugin install needed. `cache-tax.js` has no dependencies; it reads its list prices from `prices.json` beside it. Copy both, then call the script from your own status line script with the same stdin Claude Code sends you, and print its line as one more row:
```
curl -fsSL https://raw.githubusercontent.com/karanb192/claude-code-hooks/main/plugins/cache-tax/cache-tax.js -o ~/.claude/cache-tax.js
curl -fsSL https://raw.githubusercontent.com/karanb192/claude-code-hooks/main/plugins/cache-tax/prices.json -o ~/.claude/prices.json
```
Without `prices.json` next to it (or `CACHE_TAX_PRICES_FILE` pointing at one) the row still counts down and shows token counts, with `n/a` in place of dollars.
```sh
# inside your status line script, where $input holds the JSON Claude Code piped in
printf '%s' "$input" | node ~/.claude/cache-tax.js --statusline
```
It prints one line, while warm and then after the cache lapses:
```
cache 47m left · 218k · cold costs $4.37 · last miss ttl_expired_1h
cache COLD · next msg re-writes 218k = $4.37 · last miss ttl_expired_1h
```
It reads the native `prompt_cache` object Claude Code sends to status lines (v2.1.251+), so Claude Code re-runs it the moment the cache goes cold; on older versions it falls back to the transcript named in the same payload. The guard and the resume price below are the plugin; the row works without it.
## Install
```
/plugin marketplace add karanb192/claude-code-hooks # once per machine
/plugin install cache-tax@claude-code-hooks
```
Restart Claude Code, done. (Or from a shell: `claude plugin install cache-tax@claude-code-hooks`.)
## What it does
| Event | Runs | What happens |
|-------|------|--------------|
| UserPromptSubmit | sync, ~30 ms | Reads the newest usage block from the session transcript. If the cache has lapsed and the context is over `CACHE_TAX_BIG` tokens, shows the re-write cost as a warning. With `CACHE_TAX_BLOCK=1` it refuses the prompt once instead (exit 2); resend the same message to proceed, or `/clear` and start from a handoff note. |
| SessionStart (`resume\|fork`) | sync | On a cold resume, prints the idle gap, the tokens the first message re-writes, and the dollar estimate Claude Code already computed (`estimated_cache_write_usd`, v2.1.251+). Falls back to the transcript on older versions. |
`/cache-tax:status` renders the full card on demand: tier, warm or cold, context size, cold-comeback price, and this session's cache writes, reads and full re-writes so far. From a shell, `node cache-tax.js --render --transcript <path>` renders the same card for any transcript; without `--transcript` it picks the newest transcript for the current directory.
The guard ignores slash commands, so `/clear` and `/compact` never trigger it. After a compaction (manual or auto) the old context no longer applies, so until the first new turn lands the status line reads `cache reset by /compact · 17k carried · next msg writes ≥ $0.34`, the card says the same, and the guard stays quiet: the summary has never been cached, so that first write is unavoidable and small.
### The warning, verbatim
```
cache-tax: the 1h prompt cache lapsed 2h00m ago. This message re-writes 300,002 tokens at $20/MTok = $6.00
(a warm turn would have cost $0.08). If most of that context is stale, /clear and start from a handoff note instead.
```
## The Mod form
The same tool exists as a Claude Mod, [cache-tax@claude-code-mods](https://github.com/karanb192/claude-code-mods/tree/main/plugins/cache-tax), for [Claude Code 2.1.287 or later](https://code.claude.com/docs/en/plugins/mods/overview#turn-mods-on-or-off), where mods are on by default. It runs inside Claude Code instead of reading the transcript, refuses a cold send once by default, and adds what a hook cannot do: `/keepwarm 6h` sends one cache-shared ping after 50 idle minutes so the cache is read, not re-written, when you come back. Install one form, not both; two guards fire twice. The status line segment below stays with this hook's files either way, because a mod cannot draw into the status line.
## What Claude Code already does, and where this adds
On `--resume` of a session older than its cache TTL, recent Claude Code versions (seen on 2.1.261) show their own dialog, "this session is N old and M tokens, we recommend resuming from a summary". That covers the resume path in tokens. cache-tax adds the dollar figure there, and covers the case that dialog cannot see: a session you left open, came back to after an hour, and typed into. Nothing native intervenes at that keystroke.
## Status line segment
Plugins cannot ship a status line, so wire this one yourself. The same script prints one line when called with `--statusline`, and it prefers the native `prompt_cache` object Claude Code sends to status lines since v2.1.251 (`expires_at`, `recache_tokens_if_cold`, `ttl`, `last_miss_cause`), which also means Claude Code re-runs it the moment the cache goes cold.
```json
"statusLine": {
"type": "command",
"command": "node ~/.claude/plugins/marketplaces/claude-code-hooks/plugins/cache-tax/cache-tax.js --statusline"
}
```
Output while warm, then after the cache lapses:
```
cache 47m left · 218k · cold costs $4.37 · last miss ttl_expired_1h
cache COLD · next msg re-writes 218k = $4.37 · last miss ttl_expired_1h
```
That path is the marketplace clone Claude Code keeps after `/plugin marketplace add`; the installed copy also lives under `~/.claude/plugins/cache/claude-code-hooks/cache-tax/<version>/`. Already have a status line script? Pipe the same stdin into `cache-tax.js --statusline` and print its line as one more row.
## Configuration
All optional, set via environment variables:
| Variable | Default | Purpose |
|----------|---------|---------|
| `CACHE_TAX_BIG` | `50000` | Context size in tokens below which the guard stays quiet. |
| `CACHE_TAX_BLOCK` | unset | `1` makes the guard refuse a cold prompt once (exit 2) instead of warning. The resend goes through. |
| `CACHE_TAX_TTL` | auto | Force `5m` or `1h` when the transcript has no cache-write tier to infer from. |
| `CACHE_TAX_PRICES` | unset | JSON overriding single families on top of `prices.json`, in $/MTok. Either `[cache read, 5m write, 1h write]`, e.g. `{"fable-5-1":[0.25,12.5,20]}`, or the same object shape `prices.json` uses (tiers included). |
| `CACHE_TAX_PRICES_FILE` | `prices.json` beside the script | Path to a different price table, in the same format. |
## Prices
List rates live in [`prices.json`](prices.json), next to the script, with the date they took effect and the rate card they came from. As shipped: Claude API list prices effective **2026-10-07**, Standard tier, Global scope, in $/MTok as cache read / 5m write / 1h write:
- Fable 5.2 and Mythos 5.2 `0.20 / 10 / 16`. These two are newer than the 2026-10-07 rate card. Their rates come from the [pricing page](https://platform.claude.com/docs/en/about-claude/pricing), and their entries carry that page as their own `source`.
- Fable 5.1 and Mythos 5.1 `0.25 / 12.5 / 20`, Fable 5 and Mythos 5 `1 / 12.5 / 20`
- Mythos Preview `2.50 / 31.25 / 50`. This deprecated model has no announced retirement date. These cache rates are derived from the [published $25/MTok input rate](https://www.anthropic.com/glasswing) and the [standard 0.1× read, 1.25× 5m-write and 2× 1h-write multipliers](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing), not an explicit cache-price row. Its entry records both sources.
- Opus 5.5 `0.20 / 5 / 8`, Opus 5 and 4.5-4.8 `0.50 / 6.25 / 10`
- Opus 4 and 4.1 `1.50 / 18.75 / 30`. These two are retired on the Claude API and are not on the 2026-10-07 rate card. Their rates come from the pricing page, and their entries carry that page as their own `source`.
- Sonnet 5.5 `0.10 / 2.5 / 4`, Sonnet 5 `0.20 / 2.5 / 4`, Sonnet 4.x `0.30 / 3.75 / 6`
- Haiku 5.5 `0.01 / 0.125 / 0.20` up to 100k tokens of context and `0.05 / 0.625 / 1` past it; Haiku 4.5 `0.10 / 1.25 / 2`; Haiku 3.5 `0.08 / 1 / 1.6`
`/cache-tax:status` prints the effective date it is using. Only explicitly listed model IDs and aliases are priced. The documented trailing [`[1m]` context option](https://code.claude.com/docs/en/model-config) is removed before matching; it does not change the model’s rate or force a context-price tier. Actual token counts still select the tier. Unknown versions, unlisted snapshots and unsupported retired models get token counts and no dollar figure. Bedrock IDs with `anthropic.` or `us.`, `eu.`, `apac.`, `global.` inference-profile prefixes (and the legacy `-v1`/`-v1:0` suffix) use the same Standard/Global Claude API yardstick, not the provider’s bill. If you are on a subscription the dollars are what the same traffic would cost at API list price, which is the only public yardstick; how a cache write weighs against your plan limits is not documented.
If a contributing request has no price, its session dollar total shows `n/a`, rather than zero or a partial sum. Valid `CACHE_TAX_PRICES` overrides still work when the price file is missing or unreadable, and the card identifies that fallback. A known family override keeps its listed model aliases; a new override key matches that exact model ID only. An optional `models` array adds explicit aliases. Without a usable file, supply exact model IDs or a `models` list because the file’s family aliases are unavailable. Malformed rates or non-integer, non-positive, or non-finite `maxContext` thresholds are ignored, rather than coerced.
### Updating prices
1. Get the current rate card. Anthropic publishes it as a dated PDF ("Claude Model Pricing — List Prices by Platform") linked from the [pricing page](https://platform.claude.com/docs/en/about-claude/pricing). Use the **Claude API**, **Standard**, **Global** row of each model. The three columns cache-tax needs are **Cache hits & refreshes** (`read`), **5m cache writes** (`write5m`) and **1h cache writes** (`write1h`).
2. Edit `prices.json`: set `effective` to the rate card's effective date (`YYYY-MM-DD`) and `source` to its URL, then change or add entries under `families`.
3. A family key matches an exact model ID without the `claude-` prefix (`claude-opus-5-5` → `opus-5-5`). To group models or support dated snapshots and Google Cloud `@date` IDs, add a `models` array listing each exact ID, also without the `claude-` prefix. When present, that array replaces the key as the set of matching IDs; it is not a prefix or wildcard. Keep IDs unique across families. New versions need their own entry or an explicit addition to a same-price family. Give each entry a `name` for humans. If rates come from somewhere other than the top-level `source`, record the entry’s own source and any derivation.
4. A model whose rate steps up with context size gets `tiers` instead of flat rates: each tier has the three rates plus an integer `maxContext`, the largest context in tokens it covers, and the last tier has no `maxContext`. Context means everything the request sends (input plus cache read plus cache write), the same figure the re-write is priced on. See `haiku-5-5`.
5. Run `node --test plugins/cache-tax/tests/cache-tax.test.js`. It checks that every family parses, rates are ordered read ≤ 5m write ≤ 1h write, tiers ascend and end unbounded, and the date and source are filled in. Add a `priceFor` assertion for any family you added.
6. Bump `version` in `.claude-plugin/plugin.json` so installed copies pick up the new table.
## How it decides
The tier comes from the newest assistant usage block in the transcript: `cache_creation.ephemeral_1h_input_tokens` means the 1h tier, `ephemeral_5m_input_tokens` the 5m tier. Age is wall-clock time since that block's timestamp. Lapsed means age past the tier's TTL; the "lapsed N ago" figure is the time since that expiry, not since the block. The re-write cost is the block's full context (input plus cache read plus cache write) at the tier's write rate. A "full miss" on the card is a request whose cache read covered under half of the previous request's context while its write covered over half of it.
Hooks receive no token counts, so nothing here comes from the hook input except the resume fields Claude Code added in v2.1.251. Everything else is read from `transcript_path`, the file Claude Code is already writing.
## Limits
- Claude Code only. It reads the transcript Claude Code writes and the fields Claude Code sends; nothing here runs under Codex, Cursor or a raw API client.
- Needs node on PATH, like every plugin in this marketplace.
- The status line row is wired by hand (plugins cannot ship one), so the countdown is only as live as your `refreshInterval`; the cold flip itself is event-driven and needs no timer.
- Dollars use Standard tier, Global scope API list prices. Batch discounts, Fast mode and regional inference premiums are not applied. On a subscription they are the yardstick, not the bill, and how a cache write weighs against the 5-hour and weekly limits is not documented anywhere I could find.
- The guard reads the newest real turn in the transcript. A session whose last request was a subagent's is priced from that request, which can be smaller than the context you are about to send.
- After a compaction the figure is a floor. The transcript records the tokens carried into the summary (`compactMetadata.postTokens`) but not the system prompt and tools that go in front of them; on one 562k session the row said `≥ $0.34` and the first message wrote 40k tokens, $0.80.
- `/compact` is not a free exit from a cold cache. The compaction request sends the whole context to the model once more, and Claude Code does not write that request's usage to the transcript, so neither the guard nor the card's session totals see it. If the cache has lapsed and most of the context is stale, `/clear` plus a handoff note is the cheap way out.
- Two tests pin the false-positive side (warm session, small context) so the guard stays quiet where it should; there is no corpus beyond the test file.
## Related tools
[claude-hud](https://github.com/jarrodwatts/claude-hud) and [ccstatusline](https://github.com/Haleclipse/CCometixLine) show a cache countdown in the status line and price writes at a fixed 1.25x, the 5-minute tier. [cc-cache-alert](https://github.com/candiesdoodle/cc-cache-alert) pings your phone before the cache lapses so you can send a keepalive. [ccusage](https://github.com/ccusage/ccusage) prices the 1-hour tier correctly, after the fact, in reports. cache-tax is the one that puts a dollar figure on the keystroke and can refuse it.
## Data & privacy
Reads the session transcript's usage blocks and timestamps, never message text, plus its own `prices.json`. Writes a one-line JSON entry to `~/.claude/hooks-logs/<date>.jsonl` when it warns or blocks, and a tiny acknowledgement file under `~/.claude/cache-tax/` in block mode. No network calls (the script only uses `fs`, `path`, and `os`).
## Uninstall
```
/plugin uninstall cache-tax@claude-code-hooks
```
Más en Hooks
Formatear al editar
Ejecuta Prettier sobre cada archivo que Claude edita o crea.
Bloquear archivos .env
Impide que Claude lea o edite archivos de secretos.
Aviso al terminar
Notificación de escritorio en macOS cuando Claude termina.
Chequeo de tipos al editar
Corre tsc después de editar archivos TypeScript y muestra los errores.
Contexto al iniciar
Carga la rama y los últimos commits al abrir una sesión.
Registro de comandos
Guarda cada comando de shell en un log para auditoría.