Usage strip above the prompt: 5h and 7d limits, session tokens, context window, cache warmth and cost.

A Claude Code plugin marketplace with one mod, usage-band: a band above the prompt showing quota, tokens, context, cache warmth and session cost.
Preview renders:


| Pill | Shows |
|---|---|
| 5h | Percent of the 5-hour quota left. The bar is the quota left, the tick is the time left in the window; shows the time until reset. |
| 7d | Same for the 7-day quota. |
| Tokens up | Input tokens plus cache writes. |
| Tokens down | Output tokens. |
| Cache reads | Tokens read from the prompt cache. |
| Cache warm | Time the main thread's prompt cache stays warm after its last response: 57m, <1m, or cold; bar and colour show the share of the TTL left. |
| Context | Tokens of the last request. Bar and colour by fill: under 60% calm, 60-85% amber, over 85% red. |
| Cost | Session cost in US dollars. |
/clear and on resume.glyphs to unicode.Inside Claude Code:
/plugin marketplace add brooklyn96/claude-usage-band
/plugin install usage-band@claude-usage-band
From a shell:
claude plugin marketplace add brooklyn96/claude-usage-band
claude plugin install usage-band@claude-usage-band
In an open session, run /reload-plugins to pick it up.
Update:
claude plugin update usage-band@claude-usage-band
glyphs: nerd (default) or unicode. Set it through /plugin (configure).
cacheTtl: 1h (default) or 5m — how long the main thread's prompt cache stays warm, and so what the warm pill counts down from.
When the row does not fit, the cache pill drops first, then bars shorten and time labels go compact, then the token up/down pills hide too, then every pill wraps onto the next line at full size.
claude plugin validate usage-band
claude plugin test usage-band
Type-check after the mod has loaded, since the engine writes usage-band/.claude-plugin/types on load:
npx -y -p typescript@5.6 tsc -p usage-band --noEmit
A mod runs with your permissions. This one makes no network calls, writes no files and starts no processes.
MIT.
hooks/register.tsx 185 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, ModelUsage, Register, SessionContextUsage, SessionCost, SessionRateLimit } from 'claude-code'
3
4import type { Limit, Tokens } from '../types'
5import { PILL_H, STRIP_BG, alt, isRate, pillSvg, pillsOf, termLayout } from './pills'
6import type { Pill, ValuePill } from './pills'
7
8const limitsAtom = atom({ plugin: 'usage-band', key: 'limits' } as const, [])
9const costAtom = atom({ plugin: 'usage-band', key: 'cost' } as const, null)
10const tokensAtom = atom({ plugin: 'usage-band', key: 'tokens' } as const, null)
11// `tokens` shape: the value changed from a bare percent to the token reading.
12const contextAtom = atom({ plugin: 'usage-band', key: 'context' } as const, null, { shape: 'tokens' })
13// When the main thread's last response landed: the prompt cache's warm countdown.
14const warmAtom = atom({ plugin: 'usage-band', key: 'cacheWarm' } as const, null)
15const nowAtom = atom({ plugin: 'usage-band', key: 'now' } as const, 0)
16
17/** `context` only when its fill moved (or on a full reading); `tokens` is absent before the first response. */
18async function measured($: EngineInterface, rateLimits: readonly SessionRateLimit[], cost?: SessionCost, context?: SessionContextUsage) {
19 const limits = rateLimits.map(({ kind, percentUsed, resetsAt }): Limit => (resetsAt ? { kind, percentUsed, resetsAt } : { kind, percentUsed }))
20 await update($, limitsAtom, () => limits)
21 await update($, costAtom, () => cost?.usd ?? null)
22 if (context) {
23 const next = context.tokens === undefined ? null : { tokens: context.tokens, window: context.window, percent: context.percent }
24 await update($, contextAtom, () => next)
25 }
26}
27
28async function spent($: EngineInterface, u: ModelUsage | null | undefined) {
29 if (!u) return
30 await update($, tokensAtom, (t): Tokens => ({
31 input: (t?.input ?? 0) + u.input_tokens + u.cache_creation_input_tokens,
32 output: (t?.output ?? 0) + u.output_tokens,
33 cache: (t?.cache ?? 0) + u.cache_read_input_tokens,
34 }))
35}
36
37async function refresh($: EngineInterface) {
38 try {
39 const usage = await $.session.usage()
40 await measured($, usage.rateLimits, usage.cost, usage.context)
41 const now = await $.clock.now()
42 await update($, nowAtom, () => now)
43 } catch {
44 // The engine is shutting down or a hook refused the reading: the next tick tries again.
45 }
46}
47
48/** The /config theme row: `light`, `light-daltonized`, ... draw the light palette; anything else dark. */
49const isLight = ($: EngineInterface) =>
50 $.config.list().then(
51 rows => String(rows.find(row => row.key === 'theme')?.value ?? '').startsWith('light'),
52 () => false,
53 )
54
55// Timers die with the module, and a hot reload raises no session.start: whichever of
56// session.start or the first draw comes first starts the clock for this module.
57let started = false
58function start($: EngineInterface) {
59 if (started) return
60 started = true
61 $.clock.every(30_000, () => void refresh($))
62}
63
64export const register: Register = (on, options) => {
65 const glyphs = options.glyphs === 'unicode' ? 'unicode' : 'nerd'
66 // The prompt cache TTL the option names, in ms.
67 const warmTtl = (options.cacheTtl === '5m' ? 5 : 60) * 60_000
68
69 on('session.start', async ($, e, next) => {
70 await refresh($)
71 start($)
72 return next(e)
73 })
74
75 on('session.measure', async ($, e, next) => {
76 await measured($, e.rateLimits, e.cost, e.changed.includes('context') ? e.context : undefined)
77 return next(e)
78 })
79
80 // Every priced response, main loop and subagents alike, as it comes back: the totals
81 // move with the cost, not at the turn's end (turn.complete's usage is these summed).
82 on('turn.step', async function* ($, e, next) {
83 const result = yield* next(e)
84 await spent($, result.usage)
85 // Only the main thread's cache matters; a subagent's loop writes its own.
86 if (result.usage && e.agentId === undefined) {
87 const at = await $.clock.now()
88 await update($, warmAtom, () => at)
89 }
90 return result
91 })
92
93 // The compaction summarizer is priced too, and raises no turn.
94 on('session.compact', async ($, e, next) => {
95 const result = await next(e)
96 if ('usage' in result) await spent($, result.usage)
97 return result
98 })
99
100 on('session.end', async ($, e, next) => {
101 // Cost follows the new session's ledger on both, so the token totals, the
102 // context fill and the warm countdown start over too: the new session's
103 // first measure brings the figures back, its first response the countdown.
104 if (e.reason === 'clear' || e.reason === 'resume') {
105 await update($, tokensAtom, () => null)
106 await update($, contextAtom, () => null)
107 await update($, warmAtom, () => null)
108 }
109 return next(e)
110 })
111
112 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
113 if (!started) {
114 start($)
115 $.clock.after(0, () => void refresh($)) // first reading after a reload; a draw never writes
116 }
117 if (e.props.hasSurvey) return next(e)
118 await read($, nowAtom) // subscribes: the minute timer redraws the band
119 const warmAt = await read($, warmAtom) // subscribes: a response restarts the countdown
120 const pills = pillsOf(
121 await read($, limitsAtom),
122 await read($, tokensAtom),
123 await read($, costAtom),
124 await $.clock.now(),
125 await read($, contextAtom),
126 warmAt === null ? null : { at: warmAt, ttl: warmTtl },
127 )
128 if (pills.length === 0) return next(e)
129
130 const left = pills.filter(p => p.id !== 'cost')
131 const cost = pills.find((p): p is ValuePill => p.id === 'cost')
132
133 // Nerd Font text pills belong to the terminal alone; desktop, vscode, mobile and
134 // any later surface draw the Svg pills, which wrap on a narrow panel.
135 if (e.surface !== 'terminal') {
136 const { Box, Svg } = $.ui.resolve(e)
137 const pill = (p: Pill) => {
138 const { source, width } = pillSvg(p)
139 return <Svg key={p.id} source={source} alt={alt(p)} width={width} height={PILL_H} />
140 }
141 return (
142 <Box
143 flexDirection="row"
144 flexWrap="wrap"
145 alignItems="center"
146 backgroundColor={STRIP_BG}
147 borderStyle="round"
148 borderColor={STRIP_BG}
149 paddingX={2}
150 paddingY={1}
151 columnGap={1}
152 rowGap={1}
153 >
154 {left.filter(isRate).map(pill)}
155 {left.some(isRate) && left.some(p => !isRate(p)) ? <Box width={1} /> : null}
156 {left.filter(p => !isRate(p)).map(pill)}
157 <Box flexGrow={1} />
158 {cost ? pill(cost) : null}
159 </Box>
160 )
161 }
162
163 const { Box, Text } = $.ui.resolve(e)
164 const row = termLayout(pills, e.props.bodyColumns, glyphs, await isLight($))
165 const pill = ({ id, runs }: (typeof row.pills)[number]) => (
166 <Box key={id} flexDirection="row" flexShrink={0}>
167 {runs.map((r, i) => (
168 <Text key={String(i)} color={r.fg} backgroundColor={r.bg} bold={r.bold}>
169 {r.s}
170 </Text>
171 ))}
172 </Box>
173 )
174 const costPill = row.pills.find(p => p.id === 'cost')
175 // Wrapped or a tight row, no spacer: the cost pill follows on whichever line has room.
176 return (
177 <Box flexDirection="row" flexWrap={row.wrap ? 'wrap' : 'nowrap'} columnGap={1} width={e.props.bodyColumns}>
178 {row.pills.filter(p => p.id !== 'cost').map(pill)}
179 {costPill && row.spacer ? <Box flexGrow={1} /> : null}
180 {costPill ? pill(costPill) : null}
181 </Box>
182 )
183 })
184}
185hooks/pills.ts 362 lines1import type { ContextUsage, Limit, Tokens } from '../types'
2
3const MIN = 60_000
4const HOUR = 60 * MIN
5const DAY = 24 * HOUR
6const WINDOWS = { five_hour: 5 * HOUR, seven_day: 7 * DAY } as const
7
8/** `percent` is the quota remaining, `timeShare` the share of the window's time remaining. */
9export type RatePill = { id: '5h' | '7d'; percent: number; timeShare: number | null; left: string }
10export type ValuePill = { id: 'in' | 'out' | 'cache' | 'cost'; value: string }
11/** `tokens` is the last response's input side; `percent` is the context window USED (what auto-compact reacts to), unlike the quota pills. */
12export type ContextPill = { id: 'ctx'; tokens: number; percent: number }
13/** `remaining` is the share of the cache TTL still warm (0 once expired); `label` the countdown text. */
14export type WarmPill = { id: 'warm'; remaining: number; label: string }
15export type Pill = RatePill | ValuePill | ContextPill | WarmPill
16/** When the main thread last refreshed its prompt cache, and the TTL that refresh reset: the warm pill's inputs. */
17export type WarmReading = { at: number; ttl: number }
18
19export const formatTokens = (n: number): string => {
20 if (n < 1000) return String(Math.round(n))
21 const k = Math.round(n / 100) / 10
22 if (k < 1000) return `${k.toFixed(1)}k`
23 return `${(Math.round(n / 100_000) / 10).toFixed(1)}M`
24}
25
26/** Context pill only: whole thousands, no decimal (`950`, `42k`, `210k`); one decimal of millions from 1M up (`1.0M`, `1.2M`). */
27export const formatCtxTokens = (n: number): string => {
28 if (n < 1000) return String(Math.round(n))
29 if (Math.round(n / 1000) < 1000) return `${Math.round(n / 1000)}k`
30 return `${(Math.round(n / 100_000) / 10).toFixed(1)}M`
31}
32
33export const formatLeft = (ms: number): string => {
34 const minutes = Math.max(0, Math.floor(ms / MIN))
35 const d = Math.floor(minutes / 1440)
36 const h = Math.floor((minutes % 1440) / 60)
37 const m = minutes % 60
38 if (d > 0) return `${d}d ${h}h`
39 if (h > 0) return `${h}h ${m}m`
40 return `${m}m`
41}
42
43/** The warm countdown text: whole minutes rounded up (`57m`), `<1m` under one, `cold` once expired. */
44export const formatWarm = (ms: number): string => {
45 if (ms <= 0) return 'cold'
46 return ms < MIN ? '<1m' : `${Math.ceil(ms / MIN)}m`
47}
48
49/** (resetsAt - now) / window, clamped to 0..1; null when the reset is unknown. */
50export const remainingFraction = (limit: Limit, now: number): number | null => {
51 const window = WINDOWS[limit.kind as keyof typeof WINDOWS]
52 const resets = limit.resetsAt === undefined ? NaN : Date.parse(limit.resetsAt)
53 if (!window || Number.isNaN(resets)) return null
54 return Math.min(1, Math.max(0, (resets - now) / window))
55}
56
57export const pillsOf = (limits: Limit[], tokens: Tokens | null, cost: number | null, now: number, context: ContextUsage | null = null, warm: WarmReading | null = null): Pill[] => {
58 const pills: Pill[] = []
59 for (const [kind, id] of [['five_hour', '5h'], ['seven_day', '7d']] as const) {
60 const limit = limits.find(l => l.kind === kind)
61 if (!limit) continue
62 const left = limit.resetsAt === undefined ? '' : formatLeft(Date.parse(limit.resetsAt) - now)
63 pills.push({ id, percent: Math.max(0, Math.round(100 - limit.percentUsed)), timeShare: remainingFraction(limit, now), left })
64 }
65 if (tokens) {
66 pills.push({ id: 'in', value: formatTokens(tokens.input) })
67 pills.push({ id: 'out', value: formatTokens(tokens.output) })
68 pills.push({ id: 'cache', value: formatTokens(tokens.cache) })
69 }
70 if (warm !== null) {
71 const left = warm.ttl - (now - warm.at)
72 pills.push({ id: 'warm', remaining: Math.min(1, Math.max(0, left / warm.ttl)), label: formatWarm(left) })
73 }
74 if (context !== null) {
75 const percent = context.percent ?? (context.window > 0 ? (context.tokens * 100) / context.window : 0)
76 pills.push({ id: 'ctx', tokens: context.tokens, percent: Math.min(100, Math.max(0, Math.round(percent))) })
77 }
78 if (cost !== null) pills.push({ id: 'cost', value: `$${cost.toFixed(2)}` })
79 return pills
80}
81
82export const isRate = (p: Pill): p is RatePill => p.id === '5h' || p.id === '7d'
83
84/** Context fill step: below 60% calm, 60-85% amber, above 85% red. */
85export const ctxLevel = (percent: number) => (percent > 85 ? 'high' : percent >= 60 ? 'warn' : 'ok')
86/** Warm step: above half the TTL calm, 20-50% amber, under 20% red, expired muted. */
87export const warmLevel = (remaining: number) => (remaining <= 0 ? 'cold' : remaining > 0.5 ? 'ok' : remaining >= 0.2 ? 'warn' : 'high')
88
89export const STRIP_BG = '#f1f0ec'
90const INK = '#2b2b2b'
91const MUTED = '#6f6f6f'
92const FILL = '#8db36a'
93export const TRACK = '#d9d9d6'
94const TICK = '#333333'
95const DIVIDER = '#b9c2c0'
96
97// Colours sampled from the reference (light theme).
98export const COLORS = {
99 '5h': { bg: '#dce8e4', fg: '#3d8c7d' },
100 '7d': { bg: '#e4e0f3', fg: '#7b5fd3' },
101 in: { bg: '#f4ddd9', fg: '#d0553f' },
102 out: { bg: '#dde9dc', fg: '#4c9a50' },
103 cache: { bg: '#dfe2f7', fg: '#4a5bd6' },
104 cost: { bg: '#f1ebd8', fg: '#c4952a' },
105} as const
106export const CTX_COLORS = {
107 ok: { bg: '#d6eaee', fg: '#26879c' },
108 warn: { bg: '#f7e3cb', fg: '#c46a12' },
109 high: { bg: '#f6d5d8', fg: '#c62f3e' },
110 // The warm pill's expired step: muted ink on a grey distinct from the bar's track, so the empty bar stays visible.
111 cold: { bg: '#a9b0ac', fg: MUTED },
112} as const
113
114export const alt = (p: Pill): string => {
115 if (isRate(p)) {
116 const name = p.id === '5h' ? '5-hour' : '7-day'
117 return `${name} limit ${p.percent}% left${p.left ? `, resets in ${p.left}` : ''}`
118 }
119 if (p.id === 'ctx') return `context ${formatCtxTokens(p.tokens)} tokens (${p.percent}% of window)`
120 if (p.id === 'warm') return p.label === 'cold' ? 'Prompt cache cold' : `Prompt cache warm for ${p.label}`
121 return { in: 'Input tokens', out: 'Output tokens', cache: 'Cache read', cost: 'Session cost' }[p.id] + ` ${p.value}`
122}
123
124// Icons: 24-unit stroke paths (Lucide-style), drawn at ICON px.
125const ICONS = {
126 gauge: '<path d="m12 14 4-4"/><path d="M3.34 19a10 10 0 1 1 17.32 0"/>',
127 calendar:
128 '<rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/>' +
129 '<text x="12" y="19.6" font-size="10" font-weight="700" text-anchor="middle" stroke="none" fill="currentColor">7</text>',
130 history: '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>',
131 in: '<path d="M12 3v11M7 8l5-5 5 5"/><rect x="3" y="15" width="18" height="6" rx="2"/>',
132 out: '<path d="M12 2v11M7 8l5 5 5-5"/><rect x="3" y="15" width="18" height="6" rx="2"/>',
133 cache:
134 '<path d="M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z"/>' +
135 '<path d="m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65"/><path d="m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65"/>',
136 cost:
137 '<circle cx="12" cy="12" r="10" fill="#f3d98a"/><path d="M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"/><path d="M12 18V6"/>',
138 ctx:
139 '<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/>' +
140 '<path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/>' +
141 '<path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"/><path d="M12 5v13"/>',
142 warm:
143 '<path d="M5 22h14"/><path d="M5 2h14"/>' +
144 '<path d="M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22"/>' +
145 '<path d="M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2"/>',
146} as const
147
148// Sizes measured on the reference at 1x.
149export const PILL_H = 22
150const H = PILL_H
151const FONT = 12.5
152const CHAR = 7.5 // advance of a 12.5px monospace glyph (0.6em)
153const ICON = 14
154const BAR = 46
155const CTX_BAR = 30
156const FAMILY = "ui-monospace, 'SF Mono', SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace"
157
158const icon = (name: keyof typeof ICONS, x: number, size: number, color: string) =>
159 `<g transform="translate(${x} ${(H - size) / 2}) scale(${size / 24})" fill="none" stroke="${color}" ` +
160 `stroke-width="2" stroke-linecap="round" stroke-linejoin="round" color="${color}">${ICONS[name]}</g>`
161
162const text = (s: string, x: number, color: string, bold = false) =>
163 `<text x="${x}" y="${H / 2}" dominant-baseline="central" fill="${color}"${bold ? ' font-weight="700"' : ''}>${s}</text>`
164
165/** One pill as an SVG document and its width in CSS pixels. */
166export const pillSvg = (p: Pill): { source: string; width: number } => {
167 const { bg, fg } = p.id === 'ctx' ? CTX_COLORS[ctxLevel(p.percent)] : p.id === 'warm' ? CTX_COLORS[warmLevel(p.remaining)] : COLORS[p.id]
168 const parts: string[] = []
169 let x = 9
170 if (isRate(p)) {
171 parts.push(icon(p.id === '5h' ? 'gauge' : 'calendar', x, ICON, fg))
172 x += ICON + 7
173 parts.push(text(p.id, x, MUTED))
174 x += 2 * CHAR + 8
175 const fill = (BAR * Math.min(100, Math.max(0, p.percent))) / 100
176 const y = (H - 4) / 2
177 parts.push(
178 `<rect x="${x}" y="${y}" width="${BAR}" height="4" rx="2" fill="${TRACK}"/>`,
179 `<rect x="${x}" y="${y}" width="${fill}" height="4" rx="2" fill="${FILL}"/>`,
180 )
181 if (p.timeShare !== null) {
182 const tick = Math.min(BAR - 1, Math.max(1, BAR * p.timeShare))
183 parts.push(`<rect x="${x + tick - 1}" y="${(H - 12) / 2}" width="2" height="12" rx="1" fill="${TICK}"/>`)
184 }
185 x += BAR + 8
186 const pct = `${p.percent}%`
187 parts.push(text(pct, x, INK, true))
188 x += pct.length * CHAR + 9
189 if (p.left) {
190 parts.push(`<line x1="${x}" y1="${(H - 14) / 2}" x2="${x}" y2="${(H + 14) / 2}" stroke="${DIVIDER}" stroke-width="1"/>`)
191 x += 9
192 parts.push(icon('history', x, 13, fg))
193 x += 13 + 6
194 parts.push(text(p.left, x, MUTED))
195 x += p.left.length * CHAR + 11
196 } else x += 2
197 } else if (p.id === 'ctx') {
198 parts.push(icon('ctx', x, ICON, fg))
199 x += ICON + 7
200 const y = (H - 4) / 2
201 parts.push(
202 `<rect x="${x}" y="${y}" width="${CTX_BAR}" height="4" rx="2" fill="${TRACK}"/>`,
203 `<rect x="${x}" y="${y}" width="${(CTX_BAR * p.percent) / 100}" height="4" rx="2" fill="${fg}"/>`,
204 )
205 x += CTX_BAR + 8
206 const figure = formatCtxTokens(p.tokens)
207 parts.push(text(figure, x, INK, true))
208 x += figure.length * CHAR + 10
209 } else if (p.id === 'warm') {
210 parts.push(icon('warm', x, ICON, fg))
211 x += ICON + 7
212 const y = (H - 4) / 2
213 parts.push(
214 `<rect x="${x}" y="${y}" width="${CTX_BAR}" height="4" rx="2" fill="${TRACK}"/>`,
215 `<rect x="${x}" y="${y}" width="${Math.round(CTX_BAR * p.remaining * 100) / 100}" height="4" rx="2" fill="${fg}"/>`,
216 )
217 x += CTX_BAR + 8
218 parts.push(text(p.label, x, INK, true))
219 x += p.label.length * CHAR + 10
220 } else {
221 parts.push(icon(p.id, x, ICON, fg))
222 x += ICON + 7.5
223 parts.push(text(p.value, x, INK))
224 x += p.value.length * CHAR + 10
225 }
226 const width = Math.ceil(x)
227 const source =
228 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${H}" viewBox="0 0 ${width} ${H}" ` +
229 `font-family="${FAMILY}" font-size="${FONT}">` +
230 `<rect width="${width}" height="${H}" rx="${H / 2}" fill="${bg}"/>${parts.join('')}</svg>`
231 return { source, width }
232}
233
234// Terminal: each pill a row of coloured runs between two caps drawn in the pill colour.
235export type Run = { s: string; fg?: string; bg?: string; bold?: boolean }
236export type Glyphs = 'nerd' | 'unicode'
237
238const GLYPHS = {
239 // Nerd Font: powerline round caps, Material Design icons (each one cell).
240 nerd: {
241 caps: ['', ''],
242 '5h': '\u{f029a}', // md-gauge
243 '7d': '\u{f00ed}', // md-calendar
244 left: '\u{f02da}', // md-history
245 in: '\u{f011d}', // md-tray_arrow_up
246 out: '\u{f0120}', // md-tray_arrow_down
247 cache: '\u{f0328}', // md-layers
248 cost: '', // fa-coins: md has no currency-usd circle
249 ctx: '\u{f09d1}', // md-brain
250 warm: '\u{f051f}', // md-timer_sand
251 },
252 // Only glyphs Cascadia Mono has, all single width.
253 unicode: { caps: ['▐', '▌'], '5h': '◔', '7d': '▤', left: '◷', in: '↑', out: '↓', cache: '≡', cost: '◉', ctx: '◐', warm: '◶' },
254} as const
255
256export const TERM_PALETTE = {
257 dark: {
258 pill: {
259 '5h': { bg: '#1d3b36', fg: '#5ed0b8' },
260 '7d': { bg: '#2d2850', fg: '#a892ff' },
261 in: { bg: '#47231e', fg: '#ff7e66' },
262 out: { bg: '#1f3d23', fg: '#72d37c' },
263 cache: { bg: '#242c55', fg: '#8796ff' },
264 cost: { bg: '#40331a', fg: '#f2c24e' },
265 },
266 ctx: {
267 ok: { bg: '#14353d', fg: '#4cc3d9' },
268 warn: { bg: '#48300f', fg: '#ff9f43' },
269 high: { bg: '#4d1a22', fg: '#ff5c6c' },
270 cold: { bg: '#333936', fg: '#a9b1af' },
271 },
272 text: '#ececea',
273 muted: '#a9b1af',
274 track: '#4a504e',
275 fill: '#93d36d',
276 tick: '#ffffff',
277 },
278 light: { pill: COLORS, ctx: CTX_COLORS, text: INK, muted: MUTED, track: '#c5c8c4', fill: FILL, tick: TICK },
279} as const
280
281export const cells = (runs: Run[]): number => runs.reduce((n, r) => n + [...r.s].length, 0)
282
283/**
284 * One pill as runs, caps included, at ladder `step` (see termLayout): from step 3
285 * the bars are shorter, from step 4 the time labels compact (`2h40m`, no divider).
286 */
287export const termPill = (p: Pill, glyphs: Glyphs, light: boolean, step = 1): Run[] => {
288 const g = GLYPHS[glyphs]
289 const pal = TERM_PALETTE[light ? 'light' : 'dark']
290 const { bg, fg } = p.id === 'ctx' ? pal.ctx[ctxLevel(p.percent)] : p.id === 'warm' ? pal.ctx[warmLevel(p.remaining)] : pal.pill[p.id]
291 const runs: Run[] = []
292 const put = (s: string, color: string, extra: Partial<Run> = {}) => {
293 const run = { s, fg: color, bg, ...extra }
294 const last = runs[runs.length - 1]
295 if (last && last.fg === run.fg && last.bg === run.bg && !!last.bold === !!run.bold) last.s += s
296 else runs.push(run)
297 }
298 // Whole cells only: every bar cell is a space on the fill or track background, the tick the one glyph.
299 const bar = (percent: number, n: number, fill: string, tickAt = -1) => {
300 const filled = Math.min(n, Math.max(0, Math.round((percent / 100) * n)))
301 for (let i = 0; i < n; i++) {
302 const cellBg = i < filled ? fill : pal.track
303 if (i === tickAt) put('▎', pal.tick, { bg: cellBg, bold: true })
304 else put(' ', cellBg, { bg: cellBg })
305 }
306 }
307 runs.push({ s: g.caps[0], fg: bg })
308 if (isRate(p)) {
309 const n = step >= 3 ? 4 : 6
310 put(`${g[p.id]} `, fg)
311 put(`${p.id} `, pal.muted)
312 bar(p.percent, n, pal.fill, p.timeShare === null ? -1 : Math.min(n - 1, Math.floor(p.timeShare * n)))
313 put(' ', fg)
314 put(`${p.percent}%`, pal.text, { bold: true })
315 if (p.left && step >= 4) {
316 put(` ${g.left}`, fg)
317 put(p.left.replace(' ', ''), pal.muted)
318 } else if (p.left) {
319 put(' ▏ ', pal.muted)
320 put(`${g.left} `, fg)
321 put(p.left, pal.muted)
322 }
323 } else if (p.id === 'ctx') {
324 put(`${g.ctx} `, fg)
325 bar(p.percent, step >= 3 ? 3 : 4, fg)
326 put(' ', fg)
327 put(formatCtxTokens(p.tokens), pal.text, { bold: true })
328 } else if (p.id === 'warm') {
329 put(`${g.warm} `, fg)
330 bar(p.remaining * 100, step >= 3 ? 3 : 4, fg)
331 put(' ', fg)
332 put(p.label, pal.text, { bold: true })
333 } else {
334 put(`${g[p.id]} `, fg)
335 put(p.value, pal.text)
336 }
337 runs.push({ s: g.caps[1], fg: bg })
338 return runs
339}
340
341/**
342 * The terminal row at `columns`, the first step that fits: 1 every pill;
343 * 2 without the cache pill; 3 shorter bars (quota 6 -> 4 cells, context and
344 * warm 4 -> 3); 4 compact time labels; 5 also without the token-total pills;
345 * 6 every pill, wrapped. Width counts one gap between pills; the cost pill's
346 * spacer (one more gap) shows only when it fits.
347 */
348export const termLayout = (pills: Pill[], columns: number, glyphs: Glyphs, light: boolean) => {
349 const build = (step: number) => {
350 const row = pills
351 .filter(p => step < 2 || step > 5 || p.id !== 'cache')
352 .filter(p => step !== 5 || (p.id !== 'in' && p.id !== 'out'))
353 .map(p => ({ id: p.id, runs: termPill(p, glyphs, light, step > 5 ? 1 : step) }))
354 return { pills: row, width: row.reduce((n, p) => n + cells(p.runs) + 1, -1), step }
355 }
356 for (let step = 1; step <= 5; step++) {
357 const row = build(step)
358 if (row.width <= columns) return { ...row, wrap: false, spacer: row.pills.some(p => p.id === 'cost') && row.width + 1 <= columns }
359 }
360 return { ...build(6), wrap: true, spacer: false }
361}
362types/index.d.ts 20 lines1export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
2export type Tokens = { input: number; output: number; cache: number }
3/** The live context reading: the last response's input tokens, its window, and the engine's percent when given. */
4export type ContextUsage = { tokens: number; window: number; percent?: number }
5
6declare module 'claude-code' {
7 interface PluginState {
8 'usage-band': {
9 limits: Limit[]
10 cost: number | null
11 tokens: Tokens | null
12 /** Live context window reading; null before the first response fills it. */
13 context: Shaped<ContextUsage | null>
14 /** When the main thread's last response landed: the warm countdown's start; null before one, and on clear and resume. */
15 cacheWarm: number | null
16 now: number
17 }
18 }
19}
20