SLOPSHOPPER

cache-meter

Band above the prompt: prompt-cache countdown, cache hit rate, context fill and a Compact button, plus a keepwarm row from cache-tax that pings the cache…

bandcommandtoaststatuspromptmodel
v0.3.3MITupdated 2026-10-20hal-9/claude-mods/mods/cache-meter
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cache-meter
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /keepwarm ⎿ cache-meter: keepwarm on for 6h00m, a ping 50m after each idle stretch keeps the cache read, not re-written ▾ cache-meter · keepwarm 6h00m left ● keepwarm 6h00m left$0.78 cold rewrite of 97k│ping in 50m[ Stop ] ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
▾ cache-meter · keepwarm 6h00m left ● keepwarm 6h00m left$0.78 cold rewrite of 97k│ping in 50m[ Stop ]
README

cache-meter

A two-row band above the prompt (relay's buttons sit under it):

▾ cache-meter · cache 52m · context 8% · keepwarm 5h09m left
● cache 52m ▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▯ 95% hit │ ○ context 8% (auto-compact 95%) [Compact]
● keepwarm 5h09m left $4.00 cold rewrite of 200k │ ping in 49m · last ping 200k read, $0.05 [Stop]
  • cache — how long the prompt cache stays warm, counting down from the last response (green while warm, cold once the TTL has passed and the next request re-caches the whole context).
  • bar + hit — how much of the last request's input the cache served: cache_read / (input + cache_read + cache_write).
  • context — the tokens the next request re-sends against the model's window, with the auto-compact threshold beside it. Green under 50 %, yellow under 80 %, red above.
  • header — click it to fold the band to that one line and back, remembered across sessions; the band lights up under the pointer. Hovering a button shows what it does.
  • Compact — runs /compact. Refused while a turn is running; a toast says so.
  • keepwarm — the window /keepwarm armed (off, stopped and why, or the time left), what letting the cache go cold would cost (red once it has: the next send pays it), and the next ping. Keep warm arms six hours, Stop does /keepwarm off.

The figures come from the engine's own turn.step usage and $.session.usage(); nothing is estimated locally. The meter is empty until the first response of a window, and empties again after a compaction.

Keepwarm and the cold-send guard

From karanb192/cache-tax 2.3.0 (MIT, LICENSE.cache-tax), in hooks/keepwarm.ts; its own band and cube icon are dropped for the row above.

/keepwarm keep warm for six hours /keepwarm 90m a window of your own (also 2h30m, 6h) /keepwarm always every session, until six hours after its last turn /keepwarm 6h every 2m a testing period, 1m to 59m /keepwarm status | off /cache-tax the card: model, cold cost, break-even, cold writes paid /cache-tax guard warn | refuse

A ping is one tool-less $.model.fork over the session after 50 idle minutes; it bills a cache read and stops once a ping finds the cache gone. With the cache cold and 50k+ tokens of context, the guard drops your next typed message once with the rewrite price; sending it again pays it, and a paid cold write keeps the cache warm for three hours. Keepwarm assumes the one-hour cache whatever cacheTtl says.

Config

FieldValuesDefault
cacheTtl5m, 1h1h

The engine does not expose which cache TTL a session uses, so pick the one your tier has.

Install

/plugin install cache-meter --marketplace hal-9/claude-mods

Plays along with relay: whichever of the two draws the band embeds the other's.

Source 4 files
hooks/register.tsx 363 lines
1import type { EngineInterface, Register, RenderChildren } from 'claude-code'
2
3import type { Reading } from '../types'
4import type { State } from './keepwarm'
5import { setReading } from './meter'
6
7// $.state refs are read as literals in the file that uses them, so meter.ts keeps its own copies.
8const READING = { plugin: 'cache-meter', key: 'reading' } as const
9const TICK = { plugin: 'cache-meter', key: 'tick' } as const
10const COLLAPSED = { plugin: 'cache-meter', key: 'collapsed' } as const
11import { coldUsd, DEFAULT_WINDOW_MS, fmtDuration, fmtTok, fmtUsd, freshState, isCold, keepwarm, nextPing, PING_AFTER_MS, startWindow, stop } from './keepwarm'
12
13
14const SEGMENTS = 16
15const TTL_MS = { '5m': 5 * 60_000, '1h': 60 * 60_000 } as const
16
17// The savvy-progress palette, so the bands read as one family.
18const ACCENT = '#8f8cf4'
19const WARM = '#5fbf8f'
20const AMBER = '#e0a43a'
21const RED = '#e5675a'
22const COLD = '#9a9a9a'
23const FONT = "-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',sans-serif"
24
25type $ = EngineInterface
26
27const bar = (percent: number) => {
28  const filled = Math.round((percent / 100) * SEGMENTS)
29  return ['▮'.repeat(filled), '▯'.repeat(SEGMENTS - filled)] as const
30}
31
32const level = (percent: number) => (percent < 50 ? 'success' : percent < 80 ? 'warning' : 'error')
33const levelHex = (percent: number) => (percent < 50 ? ACCENT : percent < 80 ? AMBER : RED)
34const glyph = (percent: number) => (percent < 25 ? '○' : percent < 50 ? '◔' : percent < 75 ? '◑' : percent < 100 ? '◕' : '●')
35const minutes = (ms: number) => Math.ceil(ms / 60_000)
36
37// ---------------------------------------------------------------------------
38// Desktop: the row is one SVG, as savvy-progress draws its own (the desktop
39// wraps sibling elements onto new lines). Only the buttons sit beside it.
40
41const H = 22
42const BAR_H = 14
43const CELL = 3
44
45// Deterministic noise so the dither does not shimmer between redraws.
46const noise = (x: number, y: number) => {
47  const s = Math.sin(x * 12.9898 + y * 78.233) * 43758.5453
48  return s - Math.floor(s)
49}
50
51// ponytail: per-class width estimate for the system font; keepwarm's stop reasons are the only text not ours.
52const charW = (c: string) => (/[il.,:;'|· ()]/.test(c) ? 0.3 : /[mwMW]/.test(c) ? 0.86 : /[A-Z0-9$%]/.test(c) ? 0.64 : 0.54)
53const textW = (s: string, size: number) => Math.round([...s].reduce((w, c) => w + charW(c), 0) * size)
54
55// Both rows' labels take the width of the longer one, so their pills line up.
56const LABEL_W = textW('Keepwarm', 13)
57const PILL_X = 16 + LABEL_W + 8
58
59const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
60const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + '…' : s)
61
62// A rounded track, dithered up to `percent`, sparse at the start and dense toward the head.
63function ditherBar(x: number, w: number, percent: number, color: string, seed: number, marker?: number | null) {
64  const y = (H - BAR_H) / 2
65  const cols = Math.floor((w * Math.min(100, percent)) / 100 / CELL)
66  const rows = Math.floor(BAR_H / CELL)
67  const dots: string[] = []
68  for (let c = 0; c < cols; c++) {
69    const density = 0.35 + 0.6 * Math.pow(c / Math.max(1, cols), 1.2)
70    for (let r = 0; r < rows; r++) {
71      if (noise(c + seed, r) < density) dots.push(`<rect class="t${Math.floor(noise(r, c + seed) * 4)}" x="${c * CELL + 1}" y="${r * CELL + 1}" width="2" height="2"/>`)
72    }
73  }
74  const tick = marker == null ? '' : `<rect class="mk" x="${Math.round((w * marker) / 100) - 1}" y="-2" width="2" height="${BAR_H + 4}" rx="1"/>`
75  return `<g transform="translate(${x},${y})">
76<clipPath id="c${seed}"><rect width="${w}" height="${BAR_H}" rx="${BAR_H / 2}"/></clipPath>
77<rect class="k" width="${w}" height="${BAR_H}" rx="${BAR_H / 2}"/>
78<g clip-path="url(#c${seed})" fill="${color}">${dots.join('')}</g>${tick}
79</g>`
80}
81
82type Row = { m: Reading; isWarm: boolean; countdown: string; barW: number }
83
84function rowSvg({ m, isWarm, countdown, barW }: Row) {
85  const warm = isWarm ? WARM : COLD
86  const ctx = levelHex(m.percent)
87  const parts: string[] = []
88  let x = 0
89  const text = (s: string, cls: string, size = 13, weight = 500) => {
90    parts.push(`<text class="${cls}" x="${x}" y="${H / 2 + 4.5}" font-size="${size}" font-weight="${weight}">${s}</text>`)
91    x += textW(s, size)
92  }
93  // A figure and its word in one text run, so the browser sets the space between them.
94  const figure = (value: string, word: string) => {
95    parts.push(`<text x="${x}" y="${H / 2 + 4.5}" font-size="12.5"><tspan class="t" font-weight="600">${value}</tspan><tspan class="m" dx="5">${word}</tspan></text>`)
96    x += textW(value, 12.5) + 5 + textW(word, 12.5)
97  }
98
99  x = head(parts, 'Cache', countdown, warm)
100  parts.push(ditherBar(x, barW, m.hitPercent, warm, 1))
101  x += barW + 8
102  figure(`${m.hitPercent}%`, 'hit')
103  x += 14
104  parts.push(`<rect class="tk" x="${x}" y="${H / 2 - 6}" width="1" height="12"/>`)
105  x += 15
106  text('Context', 't')
107  x += 10
108  parts.push(ditherBar(x, barW, m.percent, ctx, 7, m.autoCompactPercent))
109  x += barW + 8
110  if (m.autoCompactPercent !== null) figure(`${m.percent}%`, `compacts at ${m.autoCompactPercent}%`)
111  else text(`${m.percent}%`, 't', 12.5, 600)
112  return { parts, width: x + 4, isWarm }
113}
114
115// The dot, the label in its column and the pill: how both rows start. Returns where the row goes on.
116function head(parts: string[], label: string, pill: string, color: string) {
117  parts.push(`<circle cx="5" cy="${H / 2}" r="4" fill="${color}"/>`)
118  parts.push(`<text class="t" x="16" y="${H / 2 + 4.5}" font-size="13" font-weight="500">${label}</text>`)
119  const pillW = 16 + textW(pill, 11)
120  parts.push(`<rect x="${PILL_X}" y="${(H - 16) / 2}" width="${pillW}" height="16" rx="8" fill="${color}"/>`)
121  parts.push(`<text x="${PILL_X + pillW / 2}" y="${H / 2 + 4}" text-anchor="middle" font-size="11" font-weight="600" fill="#ffffff">${esc(pill)}</text>`)
122  return PILL_X + pillW + 10
123}
124
125type Kw = { mode: 'on' | 'off' | 'stopped'; pill: string; detail: string; rewrite: { value: string; word: string } | null; isCold: boolean }
126
127// The keepwarm row: the window, what it waits for, and what letting the cache go cold costs.
128function kwOf(s: State, now: number): Kw {
129  const cold = isCold(s, now)
130  const usd = s.ctx && !s.compacted ? coldUsd(s) : null
131  const rewrite = usd == null ? null : { value: fmtUsd(usd), word: cold ? `next send rewrites ${fmtTok(s.ctx)}` : `cold rewrite of ${fmtTok(s.ctx)}` }
132  if (s.deadline && now < s.deadline) {
133    const last = s.last ? ` · last ping ${fmtTok(s.last.read)} read, ${fmtUsd(s.last.usd)}` : ''
134    return { mode: 'on', pill: `${fmtDuration(s.deadline - now)} left`, detail: nextPing(s, now) + last, rewrite, isCold: cold }
135  }
136  if (s.stopped) return { mode: 'stopped', pill: 'stopped', detail: s.stopped, rewrite, isCold: cold }
137  return { mode: 'off', pill: 'off', detail: '', rewrite, isCold: cold }
138}
139
140const kwColor = (k: Kw) => (k.mode === 'stopped' ? AMBER : k.mode === 'on' && !k.isCold ? WARM : COLD)
141
142function kwSvg(k: Kw) {
143  const parts: string[] = []
144  let x = head(parts, 'Keepwarm', k.pill, kwColor(k))
145  // The price first: the free text after it is the one whose width is only estimated.
146  if (k.rewrite) {
147    parts.push(`<text x="${x}" y="${H / 2 + 4.5}" font-size="12.5"><tspan class="${k.isCold ? 'hot' : 't'}" font-weight="600">${k.rewrite.value}</tspan><tspan class="m" dx="5">${esc(k.rewrite.word)}</tspan></text>`)
148    x += textW(k.rewrite.value, 12.5) + 5 + textW(k.rewrite.word, 12.5) + 14
149    if (k.detail) {
150      parts.push(`<rect class="tk" x="${x}" y="${H / 2 - 6}" width="1" height="12"/>`)
151      x += 15
152    }
153  }
154  if (k.detail) {
155    const detail = clip(k.detail, 72)
156    parts.push(`<text class="m" x="${x}" y="${H / 2 + 4.5}" font-size="12.5">${esc(detail)}</text>`)
157    x += textW(detail, 12.5)
158  }
159  return { parts, width: x + 4, isWarm: false }
160}
161
162// Wraps a row's parts at a width shared by both rows, so the buttons beside them line up.
163const svgOf = ({ parts, isWarm }: { parts: string[]; isWarm: boolean }, W: number) =>
164  `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" font-family="${FONT}" font-variant-numeric="tabular-nums">
165<style>
166.t{fill:#1f1f1f}.m{fill:#8a8a8a}.k{fill:#e4e4e2}.tk{fill:#c4c4c0}.mk{fill:#1f1f1f;opacity:.55}.hot{fill:${RED}}
167@media (prefers-color-scheme: dark){.t{fill:#ececec}.m{fill:#9a9a9a}.k{fill:#2c2c2c}.tk{fill:#4a4a4a}.mk{fill:#ececec}}
168${isWarm ? `.t0,.t1,.t2,.t3{animation:tw 2.6s ease-in-out infinite}
169.t1{animation-duration:3.1s;animation-delay:-.7s}.t2{animation-duration:2.2s;animation-delay:-1.3s}.t3{animation-duration:3.6s;animation-delay:-.4s}
170@keyframes tw{0%,100%{opacity:1}50%{opacity:.45}}
171@media (prefers-reduced-motion: reduce){.t0,.t1,.t2,.t3{animation:none}}` : ''}
172</style>
173${parts.join('\n')}
174</svg>`
175
176// A hairline that sets this band apart from the mod bands drawn beneath it.
177// 9px tall with the line centred: a 1px image scaled to the slot rounds away.
178const dividerSvg = (w: number) =>
179  `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="9" viewBox="0 0 ${w} 9" preserveAspectRatio="none"><style>rect{fill:#00000026}@media (prefers-color-scheme: dark){rect{fill:#ffffff38}}</style><rect y="4" width="${w}" height="1"/></svg>`
180
181// ---------------------------------------------------------------------------
182
183// Collapsed or not, remembered across sessions.
184async function setCollapsed($: $, isCollapsed: boolean) {
185  await $.state.set(COLLAPSED, isCollapsed)
186  await $.store.set('collapsed', isCollapsed)
187}
188
189async function compact($: $) {
190  try {
191    const { skip } = await $.session.compact()
192    if (skip) return $.ui.toast('cache-meter: compaction was skipped')
193    // Our own session.compact hook is skipped for our own call; clear here.
194    await setReading($, null)
195  } catch (err) {
196    $.ui.toast(`cache-meter: cannot compact now (${err instanceof Error ? err.message : String(err)})`)
197  }
198}
199
200export const register: Register = (on, options) => {
201  const ttlMs = TTL_MS[(options.cacheTtl as keyof typeof TTL_MS) ?? '1h'] ?? TTL_MS['1h']
202  // Keepwarm and the cold-send guard work on this state; the band below reads it.
203  const s = freshState()
204  keepwarm(on, s)
205
206  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
207    const { value: m } = await $.state.get(READING)
208    const now = await $.clock.now()
209    const kw = kwOf(s, now)
210    // The keepwarm row comes with the meter, or alone while a window is armed or stopped before the first reading.
211    if ((!m && kw.mode === 'off') || e.props.hasSurvey) return next(e)
212    await $.state.get(TICK)
213    const { value: isCollapsed = false } = await $.state.get(COLLAPSED)
214
215    const ui = $.ui.resolve(e)
216    const { Box, Button, Text } = ui
217    const left = m ? m.at + ttlMs - now : 0
218    const isWarm = left > 0
219    const countdown = isWarm ? `${minutes(left)}m` : 'cold'
220    // Another mod's band (relay's buttons) rides along beneath the meter; the engine's own band is empty.
221    const drawn = await next(e)
222    const below = drawn.type !== 'engine' ? drawn : null
223    const isDesktop = e.surface !== 'terminal' && 'Svg' in ui
224    const cols = e.props.bodyColumns || 100
225    // savvy-progress's row width: about 8 CSS px per column, less the slot's padding.
226    const dividerW = Math.max(180, Math.min(1600, cols * 8 - 96))
227
228    const divider = isDesktop
229      ? <ui.Svg source={dividerSvg(dividerW)} alt="separator" width={dividerW} height={9} />
230      : <Text dimColor>{'─'.repeat(Math.max(8, cols - 2))}</Text>
231    // An accordion: the header line folds and unfolds the rows, and the whole band lights while the pointer is on it.
232    const summary = [m && `cache ${countdown}`, m && `context ${m.percent}%`, `keepwarm ${kw.mode === 'on' ? kw.pill : kw.mode}`]
233    const header = (
234      <Button
235        key="toggle"
236        plain
237        dimColor
238        hover={{ dimColor: false, bold: true }}
239        label={`${isCollapsed ? '▸' : '▾'} cache-meter · ${summary.filter(Boolean).join(' · ')}`}
240        onPress={() => void setCollapsed($, !isCollapsed)}
241      />
242    )
243    const withBelow = (rows?: RenderChildren) => (
244      <Box flexDirection="column" gap={isDesktop ? 'sm' : 0} paddingTop={isDesktop ? 'xs' : 0}>
245        <Box key="band" flexDirection="column" gap={isDesktop ? 'xs' : 0} paddingX={isDesktop ? 'xs' : 0} hover={{ backgroundColor: '#8080801a' }}>
246          {header}
247          {rows}
248        </Box>
249        {below && divider}
250        {below}
251      </Box>
252    )
253
254    if (isCollapsed) return withBelow()
255
256    // A button with a hint card, hidden at rest and shown while the pointer is over the button's keyed Box.
257    // The card opens onto the other row, so the band's edge never clips it.
258    const tipped = (key: string, tip: string, isAbove: boolean, button: RenderChildren) => (
259      <Box key={`${key}-tip`} position="relative">
260        {button}
261        <Box
262          position="absolute"
263          right={0}
264          {...(isAbove ? { bottom: 1 } : { top: 1 })}
265          display="none"
266          hover={{ display: 'flex' }}
267          backgroundColor="#3a3a38"
268          borderStyle="round"
269          borderColor="#5c5c58"
270          paddingX={1}
271        >
272          <Text color="#ffffff">{tip}</Text>
273        </Box>
274      </Box>
275    )
276    const compactButton = tipped(
277      'compact',
278      'Summarise the chat now to free context; the next send re-caches it',
279      false,
280      <Button key="compact" label="Compact" variant="secondary" onPress={() => void compact($)} />,
281    )
282    // Under the meter the card opens upward; alone, the keepwarm row has nothing above it.
283    const kwButton = kw.mode === 'on'
284      ? tipped('kw', 'Stop the pings; the cache then expires an hour after your last turn', Boolean(m),
285        <Button key="kw" label="Stop" variant="secondary" onPress={() => void stop($, s, null, true)} />)
286      : tipped('kw', 'Ping the cache after 50 idle minutes, for 6 hours, so it never goes cold', Boolean(m),
287        <Button key="kw" label="Keep warm" variant="primary" onPress={() => void startWindow($, s, DEFAULT_WINDOW_MS, PING_AFTER_MS)} />)
288    const kwAlt = `keepwarm ${kw.pill}${kw.rewrite ? `, ${kw.rewrite.value} ${kw.rewrite.word}` : ''}${kw.detail ? `, ${kw.detail}` : ''}`
289
290    if (isDesktop) {
291      // Each bar gets an even share of what the labels and buttons leave, within bounds.
292      const barW = Math.max(48, Math.min(200, Math.floor((cols * 8 - 520) / 2)))
293      const meter = m && rowSvg({ m, isWarm, countdown, barW })
294      const warmRow = kwSvg(kw)
295      const W = Math.max(meter?.width ?? 0, warmRow.width)
296      const alt = m && `cache ${countdown}, ${m.hitPercent}% hit, context ${m.percent}%${m.autoCompactPercent !== null ? ` (auto-compact ${m.autoCompactPercent}%)` : ''}`
297      return withBelow([
298        meter && alt && (
299          <Box key="meter" flexDirection="row" alignItems="center" gap={1}>
300            <ui.Svg source={svgOf(meter, W)} alt={alt} width={W} height={H} />
301            {compactButton}
302          </Box>
303        ),
304        <Box key="keepwarm" flexDirection="row" alignItems="center" gap={1}>
305          <ui.Svg source={svgOf(warmRow, W)} alt={kwAlt} width={W} height={H} />
306          {kwButton}
307        </Box>,
308      ])
309    }
310
311    const kwTone = kw.mode === 'stopped' ? 'warning' : kw.mode === 'on' && !kw.isCold ? 'success' : 'inactive'
312    const warmRow = (
313      <Box key="keepwarm" gap="sm" alignItems="center">
314        <Text tabular>
315          <Text color={kwTone}>● </Text>
316          <Text dimColor>keepwarm </Text>
317          <Text color={kwTone} weight="medium">{kw.pill}</Text>
318        </Text>
319        {kw.rewrite && (
320          <Text tabular>
321            <Text color={kw.isCold ? 'error' : undefined} weight="semibold">{kw.rewrite.value}</Text>
322            <Text dimColor> {kw.rewrite.word}</Text>
323          </Text>
324        )}
325        {kw.rewrite && kw.detail && <Text dimColor>│</Text>}
326        {kw.detail && <Text dimColor>{clip(kw.detail, 72)}</Text>}
327        {kwButton}
328      </Box>
329    )
330    if (!m) return withBelow(warmRow)
331
332    const [hit, miss] = bar(m.hitPercent)
333    const ctx = level(m.percent)
334    return withBelow([
335      <Box key="meter" gap="sm" alignItems="center">
336        <Text tabular>
337          <Text color={isWarm ? 'success' : 'inactive'}>● </Text>
338          <Text dimColor>cache </Text>
339          <Text color={isWarm ? 'success' : 'inactive'} weight="medium">
340            {countdown}
341          </Text>
342          <Text> </Text>
343          <Text color="success">{hit}</Text>
344          <Text color="inactive">{miss}</Text>
345          <Text weight="semibold"> {m.hitPercent}%</Text>
346          <Text dimColor> hit</Text>
347        </Text>
348        <Text dimColor>│</Text>
349        <Text tabular>
350          <Text color={ctx}>{glyph(m.percent)} </Text>
351          <Text dimColor>context </Text>
352          <Text color={ctx} weight="semibold">
353            {m.percent}%
354          </Text>
355          {m.autoCompactPercent !== null && <Text dimColor> (auto-compact {m.autoCompactPercent}%)</Text>}
356        </Text>
357        {compactButton}
358      </Box>,
359      warmRow,
360    ])
361  })
362}
363
hooks/keepwarm.ts 643 lines
1// Keepwarm and the cold-send guard, from karanb192/cache-tax 2.3.0 (MIT, see LICENSE.cache-tax).
2// Its own band and cube icon are gone: register.tsx draws the keepwarm row under the meter.
3import type { EngineInterface, On } from 'claude-code'
4
5import { meterCompact, meterStart, meterStep } from './meter'
6
7const TTL_MS = 60 * 60 * 1000
8export const PING_AFTER_MS = 50 * 60 * 1000
9const MIN_PING_MS = 60 * 1000
10const MAX_RETRIES = 3
11const AUTO_WARM_MS = 3 * 60 * 60 * 1000
12export const DEFAULT_WINDOW_MS = 6 * 60 * 60 * 1000
13const BIG_TOKENS = 50000
14const PING_PROMPT = 'Reply with the single word: warm'
15const KEY_DEADLINE = 'deadline'
16const KEY_EVERY = 'every'
17const KEY_GUARD = 'guard'
18const KEY_ALWAYS = 'always'
19
20// Prompts no person sent, so nobody could send them again after a refusal. Every
21// other origin, including sdk, unclassified and the owner's own Slack or channel
22// messages, may carry a person's words and keeps the guard.
23const UNATTENDED = new Set(['task-notification', 'scheduled-trigger', 'peer', 'peer-send-message', 'projects-relay', 'coordinator', 'observer', 'observer-activity'])
24
25const LONG_PROMPT_TOKENS = 100000
26
27// $ per million tokens, [cache read, 1h cache write, output], list prices October 2026.
28// More specific families first: a model id takes the first row it matches.
29const PRICES: Array<[string | RegExp, number, number, number]> = [
30  ['fable-5-1', 0.25, 20, 50],
31  ['mythos-5-1', 0.25, 20, 50],
32  ['fable-5', 1, 20, 50],
33  ['mythos-5', 1, 20, 50],
34  ['opus-5-5', 0.2, 8, 20],
35  ['opus-5', 0.5, 10, 25],
36  // Opus 4 and 4.1 in every spelling (claude-opus-4-1-20250805, claude-opus-4@20250514, the -0 and -1 aliases), never Opus 4.5 and later.
37  [/opus-4(?:-[01])?(?:$|[^-\d]|-20\d{6})/, 1.5, 30, 75],
38  ['opus-4', 0.5, 10, 25],
39  ['sonnet-5-5', 0.1, 4, 10],
40  ['sonnet-5', 0.2, 4, 10],
41  ['sonnet', 0.3, 6, 15],
42  ['haiku-5-5', 0.01, 0.2, 0.5],
43  ['3-5-haiku', 0.08, 1.6, 4],
44  ['haiku-3-5', 0.08, 1.6, 4],
45  ['haiku', 0.1, 2, 5],
46]
47
48// A request whose prompt, cache reads and writes included, is over 100k tokens pays these instead.
49const LONG_PRICES: Array<[string, number, number, number]> = [
50  ['haiku-5-5', 0.05, 1, 2.5],
51]
52
53type PingRecord = { at: number; read: number; write: number; usd: number | null; warm: boolean }
54type Miss = { at: number; tokens: number; usd: number | null }
55type GuardMode = 'refuse' | 'warn'
56
57export type State = {
58  hasBand: boolean
59  sid: string
60  deadline: number
61  every: number
62  always: boolean
63  lastRequestAt: number
64  lastModel: string | null
65  ctx: number
66  compacted: boolean
67  guard: GuardMode
68  ackedAt: number
69  coldWritePending: boolean
70  misses: Miss[]
71  pending: { cancel: () => void } | null
72  last: PingRecord | null
73  stopped: string | null
74  waitForTurn: boolean
75  retries: number
76  retryReason: string
77  gen: number
78  tick: number
79  offs: number
80  turnOffs: number | null
81  inFlight: boolean
82  stepWrites: { usd: number; priced: boolean } | null
83}
84
85function priceOf(model: string | null, promptTokens: number): [number, number, number] | null {
86  const m = (model ?? '').toLowerCase().replace(/[\s.]+/g, '-')
87  if (promptTokens > LONG_PROMPT_TOKENS) {
88    for (const [family, read, write, output] of LONG_PRICES) if (m.includes(family)) return [read, write, output]
89  }
90  for (const [family, read, write, output] of PRICES) {
91    if (typeof family === 'string' ? m.includes(family) : family.test(m)) return [read, write, output]
92  }
93  return null
94}
95
96export function parseDuration(text: string): number | null {
97  const m = /^(?:(\d+)h)?(?:(\d+)m)?$/.exec(text.trim())
98  if (!m || (m[1] === undefined && m[2] === undefined)) return null
99  return (Number(m[1] ?? 0) * 60 + Number(m[2] ?? 0)) * 60 * 1000
100}
101
102export function fmtDuration(ms: number): string {
103  const total = Math.max(0, Math.round(ms / 60000))
104  const h = Math.floor(total / 60)
105  const m = total % 60
106  if (h >= 48) return `${Math.floor(h / 24)}d ${h % 24}h`
107  return h > 0 ? `${h}h${String(m).padStart(2, '0')}m` : `${m}m`
108}
109
110export function fmtUsd(usd: number | null): string {
111  return usd == null ? 'n/a' : '$' + (usd >= 100 ? usd.toFixed(0) : usd.toFixed(2))
112}
113
114export function fmtTok(n: number): string {
115  return n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1000 ? Math.round(n / 1000) + 'k' : String(n)
116}
117
118export function coldUsd(s: State): number | null {
119  const price = priceOf(s.lastModel, s.ctx)
120  return price ? s.ctx * price[1] / 1e6 : null
121}
122
123function warmUsd(s: State): number | null {
124  const price = priceOf(s.lastModel, s.ctx)
125  return price ? s.ctx * price[0] / 1e6 : null
126}
127
128/** Everything a fork bills: the cache read, any cache write, uncached input at the base rate (half the 1h write rate), and the output. */
129function pingUsd(u: { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }, price: [number, number, number]): number {
130  return (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
131}
132
133/** The read-only upper bound: pings at the cache-read rate that cost as much as one cold write of the same context. */
134function breakEvenPings(s: State): number | null {
135  const price = priceOf(s.lastModel, s.ctx)
136  if (!price || s.ctx <= 0) return null
137  return Math.floor(price[1] / price[0])
138}
139
140export function isCold(s: State, now: number): boolean {
141  return s.lastRequestAt > 0 && !s.compacted && now - s.lastRequestAt >= TTL_MS
142}
143
144function guardText(s: State, now: number): string {
145  const price = priceOf(s.lastModel, s.ctx)
146  const rate = price ? `$${price[1]}/MTok` : 'the cache-write rate'
147  const warm = warmUsd(s)
148  return `the prompt cache went cold ${fmtDuration(now - s.lastRequestAt - TTL_MS)} ago. Sending this re-writes ` +
149    `up to ${s.ctx.toLocaleString('en-US')} tokens at ${rate} = ${fmtUsd(coldUsd(s))}` +
150    (warm == null ? '' : ` (a warm turn would have cost ${fmtUsd(warm)})`) + '.'
151}
152
153export type ResumeFields = {
154  source: string
155  model?: string
156  context_tokens?: number
157  seconds_since_last_response?: number
158  prompt_cache_likely_expired?: boolean
159  estimated_cache_write_usd?: number
160}
161
162/** /clear starts a new conversation in the same process; nothing priced before it still exists. */
163export function resetForClear(s: State) {
164  s.ctx = 0
165  s.lastRequestAt = 0
166  s.compacted = false
167  s.ackedAt = 0
168  s.coldWritePending = false
169  s.misses = []
170  s.waitForTurn = false
171  s.stepWrites = null
172  outdate(s)
173  disarm(s)
174}
175
176/** Applies a resumed session's fields to the state; returns the line to log, if any. */
177export function seedFromResume(s: State, e: ResumeFields, now: number): string | null {
178  if (e.source !== 'resume' && e.source !== 'fork') return null
179  if (typeof e.context_tokens === 'number' && e.context_tokens > 0) s.ctx = e.context_tokens
180  if (typeof e.seconds_since_last_response === 'number') s.lastRequestAt = now - e.seconds_since_last_response * 1000
181  if (typeof e.model === 'string') s.lastModel = e.model
182  s.compacted = false
183  if (e.prompt_cache_likely_expired !== true || s.ctx < BIG_TOKENS) return null
184  const usd = typeof e.estimated_cache_write_usd === 'number' ? fmtUsd(e.estimated_cache_write_usd) : fmtUsd(coldUsd(s))
185  return `resuming cold. The first message re-writes ${s.ctx.toLocaleString('en-US')} tokens, about ${usd}. /clear and paste a summary if you only need the conclusions.`
186}
187
188/** What the armed window waits for next, such as "ping in 32m". */
189export function nextPing(s: State, now: number): string {
190  return !s.lastRequestAt ? 'waiting for the first turn'
191    : s.compacted ? 'waiting for the first turn after compaction'
192    : isCold(s, now) ? `cold now, first ping ${fmtDuration(s.every)} after the next turn`
193    : s.waitForTurn ? 'nothing to fork yet, first ping after the next turn'
194    : s.retries ? `API busy, ping retry ${s.retries} of ${MAX_RETRIES}`
195    : `ping in ${fmtDuration(s.lastRequestAt + s.every - now)}`
196}
197
198export function statusText(s: State, now: number): string | undefined {
199  if (s.stopped) return `keepwarm stopped: ${s.stopped}`
200  if (!s.deadline) return undefined
201  const pingText = s.last ? ` · last ping read ${fmtTok(s.last.read)} ${fmtUsd(s.last.usd)}` : ''
202  return `keepwarm ${fmtDuration(s.deadline - now)} left · ${nextPing(s, now)}${pingText}`
203}
204
205function updateStatus($: EngineInterface, s: State, now: number) {
206  if (s.hasBand) $.ui.invalidate('ui.render')
207  else $.ui.status(statusText(s, now))
208}
209
210/** Cancels the timer. Every new timer is set right after this, so the tick also says the schedule changed. */
211function disarm(s: State) {
212  if (s.pending) s.pending.cancel()
213  s.pending = null
214  s.tick++
215}
216
217/** Outdates any ping in flight: /clear, a resume, compaction or stop replaced the state it was sent for. Re-arming or extending the window does not, so a ping out at that moment still counts; a main request outdates it through the request clock. */
218function outdate(s: State) {
219  s.gen++
220}
221
222// The window and its ping period belong to the session that armed them, so a
223// second session, or one resumed from another transcript, never inherits them
224// and cannot turn them off. The always switch and the guard mode stay global.
225function deadlineKey(s: State): string {
226  return `${KEY_DEADLINE}:${s.sid}`
227}
228
229function everyKey(s: State): string {
230  return `${KEY_EVERY}:${s.sid}`
231}
232
233/** Clears this session's own dead window and the bare keys a store written before 2.1.1 still holds. Other sessions' keys are never touched: a read followed by a delete cannot be made atomic against their renewal. */
234async function prune($: EngineInterface, s: State, now: number) {
235  for (const key of [KEY_DEADLINE, deadlineKey(s)]) {
236    const deadline = await $.store.get(key)
237    if (deadline === undefined) continue
238    if (typeof deadline === 'number' && deadline > now) continue
239    await $.store.delete(key)
240    await $.store.delete(KEY_EVERY + key.slice(KEY_DEADLINE.length))
241  }
242}
243
244export async function stop($: EngineInterface, s: State, why: string | null, forgetAlways = false) {
245  // Set before any await, so a window being opened at the same moment sees the off and does not write itself back.
246  if (forgetAlways) {
247    s.always = false
248    s.offs++
249  }
250  s.deadline = 0
251  s.every = PING_AFTER_MS
252  s.stopped = why
253  s.retries = 0
254  outdate(s)
255  disarm(s)
256  await $.store.delete(deadlineKey(s))
257  await $.store.delete(everyKey(s))
258  if (forgetAlways) await $.store.delete(KEY_ALWAYS)
259  updateStatus($, s, await $.clock.now())
260}
261
262async function arm($: EngineInterface, s: State) {
263  disarm(s)
264  s.retries = 0
265  if (!s.deadline) return
266  const now = await $.clock.now()
267  // A timer set while the clock was read, such as a retry, is replaced here, never left running beside this one;
268  // from this line to the assignment below nothing awaits.
269  disarm(s)
270  s.retries = 0
271  if (now >= s.deadline) return stop($, s, null)
272  // A cold window still needs expiry cleanup, but must not send a model request.
273  if (s.lastRequestAt && !s.compacted && !isCold(s, now)) {
274    const untilCold = s.lastRequestAt + TTL_MS - now
275    // Waiting for a turn sends nothing, but wakes when the cache goes cold so the row says so.
276    if (s.waitForTurn) s.pending = $.clock.after(Math.min(s.deadline - now, untilCold), () => { void arm($, s) })
277    else {
278      const delay = Math.min(s.deadline - now, untilCold, Math.max(1000, s.lastRequestAt + s.every - now))
279      s.pending = $.clock.after(delay, () => { void ping($, s) })
280    }
281  } else {
282    s.pending = $.clock.after(s.deadline - now, () => { void arm($, s) })
283  }
284  updateStatus($, s, now)
285}
286
287async function ping($: EngineInterface, s: State) {
288  s.pending = null
289  if (!s.deadline) return
290  const tick = s.tick
291  const now = await $.clock.now()
292  // A timer set or cancelled while the clock was read (an extension, a retry, a turn) owns the window now;
293  // if that left no timer, a window still open is armed again rather than left without one.
294  if (s.tick !== tick) return s.pending || s.inFlight ? undefined : arm($, s)
295  // One fork at a time: the one already out re-arms when it settles. Checked after the await, and set
296  // below with no await in between, so two timers can never both send.
297  if (s.inFlight) return
298  if (now >= s.deadline) return arm($, s)
299  if (isCold(s, now)) return arm($, s)
300  if (s.compacted || s.waitForTurn || !s.lastRequestAt) return arm($, s)
301  // A request since this timer was set moved the clock; schedule from it.
302  if (now - s.lastRequestAt < s.every - 1000) return arm($, s)
303  // A host that slept past a retry's slot must not send it inside the last minute.
304  if (s.retries && now >= s.lastRequestAt + TTL_MS - MIN_PING_MS) return stop($, s, s.retryReason + afterRetries(s.retries))
305  const gen = s.gen
306  const sentAt = s.lastRequestAt
307  s.inFlight = true
308  const sent = await $.model.fork({ prompt: PING_PROMPT }).then(reply => ({ reply }), (err: unknown) => ({ err }))
309  const at = await $.clock.now()
310  s.inFlight = false
311  // Checked after the last await. A stop, /clear, resume or compaction, or a main request that moved the
312  // cache clock, replaced what this fork was sent for: its reply is dropped and the window armed afresh.
313  if (gen !== s.gen || s.lastRequestAt !== sentAt) return s.pending ? undefined : arm($, s)
314  if ('err' in sent) return stop($, s, `the ping failed, ${sent.err instanceof Error ? sent.err.message : String(sent.err)}`)
315  const reply = sent.reply
316  if (reply === null) return stop($, s, 'the engine did not send the ping, either the snapshot was cold or the API call failed')
317  if (reply.isAnswered === false) {
318    // A restarted process has no conversation to fork until its first turn; the window waits for one instead of ending.
319    if (reply.reason === 'nothing-to-fork') {
320      s.waitForTurn = true
321      return arm($, s)
322    }
323    const reason = reply.reason === 'api-error' ? `the API call failed${reply.status === null ? '' : ` (${reply.status})`}`
324      : reply.reason === 'aborted' ? 'the ping was interrupted'
325      : 'the ping returned no text'
326    // A busy or failing API is usually brief; retry while a ping can still land a minute before the cache goes cold.
327    if (reply.reason === 'api-error' && (reply.status === null || reply.status === 429 || reply.status >= 500)) {
328      const wait = MIN_PING_MS * 2 ** s.retries
329      if (s.retries < MAX_RETRIES && at + wait < Math.min(s.deadline, s.lastRequestAt + TTL_MS - MIN_PING_MS)) {
330        s.retries++
331        s.retryReason = reason
332        // Replaces any timer set while the fork was out, such as a window extension's, so only the retry fires.
333        disarm(s)
334        s.pending = $.clock.after(wait, () => { void ping($, s) })
335        updateStatus($, s, at)
336        return
337      }
338    }
339    return stop($, s, reason + afterRetries(s.retries))
340  }
341  const u = reply.usage
342  const price = priceOf(s.lastModel, u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens)
343  // 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.
344  const warm = u.cache_read_input_tokens > 0 && u.cache_creation_input_tokens < 0.1 * u.cache_read_input_tokens
345  const usd = price ? pingUsd(u, price) : null
346  s.last = { at: now, read: u.cache_read_input_tokens, write: u.cache_creation_input_tokens, usd, warm }
347  if (!warm) return stop($, s, `the ping read ${fmtTok(u.cache_read_input_tokens)} and wrote ${fmtTok(u.cache_creation_input_tokens)} tokens (${fmtUsd(usd)}), the cache was already gone`)
348  s.lastRequestAt = now
349  await arm($, s)
350}
351
352function afterRetries(n: number): string {
353  return n ? ` after ${n} ${n === 1 ? 'retry' : 'retries'}` : ''
354}
355
356/** The reply to an arming command; on a cold cache it says when the first ping can come. */
357/** How long keepwarm holds the cache after a paid cold write: the rolling window when always is on. */
358function holdMs(s: State): number {
359  return s.always ? DEFAULT_WINDOW_MS : AUTO_WARM_MS
360}
361
362function armedText(s: State, now: number, windowMs: number): string {
363  if (isCold(s, now)) return `keepwarm on for ${fmtDuration(windowMs)}. The cache is cold now, so the first ping comes ${fmtDuration(s.every)} after the next turn`
364  return `keepwarm on for ${fmtDuration(windowMs)}, a ping ${fmtDuration(s.every)} after each idle stretch keeps the cache read, not re-written`
365}
366
367// A /keepwarm off after `offs` was read wins: the window it cancelled is not written back. A caller that awaited
368// before deciding to open a window passes the count it read first.
369export async function startWindow($: EngineInterface, s: State, windowMs: number, every: number, offs = s.offs) {
370  if (s.offs !== offs) return
371  const now = await $.clock.now()
372  if (s.offs !== offs) return
373  const deadline = now + windowMs
374  s.every = every
375  s.deadline = deadline
376  s.stopped = null
377  if (every === PING_AFTER_MS) await $.store.delete(everyKey(s))
378  else await $.store.set(everyKey(s), every)
379  await $.store.set(deadlineKey(s), deadline)
380  if (s.offs !== offs) {
381    // Remove only what this call wrote; a window armed after the off is left alone.
382    if ((await $.store.get(deadlineKey(s))) === deadline) {
383      await $.store.delete(deadlineKey(s))
384      if (!s.deadline) await $.store.delete(everyKey(s))
385    }
386    return
387  }
388  await arm($, s)
389}
390
391function card(s: State, now: number): string {
392  const lines: string[] = []
393  lines.push(`${s.lastModel ?? 'model not seen yet'}`)
394  if (s.compacted) lines.push('state       reset by compaction, waiting for the first turn')
395  else if (!s.lastRequestAt) lines.push('state       no request yet this session')
396  else if (isCold(s, now)) lines.push(`state       COLD, last request ${fmtDuration(now - s.lastRequestAt)} ago`)
397  else lines.push(`state       warm, ${fmtDuration(s.lastRequestAt + TTL_MS - now)} left`)
398  lines.push(`context     ${s.ctx.toLocaleString('en-US')} tokens`)
399  lines.push(`cold cost   ${fmtUsd(coldUsd(s))} to re-write it (warm turn ${fmtUsd(warmUsd(s))})`)
400  const always = s.always ? ' (always)' : ''
401  const idle = s.always ? 'off until the next turn, which arms 6h00m (always)' : 'off (/keepwarm to arm it for 6h00m)'
402  lines.push(`keepwarm    ${s.deadline ? (statusText(s, now) ?? '').replace(/^keepwarm /, 'on, ') + always : s.stopped ? `stopped, ${s.stopped}${always}` : idle}`)
403  const pings = breakEvenPings(s)
404  if (pings != null) lines.push(`break-even  up to ${pings} pings at the read rate cost one cold write, about ${fmtDuration(pings * s.every)} of idle at one ping per ${fmtDuration(s.every)}`)
405  lines.push(`guard       ${s.guard === 'refuse' ? 'refuse once (/cache-tax guard warn to only show the price)' : 'warn only (/cache-tax guard refuse to be stopped once)'}`)
406  const paid = s.misses.reduce((a, m) => a + (m.usd ?? 0), 0)
407  lines.push(`session     ${s.misses.length} cold write${s.misses.length === 1 ? '' : 's'} paid, ${fmtUsd(paid)}`)
408  return lines.join('\n')
409}
410
411export function freshState(): State {
412  return {
413    hasBand: false, sid: '', deadline: 0, every: PING_AFTER_MS, always: false, lastRequestAt: 0, lastModel: null, ctx: 0, compacted: false,
414    guard: 'refuse', ackedAt: 0, coldWritePending: false, misses: [], pending: null, last: null, stopped: null,
415    waitForTurn: false, retries: 0, retryReason: '', gen: 0, tick: 0, offs: 0, turnOffs: null, inFlight: false, stepWrites: null,
416  }
417}
418
419/** Adds the keepwarm and guard hooks to `on`, working on `s`, which the caller's band reads. */
420export function keepwarm(on: On, s: State) {
421  on('session.start', async ($, e, next) => {
422    await meterStart($, e.surface)
423    const r = await next(e)
424    s.hasBand = e.surface === 'terminal' || e.surface === 'desktop'
425    if (s.hasBand) $.ui.status(undefined)
426    s.sid = await $.session.id()
427    const now = await $.clock.now()
428    await prune($, s, now)
429    const saved = await $.store.get(deadlineKey(s))
430    const savedEvery = await $.store.get(everyKey(s))
431    const savedGuard = await $.store.get(KEY_GUARD)
432    s.deadline = typeof saved === 'number' && saved > now ? saved : 0
433    s.every = typeof savedEvery === 'number' && savedEvery >= MIN_PING_MS && savedEvery < TTL_MS ? savedEvery : PING_AFTER_MS
434    s.guard = savedGuard === 'warn' ? 'warn' : 'refuse'
435    s.always = (await $.store.get(KEY_ALWAYS)) === true
436    // Always means a fresh default window every session, whatever the last one left behind.
437    if (s.always) await startWindow($, s, DEFAULT_WINDOW_MS, PING_AFTER_MS)
438    const usage = await $.session.usage()
439    if (usage.context.tokens) s.ctx = usage.context.tokens
440    await $.command.register({
441      name: 'keepwarm',
442      description: 'Keep the prompt cache warm: bare for 6h, a window such as 90m, always, off, or status (cache-tax)',
443      argumentHint: '[6h | always | off | status]',
444      immediate: true,
445    })
446    await $.command.register({
447      name: 'cache-tax',
448      description: 'Prompt cache state, cold price and this session\'s cold writes; guard warn|refuse (cache-tax, the Mod)',
449      argumentHint: '[status | guard warn | guard refuse]',
450      immediate: true,
451    })
452    // The hook form of cache-tax ships a /cache-tax:status skill; both installed means two guards.
453    const commands = await $.command.list()
454    if (commands.some(c => c.name === 'cache-tax:status')) {
455      $.ui.log('the hook form (cache-tax@claude-code-hooks) is also installed, so a cold send is warned about or refused twice. Uninstall it, or /cache-tax guard warn here.')
456    }
457    updateStatus($, s, now)
458    return r
459  })
460
461  // Resume fields seed the guard before any turn of the resumed session has run.
462  on('classic.SessionStart', async ($, e, next) => {
463    const r = await next(e)
464    // A resumed or cleared conversation is not the one a ping in flight was sent for.
465    outdate(s)
466    if (e.source === 'clear') {
467      await stop($, s, null)
468      s.stopped = null
469      resetForClear(s)
470      s.sid = await $.session.id()
471      // No session.start fires after /clear, so this is where always arms the new conversation.
472      if (s.always) await startWindow($, s, DEFAULT_WINDOW_MS, PING_AFTER_MS)
473      // A window armed while this handler awaited lost its timer to resetForClear; arm it again.
474      else if (s.deadline) await arm($, s)
475      else updateStatus($, s, await $.clock.now())
476      return r
477    }
478    const line = seedFromResume(s, e, await $.clock.now())
479    // The resume payload may omit the model; without it the guard cannot price the cold write.
480    if (!s.lastModel) s.lastModel = await $.session.model()
481    if (line) $.ui.log(line)
482    // The seeded clock decides whether a restored or always window pings before the first turn: never when it is cold.
483    await arm($, s)
484    return r
485  })
486
487  on('command.run', { command: 'keepwarm' }, async ($, e) => {
488    const words = String(e.args ?? '').trim().split(/\s+/).filter(Boolean)
489    const now = await $.clock.now()
490    if (words[0] === 'off') {
491      const wasAlways = s.always
492      await stop($, s, null, true)
493      return { text: wasAlways ? 'keepwarm is off, and always is off for every session from its next turn' : 'keepwarm is off' }
494    }
495    if (words[0] === 'always') {
496      s.always = true
497      await $.store.set(KEY_ALWAYS, true)
498      await startWindow($, s, DEFAULT_WINDOW_MS, PING_AFTER_MS)
499      const cold = isCold(s, now) ? `. The cache is cold now, so the first ping comes ${fmtDuration(s.every)} after the next turn` : ''
500      return { text: `keepwarm always on: every session stays warm until ${fmtDuration(DEFAULT_WINDOW_MS)} after its last turn; /keepwarm off turns it off for good${cold}` }
501    }
502    if (!words.length) {
503      await startWindow($, s, DEFAULT_WINDOW_MS, PING_AFTER_MS)
504      return { text: armedText(s, now, DEFAULT_WINDOW_MS) }
505    }
506    if (words[0] !== 'status') {
507      const window = parseDuration(words[0] ?? '')
508      if (!window) return { text: 'keepwarm takes a window such as 6h or 90m, or always, off, or status' }
509      // "every 2m" is a testing knob and lasts only for the window it was given with.
510      let every = PING_AFTER_MS
511      if (words[1] === 'every') {
512        const period = parseDuration(words[2] ?? '')
513        // A period of the cache's whole hour or more would fire only once the cache is already cold.
514        if (period == null || period < MIN_PING_MS || period >= TTL_MS) return { text: 'every takes a period from 1m to 59m' }
515        every = period
516      }
517      await startWindow($, s, window, every)
518      const rolls = s.always && (window < DEFAULT_WINDOW_MS || every !== PING_AFTER_MS)
519      return { text: armedText(s, now, window) + (rolls ? `. Always is on, so your next turn makes it at least ${fmtDuration(DEFAULT_WINDOW_MS)} at one ping per ${fmtDuration(PING_AFTER_MS)}` : '') }
520    }
521    return { text: statusText(s, now) ?? 'keepwarm is off' }
522  })
523
524  on('command.run', { command: 'cache-tax' }, async ($, e) => {
525    const words = String(e.args ?? '').trim().split(/\s+/).filter(Boolean)
526    const now = await $.clock.now()
527    if (words[0] === 'guard') {
528      if (words[1] !== 'warn' && words[1] !== 'refuse') return { text: '/cache-tax guard takes warn or refuse' }
529      s.guard = words[1]
530      await $.store.set(KEY_GUARD, s.guard)
531      return { text: s.guard === 'refuse' ? 'guard set to refuse once: a cold send is dropped with its price, the resend goes through' : 'guard set to warn: a cold send goes through with its price shown' }
532    }
533    return { text: card(s, now) }
534  })
535
536  // The message that pays. Only its first character is read.
537  on('prompt.submit', async ($, e, next) => {
538    if (e.origin.kind === 'plugin') return next(e)
539    if (typeof e.text !== 'string' || e.text.trimStart().startsWith('/')) return next(e)
540    const now = await $.clock.now()
541    if (!isCold(s, now) || s.ctx < BIG_TOKENS) return next(e)
542    // A refused prompt that no person sent would be lost: nobody is there to send it again.
543    const unattended = UNATTENDED.has(e.origin.kind)
544    if (s.guard === 'warn' || unattended) {
545      $.ui.log(`${guardText(s, now)} Sending anyway${unattended ? `, since this ${e.origin.kind} prompt cannot be sent again` : ''}; keepwarm will hold the cache for ${fmtDuration(holdMs(s))} once it lands.`)
546      s.coldWritePending = true
547      return next(e)
548    }
549    if (s.ackedAt === s.lastRequestAt) {
550      s.ackedAt = 0
551      s.coldWritePending = true
552      return next(e)
553    }
554    s.ackedAt = s.lastRequestAt
555    return { drop: `cache-tax: ${guardText(s, now)} Send it again to pay it, and keepwarm will then hold the cache for ${fmtDuration(holdMs(s))}. Or /clear and start from a note.` }
556  })
557
558  on('turn.step', async function* ($, e, next) {
559    if (!e.agentId) {
560      // The off count when the turn's first request went out: an off after it wins over what the turn opens.
561      if (e.index === 0) s.turnOffs = s.offs
562      s.lastRequestAt = await $.clock.now()
563    }
564    const r = yield* next(e)
565    // Each request's write is priced at its own prompt length's tier (Haiku 5.5 changes price at 100k), not the turn's sum.
566    const u = r.usage
567    if (!e.agentId && u) {
568      const price = priceOf(u.model || e.model, u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens)
569      const was = s.stepWrites ?? { usd: 0, priced: true }
570      s.stepWrites = { usd: was.usd + (price ? u.cache_creation_input_tokens * price[1] / 1e6 : 0), priced: was.priced && price != null }
571    }
572    await meterStep($, e, r)
573    return r
574  })
575
576  on('turn.complete', async ($, e, next) => {
577    const r = await next(e)
578    if (e.agentId) return r
579    // An off at any point in this turn wins over every window the turn would open; a host that raised no
580    // step falls back to the count at completion.
581    const offs = s.turnOffs ?? s.offs
582    s.turnOffs = null
583    const now = await $.clock.now()
584    // A sleeping host may deliver this turn before the expired window's timer.
585    if (s.deadline && now >= s.deadline) await stop($, s, null)
586    // turn.step stamps the exact request time; when no step of this turn did, the turn's end is the floor.
587    // A turn aborted before it sent anything touched no cache, so it leaves the clock alone.
588    if ((e.usage || !e.isAborted) && now - s.lastRequestAt > e.durationMs) s.lastRequestAt = now
589    s.compacted = false
590    s.waitForTurn = false
591    s.ackedAt = 0
592    // Always covers any break up to six hours after a turn that reached the cache (a turn that failed before any
593    // response touched nothing, and its cache may be cold): a window of at least six hours at the default period,
594    // which brings back a stopped window and replaces a shorter one or a testing period. Another session's
595    // /keepwarm off or /keepwarm always changes the shared switch, so every such turn reads it.
596    if (e.usage) {
597      const shared = (await $.store.get(KEY_ALWAYS)) === true
598      if (s.offs === offs) s.always = shared
599      if (s.always) await startWindow($, s, Math.max(DEFAULT_WINDOW_MS, s.deadline - now), PING_AFTER_MS, offs)
600    }
601    const u = e.usage
602    if (u) {
603      if (u.model) s.lastModel = u.model
604      const prev = s.ctx
605      // A turn's usage is its responses summed, so a ten-step turn reports ten
606      // reads of the context. The live window is the engine's figure; the sum
607      // is only the fallback for a host that reports no tokens.
608      const write = u.cache_creation_input_tokens
609      const live = (await $.session.usage()).context.tokens
610      s.ctx = live && live > 0 ? live : u.input_tokens + u.cache_read_input_tokens + write
611      const full = prev > 20000 && write >= 0.5 * prev
612      if (full || s.coldWritePending) {
613        // Priced per request when the steps reported usage; otherwise at the tier of the context the comeback re-sent.
614        const price = priceOf(s.lastModel, prev || s.ctx)
615        const usd = s.stepWrites?.priced ? s.stepWrites.usd : price ? write * price[1] / 1e6 : null
616        s.misses.push({ at: now, tokens: write, usd })
617        const extend = s.deadline < now + AUTO_WARM_MS && s.offs === offs
618        if (extend) await startWindow($, s, AUTO_WARM_MS, s.every, offs)
619        $.ui.log(`cold write of ${fmtTok(write)} tokens paid (${fmtUsd(usd)}).` +
620          (extend ? ` Keeping the cache warm for ${fmtDuration(AUTO_WARM_MS)} so it is not paid again today; /keepwarm off to stop.` : ''))
621      }
622    }
623    s.coldWritePending = false
624    s.stepWrites = null
625    await arm($, s)
626    return r
627  })
628
629  on('session.compact', async ($, e, next) => {
630    const r = await next(e)
631    await meterCompact($)
632    if (!e.agentId) {
633      s.compacted = true
634      s.ctx = 0
635      s.ackedAt = 0
636      outdate(s)
637      disarm(s)
638      await arm($, s)
639    }
640    return r
641  })
642}
643
hooks/meter.ts 64 lines
1// The meter's half of the events it shares with keepwarm: a mod hooks each event once,
2// so keepwarm.ts calls these from its own session.start, turn.step and session.compact.
3import type { EngineInterface, ModelUsage, TurnStepInput, TurnStepResult } from 'claude-code'
4
5import type { Reading } from '../types'
6
7const READING = { plugin: 'cache-meter', key: 'reading' } as const
8const TICK = { plugin: 'cache-meter', key: 'tick' } as const
9const COLLAPSED = { plugin: 'cache-meter', key: 'collapsed' } as const
10
11type $ = EngineInterface
12
13const inputOf = (u: ModelUsage) => u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
14const contextOf = (u: ModelUsage) => inputOf(u) + u.output_tokens
15
16// The engine's window and auto-compact figures; a summary breakdown estimates and costs no API call.
17async function windowOf($: $) {
18  try {
19    const { context } = await $.session.usage({ breakdown: 'summary' })
20    const window = context.window || 200_000
21    const at = context.breakdown?.autoCompactThreshold
22    return { window, autoCompactPercent: at ? Math.round((at / window) * 100) : null }
23  } catch {
24    return { window: 200_000, autoCompactPercent: null }
25  }
26}
27
28export async function setReading($: $, value: Reading | null) {
29  await $.state.set(READING, value)
30}
31
32// Bumped every half minute so the countdown redraws.
33async function bumpTick($: $) {
34  const { value = 0 } = await $.state.get(TICK)
35  await $.state.set(TICK, value + 1)
36}
37
38export async function meterStart($: $, surface: string | null) {
39  // A headless session draws no band, so nothing needs the countdown redrawn.
40  if (surface) $.clock.every(30_000, () => void bumpTick($))
41  await $.state.set(COLLAPSED, (await $.store.get('collapsed')) === true)
42}
43
44export async function meterStep($: $, e: TurnStepInput, r: TurnStepResult) {
45  if (e.agentId || !r.usage) return
46  const u = r.usage
47  const input = inputOf(u)
48  const { window, autoCompactPercent } = await windowOf($)
49  const tokens = contextOf(u)
50  await setReading($, {
51    at: await $.clock.now(),
52    hitPercent: input ? Math.round((u.cache_read_input_tokens / input) * 100) : 0,
53    tokens,
54    window,
55    percent: Math.round((tokens / window) * 100),
56    autoCompactPercent,
57  })
58}
59
60// The window is empty until the next response; drop the stale figures.
61export async function meterCompact($: $) {
62  await setReading($, null)
63}
64
types/index.d.ts 28 lines
1/** The last main-thread response, as the meter draws it. */
2export type Reading = {
3  /** When the response landed ($.clock.now() ms); the cache TTL counts from here. */
4  at: number
5  /** Share of the request's input the prompt cache served, whole percent. */
6  hitPercent: number
7  /** Tokens the next request re-sends. */
8  tokens: number
9  /** The model's context window. */
10  window: number
11  /** tokens over window, whole percent. */
12  percent: number
13  /** Where auto-compaction runs, as a percent of the window; null when off. */
14  autoCompactPercent: number | null
15}
16
17declare module 'claude-code' {
18  interface PluginState {
19    'cache-meter': {
20      reading: Reading | null
21      /** A clock tick, bumped every half minute so the countdown redraws. */
22      tick: number
23      /** The band is folded to a one-line summary; mirrored to $.store across sessions. */
24      collapsed: boolean
25    }
26  }
27}
28