Prompt-cache meter above the Claude Code prompt: how many tokens each request read from, wrote to and sent past the cache, a live countdown to the cache's…

A prompt-cache meter above the Claude Code prompt. Every request Claude makes reports how much of its prompt the cache served, how much it wrote and how much went uncached; this mod keeps those numbers per request and per turn, counts down to the moment the cache lapses and tells you what to do about it: keep going, /compact or /clear.
cache ██████████ 98% read 80k · wrote 1k · new 300 ⏱ 3:41 5m · warm: keep going
cache ░░░░░░░░░░ 0% read 0 · wrote 52k · new 300 ⏱ 4:58 5m · cache missed: model changed (…)
cache ██████████ 98% read 150k · wrote 1k · new 300 ⏱ 0:00 5m · expired: the next message rewrites 151k tokens. /compact first, or /clear if the task is done
/cache opens a pane: the time left with a solid bar that shrinks as the cache runs out (green, yellow below 40% of the lifetime, red from the warning threshold), a stacked read / wrote / new bar for the last request, and a colour-coded table with one row per turn. Bars are filled cells and columns have fixed widths with no-break spaces, so the terminal and the Desktop (HTML) pane render the same.
From Anthropic's prompt caching documentation:
input_tokens (uncached remainder) + cache_read_input_tokens + cache_creation_input_tokens./compact./clear starts a new conversation in the same process, so the meter and the /cache table start over with it. A change in the prefix (model, effort or thinking settings, tool set, system prompt, CLAUDE.md) makes the next request write instead of read. The mod names the cause when it sees a miss: model changed, the cache had lapsed, or the prefix changed.The mod follows Claude Code's own rules (prompt caching: cache lifetime, Claude Code 2.1.242 or later). For the main conversation the TTL is the first match of:
| # | Source | Result |
|---|---|---|
| 1 | the mod's ttl option (5m / 1h) | what you set |
| 2 | FORCE_PROMPT_CACHING_5M=1 | 5 minutes |
| 3 | CLAUDE_CODE_PROMPT_CACHE_TTL | 5m or 1h |
| 4 | the promptCacheTtl setting (local, project or user settings file) | 5m or 1h |
| 5 | ENABLE_PROMPT_CACHING_1H=1 | 1 hour |
| 6 | the account | 1 hour on a Claude subscription within its plan usage; 5 minutes on usage credits, an API key or a cloud provider |
The account comes from the rate-limit windows the last response reported: a five_hour or seven_day window means a subscription, and one at 100% means requests now draw on usage credits. An API key or a cloud provider reports no such window, and before the first response nothing is known, so the mod starts from 5 minutes there. Managed settings are not readable from a mod.
On top of that the mod watches the traffic, which beats rows 2 to 6: a request that hits the cache more than 5 minutes after the previous one proves the 1-hour lifetime (a later miss does not undo it, since a changed prefix looks the same), and a miss 5 to 60 minutes after the previous request, with the same model and a prompt that did not shrink, says the entry lapsed, so 5 minutes (a later hit overrules it). That covers what the mod cannot see: managed settings, a gateway that rewrites the TTL, or a subscription that ran out of plan usage mid-session. The pane header names the source in use.
Why the mod infers instead of reading it: the API names the TTL of each write (cache_creation.ephemeral_5m_input_tokens / ephemeral_1h_input_tokens) and Claude Code's status line exposes it as prompt_cache.ttl, but the mod API passes on only the four token counts. To check by hand, claude -p "hello" --output-format json and read usage.cache_creation.
Other switches read from the environment at session start:
| Variable | Effect on the meter |
|---|---|
DISABLE_PROMPT_CACHING=1 (and _HAIKU, _SONNET, _OPUS) | the band says caching is off for that model |
Claude Code can compact a large terminal conversation by itself while you are away, shortly before its one-hour cache lapses, so your next message reads a summary instead of rewriting the whole prompt. When that will happen, the band adds a magenta ⇣ 41:12 next to the cache countdown: the time until Claude Code compacts if nobody types. After it happens, a toast and the band say compacted while idle (240k → 30k), and the old countdown stops.
It fires at 90% of the cache lifetime (about 54 minutes) only when all of these hold (read from the 2.1.299 build, not from documentation):
| Condition | Where the mod reads it |
|---|---|
| The feature is rolled out to your account | the tengu_sunny_locket flag Claude Code caches in ~/.claude.json; mode: "off" means it never runs, and "idleCompaction": true does not turn it on |
| Auto-compact is on | DISABLE_COMPACT, DISABLE_AUTO_COMPACT, autoCompactEnabled |
| Idle compaction is not turned off | "idleCompaction": false in settings.json |
| The cache lives one hour and is still warm | the same lifetime as the main countdown |
| The prompt is at least the threshold | CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS, never below 100K, 200K when unset |
The mod reads only those two keys from ~/.claude.json (or $CLAUDE_CONFIG_DIR/.claude.json); without the cached flag it shows no idle countdown. /cache shows a line saying whether it is armed and, if not, why (for example not rolled out to this account (mode off) or waits for 200k tokens; the prompt is 80k). Two settings in the catalog set it up: environment/idle-compaction-early (from 100K) and environment/idle-compaction-off.
turn.step: reads each main-loop request's usage (subagents have their own prefixes and are left out)$.clock.every(1000): redraws the countdown, and only while its text changes, so an idle expired session costs nothingui.render on AbovePrompt (the band) and on Pane (/cache)session.compact: notes a compaction of the main conversation, and announces one with trigger idle$.ui.toast: once per cache entry at the warning threshold (60 s by default) and again at 10, 3, 2 and 1 seconds left, for prompts of 20k tokens or more ttl: string "auto" | "5m" | "1h" (default auto)
warnSeconds: number countdown threshold for the yellow state and the toast (default 60)
compactAtTokens: number prompt size that makes an expired cache suggest /compact (default 100000)
band: boolean row above the prompt (default true)
status: boolean entry under the prompt, "cache 98% · 3:41" (default false)
toast: boolean toasts at the threshold, 10, 3, 2 and 1 s (default true)
idleCompact: boolean idle compaction countdown and notice (default true)
The 100k compactAtTokens is a judgement, not a figure from the documentation: lower it if your model's cache writes are expensive for you.
npx claude-code-templates@latest --mod observability/prompt-cache-control
claude
It is written to .claude/skills/prompt-cache-control/, which Claude Code auto-loads as prompt-cache-control@skills-dir once the workspace trust prompt is accepted. For one session with hot reload: claude --plugin-dir .claude/skills/prompt-cache-control. claude plugin validate .claude/skills/prompt-cache-control prints every event it hooks and every $ call it makes; claude plugin test .claude/skills/prompt-cache-control runs its tests.
Options are read from user settings (~/.claude/settings.json, never project settings), --settings <file> or managed settings, under the plugin's full id:
{ "pluginConfigs": { "prompt-cache-control@skills-dir": { "options": { } } } }
Requirements. Mods are on by default in Claude Code 2.1.287+. Typed against Anthropic's declarations: https://github.com/anthropics/claude-code/tree/main/mods
hooks/prompt-cache-control.tsx 529 lines1/**
2 * prompt-cache-control — Claude Mod
3 *
4 * A prompt-cache meter for Claude Code. Every main-loop request reports how
5 * many prompt tokens the cache served (`cache_read_input_tokens`), wrote
6 * (`cache_creation_input_tokens`) and sent uncached (`input_tokens`); this mod
7 * keeps those per request and per turn, counts down to the moment the cache
8 * lapses, and says what to do about it: keep going, /compact or /clear.
9 *
10 * - `turn.step` reads each main-loop request's usage (subagents have their
11 * own prefixes and are left out)
12 * - `$.clock.every(1000)` redraws the countdown, and only while its text
13 * changes: an idle, expired session costs nothing
14 * - a row above the prompt (the AbovePrompt component), an optional status
15 * line entry, and `/cache`, a pane with one row per turn
16 * - idle compaction (Claude Code 2.1.290+): when Claude Code will compact
17 * the conversation by itself before the 1-hour cache lapses, the band
18 * counts down to that moment as well as to the expiry, and
19 * `session.compact` (trigger "idle") says when it happened (see idlePolicy
20 * in ./cache.ts for the conditions)
21 *
22 * The lifetime is counted from the start of the request that last wrote or read
23 * the cache, as Anthropic documents it. Which lifetime Claude Code asked for
24 * follows its documented rules (see decideTtl in ./cache.ts): FORCE_PROMPT_CACHING_5M,
25 * CLAUDE_CODE_PROMPT_CACHE_TTL, the promptCacheTtl setting, ENABLE_PROMPT_CACHING_1H,
26 * then the account (1 hour on a Claude subscription, 5 minutes otherwise). The
27 * API names the TTL of a write but the mod API passes on only the token counts,
28 * so the mod also watches the gaps between requests (a hit after more than 5
29 * minutes proves 1 hour; see observeTtl). `ttl: "5m" | "1h"` pins it.
30 *
31 * Needs Claude Code >= 2.1.287.
32 *
33 * Options (pluginConfigs["prompt-cache-control@skills-dir"].options):
34 * ttl: "auto" | "5m" | "1h" cache lifetime (default auto)
35 * warnSeconds: number countdown threshold for the warning (default 60)
36 * compactAtTokens: number prompt size that makes an expired cache suggest /compact (default 100000)
37 * band: boolean row above the prompt (default true)
38 * status: boolean entry under the prompt (default false)
39 * toast: boolean toasts near expiry: at warnSeconds, then 10, 3, 2 and 1 s (default true)
40 * idleCompact: boolean idle compaction countdown and notice (default true)
41 */
42import type { EngineInterface, Register } from 'claude-code'
43import {
44 advise,
45 COUNTDOWN_MARKS,
46 bar,
47 byTurn,
48 fit,
49 fmtClock,
50 fmtTokens,
51 hitRatio,
52 idleCompactAt,
53 idlePolicy,
54 isCachingDisabled,
55 accountOf,
56 decideTtl,
57 observeTtl,
58 lifeColor,
59 lifeRatio,
60 nextToastMark,
61 positive,
62 promptTokens,
63 remainingMs,
64 rowRatio,
65 segments,
66} from './cache.ts'
67import type { Account, Advice, CacheEnv, IdleCompact, Sample, Ttl } from './cache.ts'
68
69const PANE = 'cache'
70const COMMAND = 'cache'
71const KEEP = 200
72// below this a lapsed cache costs too little to interrupt anyone about
73const TOAST_MIN_TOKENS = 20_000
74
75let samples: Sample[] = []
76let ttl: Ttl = '5m'
77let baseTtl: Ttl = '5m'
78let pinned = false
79let observed: Ttl | undefined
80let setting: unknown
81let account: Account = 'other'
82let ttlSource = 'default'
83let envSource = 'default'
84let env: CacheEnv = {}
85let timer: { cancel: () => void } | undefined
86let lastKey = ''
87let toastedFor = 0
88let toastLevel = Infinity
89let isPaneOpen = false
90let idle: IdleCompact = idlePolicy({})
91// the last compaction of the main conversation: a cache entry older than it is gone
92let compacted: { at: number; trigger: string; before?: number; after?: number } | undefined
93
94type Policy = { warnMs: number; compactAtTokens: number }
95
96function current(policy: Policy, now: number) {
97 const last = samples[samples.length - 1]
98 const prev = samples[samples.length - 2]
99 const disabled = last ? isCachingDisabled(last.model, env) : isCachingDisabled('', env)
100 if (last && compacted && compacted.at > last.startedAt) {
101 // the conversation the last request cached is gone: the next one starts from the summary
102 const sizes = compacted.before && compacted.after ? ` (${fmtTokens(compacted.before)} → ${fmtTokens(compacted.after)})` : ''
103 const how = compacted.trigger === 'idle' ? 'compacted while idle' : 'compacted'
104 const advice: Advice = { kind: 'cold', text: `${how}${sizes}: the next message starts from the summary` }
105 return { last, advice, left: 0, idleAt: undefined }
106 }
107 const advice: Advice = advise(last, prev, { ttl, ...policy }, now, disabled)
108 const left = last ? remainingMs(last, ttl, now) : 0
109 const idleAt = disabled ? undefined : idleCompactAt(last, ttl, idle, now)
110 return { last, advice, left, idleAt }
111}
112
113// "⇣ 41:12" until Claude Code compacts on its own, "⇣ now" once that moment has come
114const idleClock = (idleAt: number, now: number) => (idleAt > now ? `⇣ ${fmtClock(idleAt - now)}` : '⇣ now')
115
116const COLOR: Record<Advice['kind'], string | undefined> = {
117 warm: 'green',
118 soon: 'yellow',
119 expired: 'red',
120 miss: 'red',
121 off: undefined,
122 cold: undefined,
123 uncached: undefined,
124}
125
126function shortLine(policy: Policy, now: number): string {
127 const { last, advice, left } = current(policy, now)
128 if (!last || advice.kind === 'off') return `cache: ${advice.text}`
129 const clock = left > 0 ? ` · ${fmtClock(left)}` : ''
130 return `cache ${Math.round(hitRatio(last) * 100)}%${clock}`
131}
132
133type Settings = { promptCacheTtl?: unknown; idleCompaction?: unknown; autoCompactEnabled?: unknown }
134
135// the settings the mod follows, each from the first settings file that sets it (local over project over user)
136async function readSettings($: EngineInterface): Promise<Settings> {
137 const home = await $.env.get('HOME').catch(() => undefined)
138 const cwd = await $.session.cwd().catch(() => undefined)
139 const files = [cwd && `${cwd}/.claude/settings.local.json`, cwd && `${cwd}/.claude/settings.json`, home && `${home}/.claude/settings.json`]
140 const out: Settings = {}
141 for (const file of files) {
142 if (!file) continue
143 try {
144 const json = JSON.parse(await $.fs.read(file))
145 if (out.promptCacheTtl === undefined && (json.promptCacheTtl === '5m' || json.promptCacheTtl === '1h')) out.promptCacheTtl = json.promptCacheTtl
146 if (out.idleCompaction === undefined && typeof json.idleCompaction === 'boolean') out.idleCompaction = json.idleCompaction
147 if (out.autoCompactEnabled === undefined && typeof json.autoCompactEnabled === 'boolean') out.autoCompactEnabled = json.autoCompactEnabled
148 } catch {
149 // missing or unreadable: the next file
150 }
151 }
152 return out
153}
154
155// Claude Code's global config: the cached idle-compaction rollout flag, and autoCompactEnabled as /config saves it.
156// Only those two keys are kept; nothing else in the file is held by the mod.
157async function readGlobalConfig($: EngineInterface): Promise<{ flag?: unknown; autoCompact?: unknown }> {
158 const dir = await $.env.get('CLAUDE_CONFIG_DIR').catch(() => undefined)
159 const home = await $.env.get('HOME').catch(() => undefined)
160 const file = dir ? `${dir}/.claude.json` : home ? `${home}/.claude.json` : undefined
161 if (!file) return {}
162 try {
163 const json = JSON.parse(await $.fs.read(file))
164 const flag = json?.cachedGrowthBookFeatures?.tengu_sunny_locket
165 return { flag: flag && typeof flag === 'object' ? flag : undefined, autoCompact: json?.autoCompactEnabled }
166 } catch {
167 return {}
168 }
169}
170
171export const register: Register = (on, options) => {
172 const policy: Policy = {
173 warnMs: positive(options.warnSeconds, 60) * 1000,
174 compactAtTokens: positive(options.compactAtTokens, 100_000),
175 }
176 const showBand = options.band !== false
177 const showStatus = options.status === true
178 const wantToast = options.toast !== false
179 const showIdle = options.idleCompact !== false
180
181 on('session.start', async ($, e, next) => {
182 const r = await next(e)
183 samples = []
184 lastKey = ''
185 toastedFor = 0
186 compacted = undefined
187 const none = () => undefined
188 env = {
189 enable1h: await $.env.get('ENABLE_PROMPT_CACHING_1H').catch(none),
190 force5m: await $.env.get('FORCE_PROMPT_CACHING_5M').catch(none),
191 ttlVar: await $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL').catch(none),
192 disableAll: await $.env.get('DISABLE_PROMPT_CACHING').catch(none),
193 disableHaiku: await $.env.get('DISABLE_PROMPT_CACHING_HAIKU').catch(none),
194 disableSonnet: await $.env.get('DISABLE_PROMPT_CACHING_SONNET').catch(none),
195 disableOpus: await $.env.get('DISABLE_PROMPT_CACHING_OPUS').catch(none),
196 }
197 pinned = options.ttl === '5m' || options.ttl === '1h'
198 observed = undefined
199 const settings = await readSettings($)
200 setting = settings.promptCacheTtl
201 const global = await readGlobalConfig($)
202 idle = idlePolicy({
203 minTokensVar: await $.env.get('CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS').catch(none),
204 disableAuto: await $.env.get('DISABLE_AUTO_COMPACT').catch(none),
205 disableAll: await $.env.get('DISABLE_COMPACT').catch(none),
206 setting: settings.idleCompaction,
207 autoCompact: settings.autoCompactEnabled ?? global.autoCompact,
208 flag: global.flag,
209 })
210 account = accountOf((await $.session.usage().catch(() => undefined))?.rateLimits ?? [])
211 const choice = decideTtl(options.ttl, env, setting, account)
212 baseTtl = choice.ttl
213 ttl = baseTtl
214 envSource = choice.source
215 ttlSource = envSource
216
217 await $.command
218 .register({
219 name: COMMAND,
220 description: 'Prompt-cache usage per turn and the time left before it lapses (stop closes)',
221 argumentHint: '[stop]',
222 immediate: true,
223 })
224 .catch(err => $.ui.log(`prompt-cache-control: /${COMMAND} not registered: ${err}`))
225 $.ui.log(`prompt-cache-control loaded: ${ttl} cache (${ttlSource}), /${COMMAND} opens the table`, { to: 'debug' })
226 $.ui.log(`prompt-cache-control: idle compaction ${idle.on ? 'on' : 'off'}, ${idle.why}${idle.known ? '' : ' (rollout flag not found)'}`, { to: 'debug' })
227
228 timer?.cancel()
229 timer = $.clock.every(1000, () => {
230 const now = Date.now()
231 const { last, advice, left, idleAt } = current(policy, now)
232 const key = `${advice.kind}|${advice.text}|${left > 0 ? fmtClock(left) : ''}|${showIdle && idleAt ? idleClock(idleAt, now) : ''}`
233 if (key !== lastKey) {
234 lastKey = key
235 if (showStatus) $.ui.status(shortLine(policy, now))
236 $.ui.invalidate('ui.render')
237 }
238 if (wantToast && last && left > 0 && promptTokens(last) >= TOAST_MIN_TOKENS) {
239 if (toastedFor !== last.startedAt) {
240 toastedFor = last.startedAt
241 toastLevel = Infinity
242 }
243 // the first toast comes at warnSeconds, then 10, 3, 2 and 1 seconds; a late tick skips to the newest one
244 const secs = Math.ceil(left / 1000)
245 const mark = nextToastMark(secs, policy.warnMs / 1000, toastLevel)
246 if (mark !== undefined) {
247 toastLevel = mark
248 const tail = secs <= COUNTDOWN_MARKS[0] ? 'send a message now' : `send a message to keep ${fmtTokens(promptTokens(last))} tokens warm`
249 $.ui.toast(`cache expires in ${secs >= 60 ? fmtClock(left) : `${secs}s`}: ${tail}`)
250 }
251 }
252 })
253 return r
254 })
255
256 on('session.end', async ($, e, next) => {
257 // /clear starts a new conversation in the same process: its cache is a new one
258 if (e.reason === 'clear') {
259 samples = []
260 lastKey = ''
261 toastedFor = 0
262 compacted = undefined
263 observed = undefined
264 ttl = baseTtl
265 ttlSource = envSource
266 $.ui.invalidate('ui.render')
267 return next(e)
268 }
269 timer?.cancel()
270 timer = undefined
271 return next(e)
272 })
273
274 // a compaction of the main conversation replaces what the cache held; "idle" is Claude Code compacting on its own (2.1.290+)
275 on('session.compact', async ($, e, next) => {
276 const r = await next(e)
277 // a precompute only prepares a summary; the conversation is unchanged until it is used.
278 // "idle" is newer than the d.ts (2.1.283), hence the string: re-check when it is regenerated
279 const trigger = String(e.trigger)
280 if (e.agentId || trigger === 'precompute' || 'skip' in r) return r
281 compacted = { at: Date.now(), trigger, before: r.tokensBefore, after: r.tokensAfter }
282 lastKey = ''
283 if (trigger === 'idle') {
284 const sizes = r.tokensBefore && r.tokensAfter ? ` ${fmtTokens(r.tokensBefore)} → ${fmtTokens(r.tokensAfter)} tokens` : ''
285 $.ui.log(`prompt-cache-control: compacted while idle${sizes}, before the ${ttl} cache lapsed`)
286 if (showIdle && wantToast) $.ui.toast(`compacted while idle${sizes}: your next message starts from the summary`)
287 }
288 if (showStatus) $.ui.status(shortLine(policy, Date.now()))
289 $.ui.invalidate('ui.render')
290 return r
291 })
292
293 // each main-loop request: what the cache did with it
294 on('turn.step', async function* ($, e, next) {
295 if (e.agentId) return yield* next(e)
296 const startedAt = Date.now()
297 const r = yield* next(e)
298 if (r.usage) {
299 samples.push({
300 turnId: e.turnId,
301 index: e.index,
302 model: r.usage.model || e.model,
303 startedAt,
304 read: r.usage.cache_read_input_tokens,
305 write: r.usage.cache_creation_input_tokens,
306 fresh: r.usage.input_tokens,
307 output: r.usage.output_tokens,
308 })
309 if (samples.length > KEEP) samples = samples.slice(-KEEP)
310 if (!pinned) {
311 // the account can change under a session: a subscription running out of plan usage moves to usage credits
312 account = accountOf((await $.session.usage().catch(() => undefined))?.rateLimits ?? [])
313 const choice = decideTtl(options.ttl, env, setting, account)
314 baseTtl = choice.ttl
315 envSource = choice.source
316 if (observed === undefined) {
317 ttl = baseTtl
318 ttlSource = envSource
319 }
320 const seen = observeTtl(samples[samples.length - 2], samples[samples.length - 1], observed)
321 if (seen !== observed) {
322 observed = seen
323 ttl = seen ?? baseTtl
324 ttlSource = `observed from request timing; ${envSource} said ${baseTtl}`
325 $.ui.log(`prompt-cache-control: cache lifetime is ${ttl} (${ttlSource})`, { to: 'debug' })
326 }
327 }
328 lastKey = ''
329 if (showStatus) $.ui.status(shortLine(policy, Date.now()))
330 $.ui.invalidate('ui.render')
331 }
332 return r
333 })
334
335 on('command.run', { command: COMMAND }, async ($, e) => {
336 if (e.args.trim().toLowerCase() === 'stop') {
337 await $.ui.close({ id: PANE }).catch(() => undefined)
338 isPaneOpen = false
339 return { text: 'cache table closed' }
340 }
341 isPaneOpen = true
342 await $.ui.open({ id: PANE, title: 'cache', focus: true })
343 $.ui.invalidate('ui.render')
344 const { advice } = current(policy, Date.now())
345 return { text: `${ttl} cache (${ttlSource}) · ${advice.text} · /${COMMAND} stop closes` }
346 })
347
348 on('ui.close', async ($, e, next) => {
349 if (e.id !== PANE) return next(e)
350 isPaneOpen = false
351 return next(e)
352 })
353
354 on('ui.press', async ($, e, next) => {
355 if (e.plugin !== $.plugin.name || e.requestId !== PANE) return next(e)
356 if (e.element === 'close') await $.ui.close({ id: PANE }).catch(() => undefined)
357 return next(e)
358 })
359
360 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
361 if (!showBand || e.props.hasSurvey || isPaneOpen) return next(e)
362 const now = Date.now()
363 const { last, advice, left, idleAt } = current(policy, now)
364 if (!last && advice.kind !== 'off') return next(e)
365 const { Box, Text } = $.ui.resolve(e)
366 const columns = e.viewport?.columns ?? 100
367 const color = COLOR[advice.kind]
368 // The band is one instance: whatever the plugins beneath draw (another mod's band) stays, under this line.
369 const below = await next(e)
370 const stack = (own: ReturnType<typeof Text>) => (
371 <Box flexDirection="column">
372 {own}
373 {below}
374 </Box>
375 )
376
377 if (!last) return stack(<Text dimColor>{fit(`cache: ${advice.text}`, columns)}</Text>)
378
379 const ratio = hitRatio(last)
380 const wide = columns >= 90
381 return stack(
382 <Box flexDirection="row" columnGap={1}>
383 <Text bold color={color}>{advice.kind === 'warm' ? '●' : advice.kind === 'soon' ? '▲' : advice.kind === 'off' || advice.kind === 'cold' || advice.kind === 'uncached' ? '○' : '✖'}</Text>
384 <Text bold color="cyan">cache</Text>
385 <Text color={color}>{bar(ratio, wide ? 10 : 6)}</Text>
386 <Text bold>{`${Math.round(ratio * 100)}%`}</Text>
387 {wide ? (
388 <>
389 <Text color="green">{`read ${fmtTokens(last.read)}`}</Text>
390 <Text color="yellow">{`wrote ${fmtTokens(last.write)}`}</Text>
391 <Text color="cyan">{`new ${fmtTokens(last.fresh)}`}</Text>
392 </>
393 ) : (
394 <Text dimColor>{`${fmtTokens(promptTokens(last))} tok`}</Text>
395 )}
396 {advice.kind !== 'uncached' && advice.kind !== 'off' && advice.kind !== 'cold' && (
397 <Text bold color={left > 0 ? lifeColor(left, ttl, policy.warnMs) : 'red'}>{left > 0 ? `⏱ ${fmtClock(left)}` : '⏱ 0:00'}</Text>
398 )}
399 {showIdle && idleAt !== undefined && <Text bold color="magenta">{idleClock(idleAt, now)}</Text>}
400 <Text dimColor wrap="truncate-end">{`${ttl} · ${showIdle && idleAt !== undefined ? (idleAt > now ? 'left idle, Claude Code compacts it before the cache lapses' : 'compacting while idle') : advice.text}`}</Text>
401 </Box>,
402 )
403 })
404
405 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
406 if (e.requestId !== PANE) return next(e)
407 const { Box, Text, Button } = $.ui.resolve(e)
408 const width = Math.max(30, e.props.bodyColumns - 1)
409 // HTML collapses runs of spaces and trims a text's ends; a no-break space keeps them
410 const sp = (t: string) => (e.surface === 'terminal' ? t : t.replace(/ /g, ' '))
411 const now = Date.now()
412 const { last, advice, left, idleAt } = current(policy, now)
413 const all = byTurn(samples)
414 const counting = !!last && advice.kind !== 'uncached' && advice.kind !== 'off' && advice.kind !== 'cold'
415 // the countdown goes green, then yellow, then red as the cache runs out
416 const clockColor = counting ? lifeColor(left, ttl, policy.warnMs) : undefined
417 const stateColor = advice.kind === 'expired' || advice.kind === 'miss' ? 'red' : (clockColor ?? COLOR[advice.kind])
418 const hitColor = (pct: number) => (pct >= 80 ? 'green' : pct >= 40 ? 'yellow' : 'red')
419 // solid bars are filled Boxes, not block characters, so HTML draws no seams between cells
420 const solid = (key: string, parts: [number, string | undefined][]) => (
421 <Box key={key} flexDirection="row" height={1} flexShrink={0}>
422 {parts.map(([w, c], i) => (w > 0 ? <Box key={`${key}:${i}`} width={w} height={1} flexShrink={0} backgroundColor={c} /> : null))}
423 </Box>
424 )
425 const cell = (key: string, w: number, text: string, c?: string, bold = false) => (
426 <Box key={key} width={w} flexShrink={0} justifyContent="flex-end">
427 <Text color={c} bold={bold} dimColor={!c}>{sp(text)}</Text>
428 </Box>
429 )
430
431 const barW = Math.min(width, 40)
432 const life = lifeRatio(left, ttl)
433 const lifeFilled = Math.round(life * barW)
434 const [sr, sw, sn] = last ? segments(last.read, last.write, last.fresh, barW) : [0, 0, 0]
435 const rows = all.slice(-Math.max(3, (e.viewport?.rows ?? 24) - 16))
436 // why the idle-compaction line says what it says
437 const idleDetail = (at: number | undefined) => {
438 if (!idle.on) return `${idle.why}`
439 if (at !== undefined) return `if nobody types, Claude Code compacts at ${Math.round(idle.fraction * 100)}% of the 1h cache, ${idle.why}`
440 if (ttl !== '1h') return `needs the 1h cache; this session's is ${ttl}`
441 if (last && promptTokens(last) < idle.minTokens) return `waits for ${fmtTokens(idle.minTokens)} tokens; the prompt is ${fmtTokens(promptTokens(last))}`
442 return `armed while the cache is warm, ${idle.why}`
443 }
444 const icon = advice.kind === 'warm' ? '●' : advice.kind === 'soon' ? '▲' : advice.kind === 'expired' || advice.kind === 'miss' ? '✖' : '○'
445
446 return (
447 <Box flexDirection="column">
448 <Box key="title" flexDirection="row" columnGap={1}>
449 <Text bold color="cyan">{sp('⚡ PROMPT CACHE')}</Text>
450 <Text dimColor>{sp(`· ${ttl} lifetime (${ttlSource})`)}</Text>
451 </Box>
452
453 <Box key="clock" flexDirection="column" marginTop={1}>
454 <Text bold color={clockColor}>{sp(counting ? `⏱ ${left > 0 ? fmtClock(left) : '0:00'}` : '⏱ --:--')}</Text>
455 {counting ? (
456 <Box flexDirection="row" columnGap={1}>
457 {solid('life', [[lifeFilled, clockColor], [barW - lifeFilled, 'gray']])}
458 <Text dimColor>{sp(`${Math.round(life * 100)}%`)}</Text>
459 </Box>
460 ) : null}
461 </Box>
462
463 <Box key="advice" marginTop={1} flexDirection="column">
464 <Text bold color={stateColor}>{sp(`${icon} ${advice.text}`)}</Text>
465 {last ? <Text dimColor>{sp(fit(`${last.model} · prompt ${fmtTokens(promptTokens(last))} tokens`, width))}</Text> : null}
466 </Box>
467
468 {showIdle ? (
469 <Box key="idle" marginTop={1} flexDirection="column">
470 <Text bold color={idleAt !== undefined ? 'magenta' : undefined} dimColor={idleAt === undefined}>
471 {sp(idleAt !== undefined ? `${idleClock(idleAt, now)} idle compaction` : `⇣ idle compaction ${idle.on ? 'on' : 'off'}`)}
472 </Text>
473 <Text dimColor>{sp(fit(idleDetail(idleAt), width))}</Text>
474 </Box>
475 ) : null}
476
477 {last ? (
478 <Box key="stack" flexDirection="column" marginTop={1}>
479 <Box flexDirection="row" columnGap={1}>
480 {solid('stack', [[sr, 'green'], [sw, 'yellow'], [sn, 'cyan']])}
481 <Text bold color={hitColor(Math.round(hitRatio(last) * 100))}>{sp(`${Math.round(hitRatio(last) * 100)}% hit`)}</Text>
482 </Box>
483 <Box flexDirection="row" columnGap={2}>
484 <Text color="green">{sp(`■ read ${fmtTokens(last.read)}`)}</Text>
485 <Text color="yellow">{sp(`■ wrote ${fmtTokens(last.write)}`)}</Text>
486 <Text color="cyan">{sp(`■ new ${fmtTokens(last.fresh)}`)}</Text>
487 </Box>
488 </Box>
489 ) : null}
490
491 <Box key="table" flexDirection="column" marginTop={1}>
492 <Box key="head" flexDirection="row" columnGap={1}>
493 {cell('h:turn', 4, 'turn', 'cyan', true)}
494 {cell('h:steps', 5, 'steps', 'cyan', true)}
495 {cell('h:read', 6, 'read', 'green', true)}
496 {cell('h:wrote', 6, 'wrote', 'yellow', true)}
497 {cell('h:new', 5, 'new', 'cyan', true)}
498 {cell('h:hit', 4, 'hit', 'magenta', true)}
499 </Box>
500 {rows.length === 0 ? <Text dimColor>{sp('no requests yet')}</Text> : null}
501 {rows.map((row, i) => {
502 const n = all.length - rows.length + i + 1
503 const pct = Math.round(rowRatio(row) * 100)
504 return (
505 <Box key={`t:${row.turnId}`} flexDirection="row" columnGap={1}>
506 {cell(`c:turn:${row.turnId}`, 4, String(n))}
507 {cell(`c:steps:${row.turnId}`, 5, String(row.steps))}
508 {cell(`c:read:${row.turnId}`, 6, fmtTokens(row.read), 'green')}
509 {cell(`c:wrote:${row.turnId}`, 6, fmtTokens(row.write), 'yellow')}
510 {cell(`c:new:${row.turnId}`, 5, fmtTokens(row.fresh), 'cyan')}
511 {cell(`c:hit:${row.turnId}`, 4, `${pct}%`, hitColor(pct), true)}
512 </Box>
513 )
514 })}
515 </Box>
516
517 <Box key="foot" marginTop={1} flexDirection="column">
518 <Button key="close" label="close" onPress={() => {}} />
519 <Box key="legend" marginTop={1} flexDirection="column">
520 <Text color="green">{sp('■ read: served by the cache')}</Text>
521 <Text color="yellow">{sp('■ wrote: new cache entry')}</Text>
522 <Text color="cyan">{sp('■ new: sent uncached')}</Text>
523 </Box>
524 </Box>
525 </Box>
526 )
527 })
528}
529hooks/cache.ts 401 lines1/**
2 * cache.ts — the pure half of prompt-cache-control: no `$`, no engine.
3 *
4 * What it models, from Anthropic's prompt-caching documentation:
5 * - the cache lives 5 minutes by default, 1 hour when asked for; a read
6 * refreshes the entry at no extra cost, and the lifetime is measured from
7 * the START of the request that wrote or read it
8 * - a request's prompt is `input_tokens` (uncached remainder) +
9 * `cache_read_input_tokens` + `cache_creation_input_tokens`
10 * - writes cost 1.25x base input for 5m and 2x for 1h; reads about 0.1x
11 * (less on some models), so an expired cache on a large context is the
12 * expensive moment
13 * - a prefix change (model, effort/thinking settings, tool set, system
14 * prompt) makes the next request write instead of read
15 *
16 * Claude Code's own switches (read from the environment):
17 * ENABLE_PROMPT_CACHING_1H=1 ask for the 1-hour TTL
18 * FORCE_PROMPT_CACHING_5M=1 force the 5-minute TTL, beating the above
19 * DISABLE_PROMPT_CACHING=1 no caching; DISABLE_PROMPT_CACHING_{HAIKU,SONNET,OPUS}
20 * turn it off for that model family only
21 */
22
23export type Ttl = '5m' | '1h'
24
25export type CacheEnv = {
26 enable1h?: string
27 force5m?: string
28 /** CLAUDE_CODE_PROMPT_CACHE_TTL: "5m" or "1h" for the main conversation */
29 ttlVar?: string
30 disableAll?: string
31 disableHaiku?: string
32 disableSonnet?: string
33 disableOpus?: string
34}
35
36/** One main-loop request, as the API reported it. */
37export type Sample = {
38 turnId: string
39 index: number
40 model: string
41 /** ms since the epoch when the request started: the cache's lifetime is counted from here */
42 startedAt: number
43 read: number
44 write: number
45 fresh: number
46 output: number
47}
48
49export type AdviceKind = 'off' | 'cold' | 'uncached' | 'warm' | 'soon' | 'expired' | 'miss'
50
51export type Advice = {
52 kind: AdviceKind
53 /** one sentence for the band */
54 text: string
55}
56
57export type Policy = {
58 ttl: Ttl
59 warnMs: number
60 compactAtTokens: number
61}
62
63export const isOn = (v: string | undefined) => v === '1' || v?.toLowerCase() === 'true'
64
65/** What the account is billed as, as far as the mod can tell. */
66export type Account = 'subscription' | 'credits' | 'other'
67
68export type TtlChoice = { ttl: Ttl; source: string }
69
70const asTtl = (v: unknown): Ttl | undefined => (v === '5m' || v === '1h' ? v : undefined)
71
72/**
73 * Which lifetime Claude Code asks for on the main conversation, in the order
74 * its documentation gives (https://code.claude.com/docs/en/prompt-caching,
75 * "Choose the TTL yourself"), after the mod's own `ttl` option:
76 *
77 * FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL, the promptCacheTtl
78 * setting, ENABLE_PROMPT_CACHING_1H, then the default of the account: one
79 * hour on a Claude subscription within its plan usage, five minutes on usage
80 * credits, an API key or a cloud provider.
81 */
82export function decideTtl(option: unknown, env: CacheEnv, setting?: unknown, account?: Account): TtlChoice {
83 const pinned = asTtl(option)
84 if (pinned) return { ttl: pinned, source: 'the ttl option' }
85 if (isOn(env.force5m)) return { ttl: '5m', source: 'FORCE_PROMPT_CACHING_5M' }
86 const fromVar = asTtl(env.ttlVar)
87 if (fromVar) return { ttl: fromVar, source: 'CLAUDE_CODE_PROMPT_CACHE_TTL' }
88 const fromSetting = asTtl(setting)
89 if (fromSetting) return { ttl: fromSetting, source: 'the promptCacheTtl setting' }
90 if (isOn(env.enable1h)) return { ttl: '1h', source: 'ENABLE_PROMPT_CACHING_1H' }
91 if (account === 'subscription') return { ttl: '1h', source: 'Claude subscription default' }
92 if (account === 'credits') return { ttl: '5m', source: 'usage credits default' }
93 return { ttl: '5m', source: 'default' }
94}
95
96export const resolveTtl = (option: unknown, env: CacheEnv, setting?: unknown, account?: Account): Ttl =>
97 decideTtl(option, env, setting, account).ttl
98
99/**
100 * The account, from the rate-limit windows the last response reported: a
101 * five-hour or seven-day window means a Claude subscription, and one that is
102 * full means the next requests draw on usage credits. No window (an API key,
103 * a cloud provider, or no response yet) says nothing.
104 */
105export function accountOf(windows: readonly { kind: string; percentUsed: number }[]): Account {
106 const plan = windows.filter(w => w.kind === 'five_hour' || w.kind === 'seven_day')
107 if (plan.length === 0) return 'other'
108 return plan.some(w => w.percentUsed >= 100) ? 'credits' : 'subscription'
109}
110
111export function ttlMs(ttl: Ttl): number {
112 return ttl === '1h' ? 3_600_000 : 300_000
113}
114
115/** Caching switched off for this model by the environment. */
116export function isCachingDisabled(model: string, env: CacheEnv): boolean {
117 if (isOn(env.disableAll)) return true
118 const name = model.toLowerCase()
119 if (name.includes('haiku')) return isOn(env.disableHaiku)
120 if (name.includes('sonnet')) return isOn(env.disableSonnet)
121 if (name.includes('opus')) return isOn(env.disableOpus)
122 return false
123}
124
125export const promptTokens = (s: Sample) => s.read + s.write + s.fresh
126
127/** Share of the prompt the cache served, 0 to 1; 0 for an empty prompt. */
128export function hitRatio(s: Sample): number {
129 const total = promptTokens(s)
130 return total === 0 ? 0 : s.read / total
131}
132
133/** When the cache entry the sample touched lapses, ms since the epoch. */
134export const expiresAt = (s: Sample, ttl: Ttl) => s.startedAt + ttlMs(ttl)
135
136/** Zero for a request that read and wrote nothing: it created or refreshed no entry, so there is nothing to count down. */
137export function remainingMs(s: Sample, ttl: Ttl, now: number): number {
138 if (s.read + s.write === 0) return 0
139 return Math.max(0, expiresAt(s, ttl) - now)
140}
141
142/**
143 * Why a request that should have read the cache wrote it instead; undefined
144 * when it did not miss. A prompt that shrank is a /compact or /clear, not a
145 * miss, and the first request of a session has nothing to read.
146 */
147export function missReason(prev: Sample | undefined, cur: Sample, ttl: Ttl): string | undefined {
148 if (!prev) return undefined
149 const before = promptTokens(prev)
150 if (before === 0 || promptTokens(cur) < before * 0.7) return undefined
151 if (cur.read >= before * 0.5 || cur.write === 0) return undefined
152 if (cur.model !== prev.model) return `model changed (${prev.model} to ${cur.model})`
153 if (cur.startedAt - prev.startedAt > ttlMs(ttl)) return `the ${ttl} cache had lapsed`
154 return 'the prompt prefix changed (effort, tools, system prompt or CLAUDE.md)'
155}
156
157export function advise(last: Sample | undefined, prev: Sample | undefined, policy: Policy, now: number, disabled: boolean): Advice {
158 if (disabled) return { kind: 'off', text: 'prompt caching is off for this model (DISABLE_PROMPT_CACHING*)' }
159 if (!last) return { kind: 'cold', text: 'no request yet: the first one writes the cache' }
160 if (last.read + last.write === 0) {
161 return { kind: 'uncached', text: 'this request was not cached (prompt under the model minimum, or caching off)' }
162 }
163 const miss = missReason(prev, last, policy.ttl)
164 const left = remainingMs(last, policy.ttl, now)
165 const size = promptTokens(last)
166 if (left <= 0) {
167 const big = size >= policy.compactAtTokens
168 return {
169 kind: 'expired',
170 text: big
171 ? `expired: the next message rewrites ${fmtTokens(size)} tokens. /compact first, or /clear if the task is done`
172 : `expired: only ${fmtTokens(size)} tokens to rebuild, just keep going`,
173 }
174 }
175 if (left <= policy.warnMs) {
176 return { kind: 'soon', text: 'expires soon: any message refreshes it for free' }
177 }
178 if (miss) return { kind: 'miss', text: `cache missed: ${miss}` }
179 return { kind: 'warm', text: 'warm: keep going' }
180}
181
182export function fmtTokens(n: number): string {
183 if (n < 1000) return String(n)
184 if (n < 100_000) return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k`
185 if (n < 1_000_000) return `${Math.round(n / 1000)}k`
186 return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
187}
188
189/** m:ss, or h:mm:ss from an hour up. */
190export function fmtClock(ms: number): string {
191 const total = Math.max(0, Math.ceil(ms / 1000))
192 const h = Math.floor(total / 3600)
193 const m = Math.floor((total % 3600) / 60)
194 const s = total % 60
195 const pad = (n: number) => String(n).padStart(2, '0')
196 return h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`
197}
198
199export function bar(ratio: number, width: number): string {
200 const filled = Math.round(Math.min(1, Math.max(0, ratio)) * width)
201 return '█'.repeat(filled) + '░'.repeat(width - filled)
202}
203
204export type TurnRow = {
205 turnId: string
206 steps: number
207 read: number
208 write: number
209 fresh: number
210 output: number
211}
212
213/** Samples grouped by turn, oldest first, each turn's requests summed. */
214export function byTurn(samples: readonly Sample[]): TurnRow[] {
215 const rows: TurnRow[] = []
216 for (const s of samples) {
217 let row = rows[rows.length - 1]
218 if (!row || row.turnId !== s.turnId) {
219 row = { turnId: s.turnId, steps: 0, read: 0, write: 0, fresh: 0, output: 0 }
220 rows.push(row)
221 }
222 row.steps += 1
223 row.read += s.read
224 row.write += s.write
225 row.fresh += s.fresh
226 row.output += s.output
227 }
228 return rows
229}
230
231export const rowRatio = (r: TurnRow) => {
232 const total = r.read + r.write + r.fresh
233 return total === 0 ? 0 : r.read / total
234}
235
236export function fit(text: string, width: number): string {
237 return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}…`
238}
239
240export function positive(v: unknown, fallback: number): number {
241 return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : fallback
242}
243
244/** Share of the cache lifetime left, 0 to 1. */
245export function lifeRatio(leftMs: number, ttl: Ttl): number {
246 return Math.min(1, Math.max(0, leftMs / ttlMs(ttl)))
247}
248
249/**
250 * Widths of the three stacked-bar segments (read, wrote, new) over `width`
251 * cells: proportional, each non-empty part at least one cell, summing to width.
252 */
253export function segments(read: number, write: number, fresh: number, width: number): [number, number, number] {
254 const total = read + write + fresh
255 if (total === 0 || width <= 0) return [0, 0, 0]
256 const parts = [read, write, fresh]
257 const cells = parts.map(p => (p > 0 ? Math.max(1, Math.round((p / total) * width)) : 0))
258 let over = cells.reduce((a, b) => a + b, 0) - width
259 while (over !== 0) {
260 const i = over > 0 ? cells.indexOf(Math.max(...cells)) : parts.indexOf(Math.max(...parts))
261 cells[i] += over > 0 ? -1 : 1
262 over += over > 0 ? -1 : 1
263 }
264 return [cells[0], cells[1], cells[2]]
265}
266
267/** Seconds left at which a toast counts down after the one at the warning threshold. */
268export const COUNTDOWN_MARKS = [10, 3, 2, 1]
269
270/**
271 * The toast mark to fire now, or undefined. `level` is the mark last fired for
272 * this cache entry (Infinity before any); a late tick skips straight to the
273 * newest mark crossed, so a stalled clock never replays old ones.
274 */
275export function nextToastMark(secsLeft: number, warnSecs: number, level: number): number | undefined {
276 const marks = [warnSecs, ...COUNTDOWN_MARKS].filter(m => m <= warnSecs)
277 const due = marks.filter(m => secsLeft <= m && m < level)
278 return due.length ? Math.min(...due) : undefined
279}
280
281export type LifeColor = 'green' | 'yellow' | 'red'
282
283/** Countdown colour: green while there is plenty, yellow below 40% of the lifetime, red from the warning threshold down. */
284export function lifeColor(leftMs: number, ttl: Ttl, warnMs: number): LifeColor {
285 if (leftMs <= warnMs) return 'red'
286 return leftMs / ttlMs(ttl) <= 0.4 ? 'yellow' : 'green'
287}
288
289// requests are timed from their start, so a little slack keeps a hit that
290// landed just inside the lifetime from reading as proof of the longer one
291const SLACK_MS = 10_000
292
293/**
294 * What the traffic says about the cache lifetime, given the request before and
295 * `known`, what earlier requests already showed.
296 *
297 * - a hit (the cache served at least half of the previous prompt) more than
298 * 5 minutes after the previous request began proves the 1-hour lifetime,
299 * and nothing later undoes it: a miss afterwards is more likely a changed
300 * prefix than a lapse
301 * - a miss with the same model and a prompt that did not shrink, 5 minutes to
302 * an hour after the previous request, says the entry lapsed: 5 minutes
303 * (weaker: a changed prefix looks the same, so a later hit overrules it)
304 *
305 * Needed because the API names the TTL of a write (`cache_creation.ephemeral_*`)
306 * but Claude Code's mod API passes on only the four token counts.
307 */
308export function observeTtl(prev: Sample | undefined, cur: Sample, known: Ttl | undefined): Ttl | undefined {
309 if (!prev || prev.read + prev.write === 0 || cur.model !== prev.model) return known
310 const gap = cur.startedAt - prev.startedAt
311 const before = promptTokens(prev)
312 if (gap <= ttlMs('5m') + SLACK_MS) return known
313 if (cur.read >= before * 0.5) return '1h'
314 if (known === '1h') return known
315 const lapsed = cur.write > 0 && promptTokens(cur) >= before * 0.7 && gap < ttlMs('1h') + SLACK_MS
316 return lapsed ? '5m' : known
317}
318
319/**
320 * Idle compaction (Claude Code 2.1.290+): a terminal conversation left idle is
321 * compacted shortly before its one-hour cache lapses, so the next message reads
322 * a summary instead of rewriting the whole prefix. Claude Code fires it at
323 * `fraction` of the cache lifetime (0.9 of an hour: about 54 minutes) when all
324 * of these hold, read from the 2.1.299 build:
325 *
326 * - the rollout flag is on for the account (a server-side flag Claude Code
327 * caches in ~/.claude.json; `mode: "off"` there means it never runs, and
328 * `idleCompaction: true` does not turn it on)
329 * - auto-compact is on (no DISABLE_COMPACT / DISABLE_AUTO_COMPACT,
330 * autoCompactEnabled not false) and the idleCompaction setting is not false
331 * - the main conversation's cache lives one hour and is still warm
332 * - the prompt is at least minTokens: CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS,
333 * never below 100K, 200K when unset
334 */
335export const IDLE_MIN_FLOOR = 100_000
336export const IDLE_MIN_DEFAULT = 200_000
337export const IDLE_FRACTION = 0.9
338
339export type IdleInputs = {
340 /** CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS */
341 minTokensVar?: string
342 /** the idleCompaction setting */
343 setting?: unknown
344 /** the autoCompactEnabled setting */
345 autoCompact?: unknown
346 /** DISABLE_AUTO_COMPACT */
347 disableAuto?: string
348 /** DISABLE_COMPACT */
349 disableAll?: string
350 /** the cached rollout flag, `{ mode, minTokens?, fireAtFraction? }`; undefined when not found */
351 flag?: unknown
352}
353
354export type IdleCompact = {
355 /** whether Claude Code will compact this session while idle */
356 on: boolean
357 /** false when the rollout flag could not be read (then `on` is false) */
358 known: boolean
359 minTokens: number
360 fraction: number
361 /** one phrase: why it is off, or where the threshold came from */
362 why: string
363}
364
365const finite = (v: unknown): number | undefined => {
366 const n = typeof v === 'string' && v.trim() !== '' ? Number(v) : v
367 return typeof n === 'number' && Number.isFinite(n) ? n : undefined
368}
369
370export function idlePolicy(i: IdleInputs): IdleCompact {
371 const flag = i.flag && typeof i.flag === 'object' ? (i.flag as Record<string, unknown>) : undefined
372 const fromVar = finite(i.minTokensVar)
373 const raw = fromVar ?? finite(flag?.minTokens)
374 const minTokens = raw === undefined ? IDLE_MIN_DEFAULT : Math.max(IDLE_MIN_FLOOR, raw)
375 const f = finite(flag?.fireAtFraction)
376 const fraction = f === undefined ? IDLE_FRACTION : Math.min(0.95, Math.max(0.5, f))
377 const base = { minTokens, fraction, known: flag !== undefined }
378 if (isOn(i.disableAll) || isOn(i.disableAuto)) return { ...base, on: false, why: 'auto-compact is off (DISABLE_*COMPACT)' }
379 if (i.autoCompact === false) return { ...base, on: false, why: 'auto-compact is off (autoCompactEnabled)' }
380 if (i.setting === false) return { ...base, on: false, why: 'turned off (idleCompaction: false)' }
381 // without the cached flag there is no telling: a countdown to something that may never happen is worse than none
382 if (!flag) return { ...base, on: false, why: 'rollout flag not found in ~/.claude.json' }
383 const mode = flag.mode
384 if (mode !== 'compact' && mode !== 'compact_on_return') {
385 return { ...base, on: false, why: `not rolled out to this account (mode ${String(mode ?? 'off')})` }
386 }
387 const source = fromVar !== undefined ? 'CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS' : 'default'
388 return { ...base, on: true, why: `from ${fmtTokens(minTokens)} tokens (${source})` }
389}
390
391/**
392 * When Claude Code will compact this conversation if nobody types, ms since
393 * the epoch; undefined when it will not (off, a 5-minute cache, a prompt under
394 * the threshold, or a cache already lapsed).
395 */
396export function idleCompactAt(last: Sample | undefined, ttl: Ttl, idle: IdleCompact, now: number): number | undefined {
397 if (!last || !idle.on || ttl !== '1h') return undefined
398 if (promptTokens(last) < idle.minTokens || remainingMs(last, ttl, now) <= 0) return undefined
399 return last.startedAt + ttlMs(ttl) * idle.fraction
400}
401