A band above the prompt for your limits, this chat's context, prompt cache and todos, and its token total and rate

Mods for the Claude Code terminal: a band above the prompt that shows your limits, this chat's usage and the prompt cache, plus a row for the subagents Claude starts.
Copy this prompt into Claude Code:
Install the Claude Code plugins from https://github.com/Oualid0/claude-mods:
add the repo as a plugin marketplace and install usage-ring. Then ask me whether
I also want agent-board (a row above the prompt that shows the subagents Claude
starts) and install it only if I say yes. If I do, ask whether I want to set
subagent limits (maxHaiku, maxSonnet, maxOpus); recommend leaving them unset if
I don't know my limits, and set only the numbers I give you. Finally tell me to
run /reload-plugins.
claude plugin marketplace add Oualid0/claude-mods
claude plugin install usage-ring@claude-mods
claude plugin install agent-board@claude-mods
Then run /reload-plugins in Claude Code, or start a new session. From a local clone, ./install.sh (it needs python3) registers the clone as the marketplace claude-mods (unless a marketplace of that name is already added, from GitHub or elsewhere) and installs the plugins that are not installed yet. It is safe to run again but does not update installed plugins.
Auto-update is off by default. Update by hand with /plugin marketplace update claude-mods in a session, or claude plugin update usage-ring@claude-mods and claude plugin update agent-board@claude-mods in the shell. You can also turn on Enable auto-update for the marketplace under Marketplaces in /plugin.
| Plugin | What it does |
|---|---|
usage-ring | One frame right above the prompt with up to three groups, separated by a dimmed │ : limits (Week, Session), chat (Context, Cache, Todos) and, only with showTokens, tokens (the chat's token count and rate). A pixel Claude stands beside the frame, hammering while a turn runs and sleeping otherwise (fast animation while it hammers, one slow step a second while it sleeps). Options add the tokens group (showTokens), the group titles (titles), the model in grey next to the pixel Claude, e.g. Opus 5.5 (mid) (showModel; effort low, mid, high, xhigh or max, known from the first request on), and always-short labels (compact). |
agent-board | A row right above the usage-ring band, shown once a subagent has started in this chat: one chip with an entry per model family (Haiku, Sonnet, Opus; Other only once used), a bar of how the tokens split, and a pixel crew beside it, one hard-hatted worker each for Haiku, Sonnet and Opus (Other has none) that works while the family has a subagent running and sleeps otherwise. A worker whose running subagents have all produced no tokens for 5 minutes looks at a clock and taps its foot (waiting). Five minutes after the last subagent ended the row hides, and it comes back with the next one, counts kept. For the single subagents, use Claude Code's own agent list below the prompt. |
session-board was removed in 2.0 and is no longer part of this marketplace. If you installed it earlier, remove it with claude plugin uninstall session-board@claude-mods.
See CHANGELOG.md for what changed in each release.
| Label | Group | Meaning |
|---|---|---|
Week (Wk) | limits | Weekly limit used, in percent, as a ring and a number. Red from 95%. |
Session (Se) | limits | Session limit (the 5-hour window) used, as a ring and a number, and the time until it resets: 4:50 (hours:minutes), or 33m under an hour. Red from 95%. Once the window is over it shows 0% 5:00 until the next reading. |
Context (Cx) | chat | Context window used, in percent, as a ring and a number. Yellow from 50%, red from 80%. |
Cache (Ca) | chat | The prompt cache as text, no ring: the time left (33m, in the last minute 45s). With a 1-hour cache it turns yellow under 10 minutes and red under 3; with a 5-minute cache yellow under 2 minutes and red under 1. A red cold once the cache is gone: its lifetime ran out, the model was switched, or the chat was compacted (/compact or automatic). A change of effort does not count. The next request warms it again. – before the first request. |
Todos (Td) | chat | Todos done out of all, as plain text, e.g. 3/5. Only while the chat has a todo list. In a muted terracotta (#9a5a44, not bold) while none is done (0/5). |
Tokens (Tk) | tokens | Only with the showTokens option; without it there is no tokens group and no such entry, and no tokens title even with titles. One entry with two figures, e.g. Tokens 39.5M 6k tok/s. The first is all tokens this chat used since the session started (input, output, cache reads and writes, subagents included); it grows after every model request. The second, after a gap of two spaces, is all tokens of the last minute per second, rounded, with the unit tok/s (800 tok/s, 6k tok/s; 0 tok/s in a pause). |
Haiku / Sonnet / Opus / Other (Ha / So / Op / Ot) | agents | Model family of the entry: Haiku, Sonnet, Opus, or Other only if a subagent's model fits none of them. The family is guessed from the model name. The label word is dimmed grey, like usage-ring's labels; the family colors are on the Split bar and the hats. The entry shows the running subagents, with a limit set as running/limit (e.g. 1/15). The count is a muted terracotta (#9a5a44) with 0 running, in the chip color from 1 running, and red above the limit. Haiku, Sonnet and Opus always show once any subagent has started; with hideUnused, a family shows only once it had a subagent. |
✔ | agents | Subagents of that family not running in this chat (done, failed, stopped, or idle teammates), e.g. ✔3, dimmed. Hidden while it would be ✔0. |
Split (Sp) | agents | A bar of how this chat's tokens split by who used them: the main loop in terracotta, Haiku neon mint (#39ff88), Sonnet neon cyan (#22d3ff), Opus neon violet (#b26bff), Other grey (#6a6a6a). The same colors tint the family's hard hat in the crew (Haiku, Sonnet and Opus; Other has no crew member), not the label words. Every part with tokens gets at least one cell. It shows the split only; the total is in the tokens group of usage-ring (option showTokens). Empty until the first request. The word Split itself shows only with the titles option. |
A value of 0 is shown in a fixed muted terracotta (#9a5a44, not bold) instead of the bright one: 0% of Week, Session or Context, a Todos count with none done, a subagent count with 0 running, and, with showTokens, a total of 0 or a rate of 0 tok/s. The labels stay grey and the ✔n done counts stay dimmed. From above 0 a value has its normal color, and the yellow and red warning colors win. The Cache text has no zero case.
Labels are full words; the short form in brackets is used once the terminal is too narrow for them, or always with the compact option. The group titles limits, chat and tokens show only with the titles option, the tokens group only with showTokens, and the model only with showModel.
When the terminal is narrower still, usage-ring drops the least important first: the model label, the group titles, then (only with showTokens) the rate part of Tokens and the whole Tokens entry (and with it the tokens group), Ca, Td, Wk, the pixel Claude, then Cx. Se stays longest (without a limit reading, whichever entry is left); if not even one entry fits, the band is hidden. Nothing is squeezed or wrapped.
The agents row first shortens its labels, then drops, in this order: the titles agents and Split, the split bar, the ✔ counts, then the crew. If not even the counts fit, the row is hidden. It is also hidden when the band has fewer than 6 rows to draw in, to leave room for the prompt.
Wk, Se, Cx), the split bar and the crew are pixel images in kitty and Ghostty; other terminals show a glyph instead.Cache row above says.Ca is an estimate. Claude Code does not tell plugins how long the cache lives (5 minutes or 1 hour) except when the model is switched, where it names the lifetime (5m or 1h) and the band takes it. Otherwise the band assumes 1 hour and learns from what each request read from the cache after a pause of more than 5 minutes: a hit means 1 hour at once, but only two misses in a row mean 5 minutes. A single miss can come from a changed system prompt or tool list (for example after /reload-plugins), which the band cannot see, so it does not count.Tokens figures and Ca start over when a session starts or resumes and on /clear; earlier tokens of a resumed session are not available. Td starts over on /clear (a new chat); on resume (in a session or with claude --resume) it shows the resumed chat's own task list. Cx is also reset on /clear and resume until the next measurement.Td counts TaskCreate/TaskUpdate/TaskList and TodoWrite. Newer models only have these tools with CLAUDE_CODE_ENABLE_TODO_TOOLS=1 (docs).agent-board syncs each subagent's status from the engine's agent list every 2 s, so a failed or stopped subagent may show a moment late. A subagent that drops out of that list without ending counts as stopped after two syncs. A subagent that is never in it (a workflow's) keeps its status until its turn ends, or counts as done once it has sent no tokens for 30 minutes; a later request revives it./clear and when another chat is resumed.usage-ring has five options, all off by default:
| Option | Meaning |
|---|---|
limitsFile | Write the session and weekly limits to $CLAUDE_CONFIG_DIR/usage-limits.json (default ~/.claude) for other tools to read. It also seeds the rings from that file when a session starts and the engine has no reading yet; a window whose reset time has passed is skipped. |
showModel | Show the model and its effort in grey next to the pixel Claude, e.g. Opus 5.5 (mid). |
showTokens | Show the tokens group: all tokens this chat used and the rate of the last minute (Tokens 39.5M 6k tok/s). Without it the group, its entry and its title are not shown. |
titles | Start each group with its title: limits, chat and (with showTokens) tokens. |
compact | Always use the two-letter labels (Wk, Se, Cx, Ca, Td, Tk), not only when the terminal is narrow. |
Set them with /plugin configure usage-ring@claude-mods in Claude Code, or:
echo '{"limitsFile":"true","showModel":"true","showTokens":"true","titles":"false","compact":"false"}' | claude plugin configure usage-ring@claude-mods --values-stdin
agent-board has seven options. The limits are unset by default (only the count), the others are off by default:
| Option | Meaning |
|---|---|
maxHaiku | Limit of Haiku subagents running at once. |
maxSonnet | Limit of Sonnet subagents running at once. |
maxOpus | Limit of Opus subagents running at once. |
hideAfter | Minutes after the last subagent ended until the row hides (default 5); 0 keeps it shown. A value that is not a number of minutes (negative, blank, text) means 5. |
titles | Show the words agents (the row's title) and Split (the bar's label). |
compact | Always write the families as Ha, So, Op, Ot (and the bar as Sp), not only when the terminal is narrow. |
hideUnused | Show a family only once it had a subagent in this chat (Other always needs a subagent of its own); by default Haiku, Sonnet and Opus always show. |
A limit counts only as a whole number from 1 up; 0, negatives, fractions and blanks mean no limit.
The limits are unset by default. Leave them unset if you don't know how many subagents you want to allow: the row then shows plain counts and never turns red.
Set them with /plugin configure agent-board@claude-mods, or (example values):
echo '{"maxHaiku":"4","maxSonnet":"2","maxOpus":"1","hideAfter":"5","titles":"false","compact":"false","hideUnused":"false"}' | claude plugin configure agent-board@claude-mods --values-stdin
plugins/<name>/: .claude-plugin/plugin.json, hooks/hooks.json, hooks/register.tsx with the hooks, pure logic in files beside it, types/index.d.ts (the state contract) and tests/.claude plugin validate ., then claude plugin validate plugins/<name> and claude plugin test plugins/<name>./reload-plugins or the next session..githooks/pre-commit, runs gitleaks on staged changes): git config core.hooksPath .githooks. The setting is local to the clone.next(e) and keeps what is beneath (agent-board's row on top, usage-ring's band next to the prompt).MIT, see LICENSE.
hooks/register.tsx 440 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { Cache, Model, Todos, TokenLog, Usage } from '../types'
5import { FRESH_CACHE, afterRequest, cacheSegment, coldCache, ttlOf, withTtl } from './cache'
6import { CLAUDE, SCALE, SPRITE, SPRITE_W, claudePixels, hammerPixels } from './claude'
7import {
8 RING_COLUMNS,
9 RING_ROWS,
10 SPRITE_COLUMNS,
11 GAP,
12 LABELS,
13 labelOf,
14 fit,
15 fromList,
16 fromSnapshot,
17 fromTodoWrite,
18 groups,
19 isOn,
20 modelLabel,
21 MODEL_GAP,
22 SEPARATOR,
23 rateAt,
24 segments,
25 tokensEntry,
26 snapshot,
27 usageFrom,
28 withCreated,
29 withUpdated,
30 withTokens,
31 ZERO,
32} from './model'
33import { RING_SIZE, hexToRgb, hot, ringGlyph, ringPixels, toBase64 } from './ring'
34
35const usage = atom({ plugin: 'usage-ring', key: 'usage' } as const, {} as Usage)
36const todos = atom({ plugin: 'usage-ring', key: 'todos' } as const, {} as Todos)
37
38// Tokens this chat used since the session started: all four counts of every
39// request, subagents included. In $.state, so a reload keeps them.
40const tokens = atom({ plugin: 'usage-ring', key: 'tokens' } as const, 0)
41// The requests of the last minute, for the token rate.
42const recent = atom({ plugin: 'usage-ring', key: 'recent' } as const, [] as TokenLog)
43// Animation frame, and whether a turn of this session is running.
44const frame = atom({ plugin: 'usage-ring', key: 'frame' } as const, 0)
45const isBusy = atom({ plugin: 'usage-ring', key: 'isBusy' } as const, false)
46const cache = atom({ plugin: 'usage-ring', key: 'cache' } as const, FRESH_CACHE as Cache)
47const model = atom({ plugin: 'usage-ring', key: 'model' } as const, {} as Model)
48
49/** Milliseconds per frame while a turn runs (the hammer swings) and while the sprite sleeps (the z's rise). */
50const FRAME_MS = 150
51const SLEEP_FRAME_MS = 1000
52/** Both frame counts divide it, so the poses stay in step when the counter wraps. */
53const FRAME_WRAP = 12_000
54/** The hammer's swing: raised, raised, swinging, hit, hit with sparks, swinging back. */
55const SWING = [0, 0, 1, 2, 3, 1]
56/** The z's change with every frame of the sleeping sprite. */
57const Z_PHASES = 12
58
59const LIMITS_FILE = 'usage-limits.json'
60
61/** Claude Code's config directory; undefined when neither CLAUDE_CONFIG_DIR nor HOME is set. */
62async function configDir($: EngineInterface): Promise<string | undefined> {
63 const dir = await $.env.get('CLAUDE_CONFIG_DIR')
64 if (dir) return dir
65 const home = await $.env.get('HOME')
66 return home ? `${home}/.claude` : undefined
67}
68
69/** Seeds the session and weekly figures from the last snapshot on disk. */
70async function seedFromSnapshot($: EngineInterface): Promise<void> {
71 try {
72 const dir = await configDir($)
73 if (!dir) return
74 const seed = fromSnapshot(JSON.parse(await $.fs.read(`${dir}/${LIMITS_FILE}`)), await $.clock.now())
75 await update($, usage, u => ({
76 ...u,
77 sessionUsed: u.sessionUsed ?? seed.sessionUsed,
78 sessionResetsAt: u.sessionResetsAt ?? seed.sessionResetsAt,
79 weekUsed: u.weekUsed ?? seed.weekUsed,
80 }))
81 } catch {
82 // No snapshot yet: the rings appear with the first reading.
83 }
84}
85
86/** Reads the task list that already exists (a resumed session, a reload). */
87async function syncTodos($: EngineInterface): Promise<void> {
88 const names = (await $.tool.list()).map(t => t.name)
89 if (!names.includes('TaskList')) return
90 try {
91 const r = await $.tool.call({ tool: 'TaskList' })
92 const list = (r.result as { tasks?: { id: string; status: string }[] } | undefined)?.tasks
93 if (list && !r.isError) await update($, todos, () => fromList(list))
94 } catch {
95 // No list to read: the ring appears with the first TaskCreate.
96 }
97}
98
99/**
100 * The context fill: the last response's figure, or before the first response
101 * (a new chat, after /clear) the local estimate of what is already loaded
102 * (system prompt, tools, memory files). Undefined when neither is known.
103 */
104async function contextPercent(
105 $: EngineInterface,
106 context: { percent?: number },
107): Promise<number | undefined> {
108 if (context.percent !== undefined) return context.percent
109 try {
110 const { context: c } = await $.session.usage({ breakdown: 'summary' })
111 return c.breakdown?.percentage
112 } catch {
113 return undefined
114 }
115}
116
117// The frame clock: one timer, 150 ms while a turn runs, one second while the sprite sleeps.
118let tick: Timer | undefined
119let tickMs = 0
120
121function stopTick(): void {
122 tick?.cancel()
123 tick = undefined
124}
125
126function startTick($: EngineInterface, ms: number): void {
127 stopTick()
128 tickMs = ms
129 // Only a redraw: the frame number picks the hammer pose or the z's.
130 tick = $.clock.every(ms, () => {
131 void update($, frame, f => (f + 1) % FRAME_WRAP).catch(() => undefined)
132 })
133}
134
135/** Switches a running clock to `ms`; before session.start (or after the session ended) there is none. */
136function retick($: EngineInterface, ms: number): void {
137 if (tick && tickMs !== ms) startTick($, ms)
138}
139
140/** Runs `step`, ignoring a failure: the steps of a start do not depend on each other. */
141async function attempt(step: () => Promise<unknown>): Promise<void> {
142 try {
143 await step()
144 } catch {
145 // The band fills in with the first reading instead.
146 }
147}
148
149const pictures = new Map<string, string>()
150
151/** The base64 picture for `key`, drawn once. */
152function cached(key: string, draw: () => Uint8Array): string {
153 const hit = pictures.get(key)
154 if (hit !== undefined) return hit
155 const base64 = toBase64(draw())
156 pictures.set(key, base64)
157 return base64
158}
159
160function picture(percent: number, color: string): string {
161 return cached(`r${Math.round(percent)}${color}`, () => ringPixels(Math.round(percent), hexToRgb(color)))
162}
163
164export const register: Register = (on, options) => {
165 const writesLimits = isOn(options.limitsFile)
166 const showsModel = isOn(options.showModel)
167 const layout = { titles: isOn(options.titles), compact: isOn(options.compact), tokens: isOn(options.showTokens) }
168
169 on('session.start', async ($, e, next) => {
170 const result = await next(e)
171 // A repeated session.start replaces the timer instead of adding a second.
172 stopTick()
173 let hasLimits = false
174 await attempt(async () => {
175 const { rateLimits, context } = await $.session.usage()
176 hasLimits = rateLimits.length > 0
177 const percent = await contextPercent($, context)
178 await update($, usage, u => usageFrom(rateLimits, percent, u))
179 })
180 if (writesLimits && !hasLimits) await attempt(() => seedFromSnapshot($))
181 await attempt(() => syncTodos($))
182 await attempt(async () => {
183 const id = await $.session.model()
184 await update($, model, m => ({ ...m, id }))
185 })
186 let isRunning = false
187 await attempt(async () => {
188 isRunning = await read($, isBusy)
189 })
190 startTick($, isRunning ? FRAME_MS : SLEEP_FRAME_MS)
191 return result
192 })
193
194 on('session.measure', async ($, e, next) => {
195 const percent = await contextPercent($, e.context)
196 await update($, usage, u => usageFrom(e.rateLimits, percent, u))
197 if (writesLimits) {
198 try {
199 const written = snapshot(e.rateLimits, await $.clock.now(), await $.session.model())
200 const dir = await configDir($)
201 if (written && dir) await $.fs.write(`${dir}/${LIMITS_FILE}`, JSON.stringify(written))
202 } catch {
203 // No model or no file: readers keep the last snapshot; the band must not break.
204 }
205 }
206 return next(e)
207 })
208
209 on('turn.start', async ($, e, next) => {
210 await update($, isBusy, () => true)
211 retick($, FRAME_MS)
212 return next(e)
213 })
214
215 // Each request's tokens as soon as it is answered, so the count moves while a
216 // turn runs; turn.complete would bring the same sum only at the turn's end.
217 on('turn.step', async function* ($, e, next) {
218 const sentAt = await $.clock.now()
219 // The model and effort this request is really sent with (a fallback, /model, /effort).
220 if (e.agentId === undefined) await update($, model, () => ({ id: e.model, effort: e.effort }))
221 const r = yield* next(e)
222 const u = r.usage
223 if (u) {
224 const used = u.input_tokens + u.output_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
225 await update($, tokens, t => t + used)
226 const at = await $.clock.now()
227 await update($, recent, log => withTokens(log, at, used))
228 // Subagents keep caches of their own; the band times the main thread's.
229 if (e.agentId === undefined) await update($, cache, c => afterRequest(c, sentAt, u.model, u))
230 }
231 return r
232 })
233
234 on('turn.complete', async ($, e, next) => {
235 if (e.agentId === undefined) {
236 await update($, isBusy, () => false)
237 retick($, SLEEP_FRAME_MS)
238 }
239 return next(e)
240 })
241
242 // A model switch drops the cache (every model has one of its own), and so does
243 // a compaction (the history it served is gone). Both are cold until the next request.
244 // A subagent's switch or compaction leaves the main thread's cache alone.
245 on('classic.PostModelSwitch', async ($, e, next) => {
246 const isMain = e.agent_id === undefined
247 const isSwitch = e.from_model !== e.to_model && e.source !== 'resume'
248 // The engine names the lifetime on a switch (5m or 1h): it settles what the requests could only hint at.
249 const ttl = ttlOf(e.cache_ttl)
250 if (isMain && (isSwitch || ttl !== undefined)) {
251 await update($, cache, c => {
252 const named = ttl === undefined ? c : withTtl(c, ttl)
253 return isSwitch ? coldCache(named) : named
254 })
255 }
256 return next(e)
257 }).catch(($, e, next) => next(e))
258
259 on('classic.PostCompact', async ($, e, next) => {
260 if (e.agent_id === undefined) await update($, cache, c => coldCache(c))
261 return next(e)
262 }).catch(($, e, next) => next(e))
263
264 // A new chat (after /clear, or another one resumed in its place) starts with no
265 // cache, no tokens, no rate, no todos and no context fill of its own, and the frame
266 // clock goes on: no session.start follows a /clear. Any other end stops the clock.
267 // A resumed chat brings its task list along, so it is read again once the end has
268 // passed; a cleared one is empty.
269 on('session.end', async ($, e, next) => {
270 const isNewChat = e.reason === 'clear' || e.reason === 'resume'
271 if (isNewChat) {
272 await update($, cache, () => FRESH_CACHE)
273 await update($, tokens, () => 0)
274 await update($, recent, () => [])
275 await update($, todos, () => ({}))
276 await update($, usage, u => ({ ...u, contextUsed: undefined }))
277 } else {
278 stopTick()
279 }
280 const result = await next(e)
281 if (e.reason === 'resume') await attempt(() => syncTodos($))
282 return result
283 })
284
285 on('tool.call', { tool: 'TaskCreate' }, async ($, e, next) => {
286 const r = await next(e)
287 const id = (r.result as { task?: { id?: string } } | undefined)?.task?.id
288 if (id !== undefined && !r.isError) await update($, todos, t => withCreated(t, id))
289 return r
290 }).catch(($, e, next) => next(e))
291
292 on('tool.call', { tool: 'TaskUpdate' }, async ($, e, next) => {
293 const r = await next(e)
294 const input = e as unknown as { taskId?: string; status?: string }
295 if (input.taskId !== undefined && !r.isError) {
296 const id = input.taskId
297 await update($, todos, t => withUpdated(t, id, input.status))
298 }
299 return r
300 }).catch(($, e, next) => next(e))
301
302 on('tool.call', { tool: 'TaskList' }, async ($, e, next) => {
303 const r = await next(e)
304 const list = (r.result as { tasks?: { id: string; status: string }[] } | undefined)?.tasks
305 if (list && !r.isError) await update($, todos, () => fromList(list))
306 return r
307 }).catch(($, e, next) => next(e))
308
309 on('tool.call', { tool: 'TodoWrite' }, async ($, e, next) => {
310 const r = await next(e)
311 const list = (e as unknown as { todos?: { status: string }[] }).todos
312 if (list && !r.isError) await update($, todos, () => fromTodoWrite(list))
313 return r
314 }).catch(($, e, next) => next(e))
315
316 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
317 if (e.surface !== 'terminal' || e.props.hasSurvey) return next(e)
318
319 const usedTokens = await read($, tokens)
320 const at = await $.clock.now()
321 const rings = segments(await read($, usage), await read($, todos), at)
322 if (rings.length === 0) return next(e)
323 const all = [...rings, cacheSegment(await read($, cache), at)]
324 const m = await read($, model)
325 const extras = {
326 total: usedTokens,
327 rate: rateAt(await read($, recent), at),
328 model: showsModel ? modelLabel(m.id, m.effort) : undefined,
329 }
330 const shown = fit(all, extras, e.props.bodyColumns, layout)
331 // Not even one entry fits: show nothing rather than squeeze it.
332 if (!shown) return next(e)
333 const tokenCount = tokensEntry(extras, shown)
334
335 // Other mods' drawings go above the band, so it stays next to the prompt.
336 const below = await next(e)
337 const { Box, Text, Image } = $.ui.resolve(e)
338 const f = await read($, frame)
339 const busy = await read($, isBusy)
340 const pose = SWING[f % SWING.length]!
341
342 // A value in the bright color of its entry, or in the muted ZERO color (not bold) when it is 0.
343 const value = (text: string, isDim: boolean, color: string) =>
344 isDim ? (
345 <Text color={ZERO}>{text}</Text>
346 ) : (
347 <Text color={hot(color)} bold>
348 {text}
349 </Text>
350 )
351 // An entry: its dimmed label, a ring for the limits and the context, then the value.
352 const entry = (s: typeof shown.segments[number]) => (
353 <Box key={s.id} flexDirection="row" gap={1} alignItems="center">
354 <Text dimColor>{labelOf(s, shown)}</Text>
355 {s.hasRing ? (
356 <Image
357 key={`ring-${s.id}`}
358 source={{ rgba: picture(s.percent, s.color), width: RING_SIZE, height: RING_SIZE }}
359 columns={RING_COLUMNS}
360 rows={RING_ROWS}
361 alt={ringGlyph(s.percent)}
362 />
363 ) : null}
364 {value(s.time ? s.text.slice(0, -(s.time.length + 1)) : s.text, s.isDim === true, s.textColor ?? s.color)}
365 {s.time ? (
366 <Text color={hot(CLAUDE)} bold>
367 {s.time}
368 </Text>
369 ) : null}
370 </Box>
371 )
372 // A group: its title in terracotta (with the `titles` option), then its entries.
373 const group = (title: string, items: ReturnType<typeof entry>[]) => (
374 <Box key={title} flexDirection="row" gap={1} alignItems="center">
375 {shown.hasTitles ? <Text color={CLAUDE}>{title}</Text> : null}
376 <Box flexDirection="row" gap={GAP} alignItems="center">
377 {items}
378 </Box>
379 </Box>
380 )
381 // The tokens group is one entry without a ring: the dimmed label, the total, then the rate a gap apart.
382 const tokenItems = tokenCount
383 ? [
384 <Box key="tokens-entry" flexDirection="row" gap={1}>
385 <Text dimColor>{tokenCount.label}</Text>
386 <Box flexDirection="row" gap={GAP}>
387 {value(tokenCount.total, tokenCount.isTotalZero, CLAUDE)}
388 {tokenCount.rate !== undefined ? value(tokenCount.rate, tokenCount.isRateZero, CLAUDE) : null}
389 </Box>
390 </Box>,
391 ]
392 : []
393
394 // Hammering while a turn runs, asleep otherwise; 24 x 24 sprite pixels, SCALE image pixels each.
395 const zPhase = f % Z_PHASES
396 const spriteKey = busy ? `h${pose}` : `s${zPhase}`
397 const sprite = (
398 <Image
399 key="claude"
400 source={{
401 rgba: cached(spriteKey, () => (busy ? hammerPixels(pose) : claudePixels(zPhase))),
402 width: SPRITE_W * SCALE,
403 height: SPRITE * SCALE,
404 }}
405 columns={SPRITE_COLUMNS}
406 rows={3}
407 alt={busy ? '⚒' : 'z'}
408 />
409 )
410 const { limits, chat } = groups(shown.segments)
411 // The groups that have something to show, one frame around them, a dimmed bar between.
412 const parts = [
413 limits.length > 0 ? group(LABELS.limits, limits.map(entry)) : null,
414 chat.length > 0 ? group(LABELS.chat, chat.map(entry)) : null,
415 tokenItems.length > 0 ? group(LABELS.tokens, tokenItems) : null,
416 ].filter(part => part !== null)
417 return (
418 <Box flexDirection="column">
419 {below}
420 <Box flexDirection="row" alignItems="center">
421 <Box borderStyle="round" borderColor={CLAUDE} paddingX={1} flexDirection="row">
422 {parts.map((part, i) => (
423 <Box key={`part-${i}`} flexDirection="row">
424 {i > 0 ? <Text dimColor>{SEPARATOR}</Text> : null}
425 {part}
426 </Box>
427 ))}
428 </Box>
429 {shown.hasSprite ? sprite : null}
430 {shown.hasModel && extras.model !== undefined ? (
431 <Box marginLeft={MODEL_GAP}>
432 <Text dimColor>{extras.model}</Text>
433 </Box>
434 ) : null}
435 </Box>
436 </Box>
437 )
438 })
439}
440hooks/cache.ts 114 lines1// The prompt cache's countdown. The engine shows neither the cache's lifetime
2// (5 minutes or 1 hour) nor when an entry lapses; both are inferred from what
3// each request read from the cache and how long after the one before it came.
4
5import type { Cache } from '../types'
6import { ALERT, COLORS, GREY, NAME, SHORT, WARN, duration, type Segment } from './model'
7
8export const SHORT_TTL = 5 * 60_000
9export const LONG_TTL = 60 * 60_000
10
11/** Time left under which the ring turns yellow, then red: 10 and 3 minutes for a 1-hour entry, 2 and 1 for a 5-minute one. */
12export function thresholds(ttl: number): { warn: number; alert: number } {
13 return ttl <= SHORT_TTL ? { warn: 2 * 60_000, alert: 60_000 } : { warn: 10 * 60_000, alert: 3 * 60_000 }
14}
15
16/** Time left as `33m`, or `45s` in the last minute. */
17export const timeLeft = (ms: number): string => (ms < 60_000 ? `${Math.max(0, Math.floor(ms / 1000))}s` : duration(ms))
18
19/** Shown once the entry is gone: its lifetime is over, the model switched or the chat compacted. */
20export const COLD = 'cold'
21
22/** Shown before the first request: nothing is cached yet. */
23export const CACHE_NONE = '–'
24
25/** At least this share of the input read from the cache counts as a hit. */
26export const HIT_SHARE = 0.5
27/** Below this share it counts as a miss. */
28export const MISS_SHARE = 0.1
29
30export const FRESH_CACHE: Cache = { ttl: LONG_TTL }
31
32type Counts = {
33 input_tokens: number
34 cache_read_input_tokens: number
35 cache_creation_input_tokens: number
36}
37
38export function readShare(u: Counts): number | undefined {
39 const total = u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
40 return total > 0 ? u.cache_read_input_tokens / total : undefined
41}
42
43/** This many telling misses in a row mean the entry lives 5 minutes; one can be a changed prompt. */
44export const MISSES_FOR_SHORT = 2
45
46/**
47 * The cache after a main-thread request sent at `sentAt` answered with `u`.
48 *
49 * Only a gap between both lifetimes says which one holds: a hit after more
50 * than 5 minutes means 1 hour at once. A miss there is also what a changed
51 * system prompt or tool list looks like (a plugin reload, an MCP change), so
52 * only `MISSES_FOR_SHORT` of them in a row mean 5 minutes; a hit, or a request in
53 * between that read some of the cache, starts the count over. Requests that are
54 * no telling ones (short gap, another model, a cold entry) leave the count as it is.
55 * The latest verdict wins, so a drop to 5 minutes (usage overage) shows too.
56 */
57export function afterRequest(cache: Cache, sentAt: number, model: string, u: Counts): Cache {
58 const share = readShare(u)
59 let { ttl } = cache
60 let misses = cache.misses ?? 0
61 const gap = cache.lastAt === undefined ? undefined : sentAt - cache.lastAt
62 // A cold entry was dropped or rewritten (a compaction), so what this request read says nothing about the lifetime.
63 const isTelling = !cache.isCold && gap !== undefined && gap > SHORT_TTL && gap < LONG_TTL && cache.model === model
64 if (isTelling && share !== undefined) {
65 if (share >= HIT_SHARE) {
66 ttl = LONG_TTL
67 misses = 0
68 } else if (share < MISS_SHARE) {
69 misses++
70 if (misses >= MISSES_FOR_SHORT) {
71 ttl = SHORT_TTL
72 misses = 0
73 }
74 } else {
75 misses = 0
76 }
77 }
78 return { lastAt: sentAt, model, ttl, ...(misses > 0 ? { misses } : {}) }
79}
80
81/** The lifetime the engine names on a model switch (`cache_ttl`), or undefined for anything else. */
82export function ttlOf(value: unknown): number | undefined {
83 return value === '1h' ? LONG_TTL : value === '5m' ? SHORT_TTL : undefined
84}
85
86/** The cache with the lifetime the engine named: it is authoritative, so the count of misses starts over. */
87export function withTtl(cache: Cache, ttl: number): Cache {
88 const { misses: _, ...rest } = cache
89 return { ...rest, ttl }
90}
91
92/** The cache after a model switch or a compaction: gone until the next request. */
93export const coldCache = (cache: Cache): Cache => ({ ...cache, isCold: true })
94
95/** Whether the entry is gone: dropped by a switch or a compaction, or its lifetime is over. False before the first request. */
96export function isCold(cache: Cache, now: number): boolean {
97 if (cache.isCold) return true
98 return cache.lastAt !== undefined && cache.lastAt + cache.ttl - now <= 0
99}
100
101/**
102 * The cache's entry, text only: the time left in the normal color, yellow and red as
103 * `thresholds` says. Cold is a red `cold`; before the first request `–`.
104 */
105export function cacheSegment(cache: Cache, now: number): Segment {
106 const base = { id: 'cache', name: NAME.cache, short: SHORT.cache, hasRing: false } as const
107 if (isCold(cache, now)) return { ...base, percent: 0, text: COLD, color: GREY, textColor: ALERT }
108 if (cache.lastAt === undefined) return { ...base, percent: 0, text: CACHE_NONE, color: GREY, textColor: COLORS.cache }
109 const left = cache.lastAt + cache.ttl - now
110 const { warn, alert } = thresholds(cache.ttl)
111 const color = left < alert ? ALERT : left < warn ? WARN : COLORS.cache
112 return { ...base, percent: (left / cache.ttl) * 100, text: timeLeft(left), color }
113}
114hooks/claude.ts 155 lines1// Pure pixel logic of the pixel Claude beside the band's frame: a hammering and a
2// sleeping frame as RGBA. No `$` in here, so the tests can drive it directly.
3import { hexToRgb, hot } from './ring'
4import type { Rgb } from './ring'
5
6export const CLAUDE = '#d97757'
7
8export const SPRITE = 24
9/** 24 x 24 pixels on 6 x 3 cells: the body from x 4, both arms inside the picture. */
10export const SPRITE_W = 24
11/** Each sprite pixel becomes SCALE x SCALE image pixels, so the terminal scales crisp blocks. */
12export const SCALE = 4
13const BODY = hexToRgb(CLAUDE)
14const EYE: Rgb = [38, 24, 20]
15const Z_RGB = hexToRgb(hot(CLAUDE))
16
17const Z = ['###', '.#.', '###']
18
19/**
20 * The sleeping Claude: eyes shut, both arms. `zPhase` 0..11 lets three z's
21 * appear one by one, rising diagonally from the top right of the head, then
22 * clears them.
23 */
24export function claudePixels(zPhase: number): Uint8Array {
25 const grid: (Rgb | null)[][] = Array.from({ length: SPRITE }, () => Array<Rgb | null>(SPRITE_W).fill(null))
26 const alpha: number[][] = Array.from({ length: SPRITE }, () => Array<number>(SPRITE_W).fill(0))
27 const put = (x: number, y: number, rgb: Rgb, a = 1) => {
28 if (x < 0 || y < 0 || x >= SPRITE_W || y >= SPRITE) return
29 grid[y]![x] = rgb
30 alpha[y]![x] = a
31 }
32 const rect = (x0: number, y0: number, w: number, h: number, rgb: Rgb) => {
33 for (let y = y0; y < y0 + h; y++) for (let x = x0; x < x0 + w; x++) put(x, y, rgb)
34 }
35
36 // Asleep where the hammering Claude stands: same height, body from x 4.
37 const top = 5
38 rect(4, top, 16, 11, BODY)
39 rect(1, top + 4, 3, 3, BODY)
40 rect(20, top + 4, 3, 3, BODY)
41 rect(7, top + 5, 4, 1, EYE)
42 rect(13, top + 5, 4, 1, EYE)
43 for (const x of [5, 9, 13, 17]) rect(x, top + 11, 2, 4, BODY)
44
45 // Three z's one by one: beside the head on the right, then up and over it.
46 const glyph = (x0: number, y0: number) =>
47 Z.forEach((line, dy) => {
48 for (let dx = 0; dx < line.length; dx++) if (line[dx] === '#') put(x0 + dx, y0 + dy, Z_RGB)
49 })
50 const shown = zPhase < 9 ? Math.floor(zPhase / 3) + 1 : 0
51 const spots = [
52 [21, top],
53 [17, top - 4],
54 [13, top - 5],
55 ] as const
56 spots.slice(0, shown).forEach(([x, y]) => glyph(x, y))
57
58 const width = SPRITE_W * SCALE
59 const height = SPRITE * SCALE
60 const px = new Uint8Array(width * height * 4)
61 for (let y = 0; y < height; y++)
62 for (let x = 0; x < width; x++) {
63 const sy = Math.floor(y / SCALE)
64 const sx = Math.floor(x / SCALE)
65 const rgb = grid[sy]![sx]
66 if (!rgb) continue
67 const i = (y * width + x) * 4
68 px[i] = rgb[0]
69 px[i + 1] = rgb[1]
70 px[i + 2] = rgb[2]
71 px[i + 3] = Math.round(alpha[sy]![sx]! * 255)
72 }
73 return px
74}
75
76// --- working poses -------------------------------------------------------------
77
78const HANDLE: Rgb = [139, 90, 60]
79const IRON: Rgb = [150, 150, 158]
80const SPARK: Rgb = [255, 214, 120]
81
82type Canvas = { put: (x: number, y: number, rgb: Rgb) => void; rect: (x: number, y: number, w: number, h: number, rgb: Rgb) => void; pixels: () => Uint8Array }
83
84function canvas(): Canvas {
85 const grid: (Rgb | null)[][] = Array.from({ length: SPRITE }, () => Array<Rgb | null>(SPRITE_W).fill(null))
86 const put = (x: number, y: number, rgb: Rgb) => {
87 if (x >= 0 && y >= 0 && x < SPRITE_W && y < SPRITE) grid[y]![x] = rgb
88 }
89 const rect = (x0: number, y0: number, w: number, h: number, rgb: Rgb) => {
90 for (let y = y0; y < y0 + h; y++) for (let x = x0; x < x0 + w; x++) put(x, y, rgb)
91 }
92 const pixels = () => {
93 const width = SPRITE_W * SCALE
94 const height = SPRITE * SCALE
95 const px = new Uint8Array(width * height * 4)
96 for (let y = 0; y < height; y++)
97 for (let x = 0; x < width; x++) {
98 const rgb = grid[Math.floor(y / SCALE)]![Math.floor(x / SCALE)]
99 if (!rgb) continue
100 const i = (y * width + x) * 4
101 px[i] = rgb[0]
102 px[i + 1] = rgb[1]
103 px[i + 2] = rgb[2]
104 px[i + 3] = 255
105 }
106 return px
107 }
108 return { put, rect, pixels }
109}
110
111/** Body, legs and open eyes at `top`; `eyeDx` shifts the pupils, `x0` the whole figure. */
112function figure(c: Canvas, top: number, x0: number, eyeDx: number, eyeDy: number, arms: 'both' | 'right' | 'none', legs = SPRITE - top - 11) {
113 c.rect(x0 + 4, top, 16, 11, BODY)
114 if (arms === 'both' || arms === 'right') c.rect(x0 + 20, top + 4, 3, 3, BODY)
115 if (arms === 'both') c.rect(x0 + 1, top + 4, 3, 3, BODY)
116 c.rect(x0 + 8 + eyeDx, top + 3 + eyeDy, 2, 3, EYE)
117 c.rect(x0 + 14 + eyeDx, top + 3 + eyeDy, 2, 3, EYE)
118 for (const x of [5, 9, 13, 17]) c.rect(x0 + x, top + 11, 2, legs, BODY)
119}
120
121/** Faces left and hammers the frame on its left: 0 raised, 1 swinging, 2 hit, 3 hit with sparks. */
122export function hammerPixels(pose: number): Uint8Array {
123 const c = canvas()
124 // High in the picture, flush left, so the hammer reaches the frame beside it.
125 const top = 5
126 figure(c, top, 0, -2, 0, 'right', 4)
127 // Left arm: from the body out to a hand at x 2..3, raised, halfway or level.
128 const hy = [top + 1, top + 3, top + 5, top + 5][pose]!
129 c.rect(2, hy, 2, 2, BODY)
130 if (pose === 0) {
131 // Hammer up: handle straight up from the hand, head on top.
132 c.rect(2, hy - 3, 1, 3, HANDLE)
133 c.rect(0, hy - 6, 4, 3, IRON)
134 } else if (pose === 1) {
135 // Halfway: handle up and to the left, head above it.
136 c.put(1, hy - 1, HANDLE)
137 c.put(1, hy - 2, HANDLE)
138 c.rect(0, hy - 6, 3, 4, IRON)
139 } else {
140 // Hit: the head against the left edge, which is the frame.
141 c.rect(0, hy - 2, 2, 4, IRON)
142 if (pose === 3) {
143 for (const [x, y] of [
144 [0, hy - 4],
145 [1, hy - 5],
146 [3, hy - 4],
147 [0, hy + 3],
148 [2, hy + 4],
149 ] as const)
150 c.put(x, y, SPARK)
151 }
152 }
153 return c.pixels()
154}
155hooks/model.ts 464 lines1// Pure logic of the band: what each entry shows, the todo bookkeeping and the
2// optional usage-limits.json snapshot. No `$` in here, so the tests
3// can drive it directly.
4
5import type { TodoStatus, Todos, TokenLog, Usage } from '../types'
6
7/** Claude's terracotta: every ring, the frame and the titles. */
8export const TERRACOTTA = '#d97757'
9
10/** A red that sits next to the terracotta: rings from 95% on and a cache about to lapse. */
11export const ALERT = '#e5484d'
12/** A yellow that sits next to the terracotta and the red: a context filling up, a cache running low. */
13export const WARN = '#e5b83c'
14/** The grey of a cache that holds nothing (cold). */
15export const GREY = '#8a8a8a'
16/** A muted terracotta for a value of 0: apart from the grey labels, quieter than the bright values. */
17export const ZERO = '#9a5a44'
18/** From this fill on a limit ring turns red. */
19export const ALERT_PERCENT = 95
20/** From this fill on the context ring turns yellow, then red. */
21export const CONTEXT_WARN_PERCENT = 50
22export const CONTEXT_ALERT_PERCENT = 80
23
24/** The color of a limit ring: red from 95%, otherwise `base`. */
25export const ringColor = (percent: number, base: string): string => (percent >= ALERT_PERCENT ? ALERT : base)
26
27/** The color of the context ring: yellow from 50%, red from 80%, otherwise `base`. */
28export const contextColor = (percent: number, base: string): string =>
29 percent >= CONTEXT_ALERT_PERCENT ? ALERT : percent >= CONTEXT_WARN_PERCENT ? WARN : base
30
31export const COLORS = {
32 session: TERRACOTTA,
33 context: TERRACOTTA,
34 week: TERRACOTTA,
35 todos: TERRACOTTA,
36 cache: TERRACOTTA,
37} as const
38
39/** The label dimmed in front of each entry: the full word, the two letters when the band is narrow or `compact` is on. */
40export const NAME = { week: 'Week', session: 'Session', context: 'Context', todos: 'Todos', cache: 'Cache' } as const
41export const SHORT = { week: 'Wk', session: 'Se', context: 'Cx', todos: 'Td', cache: 'Ca' } as const
42
43export type SegmentId = keyof typeof COLORS
44
45export type Segment = {
46 id: SegmentId
47 name: string
48 short: string
49 /** Whether a ring is drawn in front of `text` (week, session, context); todos and the cache are text only. */
50 hasRing: boolean
51 /** How full the ring is drawn, 0..100. */
52 percent: number
53 text: string
54 /** The color of `text` when it differs from `color` (a cold cache: red word). */
55 textColor?: string
56 /** The value is 0: it is drawn in the ZERO color (never a warning or alert color, which start well above 0). */
57 isDim?: boolean
58 /** The time part of `text` (`4:54`); it keeps the base color when the ring turns red. */
59 time?: string
60 color: string
61}
62
63type RateLimit = { kind: string; percentUsed: number; resetsAt?: string }
64
65/** Folds the engine's rate-limit windows into the band's usage. */
66export function usageFrom(
67 rateLimits: readonly RateLimit[],
68 contextPercent: number | undefined,
69 previous: Usage,
70): Usage {
71 const session = rateLimits.find(w => w.kind === 'five_hour')
72 const week = rateLimits.find(w => w.kind === 'seven_day')
73 return {
74 sessionUsed: session?.percentUsed ?? previous.sessionUsed,
75 sessionResetsAt: session ? session.resetsAt : previous.sessionResetsAt,
76 weekUsed: week?.percentUsed ?? previous.weekUsed,
77 contextUsed: contextPercent,
78 }
79}
80
81/** A span as the band shows it: `4:50` (hours:minutes) from an hour up, `33m` below. */
82export function duration(ms: number): string {
83 const minutes = Math.max(0, Math.floor(ms / 60_000))
84 if (minutes < 60) return `${minutes}m`
85 return `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, '0')}`
86}
87
88/** Time left until `resetsAt` (`4:50`, `33m`); undefined when unknown or past. */
89export function remaining(resetsAt: string | undefined, now: number): string | undefined {
90 if (!resetsAt) return undefined
91 const ms = Date.parse(resetsAt) - now
92 if (!Number.isFinite(ms) || ms <= 0) return undefined
93 return duration(ms)
94}
95
96/** A displayed percentage: rounded and held to 0..100; undefined for a missing or non-finite figure. */
97function clamp(n: number | undefined): number | undefined {
98 return n !== undefined && Number.isFinite(n) ? Math.min(100, Math.max(0, Math.round(n))) : undefined
99}
100
101/** The session window's length, shown once a window has run out and the next has not begun. */
102export const FRESH_WINDOW = '5:00'
103
104/** Whether the session window ending at `resetsAt` is over. */
105export function hasReset(resetsAt: string | undefined, now: number): boolean {
106 if (!resetsAt) return false
107 const at = Date.parse(resetsAt)
108 return Number.isFinite(at) && at <= now
109}
110
111export function todoCounts(todos: Todos): { done: number; total: number } {
112 const statuses = Object.values(todos)
113 return {
114 done: statuses.filter(s => s === 'completed').length,
115 total: statuses.length,
116 }
117}
118
119/** The entries in band order (week, session, then context, todos); one without a finite figure is left out, a percentage is held to 0..100. The cache entry comes from cache.ts. */
120export function segments(usage: Usage, todos: Todos, now: number): Segment[] {
121 const out: Segment[] = []
122
123 const weekUsed = clamp(usage.weekUsed)
124 if (weekUsed !== undefined) {
125 out.push({ id: 'week', name: NAME.week, short: SHORT.week, hasRing: true, isDim: weekUsed === 0, percent: weekUsed, text: `${weekUsed}%`, color: ringColor(weekUsed, COLORS.week) })
126 }
127 const sessionUsed = clamp(usage.sessionUsed)
128 if (sessionUsed !== undefined) {
129 // A window that ran out is empty and whole again until the next reading
130 // brings the new one: 0% and its full five hours.
131 const isOver = hasReset(usage.sessionResetsAt, now)
132 const used = isOver ? 0 : sessionUsed
133 const time = isOver ? FRESH_WINDOW : remaining(usage.sessionResetsAt, now)
134 out.push({
135 id: 'session',
136 name: NAME.session, short: SHORT.session,
137 hasRing: true,
138 isDim: used === 0,
139 percent: used,
140 text: time ? `${used}% ${time}` : `${used}%`,
141 time,
142 color: ringColor(used, COLORS.session),
143 })
144 }
145 const contextUsed = clamp(usage.contextUsed)
146 if (contextUsed !== undefined) {
147 out.push({ id: 'context', name: NAME.context, short: SHORT.context, hasRing: true, isDim: contextUsed === 0, percent: contextUsed, text: `${contextUsed}%`, color: contextColor(contextUsed, COLORS.context) })
148 }
149 const { done, total } = todoCounts(todos)
150 if (total > 0) {
151 out.push({
152 id: 'todos',
153 name: NAME.todos, short: SHORT.todos,
154 hasRing: false,
155 isDim: done === 0,
156 percent: (done / total) * 100,
157 text: `${done}/${total}`,
158 color: COLORS.todos,
159 })
160 }
161 return out
162}
163
164export const RING_COLUMNS = 2
165export const RING_ROWS = 1
166/** Columns between two entries inside a group. */
167export const GAP = 2
168/** Between two groups, spaces included; drawn dimmed. */
169export const SEPARATOR = ' │ '
170/** Columns the frame adds around its content: the border and one column of padding, both sides. */
171export const FRAME = 4
172
173/** Title of each group: the account's limits, this chat's own, then its tokens. */
174export const LABELS = { limits: 'limits', chat: 'chat', tokens: 'tokens' } as const
175
176export type Groups = { limits: Segment[]; chat: Segment[] }
177
178/** The chat group's entries in the order they are drawn. */
179const CHAT_ORDER: SegmentId[] = ['context', 'cache', 'todos']
180
181/** Splits the band into the limits (week, session) and the chat's own (context, cache, todos). */
182export function groups(list: readonly Segment[]): Groups {
183 const isLimit = (s: Segment) => s.id === 'week' || s.id === 'session'
184 const chat = list.filter(s => !isLimit(s))
185 return { limits: list.filter(isLimit), chat: chat.sort((a, b) => CHAT_ORDER.indexOf(a.id) - CHAT_ORDER.indexOf(b.id)) }
186}
187
188/** The pixel Claude beside the frame, in terminal columns. */
189export const SPRITE_COLUMNS = 6
190
191/** Tokens as `812`, `4.6k`, `46k`, `4.6M`. */
192export function compact(n: number): string {
193 if (n < 1000) return String(n)
194 if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`
195 return `${(n / 1_000_000).toFixed(1)}M`
196}
197
198/** Effort levels as the band shows them. */
199export const EFFORT_SHORT: Record<string, string> = {
200 low: 'low',
201 medium: 'mid',
202 high: 'high',
203 xhigh: 'xhigh',
204 max: 'max',
205}
206
207/** `claude-opus-5-5` → `Opus 5.5`, `claude-haiku-4-5-20251001` → `Haiku 4.5`; any other name as given. */
208export function modelName(id: string): string {
209 const bare = id.replace(/\[.*\]$/, '').trim()
210 const parts = bare.replace(/^claude-/, '').split('-').filter(p => !/^\d{8}$/.test(p))
211 const [family, ...version] = parts
212 if (!family || !/^[a-z]+$/.test(family) || !version.every(v => /^\d+$/.test(v))) return bare
213 const title = family[0]!.toUpperCase() + family.slice(1)
214 return version.length > 0 ? `${title} ${version.join('.')}` : title
215}
216
217/** The label beside the pixel Claude: `Opus 5.5 (mid)`, or the name alone while the effort is unknown. */
218export function modelLabel(id: string | undefined, effort: string | number | undefined): string | undefined {
219 if (!id) return undefined
220 const name = modelName(id)
221 if (effort === undefined) return name
222 return `${name} (${typeof effort === 'number' ? effort : (EFFORT_SHORT[effort] ?? effort)})`
223}
224
225/** The tokens group: all tokens of this chat, and what the last minute used. */
226export type Extras = { total: number; rate: number; model?: string }
227
228/** What of the band fits: the entries kept and which of the other parts stay. */
229export type Shown = {
230 segments: Segment[]
231 /** The tokens entry's total; without it the whole entry (and group) goes. */
232 hasTotal: boolean
233 /** The tokens entry's rate, after the total. */
234 hasRate: boolean
235 hasModel: boolean
236 /** The groups' titles `limits`, `chat` and `tokens`. */
237 hasTitles: boolean
238 /** The pixel Claude. */
239 hasSprite: boolean
240 /** Full words (`Week`, `Tokens`) as labels; two letters (`Wk`, `Tk`) without. */
241 hasLongNames: boolean
242}
243
244/** The label shown in front of an entry. */
245export const labelOf = (s: Segment, shown: Shown): string => (shown.hasLongNames ? s.name : s.short)
246
247/** The window the token rate counts: the last minute. */
248export const RATE_WINDOW_MS = 60_000
249
250/** Tokens of the last minute per second, rounded to whole units, with the unit: `800 tok/s`, `6k tok/s`. */
251export function perSecond(n: number): string {
252 const r = Math.round(n / (RATE_WINDOW_MS / 1000))
253 if (r < 1000) return `${r} tok/s`
254 if (r < 999_500) return `${Math.round(r / 1000)}k tok/s`
255 return `${Math.round(r / 1_000_000)}M tok/s`
256}
257
258/** The log with a request of `used` tokens at `at` added and everything older than the window dropped. */
259export function withTokens(log: TokenLog, at: number, used: number): TokenLog {
260 return [...log.filter(([t]) => t > at - RATE_WINDOW_MS), [at, used]]
261}
262
263/** Tokens used in the last minute before `now`; 0 in a pause. */
264export function rateAt(log: TokenLog, now: number): number {
265 return log.reduce((sum, [t, n]) => (t > now - RATE_WINDOW_MS && t <= now ? sum + n : sum), 0)
266}
267
268/** The label of the tokens entry. */
269const TOKENS_NAME = 'Tokens'
270const TOKENS_SHORT = 'Tk'
271
272/** The tokens group's one entry: the label, the chat's total, then the rate; undefined once the total is dropped. */
273export type TokensEntry = {
274 label: string
275 total: string
276 rate?: string
277 /** A 0 total, or a rate that shows as 0, is drawn in the ZERO color. */
278 isTotalZero: boolean
279 isRateZero: boolean
280}
281
282export function tokensEntry(extras: Extras, shown: Shown): TokensEntry | undefined {
283 if (!shown.hasTotal) return undefined
284 return {
285 label: shown.hasLongNames ? TOKENS_NAME : TOKENS_SHORT,
286 total: compact(extras.total),
287 rate: shown.hasRate ? perSecond(extras.rate) : undefined,
288 isTotalZero: extras.total === 0,
289 isRateZero: Math.round(extras.rate / (RATE_WINDOW_MS / 1000)) === 0,
290 }
291}
292
293/** Columns of the tokens entry: label, space, total, then `GAP` and the rate (if shown). */
294const tokensWidth = (t: TokensEntry) => t.label.length + 1 + t.total.length + (t.rate === undefined ? 0 : GAP + t.rate.length)
295
296/** A group: its title, then the items, each `GAP` apart; 0 without items. `widths` are the items' columns. */
297function groupWidth(title: string | undefined, widths: readonly number[]): number {
298 if (widths.length === 0) return 0
299 const titleWidth = title === undefined ? 0 : title.length + 1
300 return titleWidth + widths.reduce((a, b) => a + b, 0) + (widths.length - 1) * GAP
301}
302
303/** Columns of an entry: label, space, then the ring and a space (if it has one), then the value. */
304const entryWidth = (s: Segment, shown: Shown) =>
305 labelOf(s, shown).length + 1 + (s.hasRing ? RING_COLUMNS + 1 : 0) + s.text.length
306
307/** Columns of the whole band: the one frame around the groups, the pixel Claude and the model label. */
308export function widthOf(extras: Extras, shown: Shown): number {
309 const { limits, chat } = groups(shown.segments)
310 const title = (word: string) => (shown.hasTitles ? word : undefined)
311 const entry = tokensEntry(extras, shown)
312 const tokens = entry ? [tokensWidth(entry)] : []
313 const widths = [
314 groupWidth(title(LABELS.limits), limits.map(s => entryWidth(s, shown))),
315 groupWidth(title(LABELS.chat), chat.map(s => entryWidth(s, shown))),
316 groupWidth(title(LABELS.tokens), tokens),
317 ].filter(w => w > 0)
318 const frame = widths.length === 0 ? 0 : FRAME + widths.reduce((a, b) => a + b, 0) + (widths.length - 1) * SEPARATOR.length
319 const sprite = shown.hasSprite ? SPRITE_COLUMNS : 0
320 const model = shown.hasModel && extras.model !== undefined ? MODEL_GAP + extras.model.length : 0
321 return frame + sprite + model
322}
323
324/** Columns between the pixel Claude and the model label. */
325export const MODEL_GAP = 1
326
327/** The options that set how the band starts out before `fit` drops anything. */
328export type Layout = {
329 /** Start with the groups' titles. */
330 titles?: boolean
331 /** Start with the two-letter labels. */
332 compact?: boolean
333 /** Show the tokens group at all. */
334 tokens?: boolean
335}
336
337/** Whether a `userConfig` boolean is on: the CLI may hand it over as `true` or as the string `"true"`. */
338export const isOn = (value: unknown): boolean => value === true || value === 'true'
339
340/**
341 * What of the band fits `columns`, shortening the labels to two letters first
342 * (unless `layout.compact` did), then dropping the least important: the model
343 * label, the groups' titles, the rate, the total (and with it the tokens group),
344 * the cache, todos, the weekly ring, the pixel Claude, the context ring. The
345 * session ring goes last (without a limit reading, whichever entry is left):
346 * null when not even one fits, and the band shows nothing. A step that has
347 * nothing to take away (no titles, no model label, no tokens group) costs no width.
348 */
349export function fit(list: readonly Segment[], extras: Extras, columns: number, layout: Layout = {}): Shown | null {
350 const shown: Shown = {
351 segments: [...list],
352 hasTotal: layout.tokens === true,
353 hasRate: layout.tokens === true,
354 hasModel: true,
355 hasTitles: layout.titles === true,
356 hasSprite: true,
357 hasLongNames: layout.compact !== true,
358 }
359 const without = (id: SegmentId) => () => (shown.segments = shown.segments.filter(s => s.id !== id))
360 const drops: (() => void)[] = [
361 () => (shown.hasLongNames = false),
362 () => (shown.hasModel = false),
363 () => (shown.hasTitles = false),
364 () => (shown.hasRate = false),
365 () => (shown.hasTotal = false),
366 without('cache'),
367 without('todos'),
368 without('week'),
369 () => (shown.hasSprite = false),
370 without('context'),
371 ]
372 // A band without an entry is no band: it is never what fits.
373 const fits = () => shown.segments.length > 0 && widthOf(extras, shown) <= columns
374 for (const drop of drops) {
375 if (fits()) return shown
376 drop()
377 }
378 return fits() ? shown : null
379}
380
381// --- todos -------------------------------------------------------------------
382
383export function withCreated(todos: Todos, id: string): Todos {
384 return { ...todos, [id]: 'pending' }
385}
386
387export function withUpdated(todos: Todos, id: string, status: string | undefined): Todos {
388 if (status === 'deleted') {
389 const { [id]: _gone, ...rest } = todos
390 return rest
391 }
392 if (status === 'pending' || status === 'in_progress' || status === 'completed') {
393 return { ...todos, [id]: status }
394 }
395 return todos
396}
397
398export function fromList(list: readonly { id: string; status: string }[]): Todos {
399 const out: Todos = {}
400 for (const t of list) out[t.id] = t.status as TodoStatus
401 return out
402}
403
404/** TodoWrite replaces the whole list; its entries have no ids, so index them. */
405export function fromTodoWrite(list: readonly { status: string }[]): Todos {
406 const out: Todos = {}
407 list.forEach((t, i) => {
408 out[`todo-${i}`] = t.status as TodoStatus
409 })
410 return out
411}
412
413// --- usage-limits.json -------------------------------------------------------
414
415/**
416 * The figures to seed the rings from a `usage-limits.json` read off the disk.
417 * Only a window with a finite `usedPercent` counts, and one whose reset time
418 * has already passed is stale; anything of another type is ignored.
419 */
420export function fromSnapshot(raw: unknown, now: number): Pick<Usage, 'sessionUsed' | 'sessionResetsAt' | 'weekUsed'> {
421 const object = (v: unknown): Record<string, unknown> | undefined =>
422 typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : undefined
423 const window = (v: unknown): { used: number; resetsAt?: string } | undefined => {
424 const w = object(v)
425 if (!w || typeof w.usedPercent !== 'number' || !Number.isFinite(w.usedPercent)) return undefined
426 if (w.resetsAt === undefined || w.resetsAt === null) return { used: w.usedPercent }
427 if (typeof w.resetsAt !== 'string' || hasReset(w.resetsAt, now) || !Number.isFinite(Date.parse(w.resetsAt))) return undefined
428 return { used: w.usedPercent, resetsAt: w.resetsAt }
429 }
430 const file = object(raw)
431 const session = window(file?.session)
432 const week = window(file?.week)
433 return { sessionUsed: session?.used, sessionResetsAt: session?.resetsAt, weekUsed: week?.used }
434}
435
436type Window = { usedPercent: number; resetsAt: string | null; status: null }
437
438export type Snapshot = {
439 session: Window | null
440 week: Window | null
441 updatedAt: string
442 model: string
443}
444
445/**
446 * The limits as `usage-limits.json` holds them for other tools; null when the
447 * engine has no limit reading, so a good snapshot is never overwritten by an
448 * empty one.
449 */
450export function snapshot(
451 rateLimits: readonly RateLimit[],
452 now: number,
453 model: string,
454): Snapshot | null {
455 const window = (kind: string): Window | null => {
456 const w = rateLimits.find(r => r.kind === kind)
457 return w ? { usedPercent: w.percentUsed, resetsAt: w.resetsAt ?? null, status: null } : null
458 }
459 const session = window('five_hour')
460 const week = window('seven_day')
461 if (!session && !week) return null
462 return { session, week, updatedAt: new Date(now).toISOString(), model }
463}
464hooks/ring.ts 104 lines1// Draws a donut as RGBA pixels: the filled arc starts at 12 o'clock and runs
2// clockwise in a whitened "hot" tone, the rest of the ring is the same color, dimmed.
3
4export const RING_SIZE = 32
5
6const OUTER = 15.5
7const INNER = 10
8const SAMPLES = 4
9const TRACK_ALPHA = 0.22
10/** How far the arc and the ring's text move toward white. */
11const CORE = 0.35
12
13export type Rgb = readonly [number, number, number]
14
15export function hexToRgb(hex: string): Rgb {
16 const n = Number.parseInt(hex.replace('#', ''), 16)
17 return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]
18}
19
20function toWhite(rgb: Rgb, t: number): Rgb {
21 return [0, 1, 2].map(i => Math.round(rgb[i]! + (255 - rgb[i]!) * t)) as unknown as Rgb
22}
23
24/** The hot tone of `hex`, as the arc draws it; the ring's text uses it too. */
25export function hot(hex: string): string {
26 return `#${toWhite(hexToRgb(hex), CORE)
27 .map(c => c.toString(16).padStart(2, '0'))
28 .join('')}`
29}
30
31/** Fraction of the circle (0..1) at which the point lies, clockwise from 12. */
32function turnOf(x: number, y: number): number {
33 const angle = Math.atan2(x, -y)
34 return (angle < 0 ? angle + 2 * Math.PI : angle) / (2 * Math.PI)
35}
36
37/**
38 * The ring for `percent` (clamped to 0..100) as `RING_SIZE * RING_SIZE` RGBA
39 * pixels, edges antialiased by supersampling.
40 */
41export function ringPixels(percent: number, rgb: Rgb): Uint8Array {
42 const fill = Math.min(100, Math.max(0, percent)) / 100
43 const n = RING_SIZE
44 const lit = new Float32Array(n * n)
45 const track = new Float32Array(n * n)
46 const center = n / 2
47 const step = 1 / SAMPLES
48
49 for (let py = 0; py < n; py++) {
50 for (let px = 0; px < n; px++) {
51 let arc = 0
52 let rest = 0
53 for (let sy = 0; sy < SAMPLES; sy++) {
54 for (let sx = 0; sx < SAMPLES; sx++) {
55 const x = px + (sx + 0.5) * step - center
56 const y = py + (sy + 0.5) * step - center
57 const r = Math.hypot(x, y)
58 if (r > OUTER || r < INNER) continue
59 if (turnOf(x, y) < fill) arc++
60 else rest++
61 }
62 }
63 lit[py * n + px] = arc / (SAMPLES * SAMPLES)
64 track[py * n + px] = rest / (SAMPLES * SAMPLES)
65 }
66 }
67
68 const core = toWhite(rgb, CORE)
69 const pixels = new Uint8Array(n * n * 4)
70 for (let i = 0; i < n * n; i++) {
71 const ring = lit[i]! + track[i]! * TRACK_ALPHA
72 const alpha = Math.min(1, ring)
73 // The arc in its hot tone, the track in the plain color.
74 const w = alpha === 0 ? 0 : lit[i]! / alpha
75 for (let c = 0; c < 3; c++) pixels[i * 4 + c] = Math.round(core[c]! * w + rgb[c]! * (1 - w))
76 pixels[i * 4 + 3] = Math.round(alpha * 255)
77 }
78 return pixels
79}
80
81/** The same ring as a glyph, for terminals that cannot draw the picture. */
82export function ringGlyph(percent: number): string {
83 const glyphs = ['○', '◔', '◑', '◕', '●']
84 const p = Math.min(100, Math.max(0, percent))
85 return glyphs[Math.round(p / 25)] ?? '○'
86}
87
88const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
89
90/** Standard padded base64, as `Image` sources take it. */
91export function toBase64(bytes: Uint8Array): string {
92 let out = ''
93 for (let i = 0; i < bytes.length; i += 3) {
94 const a = bytes[i] ?? 0
95 const b = bytes[i + 1] ?? 0
96 const c = bytes[i + 2] ?? 0
97 const n = (a << 16) | (b << 8) | c
98 out += ALPHABET[(n >> 18) & 63]! + ALPHABET[(n >> 12) & 63]!
99 out += i + 1 < bytes.length ? ALPHABET[(n >> 6) & 63]! : '='
100 out += i + 2 < bytes.length ? ALPHABET[n & 63]! : '='
101 }
102 return out
103}
104types/index.d.ts 54 lines1export type Usage = {
2 /** five_hour window, percent used */
3 sessionUsed?: number
4 sessionResetsAt?: string
5 /** seven_day window, percent used */
6 weekUsed?: number
7 /** context window fill, percent */
8 contextUsed?: number
9}
10
11export type TodoStatus = 'pending' | 'in_progress' | 'completed'
12
13/** Task or todo id → its status. */
14export type Todos = Record<string, TodoStatus>
15
16export type Cache = {
17 /** When the last main-thread request was sent: the entry's lifetime starts there. */
18 lastAt?: number
19 /** The model that answered it; another model has a cache of its own. */
20 model?: string
21 /** Lifetime in milliseconds. */
22 ttl: number
23 /** Telling misses in a row that could mean a 5-minute lifetime; absent at 0. */
24 misses?: number
25 /** Dropped by a model switch or a compaction: cold until the next request. */
26 isCold?: boolean
27}
28
29/** When a model request used how many tokens, as `[at, tokens]`; only the last minute is kept. */
30export type TokenLog = [at: number, tokens: number][]
31
32/** The main loop's model and the effort its last request asked for. */
33export type Model = { id?: string; effort?: string | number }
34
35declare module 'claude-code' {
36 interface PluginState {
37 'usage-ring': {
38 usage: Usage
39 todos: Todos
40 /** Animation frame counter. */
41 frame: number
42 /** A turn of this session is running. */
43 isBusy: boolean
44 /** Tokens used since the session started, all four counts of every request, subagents included. */
45 tokens: number
46 /** The requests of the last minute, for the token rate. */
47 recent: TokenLog
48 /** The prompt cache's countdown. */
49 cache: Cache
50 model: Model
51 }
52 }
53}
54