Rate limits, usage credits and spend above the prompt, with a /burn pane for the last 7 days

A Claude Code mod that shows your context, rate limits, usage credits and spend above the prompt.
Opus 5.5 › Explore ◔ 31% ctx 62k/200k ◑ 59% 5h ↻7m ◕ 81% 7d ↻8h57m ● €120.06/120 ≈$3.27 session
› Explore:. The band draws only in the terminal; the Desktop app gets the /burn pane./burn: opens a pane with what fills the context (as /context counts it), each skill with where and when it loaded, the limits, credits, a bar chart of the last 7 days and the totals. Compact (c) compacts the session, Refresh (r) reloads the figures, and /burn refresh does the same from the prompt./compact.Requires Claude Code v2.1.287 or later.
/plugin marketplace add PickleBoxer/claude-plugins
/plugin install burn@pickleboxer
/status reads, through Claude Code's own credential, which the mod never sees. That endpoint is internal, so if it changes the credits group just disappears.terminalIcons picks the terminal's icons: pie (default) draws fill glyphs that work in any font, nerd draws Nerd Font icons for context, the clock, the calendar and your currency. Change it in /config, or in ~/.claude/settings.json:
{
"pluginConfigs": {
"burn@pickleboxer": { "terminalIcons": "nerd" }
}
}
claude --plugin-dir . # loads the mod and reloads it on save
claude plugin validate .claude-plugin/plugin.json
claude plugin test .
MIT
hooks/register.tsx 620 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionMeasureInput, SessionUsage } from 'claude-code'
3
4import type { ContextRow, Credits, Day, Skill, Usage } from '../types'
5import {
6 bar,
7 clockTime,
8 contextLevel,
9 creditsLabel,
10 creditsPercent,
11 daysAgo,
12 glyph,
13 lastSevenDays,
14 level,
15 limitLabel,
16 localDate,
17 modelName,
18 money,
19 parseCredits,
20 resetsIn,
21 skillFromPath,
22 tokens,
23 totals,
24} from './format'
25
26const PANE = 'burn'
27const REFRESH_MS = 10 * 60 * 1000
28const TICK_MS = 60 * 1000
29const KEEP_DAYS = 40
30const LABEL_COLUMNS = 10
31const PRICE_COLUMNS = 10
32const WARN_PERCENT = 85
33const ROW_COLUMNS = 18
34const TOKEN_COLUMNS = 8
35const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
36
37const usageAtom = atom({ plugin: 'burn', key: 'usage' } as const, null)
38const daysAtom = atom({ plugin: 'burn', key: 'days' } as const, [])
39const creditsAtom = atom({ plugin: 'burn', key: 'credits' } as const, null)
40const recordedAtom = atom({ plugin: 'burn', key: 'recordedUsd' } as const, null)
41const nowAtom = atom({ plugin: 'burn', key: 'now' } as const, 0)
42const breakdownAtom = atom({ plugin: 'burn', key: 'breakdown' } as const, null)
43const hasWarnedAtom = atom({ plugin: 'burn', key: 'hasWarned' } as const, false)
44const agentAtom = atom({ plugin: 'burn', key: 'agent' } as const, null)
45const skillsAtom = atom({ plugin: 'burn', key: 'skills' } as const, [])
46
47const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
48
49function toUsage(source: SessionUsage | SessionMeasureInput): Usage {
50 return {
51 limits: source.rateLimits.map(({ kind, percentUsed, resetsAt }) => ({ kind, percentUsed, resetsAt })),
52 sessionUsd: source.cost?.usd ?? null,
53 context: {
54 tokens: source.context.tokens ?? null,
55 window: source.context.window,
56 percent: source.context.percent ?? null,
57 },
58 }
59}
60
61// What each band group measures, drawn as a Nerd Font icon
62type Kind = 'context' | 'five_hour' | 'seven_day' | 'credits'
63
64// Nerd Font md-robot, shown before the model
65const NERD_AGENT = '\u{F06A9}'
66
67// Nerd Font md-flash, shown before the loaded skills
68const NERD_SKILLS = '\u{F0241}'
69
70// Nerd Font glyphs: md-brain, fa-clock, fa-calendar, and the currency signs
71const NERD: Record<Exclude<Kind, 'credits'>, string> = { context: '\u{F09D1}', five_hour: '\uF017', seven_day: '\uF073' }
72const NERD_CURRENCY: Record<string, string> = { EUR: '\uF153', USD: '\uF155', GBP: '\uF154' }
73
74function nerdIcon(kind: Kind | null, currency: string): string | null {
75 if (kind === 'credits') {
76 return NERD_CURRENCY[currency] ?? '\uF0D6'
77 }
78
79 return kind ? NERD[kind] : null
80}
81
82function kindOf(limitKind: string): Kind | null {
83 return limitKind === 'five_hour' || limitKind === 'seven_day' ? limitKind : null
84}
85
86function weekday(date: string): string {
87 const [y, m, d] = date.split('-').map(Number)
88
89 return WEEKDAYS[new Date(y ?? 0, (m ?? 1) - 1, d ?? 1).getDay()] ?? ''
90}
91
92// Moves the clock the countdowns read, which redraws the band and the pane
93async function tick($: EngineInterface): Promise<void> {
94 const now = await $.clock.now()
95 await update($, nowAtom, () => now)
96}
97
98// Daily totals live in $.store as `day:YYYY-MM-DD`, shared by every session on the machine
99async function loadDays($: EngineInterface): Promise<void> {
100 const oldest = daysAgo(await $.clock.now(), KEEP_DAYS)
101 const days: Day[] = []
102
103 for (const key of await $.store.keys()) {
104 if (!key.startsWith('day:')) {
105 continue
106 }
107
108 const date = key.slice(4)
109
110 if (date < oldest) {
111 await $.store.delete(key)
112 } else {
113 days.push({ date, usd: Number((await $.store.get(key)) ?? 0) })
114 }
115 }
116
117 await update($, daysAtom, () => days)
118}
119
120// Adds what the session spent since the last measurement to today's total
121async function record($: EngineInterface, sessionUsd: number | null): Promise<void> {
122 const recorded = await read($, recordedAtom)
123
124 if (sessionUsd === null) {
125 return
126 }
127
128 // First reading, or /clear started the session's cost over
129 if (recorded === null || sessionUsd < recorded) {
130 await update($, recordedAtom, () => sessionUsd)
131
132 return
133 }
134
135 const delta = sessionUsd - recorded
136
137 if (delta <= 0) {
138 return
139 }
140
141 await update($, recordedAtom, () => sessionUsd)
142 const key = `day:${localDate(await $.clock.now())}`
143 await $.store.set(key, Number((await $.store.get(key)) ?? 0) + delta)
144 await loadDays($)
145}
146
147// Usage credits come from the endpoint /status reads. It's internal, so any failure hides them.
148async function loadCredits($: EngineInterface): Promise<void> {
149 let credits: Credits | null = null
150
151 try {
152 const auth = await $.session.authorize()
153
154 if (auth) {
155 const res = await $.http.fetch(USAGE_URL, { auth: auth.handle, headers: { 'anthropic-beta': 'oauth-2025-04-20' } })
156 credits = res.ok ? parseCredits(res.text) : null
157 }
158 } catch {
159 credits = null
160 }
161
162 await update($, creditsAtom, () => credits)
163}
164
165// The /context rows, estimated locally, so it costs no request
166async function loadBreakdown($: EngineInterface): Promise<void> {
167 const { context } = await $.session.usage({ breakdown: 'summary' })
168 const rows: ContextRow[] = []
169
170 for (const category of context.breakdown?.categories ?? []) {
171 if (category.kind !== 'deferred' && category.tokens > 0) {
172 rows.push({ name: category.name, tokens: category.tokens, kind: category.kind })
173 }
174 }
175
176 await update($, breakdownAtom, () => rows)
177}
178
179// Warns once when the context nearly fills up, and again after it has been compacted
180async function warn($: EngineInterface, percent: number | null): Promise<void> {
181 const hasWarned = await read($, hasWarnedAtom)
182
183 if (percent === null) {
184 return
185 }
186
187 if (percent >= WARN_PERCENT && !hasWarned) {
188 await update($, hasWarnedAtom, () => true)
189 $.ui.toast(`Context is ${percent}% full. Run /compact, or press Compact in /burn.`)
190 } else if (percent < 50 && hasWarned) {
191 await update($, hasWarnedAtom, () => false)
192 }
193}
194
195// The main loop's model and the subagents running under it. No event says when one ends,
196// so measurements and spawns re-read the list.
197async function loadAgent($: EngineInterface): Promise<void> {
198 const model = await $.session.model()
199 const subagents = (await $.agent.list())
200 .filter(agent => agent.status === 'running')
201 .map(agent => agent.type)
202
203 await update($, agentAtom, () => ({ model, subagents: [...new Set(subagents)] }))
204}
205
206// The first load of a skill in each loop is the one kept
207async function addSkills($: EngineInterface, added: Skill[]): Promise<void> {
208 await update($, skillsAtom, skills => [
209 ...skills,
210 ...added.filter(
211 (skill, i) =>
212 !skills.some(known => known.name === skill.name && known.agent === skill.agent) &&
213 added.findIndex(other => other.name === skill.name && other.agent === skill.agent) === i,
214 ),
215 ])
216}
217
218// Skills, legacy .claude/commands and plugin skills (namespaced plugin:name) expand into a
219// prompt. Built-ins, MCP prompts and commands a plugin registers in code (/burn) don't.
220async function isSkillCommand($: EngineInterface, name: string): Promise<boolean> {
221 const command = (await $.command.list()).find(command => command.name === name)
222
223 return command?.source === 'user' || (command?.source === 'plugin' && command.name.includes(':'))
224}
225
226async function agentType($: EngineInterface, agentId: string | undefined): Promise<string | null> {
227 if (agentId === undefined) {
228 return null
229 }
230
231 return (await $.agent.list()).find(agent => agent.id === agentId)?.type ?? 'subagent'
232}
233
234// A resumed session starts with no skills, so read the Skill tool calls and SKILL.md reads it made.
235// Skills typed as /name don't show up as tool calls and are missed here.
236async function loadSkills($: EngineInterface): Promise<void> {
237 const messages = await $.session.messages()
238
239 if (!Array.isArray(messages)) {
240 return
241 }
242
243 const skills = messages
244 .flatMap(message => message.toolUses)
245 .flatMap((use): Skill[] => {
246 if (use.tool === 'Skill' && typeof use.input.skill === 'string') {
247 return [{ name: use.input.skill, agent: null, at: null }]
248 }
249
250 const name = use.tool === 'Read' && typeof use.input.file_path === 'string' ? skillFromPath(use.input.file_path) : null
251
252 return name === null ? [] : [{ name, agent: null, at: null }]
253 })
254
255 await addSkills($, skills)
256}
257
258// The main loop's skills, then each subagent's: `commit tdd › Explore: pong`
259function skillsLine(skills: Skill[]): string {
260 const main = skills.filter(skill => skill.agent === null).map(skill => skill.name)
261 const agents = [...new Set(skills.flatMap(skill => (skill.agent === null ? [] : [skill.agent])))].map(
262 agent => `› ${agent}: ${skills.filter(skill => skill.agent === agent).map(skill => skill.name).join(' ')}`,
263 )
264
265 return [main.join(' '), ...agents].filter(Boolean).join(' ')
266}
267
268async function compact($: EngineInterface): Promise<void> {
269 try {
270 const result = await $.session.compact()
271
272 if (result.skip) {
273 $.ui.toast(`Not compacted: ${result.skip}`)
274 }
275 } catch {
276 $.ui.toast("Can't compact while Claude is working")
277 }
278}
279
280async function refresh($: EngineInterface): Promise<void> {
281 await loadDays($)
282 await loadCredits($)
283}
284
285async function summary($: EngineInterface): Promise<string> {
286 const usage = await read($, usageAtom)
287 const credits = await read($, creditsAtom)
288 const now = await $.clock.now()
289 const sum = totals(usage?.sessionUsd ?? null, await read($, daysAtom), now)
290 const limits = (usage?.limits ?? []).map(limit => {
291 const resets = resetsIn(limit.resetsAt, now)
292
293 return `${glyph(limit.percentUsed)} ${limitLabel(limit.kind)} ${limit.percentUsed}%${resets ? ` (resets ${resets})` : ''}`
294 })
295
296 const context = usage?.context.percent != null
297 ? [`${glyph(usage.context.percent)} ctx ${usage.context.percent}% (${tokens(usage.context.tokens ?? 0)}/${tokens(usage.context.window)})`]
298 : []
299
300 return [
301 ...context,
302 ...limits,
303 ...(credits ? [`${glyph(creditsPercent(credits))} ${creditsLabel(credits)} credits`] : []),
304 `session ${money(sum.session)}`,
305 `today ${money(sum.today)}`,
306 `7d ${money(sum.week)}`,
307 `month ${money(sum.month)}`,
308 ].join(' · ')
309}
310
311export const register: Register = (on, options) => {
312 const isNerd = options.terminalIcons === 'nerd'
313
314 on('session.start', async ($, e, next) => {
315 await $.command.register({
316 name: 'burn',
317 description: 'Show rate limits, usage credits and spend for the last 7 days',
318 })
319
320 const usage = toUsage(await $.session.usage())
321 await update($, usageAtom, () => usage)
322 await tick($)
323
324 // A resumed session's earlier cost was recorded by the process that ran it
325 if ((await read($, recordedAtom)) === null) {
326 await update($, recordedAtom, () => usage.sessionUsd ?? 0)
327 }
328
329 await loadDays($)
330 await loadAgent($)
331 await loadSkills($)
332 void loadCredits($)
333 $.clock.every(REFRESH_MS, () => void refresh($))
334 $.clock.every(TICK_MS, () => void tick($))
335
336 return next(e)
337 })
338
339 on('session.measure', async ($, e, next) => {
340 const usage = toUsage(e)
341 await update($, usageAtom, () => usage)
342 await record($, usage.sessionUsd)
343 await warn($, usage.context.percent)
344 await loadAgent($)
345
346 if (e.changed.includes('context')) {
347 await loadBreakdown($)
348 }
349
350 return next(e)
351 })
352
353 on('agent.spawn', async ($, e, next) => {
354 const result = await next(e)
355 await loadAgent($)
356
357 return result
358 })
359
360 // skill.prompt would cover every load, but the built-in security plugin routes it past
361 // the user tier, so typed skills are read from command.run and Claude's from the Skill tool.
362 // A skill loaded by reading its SKILL.md is read from the Read tool; reads through Bash stay
363 // invisible. Preloads into a subagent's frontmatter show in none of these and are missed.
364 on('command.run', async ($, e, next) => {
365 const result = await next(e)
366
367 if (await isSkillCommand($, e.command)) {
368 await addSkills($, [{ name: e.command, agent: null, at: await $.clock.now() }])
369 }
370
371 return result
372 })
373
374 on('tool.call', { tool: 'Skill' }, async ($, e, next) => {
375 const result = await next(e)
376
377 if (!result.deny && !result.isError && typeof e.skill === 'string') {
378 await addSkills($, [{ name: e.skill, agent: await agentType($, e.agentId), at: await $.clock.now() }])
379 }
380
381 return result
382 })
383
384 on('tool.call', { tool: 'Read' }, async ($, e, next) => {
385 const result = await next(e)
386 const name = typeof e.file_path === 'string' ? skillFromPath(e.file_path) : null
387
388 if (!result.deny && !result.isError && name !== null) {
389 await addSkills($, [{ name, agent: await agentType($, e.agentId), at: await $.clock.now() }])
390 }
391
392 return result
393 })
394
395 on('command.run', { command: 'burn' }, async ($, e) => {
396 if (e.args.trim() === 'refresh') {
397 await refresh($)
398
399 return { text: await summary($) }
400 }
401
402 await loadBreakdown($)
403 await $.ui.open({ id: PANE, title: 'burn', closeOnEscape: true })
404
405 // Shown where nothing draws, such as the VS Code panel or claude -p
406 return { text: await summary($) }
407 })
408
409 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
410 const { Box, Button, Text } = $.ui.resolve(e)
411 const usage = await read($, usageAtom)
412 const credits = await read($, creditsAtom)
413 const stored = await read($, daysAtom)
414 const now = (await read($, nowAtom)) || (await $.clock.now())
415 const sum = totals(usage?.sessionUsd ?? null, stored, now)
416 const today = localDate(now)
417 const days = lastSevenDays(stored, now)
418 const max = Math.max(...days.map(day => day.usd), 0)
419 const barWidth = Math.max(8, Math.min(40, e.props.bodyColumns - LABEL_COLUMNS - PRICE_COLUMNS - 2))
420 const since = stored.map(day => day.date).sort()[0]
421 const context = usage?.context
422 const rows = (await read($, breakdownAtom)) ?? []
423 const rowBarWidth = Math.max(8, Math.min(40, e.props.bodyColumns - ROW_COLUMNS - TOKEN_COLUMNS - 2))
424 const skills = await read($, skillsAtom)
425
426 return (
427 <Box flexDirection="column" gap={1}>
428 {context && (
429 <Box flexDirection="column">
430 <Text bold>
431 Context{' '}
432 <Text dimColor>
433 {context.tokens === null ? 'no reading yet' : `${tokens(context.tokens)} / ${tokens(context.window)}`}
434 </Text>
435 {context.percent !== null && <Text color={contextLevel(context.percent)}> {context.percent}%</Text>}
436 </Text>
437 {rows.map(row => (
438 <Box key={row.name} flexDirection="row" gap={1}>
439 <Box width={ROW_COLUMNS} flexShrink={0}>
440 <Text dimColor={row.kind !== 'used'} wrap="truncate">
441 {row.name}
442 </Text>
443 </Box>
444 <Box flexGrow={1} flexShrink={1} overflow="hidden">
445 <Text color={row.kind === 'used' ? 'cyan' : undefined} dimColor={row.kind !== 'used'} wrap="truncate">
446 {bar(row.tokens, context.window, rowBarWidth)}
447 </Text>
448 </Box>
449 <Box width={TOKEN_COLUMNS} flexShrink={0} justifyContent="flex-end">
450 <Text dimColor={row.kind !== 'used'} wrap="truncate">
451 {tokens(row.tokens)}
452 </Text>
453 </Box>
454 </Box>
455 ))}
456 </Box>
457 )}
458
459 {skills.length > 0 && (
460 <Box flexDirection="column">
461 <Text bold>Skills</Text>
462 {skills.map(skill => (
463 <Box key={`skill-${skill.agent ?? 'main'}-${skill.name}`} flexDirection="row" gap={1}>
464 <Box width={ROW_COLUMNS} flexShrink={0}>
465 <Text wrap="truncate">{skill.name}</Text>
466 </Box>
467 <Box width={ROW_COLUMNS} flexShrink={0}>
468 <Text dimColor wrap="truncate">
469 {skill.agent ?? 'main'}
470 </Text>
471 </Box>
472 <Text dimColor>{skill.at === null ? 'resumed' : clockTime(skill.at)}</Text>
473 </Box>
474 ))}
475 </Box>
476 )}
477
478 <Box flexDirection="column">
479 <Text bold>Limits</Text>
480 {(usage?.limits ?? []).length === 0 && <Text dimColor>No reading yet (needs a subscription and one request)</Text>}
481 {(usage?.limits ?? []).map(limit => {
482 const resets = resetsIn(limit.resetsAt, now)
483
484 return (
485 <Text key={limit.kind}>
486 <Text color={level(limit.percentUsed)}>{glyph(limit.percentUsed)}</Text> {limitLabel(limit.kind).padEnd(8)}
487 <Text bold>{String(limit.percentUsed).padStart(5)}%</Text>
488 <Text dimColor>{resets ? ` resets in ${resets}` : ''}</Text>
489 </Text>
490 )
491 })}
492 {credits && (
493 <Text key="credits">
494 <Text color={level(creditsPercent(credits))}>{glyph(creditsPercent(credits))}</Text> {'credits'.padEnd(8)}
495 <Text bold>{String(creditsPercent(credits)).padStart(5)}%</Text>
496 <Text dimColor> {creditsLabel(credits)} this month</Text>
497 </Text>
498 )}
499 </Box>
500
501 <Box flexDirection="column">
502 <Text bold>Last 7 days</Text>
503 {/* Fixed label and price columns, so the bars line up whatever the amounts are */}
504 {days.map(day => (
505 <Box key={day.date} flexDirection="row" gap={1}>
506 <Box width={LABEL_COLUMNS} flexShrink={0}>
507 <Text bold={day.date === today} wrap="truncate">
508 {weekday(day.date)} {day.date.slice(5)}
509 </Text>
510 </Box>
511 <Box key={`day-${day.date}`} flexGrow={1} flexShrink={1} overflow="hidden">
512 <Text color="green" wrap="truncate">
513 {bar(day.usd, max, barWidth)}
514 </Text>
515 </Box>
516 <Box width={PRICE_COLUMNS} flexShrink={0} justifyContent="flex-end">
517 <Text bold={day.date === today} wrap="truncate">
518 {money(day.usd)}
519 </Text>
520 </Box>
521 </Box>
522 ))}
523 </Box>
524
525 <Text>
526 session <Text bold>{money(sum.session)}</Text> · today <Text bold>{money(sum.today)}</Text> · 7d{' '}
527 <Text bold>{money(sum.week)}</Text> · month <Text bold>{money(sum.month)}</Text>
528 </Text>
529
530 <Box flexDirection="row" gap={2}>
531 <Button key="refresh" label="Refresh" hotkey="r" onPress={() => void refresh($)} />
532 <Button key="compact" label="Compact" hotkey="c" onPress={() => void compact($)} />
533 <Text dimColor>
534 ≈ is API-equivalent cost, recorded by burn{since ? ` since ${since}` : ''}. Only credits are billed.
535 </Text>
536 </Box>
537 </Box>
538 )
539 })
540
541 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
542 const usage = await read($, usageAtom)
543 const credits = await read($, creditsAtom)
544 const now = (await read($, nowAtom)) || (await $.clock.now())
545
546 // The band draws only in the terminal
547 if (e.surface === 'desktop' || e.props.hasSurvey || !usage) {
548 return next(e)
549 }
550
551 const agent = await read($, agentAtom)
552 const skills = await read($, skillsAtom)
553 const { Box, Text } = $.ui.resolve(e)
554 const isCompact = e.props.bodyColumns < 100
555 const sum = totals(usage.sessionUsd, await read($, daysAtom), now)
556
557 const icon = (percent: number, kind: Kind | null, color = level(percent)) => (
558 <Text color={color}>{(isNerd ? nerdIcon(kind, credits?.currency ?? 'USD') : null) ?? glyph(percent)}</Text>
559 )
560 const context = usage.context
561 const below = await next(e)
562
563 return (
564 <Box flexDirection="column">
565 <Box flexDirection="row" gap={3} paddingLeft={1}>
566 {agent && (
567 <Box key="agent" flexDirection="row" gap={1}>
568 {isNerd && <Text color="magenta">{NERD_AGENT}</Text>}
569 <Text bold>{modelName(agent.model, isCompact)}</Text>
570 {agent.subagents.length > 0 && <Text dimColor>› {agent.subagents.join(', ')}</Text>}
571 </Box>
572 )}
573 {context.percent !== null && (
574 <Box key="context" flexDirection="row" gap={1}>
575 {icon(context.percent, 'context', contextLevel(context.percent))}
576 <Text bold>{context.percent}%</Text>
577 <Text dimColor>
578 ctx{!isCompact && context.tokens !== null ? ` ${tokens(context.tokens)}/${tokens(context.window)}` : ''}
579 </Text>
580 </Box>
581 )}
582 {usage.limits.map(limit => {
583 const resets = resetsIn(limit.resetsAt, now)
584
585 return (
586 <Box key={limit.kind} flexDirection="row" gap={1}>
587 {icon(limit.percentUsed, kindOf(limit.kind))}
588 <Text bold>{limit.percentUsed}%</Text>
589 <Text dimColor>
590 {limitLabel(limit.kind)}
591 {resets && !isCompact ? ` ↻${resets}` : ''}
592 </Text>
593 </Box>
594 )
595 })}
596 {credits && (
597 <Box key="credits" flexDirection="row" gap={1}>
598 {icon(creditsPercent(credits), 'credits')}
599 <Text bold>{creditsLabel(credits, true)}</Text>
600 </Box>
601 )}
602 <Box key="spend" flexDirection="row" gap={1}>
603 <Text dimColor>{money(sum.session)} session</Text>
604 {!credits && !isCompact && <Text dimColor>{money(sum.today)} today</Text>}
605 </Box>
606 </Box>
607 {skills.length > 0 && (
608 <Box key="skills" flexDirection="row" gap={1} paddingLeft={1}>
609 {isNerd ? <Text color="yellow">{NERD_SKILLS}</Text> : <Text dimColor>skills</Text>}
610 <Text dimColor wrap="truncate">
611 {skillsLine(skills)}
612 </Text>
613 </Box>
614 )}
615 {below}
616 </Box>
617 )
618 })
619}
620hooks/format.ts 160 lines1import type { Credits, Day, Skill } from '../types'
2
3const DAY_MS = 24 * 60 * 60 * 1000
4
5export function localDate(ms: number): string {
6 const d = new Date(ms)
7 const pad = (n: number) => String(n).padStart(2, '0')
8
9 return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
10}
11
12export function daysAgo(now: number, days: number): string {
13 return localDate(now - days * DAY_MS)
14}
15
16// The `extra_usage` block of /api/oauth/usage, or null when it's off or its shape changed
17export function parseCredits(body: string): Credits | null {
18 const extra = (JSON.parse(body) as { extra_usage?: Record<string, unknown> | null }).extra_usage
19
20 if (!extra?.is_enabled || typeof extra.used_credits !== 'number' || typeof extra.monthly_limit !== 'number') {
21 return null
22 }
23
24 return {
25 used: extra.used_credits,
26 limit: extra.monthly_limit,
27 currency: String(extra.currency ?? 'USD'),
28 decimals: Number(extra.decimal_places ?? 2),
29 }
30}
31
32export function lastSevenDays(days: Day[], now: number): Day[] {
33 const byDate = new Map(days.map(day => [day.date, day.usd]))
34
35 return Array.from({ length: 7 }, (_, i) => {
36 const date = daysAgo(now, 6 - i)
37
38 return { date, usd: byDate.get(date) ?? 0 }
39 })
40}
41
42export type Totals = { session: number | null; today: number; week: number; month: number }
43
44export function totals(sessionUsd: number | null, days: Day[], now: number): Totals {
45 const today = localDate(now)
46 const sum = (list: Day[]) => list.reduce((total, day) => total + day.usd, 0)
47
48 return {
49 session: sessionUsd,
50 today: sum(days.filter(day => day.date === today)),
51 week: sum(lastSevenDays(days, now)),
52 month: sum(days.filter(day => day.date.startsWith(today.slice(0, 7)))),
53 }
54}
55
56export function money(usd: number | null): string {
57 return usd === null ? '–' : `≈$${usd.toFixed(2)}`
58}
59
60const SYMBOLS: Record<string, string> = { EUR: '€', USD: '$', GBP: '£' }
61
62// `€120.06 / €120`, or `€120.06/120` where room is short
63export function creditsLabel(credits: Credits, isShort = false): string {
64 const symbol = SYMBOLS[credits.currency] ?? `${credits.currency} `
65 const amount = (minor: number, digits: number) => `${symbol}${(minor / 10 ** credits.decimals).toFixed(digits)}`
66 const isWhole = credits.limit % 10 ** credits.decimals === 0
67 const limit = amount(credits.limit, isWhole ? 0 : credits.decimals)
68
69 return isShort
70 ? `${amount(credits.used, credits.decimals)}/${limit.slice(symbol.length)}`
71 : `${amount(credits.used, credits.decimals)} / ${limit}`
72}
73
74export function creditsPercent(credits: Credits): number {
75 return credits.limit > 0 ? Math.round((credits.used / credits.limit) * 100) : 0
76}
77
78export function resetsIn(resetsAt: string | undefined, now: number): string | null {
79 if (!resetsAt) {
80 return null
81 }
82
83 const minutes = Math.max(0, Math.round((Date.parse(resetsAt) - now) / 60000))
84 const days = Math.floor(minutes / 1440)
85 const hours = Math.floor((minutes % 1440) / 60)
86 const rest = minutes % 60
87
88 if (days > 0) {
89 return `${days}d${hours}h`
90 }
91
92 return hours > 0 ? `${hours}h${rest}m` : `${rest}m`
93}
94
95export function limitLabel(kind: string): string {
96 return { five_hour: '5h', seven_day: '7d', spend_limit: 'spend' }[kind] ?? kind
97}
98
99export function level(percent: number): 'green' | 'yellow' | 'red' {
100 if (percent >= 80) {
101 return 'red'
102 }
103
104 return percent >= 50 ? 'yellow' : 'green'
105}
106
107// Context gets stricter thresholds, as answers get worse well before the window is full
108export function contextLevel(percent: number): 'green' | 'yellow' | 'red' {
109 if (percent >= 80) {
110 return 'red'
111 }
112
113 return percent >= 60 ? 'yellow' : 'green'
114}
115
116export function tokens(count: number): string {
117 if (count >= 1_000_000) {
118 return `${Number((count / 1_000_000).toFixed(1))}M`
119 }
120
121 return count >= 1000 ? `${Math.round(count / 1000)}k` : String(count)
122}
123
124export function glyph(percent: number): string {
125 return ['○', '◔', '◑', '◕', '●'][Math.min(4, Math.round(percent / 25))] ?? '○'
126}
127
128export function bar(usd: number, max: number, width: number): string {
129 const filled = max > 0 ? Math.round((usd / max) * width) : 0
130
131 return '█'.repeat(filled) + '░'.repeat(width - filled)
132}
133
134// `claude-opus-5-5[1m]` reads as `Opus 5.5`, or `Opus` when space is short. Anything else shows as given.
135export function modelName(model: string, isShort = false): string {
136 const match = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?/.exec(model)
137
138 const [, name, major, minor] = match ?? []
139
140 if (!name) {
141 return model
142 }
143
144 const family = name.charAt(0).toUpperCase() + name.slice(1)
145
146 return isShort ? family : `${family} ${major}${minor ? `.${minor}` : ''}`
147}
148
149// `14:05` in local time
150export function clockTime(ms: number): string {
151 const d = new Date(ms)
152
153 return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
154}
155
156// The skill a path loads when Claude reads it: skills/<name>/SKILL.md, on either separator
157export function skillFromPath(path: string): string | null {
158 return path.match(/[\\/]skills[\\/]([^\\/]+)[\\/]SKILL\.md$/)?.[1] ?? null
159}
160types/index.d.ts 40 lines1export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
2
3export type Context = { tokens: number | null; window: number; percent: number | null }
4
5export type Usage = { limits: Limit[]; sessionUsd: number | null; context: Context }
6
7// One row of the /context breakdown
8export type ContextRow = { name: string; tokens: number; kind: 'used' | 'free' | 'buffer' }
9
10// The main loop's model and the types of the subagents running now
11export type Agent = { model: string; subagents: string[] }
12
13// A skill loaded this session. agent is the subagent type that loaded it, null for the main
14// loop. at is null when it came from a resumed transcript.
15export type Skill = { name: string; agent: string | null; at: number | null }
16
17export type Day = { date: string; usd: number }
18
19// Usage credits, in minor units such as cents
20export type Credits = { used: number; limit: number; currency: string; decimals: number }
21
22declare module 'claude-code' {
23 interface PluginState {
24 burn: {
25 usage: Usage | null
26 days: Day[]
27 credits: Credits | null
28 // Session cost already added to the daily totals
29 recordedUsd: number | null
30 now: number
31 breakdown: ContextRow[] | null
32 // Whether this session already warned that the context is nearly full
33 hasWarned: boolean
34 agent: Agent | null
35 // The skills loaded this session, in the order they loaded
36 skills: Skill[]
37 }
38 }
39}
40