A one-line band above the prompt: context used, and a countdown until the prompt cache goes cold

A Claude Code mod that puts one line above the prompt: how long until the prompt cache goes cold, how full the context window is, and a separate clock for subagents while one is warm.

Every request to the model writes the conversation to the prompt cache. If the next request arrives before the cache expires, everything so far is read back at a fraction of the price. If it arrives after, the whole context is sent again at full price. Claude Code never shows you which side of that line you are on. This does.
sub clock.cache cold, and a toast tells you the next message is a full-price write.measured once it has seen one.onWarning):handoff (the default): Claude writes a handoff note, HANDOFF-<first 8 characters of the session id>.md, in the project root, in case you don't come back. Each session has its own file, so parallel sessions in one folder don't overwrite each other.off: just the toast.It runs once per idle stretch and re-arms when you send a message.
Idle compaction in /config, and change the 200K minimum with CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS. The mod's own compact option is gone; a saved compact now acts as off./cache-clock prints the same line as text.Does nothing in -p / SDK sessions.
The handoff is the only thing it sends to Claude: one short turn on a warm cache.
claude plugin marketplace add ray-amjad/claude-code-mods
claude plugin install cache-clock@claude-code-mods
Or inside Claude Code: /plugin marketplace add ray-amjad/claude-code-mods, then /plugin install cache-clock@claude-code-mods.
onWarning is a plugin setting: set it with /plugin configure cache-clock@claude-code-mods. The rest are optional environment variables. Minutes may be fractional.
| Variable | Default | What it does | | :- | :- | :- | | CACHE_CLOCK_MAIN_TTL_MIN | 60 | Main session TTL. Setting it pins it; otherwise the mod reads it from the transcript. | | CACHE_CLOCK_SUB_TTL_MIN | 5 | Subagent TTL | | CACHE_CLOCK_WARN_MIN | 5 | Toast, the onWarning action and the colour red when this much is left | | CACHE_CLOCK_ON_WARNING | the setting | handoff or off; overrides the plugin setting | | CACHE_CLOCK_AUTO_HANDOFF | on | 0 means off (kept from older versions) | | CACHE_CLOCK_HANDOFF_DIR | project root | Folder the handoff notes go to | | CACHE_CLOCK_SOUND | off | 1 plays sounds/cooling.wav with the warning toast |
To watch the whole cycle in two minutes:
CACHE_CLOCK_MAIN_TTL_MIN=2 CACHE_CLOCK_WARN_MIN=1.5 claude
turn.step (one per model request) restarts the main clock, or the sub clock when the step carries an agentId. A one second $.clock.every redraws the band and checks the warning./recap and /btw send the conversation to the model outside a turn, so no turn.step fires for them. Their request reads the main cache all the same, so a command.run hook on each restarts the main clock too, while the cache is still warm (a bare /btw sends nothing and is ignored).usage.cache_creation: tokens in ephemeral_1h mean 1 hour, ephemeral_5m mean 5 minutes. On --resume it seeds the clock from the session's seconds_since_last_response.$.session.usage() at start, then the pushed session.measure figures.turn.start/turn.complete) and nothing has run since your last prompt, handoff calls $.prompt.submit. A prompt.submit hook re-arms it on your next prompt.assumed.sub, then ctx) instead of wrapping.claude --plugin-dir ./cache-clock
claude plugin validate .
claude plugin test .hooks/register.js 276 lines1// cache-clock: one line above the prompt that shows how full the context is
2// and how long until the prompt cache goes cold.
3
4// Defaults, in minutes. Each can be changed with an environment variable.
5const DEFAULT_MAIN_TTL_MIN = 60 // main session cache (matches what the transcripts record)
6const DEFAULT_SUB_TTL_MIN = 5 // subagent cache
7const DEFAULT_WARN_MIN = 5 // toast (and the onWarning action) when this much is left
8
9const MIN = 60_000
10
11// State shared by the hooks below
12const cfg = { mainTtl: DEFAULT_MAIN_TTL_MIN * MIN, subTtl: DEFAULT_SUB_TTL_MIN * MIN, warn: DEFAULT_WARN_MIN * MIN, sound: false, pinned: false, onWarning: 'handoff', handoffDir: '' }
13let ttlSource = 'assumed' // 'measured' once we read it from the transcript
14let mainAt = 0 // when the main session last sent a request (ms)
15let subAt = 0 // when a subagent last sent one
16let warned = false // toast already shown for this warm period
17let wentCold = false // "went cold" already shown
18let working = false // a turn is running
19let handedOff = false // handoff done since the user last sent something
20let context = null // { tokens, window, percent } from $.session.usage()
21let transcript = null // path to this session's .jsonl
22let headless = false // -p / SDK session: no band, so skip the transcript reads too
23
24// Read a number of minutes from an env var, or keep the default
25function minutes(value, fallback) {
26 const n = parseFloat(value ?? '')
27 return Number.isFinite(n) && n > 0 ? n * MIN : fallback
28}
29
30const ACTIONS = ['handoff', 'off']
31
32// What the warning does: the env var, then the old CACHE_CLOCK_AUTO_HANDOFF=0, then the setting.
33// The old 'compact' choice means 'off' now: Claude Code's own idle compaction does that job.
34export function pickAction(envAction, envAutoHandoff, setting) {
35 let action = envAction ?? (envAutoHandoff === '0' ? 'off' : setting)
36 if (action === 'compact') action = 'off'
37 return ACTIONS.includes(action) ? action : 'handoff'
38}
39
40async function loadConfig($, options) {
41 const main = await $.env.get('CACHE_CLOCK_MAIN_TTL_MIN')
42 cfg.mainTtl = minutes(main, DEFAULT_MAIN_TTL_MIN * MIN)
43 cfg.pinned = main !== undefined // a value you set wins over the transcript
44 cfg.subTtl = minutes(await $.env.get('CACHE_CLOCK_SUB_TTL_MIN'), DEFAULT_SUB_TTL_MIN * MIN)
45 cfg.warn = minutes(await $.env.get('CACHE_CLOCK_WARN_MIN'), DEFAULT_WARN_MIN * MIN)
46 cfg.sound = (await $.env.get('CACHE_CLOCK_SOUND')) === '1'
47 cfg.handoffDir = (await $.env.get('CACHE_CLOCK_HANDOFF_DIR')) ?? ''
48 // The plugin setting, unless an env var overrides it. CACHE_CLOCK_AUTO_HANDOFF=0 still means off.
49 cfg.onWarning = pickAction(await $.env.get('CACHE_CLOCK_ON_WARNING'), await $.env.get('CACHE_CLOCK_AUTO_HANDOFF'), options?.onWarning)
50}
51
52// The real TTL: each assistant row in the transcript says which cache bucket
53// it wrote to (ephemeral_1h or ephemeral_5m). Read the newest main-thread one.
54async function readTtl($) {
55 if (!transcript || cfg.pinned) return
56 for (const row of (await lastRows($, transcript)).reverse()) {
57 if (!row.includes('"cache_creation"')) continue
58 let msg
59 try { msg = JSON.parse(row) } catch { continue }
60 if (msg.type !== 'assistant' || msg.isSidechain) continue
61 const cc = msg.message?.usage?.cache_creation ?? {}
62 if (cc.ephemeral_1h_input_tokens > 0) { cfg.mainTtl = 60 * MIN; ttlSource = 'measured'; return }
63 if (cc.ephemeral_5m_input_tokens > 0) { cfg.mainTtl = 5 * MIN; ttlSource = 'measured'; return }
64 // a pure cache read does not say which bucket; look further back
65 }
66}
67
68// The transcript's last 300 rows. A long session's transcript is past the
69// 4 MiB $.fs.read takes, so a command reads its end: `tail` on Mac and Linux,
70// PowerShell on Windows, which has no tail (the path goes in an env var, not
71// the script). If the command fails, $.fs.read is the last resort.
72export function tailCommand(isWindows, path) {
73 if (!isWindows) return [['tail', '-n', '300', path], {}]
74 const script =
75 '$r = New-Object IO.StreamReader((New-Object IO.FileStream($env:CACHE_CLOCK_FILE, "Open", "Read", "ReadWrite")), [Text.Encoding]::UTF8); ' +
76 '$q = New-Object System.Collections.Generic.Queue[string]; ' +
77 'while ($null -ne ($l = $r.ReadLine())) { $q.Enqueue($l); if ($q.Count -gt 300) { [void]$q.Dequeue() } }; ' +
78 '$b = [Text.Encoding]::UTF8.GetBytes(($q -join "`n") + "`n"); [Console]::OpenStandardOutput().Write($b, 0, $b.Length)'
79 return [['powershell', '-NoProfile', '-NonInteractive', '-Command', script], { env: { CACHE_CLOCK_FILE: path } }]
80}
81async function lastRows($, path) {
82 try {
83 const [argv, init] = tailCommand((await $.env.get('OS')) === 'Windows_NT', path)
84 const r = await $.process.run(argv, init)
85 if (r.exitCode === 0) return lastLines(r.stdout, 300)
86 } catch {}
87 return lastLines(await $.fs.read(path).catch(() => ''), 300)
88}
89
90// The last n lines of a file's text, CRLF or LF
91export function lastLines(text, n) {
92 const lines = String(text).split(/\r?\n/)
93 if (lines[lines.length - 1] === '') lines.pop()
94 return lines.slice(-n)
95}
96
97// 47:05 or 3:09
98function clock(ms) {
99 const s = Math.max(0, Math.ceil(ms / 1000))
100 return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0')
101}
102
103function fmtTokens(n) {
104 if (n >= 1_000_000) return +(n / 1_000_000).toFixed(1) + 'M'
105 return n >= 1000 ? Math.round(n / 1000) + 'k' : String(n)
106}
107
108// Everything the band shows, as plain pieces so /cache-clock can print it too
109function snapshot(now) {
110 const left = mainAt ? mainAt + cfg.mainTtl - now : 0
111 const subLeft = subAt ? subAt + cfg.subTtl - now : 0
112 // Colour: green, then yellow in the last quarter, red inside the warning window
113 let color = 'green'
114 if (!mainAt || left <= 0) color = 'gray'
115 else if (left <= cfg.warn) color = 'red'
116 else if (left <= cfg.mainTtl / 4) color = 'yellow'
117 const ttl = (cfg.mainTtl >= 60 * MIN ? cfg.mainTtl / (60 * MIN) + 'h' : cfg.mainTtl / MIN + 'm') + ' ttl ' + (cfg.pinned ? 'set' : ttlSource)
118 const cache = !mainAt ? 'cache: no request yet' : left > 0 ? 'cache ' + clock(left) + ' left' : 'cache cold'
119 let ctx = 'ctx --'
120 if (context?.tokens) {
121 const pct = context.percent ?? Math.round((context.tokens / context.window) * 100)
122 const filled = Math.round(pct / 10)
123 ctx = 'ctx ' + fmtTokens(context.tokens) + '/' + fmtTokens(context.window) + ' ' + pct + '% ' + '▰'.repeat(filled) + '▱'.repeat(10 - filled)
124 }
125 const sub = subLeft > 0 ? 'sub ' + clock(subLeft) : null
126 return { color, cache, ttl, ctx, sub, left }
127}
128
129function asText(s) {
130 return [s.cache + ' (' + s.ttl + ')', s.ctx, s.sub].filter(Boolean).join(' | ')
131}
132
133// The handoff prompt. The marker lets prompt.submit tell it from the user's own prompts.
134const HANDOFF_MARKER = 'cache-clock handoff'
135
136// One note per session, so parallel sessions in one folder never overwrite
137// each other's. It goes to CACHE_CLOCK_HANDOFF_DIR, else the project root
138// (not the shell's current folder, which a `cd` can move into a nested repo).
139export function handoffPath(dir, sessionId) {
140 return dir.replace(/[\\/]+$/, '') + '/HANDOFF-' + String(sessionId).slice(0, 8) + '.md'
141}
142function handoffText(file) {
143 return '(' + HANDOFF_MARKER + ') The prompt cache goes cold soon and the user has not replied. While the cache is still warm, write a short handoff note to ' + file + ': the goal, what is done, what is next, open questions, and the key files. Keep it brief, and write it even if the session has been short. Do nothing else. A fresh session will start from it if the user does not come back.'
144}
145
146// A main-session request just read or wrote the cache: a full TTL again
147function restartMain(now) {
148 mainAt = now
149 warned = false
150 wentCold = false
151}
152
153// /recap and /btw send the whole conversation to the model as a side request.
154// It reads the main cache, so it keeps it warm, but it is no turn, so no
155// turn.step fires for it (#15). Only a warm cache counts: a cold one the side
156// request may not write back at the main TTL, so the band stays honest. A bare
157// /btw asks nothing and sends nothing.
158async function sideRequest($, e, next) {
159 const now = await $.clock.now()
160 const asks = e.command !== 'btw' || String(e.args ?? '').trim() !== ''
161 if (asks && mainAt && mainAt + cfg.mainTtl > now) restartMain(now)
162 return next(e)
163}
164
165// Once a second: warn near expiry, note when it goes cold, redraw the band
166async function tick($) {
167 const s = snapshot(await $.clock.now())
168 if (mainAt && s.left > 0 && s.left <= cfg.warn && !warned) {
169 warned = true
170 // Idle and nothing done since the user's last message: act while the cache is warm
171 if (cfg.onWarning !== 'off' && !working && !handedOff) {
172 handedOff = true
173 const file = handoffPath(cfg.handoffDir || (await $.session.root()), await $.session.id())
174 $.ui.toast('Prompt cache goes cold in ' + clock(s.left) + '. No reply, so Claude is writing ' + file.split(/[\\/]/).pop() + ' while it is warm.', { timeoutMs: 10_000 })
175 $.prompt.submit({ text: handoffText(file) }).catch(() => {}) // waits for idle; don't await in the tick
176 } else {
177 $.ui.toast('Prompt cache goes cold in ' + clock(s.left) + '. Send something to keep it warm.', { timeoutMs: 10_000 })
178 }
179 if (cfg.sound) $.audio.play({ asset: 'sounds/cooling.wav' }).catch(() => {})
180 }
181 if (mainAt && s.left <= 0 && !wentCold) {
182 wentCold = true
183 $.ui.toast('Prompt cache is cold. The next message re-sends the whole context at full price.')
184 }
185 $.ui.invalidate('ui.render')
186}
187
188export function register(on, options) {
189 on('session.start', async ($, e, next) => {
190 // Headless (-p, SDK): no band, and the timer would submit handoff turns
191 // or compact with nobody at the prompt. Do nothing.
192 headless = e.isInteractive === false
193 if (headless) return next(e)
194 await loadConfig($, options)
195 // classic.SessionStart fires before this, so the transcript path is known: read the TTL here
196 await readTtl($).catch(() => undefined)
197 context = (await $.session.usage()).context
198 await $.command.register({ name: 'cache-clock', description: 'Print the cache countdown and context use' })
199 $.clock.every(1000, () => tick($))
200 return next(e)
201 })
202
203 // On a resume, the session tells us how long ago the last answer was,
204 // so the clock picks up where it left off. This fires before session.start, so
205 // it can't tell a headless session yet: session.start does the TTL read.
206 on('classic.SessionStart', async ($, e, next) => {
207 transcript = e.transcript_path ?? transcript
208 if (e.seconds_since_last_response != null) mainAt = (await $.clock.now()) - e.seconds_since_last_response * 1000
209 return next(e)
210 }).catch(($, e, next) => (next.called ? undefined : next(e))) // never block the session on our error
211
212 // Track whether a turn is running, so the warning action never queues behind one
213 on('turn.start', async ($, e, next) => { working = true; return next(e) })
214 on('turn.complete', async ($, e, next) => { working = false; return next(e) })
215
216 // A prompt from the user (not our own handoff) re-arms the warning action
217 on('prompt.submit', async ($, e, next) => {
218 if (!String(e.text ?? '').includes(HANDOFF_MARKER)) handedOff = false
219 return next(e)
220 })
221
222 // Every request to the model refreshes its cache: restart the right clock
223 on('turn.step', async function* ($, e, next) {
224 const now = await $.clock.now()
225 if (e.agentId) subAt = now
226 else restartMain(now)
227 yield* next(e)
228 })
229
230 // /recap and /btw: a side request that keeps the main cache warm
231 // (a hook that fails is skipped and the command still runs)
232 on('command.run', { command: 'recap' }, sideRequest)
233 on('command.run', { command: 'btw' }, sideRequest)
234
235 // After each turn, check which TTL the API actually used
236 on('classic.Stop', async ($, e, next) => {
237 transcript = e.transcript_path ?? transcript
238 if (!headless) await readTtl($)
239 return next(e)
240 }).catch(($, e, next) => (next.called ? undefined : next(e)))
241
242 // Context figures, pushed after each turn
243 on('session.measure', async ($, e, next) => {
244 context = e.context
245 return next(e)
246 })
247
248 // The band itself: one line above the prompt, with the other mods' bands drawn under it
249 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
250 if (e.props.hasSurvey) return next(e)
251 // Our line takes one row, so the bands below get one fewer
252 // A band below that fails must not take ours with it
253 let below = null
254 try { below = await next({ ...e, props: { ...e.props, maxRows: Math.max(0, e.props.maxRows - 1) } }) } catch {}
255 const { Box, Text } = $.ui.resolve(e)
256 const s = snapshot(await $.clock.now())
257 // Pieces in order of importance; drop from the end until it fits one line
258 const pieces = [
259 { text: '◷ ' + s.cache, style: { color: s.color, bold: s.color === 'red' } },
260 { text: s.ctx, style: {} },
261 s.sub && { text: s.sub, style: { dimColor: true } },
262 { text: s.ttl, style: { dimColor: true } },
263 ].filter(Boolean)
264 const SEP = ' · '
265 while (pieces.length > 1 && pieces.map((p) => p.text).join(SEP).length > e.props.bodyColumns) pieces.pop()
266 const parts = pieces.flatMap((p, i) => i ? [h(Text, { dimColor: true }, SEP), h(Text, p.style, p.text)] : [h(Text, p.style, p.text)])
267 const line = h(Box, {}, h(Text, { wrap: 'truncate-end' }, ...parts))
268 return below ? h(Box, { flexDirection: 'column' }, line, below) : line
269 })
270
271 on('command.run', { command: 'cache-clock' }, async ($) => {
272 await readTtl($)
273 return { text: asText(snapshot(await $.clock.now())) }
274 })
275}
276