Prompt cache countdown, session cost, rate limits and context window usage in the band above the prompt

Session figures in the band directly above the Claude Code prompt, on the terminal and in the desktop app's Code tab:

seconds_since_last_response), so the restored countdown is an estimate that can run long by up to that response's generation time and is shown followed by the word estimated in dim text, for example 4:00 estimated, until the next main-thread response that reads or writes the cache replaces it with the exact countdown. When Claude Code reports on resume that the prompt cache has likely expired, the row shows expired instead.showCredits to add their monthly credit spend as Credits, which is read when the session starts, so with it the row can show before any response./context's colors.Function hooks are an early-access Claude Code API that may change between releases without notice. CI tests this plugin on Claude Code 2.1.288. If the band does not appear, update Claude Code; a build where function hooks are still off by default needs CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 in its environment.
claude plugin marketplace add crane-valley/claude-plugins
claude plugin install session-band@crane-valley
Set them with /plugin configure session-band@crane-valley, in /config, or with --config KEY=VALUE on claude plugin install. Unset options take the defaults below.
| Option | Default | Meaning |
|---|---|---|
cacheTtl | 5m | The prompt cache TTL your main thread uses (5m or 1h). The plugin cannot read it from Claude Code, so a wrong value shows a wrong countdown. |
showCost | true | Show the session's cost. On a subscription this is the API price of the usage, not what you are billed. |
showCredits | false | Add the account's monthly usage-credit spend to the Limits row, as Claude Code's /usage shows it under Usage credits. The plugin asks the same endpoint with your own login at most every 5 minutes, or sooner after a failed request (30 seconds, doubling back up to 5 minutes). The endpoint is undocumented, so when it changes the row is left out; failed requests keep the last figure for up to 30 minutes. It carries no reset time, so none is shown. It needs a claude.ai login: on Bedrock, Vertex, a gateway or an API key the plugin sends no request and shows no Credits. |
The band above the prompt is one slot shared by every plugin. session-band appends its rows to whatever the plugins beneath it drew, so other plugins' rows stay visible; a plugin that draws the band without calling next(e) hides the ones beneath it.
MIT
hooks/register.tsx 403 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement } from 'claude-code'
3import type { CreditsReading, RateLimit } from '../types'
4
5const LABEL_WIDTH = 9
6const LIMIT_BAR_CELLS = 10
7const CONTEXT_BAR_CELLS = 20
8const TOP_CATEGORIES = 3
9const SECOND_MS = 1000
10const MINUTE_MS = 60 * SECOND_MS
11const TTL_MS: Record<string, number> = { '5m': 5 * MINUTE_MS, '1h': 60 * MINUTE_MS }
12const STEP_REFRESH_MS = 5 * SECOND_MS
13// The endpoint behind Claude Code's /usage "Usage credits"; undocumented, so every field is checked.
14const CREDITS_URL = 'https://api.anthropic.com/api/oauth/usage'
15const CREDITS_REFRESH_MS = 5 * MINUTE_MS
16// A session that starts with an expired login fails its first ask; /login would otherwise wait out the full interval.
17const CREDITS_RETRY_MS = 30 * SECOND_MS
18// The wait doubles with each failure in a row, so a lasting 429 or outage is not asked every 30 seconds.
19const creditsWait = (prev: CreditsReading) =>
20 prev.requestId !== null
21 ? CREDITS_ABANDON_MS
22 : prev.failures === 0
23 ? CREDITS_REFRESH_MS
24 : Math.min(CREDITS_RETRY_MS * 2 ** (prev.failures - 1), CREDITS_REFRESH_MS)
25// $.http.fetch has no timeout and cannot be cancelled, so a request open this long is given up:
26// its late answer is dropped and the next refresh asks again.
27const CREDITS_ABANDON_MS = 30 * MINUTE_MS
28// Past this the figure is not a percentage the bar can draw.
29const CREDITS_MAX_PERCENT = 10_000
30
31const FULL = String.fromCharCode(0x2588)
32const EMPTY = String.fromCharCode(0x2591)
33const SWATCH = String.fromCharCode(0x25a0)
34
35const LIMIT_NAMES: Record<string, string> = { five_hour: '5h', seven_day: '7d', spend_limit: 'Spend', usage_credits: 'Credits' }
36
37const cache = atom({ plugin: 'session-band', key: 'cache' } as const, null)
38const snapshot = atom({ plugin: 'session-band', key: 'snapshot' } as const, null)
39const credits = atom({ plugin: 'session-band', key: 'credits' } as const, null)
40
41const tokens = (n: number) => {
42 if (n >= 1_000_000) {
43 return `${Number((n / 1_000_000).toFixed(1))}M`
44 }
45 return n >= 1000 ? `${Math.round(n / 1000)}k` : String(n)
46}
47
48const duration = (ms: number) => {
49 const m = Math.max(0, Math.floor(ms / MINUTE_MS))
50 if (m < 60) {
51 return `${m}m`
52 }
53 const h = Math.floor(m / 60)
54 return h < 24 ? `${h}h ${m % 60}m` : `${Math.floor(h / 24)}d ${h % 24}h`
55}
56
57const clock = (ms: number) => {
58 const s = Math.ceil(ms / SECOND_MS)
59 return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
60}
61
62const bar = (percent: number) => {
63 const filled = Math.min(LIMIT_BAR_CELLS, Math.round((percent / 100) * LIMIT_BAR_CELLS))
64 return FULL.repeat(filled) + EMPTY.repeat(LIMIT_BAR_CELLS - filled)
65}
66
67// Largest-remainder split, so the segments always add up to the filled cells.
68const segments = (filled: number, weights: number[]) => {
69 const total = weights.reduce((a, b) => a + b, 0)
70 if (total === 0) {
71 return weights.map(() => 0)
72 }
73 const exact = weights.map(w => (w / total) * filled)
74 const cells = exact.map(Math.floor)
75 const order = exact.map((x, i) => ({ i, rest: x - Math.floor(x) })).sort((a, b) => b.rest - a.rest)
76 const missing = filled - cells.reduce((a, b) => a + b, 0)
77 for (let k = 0; k < missing; k++) {
78 cells[order[k]!.i]! += 1
79 }
80 return cells
81}
82
83const severity = (percent: number) => (percent >= 90 ? 'error' : percent >= 75 ? 'warning' : undefined)
84
85const parseCredits = (text: string): number | null => {
86 try {
87 const extra: unknown = (JSON.parse(text) as { extra_usage?: unknown }).extra_usage
88 if (typeof extra !== 'object' || extra === null) {
89 return null
90 }
91 const { is_enabled, utilization, used_credits, monthly_limit } = extra as Record<string, unknown>
92 if (is_enabled !== true) {
93 return null
94 }
95 // An allowance with nothing spent yet answers utilization null; the two amounts share a unit.
96 const percent =
97 typeof utilization === 'number'
98 ? utilization
99 : typeof used_credits === 'number' && typeof monthly_limit === 'number' && monthly_limit > 0
100 ? (used_credits / monthly_limit) * 100
101 : NaN
102 if (!(percent >= 0 && percent <= CREDITS_MAX_PERCENT)) {
103 return null
104 }
105 return Math.round(percent * 10) / 10
106 } catch {
107 return null
108 }
109}
110
111// Credit-billed plans (Enterprise seats, for one) report no rate-limit window on responses;
112// their monthly credit spend is only on the usage endpoint.
113// failed marks a missing login or a refused request, which is asked again sooner than an answer.
114const fetchCredits = async ($: EngineInterface): Promise<{ percentUsed: number | null; failed: boolean }> => {
115 let text: string
116 try {
117 const auth = await $.session.authorize()
118 // Bedrock, Vertex and gateways hold no first-party credential, nor does a session whose login
119 // expired until /login; authorize is local, so asking again soon costs no request.
120 if (auth === null) {
121 return { percentUsed: null, failed: true }
122 }
123 // The endpoint takes only a claude.ai login: an API key would be refused on every poll.
124 if (auth.kind !== 'bearer') {
125 return { percentUsed: null, failed: false }
126 }
127 const r = await $.http.fetch(CREDITS_URL, { auth: auth.handle, headers: { 'anthropic-beta': 'oauth-2025-04-20' } })
128 if (!r.ok) {
129 return { percentUsed: null, failed: true }
130 }
131 text = r.text
132 } catch {
133 return { percentUsed: null, failed: true }
134 }
135 return { percentUsed: parseCredits(text), failed: false }
136}
137
138const pollCredits = async ($: EngineInterface) => {
139 const now = await $.clock.now()
140 const requestId = Math.random().toString(36).slice(2)
141 let started = false
142 // update writes with ifVersion and retries, so of two refreshes racing here only one starts a request.
143 await update($, credits, prev => {
144 // refresh runs after every response; the endpoint is asked at most once per interval.
145 started = prev === null || now - prev.requestedAt >= creditsWait(prev)
146 // pendingSince keeps the first unanswered request's time when a given-up or failed one is asked again.
147 return started
148 ? { percentUsed: prev?.percentUsed ?? null, requestedAt: now, requestId, pendingSince: prev?.pendingSince ?? now, failures: prev?.failures ?? 0 }
149 : prev
150 })
151 if (!started) {
152 return
153 }
154 // The request runs on a timer of its own so a slow endpoint never holds up the response's hooks.
155 $.clock.after(0, async () => {
156 const { percentUsed, failed } = await fetchCredits($)
157 const answeredAt = await $.clock.now()
158 // A late answer to a request given up on, or one after /clear, no longer matches and is dropped.
159 // A failure keeps the last figure, so a passing error does not blink the row; the 30-minute
160 // pendingSince rule hides it once failures last.
161 await update($, credits, prev =>
162 prev === null || prev.requestId !== requestId
163 ? prev
164 : failed
165 ? // The wait runs from the failure, so a request that is slow to fail is not asked again at once.
166 { ...prev, requestedAt: answeredAt, requestId: null, failures: prev.failures + 1 }
167 : { ...prev, percentUsed, requestId: null, pendingSince: null, failures: 0 },
168 )
169 })
170}
171
172const refresh = async ($: EngineInterface, showCredits: boolean) => {
173 // 'full' sends a token-count request per MCP tool and memory file on every turn; 'summary' is local.
174 const usage = await $.session.usage({ breakdown: 'summary' })
175 const used = (usage.context.breakdown?.categories ?? [])
176 .filter(c => c.kind === 'used')
177 .sort((a, b) => b.tokens - a.tokens)
178 const limits: RateLimit[] = usage.rateLimits.map(l => {
179 const resetsAt = l.resetsAt === undefined ? NaN : Date.parse(l.resetsAt)
180 return { kind: l.kind, percentUsed: l.percentUsed, resetsAt: Number.isNaN(resetsAt) ? null : resetsAt }
181 })
182 if (showCredits) {
183 await pollCredits($)
184 }
185 await update($, snapshot, () => ({
186 startedAt: usage.startedAt,
187 percent: usage.context.percent ?? null,
188 tokens: usage.context.tokens ?? null,
189 window: usage.context.window,
190 top: used.slice(0, TOP_CATEGORIES).map(({ name, tokens, color }) => ({ name, tokens, color })),
191 otherTokens: used.slice(TOP_CATEGORIES).reduce((sum, c) => sum + c.tokens, 0),
192 limits,
193 costUsd: usage.cost?.usd ?? null,
194 }))
195}
196
197export const register: Register = (on, options) => {
198 // The plugin cannot observe the TTL the engine requested, so the person states it.
199 const ttlMs = TTL_MS[String(options.cacheTtl)] ?? TTL_MS['5m']!
200 const showCost = options.showCost !== false
201 const showCredits = options.showCredits === true
202 let bootstrapping = false
203 let stepRefreshAt = -Infinity
204 let stepRefresh: { cancel: () => void } | null = null
205
206 on('session.start', async ($, e, next) => {
207 const result = await next(e)
208 await refresh($, showCredits)
209 $.clock.every(SECOND_MS, () => $.ui.invalidate('ui.render'))
210 return result
211 })
212
213 on('session.measure', async ($, e, next) => {
214 const result = await next(e)
215 await refresh($, showCredits)
216 return result
217 })
218
219 on('classic.SessionStart', async ($, e, next) => {
220 if (e.seconds_since_last_response !== undefined) {
221 const now = await $.clock.now()
222 // The payload times the end of the last response, not the start of its request, so the
223 // countdown can run long by that response's generation time until a live one replaces it.
224 const respondedAt = now - e.seconds_since_last_response * SECOND_MS
225 // The engine judges expiry against the TTL it requested, which the plugin is only told.
226 const sentAt = e.prompt_cache_likely_expired === true ? Math.min(respondedAt, now - ttlMs) : respondedAt
227 await update($, cache, () => ({ sentAt, estimated: true }))
228 }
229 const result = await next(e)
230 // A resumed or forked conversation starts with empty session state and no session.start.
231 await refresh($, showCredits)
232 return result
233 })
234
235 on('turn.step', async function* ($, e, next) {
236 // The cache lifetime runs from the start of the request, so generation time counts against it.
237 const sentAt = await $.clock.now()
238 const result = yield* next(e)
239 // Subagents cache their own prefixes; only the main thread's matters for the next prompt.
240 if (e.agentId === undefined && result.usage !== null) {
241 const cached = result.usage.cache_read_input_tokens + result.usage.cache_creation_input_tokens > 0
242 await update($, cache, () => (cached ? { sentAt, estimated: false } : null))
243 }
244 // session.measure fires only when a turn ends, so a long turn would keep the fill it started with.
245 if (e.agentId === undefined && stepRefresh === null) {
246 const now = await $.clock.now()
247 // A step inside the interval is put off to its end, not dropped: the step after it may run long.
248 // Off the step, so the next request is not held up; a failed read keeps the last snapshot.
249 stepRefresh = $.clock.after(Math.max(0, stepRefreshAt + STEP_REFRESH_MS - now), async () => {
250 stepRefresh = null
251 stepRefreshAt = await $.clock.now()
252 await refresh($, showCredits).catch(() => {})
253 })
254 }
255 return result
256 })
257
258 // Compaction replaces the cached prefix. classic SessionStart(compact) also fires for a
259 // subagent's compaction with no agent fields (anthropics/claude-code#91910); this event has agentId.
260 on('session.compact', async ($, e, next) => {
261 const result = await next(e)
262 if (e.agentId === undefined && e.trigger !== 'precompute' && result.skip === undefined) {
263 await update($, cache, () => null)
264 // The engine has no fill for a compacted window until its next response, which the step
265 // refresh then reads at once.
266 await update($, snapshot, prev => (prev === null ? null : { ...prev, percent: null, tokens: null, top: [], otherTokens: 0 }))
267 stepRefresh?.cancel()
268 stepRefresh = null
269 stepRefreshAt = -Infinity
270 }
271 return result
272 })
273
274 // Each model keeps its own prompt cache, so the first request after a switch writes a new one.
275 on('classic.PostModelSwitch', async ($, e, next) => {
276 if (e.agent_id !== undefined) {
277 return next(e)
278 }
279 await update($, cache, () => null)
280 const result = await next(e)
281 // The new model may have another context window; session.measure waits for its first response.
282 await refresh($, showCredits)
283 return result
284 })
285
286 on('session.end', async ($, e, next) => {
287 if (e.reason === 'clear') {
288 await update($, cache, () => null)
289 await update($, snapshot, () => null)
290 await update($, credits, () => null)
291 }
292 return next(e)
293 })
294
295 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
296 const below = await next(e)
297 if (e.props.hasSurvey) {
298 return below
299 }
300 const c = await read($, cache)
301 const s = await read($, snapshot)
302 // A managed prepend-tier plugin can send classic.SessionStart past this plugin's hook, which
303 // leaves a resumed session with no snapshot until its first response.
304 if (s === null && !bootstrapping) {
305 bootstrapping = true
306 // A render hook may not write state; the snapshot write redraws the band.
307 $.clock.after(0, async () => {
308 try {
309 await refresh($, showCredits)
310 } catch {
311 // The next render asks again.
312 } finally {
313 bootstrapping = false
314 }
315 })
316 }
317 const cr = showCredits ? await read($, credits) : null
318 if (c === null && s === null) {
319 return below
320 }
321 const now = await $.clock.now()
322 const { Box, Text } = $.ui.resolve(e)
323 const label = (text: string) => (
324 <Box width={LABEL_WIDTH} flexShrink={0}>
325 <Text dimColor>{text}</Text>
326 </Box>
327 )
328 const rows: RenderElement[] = []
329
330 if (c !== null) {
331 const left = c.sentAt + ttlMs - now
332 rows.push(
333 <Box flexDirection="row" key="cache">
334 {label('Cache')}
335 <Text color={left > 0 ? undefined : 'warning'}>{left > 0 ? clock(left) : 'expired'}</Text>
336 {left > 0 && c.estimated ? <Text dimColor>{' estimated'}</Text> : null}
337 </Box>,
338 )
339 }
340
341 if (s !== null) {
342 rows.push(
343 <Box flexDirection="row" key="session">
344 {label('Session')}
345 <Text>
346 {showCost && s.costUsd !== null ? `$${s.costUsd.toFixed(2)} ` : ''}
347 <Text dimColor>{`${duration(now - s.startedAt)} elapsed`}</Text>
348 </Text>
349 </Box>,
350 )
351
352 const live = s.limits.filter(l => l.resetsAt === null || l.resetsAt > now)
353 // Once requests have gone unanswered or failed past the give-up time, the figure is hidden rather than shown stale.
354 const crHung = cr !== null && cr.pendingSince !== null && now - cr.pendingSince >= CREDITS_ABANDON_MS
355 if (cr !== null && cr.percentUsed !== null && !crHung) {
356 // The endpoint carries no reset time, and billing cycles differ by organization.
357 live.push({ kind: 'usage_credits', percentUsed: cr.percentUsed, resetsAt: null })
358 }
359 if (live.length > 0) {
360 rows.push(
361 <Box flexDirection="row" key="limits">
362 {label('Limits')}
363 <Box flexDirection="row" flexWrap="wrap" columnGap={4}>
364 {live.map(l => (
365 <Text>
366 {`${LIMIT_NAMES[l.kind] ?? l.kind} `}
367 <Text color={severity(l.percentUsed)} dimColor={severity(l.percentUsed) === undefined}>{bar(l.percentUsed)}</Text>
368 {` ${l.percentUsed}%`}
369 <Text dimColor>{l.resetsAt === null ? '' : ` resets in ${duration(l.resetsAt - now)}`}</Text>
370 </Text>
371 ))}
372 </Box>
373 </Box>,
374 )
375 }
376
377 const filled = s.percent === null ? 0 : Math.min(CONTEXT_BAR_CELLS, Math.round((s.percent / 100) * CONTEXT_BAR_CELLS))
378 const cells = segments(filled, [...s.top.map(c => c.tokens), s.otherTokens])
379 const unattributed = filled - cells.slice(0, s.top.length).reduce((a, b) => a + b, 0)
380 rows.push(
381 <Box flexDirection="row" key="context">
382 {label('Context')}
383 <Text wrap="truncate-end">
384 {s.top.map((c, i) => <Text color={c.color}>{FULL.repeat(cells[i] ?? 0)}</Text>)}
385 <Text dimColor>{FULL.repeat(unattributed) + EMPTY.repeat(CONTEXT_BAR_CELLS - filled)}</Text>
386 {s.percent === null || s.tokens === null ? ' --' : ` ${s.percent}% ${tokens(s.tokens)} / ${tokens(s.window)}`}
387 {s.top.map(c => (
388 <Text>
389 {' '}
390 <Text color={c.color}>{SWATCH}</Text>
391 <Text dimColor>{` ${c.name} ${tokens(c.tokens)}`}</Text>
392 </Text>
393 ))}
394 </Text>
395 </Box>,
396 )
397 }
398
399 // AbovePrompt is one band shared by every plugin; wrapping keeps their rows instead of replacing them.
400 return below ? <Box flexDirection="column">{below}{rows}</Box> : <Box flexDirection="column">{rows}</Box>
401 })
402}
403types/index.d.ts 42 lines1export type EpochMs = number
2
3export type RateLimit = {
4 kind: string
5 percentUsed: number
6 resetsAt: EpochMs | null
7}
8
9export type CacheCountdown = {
10 sentAt: EpochMs
11 estimated: boolean
12}
13
14export type CreditsReading = {
15 percentUsed: number | null
16 requestedAt: EpochMs
17 requestId: string | null
18 pendingSince: EpochMs | null
19 failures: number
20}
21
22export type SessionSnapshot = {
23 startedAt: EpochMs
24 percent: number | null
25 tokens: number | null
26 window: number
27 top: { name: string; tokens: number; color: string }[]
28 otherTokens: number
29 limits: RateLimit[]
30 costUsd: number | null
31}
32
33declare module 'claude-code' {
34 interface PluginState {
35 'session-band': {
36 cache: CacheCountdown | null
37 snapshot: SessionSnapshot | null
38 credits: CreditsReading | null
39 }
40 }
41}
42