Claude Code mod that shows the prompt-cache countdown in the footer and keeps the cache warm while you are away.

A Claude Code mod that shows the prompt-cache countdown in the footer and keeps the cache warm while you are away from the keyboard.
cache warm 3:42 (2 refreshes)
The code of this mod was written by AI.
The model API caches the conversation for 5 minutes (by default), counted from the start of each request. A cached read costs a fraction of an uncached one. If you pause longer than that (reading, a meeting, a coffee), your next prompt pays full price for the whole context again.
cache-warm sends a tiny side request shortly before the cache expires. That request is served from the cache and renews its lifetime. By default it stops after 30 minutes without a prompt (idleLimitMinutes). The cache then stays warm for up to one more cache lifetime.
Assumes the standard 5-minute prompt cache. If your setup uses the 1-hour cache, set
cacheTtlMinutesfirst (see Configuration).
Type this at the prompt of a terminal session:
/plugin install cache-warm --marketplace bastianfuchs/claude-code-cache-warm
Answer y to add the marketplace, then choose a scope (user scope applies to all your sessions). The mod is active right away.
| Footer | Meaning |
|---|---|
cache warm m:ss | Time left until the cache expires. Until the first refresh has read the cache, this assumes that caching works (see Cost). |
cache cold | Cache has expired (or a compaction or a model switch just ran). The next prompt rewrites it. |
cache keep-warm off | The first refresh found no cache hit; the mod switched itself off. |
(N refreshes) | Refreshes sent since your last prompt. Starts again from 0 with each prompt. |
, last X.Xs | Added inside the brackets when the latest refresh took half of the refresh lead or longer (15 seconds with the default lead of 30). |
paused (turn) | A turn is running; it renews the cache itself, so no refresh is sent. The countdown restarts at your prompt and again with each model request of the turn. |
paused (compact) | A compaction is running; a refresh would warm a context about to be replaced. |
paused (until next prompt) | You typed /cache-warm pause. No refreshes; your next prompt ends it. |
idle limit reached | Your last prompt is older than idleLimitMinutes; no more refreshes, the countdown runs out. |
refresh failed: <reason> | The last refresh did not get an answer; retried after 15 seconds. |
| Command | Effect |
|---|---|
/cache-warm start | Turns cache-warm on for the running session. |
/cache-warm stop | Turns it off for the running session: no footer entry, no countdown, no refreshes, and prompts are no longer counted as cold. |
/cache-warm pause | No refreshes until your next prompt, for an absence you know is long. The countdown runs out; the prompt after it is not counted as cold. start ends the pause earlier. |
/cache-warm status | Prints the state, the counters and the active settings. Plain /cache-warm does the same. |
The state is one of:
activepaused (until next prompt): after /cache-warm pause.stopped (start with /cache-warm start): after /cache-warm stop, or in a new session when autoStart is off.disabled (DISABLE_PROMPT_CACHING=1): with the value found, see Cost.disabled (caching verification: first refresh read no tokens from cache): the first refresh found no cache hit. The footer then shows keep-warm off.start and stop last for the running session only, and changing a setting in /config does not undo them. /clear resets the counters to 0 but keeps the last start or stop. Whether a new session starts with cache-warm on is the autoStart option (see Configuration). While stopped, no timer runs. To disable the mod for good, use /plugin disable cache-warm.
The counters count per session and start at 0 with a new one:
cold because the cache lifetime ran out, which paid the full price to rewrite the context. Prompts after a compaction, a model switch, /clear or a pause are not counted: the first three empty the cache whether or not it was kept warm, and a pause lets it run out on purpose, so the counter stays comparable with and without cache-warm. An estimate: it follows the configured cache lifetime, not the real cache state.debugWarnings on (see Configuration). Requests that read less than half of their input from a cache the footer showed as warm, counted for your turns and for refreshes. A large pasted prompt counts too, so this is a hint, not proof of a discarded cache.Compare refreshes sent with cold prompts to see whether keeping the cache warm paid off. A cold prompt costs about as much as 25 refreshes of the same context on Sonnet 5.5 and Opus 5.5, and 12.5 on Haiku 5.5. Other models differ (see Cost).
Install shows a screen for these options. Later, change them in the config menu (/config). A change reloads the mod.
| Option | Default | Meaning |
|---|---|---|
autoStart | on | Whether cache-warm is on when a session starts. Off: type /cache-warm start when you want it. |
cacheTtlMinutes | 5 | Cache lifetime, a choice of 5 (standard cache) or 60 (1-hour cache). |
refreshLeadSeconds | 30 | A refresh is sent this long before the cache expires. Accepted: 5 to 600, and the effective lead is capped at half of cacheTtlMinutes (150 s at 5 minutes). |
idleLimitMinutes | 30 | No refreshes once your last prompt is older than this. |
debugWarnings | off | For watching the cache: a warning line under the prompt and an unexpected rewrites (estimated) counter in /cache-warm status when a request reads less than half of its input from a cache the footer shows as warm. Covers your turns and the refreshes. The line also gives the time the footer showed as left, the time since the last cache use and whether a turn or a refresh made it, which tells an early eviction from a long gap. A large pasted prompt can trigger it too. A second kind of line warns when a refresh read at least 1.8 times as many tokens from the cache as the last request of your turn took in, which a refresh does not normally do; it is not counted. There is one line at a time, a newer one replaces the older, and it stays until your next prompt. |
A value that is not a number or out of range (5 to 600 seconds lead, 1 to 720 minutes idle limit) falls back to its default.
Each refresh re-reads your whole context from the cache at the cached-read price (a fraction of the normal input price) plus a few output tokens. With the defaults it runs roughly every 4 minutes 30 seconds, at most about 6 times per absence (30-minute idle limit). With a large context this is visible on the bill, though far below what one cold prompt costs.
Examples, with the prices per million tokens for a cache read and for a cache write (5 minutes):
| Model | Context | One refresh | Six refreshes | One cold rewrite |
|---|---|---|---|---|
| Sonnet 5.5 | 100k tokens | $0.010 | $0.06 | $0.25 |
| Sonnet 5.5 | 1M tokens | $0.10 | $0.60 | $2.50 |
| Opus 5.5 | 100k tokens | $0.020 | $0.12 | $0.50 |
| Opus 5.5 | 1M tokens | $0.20 | $1.20 | $5.00 |
| Haiku 5.5 | 100k tokens | $0.001 | $0.006 | $0.0125 |
| Haiku 5.5 | 200k tokens | $0.010 | $0.06 | $0.125 |
Output tokens add a little per refresh. Six refreshes cost less than one rewrite, but they are wasted if you do not come back. Other models have other prices and another ratio between a cache read and a cache write, so the numbers above do not carry over. They are the prices of the Anthropic API. Other services such as Amazon Bedrock can charge more, depending on the region. Check the pricing page and your provider's price list.
The footer assumes that caching works and says warm from your first prompt. The first refresh checks that: it must read at least some tokens from the cache. If it reads none, your gateway or setup does not pass caching through. The mod then switches itself off, the footer shows keep-warm off and a toast tells you. That one refresh was billed at the normal input price (no cache read, no cache write) and renewed nothing; no further one is sent. Each session checks afresh, so switching between gateways needs no setting.
If the environment variable DISABLE_PROMPT_CACHING is set to 1, true, yes or on (any case; 0 or empty does not count), Claude Code sends no cache markers, so there is nothing to keep warm. The mod then stays off for the session and shows a toast, whatever autoStart says, and /cache-warm start refuses. The variable is read at session start only.
cacheTtlMinutes to 60 (see Configuration); left at 5, the countdown is wrong (it shows cold after 5 minutes) and every refresh is wasted money. A wrong value is never caught by the mod.cold until your next prompt. The compaction does not cache the new, shorter context. Your next prompt writes it to the cache.warm. If the cache was discarded, that prompt pays the full price and is not counted as a cold prompt. A model switch is detected: the footer shows cold at once.Run it from the folder instead of installing:
claude --plugin-dir /path/to/cache-warm
or set CLAUDE_CODE_PLUGIN_DIRS in ~/.claude/settings.json (env block). Saving hooks/register.tsx reloads the mod in a running session. Check the manifest with claude plugin validate /path/to/cache-warm.
The type declarations in .claude-plugin/types/ are written by Claude Code when it loads the mod from a folder. They are not part of the repository. tsconfig.json refers to them, so an editor reports missing types until you have loaded it once.
RETRY_DELAY_MS at the top of hooks/register.tsx is not an option. Edit it there.
For maintainers: claude plugin update looks at the version in .claude-plugin/plugin.json. Raise it with every release, or installed copies are not offered the change.
hooks/register.tsx 634 lines1// cache-warm: shows the prompt-cache TTL in the footer and keeps the cache warm.
2//
3// The model API caches the conversation prefix for 5 minutes, counted from the start of
4// each request that uses it; a cached read costs a fraction of an uncached one. After a
5// longer pause the next prompt pays full price for the whole context. This mod sends a
6// tiny side request shortly before the TTL runs out, which renews it, until the user
7// has been idle for IDLE_LIMIT_MS.
8//
9// How a mod works, as far as this file needs it:
10// - `register` receives `on`, which attaches a hook to a host event. A hook gets the
11// host handle `$`, the event `e` and `next`, the rest of the chain. Calling
12// `next(e)` (possibly with a changed event) passes control on and returns the
13// result, so a hook can act before and after the host does.
14// - The module is reloaded on edits and its top-level variables are reset. State that
15// must survive lives in an atom (below), kept by the host.
16import { atom, read, update } from 'claude-code'
17import type { Register } from 'claude-code'
18
19import type { CacheWarm } from '../types'
20
21// The five values below come from the plugin's userConfig (see plugin.json); register
22// fills them on every load, the defaults hold until then.
23// How long the prompt cache lives after a request has read or written it, counted from
24// the start of that request (5 min on API keys).
25let CACHE_TTL_MS = 5 * 60_000
26// A refresh is sent this long before the cache expires.
27let REFRESH_LEAD_MS = 30_000
28// No refreshes once the last prompt is older than this; the cache then goes cold.
29let IDLE_LIMIT_MS = 30 * 60_000
30// Whether a new session starts with cache-warm on; /cache-warm start and stop switch it
31// for the running session.
32let AUTO_START = true
33// Whether a request that read less than half its input from a cache the footer calls
34// warm raises a warning line and is counted, and a refresh that read far more than
35// the last request of a turn took in raises a warning line. For watching the cache
36// behaviour, off by default.
37let DEBUG_WARNINGS = false
38// After a failed refresh, wait this long before trying again.
39const RETRY_DELAY_MS = 15_000
40// How long a toast stays; the host's default of 4 s is easy to miss.
41const TOAST_MS = 20_000
42// Shown in the footer while a compaction or a turn blocks refreshes.
43const COMPACT_NOTE = 'paused (compact)'
44const TURN_NOTE = 'paused (turn)'
45const IDLE_NOTE = 'idle limit reached'
46// Footer and status text while /cache-warm pause is in effect; derived from isPaused,
47// not stored in note.
48const PAUSE_NOTE = 'paused (until next prompt)'
49
50// The shared state, kept by the host so that a reload does not lose it. `now` is part
51// of it on purpose: writing it every second makes the footer redraw its countdown.
52// Fields: see ../types.
53const cache = atom(
54 { plugin: 'cache-warm', key: 'cache' } as const,
55 {
56 expiresAt: null,
57 now: 0,
58 tokens: 0,
59 disabledReason: '',
60 isEnabled: null,
61 isVerified: false,
62 refreshCount: 0,
63 totalRefreshCount: 0,
64 coldPromptCount: 0,
65 keptWarmPromptCount: 0,
66 usefulRefreshCount: 0,
67 note: '',
68 } as CacheWarm,
69)
70
71const fmt = (ms: number) => {
72 const s = Math.max(0, Math.round(ms / 1000))
73 return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
74}
75
76const describe = (c: CacheWarm) => {
77 if (!c.isEnabled || c.expiresAt === null) return undefined
78 // A request reads the cache as it starts, which renews it, but expiresAt is only
79 // written once the step has ended. Until then count from the request's start (or
80 // from the prompt, which precedes it): never more time than the cache has. After an
81 // ESC before the answer started, requestStartedAt is gone and the old expiry shows
82 // again, since nothing tells whether the request reached the cache.
83 const expiresAt =
84 c.requestStartedAt === undefined
85 ? c.expiresAt
86 : Math.max(c.expiresAt, c.requestStartedAt + CACHE_TTL_MS)
87 // c.now can be older than the request's start: never show more than the lifetime.
88 const left = Math.min(expiresAt - c.now, CACHE_TTL_MS)
89 const state = c.disabledReason !== ''
90 ? 'keep-warm off'
91 : left <= 0
92 ? 'cold'
93 : `warm ${fmt(left)}`
94 // The count tells that refreshes ran since the last prompt; the duration is only
95 // worth showing when a refresh was slow: it took half the refresh lead or longer, so
96 // the lead is getting tight. The lead scales with the setting, a fixed limit would
97 // not fit a large context.
98 const slow =
99 c.lastRefreshMs !== undefined && c.lastRefreshMs >= REFRESH_LEAD_MS / 2
100 ? `, last ${(c.lastRefreshMs / 1000).toFixed(1)}s`
101 : ''
102 const refreshes =
103 c.refreshCount > 0
104 ? ` (${c.refreshCount} ${c.refreshCount === 1 ? 'refresh' : 'refreshes'}${slow})`
105 : ''
106 const note = c.note !== '' ? c.note : c.isPaused ? PAUSE_NOTE : ''
107 return `cache ${state}${refreshes}${note ? ` · ${note}` : ''}`
108}
109
110type RequestUsage = {
111 input_tokens: number
112 cache_read_input_tokens: number
113 cache_creation_input_tokens: number
114}
115
116// True when a request took less than half of its input from the cache. A large pasted
117// prompt also does that, so this is a hint, not proof of a discarded cache.
118const isMostlyUncached = (u: RequestUsage) => {
119 const read = u.cache_read_input_tokens
120 const total = u.input_tokens + read + u.cache_creation_input_tokens
121 return total > 0 && read * 2 < total
122}
123
124// A refresh normally reads about as many tokens from the cache as the last request of
125// a turn took in. At this multiple of that it counts as read twice.
126const DOUBLE_READ_FACTOR = 1.8
127
128const inputOf = (u: RequestUsage) =>
129 u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
130
131// Pinned as the status line under the prompt, where it stays until the next prompt
132// clears it, for a refresh that read far more from the cache than the last request of
133// a turn took in. `$` is typed `any` as in tick.
134function warnDoubleRead($: any, u: RequestUsage, lastInputTokens: number) {
135 $.ui.status(
136 `refresh read ${u.cache_read_input_tokens} tokens from the cache, ` +
137 `${(u.cache_read_input_tokens / lastInputTokens).toFixed(1)} times the ` +
138 `${lastInputTokens} the last request took in`,
139 )
140}
141
142// Pinned as the status line under the prompt, where it stays until the next prompt
143// clears it. `$` is typed `any` as in tick.
144// The timing tells a server-side early eviction (the footer had time left, the last
145// cache use was recent) from a long gap (a sleeping machine, a stalled clock). Who
146// made that last use matters too: a refresh may reach a cache entry that a turn does
147// not, or the other way round.
148// `before` is the atom as it was when the request started; its expiresAt is not null.
149async function warnRewrite(
150 $: any,
151 source: string,
152 u: RequestUsage,
153 before: CacheWarm,
154 startedAt: number,
155) {
156 await update($, cache, (c: CacheWarm) => ({
157 ...c,
158 rewriteCount: (c.rewriteCount ?? 0) + 1,
159 }))
160 const expiresAt = before.expiresAt as number
161 $.ui.status(
162 `${source} read ${u.cache_read_input_tokens} and wrote ` +
163 `${u.cache_creation_input_tokens} tokens although the cache looked warm ` +
164 `(${fmt(expiresAt - startedAt)} left, last cache use ` +
165 `${fmt(startedAt - (expiresAt - CACHE_TTL_MS))} ago` +
166 `${before.lastUse === undefined ? '' : `, by ${before.lastUse}`})`,
167 )
168}
169
170let lastActivity = 0
171let isRefreshing = false
172// A running turn reads and writes the cache itself; no refresh beside it.
173let isTurnRunning = false
174// A compaction replaces the context; a refresh during it would warm a prefix that is
175// about to be thrown away.
176let isCompacting = false
177let lastFailureAt = 0
178let timer: { cancel: () => void } | undefined
179// The last /cache-warm start or stop. /clear resets the atom but not the module, so
180// this carries the choice over it; a reload resets this, but not the atom.
181let userChoice: boolean | undefined
182
183// Runs every second: updates the clock for the display and, when the cache is about to
184// expire, sends the refresh. It is a top-level function because the host lets `$` be
185// passed only to those; `$` is typed `any` for that reason.
186async function tick($: any) {
187 const now: number = await $.clock.now()
188 const c: CacheWarm = await read($, cache)
189 if (c.expiresAt === null) return
190 // The write redraws the SessionMode hook below, which reads this atom.
191 await update($, cache, (x: CacheWarm) => ({ ...x, now }))
192
193 // A reload resets module variables; count idle time from then on, not from 1970.
194 if (lastActivity === 0) lastActivity = now
195 const isIdle = now - lastActivity > IDLE_LIMIT_MS
196 // Say why the countdown runs down without a refresh. Only into an empty note, so it
197 // is written once and never hides another message; the next prompt replaces it.
198 if (isIdle && c.note === '' && now < c.expiresAt) {
199 await update($, cache, (x: CacheWarm) =>
200 x.note === '' ? { ...x, note: IDLE_NOTE } : x,
201 )
202 }
203 // Not after expiry: a cold cache is rewritten at full price, which the next prompt
204 // does anyway.
205 const isDue = now >= c.expiresAt - REFRESH_LEAD_MS && now < c.expiresAt
206 const isBackingOff = now - lastFailureAt < RETRY_DELAY_MS
207 const isDisabled = c.disabledReason !== ''
208 const isBlocked =
209 isDisabled || isRefreshing || isTurnRunning || isCompacting || c.isPaused === true
210 if (isBlocked || !isDue || isIdle || isBackingOff) return
211
212 isRefreshing = true
213 try {
214 // The API counts the lifetime from the start of the request that reads the cache,
215 // not from the end of its answer, so the new expiry is counted from here too.
216 const startedAt: number = await $.clock.now()
217 let r
218 // A fork repeats the main thread's last request (same model, system prompt, tools
219 // and messages) with this prompt appended and all tools denied. The API therefore
220 // serves the whole conversation from its cache, which renews the TTL; only the
221 // short prompt is computed fresh. Before the first reply there is nothing to fork.
222 try {
223 // The start time makes every prompt different. The text says what the request is
224 // and what to answer, so the model has nothing to look into.
225 r = await $.model.fork({
226 prompt:
227 `Automated keep-alive ${startedAt}: no tools, no commentary, ` +
228 'your entire reply is "ok".',
229 })
230 } catch {
231 r = { isAnswered: false as const, reason: 'error' }
232 }
233 const lastRefreshMs: number = (await $.clock.now()) - startedAt
234 if (!r.isAnswered) {
235 lastFailureAt = startedAt
236 await update($, cache, (x: CacheWarm) => ({
237 ...x,
238 note: `refresh failed: ${r.reason}`,
239 }))
240 return
241 }
242 // Why check at all: nothing in turn.complete says whether the cache was really
243 // written. The footer assumes it was and says "warm" from the first prompt; the
244 // first refresh is the silent test. If it reads any tokens from the cache, caching
245 // works and isVerified is set; if it reads none, the gateway drops caching (or the
246 // cache entry had already expired by then), and every further refresh would pay
247 // the full context price for nothing. Any hit counts, not a share of the context:
248 // the context size is only known roughly (the status line's rounded percentage),
249 // and a cache written just before covers only part of the context. isVerified is
250 // kept in the atom, which a hot reload keeps, and is never checked again once true.
251 if (!c.isVerified) {
252 if (!(r.usage.cache_read_input_tokens > 0)) {
253 await update($, cache, (x: CacheWarm) => ({
254 ...x,
255 disabledReason:
256 'caching verification: first refresh read no tokens from cache',
257 note: 'first refresh read no tokens from cache',
258 }))
259 $.ui.toast('cache-warm: caching not passed through, keep-warm switched off', {
260 timeoutMs: TOAST_MS,
261 })
262 return
263 }
264 }
265 if (DEBUG_WARNINGS && isMostlyUncached(r.usage)) {
266 await warnRewrite($, 'refresh', r.usage, c, startedAt)
267 }
268 if (
269 DEBUG_WARNINGS &&
270 c.lastInputTokens !== undefined &&
271 r.usage.cache_read_input_tokens >= c.lastInputTokens * DOUBLE_READ_FACTOR
272 ) {
273 warnDoubleRead($, r.usage, c.lastInputTokens)
274 }
275 await update($, cache, (x: CacheWarm) => ({
276 ...x,
277 isVerified: true,
278 lastRefreshMs,
279 refreshCount: x.refreshCount + 1,
280 totalRefreshCount: (x.totalRefreshCount ?? 0) + 1,
281 expiresAt: startedAt + CACHE_TTL_MS,
282 lastUse: 'refresh',
283 note: '',
284 }))
285 } finally {
286 isRefreshing = false
287 }
288}
289
290// The value of DISABLE_PROMPT_CACHING when it makes the host send no cache markers
291// (1, true, yes or on), else undefined. `$` is typed `any` here as in tick; the name
292// must be a string literal for `$.env.get`.
293async function cachingDisabledBy($: any): Promise<string | undefined> {
294 const v: string | undefined = await $.env.get('DISABLE_PROMPT_CACHING')
295 return v !== undefined && /^(1|true|yes|on)$/i.test(v.trim()) ? v.trim() : undefined
296}
297
298const envReason = (value: string) => `DISABLE_PROMPT_CACHING=${value}`
299const envText = (value: string) =>
300 `cache-warm: ${envReason(value)}, there is no cache to keep warm`
301
302// Decides the start state while isEnabled is still null: in a new session, and after
303// /clear, which resets the atom but fires no session.start. The option sets the state,
304// never overrides a stop. Without caching a refresh is billed at the normal input
305// price and renews nothing, which the first-refresh check could only find out after
306// paying for one; so the mod does not start at all.
307async function initState($: any) {
308 const envValue = await cachingDisabledBy($)
309 await update($, cache, (c: CacheWarm) => ({
310 ...c,
311 isEnabled: c.isEnabled ?? (envValue === undefined && (userChoice ?? AUTO_START)),
312 // Kept for /cache-warm status, which names why the mod is not running.
313 disabledReason: envValue !== undefined ? envReason(envValue) : c.disabledReason,
314 }))
315 if (envValue !== undefined) $.ui.toast(envText(envValue), { timeoutMs: TOAST_MS })
316}
317
318// A number option, or the default when it is missing, not finite or out of range.
319const num = (v: unknown, fallback: number, min: number, max: number) =>
320 typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max ? v : fallback
321
322export const register: Register = (on, options) => {
323 // A picker over "5" and "60" (see plugin.json); anything else counts as 5.
324 CACHE_TTL_MS = (options.cacheTtlMinutes === '60' ? 60 : 5) * 60_000
325 // The lead must stay below the lifetime, else a refresh is due the moment the cache
326 // is written.
327 REFRESH_LEAD_MS = Math.min(
328 num(options.refreshLeadSeconds, 30, 5, 600) * 1000,
329 CACHE_TTL_MS / 2,
330 )
331 IDLE_LIMIT_MS = num(options.idleLimitMinutes, 30, 1, 720) * 60_000
332 AUTO_START = options.autoStart !== false
333 DEBUG_WARNINGS = options.debugWarnings === true
334
335 // A reload cancels the timer and starts the module afresh; session.start fires again.
336 on('session.start', async ($, e, next) => {
337 // Clears the pinned line an earlier version of this mod left behind.
338 $.ui.status(undefined)
339 // Also runs after a reload, when the atom already holds the user's choice (null
340 // only in a new session).
341 await initState($)
342 await $.command.register({
343 name: 'cache-warm',
344 description: 'Start, stop or pause cache-warm, show its counters and settings',
345 argumentHint: '[start|stop|pause|status]',
346 immediate: true,
347 })
348 if ((await read($, cache)).isEnabled) {
349 timer ??= $.clock.every(1000, () => void tick($))
350 }
351 return next(e)
352 })
353
354 // "status" is the default. start and stop switch the running session only; the
355 // autoStart option decides how the next one begins. pause is for an absence you know
356 // is long: no refreshes until the next prompt, without stopping and starting again.
357 on('command.run', { command: 'cache-warm' }, async ($, e, next) => {
358 const sub = e.args.trim()
359 if (!['', 'status', 'start', 'stop', 'pause'].includes(sub)) {
360 return { text: 'usage: /cache-warm [start|stop|pause|status]' }
361 }
362 if ((await read($, cache)).isEnabled === null) await initState($)
363 if (sub === 'pause') {
364 const c: CacheWarm = await read($, cache)
365 if (!c.isEnabled || c.disabledReason !== '') {
366 return { text: 'nothing to pause, cache-warm is not running' }
367 }
368 await update($, cache, (x: CacheWarm) => ({ ...x, isPaused: true }))
369 return { text: 'paused until your next prompt (start ends it earlier)' }
370 }
371 if (sub === 'start' || sub === 'stop') {
372 const isEnabled = sub === 'start'
373 const envValue = isEnabled ? await cachingDisabledBy($) : undefined
374 if (envValue !== undefined) return { text: envText(envValue) }
375 // `now` is only written by tick, which does not run while stopped: refresh it, or
376 // the footer shows the countdown as it was at stop.
377 const now = await $.clock.now()
378 userChoice = isEnabled
379 await update($, cache, (c: CacheWarm) => ({
380 ...c,
381 isEnabled,
382 now,
383 isPaused: false,
384 }))
385 // Stopped means no timer at all, not a timer that returns at once.
386 if (isEnabled) {
387 timer ??= $.clock.every(1000, () => void tick($))
388 } else {
389 timer?.cancel()
390 timer = undefined
391 }
392 return { text: isEnabled ? 'started' : 'stopped' }
393 }
394 const c: CacheWarm = await read($, cache)
395 // The host puts "cache-warm:" before the text, so the first line is the state.
396 // The footer already shows the cache state.
397 const text = [
398 c.disabledReason !== ''
399 ? `disabled (${c.disabledReason})`
400 : c.isEnabled
401 ? c.isPaused
402 ? PAUSE_NOTE
403 : 'active'
404 : 'stopped (start with /cache-warm start)',
405 ...(c.expiresAt === null ? ['no turn completed yet, no countdown'] : []),
406 `refreshes sent: ${c.totalRefreshCount ?? 0}`,
407 `refreshes useful (estimated): ${c.usefulRefreshCount ?? 0}, ` +
408 `covering ${c.keptWarmPromptCount ?? 0} prompts`,
409 `cold prompts (estimated): ${c.coldPromptCount ?? 0}`,
410 ...(DEBUG_WARNINGS
411 ? [`unexpected rewrites (estimated): ${c.rewriteCount ?? 0}`]
412 : []),
413 `cache lifetime ${CACHE_TTL_MS / 60_000} min, ` +
414 `refresh lead ${REFRESH_LEAD_MS / 1000} s, ` +
415 `idle limit ${IDLE_LIMIT_MS / 60_000} min`,
416 ].join('\n')
417 return { text }
418 })
419
420 // A turn starts here and ends in turn.complete; refreshes stay out in between.
421 // A prompt that arrives after the expiry rewrites the cache at full price: count it.
422 // The prompt's request goes out right after this, so the footer counts from here
423 // (requestStartedAt) until the first step has ended. expiresAt stays: if ESC stops
424 // the request before it reaches the cache, the old expiry is still the true one.
425 // A prompt typed while a turn runs (e.turnId is set) fires this at Enter too, but
426 // sends no request of its own: the running turn picks it up with its next step. It
427 // is the user's activity and nothing else, so the cache fields stay as they are.
428 // A prompt after /cache-warm pause ends the pause. It is not counted as cold: the
429 // user let the cache run out on purpose, as with stop.
430 // A prompt that finds the cache still warm after at least one refresh since the
431 // previous prompt was kept warm by them: those refreshes count as useful. Refreshes
432 // before a cold prompt, a pause or a reset were not (and a refresh in a run that
433 // ended in the idle limit never gets here warm).
434 on('prompt.submit', async ($, e, next) => {
435 if ((await read($, cache)).isEnabled === null) await initState($)
436 const now = await $.clock.now()
437 lastActivity = now
438 if (e.turnId !== undefined) return next(e)
439 // Ends the debugWarnings line of an earlier request.
440 if (DEBUG_WARNINGS) $.ui.status(undefined)
441 isTurnRunning = true
442 await update($, cache, (c: CacheWarm) => {
443 const isKeptWarm =
444 c.isEnabled === true &&
445 !c.isReset &&
446 !c.isPaused &&
447 c.refreshCount > 0 &&
448 c.expiresAt !== null &&
449 now < c.expiresAt
450 return {
451 ...c,
452 refreshCount: 0,
453 keptWarmPromptCount: (c.keptWarmPromptCount ?? 0) + (isKeptWarm ? 1 : 0),
454 usefulRefreshCount:
455 (c.usefulRefreshCount ?? 0) + (isKeptWarm ? c.refreshCount : 0),
456 coldPromptCount:
457 (c.coldPromptCount ?? 0) +
458 (c.isEnabled &&
459 !c.isReset &&
460 !c.isPaused &&
461 c.expiresAt !== null &&
462 now >= c.expiresAt
463 ? 1
464 : 0),
465 isReset: false,
466 isPaused: false,
467 requestStartedAt: now,
468 note: TURN_NOTE,
469 }
470 })
471 return next(e)
472 })
473
474 // Every model request of a turn (after each tool call, too) reads the cache and so
475 // renews its TTL, counted from the start of the request, not from the end of its
476 // answer. The footer counts from there while the step runs (requestStartedAt);
477 // without this, a step started late in the countdown would show "cold" while the
478 // cache was kept alive. expiresAt is written only after the step has ended, and
479 // only if a response arrived. usage is null when the request failed or was
480 // interrupted before the answer started (measured: ESC about 1 s after sending;
481 // after the first text it is set). Such a request may never have reached the cache,
482 // so the old expiry stays. Idle until the first turn completes: the context size
483 // is unknown before that. Subagents carry an agentId and have contexts of their own,
484 // so only the main agent (no agentId) counts. requestStartedAt is set only within a
485 // turn (isTurnRunning): turn.complete clears it, and a request outside a turn (a
486 // compaction, the refresh's fork) has no turn.complete to do that.
487 on('turn.step', async function* ($, e, next) {
488 if (e.agentId !== undefined) return yield* next(e)
489 const startedAt = await $.clock.now()
490 const before: CacheWarm = await read($, cache)
491 const isWarm =
492 before.isEnabled === true &&
493 before.expiresAt !== null &&
494 startedAt < before.expiresAt
495 if (isTurnRunning) {
496 await update($, cache, (c: CacheWarm) => ({ ...c, requestStartedAt: startedAt }))
497 }
498 const r = yield* next(e)
499 if (r.usage !== null) {
500 const now = await $.clock.now()
501 // lastInputTokens is kept even before the first turn has completed (expiresAt is
502 // still null): a refresh is compared with that turn's own steps.
503 await update($, cache, (c: CacheWarm) =>
504 c.expiresAt === null
505 ? { ...c, lastInputTokens: inputOf(r.usage) }
506 : {
507 ...c,
508 now,
509 expiresAt: startedAt + CACHE_TTL_MS,
510 lastUse: 'turn',
511 lastInputTokens: inputOf(r.usage),
512 },
513 )
514 if (DEBUG_WARNINGS && isWarm && isMostlyUncached(r.usage)) {
515 await warnRewrite($, 'turn step', r.usage, before, startedAt)
516 }
517 }
518 return r
519 })
520
521 // A compaction replaces the context, so the cached prefix no longer matches it. The
522 // compaction itself does not cache the new context (measured: the next request read
523 // only the static system prompt and tools from the cache); the next prompt does.
524 // So a successful compaction marks the cache cold (expiresAt = now) and records the
525 // new, shorter size; isReset keeps the next prompt out of the cold count, and
526 // requestStartedAt goes, or the footer would still count from the old request. A
527 // skipped or aborted compaction leaves the context, and with it the cache,
528 // unchanged. Other triggers than manual and auto are left alone.
529 on('session.compact', async ($, e, next) => {
530 if (e.agentId !== undefined || (e.trigger !== 'manual' && e.trigger !== 'auto')) {
531 return next(e)
532 }
533 isCompacting = true
534 await update($, cache, (c: CacheWarm) => ({ ...c, note: COMPACT_NOTE }))
535 try {
536 const r = await next(e)
537 if (r.skip === undefined) {
538 const now = await $.clock.now()
539 await update($, cache, (c: CacheWarm) =>
540 c.expiresAt === null
541 ? c
542 : {
543 ...c,
544 now,
545 expiresAt: now,
546 tokens: r.tokensAfter ?? 0,
547 isReset: true,
548 requestStartedAt: undefined,
549 lastInputTokens: undefined,
550 },
551 )
552 }
553 return r
554 } finally {
555 isCompacting = false
556 await update($, cache, (c: CacheWarm) =>
557 c.note === COMPACT_NOTE ? { ...c, note: '' } : c,
558 )
559 }
560 })
561
562 // The cache belongs to one model: after a switch the new model starts with an empty
563 // one, whatever the countdown says. Mark it cold, as after a compaction; the next
564 // prompt writes it and is not counted as cold (isReset). isVerified stays: it
565 // describes the gateway, not the model, and no refresh is sent while the cache is
566 // marked cold. requestStartedAt goes for the same reason as in the compaction.
567 on('classic.PostModelSwitch', async ($, e, next) => {
568 if (e.from_model !== e.to_model) {
569 const now = await $.clock.now()
570 await update($, cache, (c: CacheWarm) =>
571 c.expiresAt === null
572 ? c
573 : {
574 ...c,
575 now,
576 expiresAt: now,
577 isReset: true,
578 requestStartedAt: undefined,
579 lastInputTokens: undefined,
580 },
581 )
582 }
583 return next(e)
584 })
585
586 // Adds one entry to the footer's mode labels (SessionMode). Redrawn whenever the
587 // atom changes.
588 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
589 const text = describe(await read($, cache))
590 if (text === undefined) return next(e)
591 return next({ ...e, props: { ...e.props, modes: [...e.props.modes, text] } })
592 })
593
594 // The cache lives from the start of the turn's last request (requestStartedAt), not
595 // from the end of its answer: a long answer has used up part of the lifetime. Without
596 // requestStartedAt (cleared by a compaction, model switch or /clear during the turn)
597 // the end of the turn is the fallback. An interrupted turn may or may not have
598 // reached the cache; keep the old expiry. An answer has written the cache, so a
599 // reset by an automatic compaction in the middle of the turn is spent: isReset ends
600 // here, not only at the next prompt.
601 on('turn.complete', async ($, e, next) => {
602 if (e.agentId !== undefined) return next(e)
603 isTurnRunning = false
604 const now = await $.clock.now()
605 const isAnswer = Boolean(e.usage) && e.reason === 'answer'
606 let tokens = 0
607 if (isAnswer) {
608 // Neither e.usage nor context.tokens is the live context: both sum several
609 // requests. The status line's percentage of the window is.
610 const { context } = await $.session.usage()
611 tokens = Math.round(((context.percent ?? 0) / 100) * context.window)
612 if (lastActivity === 0) lastActivity = now
613 }
614 // One write, so the footer never shows the turn as over with the old expiry.
615 await update($, cache, (c: CacheWarm) => ({
616 ...c,
617 ...(isAnswer
618 ? {
619 expiresAt: (c.requestStartedAt ?? now) + CACHE_TTL_MS,
620 now,
621 tokens,
622 isReset: false,
623 }
624 : {}),
625 requestStartedAt: undefined,
626 note: c.note === TURN_NOTE ? '' : c.note,
627 }))
628 if (isAnswer && (await read($, cache)).isEnabled) {
629 timer ??= $.clock.every(1000, () => void tick($))
630 }
631 return next(e)
632 })
633}
634types/index.d.ts 46 lines1export type CacheWarm = {
2 expiresAt: number | null
3 now: number
4 tokens: number
5 // why the mod cannot run (env variable or failed verification); '' when it can
6 disabledReason: string
7 // null until session.start decides it from the autoStart option
8 isEnabled: boolean | null
9 isVerified: boolean
10 lastRefreshMs?: number
11 refreshCount: number
12 totalRefreshCount: number
13 coldPromptCount: number
14 // prompts that met a cache which refreshes had kept warm, and the refreshes since
15 // the previous prompt that bridged the gap to them (estimated, like coldPromptCount)
16 keptWarmPromptCount?: number
17 usefulRefreshCount?: number
18 // the host emptied the cache (compaction, model switch) and no answer has written it
19 // since; the next prompt pays for that whether or not the cache was kept warm, so it
20 // is not counted as cold
21 isReset?: boolean
22 // when the latest model request of the running turn started (the prompt's time
23 // until the first one does); set only while a turn runs. The server counts the
24 // cache lifetime from the start of the last request that read or wrote the cache.
25 requestStartedAt?: number
26 // /cache-warm pause: no refreshes until the next prompt, which is not counted as cold
27 isPaused?: boolean
28 // debugWarnings: requests that read under half their input from a cache that looked
29 // warm
30 rewriteCount?: number
31 // what made the latest request that renewed the cache; named in the debugWarnings
32 // line
33 lastUse?: 'turn' | 'refresh'
34 // input (read, written and uncached) of the latest model request of a turn; what a
35 // refresh's cache read is compared with. Unset after a compaction or a model switch,
36 // when the old size no longer fits.
37 lastInputTokens?: number
38 note: string
39}
40
41declare module 'claude-code' {
42 interface PluginState {
43 'cache-warm': { cache: CacheWarm }
44 }
45}
46