Context, quota and prompt-cache meters above the prompt; while the session is idle on a 1-hour cache, keeps it alive and compacts before it lapses, holding off…

A Claude Code mod that draws two rows of meters above the prompt. When a session on a 1-hour prompt cache goes idle, it keeps the cache alive and then compacts the session before the cache lapses.
ctx ░░░░░░░░░░ 2% 20.5k/1M ▸auto 967k · 5h 28% ↻2h31m · 7d 67% ↻2d5h Opus 5.5 1M
● cache 60% ⏱ 59:41 1h · keep-alive 54:41 → compact 1:49:41 · sleep held high
▸auto). It also shows how much of the 5-hour and 7-day plan windows is used and when each resets.sleep held means system sleep is blocked.xhigh and max in yellow). Both come from the last request. A pick in /model or /effort shows within a second, read from the session's model and the effort saved for that model. An effort given at launch (--effort) is not saved, so it shows after the first response.The band keeps up while you are away. After a keep-alive the countdown starts again. After a compact, whether the keeper's, /compact or Claude Code's own, the band says so until the next response brings real figures, and who compacted the idle session (compacted by keeper or compacted by Claude Code):
ctx -- (compacted 24.6k → 3.2k) ▸auto 167k · 5h 9% ↻3h51m · 7d 72% ↻1d15h
○ cache -- 1h · compacted by keeper 12m ago
/ttl opens a pane with the full details: cache, context, quota and keeper state, a table with one row per turn, and buttons.
| Command | What it does |
|---|---|
/ttl | Opens the pane (buttons: k keep-alive now, c compact now, p pause/resume) |
/ttl pause / /ttl resume | Pauses or resumes the keeper for this session |
/ttl now | Runs a keep-alive right away |
/ttl compact | Compacts right away |
/ttl stop | Closes the pane |
The keeper arms when a main turn completes. The cache lifetime counts from the start of the last request that read or wrote the cache.
marginMinutes before the cache expires (5 by default), it sends one tool-less, one-character $.model.fork() request. The request reads the same conversation prefix, so the cache lives another hour from that point.keepAlives keep-alives (1 by default), it compacts the session with $.session.compact() before the next expiry.From Claude Code 2.1.299, Claude Code itself compacts an idle conversation on a 1-hour cache when it holds 200k tokens or more. It does so at 0.9 of the lifetime after the last main request (54 minutes), before the keeper's keep-alive at 55. A keep-alive does not move that timer, so a keep-alive sent earlier would only pay for a compaction that comes anyway.
So while Claude Code will compact the session itself, the keeper sends no keep-alive. The band shows Claude Code compacts 53:12, and the keeper's own compact before the expiry stays as a fallback for when Claude Code does not compact (its rollout is server-side). Claude Code counts as compacting the session itself when all of these hold:
autoCompactEnabled is not off)idleCompaction setting is not falseCLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS (200k when unset, never under 100k)Claude Code skips its idle compaction near a usage limit. The mod sees only how much of each window is used, not Claude Code's verdict, so it takes "near" as Claude Code's own warning rules (the 7-day window at 50% within its first 35%, or 25% within its first 15%) plus a guess at the server's point, which Claude Code is not told in advance: 90% of the 5-hour window or 75% of the 7-day one. The usage is shared by every session on the account, so other sessions can bring this on. Near a limit, the keeper plans as for a smaller conversation (keep-alive, then compact), and the claude row in /ttl says which window made Claude Code skip.
While Claude Code's idle compaction runs, the keeper holds off, and the band then says compacted by Claude Code. When the keeper's fallback compacts instead, the band says compacted by keeper, and the log says Claude Code did not compact.
To have a long conversation kept alive for another hour instead, as on a smaller one, turn Claude Code's off in settings.json:
{ "idleCompaction": false }
The keeper reads the setting every second, so the change applies to the session already open.
It does nothing in two cases:
While a keep-alive or compact is pending, the mod keeps one platform-specific process running through $.process.spawn. When nothing is pending or the session ends, it ends the process, and the hold goes with it.
| OS | How | Check | |
|---|---|---|---|
| Linux | systemd-inhibit --what=idle:sleep --mode=block | Claude Code cache-keeper in systemd-inhibit --list | |
| Windows | `SetThreadExecutionState(ES_CONTINUOUS \ | ES_SYSTEM_REQUIRED)` from PowerShell | powercfg /requests in an elevated PowerShell |
| macOS | caffeinate -i | pmset -g assertions |
On Windows and macOS this blocks idle sleep only. Closing the lid or putting the machine to sleep by hand still works. On Linux, --mode=block also blocks a manual suspend.
With ttl set to auto, the mod applies Claude Code's own rules in this order:
FORCE_PROMPT_CACHING_5M → 5 minutesCLAUDE_CODE_PROMPT_CACHE_TTL (5m / 1h)promptCacheTtl settingENABLE_PROMPT_CACHING_1H → 1 hourA new session has no quota data until its first response arrives. Until then, the mod uses the plan windows an earlier session saw, which it keeps in $.store.
After that, the gaps between requests also correct the lifetime. A cache hit after a gap of more than 5 minutes confirms 1 hour. A miss after a gap of 5 to 60 minutes means 5 minutes.
Change these in Claude Code's config menu (the plugin's rows under /config). A change reloads the mod.
| Option | Default | Meaning |
|---|---|---|
ttl | auto | auto, 5m or 1h |
marginMinutes | 5 | How many minutes before expiry the keep-alive or compact runs |
keepAlives | 1 | Keep-alives before the compact (0 compacts at the first deadline). None while Claude Code compacts the session itself |
keeper | true | Run keep-alives and compacts (false leaves only the meters) |
inhibitSleep | true | Block idle sleep while a keep-alive or compact is pending |
band | true | Show the two rows above the prompt |
quota | true | Show the plan windows in the band |
status | false | Also show a short entry in the status line |
Verified on 2026-10-05 (Claude Code 2.1.289, Manjaro), tests again on 2026-10-14 (Claude Code 2.1.299):
claude plugin validate passes, and all 32 tests in claude plugin test pass. The tests run on a mocked clock and cover:idleCompaction: false or near a usage limit/ttl compactsession.start (a reload)/model and /effort/ttl now really refreshes the cache (read 20.2k tokens, 98% hit)/ttl compact and /compact, the band switches to -- and the compact at once, and the elapsed time advances while idle (Claude Code 2.1.289, 2026-10-06)/effort shows within a second (Claude Code 2.1.291, 2026-10-06)Not yet verified:
powercfg /requests or pmset -g assertions on real machines)hooks/register.tsx 939 lines1/**
2 * cache-keeper — Claude Code mod
3 *
4 * Meters: the context window (with the point where Claude Code compacts on its
5 * own), the plan's rate-limit windows, and the prompt cache (hit rate and the
6 * countdown to its expiry), as two rows above the prompt and a /ttl pane.
7 *
8 * Keeper: once a main turn completes on a 1-hour cache, it refreshes the cache
9 * with a tool-less `$.model.fork()` shortly before it lapses (`keepAlives`
10 * times), then compacts the session before the next lapse. The person coming
11 * back cancels it. A conversation Claude Code compacts itself while idle
12 * (2.1.299 on: 1-hour cache, 200k tokens or more, idleCompaction on, no plan
13 * window near its limit) gets no keep-alive, only the keeper's compact as a fallback. While something is
14 * pending, a child process holds off idle sleep (systemd-inhibit,
15 * SetThreadExecutionState through PowerShell, or caffeinate). A cache that
16 * lapsed anyway (the machine slept) is left alone: a keep-alive then would only
17 * pay to write it again.
18 *
19 * Every function that takes `$` is declared at the top of this file, as the
20 * engine requires; the session's values live in one Runtime object.
21 */
22import { atom, read, update } from 'claude-code'
23import type {
24 EngineInterface,
25 HookStream,
26 PluginOptions,
27 ProcessSpawnChunk,
28 ProcessSpawnResult,
29 Register,
30 SessionCompacted,
31 SessionContextUsage,
32 SessionRateLimit,
33} from 'claude-code'
34import type {
35 CacheKeeperContext as Context,
36 CacheKeeperLimit as Limit,
37 CacheKeeperSample as Sample,
38 CacheKeeperSleep as Sleep,
39 CacheKeeperTtl as Ttl,
40 CacheKeeperView as View,
41} from '../types'
42import {
43 MINUTE,
44 TTL_MS,
45 accountOf,
46 bar,
47 byTurn,
48 contextTone,
49 decide,
50 decideTtl,
51 effortLabel,
52 fmtClock,
53 fmtShrink,
54 fmtTokens,
55 freshKeeper,
56 hitRatio,
57 idleCompactAt,
58 nearLimit,
59 idleCompactMinTokens,
60 isCached,
61 lifeTone,
62 limitLabel,
63 modelLabel,
64 savedEffort,
65 observeTtl,
66 percentTone,
67 positive,
68 promptTokens,
69 remainingMs,
70 resetsIn,
71 wantsAwake,
72} from './logic.ts'
73import type { KeeperPolicy, KeeperState, TtlEnv } from './logic.ts'
74import { inhibitorArgv, platformOf } from './inhibitor.ts'
75
76const PANE = 'cache-keeper'
77const COMMAND = 'ttl'
78const KEEP = 200
79const KEEP_ALIVE_PROMPT = 'Reply with exactly one character: .'
80const MAX_SLEEP_FAILURES = 3
81// The 1 s timer counts as stopped after this long without a call
82const STALE_MS = 5_000
83const STUCK_MS = 60_000
84
85const viewAtom = atom({ plugin: 'cache-keeper', key: 'view' } as const, null)
86const samplesAtom = atom({ plugin: 'cache-keeper', key: 'samples' } as const, [])
87
88const TONE = { ok: 'green', warn: 'yellow', bad: 'red', dim: undefined } as const
89
90type Child = HookStream<ProcessSpawnChunk, ProcessSpawnResult>
91
92type Runtime = {
93 policy: KeeperPolicy
94 ttlOption: unknown
95 holdSleep: boolean
96 showStatus: boolean
97 samples: Sample[]
98 lastKeepAlive?: Sample
99 keeper: KeeperState
100 /** Bumped whenever the keeper starts over, so late answers of an old run are dropped. */
101 generation: number
102 keeperError?: string
103 env: TtlEnv
104 setting: unknown
105 /** The idleCompaction setting and CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS's threshold. */
106 idleSetting: unknown
107 idleMinTokens: number
108 limits: Limit[]
109 context?: Context
110 observed?: Ttl
111 ttl: Ttl
112 ttlSource: string
113 platform: Sleep['platform']
114 child?: Child
115 sleepFailures: number
116 sleepError?: string
117 timer?: { cancel: () => void }
118 /** When the timer last called, and when the tick now running began. */
119 lastBeatAt: number
120 tickStartedAt: number
121 isTicking: boolean
122 /** startSession ran (or is running) in this load; isEnded: the session is over. */
123 isStarted: boolean
124 isEnded: boolean
125 lastKey: string
126 lastStatus: string
127 /** The main loop's model and effort, from its last request (the model from /model before any). */
128 model?: string
129 effort?: string
130 /** What /model and the saved effortLevel said at the last look; a change is a switch. */
131 seenModel?: string
132 seenEffort?: unknown
133 /** The full id the last main request named; /effort saves per model under it. */
134 requestModel?: string
135}
136
137function createRuntime(options: PluginOptions): Runtime {
138 const policy: KeeperPolicy = {
139 isEnabled: options.keeper !== false,
140 marginMs: positive(options.marginMinutes, 5) * MINUTE,
141 keepAlives: Math.min(5, Math.floor(positive(options.keepAlives, 1))),
142 }
143 return {
144 policy,
145 ttlOption: options.ttl,
146 holdSleep: options.inhibitSleep !== false && policy.isEnabled,
147 showStatus: options.status === true,
148 samples: [],
149 keeper: freshKeeper(),
150 generation: 0,
151 env: {},
152 setting: undefined,
153 idleSetting: undefined,
154 idleMinTokens: idleCompactMinTokens(undefined),
155 limits: [],
156 ttl: '5m',
157 ttlSource: 'default',
158 platform: 'unsupported',
159 sleepFailures: 0,
160 lastBeatAt: 0,
161 tickStartedAt: 0,
162 isTicking: false,
163 isStarted: false,
164 isEnded: false,
165 lastKey: '',
166 lastStatus: '',
167 }
168}
169
170const toLimit = (l: SessionRateLimit): Limit => ({ kind: l.kind, percentUsed: l.percentUsed, resetsAt: l.resetsAt })
171
172// The last plan windows any session saw: a new session reads them until its
173// first response, so a subscription starts on its 1-hour lifetime
174const LIMITS_KEY = 'limits'
175
176function isLimitList(v: unknown): v is Limit[] {
177 return Array.isArray(v) && v.every(l => typeof l?.kind === 'string' && typeof l?.percentUsed === 'number')
178}
179
180async function setLimits($: EngineInterface, rt: Runtime, limits: Limit[]) {
181 rt.limits = limits
182 if (limits.length > 0) await $.store.set(LIMITS_KEY, limits).catch(() => undefined)
183}
184
185// The host puts the plugin's name before each line
186function log($: EngineInterface, text: string, to: 'transcript' | 'debug' = 'transcript') {
187 $.ui.log(text, { to })
188}
189
190function settleTtl(rt: Runtime) {
191 const choice = decideTtl(rt.ttlOption, rt.env, rt.setting, accountOf(rt.limits))
192 if (choice.source === 'option' || rt.observed === undefined || rt.observed === choice.ttl) {
193 rt.ttl = choice.ttl
194 rt.ttlSource = choice.source
195 } else {
196 rt.ttl = rt.observed
197 rt.ttlSource = `observed; ${choice.source} says ${choice.ttl}`
198 }
199}
200
201function setContext(rt: Runtime, c: SessionContextUsage) {
202 rt.context = { ...rt.context, tokens: c.tokens, window: c.window, percent: c.percent }
203}
204
205// When Claude Code compacts this idle session itself (`at`), or the window near
206// its limit that makes it skip that (`near`); neither when it does not apply
207function idlePlan(rt: Runtime): { at?: number; near?: Limit } {
208 const isOn = rt.idleSetting !== false && rt.context?.isAutoOn !== false
209 const at = idleCompactAt(rt.samples, rt.ttl, rt.context?.tokens, { isOn, minTokens: rt.idleMinTokens })
210 if (at === undefined) return {}
211 // Claude Code judges the limits as the last response left them
212 const near = nearLimit(rt.limits, rt.samples[rt.samples.length - 1]?.at ?? at)
213 return near ? { near } : { at }
214}
215
216const idleAt = (rt: Runtime) => idlePlan(rt).at
217
218function forgetFill(rt: Runtime) {
219 if (rt.context) rt.context = { ...rt.context, tokens: undefined, percent: undefined }
220}
221
222function startOver(rt: Runtime) {
223 rt.generation += 1
224 rt.keeper = { ...freshKeeper(), isPaused: rt.keeper.isPaused }
225 rt.keeperError = undefined
226}
227
228// The plain figures, plus where Claude Code compacts on its own (a local estimate)
229async function refreshUsage($: EngineInterface, rt: Runtime) {
230 const usage = await $.session.usage({ breakdown: 'summary' }).catch(() => undefined)
231 if (!usage) return
232 setContext(rt, usage.context)
233 const b = usage.context.breakdown
234 if (b && rt.context) {
235 rt.context.isAutoOn = b.isAutoCompactEnabled
236 rt.context.autoAt = b.isAutoCompactEnabled ? b.autoCompactThreshold : undefined
237 }
238 if (usage.rateLimits.length > 0) await setLimits($, rt, usage.rateLimits.map(toLimit))
239 else if (rt.limits.length === 0) {
240 const saved = await $.store.get(LIMITS_KEY).catch(() => undefined)
241 if (isLimitList(saved)) rt.limits = saved
242 }
243 settleTtl(rt)
244}
245
246function record($: EngineInterface, rt: Runtime, s: Sample) {
247 const prev = rt.samples[rt.samples.length - 1]
248 rt.samples.push(s)
249 if (rt.samples.length > KEEP) rt.samples = rt.samples.slice(-KEEP)
250 void saveSamples($, rt)
251 const seen = observeTtl(prev, s, rt.observed)
252 if (seen !== rt.observed) {
253 rt.observed = seen
254 log($, `cache lifetime looks like ${seen} from request timing`, 'debug')
255 }
256 settleTtl(rt)
257}
258
259async function saveSamples($: EngineInterface, rt: Runtime) {
260 const samples = [...rt.samples]
261 await update($, samplesAtom, () => samples).catch(() => undefined)
262}
263
264// A reload of the mod keeps the session's $.state: pick the requests up from
265// there, so the countdown and the keeper go on instead of waiting for a request
266async function restoreSamples($: EngineInterface, rt: Runtime) {
267 const saved = await read($, samplesAtom).catch(() => [])
268 if (saved.length === 0) return
269 rt.samples = saved.slice(-KEEP)
270 rt.lastKeepAlive = [...rt.samples].reverse().find(s => s.kind === 'keep-alive')
271 for (let i = 1; i < rt.samples.length; i++) {
272 const cur = rt.samples[i]
273 if (cur) rt.observed = observeTtl(rt.samples[i - 1], cur, rt.observed)
274 }
275 // Reloads come between turns, so the session is idle
276 rt.keeper.isArmed = true
277}
278
279// ------------------------------------------------------------ sleep hold
280
281async function detectPlatform($: EngineInterface): Promise<Sleep['platform']> {
282 const osVar = await $.env.get('OS').catch(() => undefined)
283 if (osVar === 'Windows_NT') return 'windows'
284 const uname = await $.process
285 .run(['uname', '-s'], { timeoutMs: 3_000 })
286 .then(r => r.stdout)
287 .catch(() => undefined)
288 return platformOf(osVar, uname)
289}
290
291async function holdSleep($: EngineInterface, rt: Runtime, isWanted: boolean) {
292 if (!isWanted) {
293 const mine = rt.child
294 if (!mine) return
295 rt.child = undefined
296 await mine.return(undefined as never).catch(() => undefined)
297 return
298 }
299 const argv = inhibitorArgv(rt.platform)
300 if (rt.child || !argv || rt.sleepFailures >= MAX_SLEEP_FAILURES) return
301 const mine = $.process.spawn({ argv })
302 rt.child = mine
303 rt.sleepError = undefined
304 void watchHold($, rt, mine, argv[0] ?? 'inhibitor')
305}
306
307// Drains the child's output; a child that ends while still held has failed
308async function watchHold($: EngineInterface, rt: Runtime, mine: Child, name: string) {
309 let stderr = ''
310 try {
311 for await (const piece of mine) {
312 if (piece.stream === 'stderr') stderr = (stderr + piece.text).slice(-300)
313 }
314 if (rt.child === mine) {
315 const { code, signal } = await mine.result
316 rt.sleepFailures += 1
317 rt.sleepError = `${name} exited (${signal ?? code})${stderr ? `: ${stderr.trim()}` : ''}`
318 }
319 } catch (err) {
320 if (rt.child === mine) {
321 rt.sleepFailures += 1
322 rt.sleepError = `${name} did not start: ${err}`
323 }
324 }
325 if (rt.child === mine) {
326 rt.child = undefined
327 if (rt.sleepError) log($, rt.sleepError, 'debug')
328 await publish($, rt)
329 }
330}
331
332// ------------------------------------------------------------ the keeper
333
334async function publish($: EngineInterface, rt: Runtime) {
335 const now = await $.clock.now()
336 const last = rt.samples[rt.samples.length - 1]
337 const idle = idlePlan(rt)
338 const { action: _, ...status } = decide(rt.keeper, rt.policy, rt.ttl, last, now, idle.at)
339 if (rt.holdSleep) await holdSleep($, rt, wantsAwake({ ...status, action: 'none' }))
340 // Redraw by the tick only while something counts down
341 const isCounting = remainingMs(last, rt.ttl, now) > 0 || status.dueAt !== undefined
342 const sleep: Sleep = rt.holdSleep
343 ? { platform: rt.platform, isActive: rt.child !== undefined, error: rt.sleepError ?? (inhibitorArgv(rt.platform) ? undefined : 'no sleep inhibitor on this platform') }
344 : { platform: rt.platform, isActive: false, error: 'off' }
345 const view: View = {
346 now: isCounting ? now : Math.floor(now / MINUTE) * MINUTE,
347 ttl: rt.ttl,
348 ttlSource: rt.ttlSource,
349 last,
350 turns: byTurn(rt.samples).slice(-20),
351 context: rt.context,
352 limits: rt.limits,
353 keeper: status,
354 ...(idle.near ? { idleSkip: `${limitLabel(idle.near.kind)} ${Math.round(idle.near.percentUsed)}%` } : {}),
355 sleep,
356 lastKeepAlive: rt.lastKeepAlive,
357 model: rt.model,
358 effort: rt.effort,
359 }
360 const key = JSON.stringify(view)
361 if (key !== rt.lastKey) {
362 rt.lastKey = key
363 await update($, viewAtom, () => view)
364 }
365 if (rt.showStatus) {
366 const text = statusLine(view, now)
367 if (text !== rt.lastStatus) {
368 rt.lastStatus = text
369 $.ui.status(text)
370 }
371 }
372}
373
374async function keepAlive($: EngineInterface, rt: Runtime, isScheduled: boolean) {
375 if (rt.keeper.busy) return
376 const mine = rt.generation
377 rt.keeper.busy = 'keep-alive'
378 const at = await $.clock.now()
379 const model = rt.samples[rt.samples.length - 1]?.model ?? ''
380 try {
381 const r = await $.model.fork({ prompt: KEEP_ALIVE_PROMPT })
382 if (mine !== rt.generation) return
383 if (!r.isAnswered) throw new Error(`keep-alive not answered (${r.reason})`)
384 const s: Sample = {
385 turnId: `keep-alive-${at}`,
386 kind: 'keep-alive',
387 at,
388 model,
389 read: r.usage.cache_read_input_tokens,
390 write: r.usage.cache_creation_input_tokens,
391 fresh: r.usage.input_tokens,
392 output: r.usage.output_tokens,
393 }
394 record($, rt, s)
395 rt.lastKeepAlive = s
396 if (isScheduled) rt.keeper.done += 1
397 log($, `keep-alive: read ${fmtTokens(s.read)}, wrote ${fmtTokens(s.write)}, new ${fmtTokens(s.fresh)} tokens`)
398 } catch (err) {
399 if (mine !== rt.generation) return
400 rt.keeper.outcome = 'failed'
401 rt.keeperError = String(err)
402 log($, rt.keeperError, 'debug')
403 } finally {
404 if (mine === rt.generation) rt.keeper.busy = undefined
405 await publish($, rt)
406 }
407}
408
409// The conversation the compaction left has nothing cached and no measured size
410// until its next response: a marker says so, kept with the requests
411async function noteCompact($: EngineInterface, rt: Runtime, r: SessionCompacted) {
412 const at = await $.clock.now()
413 record($, rt, {
414 turnId: `compact-${at}`,
415 kind: 'compact',
416 at,
417 model: rt.samples[rt.samples.length - 1]?.model ?? '',
418 read: 0,
419 write: 0,
420 fresh: 0,
421 output: 0,
422 // $.state holds JSON: no undefined fields
423 ...(r.tokensBefore !== undefined ? { before: r.tokensBefore } : {}),
424 ...(r.tokensAfter !== undefined ? { after: r.tokensAfter } : {}),
425 })
426 // Inside a session.compact hook, usage still reads the size before
427 await refreshUsage($, rt)
428 forgetFill(rt)
429}
430
431async function compact($: EngineInterface, rt: Runtime) {
432 if (rt.keeper.busy) return
433 const mine = rt.generation
434 rt.keeper.busy = 'compact'
435 // Claude Code was to compact first: say it did not
436 const isFallback = idleAt(rt) !== undefined
437 try {
438 const r = await $.session.compact()
439 // A plugin's own call skips its own session.compact hook: note it here
440 if (r.skip === undefined) await noteCompact($, rt, r)
441 if (mine !== rt.generation) return
442 if (r.skip !== undefined) throw new Error(`compact skipped: ${r.skip}`)
443 rt.keeper.outcome = 'compacted'
444 log($, `${isFallback ? 'Claude Code did not compact while idle; ' : ''}compacted (${fmtTokens(r.tokensBefore ?? 0)} -> ${fmtTokens(r.tokensAfter ?? 0)} tokens)`)
445 } catch (err) {
446 if (mine !== rt.generation) return
447 rt.keeper.outcome = 'failed'
448 rt.keeperError = String(err)
449 log($, rt.keeperError, 'debug')
450 } finally {
451 if (mine === rt.generation) rt.keeper.busy = undefined
452 await publish($, rt)
453 }
454}
455
456// The engine refuses a compact from inside a command or a press, under the
457// turn that hook holds: run it from a timer of its own
458function laterCompact($: EngineInterface, rt: Runtime) {
459 $.clock.after(0, () => void compact($, rt))
460}
461
462// /model and /effort pick in a dialog that outlives their command: watch what they
463// change instead. /effort saves the level per model; a launch's --effort is only known from
464// a request, so only a change of the saved level counts. The idleCompaction setting is
465// watched along with them
466async function watchSwitch($: EngineInterface, rt: Runtime) {
467 const model = await $.session.model().catch(() => undefined)
468 if (model && model !== rt.seenModel) {
469 rt.seenModel = model
470 rt.model = model
471 // The last request's model is not the session's any more
472 rt.requestModel = undefined
473 }
474 const settings = (await $.settings.read().catch(() => undefined)) as Record<string, unknown> | undefined
475 if (settings) rt.idleSetting = settings.idleCompaction
476 const level = settings && savedEffort(settings, [rt.requestModel, rt.model])
477 if (settings && level !== rt.seenEffort) {
478 rt.seenEffort = level
479 if (typeof level === 'string') rt.effort = level
480 }
481}
482
483async function tick($: EngineInterface, rt: Runtime) {
484 const now = await $.clock.now()
485 rt.lastBeatAt = now
486 // A tick stuck on a call that never settles must not hold the rest off
487 if (rt.isTicking && now - rt.tickStartedAt < STUCK_MS) return
488 rt.isTicking = true
489 rt.tickStartedAt = now
490 try {
491 const d = decide(rt.keeper, rt.policy, rt.ttl, rt.samples[rt.samples.length - 1], now, idleAt(rt))
492 if (d.action === 'keep-alive') void keepAlive($, rt, true)
493 else if (d.action === 'compact') void compact($, rt)
494 else if (d.action === 'expired') {
495 rt.keeper.outcome = 'expired'
496 log($, 'the cache lapsed while away (the machine slept?); keep-alive and compact skipped')
497 }
498 await watchSwitch($, rt)
499 await publish($, rt)
500 } finally {
501 rt.isTicking = false
502 }
503}
504
505function startTimer($: EngineInterface, rt: Runtime, now: number) {
506 rt.timer?.cancel()
507 rt.timer = $.clock.every(1000, () => void tick($, rt))
508 rt.lastBeatAt = now
509}
510
511// The timer that redraws the band can stop unseen: a refused period ends
512// $.clock.every, and a reload of unchanged code brings no session.start. Any
513// hook that runs, the band's drawing among them, puts it back
514async function ensureTicking($: EngineInterface, rt: Runtime) {
515 if (rt.isEnded) return
516 if (!rt.isStarted) {
517 rt.isStarted = true
518 $.clock.after(0, () => void startSession($, rt))
519 return
520 }
521 const now = await $.clock.now()
522 if (rt.timer && now - rt.lastBeatAt < STALE_MS) return
523 log($, 'timer restarted', 'debug')
524 startTimer($, rt, now)
525}
526
527async function startSession($: EngineInterface, rt: Runtime) {
528 rt.isStarted = true
529 rt.isEnded = false
530 rt.samples = []
531 rt.lastKeepAlive = undefined
532 rt.keeper = freshKeeper()
533 rt.generation += 1
534 rt.observed = undefined
535 await restoreSamples($, rt)
536 // Until the first request names them: /model's model, and the effort a reload kept
537 const before = await read($, viewAtom).catch(() => null)
538 rt.model = (await $.session.model().catch(() => undefined)) ?? before?.model
539 rt.effort = before?.effort
540 rt.seenModel = rt.model
541 const none = () => undefined
542 rt.env = {
543 force5m: await $.env.get('FORCE_PROMPT_CACHING_5M').catch(none),
544 ttlVar: await $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL').catch(none),
545 enable1h: await $.env.get('ENABLE_PROMPT_CACHING_1H').catch(none),
546 }
547 rt.idleMinTokens = idleCompactMinTokens(await $.env.get('CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS').catch(none))
548 const settings = (await $.settings.read().catch(() => ({}))) as Record<string, unknown>
549 rt.setting = settings.promptCacheTtl
550 rt.idleSetting = settings.idleCompaction
551 rt.seenEffort = savedEffort(settings, [rt.requestModel, rt.model])
552 await refreshUsage($, rt)
553 settleTtl(rt)
554 if (rt.holdSleep) rt.platform = await detectPlatform($)
555
556 await $.command
557 .register({
558 name: COMMAND,
559 description: 'Cache, context and keeper details (args: pause, resume, now, compact, stop)',
560 argumentHint: '[pause|resume|now|compact|stop]',
561 immediate: true,
562 })
563 .catch(err => log($, `/${COMMAND} not registered: ${err}`, 'debug'))
564
565 startTimer($, rt, await $.clock.now())
566 log($, `loaded: ${rt.ttl} cache (${rt.ttlSource}), sleep hold ${rt.holdSleep ? rt.platform : 'off'}`, 'debug')
567 await publish($, rt)
568}
569
570async function runCommand($: EngineInterface, rt: Runtime, args: string): Promise<string> {
571 const arg = args.trim().toLowerCase()
572 if (arg === 'stop' || arg === 'close') {
573 await $.ui.close({ id: PANE }).catch(() => undefined)
574 return 'pane closed'
575 }
576 if (arg === 'pause' || arg === 'resume') {
577 rt.keeper.isPaused = arg === 'pause'
578 await publish($, rt)
579 return arg === 'pause' ? 'paused for this session' : 'resumed'
580 }
581 if (arg === 'now') {
582 void keepAlive($, rt, false)
583 return 'keep-alive started'
584 }
585 if (arg === 'compact') {
586 laterCompact($, rt)
587 return 'compact started'
588 }
589 await $.ui.open({ id: PANE, title: 'cache-keeper', focus: true })
590 return `${rt.ttl} cache (${rt.ttlSource}) · /${COMMAND} pause|resume|now|compact|stop`
591}
592
593function togglePause($: EngineInterface, rt: Runtime) {
594 rt.keeper.isPaused = !rt.keeper.isPaused
595 void publish($, rt)
596}
597
598// ------------------------------------------------------------ hooks
599
600export const register: Register = (on, options) => {
601 const rt = createRuntime(options)
602 const showBand = options.band !== false
603 const showQuota = options.quota !== false
604
605 on('session.start', async ($, e, next) => {
606 const started = await next(e)
607 await startSession($, rt)
608 return started
609 })
610
611 on('session.end', async ($, e, next) => {
612 if (e.reason === 'clear') {
613 // A new conversation in the same process: its cache is a new one
614 rt.samples = []
615 rt.lastKeepAlive = undefined
616 rt.observed = undefined
617 await saveSamples($, rt)
618 startOver(rt)
619 forgetFill(rt)
620 settleTtl(rt)
621 await publish($, rt)
622 return next(e)
623 }
624 rt.isEnded = true
625 rt.timer?.cancel()
626 rt.timer = undefined
627 rt.generation += 1
628 await holdSleep($, rt, false)
629 return next(e)
630 })
631
632 // The person is back: whatever the keeper had pending is off
633 on('prompt.submit', async ($, e, next) => {
634 await ensureTicking($, rt)
635 startOver(rt)
636 await publish($, rt)
637 return next(e)
638 })
639
640 on('turn.start', async ($, e, next) => {
641 if (!rt.keeper.busy) {
642 startOver(rt)
643 await publish($, rt)
644 }
645 return next(e)
646 })
647
648 on('turn.complete', async ($, e, next) => {
649 const result = await next(e)
650 await ensureTicking($, rt)
651 if (e.agentId === undefined && !rt.keeper.busy) {
652 rt.keeper.isArmed = true
653 await publish($, rt)
654 }
655 return result
656 })
657
658 // Each main-loop request: what the cache did with it
659 on('turn.step', async function* ($, e, next) {
660 if (e.agentId || rt.keeper.busy === 'keep-alive') return yield* next(e)
661 rt.model = e.model
662 rt.requestModel = e.model
663 rt.effort = effortLabel(e.effort)
664 const at = await $.clock.now()
665 const r = yield* next(e)
666 if (r.usage) {
667 record($, rt, {
668 turnId: e.turnId,
669 kind: 'turn',
670 at,
671 model: r.usage.model || e.model,
672 read: r.usage.cache_read_input_tokens,
673 write: r.usage.cache_creation_input_tokens,
674 fresh: r.usage.input_tokens,
675 output: r.usage.output_tokens,
676 })
677 await publish($, rt)
678 }
679 return r
680 })
681
682 on('session.measure', async ($, e, next) => {
683 await ensureTicking($, rt)
684 const window = rt.context?.window
685 setContext(rt, e.context)
686 if (e.changed.includes('rateLimits')) await setLimits($, rt, e.rateLimits.map(toLimit))
687 settleTtl(rt)
688 // A new model may bring a new window and a new auto-compact point
689 if (window !== undefined && window !== e.context.window) await refreshUsage($, rt)
690 await publish($, rt)
691 return next(e)
692 })
693
694 on('session.compact', async ($, e, next) => {
695 // Another's compaction (/compact, Claude Code's own); the keeper's own does not come through here
696 const isMain = e.agentId === undefined && e.trigger !== 'precompute'
697 // Armed means idle: Claude Code compacting by itself while the person is away.
698 // The keeper counts as busy meanwhile, so no keep-alive goes out on the old conversation
699 const k = rt.keeper
700 const isIdle = isMain && k.isArmed && !k.busy
701 if (isIdle) {
702 k.busy = 'compact'
703 await publish($, rt)
704 }
705 try {
706 const result = await next(e)
707 if (isMain && result.skip === undefined) {
708 await noteCompact($, rt, result)
709 if (isIdle && k === rt.keeper) k.outcome = 'claude-compacted'
710 }
711 return result
712 } finally {
713 // Let go only once the compaction is noted, so no tick in between acts on the old conversation
714 if (isIdle) k.busy = undefined
715 if (isMain) await publish($, rt)
716 }
717 })
718
719 on('command.run', { command: COMMAND }, async ($, e) => {
720 await ensureTicking($, rt)
721 return { text: await runCommand($, rt, e.args) }
722 })
723
724 // ------------------------------------------------------------ the band
725
726 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
727 await ensureTicking($, rt)
728 if (!showBand || e.props.hasSurvey) return next(e)
729 const view = await read($, viewAtom)
730 if (!view) return next(e)
731 const { Box, Text } = $.ui.resolve(e)
732 const columns = e.props.bodyColumns ?? e.viewport?.columns ?? 100
733 const isWide = columns >= 100
734 const now = view.now
735
736 const c = view.context
737 const pct = c?.tokens !== undefined ? (c.percent ?? Math.round((c.tokens / c.window) * 100)) : undefined
738 const ctxTone = c ? contextTone(c.tokens, c.window, c.autoAt) : 'green'
739 const ctxRow = (
740 <Box key="ctx" flexDirection="row" columnGap={1}>
741 <Box flexDirection="row" flexGrow={1} columnGap={1}>
742 <Text bold color="cyan">ctx</Text>
743 {c && pct !== undefined ? (
744 <Box flexDirection="row" columnGap={1}>
745 <Text color={ctxTone}>{bar(pct / 100, isWide ? 10 : 6)}</Text>
746 <Text bold color={ctxTone}>{`${pct}%`}</Text>
747 {isWide ? <Text dimColor>{`${fmtTokens(c.tokens ?? 0)}/${fmtTokens(c.window)}`}</Text> : null}
748 </Box>
749 ) : (
750 <Text dimColor>{view.last?.kind === 'compact' && fmtShrink(view.last.before, view.last.after) ? `-- (compacted ${fmtShrink(view.last.before, view.last.after)})` : '--'}</Text>
751 )}
752 {c?.autoAt !== undefined ? <Text dimColor>{`▸auto ${fmtTokens(c.autoAt)}`}</Text> : c?.isAutoOn === false ? <Text dimColor>auto off</Text> : null}
753 {showQuota
754 ? view.limits.map(l => (
755 <Text key={`q:${l.kind}`} color={percentTone(l.percentUsed)}>
756 {`· ${limitLabel(l.kind)} ${Math.round(l.percentUsed)}%${isWide && resetsIn(l.resetsAt, now) ? ` ↻${resetsIn(l.resetsAt, now)}` : ''}`}
757 </Text>
758 ))
759 : null}
760 </Box>
761 {view.model ? (
762 <Box flexShrink={0}>
763 <Text bold color="magenta">{modelLabel(view.model)}</Text>
764 </Box>
765 ) : null}
766 </Box>
767 )
768
769 const last = view.last
770 const left = remainingMs(last, view.ttl, now)
771 const cacheColor = left > 0 ? lifeTone(left, view.ttl) : 'red'
772 const icon = !isCached(last) ? '○' : left > 0 ? '●' : '✖'
773 const k = view.keeper
774 const cacheRow = (
775 <Box key="cache" flexDirection="row" columnGap={1}>
776 <Box flexDirection="row" flexGrow={1} flexShrink={1} columnGap={1}>
777 <Text bold color={isCached(last) ? cacheColor : undefined}>{icon}</Text>
778 <Text bold color="cyan">cache</Text>
779 {last && isCached(last) ? (
780 <Box flexDirection="row" columnGap={1}>
781 {isWide ? <Text bold>{`${Math.round(hitRatio(last) * 100)}%`}</Text> : null}
782 <Text bold color={cacheColor}>{left > 0 ? `⏱ ${fmtClock(left)}` : 'expired'}</Text>
783 </Box>
784 ) : (
785 <Text dimColor>--</Text>
786 )}
787 <Text dimColor>{view.ttl}</Text>
788 <Text color={TONE[k.tone]} dimColor={k.tone === 'dim'} wrap="truncate-end">{`· ${k.label}${view.sleep.isActive ? ' · sleep held' : ''}`}</Text>
789 </Box>
790 {view.effort ? (
791 <Box flexShrink={0}>
792 <Text bold color={view.effort === 'xhigh' || view.effort === 'max' ? 'yellow' : undefined}>{view.effort}</Text>
793 </Box>
794 ) : null}
795 </Box>
796 )
797
798 const mine = (
799 <Box key="cache-keeper" flexDirection="column" width={columns}>
800 {ctxRow}
801 {cacheRow}
802 </Box>
803 )
804 // Keep what the mods after this one draw in the band
805 const rest = await next(e)
806 if (!rest) return mine
807 return (
808 <Box flexDirection="column">
809 {mine}
810 {rest}
811 </Box>
812 )
813 })
814
815 // ------------------------------------------------------------ the pane
816
817 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
818 const { Box, Text, Button } = $.ui.resolve(e)
819 const view = await read($, viewAtom)
820 // HTML collapses runs of spaces; a no-break space keeps the columns
821 const sp = (t: string) => (e.surface === 'terminal' ? t : t.replace(/ /g, ' '))
822 if (!view) return <Text dimColor>no data yet</Text>
823 const width = Math.max(30, (e.props.bodyColumns ?? 60) - 1)
824 const barW = Math.min(width - 24, 30)
825 const now = view.now
826 const last = view.last
827 const left = remainingMs(last, view.ttl, now)
828 const k = view.keeper
829 const c = view.context
830 const row = (key: string, label: string, value: string, color?: string) => (
831 <Box key={key} flexDirection="row" columnGap={1}>
832 <Box width={10} flexShrink={0}>
833 <Text dimColor>{sp(label)}</Text>
834 </Box>
835 <Text color={color}>{sp(value)}</Text>
836 </Box>
837 )
838 const cell = (key: string, w: number, text: string, color?: string) => (
839 <Box key={key} width={w} flexShrink={0} justifyContent="flex-end">
840 <Text color={color} dimColor={!color}>{sp(text)}</Text>
841 </Box>
842 )
843 const rows = view.turns.slice(-Math.max(3, (e.viewport?.rows ?? 30) - 24))
844
845 return (
846 <Box flexDirection="column">
847 <Text bold color="cyan">{sp(`CACHE KEEPER · ${view.ttl} lifetime (${view.ttlSource})`)}</Text>
848
849 <Box key="cache" flexDirection="column" marginTop={1}>
850 <Text bold>cache</Text>
851 {last && isCached(last) ? (
852 <Box flexDirection="column">
853 {row('left', 'left', `${bar(left / TTL_MS[view.ttl], barW)} ${left > 0 ? fmtClock(left) : 'expired'}`, left > 0 ? lifeTone(left, view.ttl) : 'red')}
854 {row('last', 'last req', `${Math.round(hitRatio(last) * 100)}% hit · read ${fmtTokens(last.read)} · wrote ${fmtTokens(last.write)} · new ${fmtTokens(last.fresh)} · ${fmtTokens(promptTokens(last))} prompt`)}
855 </Box>
856 ) : (
857 <Text dimColor>{last?.kind === 'compact' ? 'compacted: the next request writes a new cache' : 'no cached request yet'}</Text>
858 )}
859 </Box>
860
861 <Box key="context" flexDirection="column" marginTop={1}>
862 <Text bold>context</Text>
863 {c && c.tokens !== undefined
864 ? row('ctx', 'window', `${bar(c.tokens / c.window, barW)} ${fmtTokens(c.tokens)}/${fmtTokens(c.window)}`, contextTone(c.tokens, c.window, c.autoAt))
865 : row('ctx', 'window', c ? `-- of ${fmtTokens(c.window)} (until the next response)` : '--')}
866 {row('auto', 'auto', c?.autoAt !== undefined ? `Claude Code compacts at ${fmtTokens(c.autoAt)}${c.tokens !== undefined ? ` (${fmtTokens(Math.max(0, c.autoAt - c.tokens))} left)` : ''}` : c?.isAutoOn === false ? 'off' : 'unknown')}
867 {view.limits.map(l =>
868 row(`q:${l.kind}`, limitLabel(l.kind), `${bar(l.percentUsed / 100, barW)} ${Math.round(l.percentUsed)}%${resetsIn(l.resetsAt, now) ? ` · resets in ${resetsIn(l.resetsAt, now)}` : ''}`, percentTone(l.percentUsed)),
869 )}
870 </Box>
871
872 <Box key="keeper" flexDirection="column" marginTop={1}>
873 <Text bold>keeper</Text>
874 {row('state', 'state', k.label, TONE[k.tone])}
875 {k.idleCompactAt !== undefined && k.idleCompactAt > now ? row('claude', 'claude', `Claude Code compacts in ${fmtClock(k.idleCompactAt - now)} (idleCompaction)`) : null}
876 {view.idleSkip && k.dueAt !== undefined ? row('claude', 'claude', `Claude Code skips its idle compaction: ${view.idleSkip} is near the limit`, 'yellow') : null}
877 {k.dueAt !== undefined ? row('next', 'next', `${k.next} in ${fmtClock(k.dueAt - now)}${k.idleCompactAt !== undefined ? ' (fallback)' : ''}`) : null}
878 {k.compactAt !== undefined ? row('compact', 'compact', `in ${fmtClock(k.compactAt - now)}`) : null}
879 {row('done', 'keep-alive', `${k.done}/${k.planned} this idle${view.lastKeepAlive ? ` · last read ${fmtTokens(view.lastKeepAlive.read)}, wrote ${fmtTokens(view.lastKeepAlive.write)}` : ''}`)}
880 {row('sleep', 'sleep', view.sleep.isActive ? `held (${view.sleep.platform})` : view.sleep.error ? `not held: ${view.sleep.error}` : `not held (${view.sleep.platform})`, view.sleep.isActive ? 'green' : undefined)}
881 {rt.keeperError ? row('error', 'error', rt.keeperError, 'red') : null}
882 <Box key="buttons" flexDirection="row" columnGap={1} marginTop={1}>
883 <Button key="now" label="keep-alive now" hotkey="k" onPress={() => void keepAlive($, rt, false)} />
884 <Button key="compact" label="compact now" hotkey="c" onPress={() => laterCompact($, rt)} />
885 <Button key="pause" label={k.isPaused ? 'resume' : 'pause'} hotkey="p" onPress={() => togglePause($, rt)} />
886 <Button key="close" label="close" role="dismiss" onPress={() => void $.ui.close({ id: PANE })} />
887 </Box>
888 </Box>
889
890 <Box key="table" flexDirection="column" marginTop={1}>
891 <Box key="head" flexDirection="row" columnGap={1}>
892 {cell('h:n', 4, 'turn', 'cyan')}
893 {cell('h:steps', 5, 'steps', 'cyan')}
894 {cell('h:read', 7, 'read', 'green')}
895 {cell('h:wrote', 7, 'wrote', 'yellow')}
896 {cell('h:new', 6, 'new', 'cyan')}
897 {cell('h:hit', 5, 'hit', 'magenta')}
898 </Box>
899 {rows.length === 0 ? <Text dimColor>no requests yet</Text> : null}
900 {rows.map((t, i) => {
901 if (t.kind === 'compact') {
902 return (
903 <Box key={`t:${t.turnId}`} flexDirection="row" columnGap={1}>
904 {cell(`n:${t.turnId}`, 4, 'cmp')}
905 <Text dimColor>{sp(`compacted ${fmtShrink(t.before, t.after)}`.trim())}</Text>
906 </Box>
907 )
908 }
909 const total = t.read + t.write + t.fresh
910 const hit = total > 0 ? Math.round((t.read / total) * 100) : 0
911 return (
912 <Box key={`t:${t.turnId}`} flexDirection="row" columnGap={1}>
913 {cell(`n:${t.turnId}`, 4, t.kind === 'keep-alive' ? 'ka' : String(view.turns.length - rows.length + i + 1))}
914 {cell(`s:${t.turnId}`, 5, String(t.steps))}
915 {cell(`r:${t.turnId}`, 7, fmtTokens(t.read), 'green')}
916 {cell(`w:${t.turnId}`, 7, fmtTokens(t.write), 'yellow')}
917 {cell(`f:${t.turnId}`, 6, fmtTokens(t.fresh), 'cyan')}
918 {cell(`h:${t.turnId}`, 5, `${hit}%`, percentTone(100 - hit))}
919 </Box>
920 )
921 })}
922 </Box>
923 </Box>
924 )
925 })
926}
927
928function statusLine(view: View, now: number): string {
929 const parts: string[] = []
930 const c = view.context
931 if (c?.tokens !== undefined) parts.push(`ctx ${c.percent ?? Math.round((c.tokens / c.window) * 100)}%`)
932 const left = remainingMs(view.last, view.ttl, now)
933 parts.push(left > 0 ? `cache ${fmtClock(left)}` : 'cache --')
934 const k = view.keeper
935 if (k.idleCompactAt !== undefined && k.idleCompactAt > now) parts.push(`Claude Code compacts ${fmtClock(k.idleCompactAt - now)}`)
936 else if (k.dueAt !== undefined) parts.push(`${k.next} ${fmtClock(k.dueAt - now)}`)
937 return parts.join(' · ')
938}
939hooks/logic.ts 329 lines1// Pure logic for cache-keeper: no `$`, so the tests call it directly.
2import type {
3 CacheKeeperLimit as Limit,
4 CacheKeeperSample as Sample,
5 CacheKeeperStatus as Status,
6 CacheKeeperTtl as Ttl,
7 CacheKeeperTurnRow as TurnRow,
8} from '../types'
9
10export const MINUTE = 60_000
11export const TTL_MS: Record<Ttl, number> = { '5m': 5 * MINUTE, '1h': 60 * MINUTE }
12
13// ---------------------------------------------------------------- lifetime
14
15export type Account = 'subscription' | 'credits' | 'other'
16
17export type TtlEnv = {
18 force5m?: string
19 ttlVar?: string
20 enable1h?: string
21}
22
23const isOn = (v: string | undefined) => v !== undefined && /^(1|true|yes|on)$/i.test(v.trim())
24const asTtl = (v: unknown): Ttl | undefined => (v === '5m' || v === '1h' ? v : undefined)
25
26/** A plan window says subscription; one used up means requests draw on usage credits. */
27export function accountOf(limits: readonly Limit[]): Account {
28 const plan = limits.filter(l => l.kind === 'five_hour' || l.kind === 'seven_day')
29 if (plan.length === 0) return 'other'
30 return plan.some(l => l.percentUsed >= 100) ? 'credits' : 'subscription'
31}
32
33/** The lifetime Claude Code asks for, in the order its documentation gives. */
34export function decideTtl(option: unknown, env: TtlEnv, setting: unknown, account: Account): { ttl: Ttl; source: string } {
35 const pinned = asTtl(option)
36 if (pinned) return { ttl: pinned, source: 'option' }
37 if (isOn(env.force5m)) return { ttl: '5m', source: 'FORCE_PROMPT_CACHING_5M' }
38 const fromVar = asTtl(env.ttlVar?.trim())
39 if (fromVar) return { ttl: fromVar, source: 'CLAUDE_CODE_PROMPT_CACHE_TTL' }
40 const fromSetting = asTtl(setting)
41 if (fromSetting) return { ttl: fromSetting, source: 'promptCacheTtl setting' }
42 if (isOn(env.enable1h)) return { ttl: '1h', source: 'ENABLE_PROMPT_CACHING_1H' }
43 if (account === 'subscription') return { ttl: '1h', source: 'subscription' }
44 return { ttl: '5m', source: account === 'credits' ? 'usage credits' : 'API key or provider' }
45}
46
47export const promptTokens = (s: Sample) => s.read + s.write + s.fresh
48export const isCached = (s: Sample | undefined) => !!s && s.read + s.write > 0
49export const hitRatio = (s: Sample) => (promptTokens(s) > 0 ? s.read / promptTokens(s) : 0)
50
51/**
52 * What the gap between two requests proves about the lifetime. A hit after
53 * more than 5 minutes proves 1 hour and sticks (a later miss may be a changed
54 * prefix); a miss 5 to 60 minutes later on the same model, with a prompt that
55 * did not shrink, says 5 minutes until a hit overrules it.
56 */
57export function observeTtl(prev: Sample | undefined, cur: Sample, seen: Ttl | undefined): Ttl | undefined {
58 if (!prev || !isCached(prev) || prev.model !== cur.model) return seen
59 const gap = cur.at - prev.at
60 if (gap <= TTL_MS['5m']) return seen
61 const before = promptTokens(prev)
62 if (before === 0) return seen
63 if (cur.read >= before * 0.5) return '1h'
64 const isMiss = cur.read < before * 0.1 && promptTokens(cur) >= before * 0.9
65 if (isMiss && gap < TTL_MS['1h'] && seen !== '1h') return '5m'
66 return seen
67}
68
69export function remainingMs(last: Sample | undefined, ttl: Ttl, now: number): number {
70 if (!last || !isCached(last)) return 0
71 return Math.max(0, last.at + TTL_MS[ttl] - now)
72}
73
74// ---------------------------------------------------------------- Claude Code's idle compaction
75
76/**
77 * Claude Code (2.1.299 on) compacts a long conversation on a 1-hour cache by
78 * itself, at 0.9 of the lifetime after the last main request (54 minutes).
79 * Its timer is set when the main turn ends and a keep-alive does not move it,
80 * so a keep-alive before then only pays for a compaction that comes anyway.
81 */
82export const IDLE_COMPACT_FRACTION = 0.9
83const IDLE_COMPACT_MIN_TOKENS = 200_000
84const IDLE_COMPACT_FLOOR = 100_000
85
86export type IdleCompact = {
87 /** The idleCompaction setting is not false and Claude Code compacts on its own (autoCompactEnabled). */
88 isOn: boolean
89 minTokens: number
90}
91
92/** CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS, kept at 100k or more as Claude Code keeps it; 200k without it. */
93export function idleCompactMinTokens(envVar: string | undefined): number {
94 const n = envVar?.trim() ? Number(envVar) : NaN
95 return Number.isFinite(n) ? Math.max(IDLE_COMPACT_FLOOR, n) : IDLE_COMPACT_MIN_TOKENS
96}
97
98/**
99 * When Claude Code compacts this idle session itself, or undefined when it
100 * will not: off, a 5-minute cache, a conversation under its threshold, or no
101 * main request since the last compaction.
102 */
103export function idleCompactAt(samples: readonly Sample[], ttl: Ttl, tokens: number | undefined, idle: IdleCompact): number | undefined {
104 if (!idle.isOn || ttl !== '1h' || tokens === undefined || tokens < idle.minTokens) return undefined
105 for (let i = samples.length - 1; i >= 0; i--) {
106 const s = samples[i]!
107 if (s.kind === 'compact') return undefined
108 if (s.kind === 'turn') return s.at + TTL_MS[ttl] * IDLE_COMPACT_FRACTION
109 }
110 return undefined
111}
112
113const LIMIT_WINDOW_MS: Record<string, number> = { five_hour: 5 * 60 * MINUTE, seven_day: 7 * 24 * 60 * MINUTE }
114/**
115 * Where Claude Code calls a window near its limit: past `used` percent within the
116 * first `by` of the window. Claude Code skips its idle compaction then. Its own
117 * rules are the early ones; the server says so as well, past a point it does not
118 * tell, taken here as 90% of 5 hours and 75% of 7 days whenever they come.
119 */
120const NEAR_LIMIT: Record<string, { used: number; by: number }[]> = {
121 five_hour: [{ used: 90, by: 1 }],
122 seven_day: [{ used: 75, by: 1 }, { used: 50, by: 0.35 }, { used: 25, by: 0.15 }],
123}
124
125/** The first window near its limit at `at` (when the last response came), if any. */
126export function nearLimit(limits: readonly Limit[], at: number): Limit | undefined {
127 return limits.find(l => {
128 const rules = NEAR_LIMIT[l.kind]
129 const windowMs = LIMIT_WINDOW_MS[l.kind]
130 if (!rules || !windowMs) return false
131 const resetsAt = l.resetsAt ? Date.parse(l.resetsAt) : NaN
132 const elapsed = Number.isFinite(resetsAt) ? Math.min(1, Math.max(0, 1 - (resetsAt - at) / windowMs)) : 1
133 return rules.some(r => l.percentUsed >= r.used && elapsed <= r.by)
134 })
135}
136
137// ---------------------------------------------------------------- keeper
138
139export type KeeperPolicy = {
140 isEnabled: boolean
141 marginMs: number
142 keepAlives: number
143}
144
145export type KeeperState = {
146 /** Set when a main turn completed; cleared when the person is back. */
147 isArmed: boolean
148 busy?: 'keep-alive' | 'compact'
149 done: number
150 /** `compacted`: by the keeper; `claude-compacted`: by Claude Code while idle. */
151 outcome?: 'compacted' | 'claude-compacted' | 'expired' | 'failed'
152 isPaused: boolean
153}
154
155export type Decision = Status & { action: 'none' | 'keep-alive' | 'compact' | 'expired' }
156
157export const freshKeeper = (): KeeperState => ({ isArmed: false, done: 0, isPaused: false })
158
159/** The margin, kept between 30 s and half the lifetime. */
160export function marginFor(policy: KeeperPolicy, ttl: Ttl): number {
161 return Math.min(Math.max(policy.marginMs, 30_000), TTL_MS[ttl] / 2)
162}
163
164/**
165 * What the keeper should do now, and what the band says about it. With
166 * `idleAt` (idleCompactAt), Claude Code compacts the session itself: no
167 * keep-alive, and the keeper's compact stays as the fallback.
168 */
169export function decide(k: KeeperState, policy: KeeperPolicy, ttl: Ttl, last: Sample | undefined, now: number, idleAt?: number): Decision {
170 const planned = idleAt === undefined ? policy.keepAlives : 0
171 const base = { isBusy: !!k.busy, isPaused: k.isPaused, done: k.done, planned }
172 const say = (label: string, tone: Status['tone'], action: Decision['action'] = 'none'): Decision => ({ ...base, label, tone, action })
173
174 // How long ago the last compaction ran, while nothing came after it
175 const ago = last?.kind === 'compact' ? ` ${fmtAgo(now - last.at)}` : ''
176 if (!policy.isEnabled) return say('keeper off', 'dim')
177 if (k.busy === 'keep-alive') return say('keep-alive running', 'warn')
178 if (k.busy === 'compact') return say('compacting', 'warn')
179 if (k.outcome === 'compacted') return say(`compacted by keeper${ago}`, 'ok')
180 if (k.outcome === 'claude-compacted') return say(`compacted by Claude Code${ago}`, 'ok')
181 if (k.outcome === 'expired') return say('expired while away', 'bad')
182 if (k.outcome === 'failed') return say('keeper failed (see /ttl)', 'bad')
183 if (k.isPaused) return say('paused', 'dim')
184 if (ttl !== '1h') return say('idle (5m cache: keeper off)', 'dim')
185 if (ago) return say(`compacted${ago}`, 'dim')
186 if (!isCached(last)) return say(k.isArmed ? 'idle (nothing cached)' : 'ready', 'dim')
187 if (!k.isArmed) return say('ready', 'dim')
188
189 const ttlMs = TTL_MS[ttl]
190 const margin = marginFor(policy, ttl)
191 const expiresAt = last!.at + ttlMs
192 if (now >= expiresAt) return say('expired while away', 'bad', 'expired')
193 const dueAt = expiresAt - margin
194 const left = Math.max(0, planned - k.done)
195 const next = left > 0 ? 'keep-alive' : 'compact'
196 const compactAt = dueAt + left * (ttlMs - margin)
197 const status = { ...base, next, dueAt, compactAt, ...(idleAt !== undefined ? { idleCompactAt: idleAt } : {}) } as const
198 if (now >= dueAt) return { ...status, label: next === 'keep-alive' ? 'keep-alive due' : 'compact due', tone: 'warn', action: next }
199 const label = idleAt !== undefined && now < idleAt
200 ? `Claude Code compacts ${fmtClock(idleAt - now)}`
201 : next === 'keep-alive'
202 ? `keep-alive ${fmtClock(dueAt - now)} → compact ${fmtClock(compactAt - now)}`
203 : `compact ${fmtClock(dueAt - now)}`
204 return { ...status, label, tone: 'ok', action: 'none' }
205}
206
207/** Whether the machine should be kept awake for what the keeper has pending. */
208export const wantsAwake = (d: Decision) => d.isBusy || d.dueAt !== undefined
209
210// ---------------------------------------------------------------- tables
211
212export function byTurn(samples: readonly Sample[]): TurnRow[] {
213 const rows: TurnRow[] = []
214 for (const s of samples) {
215 const row = rows[rows.length - 1]
216 if (row && row.turnId === s.turnId) {
217 row.steps += 1
218 row.read += s.read
219 row.write += s.write
220 row.fresh += s.fresh
221 } else {
222 rows.push({ turnId: s.turnId, kind: s.kind, steps: 1, read: s.read, write: s.write, fresh: s.fresh, before: s.before, after: s.after })
223 }
224 }
225 return rows
226}
227
228// ---------------------------------------------------------------- formatting
229
230export function fmtClock(ms: number): string {
231 const total = Math.max(0, Math.ceil(ms / 1000))
232 const h = Math.floor(total / 3600)
233 const m = Math.floor((total % 3600) / 60)
234 const s = total % 60
235 const ss = String(s).padStart(2, '0')
236 return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`
237}
238
239/** `just now`, `12m ago`, `2h05m ago`. */
240export function fmtAgo(ms: number): string {
241 const m = Math.floor(Math.max(0, ms) / MINUTE)
242 if (m < 1) return 'just now'
243 const h = Math.floor(m / 60)
244 return h > 0 ? `${h}h${String(m % 60).padStart(2, '0')}m ago` : `${m}m ago`
245}
246
247/** A compaction's sizes, `24.6k → 3.4k`, or '' when Claude Code recorded neither. */
248export function fmtShrink(before: number | undefined, after: number | undefined): string {
249 if (before === undefined && after === undefined) return ''
250 const f = (n: number | undefined) => (n === undefined ? '?' : fmtTokens(n))
251 return `${f(before)} → ${f(after)}`
252}
253
254export function fmtTokens(n: number): string {
255 if (n >= 1_000_000) return `${trim(n / 1_000_000)}M`
256 if (n >= 1_000) return `${trim(n / 1_000)}k`
257 return String(Math.round(n))
258}
259const trim = (v: number) => (v >= 100 ? String(Math.round(v)) : v.toFixed(1).replace(/\.0$/, ''))
260
261export function bar(ratio: number, width: number): string {
262 const filled = Math.round(Math.min(1, Math.max(0, ratio)) * width)
263 return '█'.repeat(filled) + '░'.repeat(width - filled)
264}
265
266/** `claude-opus-5-5[1m]` → `Opus 5.5 1M`; an alias or any other name stays as given. */
267export function modelLabel(model: string): string {
268 const m = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(\[1m\])?$/i.exec(model)
269 if (!m) return model
270 const [, family = '', major, minor, oneM] = m
271 return `${family.charAt(0).toUpperCase()}${family.slice(1)} ${major}${minor ? `.${minor}` : ''}${oneM ? ' 1M' : ''}`
272}
273
274/**
275 * The effort /effort saved for this model (`modelSettings.<id>.effortLevel`), else
276 * the shared `effortLevel`. Ids or aliases are tried in order, a `[1m]` suffix dropped.
277 */
278export function savedEffort(settings: Record<string, unknown>, models: readonly (string | undefined)[]): unknown {
279 const per = settings.modelSettings as Record<string, { effortLevel?: unknown } | undefined> | undefined
280 for (const m of models) {
281 if (!m || !per) continue
282 const id = m.replace(/\[[^\]]*\]$/, '')
283 // An alias (`opus`) names the newest saved id of its family
284 const key = id in per ? id : Object.keys(per).sort().reverse().find(k => k.startsWith(`claude-${id}-`))
285 const v = key ? per[key]?.effortLevel : undefined
286 if (v !== undefined) return v
287 }
288 return settings.effortLevel
289}
290
291/** A level as is, a token budget as its number. */
292export const effortLabel = (effort: string | number | undefined) => (effort === undefined ? undefined : String(effort))
293
294export const LIMIT_LABEL: Record<string, string> = { five_hour: '5h', seven_day: '7d', spend_limit: 'spend' }
295export const limitLabel = (kind: string) => LIMIT_LABEL[kind] ?? kind
296
297/** Green well below where Claude Code compacts on its own, yellow nearing it, red at it. */
298export function contextTone(tokens: number | undefined, window: number, autoAt: number | undefined): 'green' | 'yellow' | 'red' {
299 if (tokens === undefined) return 'green'
300 const limit = autoAt ?? window
301 const r = tokens / limit
302 return r >= 0.9 ? 'red' : r >= 0.7 ? 'yellow' : 'green'
303}
304
305export const percentTone = (p: number): 'green' | 'yellow' | 'red' => (p >= 90 ? 'red' : p >= 70 ? 'yellow' : 'green')
306
307/** Green, then yellow below 40% of the lifetime, red inside the last minute. */
308export function lifeTone(left: number, ttl: Ttl): 'green' | 'yellow' | 'red' {
309 if (left <= 60_000) return 'red'
310 return left / TTL_MS[ttl] < 0.4 ? 'yellow' : 'green'
311}
312
313export function resetsIn(resetsAt: string | undefined, now: number): string | undefined {
314 if (!resetsAt) return undefined
315 const at = Date.parse(resetsAt)
316 if (!Number.isFinite(at)) return undefined
317 const ms = at - now
318 if (ms <= 0) return 'now'
319 const h = Math.floor(ms / 3_600_000)
320 if (h >= 24) return `${Math.floor(h / 24)}d${h % 24}h`
321 const m = Math.ceil((ms % 3_600_000) / 60_000)
322 return h > 0 ? `${h}h${String(m).padStart(2, '0')}m` : `${m}m`
323}
324
325export function positive(value: unknown, fallback: number): number {
326 const n = Number(value)
327 return Number.isFinite(n) && n >= 0 ? n : fallback
328}
329hooks/inhibitor.ts 40 lines1// The command that holds off idle sleep for as long as it lives, per platform.
2// The module spawns it with `$.process.spawn`; ending the loop, or the module
3// unloading, kills it, and the OS drops the hold with the process.
4import type { CacheKeeperSleep as Sleep } from '../types'
5
6export type Platform = Sleep['platform']
7
8const WHO = 'Claude Code cache-keeper'
9const WHY = 'Keep the prompt cache alive before compacting'
10
11// ES_CONTINUOUS | ES_SYSTEM_REQUIRED, held by this PowerShell thread until it exits
12const WINDOWS_SCRIPT = [
13 "$sig = '[DllImport(\"kernel32.dll\")] public static extern uint SetThreadExecutionState(uint esFlags);'",
14 '$t = Add-Type -MemberDefinition $sig -Name Power -Namespace CacheKeeper -PassThru',
15 'if ($t::SetThreadExecutionState([uint32]2147483649) -eq 0) { exit 2 }',
16 'while ($true) { Start-Sleep -Seconds 3600 }',
17].join('; ')
18
19export function inhibitorArgv(platform: Platform): string[] | undefined {
20 switch (platform) {
21 case 'linux':
22 return ['systemd-inhibit', '--what=idle:sleep', `--who=${WHO}`, `--why=${WHY}`, '--mode=block', 'sleep', 'infinity']
23 case 'windows':
24 return ['powershell.exe', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WINDOWS_SCRIPT]
25 case 'macos':
26 return ['caffeinate', '-i']
27 default:
28 return undefined
29 }
30}
31
32/** `uname -s` output to a platform; Windows is told by `OS=Windows_NT` first. */
33export function platformOf(osVar: string | undefined, uname: string | undefined): Platform {
34 if (osVar === 'Windows_NT') return 'windows'
35 const name = uname?.trim()
36 if (name === 'Linux') return 'linux'
37 if (name === 'Darwin') return 'macos'
38 return 'unsupported'
39}
40types/index.d.ts 98 lines1export type CacheKeeperTtl = '5m' | '1h';
2
3/**
4 * One model request of the main loop, or a keep-alive; or a compaction, which
5 * leaves nothing cached for the conversation it leaves behind.
6 */
7export type CacheKeeperSample = {
8 turnId: string;
9 kind: 'turn' | 'keep-alive' | 'compact';
10 /** When the request started (a compaction: when it ended): the cache lifetime counts from here. */
11 at: number;
12 model: string;
13 read: number;
14 write: number;
15 fresh: number;
16 output: number;
17 /** A compaction's conversation size before and after, in tokens, when Claude Code recorded it. */
18 before?: number;
19 after?: number;
20};
21
22export type CacheKeeperTurnRow = {
23 turnId: string;
24 kind: CacheKeeperSample['kind'];
25 steps: number;
26 read: number;
27 write: number;
28 fresh: number;
29 before?: number;
30 after?: number;
31};
32
33export type CacheKeeperContext = {
34 tokens?: number;
35 window: number;
36 percent?: number;
37 /** Tokens at which Claude Code compacts on its own; absent when unknown or off. */
38 autoAt?: number;
39 /** Whether Claude Code compacts on its own; absent until known. */
40 isAutoOn?: boolean;
41};
42
43export type CacheKeeperLimit = {
44 kind: string;
45 percentUsed: number;
46 resetsAt?: string;
47};
48
49export type CacheKeeperStatus = {
50 /** What the keeper is doing, as the band says it. */
51 label: string;
52 tone: 'ok' | 'warn' | 'bad' | 'dim';
53 next?: 'keep-alive' | 'compact';
54 dueAt?: number;
55 compactAt?: number;
56 /** When Claude Code compacts the idle session itself; the keeper's compact is then the fallback. */
57 idleCompactAt?: number;
58 isBusy: boolean;
59 isPaused: boolean;
60 done: number;
61 planned: number;
62};
63
64export type CacheKeeperSleep = {
65 platform: 'linux' | 'windows' | 'macos' | 'unsupported';
66 isActive: boolean;
67 error?: string;
68};
69
70/** Everything the band and the pane draw, refreshed by the module. */
71export type CacheKeeperView = {
72 now: number;
73 ttl: CacheKeeperTtl;
74 ttlSource: string;
75 last?: CacheKeeperSample;
76 turns: CacheKeeperTurnRow[];
77 context?: CacheKeeperContext;
78 limits: CacheKeeperLimit[];
79 keeper: CacheKeeperStatus;
80 sleep: CacheKeeperSleep;
81 /** The window near its limit (`7d 78%`) for which Claude Code skips its idle compaction. */
82 idleSkip?: string;
83 lastKeepAlive?: CacheKeeperSample;
84 /** The main loop's model and effort, as its last request named them. */
85 model?: string;
86 effort?: string;
87};
88
89declare module 'claude-code' {
90 interface PluginState {
91 'cache-keeper': {
92 view: CacheKeeperView | null;
93 /** The session's requests, kept here so a reload of the mod picks them up. */
94 samples: CacheKeeperSample[];
95 };
96 }
97}
98