SLOPSHOPPER

usage-meter

Your plan's 5-hour and 7-day usage as small bars above the prompt, with the reset countdown and the session's cost.

bandtoasttimer
★ 393v0.1.1MITupdated 2026-10-15hamzafer/claude-code-mods/mods/usage-meter
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · usage-meter
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ⏱ 5h █▅▁▁▁ 31% · $0.42 session ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⏱ 5h █▅▁▁▁ 31% · $0.42 session ⟨Claude Code's own drawing⟩
README

<h1 align="center">Claude Code mods</h1>

<a href="https://www.npmjs.com/package/claude-code-mods"><img src="https://img.shields.io/npm/v/claude-code-mods.svg" alt="npm"></a> <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT"></a> <a href="https://github.com/hamzafer/claude-code-mods/actions/workflows/ci.yml"><img src="https://github.com/hamzafer/claude-code-mods/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI"></a>

<a href="#-install">Install</a> · <a href="#-the-mods">All mods</a> · <a href="docs/mods.md">Docs</a> · <a href="https://claude.dev/blog/getting-started-with-claude-code-mods/">What are mods?</a>

<table> <tr> <td align="center" width="33%"><a href="docs/mods.md#-context-bar"><img src="images/context-bar.png" alt="context-bar: Claude Code context window usage as a stacked bar, a color per category" width="260"></a><br>📊 <b>context-bar</b><br>what fills your context</td> <td align="center" width="33%"><a href="docs/mods.md#-review-watch"><img src="images/review-watch.png" alt="review-watch: live lines for running Codex and subagent code reviews in Claude Code" width="260"></a><br>🔍 <b>review-watch</b><br>running code reviews, live</td> <td align="center" width="33%"><a href="docs/mods.md#-md-preview"><img src="images/md-preview.png" alt="md-preview: Markdown that Claude Code edits, rendered like GitHub next to the diff" width="260"></a><br>📝 <b>md-preview</b><br>Markdown rendered like GitHub</td> </tr> <tr> <td align="center" width="33%"><a href="docs/mods.md#-blast-radius"><img src="images/gallery/blast-radius.png" alt="blast-radius: a Claude Code hook holds rm -rf and lists the files it would delete" width="260"></a><br>💥 <b>blast-radius</b><br>see what <code>rm -rf</code> would delete</td> <td align="center" width="33%"><a href="docs/mods.md#-now-playing"><img src="images/now-playing.png" alt="now-playing: Spotify track, progress bar and synced lyrics inside Claude Code" width="260"></a><br>🎵 <b>now-playing</b><br>Spotify and its lyrics, live</td> <td align="center" width="33%"><a href="docs/mods.md#-reels-and-snake"><img src="images/reels-demo.gif" alt="reels: YouTube Shorts in a Claude Code pane while it works" width="260"></a><br>📱 <b>reels</b><br>Shorts while Claude works</td> </tr> <tr> <td align="center" width="33%"><a href="docs/mods.md#-where-am-i"><img src="images/gallery/where-am-i.png" alt="where-am-i: the session goal, current step and what waits on you, above the Claude Code prompt" width="260"></a><br>📍 <b>where-am-i</b><br>goal, now, waiting on you</td> <td align="center" width="33%"><a href="docs/mods.md#-lines-above-the-prompt"><img src="images/gallery/lines.png" alt="token-weather, usage-meter and other Claude Code status lines stacked above the prompt" width="260"></a><br>🌦️ <b>token-weather and friends</b><br>lines above the prompt</td> <td align="center" width="33%"><a href="#mission-control"><img src="images/gallery/mission-control.png" alt="mission-control: Claude Code subagents, tool calls and the files they touch, live" width="260"></a><br>🛰️ <b>mission-control</b><br>agents and the code they touch</td> </tr> <tr> <td align="center" width="33%"><a href="docs/mods.md#-switchboard"><img src="images/switchboard.png" alt="switchboard: subagents routed from opus to sonnet and haiku, with confidence and cost" width="260"></a><br>🔀 <b>switchboard</b><br>cheaper models for subagents</td> <td align="center" width="33%"><a href="docs/mods.md#-agent-radar"><img src="images/agent-radar.png" alt="agent-radar: a running subagent and two background shells with their latest output" width="260"></a><br>📡 <b>agent-radar</b><br>subagents and shells, live</td> <td align="center" width="33%"><a href="docs/mods.md#-reels-and-snake"><img src="images/snake.png" alt="snake: a game of Snake in a Claude Code pane" width="260"></a><br>🐍 <b>snake</b><br>a game while Claude works</td> </tr> </table>

🚀 Install

npx claude-code-mods@latest

Tick the mods you want in a checklist, see what each one adds, and press Enter to install. Untick a mod to disable it (its settings stay). Restart Claude Code after. @latest makes npx skip an old cached copy.

  • --project installs for this project only
  • --dry-run prints the claude commands instead of running them
  • --pick a,b turns on exactly these mods, no checklist (--pick "" turns all off)
  • --yes-community installs picked community mods without asking (outside a terminal they are skipped without it)
  • --help shows usage

It edits the Claude profile that claude uses here, shown at the top. For another profile, set it first: CLAUDE_CONFIG_DIR=~/.claude-other npx claude-code-mods@latest.

Order your bands

Press o in the checklist to order your bands (the lines above the prompt). Move the cursor with up/down or j/k, move a band with Shift+up/down or K/J, and press Enter to save. Esc goes back without saving. The order goes to <config dir>/claude-code-mods/bands.json, where the config dir is CLAUDE_CONFIG_DIR or ~/.claude. Restart Claude Code to apply it. Bands not in the file sit on top.

Other ways

By hand:

claude plugin marketplace add hamzafer/claude-code-mods
claude plugin install context-bar@claude-code-mods

To try one without installing:

git clone https://github.com/hamzafer/claude-code-mods && cd claude-code-mods
claude --plugin-dir mods/context-bar

Needs Claude Code 2.1.287+. A few mods need more (Chrome, gh, a connector); the tables say which.

🧩 The mods

👀 See what's happening

ModWhat it doesCommand
🛰️mission-controlLive map of agents, tool calls and the code they touch/mission
📊context-barYour context window as one stacked bar, a color per category, with token counts and where it compacts/context-bar
🌦️token-weatherContext fill from Clear to Compact soon, plus a prompt-cache countdown
⏱️cache-clockA prompt-cache line under your status line, from Claude Code's own figures: time left, hit rate and misses, and the tokens your next message re-caches once it goes cold. Needs Node and Claude Code 2.1.287+/cache-clock setup
📍where-am-iGoal, doing now, waiting on you, next step/where
➡️next-steps2 or 3 likely next prompts after each turn, one key to draft one. language sets their language, layout: rows keeps one per row1 2 3, 0 hides
💰usage-meter5-hour and 7-day plan usage, the reset countdown and the session's cost
🔥heatmapA GitHub-style grid of your Claude Code time, with your streak, peak hours and top projects/heatmap
💳openai-balanceYour OpenAI API credit: an estimated balance with a gauge, today's spend, where the money mostly went, and the last call. Needs an OpenAI organization Admin key/openai-balance
🪙openrouter-balanceYour OpenRouter credit: the real balance with a gauge, today's spend and the model the money mostly went to. A regular API key shows the balance too when OpenRouter allows it, plus its own spend and limit/openrouter-balance
📡agent-radarOne live line per running subagent or background shell/radar
🔍review-watchOne live line per running code review (Codex or a review subagent) with the model, target, elapsed time and Codex's latest output. A toast lists the findings when it ends
🌐browser-lanesWhether this session has a browser, and who holds it/browser
🕌prayer-timesThe current prayer and how long is left, the next one, and zawal. Computed on your computer, Hanafi or standard Asr/prayers
🎬replay-theaterSteps through the last turn's edits, one diff at a time/replay
📝md-previewRenders the Markdown files Claude edits like GitHub does, with before and after side by side. Needs Chrome and a terminal that shows images/md

🛡️ Guard your repo

ModWhat it doesCommand
💥blast-radiusHolds rm -r, force pushes and migrations, shows what they'd delete, cancels after 60 s with no answer

💸 Spend less

ModWhat it doesCommand
🔀switchboardPicks the model for each subagent that doesn't name one, with OpenAI's Decisions API or Jev, from its short label only. Shows what every subagent cost/route

🔧 My setup (fork and adapt)

These are built around my own tools and rules. Fork them and change the rules to yours.

ModWhat it doesCommand
👀glanceOne line with what needs you: next meeting, PRs, Linear issues, Slack DMs. Needs gh and the Google Calendar, Linear and Slack connectors/glance
🚦merge-gateHolds gh pr merge until CI is green and Codex reviewed once. Needs gh and the Codex CLI. Reviews run on one fixed model; change it to yours/gate
📏rulebook-guardEnforces my writing and git rules: rewrites em dashes, asks before --amend, unformatted pushes, emails and phone numbers in notes
💾session-saverSaves where you left off, shows it on resume. Needs unpause/park [note]

🎮 For fun (opt-in)

ModWhat it doesCommand
📱reelsYouTube Shorts while Claude works, pauses when it's done/reels
🐍snakeSnake while Claude works/snake
🎵now-playingWhat Spotify is playing, with a progress bar, the lyric being sung, and ⏮ ⏸ ⏭ buttons. Needs macOS and the Spotify app/music

🤝 Community mods

Mods by other people, in their own marketplaces. They're not maintained here, so read the code before you install. They also show up last in the npx claude-code-mods@latest checklist.

ModWhat it doesInstall
🖼️image-view by @jarrodwattsSee the images you paste into Claude Code: thumbnails above the prompt instead of bare [Image #1] tagsclaude plugin marketplace add jarrodwatts/claude-image-view then claude plugin install image-view@claude-image-view
🏷️last-prompt-title by @zhangbububuSession titles that follow your latest prompt: cut for the CLI, written by Haiku for the desktop sidebarclaude plugin marketplace add zhangbububu/session-titles then claude plugin install last-prompt-title@session-titles
🌏cc-zh by @jiangnanquanSimplified Chinese UI localization via static dictionary: slash-command descriptions, /config labels, spinner, hints, notices, command output, tool summaries and turn duration. Zero tokens / network; verified on CC 2.1.296claude plugin marketplace add jiangnanquan/claude-code-zh then claude plugin install cc-zh@claude-code-zh
🎛️subagent-tuner by @KruhlikauPicks the model and effort of every subagent: a Manual/Auto band, a pick pane, review → Opus and search → Haiku, and a saved default that overrides what the agent asked forclaude plugin marketplace add Kruhlikau/subagent-tuner then claude plugin install subagent-tuner@subagent-tuner
🛒mod-store by @hellosverreAn app store in a pane: /mods browses, searches and installs about 2,700 community mods, with what each one can access shown before you install. Or ask Claude to find oneclaude plugin marketplace add hellosverre/mod-store then claude plugin install mod-store@mod-store
📈cache-meter by @T-AI-LabsThe share of each turn the prompt cache served, next to the context fill, with an auto-compact threshold and Compact and Clear buttonsclaude plugin marketplace add T-AI-Labs/claude-code-mods then claude plugin install cache-meter@T-AI-Labs
⏳usage-limits by @T-AI-Labs5-hour and weekly plan limits in percent, with the time left until each resetsclaude plugin marketplace add T-AI-Labs/claude-code-mods then claude plugin install usage-limits@T-AI-Labs
🟣pixel-pulse by @air01adityaA purple pixel strip above the prompt that drifts right to left and glows under the pointer, and a purple pixel spiral in place of the working spinner. Desktop app only; it only drawsclaude plugin marketplace add air01aditya/pixel-pulse then claude plugin install pixel-pulse@pixel-pulse
🔗open-paths by @kiankhoobanClick a file path in Claude's reply and the file opens in its app: Word, Preview or Excel for documents, your editor at the line for app.py:42, Finder for folders. Launchers, scripts and unknown types are never openedclaude plugin marketplace add kiankhooban/open-paths then claude plugin install open-paths@open-paths
🎼workflow-conductor by @bruwTerminal UI for planning, running and understanding complex agent workflows inside Claude Code: define the workflow as a graph, have Claude script and run it, and watch the run on the same graph. Needs Claude Code 2.1.296+ and a terminal 110+ columns wideclaude plugin marketplace add bruw/workflow-conductor then claude plugin install workflow-conductor@workflow-conductor
💸bedrock-meter by @weidu-tpvisionToken and USD meter for Claude Code on Amazon Bedrock: session cost, context fill, cache hit rate and today's total above the prompt, priced at AWS's own on-demand rates (refreshed weekly from the AWS price list), with a per-model breakdown in /bedrock-costclaude plugin marketplace add weidu-tpvision/claude-mods then claude plugin install bedrock-meter@weidu-claude-mods
📱brainrot-break by @BordyVA TikTok-style feed of 350+ pixel art mini-videos in a pane while Claude answers: scroll, like, pick your themes, and an end card when Claude is done. Every video is a small simulation drawn locally: no tokens, no model calls. Terminal and desktop app, in 6 languages. Try it in the browserclaude plugin marketplace add BordyV/brainrot-break then claude plugin install brainrot-break@brainrot-break

Built one? Open a PR that adds a row.

<a id="mission-control"></a>

🛰️ Flagship: mission-control

Every subagent, every tool call and every file they touch, in a pane next to the chat. Shown at 4x: two subagents building a logout feature across four files.

mission-control at 4x: two subagents and a logout feature landing across four files

Install it like any mod, restart, and type /mission (or /mission code to open the code map). q closes it.

  • 🤖 w shows the agents and every tool call, live
  • 🗺️ c shows the code map, with import arrows
  • 🔵 Blue while the agent reads a file
  • 🟠 Orange while it writes
  • 🟢 Green when done, with one line on what changed

The Code view runs on macOS and Linux and needs Google Chrome or Chromium and a terminal that shows images (Ghostty, kitty, iTerm2). The Who view works everywhere.

📚 More

Source 3 files
hooks/register.tsx 218 lines
1// Usage Meter: the plan's rate-limit windows and the session's cost, above the prompt.
2import { atom, read, update } from 'claude-code'
3import type { EngineInterface, Register, Timer } from 'claude-code'
4
5import type { UsageMeterSnapshot, UsageMeterWindow } from '../types'
6import { bandsFile, parseOrder, stackBands } from './bands'
7
8const CELLS = 5
9const BLOCKS = '▁▂▃▄▅▆▇█'
10const TICK_MS = 60_000
11const WARN_AT = 90
12const LABELS: Record<string, string> = { five_hour: '5h', seven_day: '7d', spend_limit: 'spend' }
13const ORDER = ['five_hour', 'seven_day', 'spend_limit']
14
15// Held by the host, so they survive a hot reload of this file.
16const snapshot = atom({ plugin: 'usage-meter', key: 'snapshot' } as const, null as UsageMeterSnapshot | null)
17const tick = atom({ plugin: 'usage-meter', key: 'tick' } as const, 0)
18const warned = atom({ plugin: 'usage-meter', key: 'warned' } as const, {} as Record<string, number>)
19
20type Segment = { text: string; color?: string; dim?: boolean }
21type Part = { kind: 'window' | 'cost'; isPrimary: boolean; segments: Segment[] }
22
23let bandOrder: Promise<string[]> | undefined // read once per session: restart to apply
24
25// The band order file, as the claude-code-mods checklist saves it; [] on any error.
26async function readBandOrder($: EngineInterface): Promise<string[]> {
27  const file = bandsFile(await $.env.get('CLAUDE_CONFIG_DIR'), await $.env.get('HOME'))
28  return file && (await $.fs.exists(file)) ? parseOrder(await $.fs.read(file)) : []
29}
30
31// Forgets the cached band order, for tests.
32export function resetBandOrder() {
33  bandOrder = undefined
34}
35
36export const register: Register = on => {
37  let timer: Timer | undefined // one countdown timer, even if session.start fires again
38
39  on('session.start', async ($, e, next) => {
40    const result = await next(e)
41    // Moves the reset countdown on while a window has a reset time.
42    timer?.cancel()
43    timer = $.clock.every(TICK_MS, () => {
44      void (async () => {
45        const snap = await read($, snapshot)
46        if (snap?.rateLimits.some(w => w.resetsAt)) await update($, tick, n => n + 1)
47      })().catch(() => {})
48    })
49    const usage = await $.session.usage().catch(() => null)
50    if (usage) await take($, usage.rateLimits, usage.cost?.usd).catch(() => {})
51    return result
52  })
53
54  on('session.measure', async ($, e, next) => {
55    const result = await next(e)
56    await take($, e.rateLimits, e.cost?.usd).catch(() => {})
57    return result
58  })
59
60  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
61    const rest = await next(e) // what other mods and Claude Code draw here stays
62    await read($, tick) // redraws on each tick of the countdown
63    const snap = await read($, snapshot)
64    if (e.props.hasSurvey || !snap) return rest
65
66    const parts = fit(build(snap, await $.clock.now()), e.props.bodyColumns - 2)
67    if (parts.length === 0) return rest
68
69    const { Box, Text } = $.ui.resolve(e)
70    const segments: Segment[] = [{ text: '⏱ ', dim: true }]
71    parts.forEach((p, i) => {
72      if (i > 0) segments.push({ text: ' · ', dim: true })
73      segments.push(...p.segments)
74    })
75
76    const mine = (
77      <Box flexDirection="row" paddingX={1}>
78        {segments.map((s, i) => (
79          <Text key={String(i)} color={s.color} dimColor={s.dim} wrap="truncate">
80            {s.text}
81          </Text>
82        ))}
83      </Box>
84    )
85    bandOrder ??= readBandOrder($).catch(() => [])
86    return stackBands(rest, 'usage-meter', mine, 'above', await bandOrder) // above what other mods draw, unless the band order says otherwise
87  })
88}
89
90async function take($: EngineInterface, rateLimits: readonly UsageMeterWindow[], costUsd: number | undefined) {
91  const windows = rateLimits
92    .filter(w => Number.isFinite(w.percentUsed))
93    .map(w => ({ kind: w.kind, percentUsed: w.percentUsed, resetsAt: w.resetsAt }))
94  await update($, snapshot, () => ({ rateLimits: windows, costUsd }))
95  await warn($, windows)
96}
97
98// One toast per window per reset period, once it passes WARN_AT.
99async function warn($: EngineInterface, windows: UsageMeterWindow[]) {
100  const done = await read($, warned)
101  const now = await $.clock.now()
102  const fresh: Record<string, number> = {}
103  const rearm: string[] = []
104  for (const w of windows) {
105    const resetMs = resetTime(w)
106    if (w.percentUsed < WARN_AT) {
107      // With no reset time, dropping back under the line is the only sign of a new period.
108      if (resetMs === 0 && done[w.kind] !== undefined) rearm.push(w.kind)
109      continue
110    }
111    const last = done[w.kind]
112    // A reset time that moved on by more than half an hour is a new period.
113    if (last !== undefined && resetMs <= last + 30 * 60_000) continue
114    fresh[w.kind] = resetMs
115    const when = resetMs > 0 ? `, resets in ${countdown(resetMs - now)}` : ''
116    const what = w.kind === 'spend_limit' ? 'Spend limit' : `${label(w.kind)} usage limit`
117    $.ui.toast(`${what} at ${Math.round(w.percentUsed)}%${when}`)
118  }
119  if (Object.keys(fresh).length > 0 || rearm.length > 0) {
120    await update($, warned, old => {
121      const next = { ...old, ...fresh }
122      for (const kind of rearm) delete next[kind]
123      return next
124    })
125  }
126}
127
128export function build(snap: UsageMeterSnapshot, now: number): Part[] {
129  const windows = snap.rateLimits
130    .filter(w => !isStale(w, now)) // a window past its reset waits for a fresh reading
131    .sort((a, b) => rank(a.kind) - rank(b.kind))
132  const parts: Part[] = windows.map((w, i) => {
133    const color = colorFor(w.percentUsed)
134    const segments: Segment[] = [
135      { text: `${label(w.kind)} `, dim: true },
136      { text: bar(w.percentUsed), color },
137      { text: ` ${Math.round(w.percentUsed)}%`, color },
138    ]
139    const resetMs = resetTime(w)
140    // The first window always says when it resets; the others only once they run high.
141    if (resetMs > 0 && (i === 0 || w.percentUsed >= 75)) {
142      segments.push({ text: ` · resets ${countdown(resetMs - now)}`, dim: true })
143    }
144    return { kind: 'window', isPrimary: i === 0, segments }
145  })
146  if (snap.costUsd !== undefined && snap.costUsd > 0) {
147    parts.push({ kind: 'cost', isPrimary: false, segments: [{ text: `$${snap.costUsd.toFixed(2)} session`, dim: true }] })
148  }
149  return parts
150}
151
152// Drops the secondary windows first, then the cost, until the line fits.
153export function fit(parts: Part[], columns: number): Part[] {
154  let kept = [...parts]
155  const tooWide = () => width(kept) > columns
156  while (tooWide()) {
157    const i = findLastIndex(kept, p => p.kind === 'window' && !p.isPrimary)
158    if (i < 0) break
159    kept.splice(i, 1)
160  }
161  if (tooWide() && kept.some(p => p.isPrimary)) kept = kept.filter(p => p.kind !== 'cost')
162  return kept
163}
164
165function width(parts: Part[]) {
166  const text = parts.map(p => p.segments.map(s => s.text).join('')).join(' · ')
167  return 3 + [...text].length // the clock and its space: the glyph can draw two cells wide
168}
169
170function findLastIndex<T>(list: T[], test: (item: T) => boolean) {
171  for (let i = list.length - 1; i >= 0; i--) if (test(list[i] as T)) return i
172  return -1
173}
174
175export function bar(percent: number) {
176  const filled = (Math.min(Math.max(percent, 0), 100) / 100) * CELLS
177  let out = ''
178  for (let i = 0; i < CELLS; i++) {
179    const cell = Math.min(Math.max(filled - i, 0), 1)
180    out += BLOCKS[Math.round(cell * (BLOCKS.length - 1))]
181  }
182  return out
183}
184
185export function colorFor(percent: number) {
186  if (percent >= 90) return 'red'
187  if (percent >= 75) return 'yellow'
188  return 'green'
189}
190
191export function countdown(ms: number) {
192  const minutes = Math.max(0, Math.ceil(ms / 60_000))
193  if (minutes < 1) return 'now'
194  if (minutes < 60) return `${minutes}m`
195  const hours = Math.floor(minutes / 60)
196  if (hours < 24) return `${hours}h${String(minutes % 60).padStart(2, '0')}`
197  return `${Math.floor(hours / 24)}d${hours % 24}h`
198}
199
200function resetTime(w: UsageMeterWindow) {
201  const ms = w.resetsAt ? Date.parse(w.resetsAt) : NaN
202  return Number.isFinite(ms) ? ms : 0
203}
204
205function isStale(w: UsageMeterWindow, now: number) {
206  const resetMs = resetTime(w)
207  return resetMs > 0 && resetMs <= now
208}
209
210function label(kind: string) {
211  return LABELS[kind] ?? kind.replace(/_/g, ' ')
212}
213
214function rank(kind: string) {
215  const i = ORDER.indexOf(kind)
216  return i < 0 ? ORDER.length : i
217}
218
hooks/bands.ts 73 lines
1// Band order: every band mod ships this same file (canonical copy: shared/bands.ts in the repo).
2//   The order file, <configDir>/claude-code-mods/bands.json, lists mod names top to bottom
3//   (the last sits right above the prompt). Each band mod wraps its band in a Box keyed
4//   `band:<name>` and returns one column keyed `bands`; the next band mod unpacks that
5//   column, adds its own band and sorts again, so the last one to draw sorts them all.
6//   Edit shared/bands.ts, then copy it over every mod's hooks/bands.ts (a repo test checks).
7//   Reading the file needs $, which Claude Code follows only within one file, so each mod
8//   reads it in its own register file with bandsFile and parseOrder, once per session.
9import type { RenderElement, RenderNode } from 'claude-code'
10
11const COLUMN = 'bands'
12const PREFIX = 'band:'
13
14// Where the checklist saves the order: CLAUDE_CONFIG_DIR, or ~/.claude. Undefined with neither.
15export function bandsFile(configDir: string | undefined, home: string | undefined): string | undefined {
16  const dir = configDir ? configDir.replace(/\/+$/, '') : home ? `${home}/.claude` : ''
17  return dir ? `${dir}/claude-code-mods/bands.json` : undefined
18}
19
20// The names in an order file; [] when it is no JSON or not { order: string[] }.
21export function parseOrder(text: string): string[] {
22  try {
23    const order = (JSON.parse(text) as { order?: unknown } | null)?.order
24    return Array.isArray(order) && order.every(n => typeof n === 'string') ? order : []
25  } catch {
26    return []
27  }
28}
29
30/**
31 * One column of bands: `mine` wrapped in a Box keyed `band:<name>`, placed
32 * `at` (above or below) what `next(e)` returned, then sorted by `order`.
33 * With an order, items that are no band come first, then bands not in the
34 * order (in their current order), then the listed ones in file order. With
35 * no order nothing moves, so the screen looks as it did before.
36 */
37export function stackBands(rest: RenderElement | null | undefined, name: string, mine: RenderNode, at: 'above' | 'below', order: string[]): RenderElement {
38  const own: RenderElement = { type: 'Box', props: { key: PREFIX + name, flexDirection: 'column' }, children: [mine] }
39  const others = unpack(rest)
40  const items = at === 'above' ? [own, ...others] : [...others, own]
41  return { type: 'Box', props: { key: COLUMN, flexDirection: 'column' }, children: order.length ? sorted(items, order) : items }
42}
43
44// Another band mod's column gives up its items; anything else is one item.
45function unpack(rest: RenderElement | null | undefined): RenderNode[] {
46  if (!rest) return []
47  if (!isColumn(rest)) return [rest]
48  const kids = rest.children ?? []
49  const owner = rest.part?.plugin
50  // The engine stamped the column with its owner: that stamp belongs on the owner's own band.
51  return kids.map(k => (owner && typeof k !== 'string' && bandName(k) === owner && !('part' in k && k.part) ? { ...k, part: rest.part } : k))
52}
53
54function isColumn(el: RenderElement): el is RenderElement & { type: 'Box' } {
55  return el.type === 'Box' && el.props?.key === COLUMN
56}
57
58function bandName(node: RenderNode): string | undefined {
59  if (typeof node === 'string' || node.type !== 'Box') return undefined
60  const key = node.props?.key
61  return typeof key === 'string' && key.startsWith(PREFIX) ? key.slice(PREFIX.length) : undefined
62}
63
64function sorted(items: RenderNode[], order: string[]): RenderNode[] {
65  const rank = (n: RenderNode) => {
66    const name = bandName(n)
67    if (name === undefined) return -2 // not a band: first
68    const i = order.indexOf(name)
69    return i < 0 ? -1 : i // a band not in the order: on top of the listed ones
70  }
71  return items.map((n, i) => ({ n, i, r: rank(n) })).sort((a, b) => a.r - b.r || a.i - b.i).map(x => x.n)
72}
73
types/index.d.ts 13 lines
1export type UsageMeterWindow = { kind: string; percentUsed: number; resetsAt?: string }
2export type UsageMeterSnapshot = { rateLimits: UsageMeterWindow[]; costUsd?: number }
3
4declare module 'claude-code' {
5  interface PluginState {
6    'usage-meter': {
7      snapshot: UsageMeterSnapshot | null
8      tick: number
9      warned: Record<string, number>
10    }
11  }
12}
13