SLOPSHOPPER

cache-keepalive

Keeps the main thread's prompt cache warm while you are idle: one cheap fork ping just before the TTL runs out, capped, verified on every hit.

bandcommandtoaststatuspromptmodel
★ 3v0.6.0MITupdated 2026-10-17shdennlin/agent-plugins/plugins/cache-keepalive
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cache-keepalive
› 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 › /keepalive ⎿ cache-keepalive: Usage: /keepalive done | brb <minutes|hours|reset> | compact [off] | ping | status ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

cache-keepalive

Keeps the main thread's prompt cache warm while you are away. About five minutes before the cache TTL runs out, it sends one tool-less fork of the conversation ($.model.fork) that re-reads the cached prefix and restarts the TTL. The ping never lands in the transcript, so nothing needs rewinding.

By default it pings at most twice per idle stretch, so a lunch or a meeting comes back to a warm cache. Every ping is verified: if the fork does not read the prefix from cache, keepalive turns itself off for the session.

Requires Claude Code 2.1.289 or later (hook-module plugin API). The status widget targets ccstatusline 2.2.30.

Quick setup

Nothing is required: once the plugin loads, it keeps the cache warm. The rest is optional.

You wantSet up
Keepalive itselfLoad the plugin (below)required
The state always on screenA status line field and a refresh interval (docs/status-line.md)optional; /keepalive status works without it
A Telegram question once the pings run outBot token and telegramChatId (docs/telegram.md)optional; both are needed, or nothing is sent
Only your own answers to counttelegramUserIdoptional; without it anyone in the chat can answer

Load the plugin, one of:

# every session: add the folder to CLAUDE_CODE_PLUGIN_DIRS in ~/.claude/settings.json ("env" block),
# separated by ":" from any folders already listed
"CLAUDE_CODE_PLUGIN_DIRS": "/absolute/path/to/plugins/cache-keepalive"

# one session only
claude --plugin-dir /absolute/path/to/plugins/cache-keepalive

Then set options with /plugin configure cache-keepalive (sensitive ones included) or /config (search for keep). A session started with --plugin-dir reads them from pluginConfigs["cache-keepalive"].options in settings.

Check it: /keepalive status shows the phase, the TTL it read, and telegram: on when Telegram is set up.

Commands

CommandWhat it does
/keepalive statusPhase, TTL, context size, pings so far, next ping and expiry times
/keepalive brb <minutes or hours>Keep warm for longer this idle stretch, e.g. brb 180 allows 4 pings and brb 24h 27. Resets at your next prompt
/keepalive brb resetBack to the configured maxPings for this idle stretch. Pings already sent are not taken back
/keepalive doneStop pinging for this idle stretch. Resets at your next prompt
/keepalive compactArm a one-time compact for when keepalive runs out (below). compact off cancels
/keepalive pingFire a ping immediately instead of waiting for the schedule, for testing. Refused unless armed

In a terminal the replies are coloured (a past-break-even warning in yellow, errors in red, the phase in status by state); other surfaces get plain text. Typing /keepalive brb offers 180 as a dim completion; Right arrow accepts. When you come back to an expired cache, a one-line band above the prompt says how much the next request will rewrite; your next prompt or Dismiss clears it.

Options

Set in /config (or pluginConfigs["cache-keepalive"].options in settings):

OptionDefault
enabledtrueMaster switch
leadMinutes5Ping this many minutes before the TTL runs out
maxPings2Pings per idle stretch
minContextTokens50000Smaller contexts are not kept warm
compactLeadMinutes10An armed compact starts this many minutes before the TTL runs out
compactBeforeExpiryfalseCompact in that window every idle stretch, without arming each time
engineStatusfalseShow the state as a status entry under the prompt, for sessions without a status line
telegramBotTokenemptyBot token (sensitive); see Telegram
telegramChatIdemptyChat that receives the question
telegramUserIdemptyOnly this user's answers count

Compact before expiry

Run /keepalive compact before you leave, or before a /goal you will not watch. Keepalive pings as usual; once the pings run out, it compacts the conversation compactLeadMinutes (10) before the cache expires, while it is still warm. The summary request reads the cache instead of rewriting the whole prefix (98% of a 142k prefix read from cache, measured once), and your next prompt rewrites a small summary instead of the old context.

  • One time. It clears when it fires, with /keepalive compact off, or when you type a plain prompt (a toast says so). A slash command or a /goal continuation does not clear it.
  • /keepalive done skips the pings: the compact then runs about 50 minutes after the last turn on a 1h TTL. maxPings: 0 does the same for a /goal, which done would not survive.
  • A late timer (the Mac slept), a cancelled compaction or a ping that misses the cache means no compact; the cache just expires.

Flow chart, timeline and the edge cases: docs/compact.md.

Claude Code 2.1.299+ also compacts idle sessions on its own, at about 200k context tokens and 54 minutes idle, ahead of the same 1h cache TTL. Keepalive detects this (it is not a turn, so turn.complete never fires) and resets its own state instead of pinging a prefix that no longer exists. Below 200k tokens, or before 54 minutes idle, only keepalive's own pings and compactBeforeExpiry apply. If you want pings to preserve the full context instead of letting the engine summarize it out from under you, turn the built-in behaviour off with "idleCompaction": false in settings.json, or raise its threshold with CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS.

Cost

A ping re-reads the cached prefix at the cache-read price, a small fraction of one rewrite. The default two pings cost about 5% of a rewrite on Opus 5.5 (2.5% on Fable 5.1, 10% on Sonnet 5.5), so keeping warm pays off if you are even slightly likely to come back. Past the break-even (20 pings, about 18 h, on most models; 40 and 37 h on Opus 5.5; 80 and 73 h on Fable 5.1) the pings cost more than the one rewrite they avoid. Sessions under 50k tokens are not kept warm, and a 5-minute TTL turns keepalive off. Prices and the arithmetic: docs/cost.md.

Telegram (optional)

When the pings run out while you are away, keepalive can ask on Telegram whether to keep going: +1h, +3h, or let it expire, by button or by replying with minutes (120, 2h). It needs a bot token and a chat id. Setup: docs/telegram.md.

Seeing the state

Keepalive works without a status line: /keepalive status, the expired band and a toast when it turns itself off. For an always-visible state, bin/keepalive-cache is a drop-in for ccstatusline's Cache Timer, or a status line command of its own:

🟢58:54 kp 1/2 ✂03:12

The countdown, kp used/cap and ✂ (an armed compact, with the time it is due) are explained in docs/status-line.md, with the ccstatusline setup and the engineStatus option for sessions with no status line. Set statusLine.refreshInterval (30 seconds is enough), or the field only redraws on events.

Limits

  • No pings while the Mac sleeps: the process is asleep too. A timer that fires after the cache already expired skips the ping.
  • A resumed session (claude -r/--continue) arms itself right at session.start from the transcript'''s last cache-creating row, using that row'''s real write time rather than the moment you resumed — so a cache that actually expired while you were away shows expired, not a fresh 2-ping window.
  • A turn that ends in an error or refusal reads no usage and runs no pings, but an armed compact is still scheduled from the last good response, so a /goal that dies on an API error does not lose it.
  • A turn waiting on a permission prompt has not finished, so no ping is scheduled during it.
  • After a prefix change (/model, a plugin reload that changes the system prompt or tools) the next ping misses once, and keepalive turns off for the session.

More

docs/cost.mdPrices per model, ping vs rewrite, break-even
docs/compact.mdFlow chart, timeline and edge cases of the armed compact
docs/telegram.mdThe Telegram question and its setup
docs/status-line.mdccstatusline, your own status line, engineStatus
docs/PRD.mdDesign, decisions and their evidence

Development

claude plugin validate plugins/cache-keepalive
claude --plugin-dir plugins/cache-keepalive   # once, so the engine lays .claude-plugin/types/ for tsc
tsc -p plugins/cache-keepalive
claude plugin test plugins/cache-keepalive    # hook tests (tests/*.test.ts)
node --test plugins/cache-keepalive/tests/widget.test.cjs   # status widget tests
Source 3 files
hooks/register.tsx 972 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface as Engine, Register, Timer } from 'claude-code'
3
4import type { KeepaliveSession } from '../types'
5import { header, htmlEscape, keyboard, parseUpdate } from './telegram'
6
7// Keeps the main thread's prompt cache warm while the user is idle: one fork
8// ping shortly before the TTL runs out, capped per idle stretch, verified on
9// every hit. Display lives in the status line (bin/keepalive-cache reads the
10// per-session state file). $.ui.status is used only when engineStatus is on:
11// the engine draws it as its own warning-prefixed row under the prompt.
12
13const PING_PROMPT = 'Cache keep-alive ping, not a task. Reply with exactly: ok'
14const HIT_RATIO = 0.8
15const TAIL_BYTES = 262144
16const RETRY_MS = 30_000
17const STALE_FILE_MS = 7 * 24 * 60 * 60 * 1000
18const TTL_1H = 3600
19const TTL_5M = 300
20// /keepalive brb completions, the first one offered on an empty argument.
21const BRB_PRESETS = ['180', '60', '480']
22// Pings that cost as much as one 1h-cache rewrite: the 1h write price (2x input)
23// over the cache-read price, per the pricing page (checked 2026-10-07). Reads
24// are 0.1x input on every model but Claude Fable 5.1 / Mythos 5.1 (0.025x) and
25// Claude Opus 5.5 (0.05x).
26function breakEvenPings(model: string): number | null {
27  if (/(fable|mythos)-5-1/.test(model)) return 80
28  if (/opus-5-5/.test(model)) return 40
29  return /(fable|mythos|opus|sonnet|haiku)/.test(model) ? 20 : null
30}
31const TG_POLL_MS = 10_000
32const TG_API = 'https://api.telegram.org'
33const KEYCHAIN_SERVICE = 'claude-code.cache-keepalive'
34const KEYCHAIN_ACCOUNT = 'telegram-bot-token'
35
36const INITIAL: KeepaliveSession = {
37  phase: 'active',
38  offReason: null,
39  lastActivityAt: 0,
40  lastPingAt: 0,
41  pingsSent: 0,
42  maxPings: 2,
43  ttlSec: null,
44  contextTokens: 0,
45  transcriptPath: null,
46  isBandDismissed: false,
47  isOffToastShown: false,
48  tgAskMessageId: null,
49  isCompactArmed: false,
50}
51
52const session = atom({ plugin: 'cache-keepalive', key: 'session' } as const, INITIAL)
53
54type Config = {
55  enabled: boolean
56  leadMinutes: number
57  compactLeadMinutes: number
58  maxPings: number
59  minContextTokens: number
60  engineStatus: boolean
61  compactBeforeExpiry: boolean
62  telegramChatId: string
63  telegramUserId: string
64}
65
66// Module variables start over on a hot reload; the engine drops the old
67// timers with them, and session.start re-arms from $.state.
68let config: Config = {
69  enabled: true,
70  leadMinutes: 5,
71  compactLeadMinutes: 10,
72  maxPings: 2,
73  minContextTokens: 50000,
74  engineStatus: false,
75  compactBeforeExpiry: false,
76  telegramChatId: '',
77  telegramUserId: '',
78}
79let pingTimer: Timer | undefined
80let expiryTimer: Timer | undefined
81let compactTimer: Timer | undefined
82let isCompacting = false
83let isRetrying = false
84// ANSI colour in a command's reply: the terminal draws it (checked: bold, dim,
85// 16 colours, backgrounds and truecolor), other surfaces may show the codes.
86let isTerminal = false
87let sessionId = ''
88let stateDir = ''
89let projectsDir = ''
90// The dim completion tail this module last put after the prompt draft.
91let brbTail = ''
92let cwd = ''
93// Telegram: the resolved bot token (never written anywhere) and the poller.
94let tgTokenOption = ''
95let tgToken = ''
96let tgPoll: Timer | undefined
97let isPolling = false
98
99export const register: Register = (on, options) => {
100  config = {
101    enabled: options.enabled !== false,
102    leadMinutes: positiveNumber(options.leadMinutes, 5),
103    compactLeadMinutes: positiveNumber(options.compactLeadMinutes, 10),
104    maxPings: Math.max(0, Math.floor(positiveNumber(options.maxPings, 2, true))),
105    minContextTokens: positiveNumber(options.minContextTokens, 50000, true),
106    engineStatus: options.engineStatus === true,
107    compactBeforeExpiry: options.compactBeforeExpiry === true,
108    telegramChatId: String(options.telegramChatId ?? '').trim(),
109    telegramUserId: String(options.telegramUserId ?? '').trim(),
110  }
111  tgTokenOption = String(options.telegramBotToken ?? '').trim()
112
113  on('session.start', async ($, e, next) => {
114    await $.command.register({
115      name: 'keepalive',
116      description: 'Prompt-cache keepalive: done, brb <minutes|hours|reset>, compact [off], ping, status',
117      argumentHint: 'done | brb <minutes|hours|reset> | compact [off] | ping | status',
118    })
119    const configDir = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${(await $.env.get('HOME')) ?? ''}/.claude`
120    stateDir = `${configDir}/keepalive`
121    projectsDir = `${configDir}/projects/${e.cwd.replace(/[^A-Za-z0-9]/g, '-')}`
122    cwd = e.cwd
123    isTerminal = e.surface === 'terminal'
124    tgToken = await resolveTelegramToken($)
125    await bindSession($)
126    await rearm($)
127    await armFromResume($)
128    // After a reload, keep listening for the answer to a question still open.
129    if ((await read($, session)).tgAskMessageId !== null && isTelegramOn()) startPolling($)
130    await sweepStaleFiles($)
131    return next(e)
132  })
133
134  // The settings hook envelope carries the real transcript path; the one
135  // derived from cwd in bindSession is only the fallback.
136  on('classic.UserPromptSubmit', async ($, e, next) => {
137    const s = await read($, session)
138    if (e.transcript_path && e.transcript_path !== s.transcriptPath) {
139      await update($, session, v => ({ ...v, transcriptPath: e.transcript_path }))
140    }
141    // You are back: an armed compact was for the time you are away. Only a prompt
142    // you typed counts. `source` tells it from the engine's own turns (a /goal
143    // continuation is `system`) where the engine sends it; this build leaves it
144    // out (measured: undefined on typed prompts, and no event at all on a /goal
145    // continuation), so an absent source counts as typed. A slash command does
146    // not count: /goal and /keepalive status are typed too, and arming comes
147    // before /goal.
148    const isFromYou = e.source === undefined || e.source === 'user'
149    const isTyped = isFromYou && e.prompt.trim() !== '' && !e.prompt.trimStart().startsWith('/')
150    if (isTyped && s.isCompactArmed) {
151      await save($, v => ({ ...v, isCompactArmed: false }))
152      $.ui.toast('Armed compact cancelled: you are back. /keepalive compact arms it again.')
153    }
154    return next(e)
155  })
156
157  // Only the main loop raises turn.start; a subagent's run does not.
158  on('turn.start', async ($, e, next) => {
159    await bindSession($)
160    cancelTimers()
161    isRetrying = false
162    await closeAsk($, '↩️ Back at the keyboard.')
163    await save($, v => ({
164      ...v,
165      // Off stays off for the session, except when the off switch itself was
166      // turned back on (a config change reloads the module with new options).
167      ...(v.phase === 'off' && !(v.offReason === 'disabled' && config.enabled)
168        ? {}
169        : { phase: 'active' as const, offReason: null }),
170      pingsSent: 0,
171      maxPings: config.maxPings,
172      lastPingAt: 0,
173      isBandDismissed: false,
174    }))
175    return next(e)
176  })
177
178  on('turn.complete', async ($, e, next) => {
179    const result = await next(e)
180    if (e.agentId !== undefined) return result
181    await bindSession($)
182    await onMainTurnComplete($, e.reason)
183    return result
184  })
185
186  on('session.end', async ($, e, next) => {
187    cancelTimers()
188    await closeAsk($, 'Session ended.')
189    if (sessionId) {
190      await $.process.run(['rm', '-f', stateFile()]).catch(() => undefined)
191    }
192    return next(e)
193  })
194
195  // The engine's own compaction (over the context threshold, a prompt too
196  // long, or idle ahead of the cache TTL, added 2.1.299): not a turn, so
197  // turn.complete never tells the mod. Without this it would keep pinging a
198  // prefix that no longer exists, read the miss as a ttl-mismatch, and turn
199  // itself off for the rest of the session. Cancel first: compaction takes
200  // about a minute at 140k tokens, long enough to overlap a ping or expiry
201  // timer due during it.
202  on('session.compact', { trigger: 'auto' }, async ($, e, next) => {
203    if (e.agentId !== undefined) return next(e) // a subagent's or fork's own transcript
204    cancelTimers()
205    const result = await next(e)
206    if (result.skip !== undefined) {
207      await rearm($) // vetoed: nothing changed, restore the schedule
208      return result
209    }
210    const tokens = result.tokensAfter ?? (await read($, session)).contextTokens
211    await closeAsk($, 'Compacted automatically before the cache expired.')
212    await save($, v => ({ ...v, phase: 'active', contextTokens: tokens, isCompactArmed: false }))
213    $.ui.toast('Compacted automatically before the cache expired.')
214    return result
215  })
216
217  // Fish-style completion for /keepalive brb: a dim tail after the draft,
218  // Right arrow to accept. Tab and Up/Down never reach prompt.edit (the
219  // editor keeps them), and Enter runs what the box shows, tail included.
220  on('prompt.edit', async ($, e, next) => {
221    const shown = brbTail
222    brbTail = ''
223    const hasTail = shown !== '' && e.text.endsWith(shown) && e.cursor === e.text.length - shown.length
224    if (hasTail && e.key?.key === 'right') {
225      return { text: e.text, cursor: e.text.length }
226    }
227    let draft = e
228    if (hasTail) {
229      // Take the tail back out so the edit applies to what was typed.
230      const text = e.text.slice(0, -shown.length)
231      draft = { ...e, text, start: Math.min(e.start, text.length), end: Math.min(e.end, text.length) }
232    }
233    const box = await next(draft)
234    const tail = brbCompletion(box.text, box.cursor)
235    if (!tail) return box
236    brbTail = tail
237    const at = box.text.length
238    return {
239      ...box,
240      text: box.text + tail,
241      decorations: [...(box.decorations ?? []), { start: at, end: at + tail.length, dimColor: true }],
242    }
243  })
244
245  on('command.run', { command: 'keepalive' }, async ($, e) => ({ text: await runCommand($, e.args) }))
246
247  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
248    const s = await read($, session)
249    if (e.props.hasSurvey || s.phase !== 'expired' || s.isBandDismissed) {
250      return next(e)
251    }
252    const { Box, Text, Button } = $.ui.resolve(e)
253    const rate = s.ttlSec === TTL_5M ? 1.25 : 2
254    const tokens = s.contextTokens
255    return (
256      <Box>
257        <Text color="cyan">
258          ❄ Cache expired at {clockTime(cacheStart(s) + (s.ttlSec ?? TTL_1H) * 1000)} · next request rewrites ~
259          {kilo(tokens)} (≈ {kilo(tokens * rate)} at the write rate){' '}
260        </Text>
261        <Button
262          key="dismiss"
263          label="Dismiss"
264          role="dismiss"
265          onPress={() => update($, session, v => ({ ...v, isBandDismissed: true }))}
266        />
267      </Box>
268    )
269  })
270}
271
272async function onMainTurnComplete($: Engine, reason: string) {
273  const s = await read($, session)
274  if (s.phase === 'off') return writeStateFile($, s)
275  if (!config.enabled) {
276    await save($, v => ({ ...v, phase: 'off', offReason: 'disabled' }))
277    return
278  }
279  const now = await $.clock.now()
280  if (reason === 'error' || reason === 'refusal') {
281    // An armed compact must still run (a /goal can end on an error while you
282    // sleep). No usage is read and no pings run, since what the cache holds is
283    // uncertain; the clock stays at the last good response so the lead window is
284    // not pushed past the real expiry.
285    const isArmed = s.isCompactArmed && s.ttlSec !== null && s.lastActivityAt > 0 && s.contextTokens >= config.minContextTokens
286    if (isArmed) {
287      await save($, v => ({ ...v, phase: 'capped' }))
288      await rearm($)
289    } else {
290      await save($, v => ({ ...v, phase: 'active', lastActivityAt: now }))
291    }
292    return
293  }
294  // An aborted turn may carry no usage: keep the last known values then.
295  const usage = await $.session.usage().catch(() => undefined)
296  const contextTokens = usage?.context?.tokens ?? s.contextTokens
297  const ttlSec = (await readTtl($, s.transcriptPath)) ?? s.ttlSec
298  await applyArmedState($, { lastActivityAt: now, contextTokens, ttlSec })
299}
300
301// Shared by a just-completed turn (lastActivityAt = now) and a resumed
302// session arming straight from the transcript (lastActivityAt = the real
303// write time of its last cache-creating row, so an already-expired cache
304// does not get a fresh window just because the process restarted).
305async function applyArmedState($: Engine, input: { lastActivityAt: number; contextTokens: number; ttlSec: number | null }): Promise<void> {
306  const s = await read($, session)
307  const base = { ...s, ...input }
308
309  if (input.ttlSec === TTL_5M) {
310    // 13 pings an hour at 0.1x cost more than one 1.25x rewrite.
311    await save($, () => ({ ...base, phase: 'off', offReason: '5m-ttl' }))
312    return
313  }
314  if (input.contextTokens < config.minContextTokens) {
315    await save($, () => ({ ...base, phase: 'small' }))
316    return
317  }
318  if (input.ttlSec === null) {
319    // Not read yet: no schedule. The next turn tries again.
320    await save($, () => ({ ...base, phase: 'active' }))
321    return
322  }
323  await save($, () => ({ ...base, phase: base.maxPings > 0 ? 'armed' : 'capped' }))
324  await rearm($)
325}
326
327// On session.start (a reload or a resume), $.state may already be the
328// INITIAL default: a process restart does not carry it over. Arm straight
329// from the transcript when it has a cache-creating row with a real
330// timestamp, instead of waiting for a turn that may never come if you only
331// read the status. A row with no timestamp (nothing resumed yet, e.g. a
332// genuinely new session) leaves the state untouched for the next turn.
333async function armFromResume($: Engine): Promise<void> {
334  const s = await read($, session)
335  if (s.phase === 'off' || !config.enabled) return
336  const tail = await readTranscriptTail($, s.transcriptPath)
337  if (!tail || tail.timestampMs === null) return
338  const usage = await $.session.usage().catch(() => undefined)
339  const contextTokens = usage?.context?.tokens ?? s.contextTokens
340  await applyArmedState($, { lastActivityAt: tail.timestampMs, contextTokens, ttlSec: tail.ttlSec })
341}
342
343// Schedules the next ping (armed) and the expiry (armed or capped) from state.
344async function rearm($: Engine) {
345  cancelTimers()
346  const s = await read($, session)
347  if (s.ttlSec === null) return
348  const now = await $.clock.now()
349  const expiresAt = cacheStart(s) + s.ttlSec * 1000
350  // /keepalive done stops the pings but an armed compact still runs, once, in
351  // the first lead window.
352  if (s.phase === 'stopped' && s.isCompactArmed) {
353    compactTimer = $.clock.after(Math.max(0, expiresAt - config.compactLeadMinutes * 60_000 - now), () => {
354      void compact($)
355    })
356    return
357  }
358  if (s.phase !== 'armed' && s.phase !== 'capped') return
359  if (s.phase === 'armed') {
360    const pingAt = expiresAt - config.leadMinutes * 60_000
361    pingTimer = $.clock.after(Math.max(0, pingAt - now), () => {
362      void ping($)
363    })
364  }
365  expiryTimer = $.clock.after(Math.max(0, expiresAt - now), () => {
366    void expire($)
367  })
368  // Pings used up: compact while the cache is still warm, so the summary
369  // request reads it instead of rewriting the whole prefix.
370  if (s.phase === 'capped' && (config.compactBeforeExpiry || s.isCompactArmed)) {
371    compactTimer = $.clock.after(Math.max(0, expiresAt - config.compactLeadMinutes * 60_000 - now), () => {
372      void compact($)
373    })
374  }
375}
376
377// Fires from the lead window, only while capped and still warm. It cannot run
378// from a command (the host refuses it under the command's turn), which is why
379// /keepalive compact only arms it.
380async function compact($: Engine) {
381  if (isCompacting) return
382  const s = await read($, session)
383  const isStoppedArmed = s.phase === 'stopped' && s.isCompactArmed
384  if ((s.phase !== 'capped' && !isStoppedArmed) || s.ttlSec === null) return
385  if ((await $.clock.now()) >= cacheStart(s) + s.ttlSec * 1000) {
386    if (!isStoppedArmed) await expire($) // fired late (the Mac slept): the cache is gone
387    return
388  }
389  isCompacting = true
390  let text: string
391  try {
392    const r = await $.session.compact()
393    if (r.skip !== undefined) {
394      text = `Compact skipped: ${r.skip}`
395    } else {
396      const tokens = r.tokensAfter ?? s.contextTokens
397      cancelTimers()
398      // The new prefix is not cached yet: nothing to keep warm until the next turn.
399      await save($, v =>
400        v.phase === 'armed' || v.phase === 'capped' || v.phase === 'expired'
401          ? { ...v, phase: 'active', contextTokens: tokens, isCompactArmed: false }
402          : { ...v, contextTokens: tokens, isCompactArmed: false },
403      )
404      text = `Compacted before the cache expired: ${kilo(r.tokensBefore ?? s.contextTokens)} → ${kilo(tokens)} tokens.`
405    }
406  } catch (err) {
407    // A cancel or a refusal is final: no retry, the cache just expires.
408    text = `Compact did not run: ${String(err).replace(/^.*?session\.compact: /, '')}`
409  } finally {
410    isCompacting = false
411  }
412  await update($, session, v => ({ ...v, isCompactArmed: false }))
413  $.ui.toast(text)
414}
415
416async function ping($: Engine) {
417  const s = await read($, session)
418  if (s.phase !== 'armed' || s.ttlSec === null) return
419  const startedAt = await $.clock.now()
420  if (startedAt >= cacheStart(s) + s.ttlSec * 1000) {
421    // The timer fired late (the Mac slept): the cache is already gone, and a
422    // ping now would pay a full rewrite and read as a miss.
423    await expire($)
424    return
425  }
426  const r = await $.model.fork({ prompt: PING_PROMPT })
427  const after = await read($, session)
428  if (after.phase !== 'armed') return // a turn started while the fork ran
429
430  if (!r.isAnswered && r.reason === 'nothing-to-fork') {
431    cancelTimers()
432    await save($, v => ({ ...v, phase: 'active' }))
433    return
434  }
435  const usage = 'usage' in r ? r.usage : undefined
436  const prefix = usage ? usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens : 0
437  if (!usage || prefix === 0) {
438    // api-error or aborted with nothing sent: retry once, then give up.
439    if (!isRetrying) {
440      isRetrying = true
441      pingTimer = $.clock.after(RETRY_MS, () => {
442        void ping($)
443      })
444      return
445    }
446    await turnOff($, 'api-error')
447    return
448  }
449  isRetrying = false
450  const isHit = usage.cache_read_input_tokens / prefix >= HIT_RATIO
451  await recordStats($, isHit)
452  if (!isHit) {
453    await turnOff($, 'ttl-mismatch')
454    return
455  }
456  await save($, v => {
457    const pingsSent = v.pingsSent + 1
458    return { ...v, pingsSent, lastPingAt: startedAt, phase: pingsSent >= v.maxPings ? 'capped' : 'armed' }
459  })
460  await rearm($)
461  if ((await read($, session)).phase === 'capped') await askOnTelegram($)
462}
463
464async function expire($: Engine) {
465  const s = await read($, session)
466  if (s.phase !== 'armed' && s.phase !== 'capped') return
467  cancelTimers()
468  await save($, v => ({ ...v, phase: 'expired' }))
469  if (s.ttlSec !== null) await closeAsk($, `❄️ Cache expired at ${clockTime(cacheStart(s) + s.ttlSec * 1000)}.`)
470}
471
472async function turnOff($: Engine, offReason: 'api-error' | 'ttl-mismatch') {
473  cancelTimers()
474  const s = await save($, v => ({ ...v, phase: 'off', offReason }))
475  if (!s.isOffToastShown) {
476    const why =
477      offReason === 'ttl-mismatch'
478        ? 'the ping missed the cache, so this session’s cache lasts less than the ping interval'
479        : 'the ping failed twice with an API error'
480    $.ui.toast(`cache-keepalive off for this session: ${why}.`)
481    await update($, session, v => ({ ...v, isOffToastShown: true }))
482  }
483}
484
485async function runCommand($: Engine, args: string): Promise<string> {
486  const [verb = 'status', value] = args.trim().split(/\s+/)
487  const s = await read($, session)
488
489  if (verb === 'done') {
490    cancelTimers()
491    if (s.phase === 'off') return paint('Keepalive is already off for this session.', 'red')
492    await save($, v => ({ ...v, phase: 'stopped' }))
493    await closeAsk($, '💤 Stopped with /keepalive done.')
494    await rearm($) // an armed compact stays scheduled
495    return s.isCompactArmed && s.ttlSec !== null
496      ? `Pings stopped until your next prompt; the armed compact still runs at ${clockTime(compactAt({ ...s, phase: 'stopped' }))}.`
497      : 'Keepalive stopped until your next prompt.'
498  }
499
500  if (verb === 'brb') {
501    const isReset = value?.toLowerCase() === 'reset'
502    const minutes = isReset ? 0 : parseDuration(value)
503    if (!isReset && (!Number.isFinite(minutes) || minutes <= 0)) {
504      return paint('Usage: /keepalive brb <minutes or hours> | reset, for example /keepalive brb 180, /keepalive brb 24h or /keepalive brb reset', 'red')
505    }
506    if (s.phase === 'off') return paint(`Keepalive is off for this session (${s.offReason}).`, 'red')
507    if (s.phase === 'small') return paint('This session’s context is small enough that a rewrite is cheap; not keeping it warm.', 'yellow')
508    if (s.ttlSec === null || s.phase === 'active') return paint('Nothing to keep warm yet: wait for the current turn to finish.', 'yellow')
509    if (s.phase === 'expired') return paint('The cache has already expired; your next prompt rewrites it.', 'yellow')
510    const intervalSec = s.ttlSec - config.leadMinutes * 60
511    // reset: the configured cap again (the pings already sent stay sent).
512    const maxPings = isReset ? Math.max(config.maxPings, s.pingsSent) : Math.max(s.pingsSent + 1, Math.ceil((minutes * 60) / intervalSec))
513    await save($, v => ({ ...v, maxPings, phase: v.pingsSent < maxPings ? 'armed' : 'capped' }))
514    await rearm($)
515    const now = await $.clock.now()
516    const next = Math.max(now, cacheStart(s) + s.ttlSec * 1000 - config.leadMinutes * 60_000)
517    if (isReset) {
518      if (maxPings === 0) return 'Back to the default: no pings this idle stretch.'
519      return s.pingsSent >= maxPings
520        ? `Back to the default of ${pingCount(config.maxPings)}: the ${pingCount(s.pingsSent)} already sent use it up, so the cache expires at ${clockTime(cacheStart(s) + s.ttlSec * 1000)}.`
521        : `Back to the default: up to ${pingCount(maxPings)} this idle stretch, next at ${clockTime(next)}.`
522    }
523    const model = (await $.session.model().catch(() => '')) ?? ''
524    const breakEven = breakEvenPings(model)
525    // Only a heads-up: pings past the break-even cost more than the one rewrite they avoid.
526    const warning =
527      breakEven !== null && maxPings > breakEven
528        ? `\n${paint(`⚠ Past the break-even for ${model} (about ${breakEven} pings, ${Math.round((breakEven * intervalSec) / 3600)} h): the pings cost more than the one rewrite they avoid, so it only pays if you are sure to come back.`, 'yellow')}`
529        : ''
530    return `Keeping the cache warm for about ${minutes} min: up to ${pingCount(maxPings)} this idle stretch, next at ${clockTime(next)}.${warning}`
531  }
532
533  if (verb === 'compact') {
534    // Arms the compact for when keepalive runs out; the built-in /compact does it now.
535    if (value === 'off') {
536      cancelTimers()
537      await save($, v => ({ ...v, isCompactArmed: false })) // save, not update: the state file feeds the status line
538      await rearm($)
539      return 'Compact-before-expiry disarmed.'
540    }
541    if (s.phase === 'off') return paint(`Keepalive is off for this session (${s.offReason}).`, 'red')
542    if (s.phase === 'expired') return paint('The cache has already expired; use the built-in /compact if you still want one.', 'yellow')
543    if (s.phase === 'small') return paint('This session’s context is small, so it is not kept warm and nothing is compacted. To compact anyway, use the built-in /compact.', 'yellow')
544    await save($, v => ({ ...v, isCompactArmed: true }))
545    await rearm($)
546    const tail = ' One time; it survives /goal turns. /keepalive compact off cancels. To compact now, use the built-in /compact.'
547    if (s.ttlSec === null || s.phase === 'active') {
548      return `Armed: it is scheduled when the current turn ends, after the pings run out.${tail}`
549    }
550    return `Armed: compact at about ${clockTime(compactAt(s))}${s.phase === 'armed' ? ' (after the remaining pings)' : s.phase === 'stopped' ? ' (no pings, you ran /keepalive done)' : ''}.${tail}`
551  }
552
553  if (verb === 'ping') {
554    if (s.phase !== 'armed') return paint(`Nothing to ping: phase is ${s.phase}.`, 'yellow')
555    await ping($)
556    const after = await read($, session)
557    if (after.pingsSent > s.pingsSent) return `Pinged manually: ${pingCount(after.pingsSent)} sent, phase ${after.phase}.`
558    if (after.phase === 'off') return paint(`Ping failed: keepalive is off (${after.offReason}).`, 'red')
559    if (after.phase === 'expired') return paint('Ping skipped: the cache already expired.', 'yellow')
560    return paint('Ping ran but did not count; check /keepalive status.', 'yellow')
561  }
562
563  if (verb === 'status') {
564    const stats = ((await $.store.get('stats')) as Stats | undefined) ?? { pings: 0, hits: 0 }
565    const lines = [
566      `phase: ${paintPhase(s.phase)}${s.offReason ? ` (${s.offReason})` : ''}`,
567      `ttl: ${s.ttlSec === null ? 'not read yet' : `${s.ttlSec / 60} min`}`,
568      `context: ${kilo(s.contextTokens)} tokens (minimum ${kilo(config.minContextTokens)})`,
569      `pings this idle stretch: ${s.pingsSent}/${s.maxPings}`,
570    ]
571    if (s.ttlSec !== null && (s.phase === 'armed' || s.phase === 'capped')) {
572      const expiresAt = cacheStart(s) + s.ttlSec * 1000
573      if (s.phase === 'armed') lines.push(`next ping: ${clockTime(expiresAt - config.leadMinutes * 60_000)}`)
574      lines.push(`cache expires: ${clockTime(expiresAt)}`)
575    }
576    if (config.compactBeforeExpiry || s.isCompactArmed) {
577      const due = compactDueAt(s)
578      const at = due === null ? null : clockTime(due)
579      lines.push(`compact before expiry: ${s.isCompactArmed ? 'armed' : 'on'}${at ? `, at ${at}` : ''}`)
580    } else {
581      lines.push('compact before expiry: off')
582    }
583    lines.push(`telegram: ${isTelegramOn() ? `on (chat ${config.telegramChatId}${s.tgAskMessageId !== null ? ', question open' : ''})` : 'off'}`)
584    lines.push(`all sessions: ${stats.pings} pings, ${stats.hits} hits`)
585    return lines.join('\n')
586  }
587
588  return paint('Usage: /keepalive done | brb <minutes|hours|reset> | compact [off] | ping | status', 'red')
589}
590
591type Stats = { pings: number; hits: number }
592
593// --- Telegram: ask once the pings run out, read the answer by polling ---
594
595function isTelegramOn(): boolean {
596  return tgToken !== '' && config.telegramChatId !== ''
597}
598
599async function resolveTelegramToken($: Engine): Promise<string> {
600  if (tgTokenOption) return tgTokenOption
601  const fromEnv = (await $.env.get('CLAUDE_KEEPALIVE_TELEGRAM_BOT_TOKEN'))?.trim()
602  if (fromEnv) return fromEnv
603  const r = await $.process
604    .run(['security', 'find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', KEYCHAIN_ACCOUNT, '-w'])
605    .catch(() => undefined)
606  return r && r.exitCode === 0 ? r.stdout.trim() : ''
607}
608
609// One Bot API call; undefined on any failure (network, HTTP, ok: false).
610async function telegram($: Engine, method: string, body: Record<string, unknown>): Promise<unknown> {
611  if (!tgToken) return undefined
612  const res = await $.http
613    .fetch(`${TG_API}/bot${tgToken}/${method}`, {
614      method: 'POST',
615      headers: { 'content-type': 'application/json' },
616      body: JSON.stringify(body),
617    })
618    .catch(() => undefined)
619  if (!res) return undefined
620  try {
621    const data = JSON.parse(res.text) as { ok?: boolean; result?: unknown }
622    return data.ok ? data.result : undefined
623  } catch {
624    return undefined
625  }
626}
627
628async function askOnTelegram($: Engine) {
629  const s = await read($, session)
630  if (!isTelegramOn() || s.tgAskMessageId !== null || s.ttlSec === null) return
631  const expiresAt = cacheStart(s) + s.ttlSec * 1000
632  const rate = s.ttlSec === TTL_5M ? 1.25 : 2
633  const text = [
634    await sessionHeader($),
635    `🧊 Cache expires at <b>${clockTime(expiresAt)}</b> · ${kilo(s.contextTokens)} context`,
636    `Rewrite ≈ ${kilo(s.contextTokens * rate)} · one more hour warm ≈ ${kilo(s.contextTokens * 0.1)}`,
637    ...(config.compactBeforeExpiry || s.isCompactArmed
638      ? [`Will compact at ${clockTime(compactAt(s))} unless you keep it warm.`]
639      : []),
640    'Tap a button, or reply with minutes (e.g. 120).',
641  ].join('\n')
642  const sent = (await telegram($, 'sendMessage', {
643    chat_id: config.telegramChatId,
644    text,
645    parse_mode: 'HTML',
646    reply_markup: keyboard(sessionId.slice(0, 8)),
647  })) as { message_id?: number } | undefined
648  if (typeof sent?.message_id !== 'number') return
649  await update($, session, v => ({ ...v, tgAskMessageId: sent.message_id as number }))
650  startPolling($)
651}
652
653function startPolling($: Engine) {
654  stopPolling()
655  tgPoll = $.clock.every(TG_POLL_MS, () => {
656    void pollOnce($)
657  })
658}
659
660function stopPolling() {
661  tgPoll?.cancel()
662  tgPoll = undefined
663}
664
665// Reads pending updates without confirming an offset: other sessions and
666// machines share the bot, and confirming would delete their answers. With
667// the bot's privacy mode on, only button presses and replies are pending,
668// and Telegram drops them after 24 hours.
669async function pollOnce($: Engine) {
670  if (isPolling) return
671  isPolling = true
672  try {
673    const s = await read($, session)
674    if (s.tgAskMessageId === null) {
675      stopPolling()
676      return
677    }
678    const updates = await telegram($, 'getUpdates', { timeout: 0, limit: 100 })
679    if (!Array.isArray(updates)) return
680    const target = {
681      chatId: config.telegramChatId,
682      userId: config.telegramUserId,
683      messageId: s.tgAskMessageId,
684      sessionTag: sessionId.slice(0, 8),
685    }
686    const handled = ((await $.store.get('tgHandled')) as number[] | undefined) ?? []
687    for (const u of updates) {
688      const answer = parseUpdate(u, target)
689      if (!answer || handled.includes(answer.updateId)) continue
690      // Updates stay pending (no offset is confirmed), so remember which ones
691      // were already answered: one press must never count twice.
692      await $.store.set('tgHandled', [...handled, answer.updateId].slice(-200))
693      await applyAnswer($, answer.minutes, answer.callbackId)
694      return
695    }
696  } finally {
697    isPolling = false
698  }
699}
700
701async function applyAnswer($: Engine, minutes: number, callbackId: string | undefined) {
702  const s = await read($, session)
703  let line: string
704  if (s.phase !== 'armed' && s.phase !== 'capped') {
705    line = s.phase === 'expired' ? '❄️ Too late: the cache already expired.' : 'Nothing to keep warm now.'
706  } else if (s.ttlSec === null) {
707    line = 'Nothing to keep warm now.'
708  } else if (minutes === 0) {
709    cancelTimers()
710    await save($, v => ({ ...v, phase: 'stopped' }))
711    line = `💤 Letting it expire at ${clockTime(cacheStart(s) + s.ttlSec * 1000)}.`
712  } else {
713    const intervalMs = (s.ttlSec - config.leadMinutes * 60) * 1000
714    // Each ping adds one interval (TTL − lead, 55 min on a 1h TTL): "+1h" is
715    // one more ping, not two.
716    const extra = Math.max(1, Math.round((minutes * 60_000) / intervalMs))
717    await save($, v => ({ ...v, maxPings: v.pingsSent + extra, phase: 'armed' }))
718    await rearm($)
719    const until = cacheStart(s) + extra * intervalMs + s.ttlSec * 1000
720    line = `✅ Keeping it warm until about ${clockTime(until)} (${extra} more ping${extra > 1 ? 's' : ''}).`
721  }
722  if (callbackId) await telegram($, 'answerCallbackQuery', { callback_query_id: callbackId, text: line })
723  await closeAsk($, line)
724}
725
726// Ends the open question: the message shows the outcome and loses its buttons.
727async function closeAsk($: Engine, line: string) {
728  const s = await read($, session)
729  if (s.tgAskMessageId === null) return
730  stopPolling()
731  await update($, session, v => ({ ...v, tgAskMessageId: null }))
732  await telegram($, 'editMessageText', {
733    chat_id: config.telegramChatId,
734    message_id: s.tgAskMessageId,
735    text: `${await sessionHeader($)}\n${htmlEscape(line)}`,
736    parse_mode: 'HTML',
737  })
738}
739
740// "<project> · <session title>", the header session-notifier uses.
741async function sessionHeader($: Engine): Promise<string> {
742  const project = cwd.split('/').filter(Boolean).pop() ?? 'claude'
743  const s = await read($, session)
744  let title: string | null = null
745  if (s.transcriptPath) {
746    const r = await $.process
747      .run(['grep', '-h', '-E', '^\\{"type":"(custom-title|ai-title)"', s.transcriptPath])
748      .catch(() => undefined)
749    const rows = (r?.stdout ?? '').split('\n').filter(Boolean)
750    title = lastTitle(rows, 'custom-title', 'customTitle') ?? lastTitle(rows, 'ai-title', 'aiTitle')
751  }
752  return header(project, title ?? sessionId.slice(0, 8))
753}
754
755function lastTitle(rows: string[], type: string, field: string): string | null {
756  for (let i = rows.length - 1; i >= 0; i--) {
757    try {
758      const row = JSON.parse(rows[i] ?? '') as Record<string, unknown>
759      if (row.type === type && typeof row[field] === 'string' && row[field]) return row[field] as string
760    } catch {
761      continue
762    }
763  }
764  return null
765}
766
767async function recordStats($: Engine, isHit: boolean) {
768  const stats = ((await $.store.get('stats')) as Stats | undefined) ?? { pings: 0, hits: 0 }
769  await $.store.set('stats', { pings: stats.pings + 1, hits: stats.hits + (isHit ? 1 : 0) })
770}
771
772// Follows the session id: after /clear the engine raises session.end and no
773// session.start, and the next turn runs under a new id with a fresh state.
774async function bindSession($: Engine) {
775  const id = await $.session.id()
776  if (id === sessionId) return
777  const wasBound = sessionId !== ''
778  sessionId = id
779  if (wasBound) {
780    cancelTimers()
781    await update($, session, () => ({ ...INITIAL, maxPings: config.maxPings }))
782  }
783  const s = await read($, session)
784  if (!s.transcriptPath || wasBound) {
785    await update($, session, v => ({ ...v, transcriptPath: `${projectsDir}/${id}.jsonl` }))
786  }
787}
788
789async function save($: Engine, change: (v: KeepaliveSession) => KeepaliveSession): Promise<KeepaliveSession> {
790  const s = await update($, session, v => change(v ?? INITIAL))
791  await writeStateFile($, s)
792  return s
793}
794
795// The file bin/keepalive-cache reads; it holds data, and the script draws it.
796async function writeStateFile($: Engine, s: KeepaliveSession) {
797  if (!sessionId || !stateDir) return
798  const data = {
799    v: 1,
800    phase: s.phase,
801    offReason: s.offReason,
802    ttlSec: s.ttlSec,
803    lastPingAt: s.lastPingAt,
804    pings: s.pingsSent,
805    max: s.maxPings,
806    contextTokens: s.contextTokens,
807    // Armed by /keepalive compact, and the epoch ms it is due (null while
808    // nothing is scheduled, e.g. during a turn): the status line shows both.
809    compactArmed: s.isCompactArmed,
810    compactAt: compactDueAt(s),
811  }
812  await $.fs.write(stateFile(), JSON.stringify(data) + '\n')
813  if (config.engineStatus) $.ui.status(engineStatusText(s))
814}
815
816// Pushed only on state changes, never on a clock, so it names times rather
817// than counting down.
818function engineStatusText(s: KeepaliveSession): string | undefined {
819  const expiresAt = cacheStart(s) + (s.ttlSec ?? TTL_1H) * 1000
820  switch (s.phase) {
821    case 'armed':
822      return `keep ${s.pingsSent}/${s.maxPings} · ping ${clockTime(expiresAt - config.leadMinutes * 60_000)}`
823    case 'capped':
824      return config.compactBeforeExpiry || s.isCompactArmed
825        ? `keep ${s.pingsSent}/${s.maxPings} ⏸ · compact ${clockTime(compactAt(s))}`
826        : `keep ${s.pingsSent}/${s.maxPings} ⏸ · expires ${clockTime(expiresAt)}`
827    case 'stopped':
828      return `keep ⏸ · expires ${clockTime(expiresAt)}`
829    case 'expired':
830      return 'cache expired'
831    case 'off':
832      return s.offReason === 'disabled' ? undefined : `keep off · ${s.offReason}`
833    default:
834      return undefined // active, small
835  }
836}
837
838type TtlLine = { ttlSec: number; timestampMs: number | null }
839
840// The TTL is not in the turn's usage; the transcript's assistant rows carry
841// the 1h/5m split (and, when present, a real `timestamp` for when that row
842// was written — used to arm a resumed session with the cache's real age
843// instead of assuming it just started). The latest row that wrote to the
844// cache decides, so a row not yet flushed when turn.complete fires costs
845// nothing.
846async function readTranscriptTail($: Engine, transcriptPath: string | null): Promise<TtlLine | null> {
847  if (!transcriptPath) return null
848  const r = await $.process.run(['tail', '-c', String(TAIL_BYTES), transcriptPath]).catch(() => undefined)
849  if (!r || r.exitCode !== 0) return null
850  const lines = r.stdout.split('\n')
851  for (let i = lines.length - 1; i >= 0; i--) {
852    const info = ttlLineInfo(lines[i] ?? '')
853    if (info) return info
854  }
855  return null
856}
857
858async function readTtl($: Engine, transcriptPath: string | null): Promise<number | null> {
859  return (await readTranscriptTail($, transcriptPath))?.ttlSec ?? null
860}
861
862async function sweepStaleFiles($: Engine) {
863  const entries = await $.fs.list(stateDir).catch(() => [])
864  const now = await $.clock.now()
865  for (const entry of entries) {
866    if (entry.kind === 'file' && entry.name.endsWith('.json') && now - entry.mtimeMs > STALE_FILE_MS) {
867      await $.process.run(['rm', '-f', `${stateDir}/${entry.name}`]).catch(() => undefined)
868    }
869  }
870}
871
872const ANSI = { red: '31', green: '32', yellow: '33', dim: '2' } as const
873function paint(text: string, colour: keyof typeof ANSI): string {
874  return isTerminal ? `\u001b[${ANSI[colour]}m${text}\u001b[0m` : text
875}
876
877// armed is working, capped has run out of pings, expired and off need your attention.
878function paintPhase(phase: KeepaliveSession['phase']): string {
879  const colour = { armed: 'green', capped: 'yellow', expired: 'red', off: 'red', stopped: 'dim' } as const
880  return phase in colour ? paint(phase, colour[phase as keyof typeof colour]) : phase
881}
882
883function pingCount(n: number): string {
884  return `${n} ${n === 1 ? 'ping' : 'pings'}`
885}
886
887// "180" and "180m" are minutes, "24h" is hours (the Telegram answer takes both too).
888function parseDuration(value: string | undefined): number {
889  const m = /^(\d+(?:\.\d+)?)([hm])?$/i.exec(value ?? '')
890  if (!m) return NaN
891  return m[2]?.toLowerCase() === 'h' ? Number(m[1]) * 60 : Number(m[1])
892}
893
894function brbCompletion(text: string, cursor: number): string {
895  if (cursor !== text.length) return ''
896  const m = /^\/keepalive\s+brb\s+(\d*)$/.exec(text)
897  if (!m) return ''
898  const typed = m[1] ?? ''
899  const preset = BRB_PRESETS.find(p => p.startsWith(typed) && p.length > typed.length)
900  return preset ? preset.slice(typed.length) : ''
901}
902
903function ttlLineInfo(line: string): TtlLine | null {
904  if (!line.includes('ephemeral_')) return null
905  try {
906    const entry = JSON.parse(line)
907    if (entry.type !== 'assistant' || entry.isSidechain === true) return null
908    const split = entry.message?.usage?.cache_creation
909    if (!split) return null
910    const ttlSec = (split.ephemeral_5m_input_tokens ?? 0) > 0 ? TTL_5M : (split.ephemeral_1h_input_tokens ?? 0) > 0 ? TTL_1H : null
911    if (ttlSec === null) return null
912    const parsedTs = typeof entry.timestamp === 'string' ? Date.parse(entry.timestamp) : NaN
913    return { ttlSec, timestampMs: Number.isFinite(parsedTs) ? parsedTs : null }
914  } catch {
915    return null // the tail's first line is usually cut mid-row
916  }
917}
918
919function stateFile(): string {
920  return `${stateDir}/${sessionId}.json`
921}
922
923// When the armed compact fires: compactLeadMinutes before the cache would
924// expire after the last ping, longer ahead than a ping because a compaction
925// takes minutes on a big context. Every ping moves the cache start one
926// interval (TTL minus lead) on.
927function compactAt(s: KeepaliveSession): number {
928  const ttl = s.ttlSec ?? TTL_1H
929  const intervalMs = (ttl - config.leadMinutes * 60) * 1000
930  const pingsLeft = s.phase === 'armed' ? Math.max(0, s.maxPings - s.pingsSent) : 0
931  return cacheStart(s) + pingsLeft * intervalMs + (ttl - config.compactLeadMinutes * 60) * 1000
932}
933
934// When a compact is scheduled for this state, or null: the status line and
935// /keepalive status show it. The option applies to every idle stretch; the
936// flag only to the one it was armed for, and it also survives /keepalive done.
937function compactDueAt(s: KeepaliveSession): number | null {
938  if (s.ttlSec === null) return null
939  const isOn = s.isCompactArmed || config.compactBeforeExpiry
940  const isScheduled = s.phase === 'capped' || s.phase === 'armed' || (s.phase === 'stopped' && s.isCompactArmed)
941  return isOn && isScheduled ? compactAt(s) : null
942}
943
944function cacheStart(s: KeepaliveSession): number {
945  return Math.max(s.lastActivityAt, s.lastPingAt)
946}
947
948function cancelTimers() {
949  // The Telegram poller is separate: a question stays open across re-arms.
950  pingTimer?.cancel()
951  expiryTimer?.cancel()
952  compactTimer?.cancel()
953  pingTimer = undefined
954  expiryTimer = undefined
955  compactTimer = undefined
956}
957
958function clockTime(ms: number): string {
959  const d = new Date(ms)
960  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
961}
962
963function kilo(tokens: number): string {
964  return tokens >= 1000 ? `${Math.round(tokens / 1000)}k` : String(Math.round(tokens))
965}
966
967function positiveNumber(value: unknown, fallback: number, allowZero = false): number {
968  const n = typeof value === 'number' ? value : Number(value)
969  if (!Number.isFinite(n)) return fallback
970  return allowZero ? (n >= 0 ? n : fallback) : n > 0 ? n : fallback
971}
972
hooks/telegram.ts 101 lines
1// Telegram message building and update parsing for the keepalive question.
2// Pure functions: no `$`, so register.tsx owns every call to the Bot API.
3
4export type TelegramTarget = {
5  chatId: string
6  /** Only this user's presses and replies count; empty accepts anyone in the chat. */
7  userId: string
8  /** The message that carries the question. */
9  messageId: number
10  /** First 8 characters of the session id, carried in callback_data. */
11  sessionTag: string
12}
13
14/** What the person answered: minutes to keep warm, 0 to let the cache expire. */
15export type TelegramAnswer = {
16  updateId: number
17  minutes: number
18  callbackId?: string
19}
20
21const PREFIX = 'ka'
22export const CHOICES = [
23  { label: '+1h', minutes: 60 },
24  { label: '+3h', minutes: 180 },
25  { label: 'Let it expire', minutes: 0 },
26] as const
27
28export function htmlEscape(text: string): string {
29  return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
30}
31
32/** Same header as session-notifier: bold project, italic session title. */
33export function header(project: string, title: string | null): string {
34  const head = `<b>${htmlEscape(project)}</b>`
35  return title ? `${head} · <i>${htmlEscape(title)}</i>` : head
36}
37
38export function keyboard(sessionTag: string) {
39  return {
40    inline_keyboard: [
41      CHOICES.map(c => ({ text: c.label, callback_data: `${PREFIX}:${sessionTag}:${c.minutes}` })),
42    ],
43  }
44}
45
46/**
47 * Reads one getUpdates entry. Answers only a button press on the question
48 * message, or a text reply to it, from the configured chat and user.
49 */
50export function parseUpdate(update: unknown, target: TelegramTarget): TelegramAnswer | null {
51  const u = update as {
52    update_id?: number
53    callback_query?: {
54      id?: string
55      data?: string
56      from?: { id?: number }
57      message?: { message_id?: number; chat?: { id?: number } }
58    }
59    message?: {
60      text?: string
61      from?: { id?: number }
62      chat?: { id?: number }
63      reply_to_message?: { message_id?: number }
64    }
65  }
66  if (typeof u?.update_id !== 'number') return null
67
68  const cb = u.callback_query
69  if (cb) {
70    if (!isTarget(cb.message?.chat?.id, cb.from?.id, cb.message?.message_id, target)) return null
71    const m = new RegExp(`^${PREFIX}:([^:]+):(\\d+)$`).exec(cb.data ?? '')
72    if (!m || m[1] !== target.sessionTag) return null
73    return { updateId: u.update_id, minutes: Number(m[2]), callbackId: cb.id }
74  }
75
76  const msg = u.message
77  if (msg) {
78    if (!isTarget(msg.chat?.id, msg.from?.id, msg.reply_to_message?.message_id, target)) return null
79    const minutes = minutesFromText(msg.text ?? '')
80    return minutes === null ? null : { updateId: u.update_id, minutes }
81  }
82  return null
83}
84
85/** "120", "+90", "2h", "+1.5h", "45m", "stop" → minutes; anything else → null. */
86export function minutesFromText(text: string): number | null {
87  const t = text.trim().toLowerCase()
88  if (/^(stop|expire|no|0)$/.test(t)) return 0
89  const m = /^\+?\s*(\d+(?:\.\d+)?)\s*(h|hr|hours?|m|min|mins|minutes?)?$/.exec(t)
90  if (!m) return null
91  const n = Number(m[1])
92  const minutes = m[2]?.startsWith('h') ? n * 60 : n
93  return minutes > 0 && minutes <= 24 * 60 ? Math.round(minutes) : null
94}
95
96function isTarget(chatId: number | undefined, fromId: number | undefined, messageId: number | undefined, target: TelegramTarget): boolean {
97  if (String(chatId) !== target.chatId) return false
98  if (target.userId && String(fromId) !== target.userId) return false
99  return messageId === target.messageId
100}
101
types/index.d.ts 41 lines
1export type KeepalivePhase =
2  | 'active' // a turn is running, or no idle stretch is being kept
3  | 'small' // context under minContextTokens: not kept
4  | 'armed' // a ping is scheduled
5  | 'capped' // pings used up; the cache expires on its own
6  | 'stopped' // /keepalive done
7  | 'expired' // the cache TTL ran out while idle
8  | 'off' // disabled for the rest of the session (offReason says why)
9
10export type KeepaliveOffReason = '5m-ttl' | 'ttl-mismatch' | 'api-error' | 'disabled'
11
12export type KeepaliveSession = {
13  phase: KeepalivePhase
14  offReason: KeepaliveOffReason | null
15  /** Epoch ms of the last main-thread response. */
16  lastActivityAt: number
17  /** Epoch ms of the last ping that hit, or 0. */
18  lastPingAt: number
19  pingsSent: number
20  maxPings: number
21  /** Cache TTL in seconds read from the transcript, or null until read. */
22  ttlSec: number | null
23  /** Input tokens of the last main-thread response (the cached prefix). */
24  contextTokens: number
25  transcriptPath: string | null
26  /** The expired band was dismissed for this idle stretch. */
27  isBandDismissed: boolean
28  /** The OFF toast was already shown this session. */
29  isOffToastShown: boolean
30  /** message_id of the open Telegram question, or null when none is open. */
31  tgAskMessageId: number | null
32  /** /keepalive compact: compact once, when the pings run out. Survives turns (a /goal's continuations); cleared when it fires or on `compact off`. */
33  isCompactArmed: boolean
34}
35
36declare module 'claude-code' {
37  interface PluginState {
38    'cache-keepalive': { session: KeepaliveSession }
39  }
40}
41