Keeps the prompt cache warm while you step away: a short poke before the cache expires, so the next turn reads the cache instead of writing it again. A row…

A Claude Code mod that keeps the prompt cache warm while you step away, and wakes Claude up when the usage limit resets.
Claude Code caches the conversation for 1 hour on a Claude subscription, 5 minutes on an API key. Come back after it expires and the next turn writes the whole context to the cache again. With caffeine on, a short poke goes out before the cache expires, so your next turn reads it instead.
≋≋≋
c[_] 98°F caffeine on · poke at 14:32 (in 40m) · until you turn it off (or 8h idle) t: turn off e: message
The cup is the cache: 100°F and steaming right after a request, cooling to 40°F (red to blue) as the cache runs out. It shows while caffeine is off too, so you can watch the cache go cold.
Near the usage limit a second row offers the wake:
5h limit 96% · resets 14:10 (in 2h 05m) u: wake Claude at 14:12 n: not now
From the Anthropic plugin directory, no marketplace to add:
/plugin install cache-caffeine@anthropic-plugin-directory
Needs Claude Code 2.1.287 or newer (mods on by default).
The row above the prompt has the switch (t), the message editor (e), and how long caffeine stays on: until you turn it off, or the end of a warm or until. The wake row books the wake (u) or puts it off (n). Focus the row with ctrl+x tab or a click.
| Command | What it does |
|---|---|
/caffeine | on (until you turn it off) or off, for this session |
/caffeine warm 2h | keep the cache warm for 2 hours, then off (alone: 1 hour) |
/caffeine until 18:00 | on, then off at 18:00 |
/caffeine poke | poke now |
/caffeine message <text> | what the poke says (reset for the default, "poke, just say okay") |
/caffeine every 10m | poke this long after the last request (auto: 80% of the cache's life, 48m on 1h, 4m on 5m) |
/caffeine ttl 1h | pin the cache TTL (auto to detect it again) |
/caffeine idle 8h | turn off after this long without a turn of your own |
/caffeine forever | no end this time, once you confirm: warm until you turn it off, and the next turn-on has the idle stop again (idle off does the same) |
/caffeine band off | no row; shows in the status line instead, for when other mods use the band |
/caffeine auto 100k | turn on by itself once the context passes 100k tokens (off for never, the default) |
/caffeine cost | a poke's cost against one cache rewrite, and how long caffeine pays off for |
/caffeine wake | wake Claude just after the usage limit resets |
/caffeine 1 min | wake Claude at a time: in 20 minutes, 2 hours, 14:30, at 3pm, noon (wake 1 min works too); wake off cancels |
/caffeine 20 min check the build | a wake that tells Claude exactly that |
/caffeine wake prompt <text> | what Claude is told on every wake (wake prompt default restores the defaults) |
/caffeine wake auto | book the wake by itself whenever the limit hits |
/caffeine status | what it is doing and whether the last poke found the cache warm |
/caffeine 20 min check the build), else your wake prompt, else the default ("The usage limit has reset. Pick up where you left off." after a limit reset, "Time's up. Pick up where you left off." at a set time), with [caffeine] in front. Nothing from the conversation, a file or anywhere else goes into either./clear empties the cache, so pokes wait for your next message to write it again; a poke that had to write it anyway (the first after a compaction or model switch) never counts as cold./caffeine idle), unless you confirm /caffeine forever for that run.FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL or ENABLE_PROMPT_CACHING_1H, tell caffeine too with /caffeine ttl. From the usage figures it works out the cache TTL, first match wins:None of it goes into a poke or a wake prompt. It reads no files and makes no network requests.
/caffeine forever asks you to confirm in Claude Code's own question dialog.prompt.submit only clears the "limit hit" flag when you send a prompt, and changes nothing. classic.StopFailure only notices a reply that failed on the usage limit, to offer the wake. turn.step reads each request's usage and leaves the request as it is. session.compact and session.end only note a compaction or /clear, to hold the pokes.claude --resume picks it back up.MIT
hooks/register.tsx 1028 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Brew } from '../types'
5import {
6 clock,
7 DEFAULT_IDLE,
8 DEFAULT_MESSAGE,
9 defaultEvery,
10 dollars,
11 equivalents,
12 nextPokeAt,
13 overLine,
14 parseClock,
15 parseDuration,
16 pokeGuess,
17 pokeWasCold,
18 readTiming,
19 readRate,
20 sized,
21 span,
22 TTL_1H,
23 TTL_5M,
24 ttlByPlan,
25 ttlFromCost,
26 warmth,
27 writeRate,
28} from './brew'
29import type { Limit, Usage, Warmth } from './brew'
30import { blocking, DEFAULT_TIMER_WAKE, DEFAULT_WAKE, isNear, MARK, parseWake, wakeAfter } from './wake'
31import type { Block } from './wake'
32
33// The session's switch, kept by the host so a reload of the mod finds it.
34const brew = atom({ plugin: 'cache-caffeine', key: 'brew' } as const, {
35 isOn: false,
36 until: 0,
37 lastAt: 0,
38 activeAt: 0,
39 isAutoDeclined: false,
40 isForever: false,
41})
42
43// A booked wake: when it fires, and what it waits out.
44type Armed = { at: number; label: string; text: string }
45
46// The booked wake as the store keeps it, so `--resume` finds it again.
47type KeptWake = { session: string; at: number; label: string; text?: string }
48
49type Caffeine = Brew & {
50 // a main-thread turn is running; its own requests keep the cache warm
51 isBusy: boolean
52 // a poke submitted, then running in its own turn
53 poke: 'none' | 'sent' | 'running'
54 pokeTurnId: string
55 sentAt: number
56 pokes: number
57 // what the pokes cost this session, in input-token equivalents
58 spent: number
59 lastPoke: Usage | null
60 // whether the last poke found the cache still warm
61 lastWarm: boolean | null
62 limits: Limit[]
63 context: number
64 model: string
65 // the TTL sources, in ttlOf's order: the person's override, a 1h cost
66 // reading, request timing; else Claude Code's choice by plan
67 ttl: number | null
68 // only ever 1h (a 1.25x cost cannot tell 5m from 1h); cleared by a cache found cold
69 // inside the hour, unless that request priced at 1h itself
70 measuredTtl: number | null
71 // the running turn's last request priced at 1h: its cold cache was a prefix change, not an expiry
72 isPriced: boolean
73 // what request timing says, for models caffeine has no price for
74 timedTtl: number | null
75 // what emptied the cache (compaction, /clear); pokes wait for the next request to rewrite it
76 heldBy: string
77 // the running poke was a first request (after a compaction or on another model),
78 // so its write says nothing about the pokes before it
79 isPokeExempt: boolean
80 // the last time a request found the cache cold, and the gap before it
81 coldAt: number
82 coldGap: number
83 // settings kept across sessions
84 message: string
85 every: number | null
86 isBanded: boolean
87 idle: number
88 // turn on by itself once the context passes this many tokens; 0 is never
89 autoAt: number
90 // the band's message field is open
91 isEditing: boolean
92 // the steam's shimmer
93 frame: number
94 bandId: string
95 // the wake
96 armed: Armed | null
97 // the last reply failed on the usage limit
98 isHit: boolean
99 // the reset someone said "not now" to; the wake row stays down until it passes
100 dismissed: number
101 // caffeine was off when the wake was booked, and comes off with it
102 isWakeLit: boolean
103}
104
105const MINUTE = 60_000
106// `/caffeine warm` alone
107const WARM = 60 * MINUTE
108
109// a 1h-priced request, then timing, then the plan
110const ttlOf = (c: Caffeine) => c.ttl ?? c.measuredTtl ?? c.timedTtl ?? ttlByPlan(c.limits)
111
112// Where the TTL comes from, for /caffeine status.
113function ttlSource(c: Caffeine): string {
114 if (c.ttl !== null) return 'set with /caffeine ttl'
115 if (c.measuredTtl !== null) return 'measured from what requests cost'
116 if (c.timedTtl !== null) return 'measured from request timing'
117 if (c.limits.length) return 'the subscription default'
118 return c.lastAt ? 'the API-key default' : 'a guess until the first reply shows the plan'
119}
120const everyOf = (c: Caffeine) => c.every ?? defaultEvery(ttlOf(c))
121const ttlLabel = (ms: number) => (ms >= TTL_1H ? '1h' : '5m')
122
123// Says how it went: a toast, and a line in the transcript that outlasts it.
124function tell($: EngineInterface, text: string): void {
125 $.ui.toast(`caffeine: ${text}`)
126 $.ui.log(`caffeine: ${text}`)
127}
128
129async function setting<T>($: EngineInterface, key: string, fallback: T): Promise<T> {
130 try {
131 const value = await $.store.get(key)
132 return value === undefined || value === null ? fallback : (value as T)
133 } catch {
134 return fallback
135 }
136}
137
138async function load($: EngineInterface, c: Caffeine): Promise<void> {
139 c.message = await setting($, 'message', DEFAULT_MESSAGE)
140 c.every = (await setting($, 'every', null)) as number | null
141 c.isBanded = await setting($, 'band', true)
142 c.idle = (await setting($, 'idle', DEFAULT_IDLE)) || DEFAULT_IDLE
143 c.ttl = (await setting($, 'ttl', null)) as number | null
144 c.autoAt = await setting($, 'autoAt', 0)
145}
146
147async function keep($: EngineInterface, c: Caffeine): Promise<void> {
148 const kept: Brew = {
149 isOn: c.isOn,
150 until: c.until,
151 lastAt: c.lastAt,
152 activeAt: c.activeAt,
153 isAutoDeclined: c.isAutoDeclined,
154 isForever: c.isForever,
155 }
156 await update($, brew, () => kept).catch(() => undefined)
157}
158
159// How long caffeine stays on: to a set time, or until turned off.
160function howLong(c: Caffeine, now: number): string {
161 if (c.until) {
162 return `until ${clock(c.until, now)} (${span(c.until - now)} left)`
163 }
164 return c.isForever || c.armed
165 ? 'until you turn it off'
166 : `until you turn it off (or ${span(c.idle).replace(' 00m', '')} idle)`
167}
168
169// One line for the band, the status line and /caffeine status.
170function describe(c: Caffeine, now: number): { text: string; color?: string; isDim?: boolean } {
171 if (!c.isOn) {
172 return { text: 'caffeine off', isDim: true }
173 }
174 const tail = [c.pokes ? `${c.pokes} poke${c.pokes === 1 ? '' : 's'}` : '', howLong(c, now)]
175 .filter(Boolean)
176 .map((t) => ` · ${t}`)
177 .join('')
178 const over = overLine(c.limits)
179 if (over) {
180 return { text: `caffeine paused · ${over.label} limit ${over.percent}%${tail}`, color: 'yellow' }
181 }
182 if (c.lastAt === 0) {
183 const why = c.heldBy ? `waits for your next message after the ${c.heldBy}` : 'waits for the first reply'
184 return { text: `caffeine on · ${why}${tail}`, color: 'green' }
185 }
186 if (c.isBusy || c.poke !== 'none') {
187 return { text: `caffeine on · cache warm${tail}`, color: 'green' }
188 }
189 if (now - c.lastAt >= ttlOf(c)) {
190 return { text: `caffeine on · cache went cold, waits for your next turn${tail}`, color: 'yellow' }
191 }
192 const at = nextPokeAt(c.lastAt, everyOf(c))!
193 return { text: `caffeine on · poke at ${clock(at, now)} (in ${span(at - now)})${tail}`, color: 'green' }
194}
195
196async function costNow($: EngineInterface): Promise<number | null> {
197 try {
198 const usd = (await $.session.usage()).cost?.usd
199 return typeof usd === 'number' ? usd : null
200 } catch {
201 return null
202 }
203}
204
205function cup(c: Caffeine, now: number): Warmth | null {
206 return c.lastAt ? warmth(c.lastAt + ttlOf(c) - now, ttlOf(c), c.frame) : null
207}
208
209async function refresh($: EngineInterface, c: Caffeine): Promise<void> {
210 if (c.isBanded || !c.isOn) {
211 $.ui.status(undefined)
212 } else {
213 const now = await $.clock.now()
214 const w = cup(c, now)
215 $.ui.status(`${w ? `${w.degrees}°F ` : ''}${describe(c, now).text}`)
216 }
217 $.ui.invalidate('ui.render')
218}
219
220async function switchOn($: EngineInterface, c: Caffeine, isOn: boolean, until = 0): Promise<void> {
221 c.isOn = isOn
222 c.until = isOn ? until : 0
223 c.isWakeLit = false
224 c.isForever = false
225 if (isOn) {
226 c.activeAt = await $.clock.now()
227 } else if (c.poke === 'sent') {
228 c.poke = 'none'
229 }
230 await keep($, c)
231 await refresh($, c)
232}
233
234// Sends the poke: a prompt of its own, run once the session is idle.
235function poke($: EngineInterface, c: Caffeine, now: number): void {
236 c.poke = 'sent'
237 c.sentAt = now
238 void $.prompt.submit({ text: c.message }).catch(() => {
239 c.poke = 'none'
240 })
241}
242
243async function tick($: EngineInterface, c: Caffeine): Promise<void> {
244 const now = await $.clock.now()
245 if (c.armed && now >= c.armed.at) {
246 await fire($, c, c.armed)
247 }
248 if (!c.isOn) {
249 return
250 }
251 if (c.until && now >= c.until) {
252 const wasWake = c.isWakeLit
253 await switchOn($, c, false)
254 if (!wasWake) tell($, 'wore off.')
255 return
256 }
257 if (!c.isForever && !c.armed && now - c.activeAt >= c.idle) {
258 await switchOn($, c, false)
259 tell($, `turned off after ${span(c.idle)} without a turn of your own.`)
260 return
261 }
262 if (c.poke !== 'none') {
263 // a poke that never got its turn (a dialog, a closed prompt) stops blocking the rest
264 if (c.poke === 'sent' && now - c.sentAt > 10 * MINUTE) c.poke = 'none'
265 return
266 }
267 // a poke into a cold cache would only write it again
268 if (c.isBusy || c.lastAt === 0 || overLine(c.limits) || now - c.lastAt >= ttlOf(c)) {
269 return
270 }
271 const due = nextPokeAt(c.lastAt, everyOf(c))
272 if (due !== null && now >= due) {
273 poke($, c, now)
274 }
275}
276
277async function setMessage($: EngineInterface, c: Caffeine, text: string): Promise<string> {
278 c.message = text.trim() || DEFAULT_MESSAGE
279 c.isEditing = false
280 await $.store.set('message', c.message)
281 await refresh($, c)
282 return c.message
283}
284
285async function editInBand($: EngineInterface, c: Caffeine): Promise<void> {
286 c.isEditing = true
287 $.ui.invalidate('ui.render')
288 if (c.bandId) {
289 await $.ui.focus({ requestId: c.bandId, key: 'caffeine-message' }).catch(() => undefined)
290 }
291}
292
293// What the pokes cost against one cache rewrite.
294function costLines(c: Caffeine): string[] {
295 const ttl = ttlOf(c)
296 const model = c.model
297 if (!model || c.context === 0) {
298 return ['No reply yet this session: the cost comes with the first one.']
299 }
300 const poked = c.lastPoke ?? pokeGuess(c.context)
301 const each = equivalents(poked, model, ttl)
302 const rewrite = c.context * writeRate(ttl)
303 const ratio = rewrite / each
304 const usd = (n: number) => {
305 const d = dollars(n, model)
306 return d ? `, ${d}` : ''
307 }
308 return [
309 `Context ${sized(c.context)} tokens on ${model}, ${ttlLabel(ttl)} cache, a poke ${span(everyOf(c))} after the last request.`,
310 `One poke: ${sized(each)} input-token equivalents${usd(each)}${c.lastPoke ? ' (the last one, measured)' : ` (cache read at ${readRate(model)}x)`}.`,
311 `One cache rewrite: ${sized(rewrite)} (written again at ${writeRate(ttl)}x)${usd(rewrite)}.`,
312 `A rewrite costs about ${Math.round(ratio)} pokes: caffeine pays off if you are back within ${span(ratio * everyOf(c))}.`,
313 c.pokes ? `This session: ${c.pokes} poke${c.pokes === 1 ? '' : 's'}, ${sized(c.spent)}${usd(c.spent)}.` : '',
314 'At API list prices; on a Pro or Max plan the same tokens count against your usage limits instead.',
315 ].filter(Boolean)
316}
317
318// The wake: caffeine's own timer submits the wake prompt at a set time (once
319// the session is idle), like a poke. Stored under the session id, so
320// `--resume` picks it up again.
321
322async function arm($: EngineInterface, c: Caffeine, at: number, label: string, text = ''): Promise<void> {
323 await disarm($, c)
324 c.armed = { at, label, text }
325 const kept: KeptWake = { session: await sessionKey($), at, label, text }
326 await $.store.set('wake', kept).catch(() => undefined)
327 // the cache stays warm until Claude picks the work back up
328 if (!c.isOn) {
329 await switchOn($, c, true, at)
330 c.isWakeLit = true
331 }
332 const now = await $.clock.now()
333 tell(
334 $,
335 `Claude continues at ${clock(at, now)} (in ${span(at - now)})${label ? `, after the ${label} reset` : ''}, told: ${await wakeText($, c.armed)}. Keep this session open.`,
336 )
337 $.ui.invalidate('ui.render')
338}
339
340async function disarm($: EngineInterface, c: Caffeine): Promise<boolean> {
341 const armed = c.armed
342 c.armed = null
343 await $.store.delete('wake').catch(() => undefined)
344 if (c.isWakeLit) {
345 await switchOn($, c, false)
346 }
347 $.ui.invalidate('ui.render')
348 return armed !== null
349}
350
351// The session's id, which a kept wake belongs to; '' where there is none.
352async function sessionKey($: EngineInterface): Promise<string> {
353 try {
354 return await $.session.id()
355 } catch {
356 return ''
357 }
358}
359
360// What Claude is told: the wake's own text, else the set wake prompt, else the
361// default for its kind (after a limit reset, or at a time).
362async function wakeText($: EngineInterface, armed: Armed): Promise<string> {
363 const mine = (await setting($, 'wakePrompt', null)) as string | null
364 return armed.text || mine || (armed.label ? DEFAULT_WAKE : DEFAULT_TIMER_WAKE)
365}
366
367// Sends the wake prompt: the wake is spent.
368async function fire($: EngineInterface, c: Caffeine, armed: Armed): Promise<void> {
369 c.armed = null
370 c.isHit = false
371 await $.store.delete('wake').catch(() => undefined)
372 $.ui.invalidate('ui.render')
373 const prompt = `${MARK} ${await wakeText($, armed)}`
374 void $.prompt.submit({ text: prompt }).catch(() => undefined)
375}
376
377// After `--resume` or a mod reload, take back this session's wake if still ahead.
378async function adopt($: EngineInterface, c: Caffeine): Promise<void> {
379 try {
380 const kept = (await $.store.get('wake')) as KeptWake | null | undefined
381 if (!kept || c.armed || kept.session !== (await sessionKey($))) {
382 return
383 }
384 if (kept.at > (await $.clock.now())) {
385 c.armed = { at: kept.at, label: kept.label, text: kept.text ?? '' }
386 $.ui.invalidate('ui.render')
387 } else {
388 await $.store.delete('wake')
389 }
390 } catch {
391 // nothing kept; nothing booked
392 }
393}
394
395// Books the wake at the reset of the window in the way.
396async function armAtReset($: EngineInterface, c: Caffeine): Promise<void> {
397 const block = blocking(c.limits)
398 if (!block) {
399 tell($, 'no reset time yet: it comes with the first reply on a Pro or Max plan. /caffeine wake 14:30 picks a time.')
400 return
401 }
402 await arm($, c, wakeAfter(block.resetsAt), block.label)
403}
404
405const NO_RESET =
406 'No reset time yet: it comes with the first reply on a Pro or Max plan. /caffeine wake 14:30 picks a time.'
407
408async function wakeCommand($: EngineInterface, c: Caffeine, args: string): Promise<{ text: string }> {
409 const [word = '', ...rest] = args.split(/\s+/)
410 const arg = word.toLowerCase()
411 const value = rest.join(' ').trim()
412 const now = await $.clock.now()
413 const flip = async (key: string, name: string, fallback: boolean) => {
414 const v = value.toLowerCase()
415 const next = v === 'on' ? true : v === 'off' ? false : !(await setting($, key, fallback))
416 await $.store.set(key, next)
417 return { text: `${name} ${next ? 'on' : 'off'}.` }
418 }
419 switch (arg) {
420 case '': {
421 if (!blocking(c.limits)) return { text: NO_RESET }
422 $.clock.after(50, () => void armAtReset($, c))
423 return { text: 'Booking the wake…' }
424 }
425 case 'off':
426 case 'cancel':
427 $.clock.after(50, () => void disarm($, c).then((was) => tell($, was ? 'wake cancelled.' : 'no wake was booked.')))
428 return { text: 'Cancelling the wake…' }
429 case 'prompt': {
430 if (value.toLowerCase() === 'default') {
431 await $.store.delete('wakePrompt')
432 return {
433 text: `Back to the defaults: "${DEFAULT_WAKE}" after a limit reset, "${DEFAULT_TIMER_WAKE}" at a time.`,
434 }
435 }
436 if (!value) {
437 const mine = (await setting($, 'wakePrompt', null)) as string | null
438 return {
439 text: mine
440 ? `On waking Claude is told: ${mine} (prompt default goes back to the defaults)`
441 : `On waking Claude is told "${DEFAULT_WAKE}" after a limit reset, "${DEFAULT_TIMER_WAKE}" at a time.`,
442 }
443 }
444 await $.store.set('wakePrompt', value)
445 return { text: `On waking Claude will be told: ${value}${c.armed ? ' (from the next wake you book)' : ''}` }
446 }
447 case 'auto':
448 return flip('wakeAuto', 'Booking a wake whenever the limit hits:', false)
449 default: {
450 const wake = parseWake(args, now)
451 if (wake === null) return { text: `Not a time I know: ${args}. Try 1 min, in 20 minutes, 14:30 or 3pm.` }
452 const { at, text } = wake
453 $.clock.after(50, () => void arm($, c, at, '', text))
454 return {
455 text: `Booking the wake for ${clock(at, now)} (in ${span(at - now)})${text ? `, to say: ${text}` : ''}…`,
456 }
457 }
458 }
459}
460
461const FOREVER = 'Yes, no end'
462const KEEP_STOP = 'Keep the idle stop'
463
464// No end, but only once confirmed: the dialog spells out the cost; with no one
465// to ask, a trailing "yes" confirms.
466async function forever($: EngineInterface, c: Caffeine, isSure: boolean): Promise<{ text: string }> {
467 const perDay = Math.round((24 * 60 * MINUTE) / everyOf(c))
468 if (!isSure) {
469 let answer: string
470 try {
471 answer = await $.ui.ask(
472 `Keep the cache warm with no end this time? Caffeine pokes ${span(everyOf(c))} after the last request until you turn it off: about ${perDay} pokes a day while you are away, each using your plan's usage. Turning it off brings the idle stop back.`,
473 { header: 'caffeine', options: [FOREVER, KEEP_STOP] },
474 )
475 } catch {
476 return { text: 'No one to ask here. /caffeine forever yes confirms it.' }
477 }
478 if (answer !== FOREVER) {
479 return { text: `Kept: caffeine still turns itself off after ${span(c.idle)} without a turn of your own.` }
480 }
481 }
482 if (!c.isOn || c.until) {
483 await switchOn($, c, true)
484 }
485 c.isForever = true
486 await keep($, c)
487 await refresh($, c)
488 return {
489 text: `Caffeine on with no end, until you turn it off. Next time you turn it on, the ${span(c.idle)} idle stop is back.`,
490 }
491}
492
493const help = [
494 '/caffeine turn it on or off for this session',
495 '/caffeine on | off',
496 '/caffeine warm 1h keep the cache warm for 1h, then off (90m, 1h30m; alone: 1h)',
497 '/caffeine until 18:00 on, and off again at 18:00 (6pm)',
498 '/caffeine poke poke now',
499 '/caffeine message … what the poke says (alone: show it; "reset": the default)',
500 '/caffeine auto 100k turn on by itself once the context passes 100k tokens (off: never)',
501 '/caffeine cost what the pokes cost against one cache rewrite',
502 '/caffeine every 10m poke this long after the last request (alone: back to auto)',
503 '/caffeine ttl 1h|5m pin the cache TTL (auto: back to detecting it)',
504 '/caffeine forever on with no end this time, once confirmed (also: idle off); off restores the idle stop',
505 '/caffeine idle 8h turn off after this long without a turn of your own',
506 '/caffeine band on|off the row above the prompt; off moves it to the status line',
507 '/caffeine wake wake Claude just after the usage limit resets',
508 '/caffeine 1 min wake Claude at a time: in 20 minutes, 2 hours, 14:30, 3pm (also: wake 1 min); wake off cancels',
509 '/caffeine 20 min check the build a wake that tells Claude exactly that',
510 '/caffeine wake prompt … what Claude is told on every wake; wake prompt default goes back',
511 '/caffeine wake auto book the wake by itself whenever the limit hits (on/off)',
512 '/caffeine status what it is doing',
513].join('\n')
514
515async function hold($: EngineInterface, c: Caffeine, by: string): Promise<void> {
516 c.lastAt = 0
517 c.heldBy = by
518 await keep($, c)
519 await refresh($, c)
520}
521
522export const register: Register = (on) => {
523 const c: Caffeine = {
524 isOn: false,
525 until: 0,
526 lastAt: 0,
527 activeAt: 0,
528 isAutoDeclined: false,
529 isForever: false,
530 isBusy: false,
531 poke: 'none',
532 pokeTurnId: '',
533 sentAt: 0,
534 pokes: 0,
535 spent: 0,
536 lastPoke: null,
537 lastWarm: null,
538 limits: [],
539 context: 0,
540 model: '',
541 ttl: null,
542 measuredTtl: null,
543 isPriced: false,
544 timedTtl: null,
545 heldBy: '',
546 isPokeExempt: false,
547 coldAt: 0,
548 coldGap: 0,
549 message: DEFAULT_MESSAGE,
550 every: null,
551 isBanded: true,
552 idle: DEFAULT_IDLE,
553 autoAt: 0,
554 isEditing: false,
555 frame: 0,
556 bandId: '',
557 armed: null,
558 isHit: false,
559 dismissed: 0,
560 isWakeLit: false,
561 }
562
563 on('session.start', async ($, e, next) => {
564 await $.command.register({
565 name: 'caffeine',
566 description: 'Keep the prompt cache warm while you step away, and wake Claude when the usage limit resets',
567 argumentHint: '[on|off|status|warm|until|wake|ttl|every|idle|auto|cost|poke|message|band|forever|help]',
568 })
569 const started = await next(e)
570 await load($, c)
571 try {
572 Object.assign(c, await read($, brew))
573 } catch {
574 // a fresh session: off
575 }
576 try {
577 const usage = await $.session.usage()
578 c.limits = [...usage.rateLimits]
579 } catch {
580 // the first reply brings them
581 }
582 $.clock.after(50, () => void adopt($, c))
583 $.clock.every(5_000, () => void tick($, c))
584 // the countdowns, and the cup cooling
585 $.clock.every(30_000, () => {
586 if (c.isOn || c.armed || isNear(c.limits) || c.lastAt) void refresh($, c)
587 })
588 $.clock.every(1_200, () => {
589 if (!c.isBanded || c.isEditing || !c.lastAt) return
590 void $.clock.now().then((now) => {
591 if (cup(c, now)?.steam.trim()) {
592 c.frame += 1
593 $.ui.invalidate('ui.render')
594 }
595 })
596 })
597 await refresh($, c)
598 return started
599 })
600
601 on('session.measure', async ($, e, next) => {
602 const wasNear = isNear(c.limits)
603 c.limits = [...e.rateLimits]
604 c.context = e.context?.tokens ?? c.context
605 if (c.autoAt && !c.isOn && !c.isAutoDeclined && c.context >= c.autoAt) {
606 await switchOn($, c, true)
607 tell($, `on: the context passed ${sized(c.autoAt)} tokens. /caffeine off turns it off for this session.`)
608 }
609 const block = blocking(c.limits)
610 if (block && block.percent >= 100 && !c.armed && (await setting($, 'wakeAuto', false))) {
611 await armAtReset($, c)
612 } else if (!wasNear && isNear(c.limits) && block) {
613 $.ui.toast(
614 `caffeine: ${block.label} limit at ${block.percent}%, resets ${clock(block.resetsAt, await $.clock.now())}. /caffeine wake books a wake.`,
615 )
616 }
617 $.ui.invalidate('ui.render')
618 return next(e)
619 })
620
621 on('classic.StopFailure', async ($, e, next) => {
622 if (e.error === 'rate_limit') {
623 c.isHit = true
624 if (!c.armed && (await setting($, 'wakeAuto', false))) {
625 await armAtReset($, c)
626 }
627 $.ui.invalidate('ui.render')
628 }
629 return next(e)
630 })
631
632 // Each main-thread request reads the cache and restarts its TTL. Its cost can
633 // prove a 1h write; a cache found cold inside the believed TTL takes that
634 // back, unless the rewrite priced at 1h itself: then the prefix changed (a
635 // tool list, an MCP reconnect, a resume), the cache did not expire.
636 on('turn.step', async function* ($, e, next) {
637 if (e.agentId !== undefined) {
638 return yield* next(e)
639 }
640 const at = await $.clock.now()
641 const gap = c.lastAt ? at - c.lastAt : 0
642 const believed = ttlOf(c)
643 // a first request (lastAt is 0 after a compaction or /clear) or another model
644 // writes the cache whatever the TTL
645 const isExempt = c.lastAt === 0 || (c.model !== '' && c.model !== e.model)
646 if (isExempt && c.poke === 'running') c.isPokeExempt = true
647 c.model = e.model
648 c.lastAt = at
649 c.heldBy = ''
650 void keep($, c)
651 const before = await costNow($)
652 const result = yield* next(e)
653 const after = await costNow($)
654 if (result.usage) {
655 const priced =
656 before !== null && after !== null
657 ? ttlFromCost(after - before, result.usage, result.usage.model || e.model)
658 : null
659 c.isPriced = priced !== null
660 if (priced !== null) c.measuredTtl = priced
661 const timing = readTiming(gap, result.usage, isExempt)
662 // a rewrite priced at 1h was no expiry, so it says nothing about a 5m TTL
663 if (timing.ttl !== null && !(timing.isCold && priced !== null)) c.timedTtl = timing.ttl
664 if (timing.isCold) {
665 c.coldAt = at
666 c.coldGap = gap
667 // cold inside the believed TTL with no 1h reading of its own: an earlier 1h reading was wrong
668 if (gap < believed && priced === null) c.measuredTtl = null
669 if (c.isOn && c.poke !== 'running') {
670 tell($, `the cache had gone cold after ${span(gap)} idle; this request wrote it again.`)
671 }
672 }
673 if (priced !== null || timing.ttl !== null || timing.isCold) void refresh($, c)
674 }
675 return result
676 })
677
678 on('turn.start', async ($, e, next) => {
679 c.isBusy = true
680 if (c.poke === 'sent' && e.text.includes(c.message)) {
681 c.poke = 'running'
682 c.pokeTurnId = e.turnId
683 c.isPokeExempt = false
684 } else {
685 c.activeAt = await $.clock.now()
686 }
687 return next(e)
688 })
689
690 on('turn.complete', async ($, e, next) => {
691 if (e.agentId === undefined) {
692 c.isBusy = false
693 if (c.poke === 'running' && e.turnId === c.pokeTurnId) {
694 c.poke = 'none'
695 c.pokes += 1
696 if (e.usage) {
697 c.lastPoke = e.usage
698 c.spent += equivalents(e.usage, e.usage.model || c.model, ttlOf(c))
699 }
700 const isExempt = c.isPokeExempt
701 c.isPokeExempt = false
702 // a poke that had to write the cache anyway says nothing about the pokes before it
703 if (e.usage && !isExempt && pokeWasCold(e.usage)) {
704 c.lastWarm = false
705 // a poke inside the TTL found it cold: not 1h, unless the poke's own cost says so
706 if (!c.isPriced) c.measuredTtl = null
707 await switchOn($, c, false)
708 tell(
709 $,
710 `turned off: its poke found the cache cold (rewrote ${sized(e.usage.cache_creation_input_tokens)} tokens), so pokes were not keeping it warm. /caffeine status may say why; turn it on again to retry.`,
711 )
712 } else if (e.usage && !isExempt) {
713 c.lastWarm = true
714 }
715 }
716 await keep($, c)
717 await refresh($, c)
718 }
719 return next(e)
720 })
721
722 on('prompt.submit', async ($, e, next) => {
723 if (e.origin.kind !== 'plugin') {
724 c.isHit = false
725 }
726 return next(e)
727 })
728
729 // A compaction or /clear empties the cache: no pokes until the person's next
730 // request (or the turn carrying on) writes it again.
731 on('session.compact', async ($, e, next) => {
732 const done = await next(e)
733 if (e.agentId === undefined && e.trigger !== 'precompute' && !('skip' in done && done.skip)) {
734 await hold($, c, 'compaction')
735 }
736 return done
737 })
738
739 on('session.end', async ($, e, next) => {
740 if (e.reason === 'clear') await hold($, c, '/clear')
741 return next(e)
742 })
743
744 on('command.run', { command: 'caffeine' }, async ($, e) => {
745 const args = e.args.trim()
746 const [word = '', ...rest] = args.split(/\s+/)
747 const arg = word.toLowerCase()
748 const value = rest.join(' ').trim()
749 const now = await $.clock.now()
750 switch (arg) {
751 case 'help':
752 return { text: help }
753 case '':
754 if (c.isOn) c.isAutoDeclined = true
755 await switchOn($, c, !c.isOn)
756 return {
757 text: c.isOn ? `Caffeine on: ${describe(c, now).text.replace(/^caffeine on · /, '')}.` : 'Caffeine off.',
758 }
759 case 'on':
760 await switchOn($, c, true)
761 return {
762 text: `Caffeine on until you turn it off, poking ${span(everyOf(c))} after the last request (${ttlLabel(ttlOf(c))} cache).`,
763 }
764 case 'off':
765 c.isAutoDeclined = true
766 await switchOn($, c, false)
767 return { text: 'Caffeine off.' }
768 case 'for':
769 case 'warm': {
770 const ms = value ? parseDuration(value) : WARM
771 if (ms === null) return { text: `Not a duration I know: ${value}. Try 2h, 90m or 1h30m.` }
772 await switchOn($, c, true, now + ms)
773 return { text: `Caffeine on, keeping the cache warm until ${clock(now + ms, now)}.` }
774 }
775 case 'until': {
776 const at = parseClock(value, now)
777 if (at === null) return { text: `Not a time I know: ${value || '(none)'}. Try 18:00 or 6pm.` }
778 await switchOn($, c, true, at)
779 return { text: `Caffeine on, keeping the cache warm until ${clock(at, now)}.` }
780 }
781 case 'poke':
782 if (c.poke !== 'none') return { text: 'A poke is already on its way.' }
783 // a prompt submitted from inside this command would wait on the turn it holds
784 $.clock.after(50, () => void $.clock.now().then((t) => poke($, c, t)))
785 return { text: `Poking: ${c.message}` }
786 case 'message':
787 case 'say': {
788 if (!value) return { text: `The poke says: ${c.message}` }
789 const saved = await setMessage($, c, value.toLowerCase() === 'reset' ? '' : value)
790 return { text: `The poke now says: ${saved}` }
791 }
792 case 'auto': {
793 const v = value.toLowerCase()
794 if (!v)
795 return {
796 text: c.autoAt
797 ? `Caffeine turns on by itself past ${sized(c.autoAt)} tokens of context.`
798 : 'Auto is off. /caffeine auto 100k turns it on.',
799 }
800 const n =
801 v === 'off'
802 ? 0
803 : v === 'on'
804 ? 100_000
805 : /^(\d+(?:\.\d+)?)(k|m)?$/.test(v)
806 ? Math.round(Number.parseFloat(v) * (v.endsWith('m') ? 1e6 : v.endsWith('k') ? 1e3 : 1))
807 : null
808 if (n === null || (n > 0 && n < 1000)) return { text: `Not a token count I know: ${value}. Try 100k, or off.` }
809 c.autoAt = n
810 await $.store.set('autoAt', n)
811 return {
812 text: n
813 ? `Caffeine turns on by itself once the context passes ${sized(n)} tokens (now ${sized(c.context)}).`
814 : 'Auto off.',
815 }
816 }
817 case 'cost':
818 return { text: costLines(c).join('\n') }
819 case 'every': {
820 if (!value || value === 'auto') {
821 c.every = null
822 await $.store.set('every', null)
823 await refresh($, c)
824 return { text: `Poking ${span(everyOf(c))} after the last request (auto, ${ttlLabel(ttlOf(c))} cache).` }
825 }
826 const ms = parseDuration(value)
827 if (ms === null || ms < 30_000) return { text: `Not a duration I know (30s or more): ${value}.` }
828 if (ms >= ttlOf(c))
829 return { text: `${span(ms)} is past the ${ttlLabel(ttlOf(c))} cache: it would be cold by then.` }
830 c.every = ms
831 await $.store.set('every', ms)
832 await refresh($, c)
833 return { text: `Poking ${span(ms)} after the last request.` }
834 }
835 case 'ttl': {
836 const v = value.toLowerCase()
837 const ttl = v === '1h' ? TTL_1H : v === '5m' ? TTL_5M : null
838 if (ttl === null && v && v !== 'auto') return { text: 'The TTL is 1h, 5m or auto.' }
839 c.ttl = ttl
840 await $.store.set('ttl', ttl)
841 await refresh($, c)
842 return {
843 text: `Cache TTL ${ttlLabel(ttlOf(c))} (${ttlSource(c)}); poking ${span(everyOf(c))} after the last request.`,
844 }
845 }
846 case 'forever':
847 return forever($, c, value.toLowerCase() === 'yes')
848 case 'idle': {
849 const [first = '', second = ''] = value.toLowerCase().split(/\s+/)
850 if (first === 'off' || first === 'never') {
851 return forever($, c, second === 'yes')
852 }
853 const ms = parseDuration(value)
854 if (ms === null)
855 return { text: `Not a duration I know: ${value || '(none)'}. Try 8h, or off for no end this time.` }
856 c.idle = ms
857 await $.store.set('idle', ms)
858 return { text: `Caffeine turns itself off after ${span(ms)} without a turn of your own.` }
859 }
860 case 'band': {
861 const v = value.toLowerCase()
862 c.isBanded = v === 'on' ? true : v === 'off' ? false : !c.isBanded
863 await $.store.set('band', c.isBanded)
864 await refresh($, c)
865 return {
866 text: c.isBanded
867 ? 'Caffeine shows in its row above the prompt.'
868 : 'Caffeine shows in the status line while on; no row above the prompt.',
869 }
870 }
871 case 'wake':
872 return wakeCommand($, c, value)
873 case 'status': {
874 const block = blocking(c.limits)
875 const lines = [
876 describe(c, now).text,
877 `Cache TTL ${ttlLabel(ttlOf(c))} (${ttlSource(c)}) · poke ${span(everyOf(c))} after the last request${c.every === null ? ' (auto)' : ''}`,
878 `${c.isForever ? 'No idle stop this time: on until you turn it off' : `Off by itself after ${span(c.idle)} idle`} · auto ${c.autoAt ? `past ${sized(c.autoAt)}` : 'off'} · band ${c.isBanded ? 'on' : 'off'}`,
879 c.lastWarm === null ? '' : `The last poke found the cache ${c.lastWarm ? 'warm' : 'cold'}.`,
880 c.coldAt ? `The cache last went cold before ${clock(c.coldAt, now)}, after ${span(c.coldGap)} idle.` : '',
881 `The poke says: ${c.message}`,
882 c.armed
883 ? `Wake: Claude continues at ${clock(c.armed.at, now)} (in ${span(c.armed.at - now)}), told: ${await wakeText($, c.armed)}.`
884 : 'Wake: none booked.',
885 block ? `${block.label} limit ${block.percent}%, resets ${clock(block.resetsAt, now)}.` : '',
886 ]
887 return { text: lines.filter(Boolean).join('\n') }
888 }
889 default: {
890 // a bare time is a wake: /caffeine 1 min, /caffeine at 3pm
891 if (parseWake(args, now) !== null) {
892 return wakeCommand($, c, args)
893 }
894 return { text: `Not a caffeine command: ${word}\n${help}` }
895 }
896 }
897 })
898
899 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
900 if ((e.surface !== 'terminal' && e.surface !== 'desktop') || e.props.hasSurvey) {
901 return next(e)
902 }
903 const { Box, Button, Input, Text } = $.ui.resolve(e)
904 const now = await $.clock.now()
905 c.bandId = e.requestId
906
907 // the wake row: near the limit an offer, once booked a countdown
908 const block: Block | null = blocking(c.limits)
909 const isOffered = !c.armed && block !== null && (isNear(c.limits) || c.isHit) && c.dismissed !== block.resetsAt
910 const armed = c.armed
911 const wakeRow = armed ? (
912 <Box key="caffeine-wake-row" flexDirection="row" columnGap={2}>
913 <Text key="wake-text" color="cyan" wrap="truncate-end">
914 {`caffeine · Claude continues at ${clock(armed.at, now)} (in ${span(armed.at - now)})`}
915 </Text>
916 <Button
917 key="caffeine-wake-cancel"
918 plain
919 dimColor
920 hotkey="n"
921 onPress={() => void disarm($, c).then(() => tell($, 'wake cancelled.'))}
922 >
923 cancel
924 </Button>
925 </Box>
926 ) : isOffered ? (
927 <Box key="caffeine-wake-row" flexDirection="row" columnGap={2}>
928 <Text key="wake-text" color={block!.percent >= 100 ? 'red' : 'yellow'} wrap="truncate-end">
929 {`${block!.label} limit ${block!.percent}% · resets ${clock(block!.resetsAt, now)} (in ${span(block!.resetsAt - now)})`}
930 </Text>
931 <Button key="caffeine-wake" plain hotkey="u" onPress={() => void armAtReset($, c)}>
932 {`wake Claude at ${clock(wakeAfter(block!.resetsAt), now)}`}
933 </Button>
934 <Button
935 key="caffeine-wake-dismiss"
936 plain
937 dimColor
938 hotkey="n"
939 onPress={() => {
940 c.dismissed = block!.resetsAt
941 $.ui.invalidate('ui.render')
942 }}
943 >
944 not now
945 </Button>
946 </Box>
947 ) : null
948
949 // the switch row, under its cup
950 const line = describe(c, now)
951 const warm = cup(c, now)
952 const row = !c.isBanded ? null : c.isEditing ? (
953 <Box key="caffeine" flexDirection="row" columnGap={2}>
954 <Input
955 key="caffeine-message"
956 label="caffeine says: "
957 value={c.message}
958 placeholder={DEFAULT_MESSAGE}
959 submitLabel="save"
960 autoFocus
961 onSubmit={(text) => void setMessage($, c, text).then((saved) => tell($, `the poke now says: ${saved}`))}
962 />
963 <Button
964 key="caffeine-cancel"
965 plain
966 dimColor
967 hotkey="q"
968 onPress={() => {
969 c.isEditing = false
970 $.ui.invalidate('ui.render')
971 }}
972 >
973 cancel
974 </Button>
975 </Box>
976 ) : (
977 <Box key="caffeine" flexDirection="column">
978 <Text key="steam" color={warm?.color} dimColor={!warm}>
979 {` ${warm?.steam ?? ' '}`}
980 </Text>
981 <Box key="caffeine-row" flexDirection="row" columnGap={2}>
982 <Box key="caffeine-cup" flexDirection="row" columnGap={1} flexShrink={0}>
983 <Text key="cup" color={warm?.color} dimColor={!warm}>
984 c[_]
985 </Text>
986 <Text key="degrees" color={warm?.color} dimColor={!warm}>
987 {warm ? `${warm.degrees}°F` : '--°F'}
988 </Text>
989 </Box>
990 <Box key="caffeine-line" flexShrink={1} minWidth={0}>
991 <Text key="text" color={line.color} dimColor={line.isDim} wrap="truncate-end">
992 {line.text}
993 </Text>
994 </Box>
995 <Box key="caffeine-buttons" flexDirection="row" columnGap={2} flexShrink={0}>
996 <Button
997 key="caffeine-toggle"
998 plain
999 hotkey="t"
1000 onPress={() => {
1001 if (c.isOn) c.isAutoDeclined = true
1002 void switchOn($, c, !c.isOn)
1003 }}
1004 >
1005 {c.isOn ? 'turn off' : 'turn on'}
1006 </Button>
1007 <Button key="caffeine-edit" plain dimColor hotkey="e" onPress={() => void editInBand($, c)}>
1008 message
1009 </Button>
1010 </Box>
1011 </Box>
1012 </Box>
1013 )
1014
1015 if (!wakeRow && !row) {
1016 return next(e)
1017 }
1018 const below = await next(e)
1019 return (
1020 <Box flexDirection="column">
1021 {wakeRow}
1022 {row}
1023 {below}
1024 </Box>
1025 )
1026 })
1027}
1028hooks/brew.ts 291 lines1// Pure parts of caffeine: the cache TTL, when the next poke is due, the
2// durations and times it parses and prints, and the usage lines it will not cross.
3
4export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
5
6export const DEFAULT_MESSAGE = 'poke, just say okay'
7
8const second = 1000
9const minute = 60 * second
10const hour = 60 * minute
11
12export const TTL_5M = 5 * minute
13export const TTL_1H = hour
14
15// The default poke delay after the last request: 80% of the TTL (48m of 1h,
16// 4m of 5m). Each poke restarts the TTL, so one late poke per lifetime is enough.
17export const POKE_AT = 0.8
18
19export function defaultEvery(ttl: number): number {
20 return Math.round(ttl * POKE_AT)
21}
22
23// Turns itself off after this long with no turn but pokes.
24export const DEFAULT_IDLE = 8 * hour
25
26// Pokes stop at these usage lines: the window is better spent on work.
27export const LIMIT_LINE = { five_hour: 90, seven_day: 95 } as const
28const LABELS: Record<string, string> = { five_hour: '5h', seven_day: 'weekly' }
29
30// The first window over its line, or null.
31export function overLine(limits: readonly Limit[]): { label: string; percent: number } | null {
32 for (const l of limits) {
33 const line = LIMIT_LINE[l.kind as keyof typeof LIMIT_LINE]
34 if (line !== undefined && l.percentUsed >= line) {
35 return { label: LABELS[l.kind] ?? l.kind, percent: Math.round(l.percentUsed) }
36 }
37 }
38 return null
39}
40
41// Claude Code's automatic choice: 1h on a subscription under its limits (only
42// subscriptions have rate-limit windows), else 5m.
43export function ttlByPlan(limits: readonly Limit[]): number {
44 return limits.length > 0 && limits.every((l) => l.percentUsed < 100) ? TTL_1H : TTL_5M
45}
46
47// 1h when one request's cost proves it: the session cost rose by `delta`
48// dollars for `u`, and only the cache write's rate is unknown. The cost is
49// Claude Code's estimate, not the bill: it prices a write at the 1h 2x only
50// for tokens the API reported under a 1h TTL (and only if its price table has
51// a 1h rate for the model), every other write at the 5m 1.25x. So 2x proves
52// 1h, and 1.25x proves nothing (a 5m write, or a 1h one priced as 5m).
53// Null when the write is too small to tell, the price is unknown, or the rate
54// is not 2x (1.25x, or a subagent's request landed in between).
55// Two charges never reach the hook, which gets only the four token counts and
56// the model (no inference_geo, no web search count): a web search ($0.01
57// each) and the US multiplier. So the cost is read as is and with the
58// multiplier off, and 2x from either is 1h. The write must be at least a
59// quarter of the rest of the request so the two readings cannot meet (a US 5m
60// write reads under 1.8x as is, a 1h write elsewhere under 1.85x with the
61// multiplier off), and large enough that one search moves its rate by less
62// than the tolerance, so a search cannot carry a 5m write to 2x: over 100k
63// tokens on Haiku ($1), 50k on Sonnet 5, 25k on Opus 5.5, 10k on Fable.
64// Several searches or a subagent's cost can still land on 2x by chance; a cold
65// cache inside the hour with no 2x reading of its own takes it back (register.tsx).
66export function ttlFromCost(delta: number, u: Usage, model: string): number | null {
67 const price = inputPrice(model)
68 if (price === null || u.cache_creation_input_tokens < 1000 || !(delta > 0)) {
69 return null
70 }
71 const rest = u.input_tokens + u.output_tokens * 5 + u.cache_read_input_tokens * readRate(model)
72 if (
73 rest > 4 * u.cache_creation_input_tokens ||
74 (u.cache_creation_input_tokens * price * RATE_TOLERANCE) / 1e6 <= WEB_SEARCH_USD
75 ) {
76 return null
77 }
78 const rateOf = (usd: number) => ((usd * 1e6) / price - rest) / u.cache_creation_input_tokens
79 return [delta, delta / US_MULTIPLIER].some((usd) => Math.abs(rateOf(usd) - 2) < RATE_TOLERANCE) ? TTL_1H : null
80}
81
82// how far from 2x a write's rate may read and still count as 1h
83const RATE_TOLERANCE = 0.1
84
85// Claude Code's flat charge per web search (never multiplied by the US x1.1)
86const WEB_SEARCH_USD = 0.01
87
88// Claude Code's estimate (2.1.301) multiplies a request's whole cost by 1.1
89// when usage says inference_geo "us"; no other region has one.
90export const US_MULTIPLIER = 1.1
91
92// When the next poke is due, or null before the first request.
93export function nextPokeAt(lastAt: number, every: number): number | null {
94 return lastAt > 0 ? lastAt + every : null
95}
96
97// A cache read larger than what the request had to write again: still warm.
98export function wasWarm(
99 usage: { cache_read_input_tokens: number; cache_creation_input_tokens: number } | undefined,
100): boolean | null {
101 if (!usage) return null
102 return usage.cache_read_input_tokens > usage.cache_creation_input_tokens
103}
104
105const UNITS: Record<string, number> = { h: hour, m: minute, s: second }
106
107// A span of time as people type it: `2h`, `90m`, `1h30m`, `2.5m`, `150s`,
108// `1 min`, `5 minutes`, `2 hours`, `1 hour 30 min`, `in 20 minutes`, `+90m`.
109// Milliseconds, or null.
110export function parseDuration(text: string): number | null {
111 const t = text
112 .trim()
113 .toLowerCase()
114 .replace(/^(in|for)\s+/, '')
115 .replace(/^\+/, '')
116 .replace(/,|\band\b/g, ' ')
117 const part = /(\d+(?:\.\d+)?)\s*(hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)(?![a-z])/g
118 let ms = 0
119 let rest = t
120 for (const m of t.matchAll(part)) {
121 ms += Number(m[1]) * UNITS[m[2]![0]!]!
122 rest = rest.replace(m[0], '')
123 }
124 return ms > 0 && rest.trim() === '' ? Math.round(ms) : null
125}
126
127// `18:00`, `6pm`, `6:30 pm`, `at 3pm`, `noon`, `midnight`: the next such time
128// after `now`, or null.
129export function parseClock(word: string, now: number): number | null {
130 const w = word
131 .trim()
132 .toLowerCase()
133 .replace(/^at\s+/, '')
134 .replace(/^noon$/, '12:00')
135 .replace(/^midnight$/, '0:00')
136 const time = /^(\d{1,2})(?::(\d{2}))?\s*(am|pm|a\.m\.|p\.m\.)?$/.exec(w)
137 if (!time || (!time[2] && !time[3])) {
138 return null
139 }
140 let h = Number(time[1])
141 const m = Number(time[2] ?? 0)
142 if (time[3]) {
143 if (h < 1 || h > 12) return null
144 h = (h % 12) + (time[3].startsWith('p') ? 12 : 0)
145 }
146 if (h > 23 || m > 59) {
147 return null
148 }
149 const d = new Date(now)
150 d.setHours(h, m, 0, 0)
151 return d.getTime() <= now ? d.getTime() + 24 * hour : d.getTime()
152}
153
154const two = (n: number) => String(n).padStart(2, '0')
155const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
156
157// 14:12 today, `Sat 14:12` on another day.
158export function clock(at: number, now: number): string {
159 const d = new Date(at)
160 const time = `${two(d.getHours())}:${two(d.getMinutes())}`
161 return d.toDateString() === new Date(now).toDateString() ? time : `${DAYS[d.getDay()]} ${time}`
162}
163
164// 2h 05m, 12m, 2m 30s, 45s.
165export function span(ms: number): string {
166 const s = Math.max(0, Math.round(ms / second))
167 if (s >= 3600) return `${Math.floor(s / 3600)}h ${two(Math.floor((s % 3600) / 60))}m`
168 if (s >= 600) return `${Math.round(s / 60)}m`
169 if (s >= 60) return s % 60 ? `${Math.floor(s / 60)}m ${two(s % 60)}s` : `${s / 60}m`
170 return `${s}s`
171}
172
173// Request cost in input-token equivalents (base input = 1), by the API's
174// ratios: output 5x, cache writes 1.25x (5m) or 2x (1h), cache reads 0.1x,
175// except 0.05x on Opus 5.5 and 0.025x on Fable 5.1 and Mythos 5.1.
176export function readRate(model: string): number {
177 if (/fable-5-1|mythos-5-1/.test(model)) return 0.025
178 if (/opus-5-5/.test(model)) return 0.05
179 return 0.1
180}
181
182export const writeRate = (ttl: number) => (ttl >= TTL_1H ? 2 : 1.25)
183
184// API list input price, $ per million tokens, for the models caffeine knows.
185const PRICES: [RegExp, number][] = [
186 [/fable-5|mythos-5/, 10],
187 [/opus-5-5/, 4],
188 [/opus-[45]/, 5],
189 [/sonnet-5/, 2],
190 [/sonnet-4-6/, 3],
191 [/haiku-4-5/, 1],
192]
193
194export function inputPrice(model: string): number | null {
195 return PRICES.find(([re]) => re.test(model))?.[1] ?? null
196}
197
198export type Usage = {
199 input_tokens: number
200 output_tokens: number
201 cache_read_input_tokens: number
202 cache_creation_input_tokens: number
203}
204
205export function equivalents(u: Usage, model: string, ttl: number): number {
206 return (
207 u.input_tokens +
208 u.output_tokens * 5 +
209 u.cache_read_input_tokens * readRate(model) +
210 u.cache_creation_input_tokens * writeRate(ttl)
211 )
212}
213
214// A poke over `context` cached tokens: the read, plus a short exchange.
215export const pokeGuess = (context: number): Usage => ({
216 input_tokens: 40,
217 output_tokens: 10,
218 cache_read_input_tokens: context,
219 cache_creation_input_tokens: 60,
220})
221
222// 7.3k, 284k, 1.2M.
223export function sized(n: number): string {
224 if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`
225 if (n >= 1e4) return `${Math.round(n / 1e3)}k`
226 if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`
227 return String(Math.round(n))
228}
229
230export function dollars(equiv: number, model: string): string {
231 const price = inputPrice(model)
232 if (price === null) return ''
233 const usd = (equiv * price) / 1e6
234 return usd < 0.01 ? 'under $0.01' : `about $${usd.toFixed(2)}`
235}
236
237// What one main-thread request's timing says about the cache, as Cache Keeper
238// reads it: the gap since the last request, and the prompt's read/write split.
239// Past 5.5 minutes a 5m cache has expired, so a mostly-read prompt proves 1h,
240// and a mostly-written one means the cache went cold (under an hour: a 5m TTL,
241// unless `isExempt`, the first request after a compaction or model switch).
242// Small prompts say nothing.
243export type Reading = { isCold: boolean; ttl: number | null }
244
245export const GAP = 5.5 * minute
246
247export function readTiming(gap: number, u: Usage, isExempt: boolean): Reading {
248 const total = u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
249 if (total < 30_000 || gap < GAP) {
250 return { isCold: false, ttl: null }
251 }
252 if (u.cache_read_input_tokens / total > 0.8) {
253 return { isCold: false, ttl: TTL_1H }
254 }
255 if (u.cache_creation_input_tokens / total > 0.5 && !isExempt) {
256 return { isCold: true, ttl: gap < TTL_1H ? TTL_5M : null }
257 }
258 return { isCold: false, ttl: null }
259}
260
261// A poke that wrote more than a tenth of what it read found the cache cold:
262// the pokes are not keeping it warm.
263export function pokeWasCold(u: Usage): boolean {
264 return u.cache_creation_input_tokens > 0.1 * u.cache_read_input_tokens
265}
266
267// The cup: cache warmth as a coffee's temperature, 100F (just written or read)
268// to 40F (expired), the steam thinning and the color going red to blue as it
269// cools. `frame` shimmers the steam.
270export type Warmth = { degrees: number; steam: string; color: string }
271
272const STEAM = [[' '], [' ~ ', ' ~'], ['≈ ≈', ' ≈≈'], ['≋≋≋', '≈≋≈']]
273
274export function warmth(left: number, ttl: number, frame = 0): Warmth {
275 const f = Math.max(0, Math.min(1, left / ttl))
276 const degrees = Math.round(40 + 60 * f)
277 const level = degrees >= 85 ? 3 : degrees >= 65 ? 2 : degrees >= 48 ? 1 : 0
278 const frames = STEAM[level]!
279 const color =
280 degrees >= 85
281 ? '#ff5a36'
282 : degrees >= 70
283 ? '#ff9a3c'
284 : degrees >= 55
285 ? '#f2c94c'
286 : degrees > 40
287 ? '#9cb8d8'
288 : '#5b8fd9'
289 return { degrees, steam: frames[frame % frames.length]!, color }
290}
291hooks/wake.ts 77 lines1// Pure parts of the wake (formerly wakey): the window in the way, when to
2// wake, and what Claude is told.
3
4import { parseClock, parseDuration } from './brew'
5import type { Limit } from './brew'
6
7// What a wake is waiting out: the window, how full it is, and when it resets.
8export type Block = { label: string; percent: number; resetsAt: number }
9
10const LABELS: Record<string, string> = { five_hour: '5h', seven_day: 'weekly' }
11
12// The wake row shows from here: close enough to the line to plan a wake.
13export const NEAR = { five_hour: 90, seven_day: 95 } as const
14
15// Prefix on every wake prompt, so the transcript shows it as caffeine's.
16export const MARK = '[caffeine]'
17// What Claude is told on waking: after a limit reset, or at a set time.
18export const DEFAULT_WAKE = 'The usage limit has reset. Pick up where you left off.'
19export const DEFAULT_TIMER_WAKE = "Time's up. Pick up where you left off."
20
21const minute = 60_000
22
23function window(l: Limit): Block | null {
24 const resetsAt = l.resetsAt ? Date.parse(l.resetsAt) : Number.NaN
25 if (Number.isNaN(resetsAt) || !(l.kind in LABELS)) {
26 return null
27 }
28 return { label: LABELS[l.kind]!, percent: Math.round(l.percentUsed), resetsAt }
29}
30
31// The window to wait out: of the full ones, the one that resets last (a full
32// week outlasts a 5-hour reset); with none full, the 5-hour one.
33export function blocking(limits: readonly Limit[]): Block | null {
34 const windows = limits.map(window).filter((w): w is Block => w !== null)
35 const full = windows.filter((w) => w.percent >= 100).sort((a, b) => b.resetsAt - a.resetsAt)
36 return full[0] ?? windows.find((w) => w.label === '5h') ?? null
37}
38
39export function isNear(limits: readonly Limit[]): boolean {
40 return limits.some((l) => {
41 const line = NEAR[l.kind as keyof typeof NEAR]
42 return line !== undefined && l.percentUsed >= line
43 })
44}
45
46// A couple of minutes after the reset, so the window has surely turned over
47// (and never on :00 or :30, the busiest minutes).
48export function wakeAfter(resetsAt: number): number {
49 let at = Math.ceil((resetsAt + 2 * minute) / minute) * minute
50 const m = new Date(at).getMinutes()
51 if (m === 0 || m === 30) {
52 at += minute
53 }
54 return at
55}
56
57// When to wake, as people type it: a span from now (`1 min`, `in 20 minutes`,
58// `+90m`, `2 hours`) or a clock time (`14:30`, `2:30pm`, `at 3pm`, `noon`).
59export function parseWhen(text: string, now: number): number | null {
60 const ms = parseDuration(text)
61 return ms !== null ? now + ms : parseClock(text, now)
62}
63
64// A wake time and what to say: `20 min check the build` is 20 minutes from
65// now, saying "check the build". The longest leading run of words that reads
66// as a time is the time; the rest (maybe nothing) is the text.
67export function parseWake(text: string, now: number): { at: number; text: string } | null {
68 const words = text.trim().split(/\s+/).filter(Boolean)
69 for (let k = words.length; k > 0; k--) {
70 const at = parseWhen(words.slice(0, k).join(' '), now)
71 if (at !== null) {
72 return { at, text: words.slice(k).join(' ') }
73 }
74 }
75 return null
76}
77types/index.d.ts 19 lines1// Session state a reload of the mod finds again: on or off, when it wears off
2// (0 for never), the last main-thread request, the last non-poke turn, whether
3// the person turned off what auto turned on, and whether this run has no idle
4// stop (`/caffeine forever`, cleared when caffeine turns off).
5export type Brew = {
6 isOn: boolean
7 until: number
8 lastAt: number
9 activeAt: number
10 isAutoDeclined: boolean
11 isForever: boolean
12}
13
14declare module 'claude-code' {
15 interface PluginState {
16 'cache-caffeine': { brew: Brew }
17 }
18}
19