Keeps the prompt cache warm with a cheap ping while the session is idle, forked so it never enters the transcript; reads the real cache lifetime (5m or 1h) and…

Keeps the Claude Code prompt cache warm while the session sits idle, so the next message reads the conversation from cache instead of paying to write it again.
While armed, it watches how long the session has been idle. Shortly before the cache would expire it sends a one-line ping:
Cache keep-alive ping. Reply with the single word "ok" and use no tools.
The ping is a fork ($.model.fork): the main thread's last request again, with the ping after it. The cache serves that request's prefix, which restarts the cache's lifetime, and the ping and its reply never enter the transcript, so pinging adds nothing to the context, however long you stay away. It costs a cache read of the context plus a one-word reply. Off by default.
| Command | Does |
|---|---|
/cache-keepalive on | Arm it for this session |
/cache-keepalive off | Disarm it |
/cache-keepalive status | Model, cache lifetime and where it was read from, pings used / budget, spacing |
While armed, it draws a line above the prompt, under cache-gauge's when that mod is installed:
↻ keepalive 3/24 · $0.09 spent · next ping 2:10 · keeps warm ~1h34m
↻ keepalive 24/24 · $0.72 spent · budget used, cache lapses in 4:12
↻ keepalive 3/24 · waits for the turn to end
↻ keepalive 0/24 · cache already cold, nothing to keep warm
spent is what this idle period's pings have cost, measured from the session's total. keeps warm is how long the cache will stay warm if you stay away: the remaining pings plus one cache lifetime after the last. Off, it draws nothing.
Each ping raises a native notification through your terminal's notification channel (the preferredNotifChannel setting), so you see what idling costs even when you're away from the terminal:
Cache keep-alive
Idle: ping 3/24, $0.09 spent with nobody working; keeps the cache warm ~1h34m more. Reply, or /cache-keepalive off.
When the budget runs out, a last notification says so. Set notifyEvery to 3 to hear only every third ping, or to 0 to turn notifications off. The band line still shows the cost either way.
Pinging forever would cost more than letting the cache go cold once. So each idle period has a budget, the smallest of:
(write − read) / read pings, scaled by budgetFactor. On Claude Opus 5.5 with a 5-minute cache that is (1.25 − 0.05) / 0.05 = 24 pings, about 1h48m of idle time at the default spacing.maxPings, a hard cap.maxHours, the longest an idle period is kept warm. This matters for a 1-hour cache, where break-even alone would allow almost a day.When the budget runs out it notifies you once and lets the cache lapse. Any message of your own starts a new idle period with a fresh budget. Subagent turns are ignored, since they say nothing about the main conversation's cache. After the machine sleeps past the expiry it sees the cache is already cold and sends nothing.
It also stops when a ping shows the cache was already gone: the fork reports how much of the prefix the cache served, and when that is near zero (the entry lapsed early, or /model changed the model) pinging again would only pay for the whole context each time. It waits for your next reply instead. An API error (a 429, an overload) does not use up a ping; it tries again 30 seconds later.
With ttl: auto it reads the lifetime from Claude Code's own controls, in Claude Code's precedence:
FORCE_PROMPT_CACHING_5M=1 → 5mCLAUDE_CODE_PROMPT_CACHE_TTL (5m / 1h)promptCacheTtl settingENABLE_PROMPT_CACHING_1H=1 → 1h| Option | Default | Meaning |
|---|---|---|
autoStart | false | Arm it when a session starts |
ttl | auto | auto, 5m or 1h (see above) |
intervalPercent | 90 | Idle share of the lifetime before a ping, clamped to 50–95. 90 is 4:30 on a 5m cache |
budgetFactor | 1 | Scales the break-even budget: 0.5 stops at half of it |
maxPings | 40 | Hard cap on pings per idle period |
maxHours | 4 | Hard cap on how long one idle period is kept warm |
notifyEvery | 1 | Raise a notification after every Nth ping; 0 turns them off |
Read prices come from the model id: 0.025× input for Fable and Mythos, 0.05× for Opus 5.5, 0.1× for everything else.
hooks/register.tsx 340 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, ModelUsage, Register } from 'claude-code'
3
4import type { KeepaliveView } from '../types'
5
6import { clock, describe, money, plan, resolveTtl } from './budget'
7import type { PlanOptions, Ttl } from './budget'
8
9const NAME = 'cache-keepalive'
10const TICK_MS = 1000
11const view = atom({ plugin: 'cache-keepalive', key: 'view' } as const, { kind: 'off' } as KeepaliveView)
12// Survives a reload, which starts the module over: idle time counts from the cache's last use
13// (a reply or a ping), not the reload.
14const lastReply = atom({ plugin: 'cache-keepalive', key: 'lastReply' } as const, 0)
15const PING = 'Cache keep-alive ping. Reply with the single word "ok" and use no tools.'
16// How long to wait before trying again after an API error (429, 529, a dropped connection).
17const RETRY_MS = 30_000
18
19type Keepalive = {
20 options: PlanOptions
21 override: unknown
22 isEnabled: boolean
23 isBusy: boolean
24 /** A fork is in flight; the tick must not send a second one. */
25 isPinging: boolean
26 /** A ping found the cache already gone, or there was no conversation to fork yet. */
27 hasLapsed: boolean
28 hasWarned: boolean
29 model: string | undefined
30 ttl: Ttl
31 ttlSource: string
32 /** When the cache was last used: the main thread's last reply or the last ping that read it. */
33 lastActivity: number
34 /** No ping before this, after an API error. */
35 retryAt: number
36 /** Counts idle periods, so a ping that returns after a message of your own is dropped. */
37 period: number
38 pings: number
39 notifyEvery: number
40 /** What this idle period's pings have cost, from the session total. */
41 spentUsd: number
42}
43
44const number = (value: unknown, fallback: number) =>
45 typeof value === 'number' && Number.isFinite(value) ? value : fallback
46
47// Re-read where Claude Code takes the cache lifetime from, so a changed setting is picked up.
48async function refreshTtl($: EngineInterface, k: Keepalive) {
49 const settings: Record<string, unknown> = await $.settings.read()
50 const resolved = resolveTtl({
51 override: k.override,
52 force5m: await $.env.get('FORCE_PROMPT_CACHING_5M'),
53 env: await $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL'),
54 setting: settings.promptCacheTtl,
55 enable1h: await $.env.get('ENABLE_PROMPT_CACHING_1H'),
56 })
57
58 k.ttl = resolved.ttl
59 k.ttlSource = resolved.source
60}
61
62// A tick redraws the band only when what it shows changed.
63async function show($: EngineInterface, next: KeepaliveView) {
64 const was = await read($, view)
65 if (JSON.stringify(was) !== JSON.stringify(next)) {
66 await update($, view, () => next)
67 }
68}
69
70async function sessionUsd($: EngineInterface): Promise<number | null> {
71 try {
72 return (await $.session.usage({ breakdown: 'summary' })).cost?.usd ?? null
73 } catch {
74 return null
75 }
76}
77
78// A native notification, so the person away from the terminal sees what idling costs.
79async function notify($: EngineInterface, k: Keepalive, text: string) {
80 if (k.notifyEvery <= 0) {
81 return
82 }
83 try {
84 await $.ui.notify(text, { title: 'Cache keep-alive' })
85 } catch {
86 // A Notification hook denied it, or the write failed: the band still shows it.
87 }
88}
89
90// A fork read the prefix from cache only if the cache served most of it; near zero, the entry had lapsed.
91const isCacheHit = (u: ModelUsage) => u.cache_read_input_tokens > 0 && u.cache_read_input_tokens >= u.input_tokens + u.cache_creation_input_tokens
92
93// One ping: a fork over the main thread's last request reads its prefix from cache, which
94// restarts the cache's lifetime, and adds nothing to the transcript. A ping turn would stay
95// in the conversation for good, and with it every later request.
96async function ping($: EngineInterface, k: Keepalive) {
97 // Set before the first await: the next tick must not start a second fork.
98 k.isPinging = true
99 k.pings += 1
100 const period = k.period
101
102 try {
103 const fromUsd = await sessionUsd($)
104 const r = await $.model.fork({ prompt: PING })
105 if (k.period !== period) {
106 return
107 }
108 const toUsd = await sessionUsd($)
109 if (fromUsd !== null && toUsd !== null && toUsd > fromUsd) {
110 k.spentUsd += toUsd - fromUsd
111 }
112
113 if (!r.isAnswered && (r.reason === 'api-error' || r.reason === 'aborted')) {
114 k.pings -= 1
115 k.retryAt = (await $.clock.now()) + RETRY_MS
116 } else if (!('usage' in r) || !isCacheHit(r.usage)) {
117 // Nothing cached to keep warm (nothing to fork yet, or the entry had lapsed):
118 // wait for the next reply instead of paying for the prefix again.
119 k.hasLapsed = true
120 } else {
121 k.lastActivity = await $.clock.now()
122 await update($, lastReply, () => k.lastActivity)
123 await settlePing($, k)
124 }
125 } catch {
126 // The engine refused to send it: try again later rather than on every tick.
127 k.pings -= 1
128 k.retryAt = (await $.clock.now()) + RETRY_MS
129 } finally {
130 k.isPinging = false
131 }
132}
133
134// After a ping: say every `notifyEvery` pings what idling has cost.
135async function settlePing($: EngineInterface, k: Keepalive) {
136 if (k.notifyEvery <= 0 || k.pings % k.notifyEvery !== 0) {
137 return
138 }
139 const p = plan(k.model, k.ttl, k.options)
140 const left = p.limit - k.pings
141 const tail =
142 left > 0
143 ? `keeps the cache warm ~${clock(left * p.intervalMs + p.ttlMs)} more`
144 : `that was the last, the cache lapses in ${clock(p.ttlMs)}`
145 await notify(
146 $,
147 k,
148 `Idle: ping ${k.pings}/${p.limit}, ${money(k.spentUsd)} spent with nobody working; ${tail}. Reply, or /cache-keepalive off.`,
149 )
150}
151
152async function step($: EngineInterface, k: Keepalive) {
153 if (!k.isEnabled) {
154 await show($, { kind: 'off' })
155 return
156 }
157
158 const p = plan(k.model, k.ttl, k.options)
159 const counts = { pings: k.pings, limit: p.limit, spentUsd: k.spentUsd }
160 const now = await $.clock.now()
161 const idle = now - k.lastActivity
162
163 if (k.isBusy) {
164 await show($, { kind: 'busy', ...counts })
165 return
166 }
167
168 if (k.isPinging) {
169 return
170 }
171
172 if (k.hasLapsed || idle >= p.ttlMs) {
173 await show($, { kind: 'cold', ...counts })
174 return
175 }
176
177 if (k.pings >= p.limit) {
178 await show($, { kind: 'spent', ...counts, lapsesInMs: p.ttlMs - idle })
179
180 if (!k.hasWarned) {
181 k.hasWarned = true
182 await notify($, k, `Budget used: ${p.limit} pings cost ${money(k.spentUsd)}. The cache lapses in ${clock(p.ttlMs - idle)}.`)
183 }
184
185 return
186 }
187
188 if (idle >= p.intervalMs && now >= k.retryAt) {
189 await ping($, k)
190 return
191 }
192
193 const nextPingMs = Math.max(p.intervalMs - idle, k.retryAt - now)
194 // The last ping still leaves the cache warm for a full lifetime after it.
195 const warmForMs = nextPingMs + (p.limit - k.pings - 1) * p.intervalMs + p.ttlMs
196
197 await show($, { kind: 'waiting', ...counts, nextPingMs, warmForMs })
198}
199
200export const register: Register = (on, options) => {
201 const k: Keepalive = {
202 options: {
203 factor: number(options.budgetFactor, 1),
204 hardCap: number(options.maxPings, 40),
205 maxHours: number(options.maxHours, 4),
206 intervalPercent: number(options.intervalPercent, 90),
207 },
208 override: options.ttl,
209 isEnabled: options.autoStart === true,
210 isBusy: false,
211 isPinging: false,
212 hasLapsed: false,
213 hasWarned: false,
214 model: undefined,
215 ttl: '5m',
216 ttlSource: 'default (assumed)',
217 lastActivity: 0,
218 retryAt: 0,
219 period: 0,
220 pings: 0,
221 notifyEvery: Math.max(0, Math.floor(number(options.notifyEvery, 1))),
222 spentUsd: 0,
223 }
224
225 on('session.start', async ($, e, next) => {
226 const held = await read($, lastReply)
227 k.lastActivity = held > 0 ? held : await $.clock.now()
228 await refreshTtl($, k)
229 // Priced from the start: an unknown model falls back to the 0.1x read price,
230 // which shrinks Opus 5.5's break-even budget from 24 pings to 11.
231 try {
232 k.model = (await $.session.usage({ breakdown: 'summary' })).context.breakdown?.model ?? k.model
233 } catch {
234 // Left unknown until the first reply names it.
235 }
236
237 await $.command.register({
238 name: NAME,
239 description: 'Keep the prompt cache warm while idle: /cache-keepalive on | off | status',
240 })
241
242 $.clock.every(TICK_MS, () => void step($, k))
243
244 return next(e)
245 })
246
247 on('turn.start', ($, e, next) => {
248 k.isBusy = true
249
250 return next(e)
251 })
252
253 on('turn.complete', async ($, e, next) => {
254 // A subagent's turn says nothing about the main conversation's cache.
255 if (e.agentId === undefined) {
256 k.isBusy = false
257 k.hasLapsed = false
258 k.lastActivity = await $.clock.now()
259 await update($, lastReply, () => k.lastActivity)
260 k.model = e.usage?.model ?? k.model
261 }
262
263 return next(e)
264 })
265
266 // Pings are forks and submit nothing, so every prompt starts a new idle period.
267 on('prompt.submit', ($, e, next) => {
268 k.period += 1
269 k.pings = 0
270 k.spentUsd = 0
271 k.hasWarned = false
272 k.retryAt = 0
273
274 return next(e)
275 })
276
277 on('command.run', { command: NAME }, async ($, e) => {
278 const arg = e.args.trim().toLowerCase()
279
280 if (arg === 'on') {
281 await refreshTtl($, k)
282 k.isEnabled = true
283 k.period += 1
284 k.pings = 0
285 k.spentUsd = 0
286 k.hasWarned = false
287 k.hasLapsed = false
288 k.retryAt = 0
289 await step($, k)
290
291 const p = plan(k.model, k.ttl, k.options)
292
293 return {
294 text: `Cache keep-alive armed: ${p.ttl} cache (${k.ttlSource}), up to ${p.limit} pings, one every ${clock(p.intervalMs)}.`,
295 }
296 }
297
298 if (arg === 'off') {
299 k.isEnabled = false
300 await show($, { kind: 'off' })
301
302 return { text: 'Cache keep-alive off.' }
303 }
304
305 await refreshTtl($, k)
306 const p = plan(k.model, k.ttl, k.options)
307
308 return {
309 text: `Cache keep-alive ${k.isEnabled ? 'armed' : 'off'}: model ${k.model ?? 'unknown yet'}, ${p.ttl} cache (${k.ttlSource}), ${k.pings}/${p.limit} pings this idle period (${money(k.spentUsd)}), one every ${clock(p.intervalMs)}.`,
310 }
311 })
312
313 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
314 const v = await read($, view)
315 if (e.props.hasSurvey || v.kind === 'off') {
316 return next(e)
317 }
318
319 const { Box, Text } = $.ui.resolve(e)
320 const line = describe(v)
321 const mine = (
322 <Box>
323 <Text color={line.color} dimColor={line.color === undefined}>↻ </Text>
324 <Text dimColor>{line.text}</Text>
325 </Box>
326 )
327 // Wrap, not replace: another mod's line (cache-gauge) stays in the band.
328 const below = await next(e)
329
330 return below ? (
331 <Box flexDirection="column">
332 {below}
333 {mine}
334 </Box>
335 ) : (
336 mine
337 )
338 })
339}
340hooks/budget.ts 91 lines1import type { KeepaliveView } from '../types'
2
3export type Ttl = '5m' | '1h'
4
5const TTL_MS: Record<Ttl, number> = { '5m': 5 * 60_000, '1h': 60 * 60_000 }
6
7// Cache-write price as a multiple of the base input price.
8const WRITE: Record<Ttl, number> = { '5m': 1.25, '1h': 2 }
9
10export type PlanOptions = {
11 factor: number
12 hardCap: number
13 maxHours: number
14 intervalPercent: number
15}
16
17export type Plan = { ttl: Ttl; ttlMs: number; intervalMs: number; limit: number }
18
19const isTtl = (value: unknown): value is Ttl => value === '5m' || value === '1h'
20
21// Cache-read price as a fraction of the base input price, by model id.
22export function readRatio(model: string | undefined): number {
23 const id = (model ?? '').toLowerCase()
24
25 if (id.includes('fable') || id.includes('mythos')) return 0.025
26 if (id.includes('opus-5-5') || id.includes('opus-5.5')) return 0.05
27
28 return 0.1
29}
30
31// The cache lifetime Claude Code requests, by its documented precedence. It cannot
32// see the billing type, so the unset default is the safe 5m: a 1h cache just gets
33// pinged more often than it needs.
34export function resolveTtl(input: {
35 override?: unknown
36 force5m?: string
37 env?: string
38 setting?: unknown
39 enable1h?: string
40}): { ttl: Ttl; source: string } {
41 if (isTtl(input.override)) return { ttl: input.override, source: 'mod option' }
42 if (input.force5m === '1') return { ttl: '5m', source: 'FORCE_PROMPT_CACHING_5M' }
43 if (isTtl(input.env)) return { ttl: input.env, source: 'CLAUDE_CODE_PROMPT_CACHE_TTL' }
44 if (isTtl(input.setting)) return { ttl: input.setting, source: 'promptCacheTtl setting' }
45 if (input.enable1h === '1') return { ttl: '1h', source: 'ENABLE_PROMPT_CACHING_1H' }
46
47 return { ttl: '5m', source: 'default (assumed)' }
48}
49
50// Pings are spaced at a share of the lifetime, and capped where a lapsed cache would
51// have been cheaper: one miss costs (write - read) x context, one ping read x context.
52export function plan(model: string | undefined, ttl: Ttl, options: PlanOptions): Plan {
53 const ratio = readRatio(model)
54 const ttlMs = TTL_MS[ttl]
55 const percent = Math.min(95, Math.max(50, options.intervalPercent))
56 const intervalMs = Math.round((ttlMs * percent) / 100)
57 // The epsilon absorbs float error (1.2 / 0.05 is 23.999...).
58 const breakEven = Math.floor(((WRITE[ttl] - ratio) / ratio) * options.factor + 1e-9)
59 const byTime = Math.floor((options.maxHours * 3_600_000) / intervalMs)
60
61 return { ttl, ttlMs, intervalMs, limit: Math.max(1, Math.min(breakEven, options.hardCap, byTime)) }
62}
63
64export function clock(ms: number): string {
65 const total = Math.max(0, Math.round(ms / 1000))
66 const minutes = Math.floor(total / 60)
67 const seconds = String(total % 60).padStart(2, '0')
68
69 if (minutes >= 60) return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}m`
70
71 return `${minutes}:${seconds}`
72}
73
74export const money = (usd: number): string => (usd < 0.01 ? `$${usd.toFixed(3)}` : `$${usd.toFixed(2)}`)
75
76/** The band line for an armed keep-alive: glyph colour and text. */
77export function describe(v: Exclude<KeepaliveView, { kind: 'off' }>): { color: 'success' | 'warning' | undefined; text: string } {
78 const head = `keepalive ${v.pings}/${v.limit}${v.spentUsd > 0 ? ` · ${money(v.spentUsd)} spent` : ''}`
79
80 switch (v.kind) {
81 case 'waiting':
82 return { color: 'success', text: `${head} · next ping ${clock(v.nextPingMs)} · keeps warm ~${clock(v.warmForMs)}` }
83 case 'spent':
84 return { color: 'warning', text: `${head} · budget used, cache lapses in ${clock(v.lapsesInMs)}` }
85 case 'busy':
86 return { color: 'success', text: `${head} · waits for the turn to end` }
87 case 'cold':
88 return { color: undefined, text: `${head} · cache already cold, nothing to keep warm` }
89 }
90}
91types/index.d.ts 13 lines1/** What the band line shows; `off` draws nothing. */
2export type KeepaliveView =
3 | { kind: 'off' }
4 | { kind: 'busy' | 'cold'; pings: number; limit: number; spentUsd: number }
5 | { kind: 'spent'; pings: number; limit: number; spentUsd: number; lapsesInMs: number }
6 | { kind: 'waiting'; pings: number; limit: number; spentUsd: number; nextPingMs: number; warmForMs: number }
7
8declare module 'claude-code' {
9 interface PluginState {
10 'cache-keepalive': { view: KeepaliveView; lastReply: number }
11 }
12}
13