SLOPSHOPPER

usage-gauge

Plan usage windows, reset times and session API-equivalent cost in a band above the prompt.

panebandcommandtoaststatus
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · usage-gauge
│ ┃ Usage gauge ✕ › fix the failing auth test and add an audit log call │ ┃ Usage gauge │ ┃ ⏺ Read(src/auth.ts) │ ┃ 5-hour limit ⎿ Read 6 lines │ ┃ ▰▰▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ 31% ⏺ Update(src/auth.ts) │ ┃ no reset time reported ⎿ Added 2 lines, removed 1 line │ ┃ pace: on track, or too early to tell ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ Session $0.42 │ ┃ No finished turns yet. ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /usage-gauge │ ⎿ usage-gauge: Usage gauge pane opened. │ │ plan │ 5h ▰▰▱▱▱▱ 31% │ session $0.42 ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ usage-gauge: 5h 31%

Draws

Band
plan │ 5h ▰▰▱▱▱▱ 31% │ session $0.42 ⟨Claude Code's own drawing⟩
Pane · Usage gauge
Usage gauge 5-hour limit ▰▰▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱▱ 31% no reset time reported pace: on track, or too early to tell Session $0.42 No finished turns yet.
README

lchase

Lawrence Chase's Claude Code marketplace: code review, diagram, test-evidence and software factory skills, plus a set of small Claude Code mods that add band lines and panes to the terminal UI.

/plugin marketplace add lchase/coding-agent-plugins
/plugin install smart-review@lchase
/plugin install tldraw@lchase
/plugin install test-drive@lchase
/plugin install cache-clock@lchase
/plugin install usage-gauge@lchase
/plugin install auto-handoff@lchase
/plugin install agent-watch@lchase
/plugin install recording-mode@lchase
/plugin install factory@lchase

Each plugin is independent; install only what you want. @lchase is the marketplace name (from .claude-plugin/marketplace.json), not the GitHub slug.

Updating

New versions ship whenever the version string in a plugin's manifest changes. Claude Code refreshes marketplaces in the background by default, so you normally pick up updates without doing anything. To pull them right now:

/plugin marketplace update lchase      # refresh this marketplace's manifest
/plugin update smart-review@lchase     # apply a pending update to one plugin
/plugin update tldraw@lchase

/plugin marketplace update (no name) refreshes every marketplace. From a shell: claude plugin marketplace update lchase and claude plugin update <plugin>@lchase.

Reinstalling

If a plugin gets into a bad state (stale cached script, half-applied update), do a clean reinstall:

/plugin uninstall tldraw
/plugin marketplace update lchase
/plugin install tldraw@lchase

Nuclear option, re-register the whole marketplace:

/plugin marketplace remove lchase
/plugin marketplace add lchase/coding-agent-plugins
/plugin install smart-review@lchase
/plugin install tldraw@lchase

Migrating from the old layout

Before this repo became a multi-plugin marketplace it published one plugin from the repo root under a marketplace named chase. If you installed it back then, clear the old registration first:

/plugin uninstall smart-review
/plugin uninstall tldraw            # only if you installed the short-lived tldraw@chase
/plugin marketplace remove chase
/plugin marketplace add lchase/coding-agent-plugins
/plugin install smart-review@lchase
/plugin install tldraw@lchase

The tldraw skill's command also changed: /tldraw:tldraw → /tldraw:diagram.

PluginWhat it doesSkills / commandsHarnesses
smart-reviewEnsemble code review: six specialized lenses over a diff, merged into one deduplicated, severity-ranked verdict/smart-review:{review,min,max,add-pr-review,review-pr-comments} + auto-triggerClaude Code, Cursor, Codex, Gemini CLI, any AGENTS.md agent
tldrawNatural-language description → editable tldraw document (.tldr) + rendered PNG/SVG/tldraw:diagram + auto-triggerClaude Code only (needs Node + npx)
test-driveBefore/after evidence of a UI or API change: record the app before you edit, replay the same scripted scenario after, with a deterministic verdict/test-drive:{baseline,compare} + auto-triggerClaude Code only (needs Node; UI also needs Playwright and ffmpeg)
cache-clockMod: band line showing whether the prompt cache is warm. TTL, expiry, hit ratio, and re-cache size come from Claude Code when the status-line bridge is installed; otherwise the countdown is a marked estimateCompact button (warm only), /cache-clockClaude Code only
usage-gaugeMod: band line with plan usage windows (5-hour, weekly, spend limit), reset times, pace warning, session cost on API billing, threshold toasts/usage-gauge (detail pane)Claude Code only
auto-handoffMod: band line showing how full the chat is; saves a HANDOFF.md at a threshold (auto or on request), then clear and continue or resume in a new session/auto-handoffClaude Code only
agent-watchMod: band line showing who is doing the work this turn (main chat, helper agents, models, tasks, status, skills), plus a pane with per-agent blocks, per-model totals, timeline/agent-watchClaude Code only
recording-modeMod: screen-record without leaking secrets; tells the model to keep keys, emails, private words off screen and masks them in the transcript display only, red REC chip/recClaude Code only
factorySoftware factory: a feature or bug goes through spec-writer, builder, four parallel reviewers and an approver on its own branch, then merges to main or waits for you; live dashboard/factory <input>, /factory {setup,next,approve,rework,serve}Claude Code only (dashboard needs Bun)

smart-review

An ensemble code review: several specialized lenses, one merged verdict, not another pile of comments.

Most code review, human or AI, is one reviewer making a single pass and leaving a list of comments. This runs six specialized lenses instead (spec-conformance, correctness, security, performance, design, and tests), then merges the results into one verdict: duplicates collapsed, findings that several lenses independently raise weighted up, conflicting advice reconciled, severity rolled up, structural problems first, nits capped. The merge is the point. An ensemble without it is just louder, and a longer checklist handed to one reviewer only dilutes its attention and repeats its own misses.

Two modes: a fast single pass (min) for tight loops, and an orchestrated ensemble (max) for pre-merge review. Auto-routing picks between them by change size and sensitivity.

The skill lives in plugins/smart-review/skills/smart-review/ as harness-neutral markdown. Each harness gets a thin manifest pointing at that same directory, so no skill content is copied or forked.

HarnessInstallminmaxSlash commands / auto-trigger
Claude Code/plugin marketplace add lchase/coding-agent-plugins then /plugin install smart-review@lchase✅✅ isolated parallel subagents✅
Cursorpoint Cursor at plugins/smart-review/.cursor-plugin/✅✅ sequential ensemblevia session-start hook
Codexplugins/smart-review/.codex-plugin/ manifest✅✅ sequential ensembleno
Gemini CLIgemini extensions install https://github.com/lchase/coding-agent-plugins (reads root gemini-extension.json)✅✅ sequential ensemblevia GEMINI.md
Any AGENTS.md agentreads root AGENTS.md✅✅ sequential ensembleno

max's isolated parallel subagents are a Claude Code capability. A model panel (plugins/smart-review/skills/smart-review/references/ensemble.md, off by default) rides on top when the harness can route more than one model. Otherwise max is single-model. Elsewhere max runs the same spec-gate, six lenses, and merge as a disciplined sequential walk. Design and internals: plugins/smart-review/SMART-REVIEW.md.

Claude Code slash commands:

  • /smart-review:review: auto (routes to min or max by size + sensitivity)
  • /smart-review:min: fast single-pass review
  • /smart-review:max: orchestrated ensemble review
  • /smart-review:add-pr-review <PR number or URL>: reviews a GitHub PR and, after you confirm what to publish, posts the findings as PR comments
  • /smart-review:review-pr-comments <PR number or URL>: triages a PR's existing unresolved review comments, fixes or explains each after your approval, replies, and resolves the thread

The skill also triggers automatically when you ask Claude to review a diff, PR, or branch.


tldraw

Turn a described diagram (flowchart, architecture / system diagram, process map, decision tree, state machine) into two artifacts: an editable .tldr document (opens at tldraw.com or in the tldraw editor) and a rendered PNG/SVG for docs and PRs.

Claude writes a {nodes, edges} spec from your description; a bundled Node script does a simple layered auto-layout, emits the .tldr, and renders images by loading it into a headless-Chromium tldraw instance via @kitschpatrol/tldraw-cli (first run downloads Chromium, ~1 min, cached).

/plugin install tldraw@lchase

Claude Code only. Skill: /tldraw:diagram (also auto-triggers on "draw this diagram", "diagram this flow", "make a tldraw of…"). Details: plugins/tldraw/skills/diagram/SKILL.md.


test-drive

A test drive is an e2e test that happens to produce video, and the "before" is part of the process rather than something reconstructed later. Run /test-drive:baseline before you edit: it writes a short browser scenario and records the app as it stands. Make the change, then run /test-drive:compare: it replays the identical scenario with Playwright and composes a labeled side-by-side MP4. The pass/warn/fail verdict comes from the scenario's assertions, not from reading the video.

Backend changes work the same way with "kind": "api": the scenario is a list of HTTP steps (method, path, body, expected status, JSON fields, and server-log lines to expect or avoid). There is nothing to screen-record, so each step captures the request, the response, and the server log lines it produced, and compare writes a before/after report.md instead of a video. Secrets are redacted from the stored transcript (best effort, extendable per scenario with redact), and the finished report is scanned and flagged if anything still looks secret.

/plugin install test-drive@lchase

Claude Code only. UI scenarios need ffmpeg and Playwright in the repo under test; API scenarios need only Node 18+. Only the working tree is ever run, so there is no second checkout to boot. Details: baseline and compare.


Claude Code mods

Five small plugins that change Claude Code's own interface instead of adding a task skill. Each draws a band line above the prompt (some add a side pane or slash command), is independent of the others, and works on Claude Code only.

  • cache-clock: is the prompt cache still warm? After /cache-clock setup, the countdown, TTL, hit ratio, re-cache size, and last miss cause come from Claude Code's own prompt_cache (v2.1.251+). Without that, the band uses your promptCacheTtl or cache environment variables, and only then a fallback (cacheMinutes, default 5) marked with ?. Compact is offered only while the cache is warm. Dollar figures stay hand-kept list-price estimates.
  • usage-gauge: plan usage windows (5-hour, weekly, spend limit) with reset times and a pace warning; session cost on API billing; threshold toasts. /usage-gauge opens a detail pane.
  • auto-handoff: watches context fill and saves a HANDOFF.md at a threshold (automatically or on request), then clears and continues, or resumes in a new session. /auto-handoff.
  • agent-watch: who is doing the work this turn: main chat, helper agents, models, tasks, status, skills. /agent-watch opens a pane with per-agent blocks, per-model totals, and a timeline.
  • recording-mode: for screen recordings. Tells the model to keep keys, emails, and private words off screen and masks them in the transcript display only (the underlying transcript is untouched). Red REC chip, /rec to toggle.
/plugin install cache-clock@lchase    # or usage-gauge, auto-handoff, agent-watch, recording-mode

cache-clock and the status line

Claude Code tells a status-line script whether the prompt cache is warm, when it expires, and the session hit ratio (prompt_cache on the status-line JSON, v2.1.251 or later). A plugin cannot register a status line, and the mods API does not include those fields, so cache-clock reads them through a small bridge.

In Claude Code, run:

/cache-clock setup

That edits your user settings (~/.claude/settings.json, or $CLAUDE_CONFIG_DIR/settings.json when that variable is set). It saves whatever statusLine was there and points statusLine at cache-clock/bridge.mjs, which still runs your previous status line and writes Claude Code's prompt_cache for the band to read. /cache-clock remove puts the previous value back. node must be on PATH. Setup refuses to edit a status line that comes from managed settings, --settings, or a project or local settings file.

The same edit by hand, when you have no status line yet:

{
  "statusLine": {
    "type": "command",
    "command": "node ~/.claude/cache-clock/bridge.mjs"
  }
}

Run /cache-clock setup once so the script is copied into that folder. After the next reply the band's TTL and expiry are Claude Code's figures, not a guess. The band redraws every 30 seconds from the last expires_at. Claude Code also re-runs the status line on its own events, and when a warm cache reaches expires_at.

Until the bridge is installed, the band still works. It follows this order: prompt_cache if the bridge has written it, then FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL, the promptCacheTtl setting, ENABLE_PROMPT_CACHING_1H, then the cacheMinutes option (5 or 60, default 5). Only that last step is marked with ?. A subscription within plan usage is often 60 minutes and an API key, cloud provider, or usage-credit session is often

  1. The option cannot see a mid-session change; the bridge can.

/cache-clock status names which of those sources the band is using.


factory

A small, visual software factory. /factory <input> takes a feature or bug as text, a path to a requirements .md, an issue key or URL, or a GitHub issue, and runs it through a fixed loop: spec-writer writes a spec with testable acceptance criteria, builder implements it in its own git worktree (via the Orca CLI when present, so .env and setup hooks come along, else plain git worktree), four reviewers (security, ux, ui, code) run in parallel and each writes a VERDICT: PASS | CHANGES file, the builder is resumed while any review says CHANGES (max two rounds), then an approver writes APPROVE or ESCALATE. APPROVE merges to main locally; ESCALATE parks the job as needs-human.

/plugin install factory@lchase

Then, in a repo:

/factory setup                          # once per repo: profiles it into .factory/repo.md, review that file
/factory <text | path.md | KEY-123 | #123>
/factory next                           # first unchecked item in .factory/backlog.md
/factory approve <job-id>               # merge a needs-human job
/factory rework <job-id> <note>         # send it back to the builder with your note
/factory serve                          # live board at http://localhost:8765 (needs Bun)

Nothing repo-specific is baked in: commands, conventions, commit rules, issue tracker and the approver's never-auto-merge list all come from .factory/repo.md, which /factory setup drafts and you edit. Job state is .factory/jobs/<id>/ (gitignored), one folder of markdown per job, so several sessions can run jobs at once and the dashboard shows them all.

Claude Code only. Dashboard needs Bun. Full guide, including what happens when a job stops for you: plugins/factory/README.md.


Token-savings benchmark

benchmarks/token-savings/ compares stock Claude Code with plugins and settings that claim to cut tokens or cost. It is not a marketplace plugin. Click 8.5.0 is fetched at a pinned commit when you run it. The full matrix calls the Anthropic API and has a hard ceiling of $600 at the default per-session cap. Read the benchmark README before you run it. ./benchmarks/token-savings/check.sh is the offline check and does not spend API money.

Repo layout

.claude-plugin/marketplace.json   # the "lchase" marketplace: 9 plugin entries
AGENTS.md                         # repo-level agent pointer (→ smart-review)
gemini-extension.json + GEMINI.md # Gemini CLI installs the repo as an extension (→ smart-review)

plugins/smart-review/             # plugin 1, multi-harness code review
  .claude-plugin/plugin.json
  skills/smart-review/            # the harness-neutral core (SKILL.md + references/)
  agents/ commands/ hooks/        # Claude Code packaging
  .cursor-plugin/ .codex-plugin/  # thin per-harness manifests
  scripts/                        # validate-adapters.sh, bump-version.sh
  evals/                          # dev-only eval kit (not shipped to installers)
  SMART-REVIEW.md                 # design writeup

plugins/tldraw/                   # plugin 2, Claude Code only
  .claude-plugin/plugin.json
  skills/diagram/                 # SKILL.md + scripts/build-tldr.mjs + references/

plugins/test-drive/               # plugin 3, Claude Code only
  .claude-plugin/plugin.json
  skills/{baseline,compare}/      # SKILL.md each
  scripts/{lib.mjs,record.mjs,record-api.mjs,redact.mjs,verdict.mjs,compose.sh,report.mjs}   # shared by both skills
  references/                     # UI and API scenario schemas + examples

plugins/factory/                  # plugin 4, Claude Code only
  .claude-plugin/plugin.json
  skills/factory/SKILL.md         # the orchestrator loop, commands, setup, job.json and repo.md schemas
  agents/                         # spec-writer, builder, review-{security,ux,ui,code}, approver, repo-profiler
  dashboard/                      # dashboard.html + serve.ts (Bun) + example/ dummy jobs

plugins/{cache-clock,usage-gauge,auto-handoff,agent-watch,recording-mode}/   # plugins 5-9, Claude Code mods
  .claude-plugin/plugin.json      # each with its own version
  hooks/                          # register.tsx (the mod) + hooks.json, tests where present
  types/                          # mod API typings

benchmarks/token-savings/         # paired Claude Code cost benchmark (not a plugin)

Developing

claude plugin validate .                                # marketplace + all plugins
./plugins/smart-review/scripts/validate-adapters.sh      # smart-review's per-harness manifests
./benchmarks/token-savings/check.sh                      # benchmark lint and graders; no API spend
claude plugin test plugins/cache-clock                   # mod tests, including the native prompt_cache path
node --test plugins/cache-clock/statusline/bridge.test.mjs

Releasing: users only get an update when a plugin's version string changes, so bump it on every user-facing change and push to main.

  • smart-review: version is pinned across all its manifests; bump them together with ./plugins/smart-review/scripts/bump-version.sh <version>.
  • tldraw, test-drive, factory, and each mod: version independently; edit that plugin's .claude-plugin/plugin.json.

Once pushed, installed clients pick it up on their next background marketplace refresh, or immediately with /plugin marketplace update lchase.

Source 3 files
hooks/register.tsx 370 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { Limit, Reading, Settings, Snapshot } from '../types'
5import {
6  addReading,
7  bar,
8  colorFor,
9  duration,
10  meterSvg,
11  money,
12  paceOutMs,
13  paceText,
14  parseWarn,
15  pctText,
16  resetText,
17  shortLabel,
18  windowLabel,
19  windowTitle,
20} from './lib'
21
22const PANE = 'usage-gauge'
23const MAX_TURNS = 10
24// 7 cells, the length of 'handoff', so stacked bands line up
25const LABEL_W = 7
26const DEFAULTS: Settings = { isOn: true, warnA: 75, warnB: 90 }
27
28const snap = atom({ plugin: 'usage-gauge', key: 'snap' } as const, null)
29const readings = atom({ plugin: 'usage-gauge', key: 'readings' } as const, {})
30const turns = atom({ plugin: 'usage-gauge', key: 'turns' } as const, [])
31const prevCost = atom({ plugin: 'usage-gauge', key: 'prevCost' } as const, null)
32const settings = atom({ plugin: 'usage-gauge', key: 'settings' } as const, DEFAULTS)
33
34type Measured = {
35  rateLimits: readonly Limit[]
36  context: { percent?: number }
37  cost?: { usd: number }
38}
39
40function isSettings(v: unknown): v is Settings {
41  const s = v as Settings | null
42  return (
43    typeof s === 'object' &&
44    s !== null &&
45    typeof s.isOn === 'boolean' &&
46    typeof s.warnA === 'number' &&
47    typeof s.warnB === 'number'
48  )
49}
50
51async function saveSettings($: EngineInterface, next: Settings) {
52  await update($, settings, () => next)
53  await $.store.set('settings', next)
54}
55
56async function ingest($: EngineInterface, m: Measured) {
57  const now: number = await $.clock.now()
58  const limits: Limit[] = m.rateLimits.map(l => ({
59    kind: l.kind,
60    percentUsed: l.percentUsed,
61    resetsAt: l.resetsAt,
62  }))
63  const next: Snapshot = {
64    rateLimits: limits,
65    contextPercent: m.context.percent,
66    costUsd: m.cost?.usd,
67  }
68  await update($, snap, () => next)
69  await update($, readings, all => {
70    const out: Record<string, Reading[]> = {}
71    for (const l of limits) out[l.kind] = addReading(all?.[l.kind], l.percentUsed, now)
72    return out
73  })
74
75  const cfg: Settings = ((await read($, settings)) as Settings | undefined) ?? DEFAULTS
76  if (!cfg.isOn) {
77    $.ui.status(undefined)
78    return
79  }
80  const parts = limits.map(l => `${shortLabel(l.kind)} ${pctText(l.percentUsed)}`)
81  $.ui.status(parts.length > 0 ? parts.join(' · ') : undefined)
82
83  const stored = (await $.store.get('fired')) as Record<string, string> | undefined
84  const fired: Record<string, string> = { ...(stored ?? {}) }
85  let isDirty = false
86  for (const l of limits) {
87    for (const t of [cfg.warnA, cfg.warnB]) {
88      const key = `${l.kind}:${t}`
89      const mark = l.resetsAt ?? ''
90      if (l.percentUsed >= t) {
91        if (fired[key] !== mark) {
92          fired[key] = mark
93          isDirty = true
94          const at = resetText(l, now)
95          const isSoon = l.resetsAt !== undefined && Date.parse(l.resetsAt) - now < 86_400_000
96          const when = at === undefined ? '' : `, resets ${isSoon && at !== 'now' ? 'in ' : ''}${at}`
97          $.ui.toast(`${windowTitle(l.kind)} at ${t}%${when}`)
98        }
99      } else if (key in fired) {
100        delete fired[key]
101        isDirty = true
102      }
103    }
104  }
105  if (isDirty) await $.store.set('fired', fired)
106}
107
108export const register: Register = on => {
109  on('session.start', async ($, e, next) => {
110    const saved = await $.store.get('settings')
111    if (isSettings(saved)) await update($, settings, () => saved)
112    await $.command.register({
113      name: 'usage-gauge',
114      description: 'Plan usage windows, resets and session cost',
115      argumentHint: 'on | off | warn <a> <b> | status',
116    })
117    await ingest($, await $.session.usage())
118
119    return next(e)
120  })
121
122  on('session.measure', async ($, e, next) => {
123    await ingest($, e)
124
125    return next(e)
126  })
127
128  on('turn.complete', async ($, e, next) => {
129    if (!e.agentId) {
130      const usage = await $.session.usage()
131      if (usage.cost) {
132        const total = usage.cost.usd
133        const before = await read($, prevCost)
134        await update($, prevCost, () => total)
135        if (before !== null && total > before) {
136          await update($, turns, list => [...list, total - before].slice(-MAX_TURNS))
137        }
138      }
139    }
140
141    return next(e)
142  })
143
144  on('command.run', { command: 'usage-gauge' }, async ($, e) => {
145    const arg = e.args.trim()
146    const cfg: Settings = ((await read($, settings)) as Settings | undefined) ?? DEFAULTS
147    const word = arg.split(/\s+/)[0] ?? ''
148
149    if (arg === '') {
150      await $.ui.open({ id: PANE, title: 'Usage gauge' })
151
152      return { text: 'Usage gauge pane opened.' }
153    }
154    if (word === 'on' || word === 'off') {
155      await saveSettings($, { ...cfg, isOn: word === 'on' })
156      if (word === 'off') $.ui.status(undefined)
157      else await ingest($, await $.session.usage())
158
159      return { text: `Usage gauge ${word}.` }
160    }
161    if (word === 'warn') {
162      const parsed = parseWarn(arg)
163      if (typeof parsed === 'string') return { text: parsed }
164      await saveSettings($, { ...cfg, warnA: parsed.a, warnB: parsed.b })
165
166      return { text: `Toasts at ${parsed.a}% and ${parsed.b}%.` }
167    }
168    if (word === 'status') {
169      const s = await read($, snap)
170      const now: number = await $.clock.now()
171      const lines = [
172        `Usage gauge ${cfg.isOn ? 'on' : 'off'}, toasts at ${cfg.warnA}% and ${cfg.warnB}%.`,
173      ]
174      for (const l of s?.rateLimits ?? []) {
175        const at = resetText(l, now)
176        lines.push(`${windowLabel(l.kind)} ${pctText(l.percentUsed)}${at ? ` resets ${at}` : ''}`)
177      }
178      if (s?.costUsd !== undefined) lines.push(`session ${money(s.costUsd)}`)
179      if ((s?.rateLimits.length ?? 0) === 0) lines.push('No plan windows reported (API billing).')
180
181      return { text: lines.join('\n') }
182    }
183
184    return { text: 'Usage: /usage-gauge on | off | warn <a> <b> | status' }
185  })
186
187  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
188    const cfg: Settings = ((await read($, settings)) as Settings | undefined) ?? DEFAULTS
189    const s = await read($, snap)
190    if (e.props.hasSurvey || !cfg.isOn || s === null) return next(e)
191
192    const now: number = await $.clock.now()
193    const all = await read($, readings)
194    const history = await read($, turns)
195    const last = history[history.length - 1]
196    const hasPlan = s.rateLimits.length > 0
197    const hasCtx = s.contextPercent !== undefined
198    if (!hasPlan && !hasCtx && s.costUsd === undefined) return next(e)
199
200    if (e.surface !== 'terminal') {
201      // proportional fonts collapse the padded label, │ and ▰▱ cells: a gapped row with Svg meters
202      const { Box, Text, Svg } = $.ui.resolve(e)
203      const Gauge = (label: string, pct: number) => (
204        <Box flexDirection="row" alignItems="center" gap={1}>
205          <Text dimColor>{label}</Text>
206          <Svg source={meterSvg(pct, colorFor(pct))} alt={`${label} ${pctText(pct)}`} width={56} height={8} />
207          <Text bold color={colorFor(pct)}>{pctText(pct)}</Text>
208        </Box>
209      )
210      const row = (
211        <Box flexDirection="row" alignItems="center">
212          <Box width={9} flexShrink={0}><Text dimColor bold>{hasPlan ? 'plan' : 'api'}</Text></Box>
213          <Box flexDirection="row" alignItems="center" flexWrap="wrap" flexGrow={1} columnGap={2}>
214          {s.rateLimits.map(l => {
215            const at = resetText(l, now)
216            const out = l.kind === 'five_hour' ? paceOutMs(all?.[l.kind], l.resetsAt, now) : undefined
217            return (
218              <Box flexDirection="row" alignItems="center" gap={1}>
219                {Gauge(windowLabel(l.kind), l.percentUsed)}
220                {at ? <Text dimColor>resets {at}</Text> : null}
221                {out !== undefined ? <Text color="#fbbf24">⚠ out in {paceText(out)} at this pace</Text> : null}
222              </Box>
223            )
224          })}
225          {!hasPlan && hasCtx ? Gauge('ctx', s.contextPercent as number) : null}
226          {s.costUsd !== undefined ? (
227            <Text>
228              <Text dimColor>session </Text>
229              {money(s.costUsd)}
230              {last !== undefined ? <Text dimColor> (+{money(last)})</Text> : null}
231            </Text>
232          ) : null}
233          </Box>
234        </Box>
235      )
236      const under = await next(e)
237
238      return under ? (
239        <Box flexDirection="column">
240          {row}
241          {under}
242        </Box>
243      ) : (
244        row
245      )
246    }
247
248    const { Box, Text } = $.ui.resolve(e)
249    const sep = <Text dimColor> │ </Text>
250    // filled cells in the level color, empty cells dim
251    const Meter = (cells: string, color: string) => (
252      <Text>
253        <Text color={color}>{cells.replace(/▱/g, '')}</Text>
254        <Text dimColor>{cells.replace(/▰/g, '')}</Text>
255      </Text>
256    )
257    const segs: RenderChildren[] = []
258
259    for (const l of s.rateLimits) {
260      const c = colorFor(l.percentUsed)
261      const at = resetText(l, now)
262      const out = l.kind === 'five_hour' ? paceOutMs(all?.[l.kind], l.resetsAt, now) : undefined
263      segs.push(
264        <Text>
265          {windowLabel(l.kind)} {Meter(bar(l.percentUsed, 6), c)} <Text bold color={c}>{pctText(l.percentUsed)}</Text>
266          {at ? <Text dimColor> ↻{at}</Text> : null}
267          {out !== undefined ? <Text color="#fbbf24"> ⚠ at this pace: out in {paceText(out)}</Text> : null}
268        </Text>,
269      )
270    }
271    if (!hasPlan && hasCtx) {
272      const pct = s.contextPercent as number
273      segs.push(
274        <Text>
275          <Text dimColor>ctx</Text> {Meter(bar(pct, 6), colorFor(pct))} <Text bold color={colorFor(pct)}>{pctText(pct)}</Text>
276        </Text>,
277      )
278    }
279    if (s.costUsd !== undefined) {
280      segs.push(
281        <Text>
282          <Text dimColor>session</Text> {money(s.costUsd)}
283          {last !== undefined ? <Text dimColor> (+{money(last)})</Text> : null}
284        </Text>,
285      )
286    }
287
288    const line = (
289      <Text wrap="truncate-end">
290        <Text dimColor>{(hasPlan ? 'plan' : 'api').padStart(LABEL_W)}</Text>
291        {sep}
292        {segs.flatMap((seg, i) => (i === 0 ? [seg] : [sep, seg]))}
293      </Text>
294    )
295    const below = await next(e)
296
297    return below ? (
298      <Box flexDirection="column">
299        {line}
300        {below}
301      </Box>
302    ) : (
303      line
304    )
305  })
306
307  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
308    const { Box, Text } = $.ui.resolve(e)
309    const Meter = (pct: number, cells: number, alt: string) => {
310      if (e.surface === 'terminal') {
311        return (
312          <Text>
313            <Text color={colorFor(pct)}>{bar(pct, cells)}</Text> {pctText(pct)}
314          </Text>
315        )
316      }
317      const { Svg } = $.ui.resolve(e)
318      return (
319        <Box flexDirection="row" alignItems="center" gap={1}>
320          <Svg source={meterSvg(pct, colorFor(pct), 240)} alt={alt} width={240} height={8} />
321          <Text bold color={colorFor(pct)}>{pctText(pct)}</Text>
322        </Box>
323      )
324    }
325    const s = await read($, snap)
326    const cfg: Settings = ((await read($, settings)) as Settings | undefined) ?? DEFAULTS
327    const all = await read($, readings)
328    const history = await read($, turns)
329    const now: number = await $.clock.now()
330    const width = Math.max(10, Math.min(40, (e.props.bodyColumns ?? 60) - 24))
331
332    return (
333      <Box flexDirection="column">
334        <Text bold>Usage gauge {cfg.isOn ? '' : '(off)'}</Text>
335        {(s?.rateLimits ?? []).length === 0 && (
336          <Text dimColor>No plan windows reported (API billing).</Text>
337        )}
338        {(s?.rateLimits ?? []).map(l => {
339          const at = resetText(l, now)
340          const out = paceOutMs(all?.[l.kind], l.resetsAt, now)
341          return (
342            <Box flexDirection="column" marginTop={1}>
343              <Text bold>{windowTitle(l.kind)}</Text>
344              {Meter(l.percentUsed, width, `${windowTitle(l.kind)} ${pctText(l.percentUsed)}`)}
345              <Text dimColor>
346                {at ? `resets ${at}${l.resetsAt && Date.parse(l.resetsAt) > now ? ` (in ${duration(Date.parse(l.resetsAt) - now)})` : ''}` : 'no reset time reported'}
347              </Text>
348              <Text dimColor={out === undefined} color={out === undefined ? undefined : '#fbbf24'}>
349                {out === undefined ? 'pace: on track, or too early to tell' : `pace: out in ${paceText(out)} at this rate`}
350              </Text>
351            </Box>
352          )
353        })}
354        <Box flexDirection="column" marginTop={1}>
355          <Text bold>
356            Session {s?.costUsd !== undefined ? money(s.costUsd) : ''}
357          </Text>
358          {history.length === 0 && <Text dimColor>No finished turns yet.</Text>}
359          {history.length > 0 && <Text dimColor>Last {history.length} turns</Text>}
360          {history.map((c, i) => (
361            <Text>
362              {String(history.length - i).padStart(2)} ago  {money(c)}
363            </Text>
364          ))}
365        </Box>
366      </Box>
367    )
368  })
369}
370
hooks/lib.ts 130 lines
1import type { Limit, Reading } from '../types'
2
3export const GREEN = '#4ade80'
4export const AMBER = '#fbbf24'
5export const RED = '#f87171'
6
7const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
8const MIN = 60_000
9const PACE_MIN_SPAN = 4.5 * MIN
10const PACE_KEEP = 30 * MIN
11
12export function colorFor(pct: number): string {
13  if (pct > 85) return RED
14  if (pct >= 60) return AMBER
15  return GREEN
16}
17
18export function bar(pct: number, cells: number): string {
19  const filled = Math.max(0, Math.min(cells, Math.round((pct / 100) * cells)))
20  return '▰'.repeat(filled) + '▱'.repeat(cells - filled)
21}
22
23/** A rounded meter for the surfaces that draw Svg; the terminal keeps the `bar` cells. */
24export function meterSvg(pct: number, color: string, width = 56): string {
25  const fill = Math.round((Math.max(0, Math.min(100, pct)) / 100) * width)
26  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="8" viewBox="0 0 ${width} 8"><rect width="${width}" height="8" rx="4" fill="#8080804d"/><rect width="${fill}" height="8" rx="4" fill="${color}"/></svg>`
27}
28
29export function windowLabel(kind: string): string {
30  if (kind === 'five_hour') return '5h'
31  if (kind === 'seven_day') return 'week'
32  return kind
33}
34
35export function windowTitle(kind: string): string {
36  if (kind === 'five_hour') return '5-hour limit'
37  if (kind === 'seven_day') return 'Weekly limit'
38  return `${kind} limit`
39}
40
41export function shortLabel(kind: string): string {
42  if (kind === 'five_hour') return '5h'
43  if (kind === 'seven_day') return 'wk'
44  return kind
45}
46
47export function pctText(pct: number): string {
48  return `${Math.round(pct)}%`
49}
50
51export function duration(ms: number): string {
52  const total = Math.max(0, Math.round(ms / MIN))
53  const h = Math.floor(total / 60)
54  const m = total % 60
55  if (h === 0) return `${m}m`
56  return `${h}h${String(m).padStart(2, '0')}m`
57}
58
59function clock(date: Date): string {
60  const h = date.getHours()
61  const m = date.getMinutes()
62  const h12 = h % 12 === 0 ? 12 : h % 12
63  const suffix = h < 12 ? 'am' : 'pm'
64  return m === 0 ? `${h12}${suffix}` : `${h12}:${String(m).padStart(2, '0')}${suffix}`
65}
66
67/** `2h11m` within a day, otherwise `Thu 9am`; undefined when there is no reset time. */
68export function resetText(limit: Limit, now: number): string | undefined {
69  if (!limit.resetsAt) return undefined
70  const at = Date.parse(limit.resetsAt)
71  if (Number.isNaN(at)) return undefined
72  const left = at - now
73  if (left <= 0) return 'now'
74  if (left < 24 * 60 * MIN) return duration(left)
75  const date = new Date(at)
76  return `${DAYS[date.getDay()]} ${clock(date)}`
77}
78
79export function money(usd: number): string {
80  return `$${usd.toFixed(2)}`
81}
82
83/** Append a reading; a drop in percent means the window reset, so history restarts. */
84export function addReading(list: Reading[] | undefined, pct: number, t: number): Reading[] {
85  const prior = list ?? []
86  const last = prior[prior.length - 1]
87  const base = last && pct < last.pct ? [] : prior
88  const tail = base[base.length - 1]
89  if (tail && tail.pct === pct) return base
90  return [...base, { pct, t }].filter(r => t - r.t <= PACE_KEEP).slice(-20)
91}
92
93/**
94 * Minutes until the window runs out at the rate the readings show, when that is
95 * before it resets. Needs two readings about five minutes apart.
96 */
97export function paceOutMs(
98  readings: Reading[] | undefined,
99  resetsAt: string | undefined,
100  now: number,
101): number | undefined {
102  if (!readings || readings.length < 2 || !resetsAt) return undefined
103  const first = readings[0]!
104  const last = readings[readings.length - 1]!
105  const span = last.t - first.t
106  const gain = last.pct - first.pct
107  if (span < PACE_MIN_SPAN || gain <= 0 || last.pct >= 100) return undefined
108  const rate = gain / span
109  const runOut = last.t + (100 - last.pct) / rate
110  const reset = Date.parse(resetsAt)
111  if (Number.isNaN(reset) || runOut >= reset) return undefined
112  return Math.max(MIN, runOut - now)
113}
114
115export function paceText(outMs: number): string {
116  const mins = Math.max(1, Math.round(outMs / MIN))
117  if (mins < 60) return `~${mins}m`
118  return `~${Math.floor(mins / 60)}h${String(mins % 60).padStart(2, '0')}m`
119}
120
121export function parseWarn(args: string): { a: number; b: number } | string {
122  const parts = args.trim().split(/\s+/).slice(1)
123  const [a, b] = parts.map(Number)
124  const ok = (n: number | undefined): n is number =>
125    n !== undefined && Number.isFinite(n) && n > 0 && n <= 100
126  if (parts.length !== 2 || !ok(a) || !ok(b)) return 'Usage: /usage-gauge warn <a> <b> (percent, e.g. 75 90)'
127  if (a >= b) return 'The first threshold must be below the second.'
128  return { a, b }
129}
130
types/index.d.ts 21 lines
1export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
2export type Snapshot = {
3  rateLimits: Limit[]
4  contextPercent?: number
5  costUsd?: number
6}
7export type Reading = { pct: number; t: number }
8export type Settings = { isOn: boolean; warnA: number; warnB: number }
9
10declare module 'claude-code' {
11  interface PluginState {
12    'usage-gauge': {
13      snap: Snapshot | null
14      readings: Record<string, Reading[]>
15      turns: number[]
16      prevCost: number | null
17      settings: Settings
18    }
19  }
20}
21