Prompt-cache meter above the Claude Code prompt: how many tokens each request read from, wrote to and sent past the cache, a live countdown to the cache's…

A prompt-cache meter above the Claude Code prompt. Every request Claude makes reports how much of its prompt the cache served, how much it wrote and how much went uncached; this mod keeps those numbers per request and per turn, counts down to the moment the cache lapses and tells you what to do about it: keep going, /compact or /clear.
cache ██████████ 98% read 80k · wrote 1k · new 300 ⏱ 3:41 5m · warm, keep going
cache ░░░░░░░░░░ 0% read 0 · wrote 52k · new 300 ⏱ 4:58 5m · cache missed: model changed (…)
cache ██████████ 98% read 150k · wrote 1k · new 300 ⏱ 0:00 5m · expired: the next message rewrites 151k tokens. /compact first, or /clear if the task is done
/cache opens a pane: the time left with a solid bar that shrinks as the cache runs out (green, yellow below 40% of the lifetime, red from the warning threshold), a stacked read / wrote / new bar for the last request, and a colour-coded table with one row per turn. Bars are filled cells and columns have fixed widths with no-break spaces, so the terminal and the Desktop (HTML) pane render the same.
From Anthropic's prompt caching documentation:
input_tokens (uncached remainder) + cache_read_input_tokens + cache_creation_input_tokens./compact./clear starts a new conversation in the same process, so the meter and the /cache table start over with it. A change in the prefix (model, effort or thinking settings, tool set, system prompt, CLAUDE.md) makes the next request write instead of read. The mod names the cause when it sees a miss: model changed, the cache had lapsed, or the prefix changed.The mod follows Claude Code's own rules (prompt caching: cache lifetime, Claude Code 2.1.242 or later). For the main conversation the TTL is the first match of:
| # | Source | Result |
|---|---|---|
| 1 | the mod's ttl option (5m / 1h) | what you set |
| 2 | FORCE_PROMPT_CACHING_5M=1 | 5 minutes |
| 3 | CLAUDE_CODE_PROMPT_CACHE_TTL | 5m or 1h |
| 4 | the promptCacheTtl setting (local, project or user settings file) | 5m or 1h |
| 5 | ENABLE_PROMPT_CACHING_1H=1 | 1 hour |
| 6 | the account | 1 hour on a Claude subscription within its plan usage; 5 minutes on usage credits, an API key or a cloud provider |
The account comes from the rate-limit windows the last response reported: a five_hour or seven_day window means a subscription, and one at 100% means requests now draw on usage credits. An API key or a cloud provider reports no such window, and before the first response nothing is known, so the mod starts from 5 minutes there. Managed settings are not readable from a mod.
On top of that the mod watches the traffic, which beats rows 2 to 6: a request that hits the cache more than 5 minutes after the previous one proves the 1-hour lifetime (a later miss does not undo it, since a changed prefix looks the same), and a miss 5 to 60 minutes after the previous request, with the same model and a prompt that did not shrink, says the entry lapsed, so 5 minutes (a later hit overrules it). That covers what the mod cannot see: managed settings, a gateway that rewrites the TTL, or a subscription that ran out of plan usage mid-session. The pane header names the source in use.
Why the mod infers instead of reading it: the API names the TTL of each write (cache_creation.ephemeral_5m_input_tokens / ephemeral_1h_input_tokens) and Claude Code's status line exposes it as prompt_cache.ttl, but the mod API passes on only the four token counts. To check by hand, claude -p "hello" --output-format json and read usage.cache_creation.
Other switches read from the environment at session start:
| Variable | Effect on the meter |
|---|---|
DISABLE_PROMPT_CACHING=1 (and _HAIKU, _SONNET, _OPUS) | the band says caching is off for that model |
turn.step: reads each main-loop request's usage (subagents have their own prefixes and are left out)$.clock.every(1000): redraws the countdown, and only while its text changes, so an idle expired session costs nothingui.render on AbovePrompt (the band) and on Pane (/cache)$.ui.toast: once per cache entry at the warning threshold (60 s by default) and again at 10, 3, 2 and 1 seconds left, for prompts of 20k tokens or more ttl: string "auto" | "5m" | "1h" (default auto)
warnSeconds: number countdown threshold for the yellow state and the toast (default 60)
compactAtTokens: number prompt size that makes an expired cache suggest /compact (default 100000)
band: boolean row above the prompt (default true)
status: boolean entry under the prompt, "cache 98% · 3:41" (default false)
toast: boolean toasts at the threshold, 10, 3, 2 and 1 s (default true)
The 100k compactAtTokens is a judgement, not a figure from the documentation: lower it if your model's cache writes are expensive for you.
npx claude-code-templates@latest --mod observability/prompt-cache-control
claude
It is written to .claude/skills/prompt-cache-control/, which Claude Code auto-loads as prompt-cache-control@skills-dir once the workspace trust prompt is accepted. For one session with hot reload: claude --plugin-dir .claude/skills/prompt-cache-control. claude plugin validate .claude/skills/prompt-cache-control prints every event it hooks and every $ call it makes; claude plugin test .claude/skills/prompt-cache-control runs its tests.
Options are read from user settings (~/.claude/settings.json, never project settings), --settings <file> or managed settings, under the plugin's full id:
{ "pluginConfigs": { "prompt-cache-control@skills-dir": { "options": { } } } }
Requirements. Mods are on by default in Claude Code 2.1.287+. Typed against Anthropic's declarations: https://github.com/anthropics/claude-code/tree/main/mods
hooks/prompt-cache-control.tsx 1135 lines1/**
2 * prompt-cache-control — Claude Mod
3 *
4 * A prompt-cache meter for Claude Code. Every main-loop request reports how
5 * many prompt tokens the cache served (`cache_read_input_tokens`), wrote
6 * (`cache_creation_input_tokens`) and sent uncached (`input_tokens`); this mod
7 * keeps those per request and per turn, counts down to the moment the cache
8 * lapses, and says what to do about it: keep going, /compact or /clear.
9 *
10 * - `turn.step` reads each main-loop request's usage (subagents have their
11 * own prefixes and are left out)
12 * - `$.clock.every(1000)` redraws the countdown, and only while its text
13 * changes: an idle, expired session costs nothing
14 * - `/keepwarm` pings the cache after idle stretches (ported from cache-tax)
15 * - a row above the prompt (the AbovePrompt component), an optional status
16 * line entry, and `/cache`, a pane with one row per turn
17 *
18 * The lifetime is counted from the start of the request that last wrote or read
19 * the cache, as Anthropic documents it. Which lifetime Claude Code asked for
20 * follows its documented rules (see decideTtl in ./cache.ts): FORCE_PROMPT_CACHING_5M,
21 * CLAUDE_CODE_PROMPT_CACHE_TTL, the promptCacheTtl setting, ENABLE_PROMPT_CACHING_1H,
22 * then the account (1 hour on a Claude subscription, 5 minutes otherwise). The
23 * API names the TTL of a write but the mod API passes on only the token counts,
24 * so the mod also watches the gaps between requests (a hit after more than 5
25 * minutes proves 1 hour; see observeTtl). `ttl: "5m" | "1h"` pins it.
26 *
27 * Needs Claude Code >= 2.1.287.
28 *
29 * Options (pluginConfigs["prompt-cache-control@skills-dir"].options):
30 * ttl: "auto" | "5m" | "1h" cache lifetime (default auto)
31 * warnSeconds: number countdown threshold for the warning (default 60)
32 * compactAtTokens: number prompt size that makes an expired cache suggest /compact (default 100000)
33 * band: boolean row above the prompt (default true)
34 * breakdown: boolean read/wrote/new token counts in the band (default true)
35 * status: boolean entry under the prompt (default false)
36 * toast: boolean toasts near expiry: at warnSeconds, then 10, 3, 2 and 1 s (default true)
37 */
38import type { EngineInterface, Register, RenderChildren } from 'claude-code'
39import {
40 calibRate,
41 windowSpend,
42 type Spend,
43 guardVerdict,
44 idleCompactState,
45 isColdWrite,
46 advise,
47 ttlMs,
48 COUNTDOWN_MARKS,
49 bar,
50 byTurn,
51 fmtClock,
52 fmtCountdown,
53 fmtLimit,
54 fmtTokens,
55 hitRatio,
56 isCachingDisabled,
57 accountOf,
58 decideTtl,
59 observeTtl,
60 lifeColor,
61 lifeRatio,
62 nextToastMark,
63 positive,
64 promptTokens,
65 remainingMs,
66 rowRatio,
67 segments,
68} from './cache.ts'
69import type { Account, Advice, CacheEnv, GuardMode, Sample, Ttl } from './cache.ts'
70
71const PANE = 'cache'
72// the pane's label column
73const LABEL_W = 13
74const COMMAND = 'cache'
75const KEEP = 200
76// below this a lapsed cache costs too little to interrupt anyone about
77const TOAST_MIN_TOKENS = 20_000
78
79let samples: Sample[] = []
80let ttl: Ttl = '5m'
81let baseTtl: Ttl = '5m'
82let pinned = false
83let observed: Ttl | undefined
84let setting: unknown
85let account: Account = 'other'
86/** the 5-hour plan window as the last response reported it, for the line under the prompt */
87let fiveHour: { percentUsed: number; resetsAt?: string } | undefined
88let ttlSource = 'default'
89let envSource = 'default'
90let env: CacheEnv = {}
91let timer: { cancel: () => void } | undefined
92let lastKey = ''
93let toastedFor = 0
94let toastLevel = Infinity
95let isPaneOpen = false
96/** when the session began (its first launch if resumed, /clear restarts it); 0 until known */
97let sessionStartedAt = 0
98
99type Policy = { warnMs: number; compactAtTokens: number }
100
101function current(policy: Policy, now: number) {
102 const last = samples[samples.length - 1]
103 const prev = samples[samples.length - 2]
104 const disabled = last ? isCachingDisabled(last.model, env) : isCachingDisabled('', env)
105 const advice: Advice = advise(last, prev, { ttl, ...policy }, now, disabled)
106 const left = last ? remainingMs(last, ttl, now) : 0
107 return { last, advice, left }
108}
109
110const COLOR: Record<Advice['kind'], string | undefined> = {
111 warm: 'green',
112 soon: 'yellow',
113 expired: 'red',
114 miss: 'red',
115 off: undefined,
116 cold: undefined,
117 uncached: undefined,
118}
119
120/** a hit rate with one decimal, e.g. 99.5% */
121const pct1 = (ratio: number) => `${(ratio * 100).toFixed(1)}%`
122
123async function openPane($: EngineInterface) {
124 isPaneOpen = true
125 await $.ui.open({ id: PANE, title: 'cache', focus: true })
126 $.ui.invalidate('ui.render')
127}
128
129function shortLine(policy: Policy, now: number): string {
130 const { last, advice, left } = current(policy, now)
131 if (!last || advice.kind === 'off') return `cache: ${advice.text}`
132 const clock = left > 0 ? ` · ${fmtCountdown(left)}` : ''
133 return `cache ${pct1(hitRatio(last))}${clock}`
134}
135
136// the promptCacheTtl setting, from the settings files that can carry it (local over project over user)
137async function readSetting($: EngineInterface): Promise<unknown> {
138 const home = await $.env.get('HOME').catch(() => undefined)
139 const cwd = await $.session.cwd().catch(() => undefined)
140 const files = [cwd && `${cwd}/.claude/settings.local.json`, cwd && `${cwd}/.claude/settings.json`, home && `${home}/.claude/settings.json`]
141 for (const file of files) {
142 if (!file) continue
143 try {
144 const value = JSON.parse(await $.fs.read(file)).promptCacheTtl
145 if (value === '5m' || value === '1h') return value
146 } catch {
147 // missing or unreadable: the next file
148 }
149 }
150 return undefined
151}
152
153let idle: ReturnType<typeof idleCompactState> | undefined
154/** Claude Code's idle compaction, from its cached remote flag and the settings that turn it off */
155async function readIdleCompact($: EngineInterface) {
156 const none = () => undefined
157 const home = (await $.env.get('HOME').catch(none)) ?? (await $.env.get('USERPROFILE').catch(none))
158 const json = async (file: string) => JSON.parse(await $.fs.read(file).catch(() => '{}'))
159 const cfg = home ? await json(`${home}/.claude.json`).catch(() => ({})) : {}
160 const cwd = await $.session.cwd().catch(none)
161 let idleSetting: unknown
162 for (const file of [cwd && `${cwd}/.claude/settings.local.json`, cwd && `${cwd}/.claude/settings.json`, home && `${home}/.claude/settings.json`]) {
163 if (!file) continue
164 const v = (await json(file).catch(() => ({}))).idleCompaction
165 if (typeof v === 'boolean') { idleSetting = v; break }
166 }
167 return idleCompactState({
168 flagMode: cfg.cachedGrowthBookFeatures?.tengu_sunny_locket?.mode,
169 idleSetting,
170 autoCompact: cfg.autoCompactEnabled,
171 disableEnv: await $.env.get('DISABLE_AUTO_COMPACT').catch(none),
172 minEnv: await $.env.get('CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS').catch(none),
173 })
174}
175
176
177// ---- /keepwarm, ported from cache-tax 2.2.1 (MIT): a tool-less $.model.fork after each idle stretch re-reads
178// the cached prefix; each ping is recorded as a Sample, so the meter counts it
179const DEFAULT_WINDOW_MS = 6 * 60 * 60 * 1000
180const MIN_PING_MS = 60 * 1000
181const PING_PROMPT = 'Reply with the single word: warm'
182const KEY_DEADLINE = 'keepwarm.deadline'
183const KEY_EVERY = 'keepwarm.every'
184const KEY_ALWAYS = 'keepwarm.always'
185
186// $ per million tokens, [cache read, 1h cache write, output], list prices September 2026 (from cache-tax).
187const PRICES: Array<[string, number, number, number]> = [
188 ['fable-5-1', 0.25, 20, 50],
189 ['fable-5', 1, 20, 50],
190 ['opus-5', 0.5, 10, 25],
191 ['opus-4', 0.5, 10, 25],
192 ['sonnet-5', 0.2, 4, 10],
193 ['sonnet', 0.3, 6, 15],
194 ['haiku', 0.1, 2, 5],
195]
196
197type Ping = { read: number; usd: number | null }
198
199function parseDuration(text: string): number | null {
200 const m = /^(?:(\d+)h)?(?:(\d+)m)?$/.exec(text.trim())
201 if (!m || (m[1] === undefined && m[2] === undefined)) return null
202 return (Number(m[1] ?? 0) * 60 + Number(m[2] ?? 0)) * 60 * 1000
203}
204
205function fmtDuration(ms: number): string {
206 const total = Math.max(0, Math.round(ms / 60000))
207 const h = Math.floor(total / 60)
208 const m = total % 60
209 return h > 0 ? `${h}h${String(m).padStart(2, '0')}m` : `${m}m`
210}
211
212function priceOf(model: string): [number, number, number] | null {
213 const m = model.toLowerCase().replace(/[\s.]+/g, '-')
214 for (const [family, read, write, output] of PRICES) if (m.includes(family)) return [read, write, output]
215 return null
216}
217
218function fmtUsd(usd: number | null): string {
219 return usd == null ? 'n/a' : '$' + usd.toFixed(2)
220}
221
222/** 50m on a 1h cache, about 4m on a 5m one */
223const defaultEvery = (ttlMs: number) => Math.max(MIN_PING_MS, Math.round((ttlMs * 5) / 6))
224
225let sid = ''
226let deadline = 0
227let windowStart = 0 // when the current window was armed, for the pane's bar
228let every = 0 // 0: the default for the TTL in force
229let always = false
230// ponytail: in memory, a plugin reload or a restarted process lets autoKeepwarm start it again
231let userOff = false // /keepwarm off or the pane's stop: autoKeepwarm leaves it off until it is started by hand
232let compacted = false
233let stopped: string | null = null
234let lastPing: Ping | null = null
235/** keepwarm pings in the current window, counted from the samples (they survive a restart with them) */
236// ponytail: a restart keeps the last SAVED samples, so a longer run of pings than that counts short
237const pingsInWindow = () => samples.filter(x => x.turnId.startsWith('keepwarm-') && x.startedAt >= windowStart).length
238let pending: { cancel: () => void } | null = null
239
240const period = () => every || defaultEvery(ttlMs(ttl))
241const lastAt = () => samples[samples.length - 1]?.startedAt ?? 0
242const isCold = (now: number) => lastAt() > 0 && now - lastAt() >= ttlMs(ttl)
243
244/** the band's segment, undefined when keepwarm is off */
245function keepwarmStatus(now: number): { text: string; stopped: boolean } | undefined {
246 if (stopped) return { text: `keepwarm stopped: ${stopped}`, stopped: true }
247 if (!deadline || now >= deadline) return undefined
248 const next = !lastAt() || compacted ? 'waiting for a turn'
249 : isCold(now) ? 'cold'
250 : `ping ${fmtDuration(lastAt() + period() - now)}`
251 const pings = pingsInWindow()
252 const last = pings ? ` · ${pings} ping${pings === 1 ? '' : 's'}` : ''
253 return { text: `♨ keepwarm ${fmtDuration(deadline - now)} · ${next}${last}`, stopped: false }
254}
255
256/** keepwarm for the pane, as values rather than one line */
257function keepwarmInfo(now: number) {
258 const on = !!deadline && now < deadline
259 const next = !on ? undefined
260 : !lastAt() || compacted ? 'after the next turn'
261 : isCold(now) ? 'cold, after the next turn'
262 : `in ${fmtDuration(lastAt() + period() - now)}`
263 return {
264 on,
265 stopped,
266 always,
267 left: on ? deadline - now : 0,
268 window: on ? Math.max(1, deadline - windowStart) : 1,
269 next,
270 every: period(),
271 lastPing,
272 }
273}
274
275/** from the module's session.start (one hook per event per module) */
276async function keepwarmStart($: EngineInterface) {
277 disarm()
278 sid = await $.session.id()
279 const now = Date.now()
280 const saved = await $.store.get(keyOf(KEY_DEADLINE))
281 const savedEvery = await $.store.get(keyOf(KEY_EVERY))
282 deadline = typeof saved === 'number' && saved > now ? saved : 0
283 // a restored window's start is not stored: assume the default length
284 windowStart = deadline ? Math.min(now, deadline - DEFAULT_WINDOW_MS) : 0
285 if (!deadline) {
286 await $.store.delete(keyOf(KEY_DEADLINE))
287 await $.store.delete(keyOf(KEY_EVERY))
288 }
289 every = typeof savedEvery === 'number' && savedEvery >= MIN_PING_MS ? savedEvery : 0
290 always = (await $.store.get(KEY_ALWAYS)) === true
291 if (always) await startWindow($, DEFAULT_WINDOW_MS, 0)
292 await $.command.register({
293 name: 'keepwarm',
294 description: 'Keep the prompt cache warm: bare for 6h, a window such as 90m, always, off, or status',
295 argumentHint: '[6h | always | off | status]',
296 immediate: true,
297 })
298 await arm($)
299}
300
301/** from the module's session.end */
302async function keepwarmEnd($: EngineInterface, reason: string) {
303 // /clear starts a new conversation: nothing to keep warm until it has a turn
304 if (reason === 'clear') {
305 await stop($, null)
306 lastPing = null
307 userOff = false
308 misses = []
309 ackedAt = 0
310 coldWritePending = false
311 } else disarm()
312}
313
314const keyOf = (k: string) => `${k}:${sid}`
315
316const disarm = () => {
317 pending?.cancel()
318 pending = null
319}
320
321async function stop($: EngineInterface, why: string | null, forgetAlways = false) {
322 if (forgetAlways) userOff = true
323 deadline = 0
324 every = 0
325 stopped = why
326 disarm()
327 await $.store.delete(keyOf(KEY_DEADLINE))
328 await $.store.delete(keyOf(KEY_EVERY))
329 if (forgetAlways) {
330 always = false
331 await $.store.delete(KEY_ALWAYS)
332 }
333 $.ui.invalidate('ui.render')
334}
335
336async function arm($: EngineInterface) {
337 disarm()
338 if (!deadline) return
339 const now = Date.now()
340 if (now >= deadline) return stop($, null)
341 // a cold or compacted cache is not pinged: the next turn writes it anew, then pinging resumes
342 if (lastAt() && !compacted && !isCold(now)) {
343 const delay = Math.min(deadline - now, lastAt() + ttlMs(ttl) - now, Math.max(1000, lastAt() + period() - now))
344 pending = $.clock.after(delay, () => void ping($))
345 } else {
346 pending = $.clock.after(deadline - now, () => void arm($))
347 }
348 $.ui.invalidate('ui.render')
349}
350
351async function ping($: EngineInterface) {
352 pending = null
353 if (!deadline) return
354 const now = Date.now()
355 if (now >= deadline || isCold(now)) return arm($)
356 // a turn in the meantime re-armed the timer; this callback is stale
357 if (now - lastAt() < period() - 1000) return
358 const model = samples[samples.length - 1]?.model ?? ''
359 let reply
360 try {
361 reply = await $.model.fork({ prompt: PING_PROMPT })
362 } catch (err) {
363 return stop($, `the ping failed, ${err instanceof Error ? err.message : String(err)}`)
364 }
365 if (reply.isAnswered === false) {
366 const reason = reply.reason === 'nothing-to-fork' ? 'no conversation to warm yet'
367 : reply.reason === 'api-error' ? `the API call failed${reply.status === null ? '' : ` (${reply.status})`}`
368 : reply.reason === 'aborted' ? 'the ping was interrupted'
369 : 'the ping returned no text'
370 return stop($, reason)
371 }
372 const u = reply.usage
373 const price = priceOf(model)
374 const usd = price
375 ? (u.cache_read_input_tokens * price[0] + u.cache_creation_input_tokens * price[1] + (u.input_tokens * price[1]) / 2 + u.output_tokens * price[2]) / 1e6
376 : null
377 lastPing = { read: u.cache_read_input_tokens, usd }
378 if (usd != null) spentUsd += usd
379 await pushSample($, {
380 turnId: `keepwarm-${now}`,
381 index: 0,
382 model,
383 startedAt: now,
384 read: u.cache_read_input_tokens,
385 write: u.cache_creation_input_tokens,
386 fresh: u.input_tokens,
387 output: u.output_tokens,
388 })
389 $.ui.invalidate('ui.render')
390 // a warm ping reads the prefix and writes only its own message; a write of a tenth of the read or more means the prefix broke
391 const warm = u.cache_read_input_tokens > 0 && u.cache_creation_input_tokens < 0.1 * u.cache_read_input_tokens
392 if (!warm) return stop($, `the ping wrote ${fmtTokens(u.cache_creation_input_tokens)} tokens (${fmtUsd(usd)}), the cache was already gone`)
393 await arm($)
394}
395
396async function startWindow($: EngineInterface, windowMs: number, everyMs: number) {
397 every = everyMs
398 if (every) await $.store.set(keyOf(KEY_EVERY), every)
399 else await $.store.delete(keyOf(KEY_EVERY))
400 windowStart = Date.now()
401 deadline = windowStart + windowMs
402 userOff = false
403 stopped = null
404 await $.store.set(keyOf(KEY_DEADLINE), deadline)
405 await arm($)
406}
407
408function statusLine(now: number): string | undefined {
409 if (stopped) return `keepwarm stopped: ${stopped}`
410 if (!deadline || now >= deadline) return undefined
411 const next = !lastAt() ? ' · waiting for the first turn'
412 : compacted ? ' · waiting for the first turn after compaction'
413 : isCold(now) ? ` · cold now, first ping ${fmtDuration(period())} after the next turn`
414 : ` · ping in ${fmtDuration(lastAt() + period() - now)}`
415 const last = lastPing ? ` · last ping read ${fmtTokens(lastPing.read)} ${fmtUsd(lastPing.usd)}` : ''
416 return `keepwarm ${fmtDuration(deadline - now)} left${next}${last}`
417}
418
419function armedText(windowMs: number): string {
420 if (isCold(Date.now())) return `keepwarm on for ${fmtDuration(windowMs)}. The cache is cold now, so the first ping comes ${fmtDuration(period())} after the next turn`
421 return `keepwarm on for ${fmtDuration(windowMs)}, a ping ${fmtDuration(period())} after each idle stretch keeps the cache read, not re-written`
422}
423
424// ---- cold-cache price and guard, ported from cache-tax 2.2.1 (MIT)
425/** the last request's cache has lapsed: the next message writes the whole prefix again */
426function coldSince(now: number): number | undefined {
427 const last = samples[samples.length - 1]
428 if (!last || compacted || last.read + last.write === 0) return undefined
429 const at = last.startedAt + ttlMs(ttl)
430 return now >= at ? at : undefined
431}
432
433/** $ per million tokens written to the cache for `model` at the TTL in force: the 1h rate is 2x base, the 5m one 1.25x */
434function writeRate(model: string): number | null {
435 const price = priceOf(model)
436 return price ? (ttl === '1h' ? price[1] : price[1] * 0.625) : null
437}
438
439const AUTO_WARM_MS = 3 * 60 * 60 * 1000
440type Miss = { at: number; turnId: string; tokens: number; usd: number | null }
441/** this session's cold writes */
442let misses: Miss[] = []
443/** the guard let a message to a cold cache through: its turn pays a cold write */
444let coldWritePending = false
445
446/** the request of `turnId` that re-wrote the prefix: after the guard let it through, or one that wrote half the previous prompt or more */
447function coldWriteOf(turnId: string): Sample | undefined {
448 const i = samples.findIndex(x => x.turnId === turnId)
449 if (i < 0) return undefined
450 const prevTokens = i > 0 ? promptTokens(samples[i - 1]) : 0
451 const first = samples[i]
452 return isColdWrite(prevTokens, first.write, coldWritePending) ? first : undefined
453}
454
455
456/** what re-writing the last prompt costs, and what a warm turn would have read it for */
457function coldPrice(): { tokens: number; cold: number | null; warm: number | null } {
458 const last = samples[samples.length - 1]
459 const tokens = last ? promptTokens(last) : 0
460 const price = priceOf(last?.model ?? '')
461 const write = writeRate(last?.model ?? '')
462 return { tokens, cold: write == null ? null : (tokens * write) / 1e6, warm: price ? (tokens * price[0]) / 1e6 : null }
463}
464
465/** the band's and pane's segment while the cache is cold */
466function coldStatus(now: number): string | undefined {
467 if (coldSince(now) === undefined) return undefined
468 const { tokens, cold } = coldPrice()
469 return `❄ re-warm ${fmtTokens(tokens)} ≈ ${fmtUsd(cold)}`
470}
471
472function guardText(now: number): string {
473 const since = coldSince(now) ?? now
474 const { tokens, cold, warm } = coldPrice()
475 return `the prompt cache went cold ${fmtDuration(now - since)} ago. Sending this re-writes about ${fmtTokens(tokens)} tokens ≈ ${fmtUsd(cold)}` +
476 (warm == null ? '' : ` (a warm turn would have cost ${fmtUsd(warm)})`) + '.'
477}
478
479let ackedAt = 0
480
481// ---- experimental: list price as a share of the 5-hour plan window. The engine
482// reports the window's percentUsed but not its size, so this session's spend at
483// list price is set against how far the window moved. Each session writes its
484// spend in the window under `spend:<sid>` in the shared store and the estimate
485// sums them all; sessions without this mod (claude.ai, other machines) still
486// make it read high.
487const KEY_CALIB = 'calib.pctPerUsd'
488const KEY_SPEND = 'spend'
489/** this session's spend at list price, requests and keepwarm pings */
490let spentUsd = 0
491/** the window this session last wrote its spend for, and spentUsd when that window began for it */
492let winResetsAt: string | undefined
493let winBase = 0
494/** where the window and every session's spend stood when this window was first seen */
495let anchor: { resetsAt: string; pct: number; usd: number } | undefined
496/** the last estimate: percent of the 5-hour window per list-price dollar */
497let pctPerUsd: number | undefined
498/** sessions that wrote their spend in the last 10 minutes, this one included */
499let activeSessions = 0
500
501/** a call's list price: cache read, cache write at the TTL in force, uncached input at base (half the 1h write rate), output */
502function usdOf(u: { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }, model: string): number | null {
503 const price = priceOf(model)
504 const rate = writeRate(model)
505 if (!price || rate == null) return null
506 return (u.cache_read_input_tokens * price[0] + u.cache_creation_input_tokens * rate + (u.input_tokens * price[1]) / 2 + u.output_tokens * price[2]) / 1e6
507}
508
509/** a turn's requests at list price, each at its own model's rates; null when a model's price is unknown */
510function turnUsd(turnId: string): number | null {
511 let sum = 0
512 for (const x of samples) {
513 if (x.turnId !== turnId) continue
514 const usd = usdOf({ input_tokens: x.fresh, output_tokens: x.output, cache_read_input_tokens: x.read, cache_creation_input_tokens: x.write }, x.model)
515 if (usd == null) return null
516 sum += usd
517 }
518 return sum
519}
520
521/** after a turn: move the anchor on a new window, otherwise update the estimate */
522async function calibrate($: EngineInterface) {
523 const w = (await $.session.usage().catch(() => undefined))?.rateLimits?.find(x => x.kind === 'five_hour')
524 if (!w || !w.resetsAt) return
525 const mine = keyOf(KEY_SPEND)
526 if (winResetsAt !== w.resetsAt) {
527 // a reload zeroes spentUsd: carry on from what this session wrote for the same window
528 const saved = winResetsAt === undefined ? ((await $.store.get(mine)) as Partial<Spend> | undefined) : undefined
529 winBase = saved?.resetsAt === w.resetsAt && typeof saved.usd === 'number' ? spentUsd - saved.usd : spentUsd
530 winResetsAt = w.resetsAt
531 }
532 const now = Date.now()
533 await $.store.set(mine, { resetsAt: w.resetsAt, usd: spentUsd - winBase, at: now } satisfies Spend)
534 // ponytail: one JSON file for every session, two writing at once can drop one write; the next turn rewrites it
535 const keys = (await $.store.keys()).filter(k => k.startsWith(`${KEY_SPEND}:`))
536 const all = await Promise.all(keys.map(async k => [k, await $.store.get(k)] as [string, unknown]))
537 const { usd, active, stale } = windowSpend(all, w.resetsAt, now)
538 activeSessions = active
539 for (const k of stale) await $.store.delete(k)
540 if (!anchor || anchor.resetsAt !== w.resetsAt || w.percentUsed < anchor.pct) {
541 anchor = { resetsAt: w.resetsAt, pct: w.percentUsed, usd }
542 return
543 }
544 const r = calibRate(anchor.pct, anchor.usd, w.percentUsed, usd)
545 if (r !== undefined) {
546 pctPerUsd = r
547 await $.store.set(KEY_CALIB, r)
548 }
549}
550
551/** recount the active sessions from the store, for /cache between turns */
552async function refreshActive($: EngineInterface) {
553 if (!winResetsAt) return
554 const keys = (await $.store.keys()).filter(k => k.startsWith(`${KEY_SPEND}:`))
555 const all = await Promise.all(keys.map(async k => [k, await $.store.get(k)] as [string, unknown]))
556 activeSessions = windowSpend(all, winResetsAt, Date.now()).active
557}
558
559const sessionsText = () => `${activeSessions} active session${activeSessions === 1 ? '' : 's'}`
560
561// the engine's process can stop under an idle session and start again on resume, which runs session.start
562// with the module's variables zeroed: keep the latest requests in the store, under `samples:<sid>`
563const KEY_SAMPLES = 'samples'
564const SAVED = 30
565const SAVED_FOR_MS = 7 * 24 * 60 * 60 * 1000
566
567async function pushSample($: EngineInterface, sample: Sample) {
568 samples.push(sample)
569 if (samples.length > KEEP) samples = samples.slice(-KEEP)
570 lastKey = ''
571 await $.store.set(keyOf(KEY_SAMPLES), { at: Date.now(), samples: samples.slice(-SAVED) }).catch(() => undefined)
572}
573
574/** this session's saved requests; drops other sessions' older than a week */
575async function restoreSamples($: EngineInterface): Promise<Sample[]> {
576 const now = Date.now()
577 let mine: Sample[] = []
578 for (const k of (await $.store.keys()).filter(k => k.startsWith(`${KEY_SAMPLES}:`))) {
579 const v = (await $.store.get(k)) as { at?: number; samples?: Sample[] } | undefined
580 if (k === keyOf(KEY_SAMPLES)) mine = Array.isArray(v?.samples) ? v.samples : []
581 else if (!v || typeof v.at !== 'number' || now - v.at > SAVED_FOR_MS) await $.store.delete(k)
582 }
583 return mine
584}
585
586export const register: Register = (on, options) => {
587 const policy: Policy = {
588 warnMs: positive(options.warnSeconds, 60) * 1000,
589 compactAtTokens: positive(options.compactAtTokens, 100_000),
590 }
591 const showBand = options.band !== false
592 const showBreakdown = options.breakdown !== false
593 const showStatus = options.status === true
594 const showLimit = options.limit !== false
595 const autoWarm = options.autoKeepwarm === true
596 /** the entry under the prompt: the cache's short line and/or the 5-hour window */
597 const statusText = (now: number) =>
598 [showStatus ? shortLine(policy, now) : undefined, showLimit ? fmtLimit(fiveHour, now) : undefined].filter(Boolean).join(' · ') || undefined
599 const wantToast = options.toast !== false
600 const guard: GuardMode = options.guard === 'warn' || options.guard === 'off' ? options.guard : 'refuse'
601
602 on('session.start', async ($, e, next) => {
603 const r = await next(e)
604 samples = []
605 lastKey = ''
606 toastedFor = 0
607 const none = () => undefined
608 env = {
609 enable1h: await $.env.get('ENABLE_PROMPT_CACHING_1H').catch(none),
610 force5m: await $.env.get('FORCE_PROMPT_CACHING_5M').catch(none),
611 ttlVar: await $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL').catch(none),
612 disableAll: await $.env.get('DISABLE_PROMPT_CACHING').catch(none),
613 disableHaiku: await $.env.get('DISABLE_PROMPT_CACHING_HAIKU').catch(none),
614 disableSonnet: await $.env.get('DISABLE_PROMPT_CACHING_SONNET').catch(none),
615 disableOpus: await $.env.get('DISABLE_PROMPT_CACHING_OPUS').catch(none),
616 }
617 pinned = options.ttl === '5m' || options.ttl === '1h'
618 observed = undefined
619 setting = await readSetting($)
620 idle = await readIdleCompact($).catch(() => undefined)
621 if (idle?.on) $.ui.log(`prompt-cache-control: Claude Code's idle compaction is ${idle.text}: it compacts ~54m into an idle stretch whatever keepwarm does, so keepwarm's 50m ping on such a conversation is wasted. "idleCompaction": false in settings.json turns it off.`)
622 const usage = await $.session.usage().catch(() => undefined)
623 sessionStartedAt = usage?.startedAt ?? 0
624 const limits = usage?.rateLimits ?? []
625 account = accountOf(limits)
626 fiveHour = limits.find(x => x.kind === 'five_hour')
627 const choice = decideTtl(options.ttl, env, setting, account)
628 baseTtl = choice.ttl
629 ttl = baseTtl
630 envSource = choice.source
631 ttlSource = envSource
632
633 await $.command
634 .register({
635 name: COMMAND,
636 description: 'Prompt-cache usage per turn and the time left before it lapses (stop closes)',
637 argumentHint: '[stop]',
638 immediate: true,
639 })
640 .catch(err => $.ui.log(`prompt-cache-control: /${COMMAND} not registered: ${err}`))
641 $.ui.log(`prompt-cache-control loaded: ${ttl} cache (${ttlSource}), /${COMMAND} opens the table`, { to: 'debug' })
642
643 // the cache's part waits for the first request; this also clears what a previous load left
644 $.ui.status(showLimit ? fmtLimit(fiveHour, Date.now()) : undefined)
645 spentUsd = 0
646 winResetsAt = undefined
647 winBase = 0
648 activeSessions = 0
649 anchor = undefined
650 const savedRate = await $.store.get(KEY_CALIB).catch(() => undefined)
651 pctPerUsd = typeof savedRate === 'number' && savedRate > 0 ? savedRate : undefined
652 // a resumed session, or a restarted process under it, goes on from its saved requests
653 sid = await $.session.id().catch(() => '')
654 samples = sid ? await restoreSamples($).catch(() => []) : []
655 // keepwarm failing to start must not take the meter down with it
656 try {
657 await keepwarmStart($)
658 } catch (err) {
659 $.ui.log(`prompt-cache-control: /keepwarm not started: ${err}`, { to: 'debug' })
660 }
661 timer?.cancel()
662 timer = $.clock.every(1000, () => {
663 const now = Date.now()
664 const { last, advice, left } = current(policy, now)
665 // the band counts in minutes from 10 minutes up; the open pane counts seconds, so it redraws each one
666 const key = `${advice.kind}|${advice.text}|${left > 0 ? (isPaneOpen ? fmtClock(left) : fmtCountdown(left)) : ''}|${keepwarmStatus(now)?.text ?? ''}|${coldStatus(now) ?? ''}|${showLimit ? fmtLimit(fiveHour, now) ?? '' : ''}|${isPaneOpen && sessionStartedAt ? fmtClock(now - sessionStartedAt) : ''}`
667 if (key !== lastKey) {
668 lastKey = key
669 if (showStatus || showLimit) $.ui.status(statusText(now))
670 $.ui.invalidate('ui.render')
671 }
672 if (wantToast && last && left > 0 && promptTokens(last) >= TOAST_MIN_TOKENS) {
673 if (toastedFor !== last.startedAt) {
674 toastedFor = last.startedAt
675 toastLevel = Infinity
676 }
677 // the first toast comes at warnSeconds, then 10, 3, 2 and 1 seconds; a late tick skips to the newest one
678 const secs = Math.ceil(left / 1000)
679 const mark = nextToastMark(secs, policy.warnMs / 1000, toastLevel)
680 if (mark !== undefined) {
681 toastLevel = mark
682 const tail = secs <= COUNTDOWN_MARKS[0] ? 'send a message now' : `send a message to keep ${fmtTokens(promptTokens(last))} tokens warm`
683 $.ui.toast(`cache expires in ${secs >= 60 ? fmtClock(left) : `${secs}s`}: ${tail}`)
684 }
685 }
686 })
687 return r
688 })
689
690 on('session.end', async ($, e, next) => {
691 await keepwarmEnd($, e.reason)
692 // /clear starts a new conversation in the same process: its cache is a new one
693 if (e.reason === 'clear') {
694 samples = []
695 lastKey = ''
696 toastedFor = 0
697 observed = undefined
698 ttl = baseTtl
699 ttlSource = envSource
700 $.ui.invalidate('ui.render')
701 return next(e)
702 }
703 timer?.cancel()
704 timer = undefined
705 return next(e)
706 })
707
708 // the plan windows moved: the 5-hour one goes under the prompt
709 on('session.measure', async ($, e, next) => {
710 const w = e.rateLimits.find(x => x.kind === 'five_hour')
711 if (w) fiveHour = w
712 if (showLimit) $.ui.status(statusText(Date.now()))
713 return next(e)
714 })
715
716 // each main-loop request: what the cache did with it
717 on('turn.step', async function* ($, e, next) {
718 if (e.agentId) return yield* next(e)
719 const startedAt = Date.now()
720 const r = yield* next(e)
721 if (r.usage) {
722 await pushSample($, {
723 turnId: e.turnId,
724 index: e.index,
725 model: r.usage.model || e.model,
726 startedAt,
727 read: r.usage.cache_read_input_tokens,
728 write: r.usage.cache_creation_input_tokens,
729 fresh: r.usage.input_tokens,
730 output: r.usage.output_tokens,
731 })
732 // autoKeepwarm: a message opens a window when none is running, unless the person turned it off
733 if (autoWarm && !userOff && !(deadline > Date.now())) {
734 await startWindow($, DEFAULT_WINDOW_MS, every).catch(err => $.ui.log(`prompt-cache-control: autoKeepwarm not started: ${err}`, { to: 'debug' }))
735 }
736 if (!pinned) {
737 // the account can change under a session: a subscription running out of plan usage moves to usage credits
738 account = accountOf((await $.session.usage().catch(() => undefined))?.rateLimits ?? [])
739 const choice = decideTtl(options.ttl, env, setting, account)
740 baseTtl = choice.ttl
741 envSource = choice.source
742 if (observed === undefined) {
743 ttl = baseTtl
744 ttlSource = envSource
745 }
746 const seen = observeTtl(samples[samples.length - 2], samples[samples.length - 1], observed)
747 if (seen !== observed) {
748 observed = seen
749 ttl = seen ?? baseTtl
750 ttlSource = `observed from request timing; ${envSource} said ${baseTtl}`
751 $.ui.log(`prompt-cache-control: cache lifetime is ${ttl} (${ttlSource})`, { to: 'debug' })
752 }
753 }
754 lastKey = ''
755 if (showStatus || showLimit) $.ui.status(statusText(Date.now()))
756 $.ui.invalidate('ui.render')
757 }
758 return r
759 })
760
761 /** the pane as plain lines, for where nothing draws it (Remote Control) */
762 function textSummary(now: number): string {
763 const { last, advice, left } = current(policy, now)
764 const kwi = keepwarmInfo(now)
765 const { cold, warm } = coldPrice()
766 const isColdNow = coldSince(now) !== undefined
767 const price = priceOf(last?.model ?? '')
768 const rate = writeRate(last?.model ?? '')
769 const breakEven = price && rate ? Math.floor(rate / price[0]) : undefined
770 const paid = misses.reduce((a, m) => a + (m.usd ?? 0), 0)
771 const counting = !!last && advice.kind !== 'uncached' && advice.kind !== 'off'
772 const row = (label: string, value: string) => `${label.padEnd(LABEL_W)}${value}`
773 // the engine prefixes the plugin's name to the first line
774 const lines = [advice.text]
775 if (sessionStartedAt) lines.push(row('session', fmtClock(now - sessionStartedAt)))
776 if (counting) lines.push(row('expires in', left > 0 ? fmtClock(left) : '0:00'))
777 if (last) {
778 lines.push(row('last request', `${pct1(hitRatio(last))} hit`))
779 }
780 lines.push(row('keepwarm', kwi.stopped ? `stopped: ${kwi.stopped}`
781 : kwi.on ? `${fmtDuration(kwi.left)} left · next ping ${kwi.next ?? ''} · every ${fmtDuration(kwi.every)}`
782 : kwi.always ? 'off until next session (always)' : 'off (/keepwarm arms 6h)'))
783 if (kwi.lastPing) lines.push(row('last ping', `${fmtTokens(kwi.lastPing.read)} read · ${fmtUsd(kwi.lastPing.usd)}`))
784 if (breakEven !== undefined) lines.push(row('break-even', `${breakEven} pings = one cold write, ~${fmtDuration(breakEven * kwi.every)} idle`))
785 if (last && cold != null) {
786 lines.push(row('cold write', `${fmtUsd(cold)}${isColdNow ? ' · cold now: the next message pays it' : ''}` +
787 (warm != null ? ` (warm turn ${fmtUsd(warm)})` : '')))
788 }
789 if (idle) lines.push(row('idle compact', idle.text))
790 lines.push(row('guard', guard === 'refuse' ? 'refuse once' : guard === 'warn' ? 'warn only' : 'off'))
791 if (pctPerUsd !== undefined && cold != null && warm != null) {
792 lines.push(row('5h window', `≈ ${(cold * pctPerUsd).toFixed(1)}% cold · ${(warm * pctPerUsd).toFixed(1)}% warm (experimental, ${sessionsText()})`))
793 }
794 lines.push(row('this session', `${misses.length} cold write${misses.length === 1 ? '' : 's'} · ${fmtUsd(paid)}`))
795 return lines.join('\n')
796 }
797
798 on('command.run', { command: COMMAND }, async ($, e) => {
799 const arg = e.args.trim().toLowerCase()
800 if (arg === 'stop') {
801 await $.ui.close({ id: PANE }).catch(() => undefined)
802 isPaneOpen = false
803 $.ui.invalidate('ui.render')
804 return { text: 'cache table closed' }
805 }
806 // nothing draws the pane under Remote Control: answer in text
807 await refreshActive($).catch(() => undefined)
808 const surfaces = await $.session.surfaces().catch(() => [])
809 if (arg === 'text' || surfaces.length === 0) return { text: textSummary(Date.now()) }
810 await openPane($)
811 const { advice } = current(policy, Date.now())
812 return { text: `${ttl} cache (${ttlSource}) · ${advice.text} · /${COMMAND} stop closes` }
813 })
814
815 on('ui.close', async ($, e, next) => {
816 if (e.id !== PANE) return next(e)
817 isPaneOpen = false
818 // the band hides while the pane is open: draw it again now, not at the next countdown tick
819 $.ui.invalidate('ui.render')
820 return next(e)
821 })
822
823 on('ui.press', async ($, e, next) => {
824 if (e.plugin !== $.plugin.name || e.requestId !== PANE) return next(e)
825 if (e.element === 'close') await $.ui.close({ id: PANE }).catch(() => undefined)
826 if (e.element === 'kw-start') await startWindow($, DEFAULT_WINDOW_MS, 0)
827 if (e.element === 'kw-stop') await stop($, null, true)
828 return next(e)
829 })
830
831 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
832 if (!showBand || e.props.hasSurvey || isPaneOpen) return next(e)
833 const { last, advice, left } = current(policy, Date.now())
834 const { Box, Text, Button } = $.ui.resolve(e)
835 const columns = e.viewport?.columns ?? 100
836 const color = COLOR[advice.kind]
837 // other mods' rows above the prompt come back from next(e). Ours goes on top, with a gap before theirs,
838 // so the order does not hang on which mod the engine loaded first (it differs by install source)
839 const rest = await next(e)
840 const band = (row: RenderChildren) => (
841 <Box flexDirection="column">
842 {row}
843 {rest ? <Box key="rest" flexDirection="column" marginTop={1}>{rest}</Box> : null}
844 </Box>
845 )
846
847 // no request yet (new session, /clear, a plugin reload): a placeholder row, so the band does not vanish
848 if (!last) {
849 return band(
850 <Box key="cache" flexDirection="row" columnGap={1}>
851 <Text dimColor wrap="truncate-end">{advice.kind === 'off' ? `cache: ${advice.text}` : '○ cache · waiting for the first request'}</Text>
852 <Button key="open" label="details" onPress={() => openPane($)} />
853 </Box>,
854 )
855 }
856
857 const ratio = hitRatio(last)
858 const wide = columns >= 90
859 const kw = keepwarmStatus(Date.now())
860 const cold = coldStatus(Date.now())
861 return band(
862 <Box key="cache" flexDirection="row" columnGap={1}>
863 <Text bold color={color}>{advice.kind === 'warm' ? '●' : advice.kind === 'soon' ? '▲' : advice.kind === 'off' || advice.kind === 'cold' || advice.kind === 'uncached' ? '○' : '✖'}</Text>
864 <Text bold color="cyan">cache</Text>
865 <Text color={color}>{bar(ratio, wide ? 10 : 6)}</Text>
866 <Text bold>{pct1(ratio)}</Text>
867 {!showBreakdown ? null : wide ? (
868 <>
869 <Text color="green">{`read ${fmtTokens(last.read)}`}</Text>
870 <Text color="yellow">{`wrote ${fmtTokens(last.write)}`}</Text>
871 <Text color="cyan">{`new ${fmtTokens(last.fresh)}`}</Text>
872 </>
873 ) : (
874 <Text dimColor>{`${fmtTokens(promptTokens(last))} tok`}</Text>
875 )}
876 {advice.kind !== 'uncached' && advice.kind !== 'off' && (
877 <Text bold color={left > 0 ? lifeColor(left, ttl, policy.warnMs) : 'red'}>{left > 0 ? `⏱ ${fmtCountdown(left)}` : '⏱ 0:00'}</Text>
878 )}
879 {kw && <Text color={kw.stopped ? 'red' : 'magenta'}>{kw.text}</Text>}
880 {cold && <Text color="cyan">{cold}</Text>}
881 <Button key="open" label="details" onPress={() => openPane($)} />
882 <Text dimColor wrap="truncate-end">{`${ttl} · ${advice.text}`}</Text>
883 </Box>,
884 )
885 })
886
887 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
888 if (e.requestId !== PANE) return next(e)
889 const { Box, Text, Button } = $.ui.resolve(e)
890 const width = Math.max(30, e.props.bodyColumns - 1)
891 // HTML collapses runs of spaces and trims a text's ends; a no-break space keeps them
892 const sp = (t: string) => (e.surface === 'terminal' ? t : t.replace(/ /g, ' '))
893 const now = Date.now()
894 const { last, advice, left } = current(policy, now)
895 const kw = keepwarmStatus(now)
896 const all = byTurn(samples)
897 const counting = !!last && advice.kind !== 'uncached' && advice.kind !== 'off'
898 // the countdown goes green, then yellow, then red as the cache runs out
899 const clockColor = counting ? lifeColor(left, ttl, policy.warnMs) : undefined
900 const stateColor = advice.kind === 'expired' || advice.kind === 'miss' ? 'red' : (clockColor ?? COLOR[advice.kind])
901 const hitColor = (pct: number) => (pct >= 80 ? 'green' : pct >= 40 ? 'yellow' : 'red')
902 // solid bars are filled Boxes, not block characters, so HTML draws no seams between cells
903 const solid = (key: string, parts: [number, string | undefined][]) => (
904 <Box key={key} flexDirection="row" height={1} flexShrink={0}>
905 {parts.map(([w, c], i) => (w > 0 ? <Box key={`${key}:${i}`} width={w} height={1} flexShrink={0} backgroundColor={c} /> : null))}
906 </Box>
907 )
908 const cell = (key: string, w: number, text: string, c?: string, bold = false) => (
909 <Box key={key} width={w} flexShrink={0} justifyContent="flex-end">
910 <Text color={c} bold={bold} dimColor={!c}>{sp(text)}</Text>
911 </Box>
912 )
913
914 const barW = Math.max(8, Math.min(width - LABEL_W - 10, 32))
915 const life = lifeRatio(left, ttl)
916 const lifeFilled = Math.round(life * barW)
917 const [sr, sw, sn] = last ? segments(last.read, last.write, last.fresh, barW) : [0, 0, 0]
918 const rows = all.slice(-Math.max(3, (e.viewport?.rows ?? 24) - 30))
919 const icon = advice.kind === 'warm' ? '●' : advice.kind === 'soon' ? '▲' : advice.kind === 'expired' || advice.kind === 'miss' ? '✖' : '○'
920 const kwi = keepwarmInfo(now)
921 const { tokens, cold, warm } = coldPrice()
922 const isColdNow = coldSince(now) !== undefined
923 const price = priceOf(last?.model ?? '')
924 const rate = writeRate(last?.model ?? '')
925 const breakEven = price && rate ? Math.floor(rate / price[0]) : undefined
926 const paid = misses.reduce((a, m) => a + (m.usd ?? 0), 0)
927
928 // a section: a title, then label/value rows under it
929 const section = (key: string, title: string, children: RenderChildren[]) => (
930 <Box key={key} flexDirection="column" marginTop={1}>
931 <Text bold color="cyan">{sp(title)}</Text>
932 {children}
933 </Box>
934 )
935 // one row: the label dim in a fixed column, the value after it
936 const row = (key: string, label: string, ...value: RenderChildren[]) => (
937 <Box key={key} flexDirection="row" columnGap={1}>
938 <Box width={LABEL_W} flexShrink={0}>
939 <Text dimColor>{sp(label)}</Text>
940 </Box>
941 {value}
942 </Box>
943 )
944 const bar = (key: string, ratio: number, c: string) => {
945 const w = Math.max(0, Math.min(barW, Math.round(ratio * barW)))
946 return solid(key, [[w, c], [barW - w, 'gray']])
947 }
948
949 // same as /keepwarm and /keepwarm off; handled in ui.press like close
950 const kwButton = kwi.on
951 ? <Button key="kw-stop" label="stop" onPress={() => {}} />
952 : <Button key="kw-start" label={`start ${DEFAULT_WINDOW_MS / 3600000}h`} onPress={() => {}} />
953
954 return (
955 <Box flexDirection="column">
956 <Box key="title" flexDirection="row" columnGap={1}>
957 <Text bold color="cyan">{sp('⚡ PROMPT CACHE')}</Text>
958 <Text bold color={stateColor}>{sp(`${icon} ${advice.text}`)}</Text>
959 </Box>
960
961 {section('cache', 'CACHE', [
962 sessionStartedAt ? row('c:session', 'session', <Text key="v" bold>{sp(fmtClock(now - sessionStartedAt))}</Text>) : null,
963 row('c:ttl', 'lifetime', <Text key="v" bold>{sp(ttl)}</Text>, <Text key="s" dimColor>{sp(`(${ttlSource})`)}</Text>),
964 row('c:left', 'expires in',
965 counting ? solid('life', [[lifeFilled, clockColor], [barW - lifeFilled, 'gray']]) : null,
966 <Text key="v" bold color={clockColor}>{sp(counting ? (left > 0 ? fmtClock(left) : '0:00') : '--:--')}</Text>),
967 last ? row('c:model', 'model', <Text key="v" bold>{sp(last.model)}</Text>) : null,
968 last ? row('c:prompt', 'prompt', <Text key="v" bold>{sp(`${fmtTokens(promptTokens(last))} tokens`)}</Text>) : null,
969 ])}
970
971 {last ? section('req', 'LAST REQUEST', [
972 row('r:hit', 'hit rate', solid('stack', [[sr, 'green'], [sw, 'yellow'], [sn, 'cyan']]),
973 <Text key="v" bold color={hitColor(Math.round(hitRatio(last) * 100))}>{sp(pct1(hitRatio(last)))}</Text>),
974 row('r:read', 'read', <Text key="v" bold color="green">{sp(`■ ${fmtTokens(last.read)}`)}</Text>, <Text key="s" dimColor>{sp('served by the cache')}</Text>),
975 row('r:wrote', 'wrote', <Text key="v" bold color="yellow">{sp(`■ ${fmtTokens(last.write)}`)}</Text>, <Text key="s" dimColor>{sp('new cache entry')}</Text>),
976 row('r:new', 'new', <Text key="v" bold color="cyan">{sp(`■ ${fmtTokens(last.fresh)}`)}</Text>, <Text key="s" dimColor>{sp('sent uncached')}</Text>),
977 ]) : null}
978
979 {section('kw', 'KEEPWARM', [
980 kwi.stopped
981 ? row('k:state', 'status', <Text key="v" bold color="red">{sp(`stopped: ${kwi.stopped}`)}</Text>, kwButton)
982 : kwi.on
983 ? row('k:state', 'window', bar('kwbar', kwi.left / kwi.window, 'magenta'),
984 <Text key="v" bold color="magenta">{sp(`${fmtDuration(kwi.left)} left`)}</Text>, kwButton)
985 : row('k:state', 'status', <Text key="v" bold>{sp(kwi.always ? 'off until next session (always)' : 'off')}</Text>, kwButton),
986 kwi.on ? row('k:next', 'next ping', <Text key="v" bold>{sp(kwi.next ?? '')}</Text>, <Text key="s" dimColor>{sp(`every ${fmtDuration(kwi.every)}`)}</Text>) : null,
987 kwi.lastPing ? row('k:last', 'last ping', <Text key="v" bold>{sp(`${fmtTokens(kwi.lastPing.read)} read · ${fmtUsd(kwi.lastPing.usd)}`)}</Text>) : null,
988 breakEven !== undefined ? row('k:be', 'break-even', <Text key="v" bold>{sp(`${breakEven} pings`)}</Text>,
989 <Text key="s" dimColor>{sp(`= one cold write, ~${fmtDuration(breakEven * kwi.every)} idle`)}</Text>) : null,
990 idle ? row('k:idle', 'idle compact', <Text key="v" bold color={idle.on ? 'red' : undefined}>{sp(idle.text)}</Text>) : null,
991 ])}
992
993 {section('cost', 'COST', [
994 last && cold != null ? row('$:cold', 'cold write', bar('coldbar', 1, isColdNow ? 'red' : 'yellow'),
995 <Text key="v" bold color={isColdNow ? 'red' : 'yellow'}>{sp(fmtUsd(cold))}</Text>,
996 <Text key="s" dimColor>{sp(isColdNow ? `cold now: the next message re-writes ${fmtTokens(tokens)}` : `to re-write ${fmtTokens(tokens)}`)}</Text>) : null,
997 last && warm != null && cold ? row('$:warm', 'warm turn', bar('warmbar', Math.max(warm / cold, 1 / barW), 'green'),
998 <Text key="v" bold color="green">{sp(fmtUsd(warm))}</Text>) : null,
999 row('$:guard', 'guard', <Text key="v" bold>{sp(guard === 'refuse' ? 'refuse once' : guard === 'warn' ? 'warn only' : 'off')}</Text>,
1000 <Text key="s" dimColor>{sp(`on a cold cache of ${fmtTokens(policy.compactAtTokens)}+ tokens`)}</Text>),
1001 pctPerUsd !== undefined && cold != null && warm != null
1002 ? row('$:plan', '5h window', <Text key="v" bold color="magenta">{sp(`≈ ${(cold * pctPerUsd).toFixed(1)}% cold · ${(warm * pctPerUsd).toFixed(1)}% warm`)}</Text>,
1003 <Text key="s" dimColor>{sp(`🧪 ${pctPerUsd.toFixed(2)}% per $ · ${sessionsText()}`)}</Text>)
1004 : anchor
1005 ? row('$:plan', '5h window', <Text key="v" dimColor>{sp(`🧪 calibrating… · ${sessionsText()}`)}</Text>)
1006 : null,
1007 row('$:session', 'this session', <Text key="v" bold color={misses.length ? 'red' : undefined}>{sp(`${misses.length} cold write${misses.length === 1 ? '' : 's'} · ${fmtUsd(paid)}`)}</Text>),
1008 ])}
1009
1010 {section('turns', 'TURNS', [
1011 rows.length === 0 ? <Text key="none" dimColor>{sp('no requests yet')}</Text> : <Box key="head" flexDirection="row" columnGap={1}>
1012 {cell('h:turn', 4, 'turn', 'cyan', true)}
1013 {cell('h:steps', 5, 'steps', 'cyan', true)}
1014 {cell('h:read', 6, 'read', 'green', true)}
1015 {cell('h:wrote', 6, 'wrote', 'yellow', true)}
1016 {cell('h:new', 5, 'new', 'cyan', true)}
1017 {cell('h:hit', 6, 'hit', 'magenta', true)}
1018 {cell('h:usd', 6, 'cost', 'cyan', true)}
1019 {pctPerUsd !== undefined ? cell('h:pct', 7, '5h% 🧪', 'magenta', true) : null}
1020 </Box>,
1021 ...rows.map((r, i) => {
1022 const n = all.length - rows.length + i + 1
1023 const pct = Math.round(rowRatio(r) * 100)
1024 const usd = turnUsd(r.turnId)
1025 return (
1026 <Box key={`t:${r.turnId}`} flexDirection="row" columnGap={1}>
1027 {r.turnId.startsWith('keepwarm-') ? cell(`c:turn:${r.turnId}`, 4, '♨')
1028 : misses.some(m => m.turnId === r.turnId) ? cell(`c:turn:${r.turnId}`, 4, `❄${n}`, 'cyan', true)
1029 : cell(`c:turn:${r.turnId}`, 4, String(n))}
1030 {cell(`c:steps:${r.turnId}`, 5, String(r.steps))}
1031 {cell(`c:read:${r.turnId}`, 6, fmtTokens(r.read), 'green')}
1032 {cell(`c:wrote:${r.turnId}`, 6, fmtTokens(r.write), 'yellow')}
1033 {cell(`c:new:${r.turnId}`, 5, fmtTokens(r.fresh), 'cyan')}
1034 {cell(`c:hit:${r.turnId}`, 6, pct1(rowRatio(r)), hitColor(pct), true)}
1035 {cell(`c:usd:${r.turnId}`, 6, fmtUsd(usd))}
1036 {pctPerUsd !== undefined ? cell(`c:pct:${r.turnId}`, 7, usd == null ? 'n/a' : `${(usd * pctPerUsd).toFixed(1)}%`, 'magenta') : null}
1037 </Box>
1038 )
1039 }),
1040 ])}
1041
1042 <Box key="foot" marginTop={1}>
1043 <Button key="close" label="close" onPress={() => {}} />
1044 </Box>
1045 </Box>
1046 )
1047 })
1048
1049 // a message to a cold cache: refused once with its price (guard: refuse), or sent with the price logged (warn)
1050 on('prompt.submit', async ($, e, next) => {
1051 if (e.origin.kind === 'plugin' || typeof e.text !== 'string' || e.text.trimStart().startsWith('/')) return next(e)
1052 const now = Date.now()
1053 const last = samples[samples.length - 1]
1054 if (!last) return next(e)
1055 const verdict = guardVerdict({ mode: guard, coldAt: coldSince(now), tokens: promptTokens(last), minTokens: policy.compactAtTokens, startedAt: last.startedAt, ackedAt })
1056 if (verdict === 'pass') return next(e)
1057 if (verdict === 'warn') {
1058 $.ui.log(`prompt-cache-control: ${guardText(now)} Sending anyway; keepwarm will hold the cache for ${fmtDuration(AUTO_WARM_MS)} once it lands.`)
1059 coldWritePending = true
1060 return next(e)
1061 }
1062 if (verdict === 'resend') {
1063 ackedAt = 0
1064 coldWritePending = true
1065 return next(e)
1066 }
1067 ackedAt = last.startedAt
1068 return { drop: `prompt-cache-control: ${guardText(now)} Send it again to pay it, and keepwarm will then hold the cache for ${fmtDuration(AUTO_WARM_MS)}. Or /clear and start from a note.` }
1069 })
1070
1071 on('session.compact', async ($, e, next) => {
1072 const r = await next(e)
1073 if (!e.agentId) {
1074 compacted = true
1075 await arm($)
1076 }
1077 return r
1078 })
1079
1080 on('turn.complete', async ($, e, next) => {
1081 const r = await next(e)
1082 if (e.agentId) return r
1083 compacted = false
1084 if (e.usage) {
1085 const usd = usdOf(e.usage, e.usage.model || (samples[samples.length - 1]?.model ?? ''))
1086 if (usd != null) spentUsd += usd
1087 }
1088 await calibrate($).catch(() => undefined)
1089 const paid = coldWriteOf(e.turnId)
1090 coldWritePending = false
1091 if (paid) {
1092 const rate = writeRate(paid.model)
1093 const usd = rate == null ? null : (paid.write * rate) / 1e6
1094 misses.push({ at: paid.startedAt, turnId: paid.turnId, tokens: paid.write, usd })
1095 // a cold write was just paid: keep it from being paid again today
1096 if (deadline < Date.now() + AUTO_WARM_MS) {
1097 await startWindow($, AUTO_WARM_MS, every)
1098 $.ui.log(`prompt-cache-control: cold write of ${fmtTokens(paid.write)} tokens paid (${fmtUsd(usd)}). Keeping the cache warm for ${fmtDuration(AUTO_WARM_MS)} so it is not paid again today; /keepwarm off to stop.`)
1099 }
1100 }
1101 await arm($)
1102 return r
1103 })
1104
1105 on('command.run', { command: 'keepwarm' }, async ($, e) => {
1106 const words = String(e.args ?? '').trim().split(/\s+/).filter(Boolean)
1107 if (words[0] === 'off') {
1108 const wasAlways = always
1109 await stop($, null, true)
1110 return { text: wasAlways ? 'keepwarm is off, and no longer arms itself at session start' : 'keepwarm is off' }
1111 }
1112 if (words[0] === 'always') {
1113 always = true
1114 await $.store.set(KEY_ALWAYS, true)
1115 await startWindow($, DEFAULT_WINDOW_MS, 0)
1116 return { text: `keepwarm always on: every session starts with a ${fmtDuration(DEFAULT_WINDOW_MS)} window; /keepwarm off turns it off for good` }
1117 }
1118 if (!words.length) {
1119 await startWindow($, DEFAULT_WINDOW_MS, 0)
1120 return { text: armedText(DEFAULT_WINDOW_MS) }
1121 }
1122 if (words[0] === 'status') return { text: statusLine(Date.now()) ?? 'keepwarm is off' }
1123 const windowMs = parseDuration(words[0])
1124 if (windowMs == null) return { text: 'keepwarm takes a window such as 6h or 90m, or always, off, or status' }
1125 let everyMs = 0
1126 if (words[1] === 'every') {
1127 const p = parseDuration(words[2] ?? '')
1128 if (p == null || p < MIN_PING_MS) return { text: 'every takes a period of at least 1m' }
1129 everyMs = p
1130 }
1131 await startWindow($, windowMs, everyMs)
1132 return { text: armedText(windowMs) }
1133 })
1134}
1135hooks/cache.ts 407 lines1/**
2 * cache.ts — the pure half of prompt-cache-control: no `$`, no engine.
3 *
4 * What it models, from Anthropic's prompt-caching documentation:
5 * - the cache lives 5 minutes by default, 1 hour when asked for; a read
6 * refreshes the entry at no extra cost, and the lifetime is measured from
7 * the START of the request that wrote or read it
8 * - a request's prompt is `input_tokens` (uncached remainder) +
9 * `cache_read_input_tokens` + `cache_creation_input_tokens`
10 * - writes cost 1.25x base input for 5m and 2x for 1h; reads about 0.1x
11 * (less on some models), so an expired cache on a large context is the
12 * expensive moment
13 * - a prefix change (model, effort/thinking settings, tool set, system
14 * prompt) makes the next request write instead of read
15 *
16 * Claude Code's own switches (read from the environment):
17 * ENABLE_PROMPT_CACHING_1H=1 ask for the 1-hour TTL
18 * FORCE_PROMPT_CACHING_5M=1 force the 5-minute TTL, beating the above
19 * DISABLE_PROMPT_CACHING=1 no caching; DISABLE_PROMPT_CACHING_{HAIKU,SONNET,OPUS}
20 * turn it off for that model family only
21 */
22
23export type Ttl = '5m' | '1h'
24
25export type CacheEnv = {
26 enable1h?: string
27 force5m?: string
28 /** CLAUDE_CODE_PROMPT_CACHE_TTL: "5m" or "1h" for the main conversation */
29 ttlVar?: string
30 disableAll?: string
31 disableHaiku?: string
32 disableSonnet?: string
33 disableOpus?: string
34}
35
36/** One main-loop request, as the API reported it. */
37export type Sample = {
38 turnId: string
39 index: number
40 model: string
41 /** ms since the epoch when the request started: the cache's lifetime is counted from here */
42 startedAt: number
43 read: number
44 write: number
45 fresh: number
46 output: number
47}
48
49export type AdviceKind = 'off' | 'cold' | 'uncached' | 'warm' | 'soon' | 'expired' | 'miss'
50
51export type Advice = {
52 kind: AdviceKind
53 /** one sentence for the band */
54 text: string
55}
56
57export type Policy = {
58 ttl: Ttl
59 warnMs: number
60 compactAtTokens: number
61}
62
63export const isOn = (v: string | undefined) => v === '1' || v?.toLowerCase() === 'true'
64
65/** What the account is billed as, as far as the mod can tell. */
66export type Account = 'subscription' | 'credits' | 'other'
67
68export type TtlChoice = { ttl: Ttl; source: string }
69
70const asTtl = (v: unknown): Ttl | undefined => (v === '5m' || v === '1h' ? v : undefined)
71
72/**
73 * Which lifetime Claude Code asks for on the main conversation, in the order
74 * its documentation gives (https://code.claude.com/docs/en/prompt-caching,
75 * "Choose the TTL yourself"), after the mod's own `ttl` option:
76 *
77 * FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL, the promptCacheTtl
78 * setting, ENABLE_PROMPT_CACHING_1H, then the default of the account: one
79 * hour on a Claude subscription within its plan usage, five minutes on usage
80 * credits, an API key or a cloud provider.
81 */
82export function decideTtl(option: unknown, env: CacheEnv, setting?: unknown, account?: Account): TtlChoice {
83 const pinned = asTtl(option)
84 if (pinned) return { ttl: pinned, source: 'the ttl option' }
85 if (isOn(env.force5m)) return { ttl: '5m', source: 'FORCE_PROMPT_CACHING_5M' }
86 const fromVar = asTtl(env.ttlVar)
87 if (fromVar) return { ttl: fromVar, source: 'CLAUDE_CODE_PROMPT_CACHE_TTL' }
88 const fromSetting = asTtl(setting)
89 if (fromSetting) return { ttl: fromSetting, source: 'the promptCacheTtl setting' }
90 if (isOn(env.enable1h)) return { ttl: '1h', source: 'ENABLE_PROMPT_CACHING_1H' }
91 if (account === 'subscription') return { ttl: '1h', source: 'Claude subscription default' }
92 if (account === 'credits') return { ttl: '5m', source: 'usage credits default' }
93 return { ttl: '5m', source: 'default' }
94}
95
96export const resolveTtl = (option: unknown, env: CacheEnv, setting?: unknown, account?: Account): Ttl =>
97 decideTtl(option, env, setting, account).ttl
98
99/**
100 * The account, from the rate-limit windows the last response reported: a
101 * five-hour or seven-day window means a Claude subscription, and one that is
102 * full means the next requests draw on usage credits. No window (an API key,
103 * a cloud provider, or no response yet) says nothing.
104 */
105export function accountOf(windows: readonly { kind: string; percentUsed: number }[]): Account {
106 const plan = windows.filter(w => w.kind === 'five_hour' || w.kind === 'seven_day')
107 if (plan.length === 0) return 'other'
108 return plan.some(w => w.percentUsed >= 100) ? 'credits' : 'subscription'
109}
110
111export function ttlMs(ttl: Ttl): number {
112 return ttl === '1h' ? 3_600_000 : 300_000
113}
114
115/** Caching switched off for this model by the environment. */
116export function isCachingDisabled(model: string, env: CacheEnv): boolean {
117 if (isOn(env.disableAll)) return true
118 const name = model.toLowerCase()
119 if (name.includes('haiku')) return isOn(env.disableHaiku)
120 if (name.includes('sonnet')) return isOn(env.disableSonnet)
121 if (name.includes('opus')) return isOn(env.disableOpus)
122 return false
123}
124
125export const promptTokens = (s: Sample) => s.read + s.write + s.fresh
126
127/** Share of the prompt the cache served, 0 to 1; 0 for an empty prompt. */
128export function hitRatio(s: Sample): number {
129 const total = promptTokens(s)
130 return total === 0 ? 0 : s.read / total
131}
132
133/** When the cache entry the sample touched lapses, ms since the epoch. */
134export const expiresAt = (s: Sample, ttl: Ttl) => s.startedAt + ttlMs(ttl)
135
136/** Zero for a request that read and wrote nothing: it created or refreshed no entry, so there is nothing to count down. */
137export function remainingMs(s: Sample, ttl: Ttl, now: number): number {
138 if (s.read + s.write === 0) return 0
139 return Math.max(0, expiresAt(s, ttl) - now)
140}
141
142/**
143 * Why a request that should have read the cache wrote it instead; undefined
144 * when it did not miss. A prompt that shrank is a /compact or /clear, not a
145 * miss, and the first request of a session has nothing to read.
146 */
147export function missReason(prev: Sample | undefined, cur: Sample, ttl: Ttl): string | undefined {
148 if (!prev) return undefined
149 const before = promptTokens(prev)
150 if (before === 0 || promptTokens(cur) < before * 0.7) return undefined
151 if (cur.read >= before * 0.5 || cur.write === 0) return undefined
152 if (cur.model !== prev.model) return `model changed (${prev.model} to ${cur.model})`
153 if (cur.startedAt - prev.startedAt > ttlMs(ttl)) return `the ${ttl} cache had lapsed`
154 return 'the prompt prefix changed (effort, tools, system prompt or CLAUDE.md)'
155}
156
157export function advise(last: Sample | undefined, prev: Sample | undefined, policy: Policy, now: number, disabled: boolean): Advice {
158 if (disabled) return { kind: 'off', text: 'prompt caching is off for this model (DISABLE_PROMPT_CACHING*)' }
159 if (!last) return { kind: 'cold', text: 'no request yet: the first one writes the cache' }
160 if (last.read + last.write === 0) {
161 return { kind: 'uncached', text: 'this request was not cached (prompt under the model minimum, or caching off)' }
162 }
163 const miss = missReason(prev, last, policy.ttl)
164 const left = remainingMs(last, policy.ttl, now)
165 const size = promptTokens(last)
166 if (left <= 0) {
167 const big = size >= policy.compactAtTokens
168 return {
169 kind: 'expired',
170 text: big
171 ? `expired: the next message rewrites ${fmtTokens(size)} tokens. /compact first, or /clear if the task is done`
172 : `expired: only ${fmtTokens(size)} tokens to rebuild, just keep going`,
173 }
174 }
175 if (left <= policy.warnMs) {
176 return { kind: 'soon', text: 'expires soon: any message refreshes it for free' }
177 }
178 if (miss) return { kind: 'miss', text: `cache missed: ${miss}` }
179 return { kind: 'warm', text: 'warm, keep going' }
180}
181
182export function fmtTokens(n: number): string {
183 if (n < 1000) return String(n)
184 if (n < 100_000) return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k`
185 if (n < 1_000_000) return `${Math.round(n / 1000)}k`
186 return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
187}
188
189/** m:ss, or h:mm:ss from an hour up. */
190export function fmtClock(ms: number): string {
191 const total = Math.max(0, Math.ceil(ms / 1000))
192 const h = Math.floor(total / 3600)
193 const m = Math.floor((total % 3600) / 60)
194 const s = total % 60
195 const pad = (n: number) => String(n).padStart(2, '0')
196 return h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`
197}
198
199/** the band's countdown: whole minutes (rounded down) from 10 minutes up, so it does not tick; m:ss below */
200export function fmtCountdown(ms: number): string {
201 if (ms < 10 * 60_000) return fmtClock(ms)
202 const total = Math.floor(ms / 60_000)
203 const h = Math.floor(total / 60)
204 const m = total % 60
205 return h > 0 ? `${h}h${String(m).padStart(2, '0')}m` : `${m}m`
206}
207
208/** the 5-hour plan window under the prompt: `5h 42% · reset 2h13m`; undefined without a reading or once it has reset */
209export function fmtLimit(w: { percentUsed: number; resetsAt?: string } | undefined, now: number): string | undefined {
210 if (!w) return undefined
211 const at = w.resetsAt ? Date.parse(w.resetsAt) : NaN
212 if (Number.isNaN(at)) return `5h ${w.percentUsed}%`
213 if (at <= now) return undefined
214 const total = Math.ceil((at - now) / 60_000)
215 const h = Math.floor(total / 60)
216 const m = total % 60
217 return `5h ${w.percentUsed}% · reset ${h > 0 ? `${h}h${String(m).padStart(2, '0')}m` : `${m}m`}`
218}
219
220export function bar(ratio: number, width: number): string {
221 const filled = Math.round(Math.min(1, Math.max(0, ratio)) * width)
222 return '█'.repeat(filled) + '░'.repeat(width - filled)
223}
224
225export type TurnRow = {
226 turnId: string
227 steps: number
228 read: number
229 write: number
230 fresh: number
231 output: number
232}
233
234/** Samples grouped by turn, oldest first, each turn's requests summed. */
235export function byTurn(samples: readonly Sample[]): TurnRow[] {
236 const rows: TurnRow[] = []
237 for (const s of samples) {
238 let row = rows[rows.length - 1]
239 if (!row || row.turnId !== s.turnId) {
240 row = { turnId: s.turnId, steps: 0, read: 0, write: 0, fresh: 0, output: 0 }
241 rows.push(row)
242 }
243 row.steps += 1
244 row.read += s.read
245 row.write += s.write
246 row.fresh += s.fresh
247 row.output += s.output
248 }
249 return rows
250}
251
252export const rowRatio = (r: TurnRow) => {
253 const total = r.read + r.write + r.fresh
254 return total === 0 ? 0 : r.read / total
255}
256
257export function positive(v: unknown, fallback: number): number {
258 return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : fallback
259}
260
261/** Share of the cache lifetime left, 0 to 1. */
262export function lifeRatio(leftMs: number, ttl: Ttl): number {
263 return Math.min(1, Math.max(0, leftMs / ttlMs(ttl)))
264}
265
266/**
267 * Widths of the three stacked-bar segments (read, wrote, new) over `width`
268 * cells: proportional, each non-empty part at least one cell, summing to width.
269 */
270export function segments(read: number, write: number, fresh: number, width: number): [number, number, number] {
271 const total = read + write + fresh
272 if (total === 0 || width <= 0) return [0, 0, 0]
273 const parts = [read, write, fresh]
274 const cells = parts.map(p => (p > 0 ? Math.max(1, Math.round((p / total) * width)) : 0))
275 let over = cells.reduce((a, b) => a + b, 0) - width
276 while (over !== 0) {
277 const i = over > 0 ? cells.indexOf(Math.max(...cells)) : parts.indexOf(Math.max(...parts))
278 cells[i] += over > 0 ? -1 : 1
279 over += over > 0 ? -1 : 1
280 }
281 return [cells[0], cells[1], cells[2]]
282}
283
284/** Seconds left at which a toast counts down after the one at the warning threshold. */
285export const COUNTDOWN_MARKS = [10, 3, 2, 1]
286
287/**
288 * The toast mark to fire now, or undefined. `level` is the mark last fired for
289 * this cache entry (Infinity before any); a late tick skips straight to the
290 * newest mark crossed, so a stalled clock never replays old ones.
291 */
292export function nextToastMark(secsLeft: number, warnSecs: number, level: number): number | undefined {
293 const marks = [warnSecs, ...COUNTDOWN_MARKS].filter(m => m <= warnSecs)
294 const due = marks.filter(m => secsLeft <= m && m < level)
295 return due.length ? Math.min(...due) : undefined
296}
297
298export type LifeColor = 'green' | 'yellow' | 'red'
299
300/** Countdown colour: green while there is plenty, yellow below 40% of the lifetime, red from the warning threshold down. */
301export function lifeColor(leftMs: number, ttl: Ttl, warnMs: number): LifeColor {
302 if (leftMs <= warnMs) return 'red'
303 return leftMs / ttlMs(ttl) <= 0.4 ? 'yellow' : 'green'
304}
305
306// requests are timed from their start, so a little slack keeps a hit that
307// landed just inside the lifetime from reading as proof of the longer one
308const SLACK_MS = 10_000
309
310/**
311 * What the traffic says about the cache lifetime, given the request before and
312 * `known`, what earlier requests already showed.
313 *
314 * - a hit (the cache served at least half of the previous prompt) more than
315 * 5 minutes after the previous request began proves the 1-hour lifetime,
316 * and nothing later undoes it: a miss afterwards is more likely a changed
317 * prefix than a lapse
318 * - a miss with the same model and a prompt that did not shrink, 5 minutes to
319 * an hour after the previous request, says the entry lapsed: 5 minutes
320 * (weaker: a changed prefix looks the same, so a later hit overrules it)
321 *
322 * Needed because the API names the TTL of a write (`cache_creation.ephemeral_*`)
323 * but Claude Code's mod API passes on only the four token counts.
324 */
325export function observeTtl(prev: Sample | undefined, cur: Sample, known: Ttl | undefined): Ttl | undefined {
326 if (!prev || prev.read + prev.write === 0 || cur.model !== prev.model) return known
327 const gap = cur.startedAt - prev.startedAt
328 const before = promptTokens(prev)
329 if (gap <= ttlMs('5m') + SLACK_MS) return known
330 if (cur.read >= before * 0.5) return '1h'
331 if (known === '1h') return known
332 const lapsed = cur.write > 0 && promptTokens(cur) >= before * 0.7 && gap < ttlMs('1h') + SLACK_MS
333 return lapsed ? '5m' : known
334}
335
336export type GuardMode = 'refuse' | 'warn' | 'off'
337
338/**
339 * What to do with a message (cold-cache guard, from cache-tax): `coldAt` is when
340 * the last request's cache lapsed (undefined while warm), `minTokens` the prompt size below which a
341 * cold write is cheap enough to just send (compactAtTokens, as in `advise`), `startedAt` that
342 * request's start, `ackedAt` the request a previous refusal was for.
343 */
344export function guardVerdict(g: { mode: GuardMode; coldAt: number | undefined; tokens: number; minTokens: number; startedAt: number; ackedAt: number }): 'pass' | 'warn' | 'drop' | 'resend' {
345 if (g.mode === 'off' || g.coldAt === undefined || g.tokens < g.minTokens) return 'pass'
346 if (g.mode === 'warn') return 'warn'
347 return g.ackedAt === g.startedAt ? 'resend' : 'drop'
348}
349
350/**
351 * Claude Code's idle compaction (2.1.299): about 54 minutes into a 1h cache it
352 * compacts a conversation of `minTokens` or more. A remote flag
353 * (`tengu_sunny_locket.mode` in ~/.claude.json's cachedGrowthBookFeatures)
354 * turns it on; `idleCompaction: false`, `autoCompactEnabled: false` or
355 * DISABLE_AUTO_COMPACT turn it off. Our keepwarm pings do not reset its timer
356 * (they are auxiliary requests), so with it on a ping at 50m is paid for nothing.
357 */
358export function idleCompactState(i: { flagMode: unknown; idleSetting: unknown; autoCompact: unknown; disableEnv: string | undefined; minEnv: string | undefined }): { on: boolean; text: string; minTokens: number } {
359 const n = Number(i.minEnv)
360 const minTokens = Number.isFinite(n) && n > 0 ? Math.max(100_000, n) : 200_000
361 const off = (text: string) => ({ on: false, text, minTokens })
362 if (i.flagMode !== 'compact' && i.flagMode !== 'log') return off(i.flagMode === undefined ? 'unknown (no flag cached)' : 'off (not rolled out)')
363 if (i.idleSetting === false) return off('off (idleCompaction: false)')
364 if (i.autoCompact === false) return off('off (autoCompactEnabled: false)')
365 if (isOn(i.disableEnv)) return off('off (DISABLE_AUTO_COMPACT)')
366 if (i.flagMode === 'log') return off('dry run (flag mode log)')
367 return { on: true, text: `ON at ${fmtTokens(minTokens)}+ tokens on a 1h cache`, minTokens }
368}
369
370/** a request re-wrote the prefix: the guard let a cold send through, or it wrote half a 20k+ previous prompt or more (from cache-tax) */
371export const isColdWrite = (prevTokens: number, write: number, guardLetThrough: boolean) =>
372 guardLetThrough || (prevTokens > 20_000 && write >= 0.5 * prevTokens)
373
374/**
375 * Experimental: percent of a plan window per list-price dollar, from how far
376 * the window moved (`pct0` to `pct`) while `usd0` to `usd` was spent. Undefined
377 * until the window moved half a percent, as it reports one decimal.
378 */
379export function calibRate(pct0: number, usd0: number, pct: number, usd: number): number | undefined {
380 const dp = pct - pct0
381 const du = usd - usd0
382 return dp >= 0.5 && du > 0 ? dp / du : undefined
383}
384
385/** one session's spend in a plan window, as each session writes it to the shared store */
386export type Spend = { resetsAt: string; usd: number; at: number }
387
388/**
389 * Every session's spend in the window that resets at `resetsAt`, summed; how
390 * many of them wrote within `activeMs`; and the keys left from other windows.
391 */
392export function windowSpend(entries: [string, unknown][], resetsAt: string, now: number, activeMs = 10 * 60_000) {
393 let usd = 0
394 let active = 0
395 const stale: string[] = []
396 for (const [key, v] of entries) {
397 const s = v as Partial<Spend> | undefined
398 if (!s || s.resetsAt !== resetsAt || typeof s.usd !== 'number') {
399 stale.push(key)
400 continue
401 }
402 usd += s.usd
403 if (typeof s.at === 'number' && now - s.at <= activeMs) active++
404 }
405 return { usd, active, stale }
406}
407