SLOPSHOPPER

cache-keeper

Keeps an idle session's prompt cache warm with a cache-served fork just before the TTL lapses, within limits you set.

commandtoaststatusmodeltimer
v0.3.0MITupdated 2026-10-09chrisvaillancourt/claude-cache-keeper
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cache-keeper
› 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-keeper: keep-warm auto (on) · cache warm until 09:53 · next ping 09:48 · 0 pings since last turn ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ cache-keeper: cache warm until 09:53 · keep-alive 09:48
README

cache-keeper

A Claude Code mod (function-hook plugin) that keeps an idle session's prompt cache warm. Just before the cache TTL lapses (default: 55 minutes after the last request), it sends a $.model.fork ping. The ping is served from the cache and adds nothing to the conversation.

On Opus 5.5, one cache read costs about 1/35–1/40 as much as re-caching the same prefix, measured against subscription usage. Pinging through a workday therefore costs much less than one cold restart.

Behavior

  • Keeps only the main conversation's cache warm. A ping ($.model.fork) always replays the main thread's last request, and subagent turns don't arm or reset the timer, so an idle subagent's cache is never pinged and just expires.
  • Arms a timer after each main-loop turn.
  • Pings at ttlMinutes − leadMinutes (60 − 5).
  • Waits for the next turn, without pinging, after a /model switch or a compaction: the new model or the compacted conversation has nothing cached yet, and a fork then would miss.
  • Retries a ping that fails with an API error once, 2 minutes later (sooner if the cache would lapse first). A second error in a row stops pinging until the next turn. An error is not a miss and benches nothing.
  • Stops when:
  • the cache has already expired (e.g. the machine slept);
  • Claude Code reports a 5-minute cache TTL (it says so on a model switch or resume). Pinging every few minutes costs more than a re-cache within the hour;
  • you've been idle longer than maxIdleHours (8). The window restarts on any main-loop turn, including ones you didn't type: a background agent's result arriving, a /loop wakeup. That's intended, because those turns use the main cache too. /keepwarm for|until extends the window to at least that time, and never shortens it;
  • the context is under minContextTokens (60k);
  • a ping misses the cache. A miss also benches automatic pings in every session until Claude Code's version changes, because forks can miss the conversation cache (anthropics/claude-code#100083) and a missed ping costs about a full re-cache. A /keepwarm now hit lifts the bench.
  • Checks itself: the first request of the first real turn after a pinged break longer than the TTL should read the context from cache. If it re-writes most of it, the pings didn't extend the main cache entry, and automatic pings are benched for that Claude Code version (log kind: verify). Later requests in that turn don't count, since they write what the turn added. There's no check after a compaction or model switch, since that turn re-writes the context anyway.
  • Keeps pinging whatever your plan usage. Past the plan's limit, extra usage bills per token, and a ping (a cache read, about 0.1× the input price) costs about a twentieth of the re-cache it saves (a 1-hour cache write, about 2×). If you're blocked at the limit instead, the ping fails with an API error and pinging stops until the next turn, with no bench.
  • Skips headless sessions (-p, SDK).
  • Logs to ~/.claude/cache-keeper/<session-id>.jsonl:
  • every ping: token usage, plan-usage percentage before and after, and API-equivalent cost before and after;
  • every stop: the reason, context size, plan usage, model and Claude Code version. off is logged once per switch to off, not after every turn.

Command

/keepwarm [status | on | off | auto | now | for 3h | until 18:00]

  • on / off / auto: keep warm always, never, or as the enabled option says. Each clears a for/until window.
  • for 3h / until 18:00: keep warm at least that long, even when the mode is off. When the window ends, the mode and idle limit apply again.
  • now: ping right away and report what the cache served. It won't ping after a model switch or compaction, when nothing is cached yet.

Install

claude plugin marketplace add chrisvaillancourt/claude-cache-keeper
claude plugin install cache-keeper@cache-keeper --scope user

Or from inside Claude Code: /plugin install cache-keeper --marketplace chrisvaillancourt/claude-cache-keeper.

To work on it locally, add your clone as the marketplace instead (claude plugin marketplace add <path to clone>). The plugin is read from that folder; after editing, run /reload-plugins.

Update

claude plugin update cache-keeper@cache-keeper

Then restart Claude Code. If it says the plugin is already at the latest version but a newer release exists, refresh the marketplace first and run the update again:

claude plugin marketplace update cache-keeper
claude plugin update cache-keeper@cache-keeper

Develop

claude plugin validate .
claude plugin test .

Commit messages follow Conventional Commits (feat:, fix:, docs:, ...).

License

MIT. See LICENSE.

Source 3 files
hooks/register.ts 423 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, ModelUsage, PluginOptions, Register, SessionUsage, Timer } from 'claude-code'
3
4import { classifyPing, decide, parseKeepwarmArgs, retryAt } from './policy'
5import type { Config, PingRecord, Session } from '../types'
6
7const MIN = 60_000
8const HOUR = 60 * MIN
9
10const PING_PROMPT =
11  '[cache-keeper keep-alive] This is an automated ping to keep the prompt cache warm. Reply with exactly: ok'
12
13const INITIAL: Session = {
14  mode: 'auto',
15  untilMs: null,
16  lastRequestAt: null,
17  lastTurnAt: null,
18  isTurnRunning: false,
19  turnId: null,
20  cacheTtl: null,
21  isCompacted: false,
22  pings: 0,
23  pingErrors: 0,
24  lastPing: null,
25  stopReason: null,
26  probe: null,
27}
28
29const sessionAtom = atom({ plugin: 'cache-keeper', key: 'session' } as const, INITIAL)
30
31// Module variables reset on a hot reload; session.start fires again then and
32// reschedules from $.state, which survives.
33let config: Config = configFrom({})
34let isActive = false
35let isPinging = false
36let timer: Timer | null = null
37
38function num(v: unknown, fallback: number) {
39  return typeof v === 'number' && Number.isFinite(v) ? v : fallback
40}
41
42function configFrom(options: PluginOptions): Config {
43  return {
44    enabled: options.enabled !== false,
45    ttlMs: num(options.ttlMinutes, 60) * MIN,
46    leadMs: num(options.leadMinutes, 5) * MIN,
47    maxIdleMs: num(options.maxIdleHours, 8) * HOUR,
48    minContextTokens: num(options.minContextTokens, 60_000),
49  }
50}
51
52function hhmm(ms: number) {
53  const d = new Date(ms)
54  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
55}
56
57function kTokens(n: number) {
58  return `${Math.round(n / 1000)}k`
59}
60
61function limitsOf(u: SessionUsage) {
62  return u.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed }))
63}
64
65function cancelTimer() {
66  timer?.cancel()
67  timer = null
68}
69
70/** Appends one JSON line to ~/.claude/cache-keeper/<session id>.jsonl; best effort. */
71async function appendLog($: EngineInterface, record: Record<string, unknown>) {
72  try {
73    const home = await $.env.get('HOME')
74    if (!home) return
75    const path = `${home}/.claude/cache-keeper/${await $.session.id()}.jsonl`
76    const before = (await $.fs.exists(path)) ? await $.fs.read(path) : ''
77    const line = JSON.stringify({ ts: new Date(await $.clock.now()).toISOString(), ...record })
78    await $.fs.write(path, `${before}${line}\n`)
79  } catch {
80    // Logging must never stop the keeper.
81  }
82}
83
84/** What a stop line needs to be audited later: context, plan usage, model and version. */
85async function logContext($: EngineInterface) {
86  try {
87    const usage = await $.session.usage()
88    return {
89      contextTokens: usage.context.tokens ?? null,
90      limits: limitsOf(usage),
91      model: await $.session.model(),
92      version: (await $.session.version()).version,
93    }
94  } catch {
95    return {}
96  }
97}
98
99/**
100 * Logs a stop when its reason differs from the current one, so a stop that
101 * holds across turns (off) logs once. A stop ends only when the keeper is
102 * active again: waiting for a ping, or after a hit.
103 */
104async function stop($: EngineInterface, reason: string, extra: Record<string, unknown> = {}) {
105  const s = await read($, sessionAtom)
106  if (s.stopReason !== reason) {
107    await update($, sessionAtom, cur => ({ ...cur, stopReason: reason }))
108    await appendLog($, { kind: 'stop', reason, pings: s.pings, ...(await logContext($)), ...extra })
109  }
110  $.ui.status(reason === 'off' ? undefined : `cache-keeper: stopped (${reason})`)
111}
112
113/**
114 * A fork that missed the cache (anthropics/claude-code#100083) costs about a
115 * full re-cache, and a fork that hit but didn't extend the main entry's TTL
116 * buys nothing. Either benches automatic pings, in every session, until
117 * Claude Code's version changes. A manual `/keepwarm now` hit lifts a miss.
118 */
119async function isBenched($: EngineInterface) {
120  const version = (await $.session.version()).version
121  const miss = (await $.store.get('forkMiss')) as { version?: string } | undefined
122  const refreshFail = (await $.store.get('refreshFail')) as { version?: string } | undefined
123  return miss?.version === version || refreshFail?.version === version
124}
125
126/**
127 * Judges the first request of the first real turn after a pinged break longer
128 * than the TTL: had the pings not refreshed the main entry, it re-writes most
129 * of the context. Only the first request counts; later ones in the turn write
130 * what the turn added.
131 */
132async function verifyRefresh($: EngineInterface, probe: NonNullable<Session['probe']>, usage: ModelUsage) {
133  const verdict = usage.cache_creation_input_tokens < 0.5 * probe.contextTokens ? 'warm' : 'cold'
134  const version = (await $.session.version()).version
135  await appendLog($, {
136    kind: 'verify',
137    verdict,
138    ...probe,
139    cacheRead: usage.cache_read_input_tokens,
140    cacheWrite: usage.cache_creation_input_tokens,
141    version,
142  })
143  const at = await $.clock.now()
144  if (verdict === 'cold') {
145    await $.store.set('refreshFail', { version, at })
146    $.ui.toast('cache-keeper: pings did not keep the cache warm on this version; automatic pings paused')
147  } else {
148    await $.store.set('refreshVerified', { version, at })
149  }
150}
151
152/** Pings once. A manual ping's error doesn't count toward the automatic retry. */
153async function ping($: EngineInterface, isManual = false): Promise<PingRecord> {
154  isPinging = true
155  try {
156    const before = await $.session.usage()
157    const result = await $.model.fork({ prompt: PING_PROMPT })
158    const now = await $.clock.now()
159    const after = await $.session.usage()
160    // Usage that counted a prompt says whether the cache served the fork,
161    // whatever ended it. An api-error whose one request was refused carries
162    // all zeros: that's an error, not a miss.
163    const counted: ModelUsage | undefined = 'usage' in result ? result.usage : undefined
164    const prompt = counted
165      ? counted.cache_read_input_tokens + counted.cache_creation_input_tokens + counted.input_tokens
166      : 0
167    const usage = prompt > 0 ? counted : undefined
168    const outcome = usage ? classifyPing(usage) : 'error'
169    const record: PingRecord = {
170      at: now,
171      outcome,
172      cacheRead: usage?.cache_read_input_tokens ?? 0,
173      cacheWrite: usage?.cache_creation_input_tokens ?? 0,
174      input: usage?.input_tokens ?? 0,
175      output: usage?.output_tokens ?? 0,
176      ...(result.isAnswered ? {} : { detail: result.reason }),
177    }
178    const s = await update($, sessionAtom, cur => ({
179      ...cur,
180      lastPing: record,
181      pingErrors: outcome !== 'error' ? 0 : isManual ? cur.pingErrors : cur.pingErrors + 1,
182      ...(outcome === 'hit' ? { lastRequestAt: now, pings: cur.pings + 1, stopReason: null } : {}),
183    }))
184    await appendLog($, {
185      kind: 'ping',
186      ...record,
187      ping: s.pings,
188      idleMinutes: s.lastTurnAt === null ? null : Math.round((now - s.lastTurnAt) / MIN),
189      contextTokens: before.context.tokens ?? null,
190      limitsBefore: limitsOf(before),
191      limitsAfter: limitsOf(after),
192      costBefore: before.cost?.usd ?? null,
193      costAfter: after.cost?.usd ?? null,
194    })
195    if (outcome === 'miss') {
196      await $.store.set('forkMiss', {
197        version: (await $.session.version()).version,
198        at: now,
199        cacheRead: record.cacheRead,
200        cacheWrite: record.cacheWrite,
201      })
202    } else if (outcome === 'hit') {
203      await $.store.delete('forkMiss')
204    }
205    if (outcome === 'hit') $.ui.toast(`cache-keeper: kept ${kTokens(record.cacheRead)} cached (ping ${s.pings})`)
206    return record
207  } finally {
208    isPinging = false
209  }
210}
211
212/** Decides what the session's cache needs now and acts: wait, ping, or stop. */
213async function schedule($: EngineInterface): Promise<void> {
214  cancelTimer()
215  if (!isActive || isPinging) return
216
217  const s = await read($, sessionAtom)
218  const now = await $.clock.now()
219  const usage = await $.session.usage()
220  const d = decide(s, now, { contextTokens: usage.context.tokens ?? 0 }, config)
221
222  switch (d.action) {
223    case 'idle':
224      $.ui.status(undefined)
225      return
226    case 'wait':
227      if (s.stopReason !== null) await update($, sessionAtom, cur => ({ ...cur, stopReason: null }))
228      $.ui.status(`cache warm until ${hhmm(d.at + config.leadMs)} · keep-alive ${hhmm(d.at)}`)
229      timer = $.clock.after(d.at - now, () => void schedule($))
230      return
231    case 'stop':
232      await stop($, d.reason)
233      return
234    case 'ping': {
235      if (await isBenched($)) {
236        await stop($, 'fork-miss-on-this-version')
237        return
238      }
239      const r = await ping($)
240      if (r.outcome === 'hit') return schedule($)
241      // One retry for a transient failure (an overloaded API, a dropped connection).
242      if (r.outcome === 'error' && (await read($, sessionAtom)).pingErrors < 2) return retryLater($, r)
243      await stop($, r.outcome === 'miss' ? 'cache-miss' : 'error', { detail: r.detail ?? null })
244      return
245    }
246  }
247}
248
249/** After a failed ping: tries again at retryAt, or stops when the cache would lapse first. */
250async function retryLater($: EngineInterface, r: PingRecord) {
251  const now = await $.clock.now()
252  const at = retryAt(await read($, sessionAtom), now, config)
253  if (at === null) return stop($, 'error', { detail: r.detail ?? null })
254  $.ui.status(`cache-keeper: ping failed, retrying at ${hhmm(at)}`)
255  timer = $.clock.after(at - now, () => void schedule($))
256}
257
258async function statusText($: EngineInterface) {
259  const s = await read($, sessionAtom)
260  const now = await $.clock.now()
261  const parts = [`keep-warm ${s.mode}${s.mode === 'auto' ? (config.enabled ? ' (on)' : ' (off)') : ''}`]
262  if (s.lastRequestAt !== null) {
263    const expiresAt = s.lastRequestAt + config.ttlMs
264    parts.push(now < expiresAt ? `cache warm until ${hhmm(expiresAt)}` : `cache likely cold since ${hhmm(expiresAt)}`)
265    if (timer !== null) parts.push(`next ping ${hhmm(expiresAt - config.leadMs)}`)
266  }
267  if (s.untilMs !== null && s.untilMs > now) parts.push(`keeping warm until ${hhmm(s.untilMs)}`)
268  parts.push(`${s.pings} ping${s.pings === 1 ? '' : 's'} since last turn`)
269  if (s.lastPing) {
270    parts.push(`last ping ${hhmm(s.lastPing.at)} ${s.lastPing.outcome} (${kTokens(s.lastPing.cacheRead)} cached)`)
271  }
272  if (s.stopReason) parts.push(`stopped: ${s.stopReason}`)
273  return parts.join(' · ')
274}
275
276export const register: Register = (on, options) => {
277  config = configFrom(options)
278  isActive = false
279  isPinging = false
280  timer = null
281
282  on('session.start', async ($, e, next) => {
283    const result = await next(e)
284    isActive = e.isInteractive
285    if (!isActive) return result
286    await $.command.register({
287      name: 'keepwarm',
288      description: 'Prompt-cache keep-alive: status, on, off, auto, now, for <n>h, until HH:MM',
289      argumentHint: '[status|on|off|auto|now|for 3h|until 18:00]',
290    })
291    // Spread over INITIAL so state saved by an older version gains the fields added since.
292    await update($, sessionAtom, s => ({ ...INITIAL, ...s, isTurnRunning: false, turnId: null }))
293    await schedule($)
294    return result
295  })
296
297  on('turn.start', async ($, e, next) => {
298    cancelTimer()
299    const now = await $.clock.now()
300    const s = await read($, sessionAtom)
301    const isProbe =
302      s.pings > 0 &&
303      !s.isCompacted &&
304      s.lastTurnAt !== null &&
305      s.lastRequestAt !== null &&
306      now - s.lastTurnAt > config.ttlMs &&
307      now - s.lastRequestAt < config.ttlMs
308    const probe = isProbe
309      ? {
310          contextTokens: (await $.session.usage()).context.tokens ?? 0,
311          idleMinutes: Math.round((now - (s.lastTurnAt ?? now)) / MIN),
312          pings: s.pings,
313        }
314      : null
315    await update($, sessionAtom, cur => ({ ...cur, isTurnRunning: true, turnId: e.turnId, probe }))
316    return next(e)
317  })
318
319  on('turn.step', async function* ($, e, next) {
320    const result = yield* next(e)
321    if (e.agentId !== undefined) return result
322    try {
323      const s = await read($, sessionAtom)
324      if (s.turnId !== e.turnId) return result
325      if (s.isCompacted) await update($, sessionAtom, cur => ({ ...cur, isCompacted: false }))
326      if (e.index === 0 && s.probe !== null) {
327        await update($, sessionAtom, cur => ({ ...cur, probe: null }))
328        if (result.usage !== null) await verifyRefresh($, s.probe, result.usage)
329      }
330    } catch {
331      // The check is best effort; never fail the turn over it.
332    }
333    return result
334  })
335
336  on('turn.complete', async ($, e, next) => {
337    const result = await next(e)
338    if (e.agentId !== undefined) return result
339    // A ping's fork may raise a turn.complete of its own: while one runs, only
340    // the main turn whose start this module saw counts.
341    const { turnId } = await read($, sessionAtom)
342    if (isPinging && e.turnId !== turnId) return result
343    const now = await $.clock.now()
344    await update($, sessionAtom, s => ({
345      ...s,
346      probe: null,
347      isTurnRunning: false,
348      turnId: null,
349      lastRequestAt: now,
350      lastTurnAt: now,
351      pings: 0,
352      pingErrors: 0,
353      untilMs: s.untilMs !== null && s.untilMs <= now ? null : s.untilMs,
354    }))
355    await schedule($)
356    return result
357  })
358
359  // A compaction replaces the conversation: the next request shares no cached
360  // prefix with the last one, so there is nothing to keep warm, and its first
361  // request can't show whether pings worked. A precompute installs nothing.
362  // This hook and the next only observe: on a failure, `.catch` lets the event
363  // go on as it settled.
364  on('session.compact', async ($, e, next) => {
365    const result = await next(e)
366    if (e.agentId !== undefined || e.trigger === 'precompute' || result.messages === undefined) return result
367    await update($, sessionAtom, s => ({ ...s, isCompacted: true, probe: null }))
368    await schedule($)
369    return result
370  }).catch(($, e, next) => next(e))
371
372  // A new model has no cache entry until its first request, and a fork before
373  // then would miss and bench pings. The engine also says the cache's TTL here.
374  on('classic.PostModelSwitch', async ($, e, next) => {
375    const result = await next(e)
376    if (e.agent_id !== undefined) return result
377    const isNewModel = e.from_model !== e.to_model
378    await update($, sessionAtom, s => ({
379      ...s,
380      cacheTtl: e.cache_ttl,
381      ...(isNewModel ? { lastRequestAt: null, probe: null } : {}),
382    }))
383    await schedule($)
384    return result
385  }).catch(($, e, next) => next(e))
386
387  on('command.run', { command: 'keepwarm' }, async ($, e) => {
388    const cmd = parseKeepwarmArgs(e.args, await $.clock.now(), new Date().getTimezoneOffset())
389    switch (cmd.kind) {
390      case 'error':
391        return { text: cmd.message }
392      case 'status':
393        return { text: await statusText($) }
394      case 'mode':
395        await update($, sessionAtom, s => ({ ...s, mode: cmd.mode, untilMs: null }))
396        await schedule($)
397        return { text: `Keep-warm ${cmd.mode}. ${await statusText($)}` }
398      case 'until':
399        await update($, sessionAtom, s => ({ ...s, untilMs: cmd.untilMs }))
400        await schedule($)
401        return { text: `Keeping warm until ${hhmm(cmd.untilMs)}. ${await statusText($)}` }
402      case 'now': {
403        // After a model switch or compaction a fork would re-write the context
404        // and read as a miss, benching pings everywhere.
405        const s = await read($, sessionAtom)
406        if (s.lastRequestAt === null || s.isCompacted) {
407          return { text: 'Nothing cached to keep warm yet: the next turn caches the conversation.' }
408        }
409        cancelTimer()
410        const r = await ping($, true)
411        const now = await $.clock.now()
412        if (r.outcome === 'miss') await stop($, 'cache-miss', { detail: r.detail ?? null })
413        // Inside the ping window, an error waits for the retry rather than pinging again at once.
414        else if (r.outcome === 'error' && now >= s.lastRequestAt + config.ttlMs - config.leadMs) await retryLater($, r)
415        else await schedule($)
416        return {
417          text: `Ping ${r.outcome}: ${kTokens(r.cacheRead)} read from cache, ${kTokens(r.cacheWrite)} written, ${r.output} output tokens.`,
418        }
419      }
420    }
421  })
422}
423
hooks/policy.ts 110 lines
1import type { ModelUsage } from 'claude-code'
2
3import type { Config, Mode, Session } from '../types'
4
5const MIN = 60_000
6const HOUR = 60 * MIN
7const DAY = 24 * HOUR
8
9export type Facts = {
10  contextTokens: number
11}
12
13export type StopReason = 'off' | 'expired' | 'short-ttl' | 'idle-limit' | 'small-context'
14
15export type Decision =
16  | { action: 'idle' }
17  | { action: 'wait'; at: number }
18  | { action: 'ping' }
19  | { action: 'stop'; reason: StopReason }
20
21/**
22 * What to do about the session's cache at `now`. Pure: the caller supplies
23 * the session's state, the context size and the config.
24 */
25export const decide = (s: Session, now: number, facts: Facts, config: Config): Decision => {
26  const isInWindow = s.untilMs !== null && now <= s.untilMs
27  const isOn = isInWindow || s.mode === 'on' || (s.mode === 'auto' && config.enabled)
28  if (!isOn) return { action: 'stop', reason: 'off' }
29  if (s.isTurnRunning || s.lastRequestAt === null || s.isCompacted) return { action: 'idle' }
30  // A five-minute cache needs a ping every few minutes: within the hour that costs more than a re-cache.
31  if (s.cacheTtl === '5m') return { action: 'stop', reason: 'short-ttl' }
32
33  const expiresAt = s.lastRequestAt + config.ttlMs
34  if (now >= expiresAt) return { action: 'stop', reason: 'expired' }
35
36  const pingAt = expiresAt - config.leadMs
37  if (now < pingAt) return { action: 'wait', at: pingAt }
38
39  // lastTurnAt moves on every main-loop turn, typed or not (a background
40  // agent's result, a /loop wakeup): those extend the idle window by design.
41  // A /keepwarm for|until window extends that, never shortens it.
42  const keepUntil = Math.max(s.untilMs ?? 0, (s.lastTurnAt ?? s.lastRequestAt) + config.maxIdleMs)
43  if (now > keepUntil) return { action: 'stop', reason: 'idle-limit' }
44  if (facts.contextTokens < config.minContextTokens) return { action: 'stop', reason: 'small-context' }
45  // No plan-usage ceiling: past the limit, extra usage bills per token, and a
46  // ping costs about a twentieth of the re-cache it saves. A blocked ping is
47  // an API error, which stops pinging without benching.
48
49  return { action: 'ping' }
50}
51
52const RETRY_MS = 2 * MIN
53const RETRY_MARGIN_MS = 30_000
54
55/**
56 * When to retry a failed ping: two minutes on, or halfway to expiry when the
57 * cache would lapse first; null when too little of it is left.
58 */
59export const retryAt = (s: Session, now: number, config: Config): number | null => {
60  if (s.lastRequestAt === null) return null
61  const expiresAt = s.lastRequestAt + config.ttlMs
62  const at = Math.min(now + RETRY_MS, now + (expiresAt - now) / 2)
63  return expiresAt - at >= RETRY_MARGIN_MS ? at : null
64}
65
66/** A fork the cache served at least 80% of is a hit; otherwise it paid for the prefix. */
67export const classifyPing = (u: ModelUsage): 'hit' | 'miss' => {
68  const prompt = u.cache_read_input_tokens + u.cache_creation_input_tokens + u.input_tokens
69  return prompt > 0 && u.cache_read_input_tokens / prompt >= 0.8 ? 'hit' : 'miss'
70}
71
72export type KeepwarmCommand =
73  | { kind: 'status' }
74  | { kind: 'now' }
75  | { kind: 'mode'; mode: Mode }
76  | { kind: 'until'; untilMs: number }
77  | { kind: 'error'; message: string }
78
79export const USAGE = 'Usage: /keepwarm [status | on | off | auto | now | for <n>h|<n>m | until HH:MM]'
80
81/**
82 * Parses /keepwarm's arguments. `tzOffsetMinutes` is Date#getTimezoneOffset():
83 * minutes to add to local time to get UTC.
84 */
85export const parseKeepwarmArgs = (args: string, now: number, tzOffsetMinutes: number): KeepwarmCommand => {
86  const [head, arg] = args.trim().toLowerCase().split(/\s+/).filter(Boolean)
87
88  if (head === undefined || head === 'status') return { kind: 'status' }
89  if (head === 'now') return { kind: 'now' }
90  if (head === 'on' || head === 'off' || head === 'auto') return { kind: 'mode', mode: head }
91
92  if (head === 'for' && arg !== undefined) {
93    const m = /^(\d+(?:\.\d+)?)(h|m)$/.exec(arg)
94    if (m) return { kind: 'until', untilMs: now + Number(m[1]) * (m[2] === 'h' ? HOUR : MIN) }
95  }
96
97  if (head === 'until' && arg !== undefined) {
98    const m = /^(\d{1,2}):(\d{2})$/.exec(arg)
99    if (m && Number(m[1]) < 24 && Number(m[2]) < 60) {
100      const offset = tzOffsetMinutes * MIN
101      const localMidnight = Math.floor((now - offset) / DAY) * DAY
102      let untilMs = localMidnight + Number(m[1]) * HOUR + Number(m[2]) * MIN + offset
103      if (untilMs <= now) untilMs += DAY
104      return { kind: 'until', untilMs }
105    }
106  }
107
108  return { kind: 'error', message: USAGE }
109}
110
types/index.d.ts 51 lines
1export type Mode = 'auto' | 'on' | 'off'
2
3export type Config = {
4  enabled: boolean
5  ttlMs: number
6  leadMs: number
7  maxIdleMs: number
8  minContextTokens: number
9}
10
11export type PingRecord = {
12  at: number
13  outcome: 'hit' | 'miss' | 'error'
14  cacheRead: number
15  cacheWrite: number
16  input: number
17  output: number
18  detail?: string
19}
20
21export type Session = {
22  mode: Mode
23  /** A /keepwarm for|until window: keeps warm at least this long, whatever the mode. */
24  untilMs: number | null
25  /** When the cache was last refreshed: the end of a main turn or a ping. */
26  lastRequestAt: number | null
27  /** When the last real (non-ping) main turn ended. */
28  lastTurnAt: number | null
29  isTurnRunning: boolean
30  /** The main turn in progress, from its turn.start; null between turns. */
31  turnId: string | null
32  /** The prompt-cache TTL the engine last reported (on a model switch or resume). */
33  cacheTtl: '5m' | '1h' | null
34  /** Compacted since the last main-loop request: nothing cached matches the next one. */
35  isCompacted: boolean
36  /** Pings since the last real turn. */
37  pings: number
38  /** Ping errors in a row since the last hit or real turn. */
39  pingErrors: number
40  lastPing: PingRecord | null
41  stopReason: string | null
42  /** Set at the start of a real turn that follows a pinged break longer than the TTL. */
43  probe: { contextTokens: number; idleMinutes: number; pings: number } | null
44}
45
46declare module 'claude-code' {
47  interface PluginState {
48    'cache-keeper': { session: Session }
49  }
50}
51