cache-tax — плагин для Claude Code: цена холодного кеша
Плагин cache-tax показывает, во сколько обойдётся возврат в сессию после того, как часовой кеш промпта остыл, — до того, как вы нажмёте Enter.
MIT ★ 586 обновлён 2026-10-26
/plugin marketplace add karanb192/claude-code-hooks
/plugin install cache-tax@claude-code-hooksЧто делает cache-tax
Плагин следит за часовым кешем промпта в Claude и называет цену позднего возврата. На каждый UserPromptSubmit он читает свежий блок usage из транскрипта сессии. Кеш истёк, а контекст больше CACHE_TAX_BIG (по умолчанию 50000 токенов) — до отправки появляется стоимость перезаписи. С CACHE_TAX_BLOCK=1 гард вместо предупреждения один раз отказывает с кодом 2; повторная отправка того же сообщения проходит.
Хук на SessionStart для resume и fork печатает простой, объём токенов под перезапись и оценку в долларах. Команда /cache-tax:status показывает карточку целиком: тир, тёплый кеш или холодный, размер контекста и сколько записей, чтений и полных перезаписей уже накопилось за сессию.
Строку статуса плагин не поставляет. node ~/.claude/cache-tax.js --statusline печатает одну строку, и её добавляют в свой скрипт статуса как ещё один ряд. Без node в системе ничего не запустится. На версиях до v2.1.251 скрипт читает транскрипт вместо нативного объекта prompt_cache. Слэш-команды гард пропускает, так что /clear и /compact его не задевают.
Какие задачи решает
- узнать цену возврата к сессии до отправки сообщения
- не платить за перезапись контекста после часового простоя
- остановить случайную отправку в холодный кеш одним отказом
- посмотреть, сколько кеша уже записано, прочитано и перезаписано
- вывести остаток минут кеша в свою строку статуса
Примеры запросов агенту
- Вызови
/cache-tax:statusи скажи, во сколько обойдётся вернуться в эту сессию сейчас. - Поставь
CACHE_TAX_BLOCK=1, чтобы гард один раз отказывал на холодный промпт. - Запусти
node ~/.claude/cache-tax.js --statuslineи добавь эту строку в мой скрипт статуса.
Как установить cache-tax
Через маркетплейс плагинов
/plugin marketplace add karanb192/claude-code-hooks/plugin install cache-tax@claude-code-hooksПо шагам, с командами для каждой платформы: Плагины Claude Code: маркетплейсы, установка и как собрать свой
Вопросы о cache-tax
Как установить cache-tax в Claude Code?
Сначала /plugin marketplace add karanb192/claude-code-hooks, потом /plugin install cache-tax@claude-code-hooks. После установки перезапустите Claude.
Что делает cache-tax?
Считает, во что обойдётся возврат в сессию с остывшим кешем. Предупреждает на холодный промпт, оценивает резюме в долларах и показывает карточку по команде /cache-tax:status.
Что нужно, чтобы плагин заработал?
Нужен node в системе. Строку статуса подключают вручную: плагин её не поставляет, скрипт вызывают с флагом --statusline из своего скрипта статуса.
Исходный текст
cache-tax · MIT
# 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` is one file with no dependencies. Copy it, then call it 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
```
```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` | list rates | JSON overriding per-family prices as `[cache read, 5m write, 1h write]` in $/MTok, e.g. `{"fable-5-1":[0.25,12.5,20]}`. |
Built-in list rates (October 2026): Fable 5.1 and Mythos 5.1 `[0.25, 12.5, 20]`, Fable 5 and Mythos 5 `[1, 12.5, 20]`, Opus 5.5 `[0.2, 5, 8]`, Opus 5 and 4.5 to 4.8 `[0.5, 6.25, 10]`, Opus 4 and 4.1 `[1.5, 18.75, 30]`, Sonnet 5.5 `[0.1, 2.5, 4]`, Sonnet 5 `[0.2, 2.5, 4]`, Sonnet 4.x `[0.3, 3.75, 6]`, Haiku 5.5 `[0.01, 0.125, 0.2]` up to 100k prompt tokens and `[0.05, 0.625, 1]` above, Haiku 4.5 `[0.1, 1.25, 2]`, Haiku 3.5 `[0.08, 1, 1.6]`. Unknown models get token counts and no dollar figure. 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.
## 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 are API list prices. 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. 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
```
© Karan Bansal · MIT · karanb192/claude-code-hooks