Plan-limit bars with burn rate and time-to-empty, session cost, cache hit ratio and tokens-per-turn sparkline.

Panels, guardrails and quality-of-life mods for Claude Code: see what fills your context, how fast you burn your plan, and what the agent is running right now, and block the commands you never want run.
<img src="docs/demo-guardrails.gif" alt="guardrails blocking an agent's oc delete all --all before it runs" width="900">
<sub>If a mod saves you from one bad approve, a ⭐ on this repo helps other people find it.</sub>
Claude Code is a black box while it works. You can't see the context window filling up until it compacts away the decision you made an hour ago. You find out you've burned your 5-hour limit when it stops answering. You approve a command, tab away, and come back ten minutes later to find it has been waiting on a second approval the whole time. And most people discover /rewind only after the edit they wanted to undo.
claude-mods is a set of small plugins that open that box. Each mod is a standalone Claude Code plugin built on function hooks, the in-process plugin API: it sees every prompt, tool call and turn as it happens, and it can draw panels, toasts and status lines inside Claude Code itself. Install all eleven or only the ones you want.
They are deliberately boring about tokens. Nine of the eleven never call a model. The two that do (prompt-coach's review and context-keeper's handoff note) say so and are easy to turn off.
| 🧩 mod-manager | One panel (/mods) to install, turn on or off, update, or remove each mod, with presets (Safety only, Essentials, Zero tokens, Everything). Shows when a mod has a newer version. Install this first and pick the rest |
| 🚦 quickbar | One line above the prompt: live context % and a button for every claude-mods panel you have installed. Start here |
| 🧠 context-keeper | What fills your context window, tips to trim it, and checkpoints: a handoff note (goal, decisions, files, TODOs) saved to .claude/checkpoints/ so /clear and /compact stop losing the thread. Archives the raw transcript before every compaction, for zero tokens |
| 📈 usage-meter | 5-hour and 7-day plan-limit bars with reset countdown, burn rate and "full in ~2.3h", session cost, cache hit ratio (and why it's low), tokens-per-turn sparkline (drawn as charts in the desktop app) |
| 🔔 notify | Notification inbox plus native OS notifications (Windows, macOS, Linux) when a long turn ends, a subagent or background task finishes, Claude asks you something, or an approval has been waiting 15s |
| 👀 activity | What Claude is doing this second: thinking, running $ npm test for 0m42s, waiting for YOUR approval, which subagents run, and its todo plan with progress |
| 🛡️ guardrails | Clickable safety rules with presets (Safe defaults, Locked to project, Read-only review): block rm -rf, mass kubectl/oc deletes, terraform destroy, force-push, destructive git, .env and key files, sudo, installs, network; keep Claude inside the project; add your own patterns. Checks scripts the agent wrote before they run, and keeps a weekly log of what it blocked |
| ✍️ prompt-coach | Before a vague prompt is sent, a small fast model suggests a sharper one. You pick Send improved / Send mine / Edit. Never rewrites silently, never touches "yes" or "continue" |
| 🧰 toolbox | Every tool Claude can use (built-in and MCP, grouped by server) in plain language, how often each was used, and suggestions for the project you're in |
| ⌨️ command-hub | The built-in commands you're probably missing, each with when to use it; a searchable list of everything installed; a form to create your own slash command; tips when your prompt matches one ("undo that" → /rewind) |
| 📝 changes | Every file Claude created or edited this session with +/- counts from git, plus one-click why?, summarize all and self-review |
| 🔁 loop-breaker | Notices Claude going in circles (the same command failing 3×, the same code rewritten 3× in a turn), tells you, and tells Claude to stop and rethink |
activity: what Claude is running right now, and the moment it's waiting on you
<img src="docs/demo-activity.gif" alt="activity panel showing thinking, waiting for approval, then completed tool calls" width="900">
context-keeper + usage-meter: what fills the window, a checkpoint saved to disk, plan limits
<img src="docs/demo-context.gif" alt="context panel, writing a checkpoint, then the usage meter" width="900">
prompt-coach: a vague prompt, a suggested rewrite, you choose
<img src="docs/demo-coach.gif" alt="prompt coach suggesting a sharper prompt and sending it" width="900">
command-hub: the built-in commands worth knowing, explained
<img src="docs/demo-commands.gif" alt="command hub listing essential slash commands" width="900">
You ──prompt──▶ ┌──────────────────────────────┐
│ Claude Code engine │
│ │
│ prompt.submit tool.call │
│ turn.start turn.complete│
│ session.compact ui.render │
└──────┬─────────────────▲──────┘
events, in │ │ allow · deny · rewrite
order, live ▼ │ panes · toasts · status
┌──────────────────────────────┐
│ claude-mods (one plugin each)│
│ │
│ guardrails ── may deny ──────┤
│ prompt-coach ─ may ask you ──┤
│ activity · changes · notify │
│ usage-meter · context-keeper │──▶ .claude/checkpoints/
│ toolbox · command-hub ... │──▶ OS notifications
└──────────────────────────────┘
What a mod sees. Each mod registers hooks on engine events. A tool.call hook sits in front of every tool the agent runs (Bash, Edit, MCP tools, subagents) and sees its real arguments before anything executes. That is how activity can show the exact command and guardrails can refuse it.
What it can change. A hook either passes the event on, rewrites it, or answers it itself. Guardrails answers with a denial the model reads ("blocked by the user's guardrails, don't work around it"). Prompt-coach never rewrites on its own: it asks you first, in Claude Code's own question dialog.
What it draws. Panels are ui.render hooks returning a small element tree (Box, Text, Button, Input) that Claude Code draws natively in the terminal and the desktop app. State lives in the engine ($.state), so panels survive a hot reload and redraw only when their data changes.
What it costs. Nothing, for nine of the mods. They read numbers the engine already has ($.session.usage(), $.tool.list(), $.command.list()). The two model calls are opt-out and listed under Honest limits.
Prerequisites: Claude Code 2.1.286 or newer (claude update). Panels dock beside the chat in the desktop app or a terminal ≥ 144 columns wide, and open inline in narrower terminals.
From any terminal:
claude plugin marketplace add mishgoldenberg/claude-mods
claude plugin install mod-manager@claude-mods
(In the Claude Code CLI you can also use /plugin marketplace add mishgoldenberg/claude-mods and the /plugin menu.)
Restart Claude Code. The first session says hello once ("claude-mods ready: /mods to pick your set"). Type /mods: the manager lists every mod with what it does, whether it uses tokens, and whether an update is available. Install, turn on or off, update, or remove each one with a click, or apply a preset:
| Preset | What you get |
|---|---|
| Safety only | guardrails, notify |
| Essentials | guardrails, activity, notify, context-keeper, usage-meter |
| Zero tokens | every mod that never calls a model |
| Everything | all eleven |
Presets turn off what they don't list and never remove anything. Changes apply in your next session.
With quickbar installed, a one-line bar sits above the prompt: live context % and a button for every installed panel. /quickbar (or its ×) hides it; /quickbar again brings it back.
Or just ask Claude: "Install the claude-mods plugins from github.com/mishgoldenberg/claude-mods. Follow its INSTALL-FOR-CLAUDE.md."
The VS Code extension has no /plugin menu, so install from a terminal with the two commands in step 1, then use /mods inside VS Code. Mods need the extension to run Claude Code 2.1.286 or newer.
for m in quickbar context-keeper usage-meter notify activity guardrails prompt-coach toolbox command-hub changes loop-breaker; do
claude plugin install "$m@claude-mods"
done
git clone https://github.com/mishgoldenberg/claude-mods.git
claude --plugin-dir claude-mods/plugins/activity --plugin-dir claude-mods/plugins/guardrails
| Command | Mod | What it does | |||
|---|---|---|---|---|---|
/mods | mod-manager | Install, turn on or off, update, or remove mods; apply a preset | |||
/quickbar | quickbar | Show or hide the launcher above the prompt | |||
/ctx | context-keeper | Open the context panel | |||
/checkpoint | context-keeper | Save a handoff note of this session now | |||
/resume-checkpoint | context-keeper | Load the latest checkpoint into the prompt box (use after /clear) | |||
/meter | usage-meter | Open plan limits, burn rate and cost | |||
/notifications | notify | Open the notification inbox | |||
| `/mute [on\ | off]` | notify | Mute or unmute notifications | ||
/activity | activity | Open the live activity panel | |||
/guard | guardrails | Open the rules panel | |||
| `/guard-preset <safe\ | locked\ | review\ | off>` | guardrails | Apply a preset |
/guard-log [json] | guardrails | What guardrails blocked in the last 7 days | |||
| `/coach [on\ | off]` | prompt-coach | Turn the prompt coach on or off | ||
/tools | toolbox | Open the tools panel and project suggestions | |||
/cmds | command-hub | Open the command hub | |||
/new-command | command-hub | Create your own slash command | |||
/changes | changes | Open the changed-files panel |
Options appear in /config once a mod is installed, or go in ~/.claude/settings.json under pluginConfigs.<mod>.
| Option | Default | Description |
|---|---|---|
warnAt | 70 | Toast a tip when context passes this % |
checkpointAt | 85 | Write a handoff note automatically at this % (0 = off) |
| Option | Default | Description |
|---|---|---|
warnAt | 80 | Toast when a plan window passes this % (a second toast always fires at 95%) |
| Option | Default | Description |
|---|---|---|
minSeconds | 30 | Only notify for turns at least this long |
osNotify | true | Also raise a native OS notification |
approvalWaitSeconds | 15 | Ping when an approval has waited this long (-1 = off) |
| Mod | Option | Default | Description |
|---|---|---|---|
| activity | autoOpen | false | Dock the panel on session start when there is room |
| prompt-coach | enabled | true | Review prompts before sending |
| prompt-coach | model | claude-haiku-4-5 | Reviewer model; small keeps the delay near a second |
| prompt-coach | minChars | 8 | Never review prompts shorter than this |
| loop-breaker | failLimit | 3 | Same failing command this many times in a row |
| loop-breaker | editLimit | 3 | Times the same code is rewritten in one turn (separate edits to different parts of a file never count) |
| Rule | Blocks | In preset |
|---|---|---|
no-rm-rf | rm -rf, rm -fr, Remove-Item -Recurse -Force, rmdir /s | Safe · Locked |
no-mass-delete | kubectl/oc delete --all or -A, delete namespace/project, helm uninstall, terraform destroy | Safe · Locked · Review |
no-force-push | git push --force / -f (--force-with-lease allowed) | Safe · Locked |
no-history-rewrite | git reset --hard, git clean -f, git checkout -- ., branch -D, stash drop, fetch/pull --prune, remote prune | Safe · Locked |
protect-secrets | reading or writing .env*, *.pem, *.key, id_rsa, credentials files | Safe · Locked · Review |
no-sudo | sudo, su -, runas | Safe · Locked · Review |
no-installs | npm i, pip install, cargo add, brew/apt/winget install … | Review |
no-network | WebFetch, WebSearch, curl, wget, Invoke-WebRequest | — |
jail-writes | Write/Edit outside the project folder | — |
jail-all | any file tool outside the project, cd out of it | Locked |
read-only | all edits; shell limited to look-only commands | Review |
Guardrails turns on Safe defaults the first time it loads. /guard-preset off turns everything off.
Whatever the preset, while any rule is on:
Write in this session (and edits after that) is remembered, and when a shell command runs it (bash cleanup.sh, python tools/x.py, ./run, node a.mjs), its code is checked against your enabled rules and patterns first. os.system("rm -rf …") inside a Python file counts.Write/Edit on them, and the obvious shell writes (sed -i, >, tee, cp, mv, rm), are denied with the same "ask the user" message./guard-log prints a summary (/guard-log json for the raw list), and clear wipes it. Commands are cut to 200 characters.Mods run inside Claude Code with your permissions and no sandbox, so this is the right question to ask about any mod, including these. What these ones do:
git diff --numstat (changes), the claude plugin CLI when you open /mods or click in it (mod-manager; only Install, Update and Check for updates go online, through Claude Code's own plugin installer), your OS notification tool (notify), and gh --version to see whether the GitHub CLI exists (toolbox)..claude/checkpoints/ (context-keeper), and a new slash command file when you use the form (command-hub). Settings, and guardrails' 30-day block log, live in Claude Code's own plugin store under ~/.claude. Nothing else.Every mod is a few hundred lines of TypeScript in plugins/<mod>/hooks/register.tsx. Read the ones you install.
rm -rf doesn't block you, except when the text is handed to a shell (bash -c, | sh, powershell -Command), which is checked. For hard guarantees use Claude Code's permission rules and sandboxing; use guardrails to catch the honest mistakes./coach off turns it off.claude-mods/
├── .claude-plugin/
│ └── marketplace.json The marketplace: one entry per mod
├── plugins/
│ ├── activity/
│ │ ├── .claude-plugin/
│ │ │ └── plugin.json Name, description, userConfig options
│ │ ├── hooks/
│ │ │ ├── hooks.json Points at the hooks module
│ │ │ └── register.tsx The mod: hooks, commands, panel
│ │ ├── tests/
│ │ │ └── surfaces.test.tsx The panel draws on every surface (claude plugin test)
│ │ └── types/
│ │ └── index.d.ts Its $.state contract
│ ├── guardrails/ …same shape for every mod
│ └── …
├── docs/
│ └── design.md The shared design spec and kit every mod copies
├── tests/
│ ├── guardrails-rules.test.mjs Every rule against real commands
│ └── design-kit.test.mjs Every mod's kit matches docs/design.md
├── INSTALL-FOR-CLAUDE.md Steps Claude follows when asked to install
└── tsconfig.json Type-checks all mods against the engine API
Add a guardrail rule. Append an entry to RULES in plugins/guardrails/hooks/register.tsx (an id, a title, and a test that returns the offending text) and add cases to tests/guardrails-rules.test.mjs. The panel and presets pick it up automatically.
Add an essential command. One line in ESSENTIALS in plugins/command-hub/hooks/register.tsx. It only shows when that command exists in the user's Claude Code.
Write a new mod. Copy plugins/changes (a small mod with a panel) or plugins/loop-breaker (no UI), rename it everywhere, and add it to marketplace.json. Or ask Claude Code to "make a mod that …": it has a built-in skill for exactly this, with hot reload.
Issues and pull requests are welcome. Start with CONTRIBUTING.md, which has the mod checklist.
npm install
npm run typecheck
npm test
claude plugin validate plugins/<mod>
claude plugin test plugins/<mod>
Every mod follows one design spec, docs/design.md: theme colors only (Claude orange as the single accent), the same pane header, glyphs, hotkeys and empty states, so the set feels like one product in any theme.
Two house rules worth knowing before you write anything, because the validator enforces both:
$ must be top-level function declarations. A closure inside register that receives $ is rejected.$.state key is declared in the mod's types/index.d.ts, under the mod's name.Found a way around guardrails, or another security problem? Please report it privately; see SECURITY.md.
MIT © 2026 Michael Goldenberg
hooks/register.tsx 309 lines1import { atom, read, update } from 'claude-code'
2import type { ElementTable, EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { UsageSnapshot, UsageTurn, UsageWindow } from '../types'
5
6// ── claude-mods kit v1 (docs/design.md): identical in every mod ──
7const TONE = { accent: 'claude', ok: 'success', warn: 'warning', bad: 'error', dim: 'inactive' } as const
8const GLYPH = { on: '●', off: '○', warn: '▲', ok: '✓', fail: '✗' } as const
9type Kit = Pick<ElementTable, 'Box' | 'Text'>
10
11/** Pane header: state glyph, mod name, one-line live status. */
12function header({ Box, Text }: Kit, glyph: string, tone: string, name: string, status: string) {
13 return (
14 <Box gap={1}>
15 <Text color={tone}>{glyph}</Text>
16 <Text bold>{name}</Text>
17 <Text dimColor wrap="truncate-end">{status}</Text>
18 </Box>
19 )
20}
21
22/** A section: a dim label (with optional small controls beside it), then its rows. */
23function section({ Box, Text }: Kit, label: string, rows: RenderChildren, aside?: RenderChildren) {
24 return (
25 <Box flexDirection="column">
26 <Box gap={1}>
27 <Text dimColor>{label}</Text>
28 {aside}
29 </Box>
30 {rows}
31 </Box>
32 )
33}
34
35/** A number right-aligned in a fixed-width cell. */
36function num({ Box, Text }: Kit, value: string, width: number, color?: string) {
37 return (
38 <Box width={width} flexShrink={0} justifyContent="flex-end">
39 <Text color={color}>{value}</Text>
40 </Box>
41 )
42}
43
44/** Empty state: what will show up here, and how to get it. */
45function empty({ Text }: Kit, text: string) {
46 return <Text dimColor>{text}</Text>
47}
48// ── end kit ──
49
50const PANE = 'usage-meter'
51const snapshot = atom({ plugin: 'usage-meter', key: 'snapshot' } as const, null)
52const turns = atom({ plugin: 'usage-meter', key: 'turns' } as const, [])
53const baseline = atom({ plugin: 'usage-meter', key: 'baseline' } as const, null)
54
55const LABELS: Record<string, string> = { five_hour: '5-hour', seven_day: '7-day', spend_limit: 'Spend limit' }
56const SPARK = '▁▂▃▄▅▆▇█'
57
58const bar = (percent: number, width: number) => {
59 const filled = Math.max(0, Math.min(width, Math.round((percent / 100) * width)))
60
61 return '█'.repeat(filled) + '░'.repeat(width - filled)
62}
63
64const k = (n: number) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(Math.round(n)))
65
66const spark = (values: number[]) => {
67 const max = Math.max(1, ...values)
68
69 return values.map(v => SPARK[Math.min(7, Math.floor((v / max) * 7.999))]).join('')
70}
71
72/** Svg is drawn as an isolated image and can't read the theme: the accent's fixed value and a neutral track (docs/design.md). */
73const SVG_ACCENT = 'rgb(215,119,87)'
74const SVG_TRACK = 'rgb(127,127,127)'
75
76/** A limit bar for the surfaces that draw Svg (desktop, VS Code, mobile). */
77const svgBar = (percent: number) => {
78 const w = 240
79 const filled = Math.max(0, Math.min(w, Math.round((percent / 100) * w)))
80
81 return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="10" viewBox="0 0 ${w} 10"><rect width="${w}" height="10" rx="3" fill="${SVG_TRACK}" fill-opacity="0.25"/><rect width="${filled}" height="10" rx="3" fill="${SVG_ACCENT}"/></svg>`
82}
83
84/** Tokens per turn as a small bar chart, for the surfaces that draw Svg. */
85const svgSpark = (values: number[]) => {
86 const max = Math.max(1, ...values)
87 const step = 6
88 const h = 32
89 const bars = values.map((v, i) => {
90 const bh = Math.max(1, Math.round((v / max) * h))
91
92 return `<rect x="${i * step}" y="${h - bh}" width="${step - 2}" height="${bh}" rx="1" fill="${SVG_ACCENT}"/>`
93 })
94
95 return `<svg xmlns="http://www.w3.org/2000/svg" width="${values.length * step}" height="${h}" viewBox="0 0 ${values.length * step} ${h}">${bars.join('')}</svg>`
96}
97
98const until = (iso: string | undefined, now: number) => {
99 if (iso === undefined) return ''
100 const minutes = Math.max(0, Math.round((Date.parse(iso) - now) / 60000))
101
102 return minutes >= 60 * 24 ? `resets in ${Math.round(minutes / 60 / 24)}d` : minutes >= 60 ? `resets in ${Math.floor(minutes / 60)}h${minutes % 60}m` : `resets in ${minutes}m`
103}
104
105async function refresh($: EngineInterface) {
106 const usage = await $.session.usage()
107 const now = await $.clock.now()
108 const windows: UsageWindow[] = usage.rateLimits.map(w => ({ kind: w.kind, percentUsed: w.percentUsed, resetsAt: w.resetsAt }))
109 const snap: UsageSnapshot = { windows, costUsd: usage.cost?.usd ?? null, startedAt: usage.startedAt, updatedAt: now }
110 await update($, snapshot, () => snap)
111 await update($, baseline, b => b ?? { at: now, windows })
112
113 return snap
114}
115
116/** Percent-per-hour burn of a window since this session's first reading, and when it would hit 100. */
117function burn(window: UsageWindow, base: { at: number; windows: UsageWindow[] } | null, now: number) {
118 const start = base?.windows.find(w => w.kind === window.kind)
119 if (start === undefined || base === null) return null
120 const hours = (now - base.at) / 3_600_000
121 const used = window.percentUsed - start.percentUsed
122 if (hours < 0.05 || used <= 0) return null
123 const perHour = used / hours
124 const hoursLeft = (100 - window.percentUsed) / perHour
125
126 return { perHour, hoursLeft }
127}
128
129export const register: Register = (on, options) => {
130 const warnAt = Number(options.warnAt ?? 80)
131 const warned = new Set<string>()
132
133 on('session.start', async ($, e, next) => {
134 await $.command.register({ name: 'meter', description: 'Open the usage meter (rate limits, cost, tokens per turn)' })
135 void refresh($)
136 $.clock.every(60_000, () => void refresh($))
137
138 return next(e)
139 })
140
141 on('command.run', { command: 'meter' }, async $ => {
142 await refresh($)
143 await $.ui.open({ id: PANE, title: 'Usage' })
144
145 return { text: 'Usage meter opened.' }
146 })
147
148 on('turn.complete', async ($, e, next) => {
149 const result = await next(e)
150 const usage = e.usage
151 if (usage !== undefined) {
152 const turn: UsageTurn = {
153 at: await $.clock.now(),
154 durationMs: e.durationMs,
155 input: usage.input_tokens,
156 output: usage.output_tokens,
157 cacheRead: usage.cache_read_input_tokens,
158 cacheWrite: usage.cache_creation_input_tokens,
159 model: usage.model,
160 }
161 await update($, turns, list => [...list, turn].slice(-60))
162 }
163 if (e.agentId !== undefined) return result
164
165 const snap = await refresh($)
166 for (const w of snap.windows) {
167 for (const level of [warnAt, 95]) {
168 const id = `${w.kind}:${level}`
169 if (w.percentUsed >= level && !warned.has(id)) {
170 warned.add(id)
171 $.ui.toast(`${LABELS[w.kind] ?? w.kind} limit at ${Math.round(w.percentUsed)}% (${until(w.resetsAt, snap.updatedAt)})`, { timeoutMs: 10000 })
172 }
173 }
174 }
175 const five = snap.windows.find(w => w.kind === 'five_hour')
176 const parts = [five ? `5h ${Math.round(five.percentUsed)}%` : '', snap.costUsd !== null ? `$${snap.costUsd.toFixed(2)}` : ''].filter(Boolean)
177 $.ui.status(parts.length > 0 ? parts.join(' · ') : undefined)
178
179 return result
180 })
181
182 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
183 const els = $.ui.resolve(e)
184 const { Box, Text, Button } = els
185 const Svg = 'Svg' in els ? els.Svg : undefined
186 const kit = { Box, Text }
187 const snap = await read($, snapshot)
188 const list = await read($, turns)
189 const base = await read($, baseline)
190 const cols = e.props.bodyColumns ?? 40
191 const width = Math.max(10, Math.min(30, cols - 20))
192
193 if (snap === null) {
194 return (
195 <Box flexDirection="column" gap={1}>
196 {header(kit, GLYPH.off, TONE.dim, 'usage-meter', 'no reading yet')}
197 {empty(kit, 'Plan limits and cost update after every turn and once a minute. Read them now to see where you stand.')}
198 <Box>
199 <Button key="refresh" hotkey="r" variant="primary" label="Read usage" onPress={() => void refresh($)} />
200 </Box>
201 </Box>
202 )
203 }
204
205 const now = snap.updatedAt
206 const totals = list.reduce((s, t) => ({ input: s.input + t.input, output: s.output + t.output, cacheRead: s.cacheRead + t.cacheRead, cacheWrite: s.cacheWrite + t.cacheWrite }), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 })
207 const prompted = totals.input + totals.cacheRead + totals.cacheWrite
208 const cacheHit = prompted > 0 ? Math.round((totals.cacheRead / prompted) * 100) : null
209 const minutes = Math.round((now - snap.startedAt) / 60000)
210 const perTurn = list.map(t => t.input + t.output + t.cacheWrite)
211 const toneOf = (pct: number) => (pct >= 95 ? TONE.bad : pct >= warnAt ? TONE.warn : undefined)
212 const worst = Math.max(0, ...snap.windows.map(w => w.percentUsed))
213 const five = snap.windows.find(w => w.kind === 'five_hour')
214 const status = [five ? `5h ${Math.round(five.percentUsed)}%` : '', snap.costUsd !== null ? `$${snap.costUsd.toFixed(2)}` : '', `${list.length} turns`].filter(Boolean).join(' · ')
215 const stat = (label: string, value: string, color?: string) => (
216 <Box gap={1}>
217 <Box flexGrow={1} flexShrink={1}>
218 <Text dimColor wrap="truncate-end">
219 {label}
220 </Text>
221 </Box>
222 {num(kit, value, 9, color)}
223 </Box>
224 )
225
226 return (
227 <Box flexDirection="column" gap={1}>
228 {header(kit, worst >= warnAt ? GLYPH.warn : GLYPH.on, toneOf(worst) ?? TONE.accent, 'usage-meter', status)}
229
230 {section(
231 kit,
232 'Plan limits',
233 <Box flexDirection="column">
234 {snap.windows.length === 0 && empty(kit, 'No rate-limit windows reported (API key, or a plan without limits).')}
235 {snap.windows.map(w => {
236 const b = burn(w, base, now)
237 const pct = Math.round(w.percentUsed)
238
239 return (
240 <Box flexDirection="column">
241 <Box gap={1}>
242 <Box width={11} flexShrink={0}>
243 <Text wrap="truncate-end">{LABELS[w.kind] ?? w.kind}</Text>
244 </Box>
245 {Svg !== undefined ? (
246 <Box flexGrow={1} flexShrink={1}>
247 <Svg alt={`${LABELS[w.kind] ?? w.kind} ${pct}% used`} source={svgBar(w.percentUsed)} />
248 </Box>
249 ) : (
250 <Text color={TONE.accent}>{bar(w.percentUsed, width)}</Text>
251 )}
252 {num(kit, `${w.percentUsed >= warnAt ? `${GLYPH.warn} ` : ''}${pct}%`, 6, toneOf(w.percentUsed))}
253 </Box>
254 <Box paddingLeft={12}>
255 <Text dimColor wrap="truncate-end">
256 {until(w.resetsAt, now)}
257 {b !== null && ` · +${b.perHour.toFixed(1)}%/h this session · full in ~${b.hoursLeft < 1 ? `${Math.round(b.hoursLeft * 60)}m` : `${b.hoursLeft.toFixed(1)}h`}`}
258 </Text>
259 </Box>
260 </Box>
261 )
262 })}
263 </Box>,
264 )}
265
266 {section(
267 kit,
268 'This session',
269 <Box flexDirection="column">
270 {stat('Cost', snap.costUsd !== null ? `$${snap.costUsd.toFixed(2)}` : 'n/a')}
271 {stat('Time', `${minutes}m`)}
272 {stat('Turns', String(list.length))}
273 {stat('Input', k(totals.input))}
274 {stat('Output', k(totals.output))}
275 {stat('Cache read', k(totals.cacheRead))}
276 {stat('Cache write', k(totals.cacheWrite))}
277 {cacheHit !== null && stat('Cache hit', `${cacheHit < 40 ? `${GLYPH.warn} ` : ''}${cacheHit}%`, cacheHit >= 70 ? TONE.ok : cacheHit >= 40 ? undefined : TONE.warn)}
278 {cacheHit !== null && cacheHit < 40 && <Text dimColor>Low cache hit: long pauses or edits to early context break the cache.</Text>}
279 </Box>,
280 )}
281
282 {section(
283 kit,
284 'Tokens per turn (new, uncached)',
285 perTurn.length < 2 ? (
286 empty(kit, 'The chart starts after two turns.')
287 ) : (
288 <Box flexDirection="column">
289 {Svg !== undefined ? (
290 <Svg alt={`Tokens per turn over the last ${Math.min(perTurn.length, 60)} turns`} source={svgSpark(perTurn.slice(-60))} />
291 ) : (
292 <Text color={TONE.accent}>{spark(perTurn.slice(-Math.max(8, cols - 4)))}</Text>
293 )}
294 {stat('Last', k(perTurn.at(-1) ?? 0))}
295 {stat('Average', k(perTurn.reduce((a, b) => a + b, 0) / perTurn.length))}
296 {stat('Max', k(Math.max(...perTurn)))}
297 </Box>
298 ),
299 )}
300
301 <Box gap={1}>
302 <Button key="refresh" hotkey="r" variant="primary" label="Refresh" onPress={() => void refresh($)} />
303 <Button key="reset" label="Reset burn baseline" onPress={() => void update($, baseline, () => null).then(() => refresh($))} />
304 </Box>
305 </Box>
306 )
307 })
308}
309types/index.d.ts 30 lines1export type UsageTurn = {
2 at: number
3 durationMs: number
4 input: number
5 output: number
6 cacheRead: number
7 cacheWrite: number
8 model: string
9}
10
11export type UsageWindow = { kind: string; percentUsed: number; resetsAt?: string }
12
13export type UsageSnapshot = {
14 windows: UsageWindow[]
15 costUsd: number | null
16 startedAt: number
17 updatedAt: number
18}
19
20declare module 'claude-code' {
21 interface PluginState {
22 'usage-meter': {
23 snapshot: UsageSnapshot | null
24 turns: UsageTurn[]
25 /** first reading of each window this session, to estimate burn rate */
26 baseline: { at: number; windows: UsageWindow[] } | null
27 }
28 }
29}
30