See where every Claude token goes, live: plan-limit % used and left, burn rate, tokens and API-equivalent $, by session, subagent, model and machine

See exactly where your Claude usage goes, live, inside Claude Code.
https://github.com/user-attachments/assets/bcb43cc6-a6dd-48e8-b80d-d9de9b03ba7b
Hit a limit sooner than you expected and wondering whether it got nerfed? usage-meter shows your 5-hour and weekly plan limits as they move, what's using them (which session, subagent, prompt and model), how fast you're burning, and how much you have left in real terms. It works out how much of your plan each model's tokens use, from your own data.

In Claude Code (terminal), paste:
/plugin install usage-meter --marketplace rohit3a/usage-meter
Answer y to add the marketplace, press Enter through the scope and settings screens (the defaults are fine), then type /burn.
In the desktop app: click + next to the prompt box → Plugins → Add marketplace, enter rohit3a/usage-meter, then add usage-meter.
That's all. On the first session start the mod sets up its collector, a small Python process that reads your transcripts and does the math, as a background service (systemd on Linux, launchd on macOS), and tells you it did. It reads your existing history right away, so the numbers aren't empty on day one. When the plugin updates, the collector updates with it.
Needs: Claude Code 2.1.280 or later, Python 3.9+ (python3; macOS has it with the Xcode command line tools), macOS or Linux (WSL included). Some older builds (2.1.280 among them) keep mods behind a switch: add "CLAUDE_CODE_ENABLE_FUNCTION_HOOKS": "1" to the env block of ~/.claude/settings.json.
curl -fsSL https://raw.githubusercontent.com/rohit3a/usage-meter/main/install.sh | bash
This clones the repository to ~/.local/share/usage-meter, loads the mod in every Claude Code session (~/.claude/skills/usage-meter), sets the function-hooks switch and starts the collector. Re-running it updates. Use one install method, not both.
/burn | open the usage pane: limits, budget left, sessions, and breakdowns behind the Overview menu |
/burn text | the same summary as plain text |
/burn band | hide or show the band above the prompt |
/burn setup | (re)start the collector, e.g. after /burn uninstall |
/burn uninstall | stop and remove the collector (your data stays in ~/.claude/usage-meter) |
Settings: /plugin configure usage-meter, or in the desktop app's plugin settings:
| Option | Default | |
|---|---|---|
| Start the collector automatically | on | off: nothing runs until you type /burn setup |
| Cache countdown | on | the idle countdown in the band |
| Compact idle sessions | off | see below |
| Idle compaction: minimum context | 150,000 | only sessions at least this big are compacted |
| Prompt cache lifetime (minutes) | 60 | 60 on a subscription; 5 where only the 5-minute cache is used |
Install on each machine, then name each one and point it at the others by SSH host (anything ssh <host> reaches without a password prompt, e.g. a Tailscale name):
python3 ~/.claude/usage-meter/app/collector/umeter.py config --host Desktop --peer Laptop=my-laptop # on the desktop
python3 ~/.claude/usage-meter/app/collector/umeter.py config --host Laptop # on the laptop
Each machine pushes its own ledger and pulls the others' every 20 seconds. The pane's footer shows each machine as live, a time since its last sync, or offline.
Claude Code caches a session's prompt for an hour after its last request. Once that lapses, your next message pays to cache the whole conversation again (2× input price on every token of context). After 10 minutes idle the band shows how long is left:
◷ cache expires in 12m · 352k context · auto-compacts in 7m
With Compact idle sessions on, a session holding at least 150k tokens of context is compacted 5 minutes before its cache expires, while the cache can still serve the read, so the next message caches a short summary instead. It's off by default. It never runs during a turn, while a subagent or Codex run is going, or twice for one idle stretch.
claude -p) runsRuns started with --no-session-persistence (benchmarks, scripts, CI) write no transcript, so the collector can't see them, yet they use your plan's limits. If you keep their --output-format stream-json output, list the folders in ~/.claude/usage-meter/local/collector.json and run /burn setup:
"streamLogs": [
{ "label": "Benchmarks", "cwd": "~/code/bench", "match": "*claude*.jsonl", "dirs": ["~/code/bench/logs"] }
]
Each log becomes a session titled <label> · <file name> under the cwd's project. Requests are counted as they stream (output from the thinking estimates), then topped up to the exact per-model totals of the run's closing result event.
/burn says what's wrong when the collector can't start. From a shell:
python3 ~/.claude/usage-meter/app/collector/umeter.py status # running? up to date?
journalctl --user -u usage-meter -n 50 # Linux: the collector's log
tail -50 ~/.claude/usage-meter/local/collector.log # macOS, or no systemd
python3 is on your PATH (macOS: xcode-select --install or Homebrew), then /burn setup./burn setup restarts it.Uninstall: /burn uninstall, then /plugin uninstall usage-meter. Delete ~/.claude/usage-meter to remove your usage history too.
mod/collector/umeter.py: one per machine, always running (systemd user service on Linux, launchd agent on macOS, a background process elsewhere). Reads Claude Code's transcripts (~/.claude/projects/**.jsonl) incrementally into a compact ledger, one file per UTC day, at ~/.claude/usage-meter/hosts/<host>/days/. Each request is keyed by its API message id, so nothing is counted twice, and carries its model, effort level, skill and MCP server. With peers configured it syncs every 20 s over SSH: it pushes its own hosts/<host>/ and pulls each peer's.mod/collector/view.py: inside the collector, does all the arithmetic in its own process and writes local/view.json (about 100 KB), plus a detail file per recently active session in local/sessions/. A rebuild takes a fraction of a second (about 0.2 s for a week of 40k requests) and runs at most every 10 s, only when the ledger or the limit readings change.mod/: the Claude Code mod. It reads view.json only when it changes (a stat every 2 s while the pane is open), records the plan-limit readings only a live session sees, and draws the status line, the live band above the prompt and the /burn pane. It never crunches the ledger itself, so the UI stays responsive.mod/collector/live.py: follows Codex runs (~/.codex/sessions/**/rollout-*.jsonl) and live Claude sessions (Claude Code's own ~/.claude/sessions/<pid>.json plus each transcript's tail). Each machine writes hosts/<host>/codex.json and fleet.json (synced); the collector merges every machine's into local/live.json. A Codex run Claude started (codex exec in a Bash call, or T3 Code's delegate_task) is linked to that chat and prompt. Stop drops local/stop/<run>.json; the collector sends SIGINT (SIGTERM after 8 s) only to a process that is Codex and holds that run's log open.mod/collector/service.py: setup. The plugin's folder changes with every version, so the collector runs from a copy in ~/.claude/usage-meter/app/. At each session start the mod runs umeter.py install --if-needed, which checks (in about 0.1 s) that a collector on the plugin's current code is running, and copies, restarts or starts it when not.mod/prices.json: list prices for the collector. Cache writes are priced by TTL (5m 1.25×, 1h 2× input); fast mode 2× on Opus 5/5.5; web search $0.01.~/.claude/usage-meter/
app/ the collector's code, copied from the plugin
config.json plan name and price (synced)
local/view.json everything the pane draws (rebuilt by the collector)
local/sessions/<id>.json per-session detail for "This session"
local/live.json Codex runs, Codex limits and live sessions, every machine
local/refresh the pane's Refresh button: rebuild now
hosts/<host>/days/<day>.json requests; written only by <host>'s collector
hosts/<host>/limits.json 5h / 7d limit readings
hosts/<host>/status.json collector heartbeat and sync results
local/collector.json this machine's name, sync peers and stream-log folders
local/state.json transcript read offsets (rebuildable)
local/setup.json which code and service the collector runs on
The desktop app keeps local copies of sessions it runs on another machine over SSH (~/.claude/projects/ssh-* on the client). They're ingested with the session marked remote. A message from a remote copy counts only when no machine recorded it as its own, so remote sessions aren't double counted and a remote host without a collector still shows up.
Two meters, kept separate:
mod/prices.json, with dated changes), so the Sonnet 5.5 cache-read cut shows up here."apiOnly": true; Claude Code plan limits didn't change with the Sonnet cut). The weights are fit by least squares, each pulled toward the overall rate with about one point's worth of evidence, so a family with no data counts like its price and one with data counts like its data.In practice Sonnet 5.5 cache reads have measured at about 0.70× Opus per token, and a week holds about 3.5 full 5h windows. Your own weights are learned from your own readings.
Budget left = (100 − % − 0.5) / Opus weight, shown as Opus-equivalent $. Burn = the last fifth of the window's usage by model × its weight. "Outside Claude Code" is only claimed when there are 3+ consistent stretches and the gap is a whole point.
git clone https://github.com/rohit3a/usage-meter.git && cd usage-meter
deploy/install.sh # loads mod/ from this checkout in every session
(cd mod && claude plugin validate . && claude plugin test .)
python3 mod/collector/umeter.py report --hours 5 # spend per machine and session
Edits to mod/hooks/ reload in open sessions; edits to mod/collector/ reach the running collector at the next session start (or /burn setup). Bump VERSION in umeter.py when the ledger format changes: each machine rebuilds from its transcripts on restart (about 20 s to a minute).
MIT
hooks/register.tsx 1582 lines1import type { EngineInterface, PluginState, Register, SessionRateLimit } from 'claude-code'
2
3import type {
4 CodexRun,
5 CodexWindow,
6 ContextView,
7 FleetEntry,
8 HistoryDay,
9 Idle,
10 Live,
11 Pulse,
12 Scope,
13 ScopeView,
14 Setup,
15 Tab,
16 ThreadRow,
17 Tokens,
18 View,
19 ViewRow,
20 WindowView,
21} from '../types'
22
23// The collector (collector/umeter.py, one per machine) reads Claude Code's
24// transcripts, syncs every machine's ledger and does all the arithmetic in
25// its own process, writing ~/.claude/usage-meter/local/view.json. This mod
26// only reads that file when it changes, records the plan-limit readings a
27// live session sees, and draws. Nothing heavy runs inside Claude Code.
28
29type $T = EngineInterface
30/** ts, window kind, percent used, resetsAt (ms, 0 unknown) */
31type Lim = [number, string, number, number]
32
33const PANE = 'usage-meter'
34const HEARTBEAT = 10 * 60_000
35const ALERTS = [80, 90, 95]
36const LABELS: Record<string, string | undefined> = { five_hour: '5h', seven_day: '7d' }
37const HOST_COLORS = ['#58a6ff', '#bc8cff', '#3fb950', '#d29922', '#8b949e']
38
39// ---------------------------------------------------------------- state
40
41// The host's $.state, or module variables on a build without it: 2.1.280 (the
42// desktop app's build before 3.1623) has none, so there each value lives here
43// and a write redraws through $.ui.invalidate. A $.state call has to name its
44// plugin and key literally, hence one line per value in hostGet and hostSet.
45
46type Values = PluginState['usage-meter']
47type Key = keyof Values
48const INITIAL: Values = {
49 view: null, pulse: null, mine: null, context: null, cc: null, live: null, tab: 'overview', scope: 'window', expanded: [], isAllShown: false, isBandHidden: false, idle: null, setup: null,
50}
51// undefined until the first read finds out
52let hasState: boolean | undefined
53const local: Partial<Values> = {}
54
55// Not async: on a build without $.state, `$.state.get` throws right here, while
56// a refusal by the host comes back as a rejected promise.
57function hostGet($: $T, key: Key): Promise<{ value: unknown; version: number }> {
58 switch (key) {
59 case 'view': return $.state.get({ plugin: 'usage-meter', key: 'view' })
60 case 'pulse': return $.state.get({ plugin: 'usage-meter', key: 'pulse' })
61 case 'mine': return $.state.get({ plugin: 'usage-meter', key: 'mine' })
62 case 'context': return $.state.get({ plugin: 'usage-meter', key: 'context' })
63 case 'cc': return $.state.get({ plugin: 'usage-meter', key: 'cc' })
64 case 'live': return $.state.get({ plugin: 'usage-meter', key: 'live' })
65 case 'tab': return $.state.get({ plugin: 'usage-meter', key: 'tab' })
66 case 'scope': return $.state.get({ plugin: 'usage-meter', key: 'scope' })
67 case 'expanded': return $.state.get({ plugin: 'usage-meter', key: 'expanded' })
68 case 'isAllShown': return $.state.get({ plugin: 'usage-meter', key: 'isAllShown' })
69 case 'isBandHidden': return $.state.get({ plugin: 'usage-meter', key: 'isBandHidden' })
70 case 'idle': return $.state.get({ plugin: 'usage-meter', key: 'idle' })
71 case 'setup': return $.state.get({ plugin: 'usage-meter', key: 'setup' })
72 }
73}
74
75function hostSet($: $T, key: Key, value: unknown, ifVersion: number): Promise<{ isSet: boolean }> {
76 const at = { ifVersion }
77 switch (key) {
78 case 'view': return $.state.set({ plugin: 'usage-meter', key: 'view' }, value as Values['view'], at)
79 case 'pulse': return $.state.set({ plugin: 'usage-meter', key: 'pulse' }, value as Values['pulse'], at)
80 case 'mine': return $.state.set({ plugin: 'usage-meter', key: 'mine' }, value as Values['mine'], at)
81 case 'context': return $.state.set({ plugin: 'usage-meter', key: 'context' }, value as Values['context'], at)
82 case 'cc': return $.state.set({ plugin: 'usage-meter', key: 'cc' }, value as Values['cc'], at)
83 case 'live': return $.state.set({ plugin: 'usage-meter', key: 'live' }, value as Values['live'], at)
84 case 'tab': return $.state.set({ plugin: 'usage-meter', key: 'tab' }, value as Values['tab'], at)
85 case 'scope': return $.state.set({ plugin: 'usage-meter', key: 'scope' }, value as Values['scope'], at)
86 case 'expanded': return $.state.set({ plugin: 'usage-meter', key: 'expanded' }, value as Values['expanded'], at)
87 case 'isAllShown': return $.state.set({ plugin: 'usage-meter', key: 'isAllShown' }, value as Values['isAllShown'], at)
88 case 'isBandHidden': return $.state.set({ plugin: 'usage-meter', key: 'isBandHidden' }, value as Values['isBandHidden'], at)
89 case 'idle': return $.state.set({ plugin: 'usage-meter', key: 'idle' }, value as Values['idle'], at)
90 case 'setup': return $.state.set({ plugin: 'usage-meter', key: 'setup' }, value as Values['setup'], at)
91 }
92}
93
94/** The value under `key`; while a ui.render hook draws, a $.state read subscribes it. */
95async function read<K extends Key>($: $T, key: K): Promise<Values[K]> {
96 if (hasState !== false) {
97 let held: Promise<{ value: unknown }> | undefined
98 try {
99 held = hostGet($, key)
100 } catch {
101 hasState = false
102 }
103 if (held !== undefined) {
104 const { value } = await held
105 hasState = true
106 return (value ?? INITIAL[key]) as Values[K]
107 }
108 }
109 return (local[key] ?? INITIAL[key]) as Values[K]
110}
111
112/** Applies `fn` and writes, as `update` from claude-code does: with `ifVersion`, again on a miss. */
113async function update<K extends Key>($: $T, key: K, fn: (v: Values[K]) => Values[K]): Promise<Values[K]> {
114 if (hasState === undefined) await read($, key)
115 if (!hasState) {
116 const value = fn((local[key] ?? INITIAL[key]) as Values[K])
117 local[key] = value
118 $.ui.invalidate('ui.render')
119 return value
120 }
121 for (;;) {
122 const held = await hostGet($, key)
123 const value = fn((held.value ?? INITIAL[key]) as Values[K])
124 if ((await hostSet($, key, value, held.version)).isSet) return value
125 }
126}
127
128// ---------------------------------------------------------------- files
129
130let root = ''
131let sessionId = ''
132let viewMtime = -1
133let mineMtime = -1
134let mineFor = ''
135
136async function initPaths($: $T): Promise<void> {
137 if (!root) root = `${(await $.env.get('HOME')) ?? '.'}/.claude/usage-meter`
138}
139
140async function mtimeOf($: $T, path: string): Promise<number | null> {
141 try {
142 return (await $.fs.stat(path)).mtimeMs
143 } catch {
144 return null
145 }
146}
147
148/** Reads view.json and this session's detail file, only when they changed. */
149async function loadView($: $T): Promise<void> {
150 await initPaths($)
151 const vm = await mtimeOf($, `${root}/local/view.json`)
152 if (vm !== null && vm !== viewMtime) {
153 try {
154 const view = JSON.parse(String(await $.fs.read(`${root}/local/view.json`))) as View
155 viewMtime = vm
156 pulseRates = view.windows.find(w => w.kind === 'five_hour')?.rates ?? null
157 await update($, 'view', () => view)
158 } catch {
159 // mid-replace: the next tick reads it
160 }
161 }
162 if (!sessionId) return
163 const path = `${root}/local/sessions/${sessionId}.json`
164 const mm = await mtimeOf($, path)
165 if (mm !== null && (mm !== mineMtime || mineFor !== sessionId)) {
166 try {
167 const mine = JSON.parse(String(await $.fs.read(path))) as ScopeView
168 mineMtime = mm
169 mineFor = sessionId
170 await update($, 'mine', () => mine)
171 } catch {
172 // try again next tick
173 }
174 }
175}
176
177/** live.json: Codex runs and live sessions on every machine, rewritten every few seconds. */
178let pulseMtime = -1
179let pulse: Pulse | null = null
180
181async function loadPulse($: $T): Promise<void> {
182 await initPaths($)
183 const m = await mtimeOf($, `${root}/local/live.json`)
184 if (m === null || m === pulseMtime) return
185 try {
186 const next = JSON.parse(String(await $.fs.read(`${root}/local/live.json`))) as Pulse
187 pulseMtime = m
188 pulse = next
189 await update($, 'pulse', () => next)
190 } catch {
191 // mid-replace: the next tick reads it
192 }
193}
194
195/** The 5h window's learned points per plan-reference $, by model family (kept from view.json). */
196let pulseRates: Record<string, number | undefined> | null = null
197
198/** Codex calls this session has in flight (a Bash `codex exec` still running). */
199let codexCalls = 0
200
201function myRunningCodex(): CodexRun | undefined {
202 return pulse?.codex.runs.find(r => r.status === 'running' && r.parent?.sid === sessionId)
203}
204
205/** Asks the collector to re-read everything now, then picks up what it writes. */
206async function refreshNow($: $T): Promise<void> {
207 await initPaths($)
208 await $.fs.write(`${root}/local/refresh`, String(await $.clock.now()))
209 for (const ms of [800, 1800, 3500]) {
210 $.clock.after(ms, () => void Promise.all([loadView($), loadPulse($)]))
211 }
212}
213
214async function stopCodex($: $T, run: CodexRun): Promise<void> {
215 await initPaths($)
216 await $.fs.write(`${root}/local/stop/${run.id}.json`, JSON.stringify({ at: await $.clock.now() }))
217 $.ui.toast(`Asking Codex to stop: ${run.task.slice(0, 60)}`, { timeoutMs: 5000 })
218}
219
220// ---------------------------------------------------------------- plan-limit readings
221
222const samples: Lim[] = []
223const lastLim = new Map<string, Lim>()
224const alerted = new Set<string>()
225let isSamplesDirty = false
226let ccUsd: number | null = null
227
228function windowId(resetsAt: number): number {
229 return Math.round(resetsAt / 600_000)
230}
231
232/** Records a reading when it changes, and every ten minutes while unchanged so
233 * the collector knows the session was watching when a point was crossed. */
234function recordLim($: $T, now: number, w: SessionRateLimit): void {
235 const resets = w.resetsAt ? Date.parse(w.resetsAt) || 0 : 0
236 const prev = lastLim.get(w.kind)
237 const isSame = prev !== undefined && prev[2] === w.percentUsed && windowId(prev[3]) === windowId(resets)
238 if (isSame && now - prev[0] < HEARTBEAT) return
239 const row: Lim = [now, w.kind, w.percentUsed, resets]
240 samples.push(row)
241 if (samples.length > 3000) samples.splice(0, samples.length - 3000)
242 lastLim.set(w.kind, row)
243 isSamplesDirty = true
244 if (isSame) return
245 for (const at of ALERTS) {
246 const key = `${w.kind}:${windowId(resets)}:${at}`
247 if (w.percentUsed < at || alerted.has(key)) continue
248 alerted.add(key)
249 if (prev === undefined) continue
250 const left = resets > now ? `, resets in ${fmtDur(resets - now)}` : ''
251 $.ui.toast(`${LABELS[w.kind] ?? w.kind} limit at ${w.percentUsed}%${left}`, { timeoutMs: 8000 })
252 }
253}
254
255async function saveSamples($: $T): Promise<void> {
256 if (!isSamplesDirty || !sessionId || !root) return
257 isSamplesDirty = false
258 try {
259 await $.fs.write(`${root}/local/limits/${sessionId}.json`, JSON.stringify({ sessionId, samples }))
260 } catch (err) {
261 isSamplesDirty = true
262 $.ui.log(`usage-meter: could not save limit readings: ${String(err)}`, { to: 'debug' })
263 }
264}
265
266async function sample($: $T): Promise<void> {
267 const u = await $.session.usage()
268 const now = await $.clock.now()
269 if (u.cost && u.cost.usd !== ccUsd) {
270 ccUsd = u.cost.usd
271 await update($, 'cc', () => ccUsd)
272 }
273 for (const w of u.rateLimits) recordLim($, now, w)
274 $.ui.status(statusText())
275}
276
277function statusText(): string {
278 const parts: string[] = []
279 for (const kind of ['five_hour', 'seven_day']) {
280 const x = lastLim.get(kind)
281 if (x) parts.push(`${LABELS[kind]} ${x[2]}%`)
282 }
283 if (ccUsd !== null) parts.push(`${fmtUsd(ccUsd)} session`)
284 return parts.length ? parts.join(' · ') : 'usage-meter'
285}
286
287/** Enough of the price list to show a turn's cost before the collector has it. */
288/** planCr: the cache-read price the plan-limit weights are learned against (API-only cuts left out). */
289/** prompt: tokens sent; Haiku 5.5 is priced 5x past 100k, and that gets a plan weight of its own. */
290function rateCard(model: string, prompt = 0): { label: string; fam: string; in: number; out: number; cr: number; planCr: number } {
291 const m = model.toLowerCase()
292 if (m.includes('fable') || m.includes('mythos')) {
293 const cr = m.includes('5-1') ? 0.25 : 1
294 return { label: 'Fable', fam: 'fable', in: 10, out: 50, cr, planCr: cr }
295 }
296 if (m.includes('opus-5-5')) return { label: 'Opus 5.5', fam: 'opus', in: 4, out: 20, cr: 0.2, planCr: 0.2 }
297 if (m.includes('opus')) return { label: 'Opus', fam: 'opus', in: 5, out: 25, cr: 0.5, planCr: 0.5 }
298 if (m.includes('sonnet-4')) return { label: 'Sonnet 4.x', fam: 'sonnet', in: 3, out: 15, cr: 0.3, planCr: 0.3 }
299 if (m.includes('sonnet-5-5')) return { label: 'Sonnet 5.5', fam: 'sonnet', in: 2, out: 10, cr: 0.1, planCr: 0.2 }
300 if (m.includes('sonnet')) return { label: 'Sonnet', fam: 'sonnet', in: 2, out: 10, cr: 0.2, planCr: 0.2 }
301 if (m.includes('haiku-5-5') && prompt > 100_000) return { label: 'Haiku 5.5', fam: 'haiku-long', in: 0.5, out: 2.5, cr: 0.05, planCr: 0.05 }
302 if (m.includes('haiku-5-5')) return { label: 'Haiku 5.5', fam: 'haiku', in: 0.1, out: 0.5, cr: 0.01, planCr: 0.01 }
303 if (m.includes('haiku')) return { label: 'Haiku', fam: 'haiku', in: 1, out: 5, cr: 0.1, planCr: 0.1 }
304 return { label: model || 'model', fam: 'other', in: 4, out: 20, cr: 0.2, planCr: 0.2 }
305}
306
307async function computeContext($: $T): Promise<void> {
308 const u = await $.session.usage({ breakdown: 'summary' })
309 const b = u.context.breakdown
310 if (!b) return
311 const servers = new Map<string, { tokens: number; tools: number }>()
312 for (const t of b.mcpTools) {
313 if (!t.isLoaded) continue
314 const s = servers.get(t.serverName) ?? { tokens: 0, tools: 0 }
315 s.tokens += t.tokens
316 s.tools += 1
317 servers.set(t.serverName, s)
318 }
319 const p = rateCard(await $.session.model())
320 const resend = u.context.tokens ?? null
321 const ctx: ContextView = {
322 model: p.label,
323 total: b.totalTokens,
324 max: b.rawMaxTokens,
325 categories: b.categories
326 .filter(c => c.kind === 'used' && c.tokens > 0)
327 .sort((a, c) => c.tokens - a.tokens)
328 .map(c => ({ name: c.name, tokens: c.tokens })),
329 mcp: [...servers.entries()]
330 .map(([server, s]) => ({ server, ...s }))
331 .sort((a, c) => c.tokens - a.tokens)
332 .slice(0, 8),
333 resend,
334 readUsd: resend === null ? null : (resend * p.cr) / 1e6,
335 writeUsd: resend === null ? null : (resend * p.in * 2) / 1e6,
336 }
337 await update($, 'context', () => ctx)
338}
339
340// ---------------------------------------------------------------- live turn (band)
341
342let live: Live | null = null
343let liveTurn = ''
344let mainTurn = ''
345const agentTurn = new Map<string, string>()
346const agentLabel = new Map<string, string>()
347const liveAgents = new Map<string, { label: string; usd: number; isRunning: boolean }>()
348
349async function pushLive($: $T): Promise<void> {
350 if (!live) return
351 const agents = [...liveAgents.values()].sort((a, b) => b.usd - a.usd).slice(0, 6)
352 const copy: Live = { ...live, tok: [live.tok[0], live.tok[1], live.tok[2], live.tok[3]], agents: agents.map(a => ({ ...a })) }
353 await update($, 'live', () => copy)
354}
355
356// ---------------------------------------------------------------- idle cache
357
358// The main thread's prompt cache lapses an hour (cacheMinutes) after its last
359// request; the next message then writes the whole context to the cache again.
360// After COUNTDOWN_AFTER idle the band counts down to that, and with
361// idleCompact on, a session holding a large context is compacted COMPACT_LEAD
362// before it lapses, while the cache still serves the read: the next message
363// then writes the short summary instead of the whole conversation.
364
365type Opts = { autoStart: boolean; idleCompact: boolean; idleCompactMinTokens: number; cacheMinutes: number; cacheCountdown: boolean }
366const DEFAULTS: Opts = { autoStart: true, idleCompact: false, idleCompactMinTokens: 150_000, cacheMinutes: 60, cacheCountdown: true }
367const MIN = 60_000
368const COUNTDOWN_AFTER = 10 * MIN
369const COMPACT_LEAD = 5 * MIN
370const COMPACT_NOTE =
371 'The session went idle and its prompt cache was about to expire. Keep everything needed to pick the work back up: ' +
372 'the goal, decisions made, what is done, what is next, and the files and commands involved.'
373
374let opts: Opts = DEFAULTS
375let isCompacting = false
376let idleKey = ''
377
378function isTurnRunning(): boolean {
379 return live !== null && live.endedAt === null
380}
381
382function canIdleCompact(idle: Idle): boolean {
383 return opts.idleCompact && !idle.compacted && !idle.isSkipped && idle.ctx >= opts.idleCompactMinTokens
384}
385
386function idleLine(idle: Idle | null, now: number): { text: string; color?: string } | null {
387 if (!idle || isTurnRunning()) return null
388 if (idle.compacted) {
389 const c = idle.compacted
390 return { text: `◷ compacted while idle · ${fmtTok(c.before)} → ${fmtTok(c.after)} context · its cache was about to expire`, color: 'green' }
391 }
392 if (!opts.cacheCountdown || now - idle.at < COUNTDOWN_AFTER) return null
393 const left = idle.at + opts.cacheMinutes * MIN - now
394 if (left <= 0) return { text: `◷ cache expired ${fmtDur(-left)} ago · your next message re-caches ${fmtTok(idle.ctx)} context` }
395 const will = canIdleCompact(idle)
396 const parts = [
397 `◷ cache expires in ${Math.ceil(left / MIN)}m`,
398 `${fmtTok(idle.ctx)} context`,
399 will ? (left > COMPACT_LEAD ? `auto-compacts in ${Math.ceil((left - COMPACT_LEAD) / MIN)}m` : 'compacting…') : '',
400 ].filter(Boolean)
401 return { text: parts.join(' · '), color: left <= 10 * MIN ? 'yellow' : undefined }
402}
403
404async function idleTick($: $T): Promise<void> {
405 const idle = await read($, 'idle')
406 if (!idle) return
407 const now = await $.clock.now()
408 const left = idle.at + opts.cacheMinutes * MIN - now
409 const isBusy = isTurnRunning() || isCompacting || codexCalls > 0 || [...liveAgents.values()].some(a => a.isRunning)
410 if (canIdleCompact(idle) && !isBusy && left > 0 && left <= COMPACT_LEAD) void idleCompact($, idle, now)
411 const key = JSON.stringify(idleLine(idle, now))
412 if (key !== idleKey) {
413 idleKey = key
414 $.ui.invalidate('ui.render')
415 }
416}
417
418async function idleCompact($: $T, idle: Idle, now: number): Promise<void> {
419 isCompacting = true
420 try {
421 const r = await $.session.compact({ instructions: COMPACT_NOTE })
422 if (r.skip !== undefined) {
423 await update($, 'idle', i => (i && i.at === idle.at ? { ...i, isSkipped: true } : i))
424 return
425 }
426 const compacted = { before: r.tokensBefore ?? idle.ctx, after: r.tokensAfter ?? 0, at: now }
427 await update($, 'idle', i => (i && i.at === idle.at ? { ...i, compacted } : i))
428 } catch (err) {
429 // a turn started meanwhile, or the compaction failed: wait for the next request
430 $.ui.log(`usage-meter: idle compaction did not run: ${String(err)}`, { to: 'debug' })
431 await update($, 'idle', i => (i && i.at === idle.at ? { ...i, isSkipped: true } : i))
432 } finally {
433 isCompacting = false
434 $.ui.invalidate('ui.render')
435 }
436}
437
438// ---------------------------------------------------------------- formatting
439
440function fmtTok(n: number): string {
441 if (n < 1000) return String(Math.round(n))
442 if (n < 1e6) return `${(n / 1e3).toFixed(n < 1e4 ? 1 : 0)}k`
443 if (n < 1e9) return `${(n / 1e6).toFixed(n < 1e7 ? 1 : 0)}M`
444 return `${(n / 1e9).toFixed(1)}B`
445}
446
447function fmtUsd(n: number): string {
448 if (n < 100) return `$${n.toFixed(2)}`
449 if (n < 10_000) return `$${Math.round(n).toLocaleString('en-US')}`
450 return `$${(n / 1000).toFixed(1)}k`
451}
452
453/** Estimated shares of a limit: never shown more precisely than the data allows. */
454function fmtShare(n: number | null): string {
455 if (n === null) return ''
456 if (n < 0.1) return '<0.1%'
457 return `≈${n < 10 ? n.toFixed(1) : Math.round(n)}%`
458}
459
460function fmtDur(ms: number): string {
461 const s = Math.max(0, Math.round(ms / 1000))
462 if (s < 60) return `${s}s`
463 const m = Math.floor(s / 60)
464 if (m < 60) return `${m}m`
465 const hours = Math.floor(m / 60)
466 if (hours < 48) return `${hours}h ${String(m % 60).padStart(2, '0')}m`
467 return `${Math.floor(hours / 24)}d ${hours % 24}h`
468}
469
470function sumTok(t: Tokens): number {
471 return t[0] + t[1] + t[2] + t[3]
472}
473
474/** Tokens with what they mostly are: a turn's millions are the context re-read from cache. */
475function tokText(t: Tokens): string {
476 const total = sumTok(t)
477 const cached = total > 0 ? Math.round((t[2] / total) * 100) : 0
478 return `${fmtTok(total)} tok${cached >= 50 ? ` (${cached}% cached)` : ''}`
479}
480
481function clip(text: string, n: number): string {
482 const one = text.replace(/\s+/g, ' ').trim()
483 if (one.length <= n) return one
484 const cut = one.slice(0, Math.max(1, n - 1))
485 const space = cut.lastIndexOf(' ')
486 return `${space > n * 0.6 ? cut.slice(0, space) : cut}…`
487}
488
489function pctColor(pct: number): string {
490 return pct >= 90 ? 'red' : pct >= 70 ? 'yellow' : 'green'
491}
492
493function svgBar(pct: number): string {
494 const fill = pct >= 90 ? '#f85149' : pct >= 70 ? '#d29922' : '#3fb950'
495 const w = Math.max(0, Math.min(500, (pct / 100) * 500))
496 return (
497 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 10" width="2000" height="40" preserveAspectRatio="none">` +
498 `<rect width="500" height="10" rx="5" fill="#8b949e" fill-opacity="0.22"/>` +
499 (w > 0 ? `<rect width="${Math.max(10, w).toFixed(1)}" height="10" rx="5" fill="${fill}"/>` : '') +
500 `</svg>`
501 )
502}
503
504function svgHistory(days: HistoryDay[], hosts: string[]): string {
505 const max = Math.max(1, ...days.map(d => d.total))
506 const width = 700
507 const height = 150
508 const pad = 22
509 const bw = width / Math.max(1, days.length)
510 let out = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height + pad}" width="${width}" height="${height + pad}">`
511 days.forEach((d, i) => {
512 let y = height
513 hosts.forEach((host, j) => {
514 const usd = d.hosts[host] ?? 0
515 if (usd <= 0) return
516 const bar = (usd / max) * (height - 8)
517 y -= bar
518 out += `<rect x="${(i * bw + 4).toFixed(1)}" y="${y.toFixed(1)}" width="${(bw - 8).toFixed(1)}" height="${bar.toFixed(1)}" rx="3" fill="${HOST_COLORS[j % HOST_COLORS.length]}"/>`
519 })
520 if ((days.length - 1 - i) % 2 === 0) {
521 out += `<text x="${(i * bw + bw / 2).toFixed(1)}" y="${height + 16}" font-size="13" text-anchor="middle" fill="#8b949e" font-family="system-ui">${d.label.split(' ')[1] ?? ''}</text>`
522 }
523 })
524 return `${out}</svg>`
525}
526
527function paceLine(w: WindowView, now: number): { text: string; isBad: boolean } {
528 if (w.isReset) return { text: 'reset · waiting for the next reading', isBad: false }
529 const parts = [w.resetsAt ? `${fmtDur(w.resetsAt - now)} left` : '']
530 if (w.usdLeft !== null && w.usdLeft > 0) parts.push(`≈${fmtUsd(w.usdLeft)} to go`)
531 let isBad = false
532 if (w.fullAt !== null && w.resetsAt !== null && w.fullAt < w.resetsAt) {
533 parts.push(`runs out in ~${fmtDur(w.fullAt - now)}`)
534 isBad = true
535 } else if (w.atReset !== null) {
536 parts.push(`~${Math.round(w.atReset)}% at reset`)
537 }
538 return { text: parts.filter(Boolean).join(' · '), isBad }
539}
540
541/** What the "outside Claude Code" check found, in plain words. */
542const OUTSIDE: Record<WindowView['outside'], string> = {
543 unknown: 'Usage outside Claude Code (claude.ai, phone): too early to tell',
544 none: '✓ Claude Code accounts for all of this limit',
545 some: 'The rest came from outside Claude Code: claude.ai, the phone app or Cowork',
546}
547
548const CONFIDENCE: Record<string, string | undefined> = {
549 none: 'no estimate yet',
550 rough: 'rough estimate',
551 low: 'low confidence',
552 medium: 'medium confidence',
553 high: 'high confidence',
554}
555
556function summaryText(v: View | null, now: number): string {
557 if (!v) return 'No usage data yet: the collector writes it within seconds of starting.'
558 const lines = v.windows.map(w => `${w.label} limit ${w.pct}% · ${paceLine(w, now).text}`)
559 lines.push(`5h window ${fmtUsd(v.window.usd)} · last 30 days ${fmtUsd(v.monthUsd)}`)
560 return lines.join('\n')
561}
562
563// ---------------------------------------------------------------- setup
564
565// The collector ships inside the plugin. `install --if-needed` copies it to
566// ~/.claude/usage-meter/app, runs it as a service and restarts it when the
567// plugin's code changed; while a collector on this code runs it only checks
568// (a fraction of a second, off the session's path).
569
570const PYTHONS = ['python3', 'python']
571
572async function runSetup($: $T, args: string[]): Promise<Setup> {
573 const script = `${$.plugin.root}/collector/umeter.py`
574 let missing = ''
575 for (const py of PYTHONS) {
576 try {
577 const r = await $.process.run([py, script, ...args, '--json'], { timeoutMs: 90_000 })
578 const line = r.stdout.trim().split('\n').pop() ?? ''
579 try {
580 return JSON.parse(line) as Setup
581 } catch {
582 return { action: 'failed', message: (r.stderr || r.stdout || `${py} exited ${r.exitCode}`).trim().slice(-400) }
583 }
584 } catch (err) {
585 missing = String(err)
586 }
587 }
588 return { action: 'failed', message: `Needs Python 3.9 or later on PATH (${missing.slice(0, 160)})` }
589}
590
591const SETUP_TOAST: Partial<Record<Setup['action'], string>> = {
592 installed: 'usage-meter is set up: its collector now runs in the background. Type /burn to see your usage.',
593 failed: "usage-meter couldn't start its collector. /burn shows why.",
594}
595
596async function ensureCollector($: $T, args = ['install', '--if-needed']): Promise<Setup> {
597 const result = await runSetup($, args)
598 await update($, 'setup', () => result)
599 const toast = SETUP_TOAST[result.action]
600 if (toast && args.includes('--if-needed')) $.ui.toast(toast)
601 if (result.action === 'installed' || result.action === 'updated' || result.action === 'started') await refreshNow($)
602 return result
603}
604
605const SETUP_TEXT: Record<Setup['action'], string> = {
606 ok: 'The collector is running and up to date.',
607 installed: 'The collector is set up and running in the background.',
608 updated: 'The collector is updated and running.',
609 started: 'The collector is running again.',
610 disabled: 'Auto-start is off. /burn setup turns it back on.',
611 uninstalled: 'The collector is stopped and removed.',
612 failed: "The collector couldn't start.",
613}
614
615function setupText(s: Setup): string {
616 const how = s.service ? ` (${s.service === 'process' ? 'background process' : `${s.service} service`})` : ''
617 return `${SETUP_TEXT[s.action].replace(/\.$/, '')}${how}.${s.message ? ` ${s.message}` : ''}`
618}
619
620// ---------------------------------------------------------------- hooks
621
622export const register: Register = (on, options) => {
623 opts = { ...DEFAULTS, ...(options as Partial<Opts>) }
624
625 on('session.start', async ($, e, next) => {
626 await initPaths($)
627 sessionId = await $.session.id()
628 await $.command.register({
629 name: 'burn',
630 description: 'Usage meter: plan limits, budget left, and where every token went',
631 argumentHint: '[text|band|setup|uninstall]',
632 immediate: true,
633 })
634 // Cheap: a stat or two. Reads view.json only when the collector rewrote it.
635 let tick = 0
636 $.clock.every(2000, () => {
637 tick += 1
638 void (async () => {
639 const isOpen = (await $.ui.panes()).some(p => p.id === PANE)
640 if (isOpen || tick % 15 === 0) await loadView($)
641 const isCodexLive = codexCalls > 0 || myRunningCodex() !== undefined
642 if (isOpen || isCodexLive || tick % 15 === 0) await loadPulse($)
643 if (isCodexLive || isOpen) $.ui.invalidate('ui.render')
644 if (isOpen && tick % 5 === 0 && (await read($, 'tab')) === 'context') await computeContext($)
645 if (tick % 2 === 0) await saveSamples($)
646 await idleTick($)
647 })()
648 })
649 void sample($).then(() => Promise.all([loadView($), loadPulse($)]))
650 if (opts.autoStart) void ensureCollector($)
651
652 return next(e)
653 })
654
655 on('turn.start', async ($, e, next) => {
656 const now = await $.clock.now()
657 mainTurn = e.turnId
658 liveTurn = e.turnId
659 liveAgents.clear()
660 live = { turnId: e.turnId, startedAt: now, endedAt: null, usd: 0, tok: [0, 0, 0, 0], reqs: 0, agents: [] }
661 await pushLive($)
662
663 return next(e)
664 })
665
666 on('agent.spawn', async ($, e, next) => {
667 const r = await next(e)
668 // the subagent has started: bookkeeping that fails here must not fail the spawn
669 try {
670 if (r.agentId) {
671 const turn = (e.parentAgentId ? agentTurn.get(e.parentAgentId) : undefined) ?? mainTurn
672 agentTurn.set(r.agentId, turn)
673 const label = e.description ? `${e.subagentType}: ${e.description}` : e.subagentType || 'subagent'
674 agentLabel.set(r.agentId, label)
675 if (turn === liveTurn && live) {
676 liveAgents.set(r.agentId, { label, usd: 0, isRunning: true })
677 await pushLive($)
678 }
679 }
680 } catch {
681 // the band misses this subagent's live cost; the collector still counts it
682 }
683
684 return r
685 })
686
687 on('turn.step', async function* ($, e, next) {
688 const r = yield* next(e)
689 try {
690 const u = r.usage
691 if (u) {
692 const turn = e.agentId ? (agentTurn.get(e.agentId) ?? mainTurn) : e.turnId
693 if (live && turn === liveTurn) {
694 const p = rateCard(u.model || e.model, u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens)
695 const rest = (u.input_tokens * p.in + u.output_tokens * p.out + u.cache_creation_input_tokens * p.in * 2) / 1e6
696 const usd = rest + (u.cache_read_input_tokens * p.cr) / 1e6
697 const planUsd = rest + (u.cache_read_input_tokens * p.planCr) / 1e6
698 const k5 = pulseRates?.[p.fam] ?? pulseRates?.opus
699 live.usd += usd
700 if (k5 !== undefined) live.pts = (live.pts ?? 0) + planUsd * k5
701 live.tok[0] += u.input_tokens
702 live.tok[1] += u.output_tokens
703 live.tok[2] += u.cache_read_input_tokens
704 live.tok[3] += u.cache_creation_input_tokens
705 live.reqs += 1
706 if (e.agentId) {
707 const cur = liveAgents.get(e.agentId)
708 liveAgents.set(e.agentId, {
709 label: cur?.label ?? agentLabel.get(e.agentId) ?? 'subagent',
710 usd: (cur?.usd ?? 0) + usd,
711 isRunning: cur?.isRunning ?? true,
712 })
713 }
714 await pushLive($)
715 }
716 if (!e.agentId) {
717 const at = await $.clock.now()
718 const ctx = u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
719 await update($, 'idle', () => ({ at, ctx }))
720 }
721 await sample($)
722 }
723 } catch (err) {
724 $.ui.log(`usage-meter: live update failed: ${String(err)}`, { to: 'debug' })
725 }
726
727 return r
728 })
729
730 // A Bash call that runs `codex exec`: the band follows that Codex run live.
731 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
732 if (!/\bcodex\s+exec\b/.test(e.command)) return next(e)
733 codexCalls += 1
734 try {
735 return await next(e)
736 } finally {
737 codexCalls = Math.max(0, codexCalls - 1)
738 void loadPulse($)
739 }
740 })
741
742 on('turn.complete', async ($, e, next) => {
743 const now = await $.clock.now()
744 if (e.agentId) {
745 const cur = liveAgents.get(e.agentId)
746 if (cur) {
747 cur.isRunning = false
748 await pushLive($)
749 }
750 } else if (live && live.turnId === e.turnId) {
751 live.endedAt = now
752 await pushLive($)
753 void saveSamples($)
754 }
755
756 return next(e)
757 })
758
759 // A compaction the person or the engine ran replaces what the cache held.
760 on('session.compact', async ($, e, next) => {
761 const r = await next(e)
762 if (!e.agentId && r.messages && (e.trigger === 'manual' || e.trigger === 'auto')) {
763 await update($, 'idle', () => null).catch(() => undefined)
764 }
765
766 return r
767 })
768
769 on('session.measure', async ($, e, next) => {
770 const now = await $.clock.now()
771 if (e.cost && e.cost.usd !== ccUsd) {
772 ccUsd = e.cost.usd
773 await update($, 'cc', () => ccUsd)
774 }
775 for (const w of e.rateLimits) recordLim($, now, w)
776 $.ui.status(statusText())
777
778 return next(e)
779 })
780
781 on('session.end', async ($, e, next) => {
782 await saveSamples($)
783 if (e.reason === 'clear') {
784 live = null
785 liveTurn = ''
786 liveAgents.clear()
787 sessionId = ''
788 ccUsd = null
789 await update($, 'idle', () => null)
790 }
791
792 return next(e)
793 })
794
795 on('command.run', { command: 'burn' }, async ($, e) => {
796 if (!sessionId) sessionId = await $.session.id()
797 const arg = e.args.trim()
798 if (arg === 'setup' || arg === 'uninstall') {
799 const result = await ensureCollector($, arg === 'setup' ? ['install'] : ['uninstall'])
800 return { text: setupText(result) }
801 }
802 if (arg === 'band') {
803 const isHidden = await read($, 'isBandHidden')
804 await update($, 'isBandHidden', () => !isHidden)
805 return { text: isHidden ? 'Band shown.' : 'Band hidden.' }
806 }
807 await Promise.all([loadView($), loadPulse($)])
808 if (arg === 'text') return { text: summaryText(await read($, 'view'), await $.clock.now()) }
809 const opened = await $.ui.open({ id: PANE, title: 'Usage' })
810 if (!opened.isPlaced) return { text: summaryText(await read($, 'view'), await $.clock.now()) }
811
812 return {}
813 })
814
815 // ---- the band above the prompt: this turn's burn, and Codex when it's running for this chat
816
817 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
818 if (e.props.hasSurvey || (await read($, 'isBandHidden'))) return next(e)
819 const lv = await read($, 'live')
820 const p = await read($, 'pulse')
821 const run = p?.codex.runs.find(r => r.status === 'running' && r.parent?.sid === sessionId)
822 const v = await read($, 'view')
823 const now = await $.clock.now()
824 const il = e.props.isWorking ? null : idleLine(await read($, 'idle'), now)
825 if (!lv && !run && !v && !il) return next(e)
826 const { Box, Text, Button } = $.ui.resolve(e)
827 // 2.1.280, the one build without $.state, hands the band the terminal's whole
828 // width and then draws its own [-] over the last three columns
829 const W = e.props.bodyColumns - (hasState === false ? 4 : 0)
830
831 const idleRow = il ? (
832 <Box flexDirection="row" width={W}>
833 <Text color={il.color} dimColor={!il.color} wrap="truncate-end">
834 {il.text}
835 </Text>
836 </Box>
837 ) : null
838
839 let turnRow: JSX.Element | null = null
840 if (lv) {
841 const isWorking = lv.endedAt === null
842 const r5 = v?.windows.find(w => w.kind === 'five_hour')?.rate ?? null
843 const running = lv.agents.filter(a => a.isRunning).length
844 // each request re-sends the whole conversation: its average size is the context
845 const context = lv.reqs > 0 ? (lv.tok[0] + lv.tok[2] + lv.tok[3]) / lv.reqs : 0
846 const parts = [
847 isWorking ? '● this turn' : 'last turn',
848 fmtUsd(lv.usd),
849 `${lv.reqs} request${lv.reqs === 1 ? '' : 's'}`,
850 tokText(lv.tok),
851 context >= 300_000 ? `context ${fmtTok(context)}` : '',
852 lv.pts !== undefined ? `${fmtShare(lv.pts)} of 5h` : r5 === null ? '' : `${fmtShare(lv.usd * r5)} of 5h`,
853 lv.agents.length ? `${lv.agents.length} subagent${lv.agents.length === 1 ? '' : 's'}${running ? ` (${running} running)` : ''}` : '',
854 ].filter(Boolean)
855 turnRow = (
856 <Box flexDirection="row" width={W}>
857 <Box flexGrow={1} flexShrink={1}>
858 <Text dimColor={!isWorking} wrap="truncate-end">
859 {parts.join(' · ')}
860 </Text>
861 </Box>
862 <Button key="details" label="details" plain dimColor onPress={() => void $.ui.open({ id: PANE, title: 'Usage' })} />
863 <Text> </Text>
864 <Button key="hide" label="hide" plain dimColor onPress={() => void update($, 'isBandHidden', () => true)} />
865 </Box>
866 )
867 }
868
869 let codexRow: JSX.Element | null = null
870 if (run) {
871 const doing = run.current ? `▶ ${run.current}` : run.progress || 'thinking'
872 const line = `◆ Codex · ${doing}`
873 const meta = ` · ${fmtDur(now - (run.started || now))} · ${fmtTok(run.tokens[0] + run.tokens[2])} tok`
874 codexRow = (
875 <Box flexDirection="row" width={W}>
876 <Box flexGrow={1} flexShrink={1}>
877 <Text color="cyan" wrap="truncate-end">
878 {clip(line, Math.max(20, W - meta.length - 16))}
879 <Text dimColor>{meta}</Text>
880 </Text>
881 </Box>
882 <Button
883 key="codex-watch"
884 label="watch"
885 plain
886 dimColor
887 onPress={() => void update($, 'tab', () => 'codex').then(() => $.ui.open({ id: PANE, title: 'Usage' }))}
888 />
889 {run.isSelf && <Text> </Text>}
890 {run.isSelf && <Button key="codex-stop" label="stop" plain dimColor onPress={() => void stopCodex($, run)} />}
891 </Box>
892 )
893 }
894
895 // Before the first turn: a slim meter, so the analysis is always one click away
896 // (the status line is plain text and can't be clicked).
897 let meterRow: JSX.Element | null = null
898 if (!turnRow && v) {
899 const cw = p?.codex.limits?.primary
900 const cc = await read($, 'cc')
901 const parts = [
902 ...v.windows.filter(w => w.kind === 'five_hour' || w.kind === 'seven_day').map(w => `${w.label} ${w.pct}%`),
903 cw ? `Codex ${Math.round(cw.used_percent)}%` : '',
904 cc !== null ? `${fmtUsd(cc)} session` : '',
905 ].filter(Boolean)
906 meterRow = (
907 <Box flexDirection="row" width={W}>
908 <Box flexGrow={1} flexShrink={1}>
909 <Text dimColor wrap="truncate-end">
910 {parts.join(' · ')}
911 </Text>
912 </Box>
913 <Button key="details" label="open usage" plain dimColor onPress={() => void $.ui.open({ id: PANE, title: 'Usage' })} />
914 <Text> </Text>
915 <Button key="hide" label="hide" plain dimColor onPress={() => void update($, 'isBandHidden', () => true)} />
916 </Box>
917 )
918 }
919
920 return (
921 <Box flexDirection="column" width={W}>
922 {codexRow}
923 {idleRow}
924 {turnRow ?? meterRow}
925 </Box>
926 )
927 })
928
929 // ---- the pane
930
931 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
932 const els = $.ui.resolve(e)
933 const { Box, Text, Button } = els
934 // chosen by surface: the terminal draws no Svg and the mobile app no Select
935 const Svg = e.surface !== 'terminal' && 'Svg' in els ? els.Svg : undefined
936 const Select = e.surface !== 'mobile' && 'Select' in els ? els.Select : undefined
937 const v = await read($, 'view')
938 const W = Math.max(28, e.props.bodyColumns)
939
940 const setup = await read($, 'setup')
941 if (!v) {
942 const isFailed = setup?.action === 'failed'
943 const text = isFailed || setup?.action === 'disabled' || setup?.action === 'uninstalled'
944 ? setupText(setup)
945 : 'Waiting for the collector’s first summary: a few seconds, or up to a minute while it reads your past sessions.'
946 return (
947 <Box flexDirection="column" width={W}>
948 <Text bold color={isFailed ? 'red' : undefined}>{isFailed ? 'The collector isn’t running' : 'Starting up'}</Text>
949 <Text dimColor wrap="wrap">{text}</Text>
950 {isFailed && <Text dimColor wrap="wrap">Try /burn setup, or see github.com/rohit3a/usage-meter#troubleshooting</Text>}
951 </Box>
952 )
953 }
954 const tab = await read($, 'tab')
955 const scope = await read($, 'scope')
956 const now = await $.clock.now()
957
958 // ---- building blocks. Proportional fonts on the desktop: alignment comes
959 // from flex boxes, never from spaces.
960 const Line = (p: { left: string; right?: string; bold?: boolean; dim?: boolean; color?: string; indent?: number; rightDim?: boolean }) => (
961 <Box flexDirection="row" width={W - (p.indent ?? 0)} marginLeft={p.indent ?? 0}>
962 <Box flexGrow={1} flexShrink={1}>
963 <Text bold={p.bold} dimColor={p.dim} wrap="truncate-end">
964 {p.left}
965 </Text>
966 </Box>
967 {p.right !== undefined && (
968 <Box flexShrink={0} marginLeft={1}>
969 <Text bold={p.bold} dimColor={p.rightDim ?? p.dim} color={p.color}>
970 {p.right}
971 </Text>
972 </Box>
973 )}
974 </Box>
975 )
976 const Note = (p: { text: string; color?: string; indent?: number; wrap?: boolean }) => (
977 <Box width={W - (p.indent ?? 0)} marginLeft={p.indent ?? 0}>
978 <Text dimColor={!p.color} color={p.color} wrap={p.wrap ? 'wrap' : 'truncate-end'}>
979 {p.text}
980 </Text>
981 </Box>
982 )
983 const Section = (p: { title: string; right?: string }) => (
984 <Box flexDirection="column" marginTop={1}>
985 <Line left={p.title.toUpperCase()} right={p.right} bold dim rightDim={false} />
986 </Box>
987 )
988 const Bar = (p: { pct: number }) =>
989 Svg ? (
990 <Box width={W}>
991 <Svg source={svgBar(p.pct)} alt={`${p.pct}% used`} />
992 </Box>
993 ) : (
994 <Text color={pctColor(p.pct)}>
995 {'━'.repeat(Math.max(0, Math.min(W, Math.round((p.pct / 100) * W)))) +
996 '─'.repeat(Math.max(0, W - Math.round((p.pct / 100) * W)))}
997 </Text>
998 )
999 const share = (row: ViewRow) => fmtShare(scope === 'week' ? row.p7 : row.p5)
1000 const meta = (row: ViewRow) =>
1001 [share(row), tokText(row.tok), row.ms > 0 ? fmtDur(row.ms) : '', row.sub].filter(Boolean).join(' · ')
1002 const Row = (p: { row: ViewRow }) => (
1003 <Box flexDirection="column">
1004 <Line left={p.row.label} right={fmtUsd(p.row.usd)} />
1005 <Note text={meta(p.row)} />
1006 </Box>
1007 )
1008 const Compact = (p: { row: ViewRow; total: number }) => (
1009 <Line left={p.row.label} right={`${fmtUsd(p.row.usd)} · ${p.total > 0 ? Math.round((p.row.usd / p.total) * 100) : 0}%`} rightDim={false} />
1010 )
1011
1012 const Para = (p: { text: string; indent?: number }) => (
1013 <Box width={W - (p.indent ?? 0)} marginLeft={p.indent ?? 0}>
1014 <Text wrap="wrap">{p.text}</Text>
1015 </Box>
1016 )
1017 const stepIcon = (k: string, ok: boolean | null) =>
1018 k === 'cmd' ? (ok === false ? '✕' : '$') : k === 'edit' ? '✎' : k === 'mcp' ? '⚙' : k === 'agent' ? '↳' : '·'
1019 const statusIcon: Record<CodexRun['status'], string> = { running: '●', done: '✓', aborted: '✕', stopped: '⏹', stale: '⚠', idle: '○' }
1020 const statusWord: Record<CodexRun['status'], string> = {
1021 running: 'running', done: 'finished', aborted: 'interrupted', stopped: 'stopped by you', stale: 'stopped responding', idle: 'idle',
1022 }
1023 const originOf = (r: CodexRun) =>
1024 r.origin === 'exec' ? (r.parent ? 'started by Claude' : 'codex exec') : r.origin === 'app' ? 'Codex app' : r.origin || 'Codex'
1025
1026 // ---- header: the limits, always on top
1027 const limits = v.windows.map(w => {
1028 const pace = paceLine(w, now)
1029 return (
1030 <Box flexDirection="column" marginBottom={1}>
1031 <Line left={`${w.label} limit`} right={`${w.pct}%`} bold color={pctColor(w.pct)} />
1032 <Bar pct={w.pct} />
1033 <Note text={pace.text} color={pace.isBad ? 'red' : undefined} />
1034 </Box>
1035 )
1036 })
1037
1038 // ---- navigation: one row of dropdowns where the surface has them
1039 const tabs: [Tab, string][] = [
1040 ['overview', 'Overview'],
1041 ['sessions', 'Sessions'],
1042 ['codex', 'Codex'],
1043 ['threads', 'Threads'],
1044 ['tasks', 'Tasks'],
1045 ['breakdown', 'Breakdown'],
1046 ['history', 'History'],
1047 ['accuracy', 'Accuracy'],
1048 ['context', 'Context'],
1049 ]
1050 const scopes: [Scope, string][] = [
1051 ['window', '5h window'],
1052 ['week', '7 days'],
1053 ['session', 'This session'],
1054 ]
1055 const usesScope = tab === 'threads' || tab === 'tasks' || tab === 'breakdown'
1056 // a long list shown in full folds back when the view or the scope changes
1057 const pickTab = (t: string) => {
1058 void update($, 'isAllShown', () => false)
1059 void update($, 'tab', () => t as Tab).then(() => (t === 'context' ? computeContext($) : loadView($)))
1060 }
1061 const pickScope = (x: string) => {
1062 void update($, 'isAllShown', () => false)
1063 void update($, 'scope', () => x as Scope)
1064 }
1065 const age = Math.max(0, now - Math.max(v.builtAt, (await read($, 'pulse'))?.at ?? 0))
1066 const refresh = (
1067 <Box flexDirection="row" flexShrink={0} marginLeft={1}>
1068 <Text dimColor>{age < 10_000 ? 'now ' : `${fmtDur(age)} ago `}</Text>
1069 <Button key="refresh" label="↻ Refresh" plain onPress={() => void refreshNow($)} />
1070 </Box>
1071 )
1072 const nav = Select ? (
1073 <Box flexDirection="row" width={W} flexWrap="wrap">
1074 <Box marginRight={2}>
1075 <Select key="tab" options={tabs.map(([value, label]) => ({ value, label }))} value={tab} onSelect={pickTab} />
1076 </Box>
1077 {usesScope && <Select key="scope" options={scopes.map(([value, label]) => ({ value, label }))} value={scope} onSelect={pickScope} />}
1078 <Box flexGrow={1} />
1079 {refresh}
1080 </Box>
1081 ) : (
1082 <Box flexDirection="column" width={W}>
1083 <Box flexDirection="row" flexWrap="wrap">
1084 {tabs.map(([t, label]) => (
1085 <Button key={`tab-${t}`} label={label} plain variant={t === tab ? 'primary' : undefined} dimColor={t !== tab} onPress={() => pickTab(t)} />
1086 ))}
1087 </Box>
1088 {refresh}
1089 {usesScope && (
1090 <Box flexDirection="row" flexWrap="wrap">
1091 {scopes.map(([x, label]) => (
1092 <Button key={`scope-${x}`} label={label} plain variant={x === scope ? 'primary' : undefined} dimColor={x !== scope} onPress={() => pickScope(x)} />
1093 ))}
1094 </Box>
1095 )}
1096 </Box>
1097 )
1098
1099 // ---- Codex's own plan limit, and the live sessions at a glance
1100 const pl = await read($, 'pulse')
1101 const cl = pl?.codex.limits
1102 const cwLabel = (cw: CodexWindow) =>
1103 cw.window_minutes >= 10_000 ? 'week' : cw.window_minutes === 300 ? '5h' : `${Math.round(cw.window_minutes / 60)}h`
1104 const credits = cl?.credits?.balance ? Math.round(Number(cl.credits.balance)) : null
1105 const codexHeader = [cl?.primary, cl?.secondary]
1106 .filter((cw): cw is CodexWindow => !!cw)
1107 .map(cw => (
1108 <Box flexDirection="column" marginBottom={1}>
1109 <Line left={`Codex ${cwLabel(cw)}`} right={`${Math.round(cw.used_percent)}%`} bold color={pctColor(cw.used_percent)} />
1110 <Bar pct={cw.used_percent} />
1111 <Note
1112 text={[
1113 `${fmtDur(cw.resets_at * 1000 - now)} left`,
1114 cl?.plan_type ? `${cl.plan_type[0]?.toUpperCase() ?? ''}${cl.plan_type.slice(1)} plan` : '',
1115 credits !== null ? `${credits.toLocaleString('en-US')} credits` : '',
1116 ]
1117 .filter(Boolean)
1118 .join(' · ')}
1119 />
1120 </Box>
1121 ))
1122 const fleet: FleetEntry[] = pl?.fleet ?? []
1123 const count = (state: FleetEntry['state']) => fleet.filter(f => f.state === state).length
1124 const codexRunning = (pl?.codex.runs ?? []).filter(r => r.status === 'running')
1125 const summary = [
1126 count('needs-you') ? `${count('needs-you')} need you` : '',
1127 count('working') ? `${count('working')} working` : '',
1128 count('your-turn') ? `${count('your-turn')} your turn` : '',
1129 codexRunning.length ? `${codexRunning.length} Codex` : '',
1130 ].filter(Boolean)
1131 const fleetSummary =
1132 summary.length > 0 ? (
1133 <Box marginBottom={1}>
1134 <Button
1135 key="fleet-summary"
1136 label={`Sessions: ${summary.join(' · ')}`}
1137 plain
1138 variant={count('needs-you') ? 'primary' : undefined}
1139 onPress={() => pickTab('sessions')}
1140 />
1141 </Box>
1142 ) : null
1143
1144 const mine = await read($, 'mine')
1145 const scoped: ScopeView | null = scope === 'session' ? mine : scope === 'week' ? v.week : v.window
1146 const cc = await read($, 'cc')
1147 const mineUsd = mine?.usd ?? v.sessionUsd[sessionId] ?? null
1148 const ccCheck =
1149 cc === null || mineUsd === null
1150 ? null
1151 : Math.abs(cc - mineUsd) <= Math.max(0.05, cc * 0.03)
1152 ? '✓ matches Claude Code’s own total'
1153 : cc > mineUsd
1154 ? `Claude Code says ${fmtUsd(cc)} (collector catching up)`
1155 : `Claude Code says ${fmtUsd(cc)}`
1156 const w5 = v.windows.find(w => w.kind === 'five_hour')
1157 const scopeTitle = scope === 'session' ? 'this session' : scope === 'week' ? 'last 7 days' : '5h window'
1158
1159 let body: JSX.Element
1160 if (tab === 'overview') {
1161 const machines = v.window.dims.machines ?? []
1162 const plan = v.config.plan
1163 const value = plan?.usdPerMonth
1164 ? `${plan.name ?? 'Plan'} · ${(v.monthUsd / plan.usdPerMonth).toFixed(1)}× its ${fmtUsd(plan.usdPerMonth)}/mo price`
1165 : (plan?.name ?? '')
1166 body = (
1167 <Box flexDirection="column">
1168 <Section title="Where the 5h window went" right={fmtUsd(v.window.usd)} />
1169 {machines.length === 0 && <Note text="Nothing in this window yet." />}
1170 {machines.map(row => (
1171 <Line left={row.label} right={`${fmtUsd(row.usd)}${row.p5 !== null ? ` · ${fmtShare(row.p5)}` : ''}`} rightDim={false} />
1172 ))}
1173 {w5?.outside === 'some' && w5.untrackedPct !== null && (
1174 <Line left="Outside Claude Code" right={fmtShare(w5.untrackedPct)} rightDim={false} />
1175 )}
1176 {w5 && <Note text={OUTSIDE[w5.outside]} wrap />}
1177 {w5?.rate ? <Note text={`1% of 5h ≈ ${fmtUsd(1 / w5.rate)} of Opus usage · ${CONFIDENCE[w5.confidence] ?? ''}`} /> : null}
1178
1179 <Section title="This session" right={mineUsd !== null ? fmtUsd(mineUsd) : undefined} />
1180 {mine ? <Note text={`${mine.reqs} requests · ${tokText(mine.tok)}`} /> : <Note text="Appears after its first response." />}
1181 {ccCheck && <Note text={ccCheck} />}
1182
1183 <Section title="Top tasks · 5h" />
1184 {v.window.tasks.length === 0 && <Note text="none yet" />}
1185 {v.window.tasks.slice(0, 4).map(row => (
1186 <Row row={row} />
1187 ))}
1188
1189 <Section title="Last 30 days" right={fmtUsd(v.monthUsd)} />
1190 {value && <Note text={value} />}
1191 <Note text="value at API list prices" />
1192 </Box>
1193 )
1194 } else if (tab === 'sessions') {
1195 const groups: [FleetEntry['state'], string][] = [
1196 ['needs-you', 'Needs you'],
1197 ['working', 'Working'],
1198 ['your-turn', 'Your turn'],
1199 ]
1200 body = (types/index.d.ts 242 lines1/** Token counts: uncached input, output, cache read, cache write. */
2export type Tokens = [number, number, number, number]
3
4/** One line of a breakdown, as the collector's view.json writes it. */
5export type ViewRow = {
6 label: string
7 sub: string
8 usd: number
9 tok: Tokens
10 reqs: number
11 ms: number
12 /** Share of the 5-hour / 7-day limit, from the %-per-$ rate. */
13 p5: number | null
14 p7: number | null
15 depth?: number
16}
17
18export type ThreadRow = ViewRow & {
19 id: string
20 agents: number
21 kids: ViewRow[]
22 tasks: ViewRow[]
23}
24
25export type ScopeView = {
26 usd: number
27 tok: Tokens
28 reqs: number
29 sessions: number
30 threads: ThreadRow[]
31 tasks: ViewRow[]
32 dims: Record<string, ViewRow[] | undefined>
33 cache: { read: number; write: number; fresh: number; out: number; rebuilds: number; rebuildUsd: number }
34}
35
36export type Stretch = {
37 from: number
38 to: number
39 pctFrom: number
40 pctTo: number
41 usd: number
42 usdPerPoint: number
43 opusShare: number
44 /** the model family that made up most of the stretch */
45 mostly?: string
46}
47
48/** How much of a limit a plan-reference dollar of each model family uses, learned from crossings. */
49export type ModelWeight = { family: string; label: string; weight: number; points: number }
50
51export type WindowView = {
52 kind: string
53 label: string
54 pct: number
55 resetsAt: number | null
56 isReset: boolean
57 rate: number | null
58 /** points per plan-reference $ by model family (opus, sonnet, haiku, haiku-long, fable, other); Haiku 5.5 prompts over 100k are haiku-long */
59 rates?: Record<string, number | undefined> | null
60 models?: ModelWeight[]
61 rateFrom: 'learned' | 'estimate' | 'none'
62 confidence: 'none' | 'rough' | 'low' | 'medium' | 'high'
63 stretches: Stretch[]
64 spread: number | null
65 readings: number
66 usdInWindow: number | null
67 untrackedPct: number | null
68 /** Whether anything outside Claude Code used this limit: not measurable yet, none, or some. */
69 outside: 'unknown' | 'none' | 'some'
70 burnPerHour: number | null
71 atReset: number | null
72 fullAt: number | null
73 usdLeft: number | null
74 typicalSessions: number | null
75}
76
77export type HistoryDay = {
78 date: string
79 label: string
80 hosts: Record<string, number | undefined>
81 total: number
82 top: [string, number][]
83}
84
85export type HostInfo = {
86 host: string
87 isSelf: boolean
88 updatedAt: number
89 syncError: string | null
90 subscription: string
91}
92
93/** What the collector writes to ~/.claude/usage-meter/local/view.json. */
94export type View = {
95 v: number
96 builtAt: number
97 host: string
98 windows: WindowView[]
99 window: ScopeView
100 week: ScopeView
101 history: HistoryDay[]
102 monthUsd: number
103 typicalSessionUsd: number
104 biggestSessionUsd: number
105 sessionUsd: Record<string, number | undefined>
106 accuracy: { requestsByHost: Record<string, number | undefined> }
107 hosts: HostInfo[]
108 config: { plan?: { name?: string; usdPerMonth?: number } }
109}
110
111export type CodexStep = { k: 'cmd' | 'edit' | 'mcp' | 'agent' | 'note'; t: string; ts: number; ok: boolean | null }
112
113/** One Codex run, as the collector reads it from ~/.codex/sessions. */
114export type CodexRun = {
115 id: string
116 host: string
117 started: number
118 updated: number
119 ended: number
120 status: 'running' | 'done' | 'aborted' | 'stopped' | 'stale' | 'idle'
121 origin: string
122 cwd: string
123 project: string
124 model: string
125 tier: string
126 task: string
127 progress: string
128 current: string | null
129 currentSince: number
130 steps: CodexStep[]
131 counts: { cmds: number; edits: number; mcp: number; agents: number }
132 tokens: [number, number, number, number]
133 final: string
134 reason: string
135 parent: { sid: string; prompt: string; host: string } | null
136 pid?: number | null
137 stopAsked?: number
138 isSelf: boolean
139}
140
141export type CodexWindow = { used_percent: number; window_minutes: number; resets_at: number }
142export type CodexLimits = {
143 at: number
144 plan_type?: string | null
145 primary?: CodexWindow | null
146 secondary?: CodexWindow | null
147 credits?: { has_credits: boolean; unlimited: boolean; balance: string | null } | null
148}
149
150/** One live Claude session, from Claude Code's own status file and its transcript. */
151export type FleetEntry = {
152 sid: string
153 host: string
154 pid: number
155 name: string
156 cwd: string
157 project: string
158 entry: string
159 kind: string
160 startedAt: number
161 since: number
162 state: 'working' | 'needs-you' | 'your-turn' | 'idle'
163 detail: string
164 lastAt: number
165 isSelf: boolean
166}
167
168/** What the collector writes to ~/.claude/usage-meter/local/live.json, every few seconds. */
169export type Pulse = {
170 at: number
171 codex: { limits: CodexLimits | null; runs: CodexRun[] }
172 fleet: FleetEntry[]
173}
174
175export type ContextView = {
176 model: string
177 total: number
178 max: number
179 categories: { name: string; tokens: number }[]
180 mcp: { server: string; tokens: number; tools: number }[]
181 resend: number | null
182 readUsd: number | null
183 writeUsd: number | null
184}
185
186export type LiveAgent = { label: string; usd: number; isRunning: boolean }
187
188/** The main thread's current (or last) turn, for the band above the prompt. */
189export type Live = {
190 /** estimated points of the 5h limit this turn used, by learned model weights */
191 pts?: number
192 turnId: string
193 startedAt: number
194 endedAt: number | null
195 usd: number
196 tok: Tokens
197 reqs: number
198 agents: LiveAgent[]
199}
200
201/** The main thread's prompt cache: when its last request ran and how much it holds. */
202export type Idle = {
203 /** when the main thread's last request finished (ms) */
204 at: number
205 /** context that request sent: what the cache holds */
206 ctx: number
207 /** set once an idle compaction replaced the context */
208 compacted?: { before: number; after: number; at: number }
209 /** an idle compaction was declined or failed: not retried until the next request */
210 isSkipped?: boolean
211}
212
213/** What `umeter.py install` answered at session start (or /burn setup). */
214export type Setup = {
215 action: 'ok' | 'installed' | 'updated' | 'started' | 'disabled' | 'uninstalled' | 'failed'
216 service?: 'systemd' | 'launchd' | 'process'
217 message?: string
218}
219
220export type Tab = 'overview' | 'sessions' | 'codex' | 'threads' | 'tasks' | 'breakdown' | 'history' | 'accuracy' | 'context'
221export type Scope = 'session' | 'window' | 'week'
222
223declare module 'claude-code' {
224 interface PluginState {
225 'usage-meter': {
226 view: View | null
227 pulse: Pulse | null
228 mine: ScopeView | null
229 context: ContextView | null
230 cc: number | null
231 live: Live | null
232 tab: Tab
233 scope: Scope
234 expanded: string[]
235 isAllShown: boolean
236 isBandHidden: boolean
237 idle: Idle | null
238 setup: Setup | null
239 }
240 }
241}
242