SLOPSHOPPER

clawd-band

A band above the prompt: an animated Clawd sprite, five-hour and weekly usage bars, and a countdown to each window's reset

bandspinnerguardnetworktimer
★ 1v0.2.3MITupdated 2026-10-18nninkovic95/clawd-band
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · clawd-band
› 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 ▣ Clawd resting 7d ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ -- ↻ --d---h---m -- 5h ████████████████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 31% ↻ NaNh-NaNm-NaNs ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
▣ Clawd resting 7d ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ -- ↻ --d---h-- -- 5h ████████████████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 31% ↻ NaNh-NaNm
README

clawd-band

A Claude Code mod that puts a band above the prompt: an animated pixel-art Clawd that acts out what Claude is doing, your weekly and five-hour usage bars, and a live countdown to each window's reset.

clawd-band cycling through every pose

The band

 ┌ sprite ┐  7d ███████████░░░░░░░░░░░░░░░░░░░░░░░░░░░  26% ↻ 04d-07h-31m
 │ 12 × 3 │  5h ███████████████░░░░░░░░░░░░░░░░░░░░░░░  38% ↻ 02h-14m-09s
 Opus 5.5 high
  • Sprite: Clawd, drawn with kitty's graphics protocol at 12 columns by 3 rows, in stop-motion (a few frames, each held for 400 ms). It is the only thing that moves: the mod replaces Claude Code's own spinner with an empty box.
  • Model and effort: the session's model, shortened (claude-opus-5-5 becomes Opus 5.5), with the reasoning effort beside it.
  • Usage bars: 7d is the weekly window, 5h the five-hour window. Each bar turns from green to amber at 60% and to red at 85%.
  • Countdown: the time to each window's reset, 04d-07h-31m for the weekly window and 02h-14m-09s for the five-hour one. Both are 11 characters wide, so they line up under each other. Until a window has a reading, its line shows --d---h---m or --h---m---s.

Where the numbers come from

The percentages and reset times are the same ones /usage shows. The band keeps them current in four ways:

  1. At startup, /clear and /new: it shows the last reading it saved, then asks Claude Code for its own. A fresh session has none yet, so the band asks your account once (see Privacy).
  2. When a window moves: Claude Code reads the limits from the response headers of every request and tells the band whenever a window moves by a whole point.
  3. After every turn: the band reads Claude Code's latest figures again, so a new reset time shows even when the percentage did not move (a window that reset and started over at the same rounded percent).
  4. When a reset time passes: the window drops to 0% and its countdown to dashes straight away. Five seconds later the band asks your account for the next window, so the countdown fills without waiting for a reply. If the account has no new reset time yet, it asks again once a minute, five times at most; after that the next reply fills it.

While a session sits idle, nothing else updates the bars, so use on claude.ai or another device shows up after the next reply.

Every pose

The pose follows Claude's current step: thinking, replying, or the tool it is calling. When the turn ends, Clawd goes back to idle.

idle

Nothing running. Clawd stands and blinks now and then.

thinking

The model is thinking. A hand scratches the head while a thought bubble rises.

working

The model is replying, or calls any tool not listed below (TodoWrite, an MCP tool, …). Both arms pump.

reading

Read, Grep, Glob, LS, NotebookRead, ToolSearch, and the Claude Docs connector's read, query and guide. Clawd holds up a book, the eyes run along the line, and a page turns.

writing

Edit, Write, MultiEdit, NotebookEdit, and every other Claude Docs tool (create, update, batch, …). A pencil leaves a line of ink.

running

Bash, BashOutput, KillShell, TaskStop. A stride and a bounce, with speed lines.

searching

WebFetch, WebSearch. A magnifying glass, held up on one side and then the other.

delegating

Agent, Task, SendMessage, Workflow, Skill. Clawd waves a small Clawd off on its errand.

questioning

AskUserQuestion. A "?" bobs beside the head while Claude writes the question.

While an AskUserQuestion menu is open, Claude Code hides the band. The mod also swaps the sprite for Claude Code's text logo and stops animating until the menu closes, so a kitty image can't cover the menu.

About the demo

kitty's graphics protocol draws the sprite as an image on its own layer, and terminal recorders such as asciinema record only the text stream, so a recording would show the bars with no Clawd. The GIF at the top is therefore rendered by scripts/render-demo.ts from the mod's own frame data (hooks/sprite.ts). The script uses the band's layout from hooks/register.tsx and Claude Code's dark-theme colours. To re-render it:

node scripts/render-demo.ts   # needs node 23.6+, rsvg-convert and ImageMagick

Requirements

  • Claude Code with function-hook plugins (mods): built against 2.1.296, tested on 2.1.299. The mod API is early access and may change between releases.
  • A terminal that supports the kitty graphics protocol, for the sprite. It has been tested in kitty; other terminals are untested.
  • A claude.ai subscription login (Pro or Max) for the usage bars: the five-hour and weekly windows belong to a subscription, and without them the bars read --.

Install

At the prompt of a Claude Code terminal session:

/plugin install clawd-band --marketplace nninkovic95/clawd-band

Answer y to add the marketplace, then pick a scope. From a shell instead:

claude plugin install clawd-band --marketplace nninkovic95/clawd-band

To run it from a clone while you work on it: claude --plugin-dir /path/to/clawd-band.

Configuration

The options are the plugin's userConfig fields, Claude Code's standard way for a plugin to take settings. You can set them on the screen shown at install, or later in /config, where each one is a row. A change reloads the band at once. Claude Code stores them in ~/.claude/settings.json under pluginConfigs:

{
  "pluginConfigs": {
    "clawd-band@clawd-band": {
      "options": {
        "show_model": false,
        "sprite_color": "#6a9bcc",
        "bar_color_low": "suggestion",
        "bar_color_mid": "#ffc107",
        "bar_color_high": "red",
        "bar_color_empty": "subtle"
      }
    }
  }
}
OptionDefaultWhat it does
show_modeltrueShows the model and effort line under Clawd. Turned off, the band is three rows tall.
sprite_color#d77757Clawd's body colour, as hex. The props keep their own colours.
bar_color_lowsuccessBar colour below 60%.
bar_color_midwarningBar colour from 60%.
bar_color_higherrorBar colour from 85%.
bar_color_emptyinactiveThe unfilled part of each bar.

Each bar colour can be a Claude Code theme key, which follows your /theme: success, warning, error, inactive, subtle, claude, suggestion, permission, planMode, autoAccept, ide and others. It can also be a colour name (green, magenta) or hex (#4eba65). A value that is none of these falls back to the default. The key under pluginConfigs is clawd-band@<marketplace> for an installed copy, and clawd-band (or clawd-band@inline) when loaded with --plugin-dir.

Privacy

This section is clawd-band's privacy policy: what the mod reads, stores and sends. clawd-band has no server of its own and collects nothing.

The one host it contacts is api.anthropic.com, with one request: GET https://api.anthropic.com/api/oauth/usage (hooks/register.tsx, fetchAccountUsage).

  • When: once at the start of a session, and again after /clear or /new, but only if Claude Code has no rate-limit reading yet; and when a window's reset time passes, five seconds later and then once a minute, at most five times, until the account reports the next window. Otherwise Claude Code's own reading from the response headers of its requests is used and nothing is fetched.
  • What is sent: the request carries your own claude.ai sign-in, which Claude Code attaches through $.session.authorize() (the mod never sees the token), and the header anthropic-beta: oauth-2025-04-20. It has no body. Nothing from the conversation, your files or your settings is sent.
  • What comes back: your five-hour and weekly usage percentages and reset times. This is the same data /usage shows. An API-key session makes no request.

What it reads from the session (all of it stays on your machine):

  • The name of each tool Claude calls (for example Read or Bash), to pick the pose. It does not read tool inputs, tool results or message text.
  • Whether the model's output stream is in a thinking, text or tool-call part, to switch between the thinking and working poses. It does not read the content of those parts.
  • The model name and reasoning effort, for the line under the sprite.
  • The rate-limit readings Claude Code already holds.
  • The session id, to notice a /clear (which starts a new session in the same process) and load the band again. It is compared with the last id seen and never sent.

What it stores: the last usage reading and the last model and effort, in Claude Code's own plugin store on your machine, so that the band is filled at startup. A cached effort is shown only for the same model. Each new reading replaces the old one; uninstalling the plugin and deleting its store removes them.

No telemetry, no analytics, no third parties, no other network calls, and no files written outside the plugin store. The usage request goes to Anthropic under your own account, and Anthropic's privacy policy applies to it. Questions or concerns: open an issue.

Development

scripts/ holds two developer tools that the plugin never runs. render-demo.ts writes the demo GIF, docs/demo/tour.gif, and render-icon.ts writes .claude-plugin/icon.png. Both are run by hand with node, and both write images; neither reads or runs one.

claude plugin validate .
claude plugin test .

claude plugin test runs hooks/band.test.tsx: pose mapping, usage parsing and merging, the reset time read after each turn, the fetch when a reset passes and its five-try limit, countdowns and colours, whole RGBA frames, the band's content, the survey case, a /clear reload, and the options (checking, the model line, bar and sprite colours). Saving a file while the mod is loaded through --plugin-dir hot-reloads it.

Credits

The sprites are original to this project. They are drawn in code (hooks/sprite.ts) on a 28 × 14 grid, and Clawd's body is Claude Code's own startup logo (▐▛███▜▌ / ▝▜█████▛▘ / ▘▘ ▝▝) traced pixel for pixel. Every prop (book, pencil, magnifying glass, thought bubble, "?", mini Clawd) is drawn here.

Clawd is the Claude Code mascot. This is an unofficial community project, not affiliated with or endorsed by Anthropic.

License

MIT

Source 3 files
hooks/register.tsx 478 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, Register, SessionRateLimit } from 'claude-code'
3
4import type { Model, Pose, Usage, Window } from '../types'
5import { ALT, CLAUDE_ORANGE, FRAMES, framesFor, PIXEL_HEIGHT, PIXEL_WIDTH } from './sprite'
6import type { Rgb } from './sprite'
7
8const poseAtom = atom({ plugin: 'clawd-band', key: 'pose' } as const, 'idle')
9const usageAtom = atom({ plugin: 'clawd-band', key: 'usage' } as const, null)
10const modelAtom = atom({ plugin: 'clawd-band', key: 'model' } as const, { name: null, effort: null })
11
12const SPRITE_COLUMNS = 12
13const SPRITE_ROWS = 3
14const FRAME_MS = 400 // stop-motion: a few frames, each held
15const LABEL = 3 // "7d "
16const PERCENT = 5 // " 100%"
17const RESET = 14 // " ↻ 06d-23h-59m" or " ↻ 04h-59m-59s": one width for both bars
18const DOCS_PREFIX = 'mcp__claude_ai_Claude_Docs__'
19
20const READING = ['Read', 'Grep', 'Glob', 'LS', 'NotebookRead', 'ToolSearch']
21const WRITING = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit']
22const RUNNING = ['Bash', 'BashOutput', 'KillShell', 'TaskStop']
23const SEARCHING = ['WebFetch', 'WebSearch']
24const DELEGATING = ['Agent', 'Task', 'SendMessage', 'Workflow', 'Skill']
25const DOCS_READING = ['read', 'query', 'guide']
26
27export const poseFor = (tool: string): Pose => {
28  if (tool === 'AskUserQuestion') return 'questioning'
29  if (tool.startsWith(DOCS_PREFIX)) return DOCS_READING.includes(tool.slice(DOCS_PREFIX.length)) ? 'reading' : 'writing'
30  if (READING.includes(tool)) return 'reading'
31  if (WRITING.includes(tool)) return 'writing'
32  if (RUNNING.includes(tool)) return 'running'
33  if (SEARCHING.includes(tool)) return 'searching'
34  if (DELEGATING.includes(tool)) return 'delegating'
35  return 'working'
36}
37
38const toWindow = (limits: readonly SessionRateLimit[], kind: string): Window | null => {
39  const found = limits.find(l => l.kind === kind)
40  return found ? { percentUsed: found.percentUsed, resetsAt: found.resetsAt ?? null } : null
41}
42
43export const toUsage = (limits: readonly SessionRateLimit[]): Usage | null =>
44  limits.length === 0 ? null : { fiveHour: toWindow(limits, 'five_hour'), sevenDay: toWindow(limits, 'seven_day') }
45
46// The weekly window as `06d-18h-44m`, the five-hour one as `03h-33m-24s`: the
47// same width, so the two countdowns line up under each other.
48export const countdown = (resetsAt: string | null | undefined, now: number, withDays = false): string => {
49  if (!resetsAt) return withDays ? '--d---h---m' : '--h---m---s'
50  const total = Math.max(0, Math.floor((Date.parse(resetsAt) - now) / 1000))
51  const two = (n: number) => String(n).padStart(2, '0')
52  const minutes = Math.floor((total % 3600) / 60)
53  // Not `h`: in a .tsx file that name is the JSX factory.
54  if (withDays) return `${two(Math.floor(total / 86400))}d-${two(Math.floor((total % 86400) / 3600))}h-${two(minutes)}m`
55  return `${two(Math.floor(total / 3600))}h-${two(minutes)}m-${two(total % 60)}s`
56}
57
58// "claude-opus-5-5" -> "Opus 5.5"; a name already shown as words is kept.
59export const shortModel = (model: string): string => {
60  const m = /^claude-([a-z]+)-(\d+)(?:-(\d+))?/.exec(model)
61  if (!m) return model
62  return `${m[1].charAt(0).toUpperCase()}${m[1].slice(1)} ${m[2]}${m[3] ? `.${m[3]}` : ''}`
63}
64
65async function setModel($: EngineInterface, next: Partial<Model>) {
66  let changed: Model | null = null
67  await update($, modelAtom, (current: Model | undefined) => {
68    const base = current ?? { name: null, effort: null }
69    const merged = { name: next.name ?? base.name, effort: next.effort ?? base.effort }
70    if (merged.name === base.name && merged.effort === base.effort) return base
71    changed = merged
72    return merged
73  })
74  if (changed) await $.store.set('model', changed)
75}
76
77// A window whose reset has passed is empty: 0% until the next request starts a
78// new one and a response reports its reset.
79export const resetExpired = (usage: Usage | null, now: number): Usage | null => {
80  if (!usage) return null
81  const live = (w: Window | null) =>
82    w?.resetsAt && Date.parse(w.resetsAt) <= now ? { percentUsed: 0, resetsAt: null } : w
83  return { fiveHour: live(usage.fiveHour), sevenDay: live(usage.sevenDay) }
84}
85
86// A reading names only the windows it has; one it leaves out keeps its last value.
87export const mergeUsage = (current: Usage | null | undefined, limits: readonly SessionRateLimit[]): Usage | null => {
88  const fresh = toUsage(limits)
89  if (!fresh) return current ?? null
90  return { fiveHour: fresh.fiveHour ?? current?.fiveHour ?? null, sevenDay: fresh.sevenDay ?? current?.sevenDay ?? null }
91}
92
93const sameWindow = (a: Window | null | undefined, b: Window | null | undefined) =>
94  (a?.percentUsed ?? null) === (b?.percentUsed ?? null) && (a?.resetsAt ?? null) === (b?.resetsAt ?? null)
95
96export const sameUsage = (a: Usage | null | undefined, b: Usage | null | undefined): boolean =>
97  sameWindow(a?.fiveHour, b?.fiveHour) && sameWindow(a?.sevenDay, b?.sevenDay)
98
99async function setUsage($: EngineInterface, limits: readonly SessionRateLimit[]) {
100  if (limits.length === 0) return
101  let merged: Usage | null = null
102  await update($, usageAtom, (current: Usage | null | undefined) => {
103    const next = mergeUsage(current, limits)
104    // An unchanged reading leaves the atom and the store alone.
105    if (sameUsage(current, next)) return current ?? null
106    return (merged = next)
107  })
108  if (merged) await $.store.set('usage', merged)
109}
110
111// session.measure is raised only when a window moves a whole point, so a new
112// reset time at the same percent (a window that reset and started again) never
113// reaches it: after each turn the band reads the session's latest reading too.
114async function refreshUsage($: EngineInterface) {
115  const { rateLimits } = await $.session.usage()
116  await setUsage($, rateLimits)
117}
118
119// The person's userConfig values (plugin.json), checked: a colour that is not
120// a theme key, a colour name or hex falls back to its default.
121export type Settings = {
122  showModel: boolean
123  spriteColor: string
124  spriteRgb: Rgb
125  low: string
126  mid: string
127  high: string
128  empty: string
129}
130
131const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i
132const COLOR = /^([a-z]+|#[0-9a-f]{3}|#[0-9a-f]{6})$/i // a theme key, a colour name, or hex
133
134const toRgb = (hex: string): Rgb | null => {
135  const m = HEX.exec(hex.trim())
136  if (!m) return null
137  const digits = m[1].length === 3 ? [...m[1]].map(d => d + d).join('') : m[1]
138  return [0, 2, 4].map(i => parseInt(digits.slice(i, i + 2), 16)) as Rgb
139}
140
141const textColor = (value: unknown, fallback: string): string =>
142  typeof value === 'string' && COLOR.test(value.trim()) ? value.trim() : fallback
143
144export const settings = (options: PluginOptions): Settings => {
145  const parsed = typeof options.sprite_color === 'string' ? toRgb(options.sprite_color) : null
146  const custom = parsed && parsed.join() !== CLAUDE_ORANGE.join() ? parsed : null
147  const spriteRgb = custom ?? CLAUDE_ORANGE
148  return {
149    showModel: options.show_model !== false,
150    // The text logo shown while a question is open: the theme's own Claude
151    // colour unless the sprite has one of its own.
152    spriteColor: custom ? `#${custom.map(c => c.toString(16).padStart(2, '0')).join('')}` : 'claude',
153    spriteRgb,
154    low: textColor(options.bar_color_low, 'success'),
155    mid: textColor(options.bar_color_mid, 'warning'),
156    high: textColor(options.bar_color_high, 'error'),
157    empty: textColor(options.bar_color_empty, 'inactive'),
158  }
159}
160
161// Set by register from the person's options; a change there reloads the module.
162let config = settings({})
163let frames = FRAMES
164
165export const barColor = (percent: number, colors: Settings = config) =>
166  percent >= 85 ? colors.high : percent >= 60 ? colors.mid : colors.low
167
168// The timer reads these between draws; a reload starts them over.
169const live: {
170  pose: Pose
171  isWorking: boolean
172  frame: number
173  bandId: string | null
174  isStarted: boolean
175  isAsking: boolean
176  sessionId: string | null
177  resetKey: string | null
178  resetTries: number
179  resetAt: number
180} = {
181  pose: 'idle',
182  isWorking: false,
183  frame: 0,
184  bandId: null,
185  isStarted: false,
186  isAsking: false,
187  sessionId: null,
188  resetKey: null,
189  resetTries: 0,
190  resetAt: 0,
191}
192
193const shown = (): Pose => (live.isWorking ? live.pose : 'idle')
194
195async function setPose($: EngineInterface, next: Pose) {
196  if (next === live.pose) return
197  live.pose = next
198  live.frame = 0
199  await update($, poseAtom, () => next)
200}
201
202async function tick($: EngineInterface) {
203  live.frame += 1
204  // Frozen while a question dialog is open: frame swaps kept it from showing as a menu.
205  if (!live.bandId || live.isAsking) return
206  const poseFrames = frames[shown()]
207  const source = { rgba: poseFrames[live.frame % poseFrames.length], width: PIXEL_WIDTH, height: PIXEL_HEIGHT }
208  try {
209    await $.ui.blit({ requestId: live.bandId, key: 'clawd', source })
210  } catch {
211    // The band was taken down between draws; the next render places it again.
212  }
213}
214
215const USAGE_WINDOWS = ['five_hour', 'seven_day']
216
217// The account usage endpoint (what /usage reads): `{ five_hour: { utilization,
218// resets_at }, seven_day: { ... } }`, utilization in percent, a window null
219// while none is open.
220export const parseAccountUsage = (text: string): SessionRateLimit[] => {
221  let body: Record<string, { utilization?: unknown; resets_at?: unknown } | null>
222  try {
223    body = JSON.parse(text)
224  } catch {
225    return []
226  }
227  if (!body || typeof body !== 'object') return []
228  return USAGE_WINDOWS.flatMap(kind => {
229    const w = body[kind]
230    if (!w || typeof w.utilization !== 'number') return []
231    const reset = typeof w.resets_at === 'string' && !Number.isNaN(Date.parse(w.resets_at)) ? w.resets_at : undefined
232    return [{ kind, percentUsed: Math.round(w.utilization * 10) / 10, resetsAt: reset }]
233  })
234}
235
236async function fetchAccountUsage($: EngineInterface): Promise<SessionRateLimit[]> {
237  const auth = await $.session.authorize()
238  if (auth?.kind !== 'bearer') return []
239  // The one request the mod makes: GET, to this address only, with the
240  // person's own sign-in; it sends nothing from the conversation.
241  const res = await $.http.fetch('https://api.anthropic.com/api/oauth/usage', {
242    auth: auth.handle,
243    headers: { 'anthropic-beta': 'oauth-2025-04-20' },
244  })
245  return res.ok ? parseAccountUsage(res.text) : []
246}
247
248// The reset times of the windows that have run out, joined: what one fetch on
249// reset answers. Null while every window still has time left.
250export const expiredKey = (usage: Usage | null | undefined, now: number): string | null => {
251  const gone = [usage?.fiveHour?.resetsAt, usage?.sevenDay?.resetsAt].filter(
252    (r): r is string => !!r && Date.parse(r) <= now,
253  )
254  return gone.length > 0 ? gone.join() : null
255}
256
257const RESET_FIRST_MS = 5_000 // the account has rolled the window over by then
258const RESET_RETRY_MS = 60_000
259const RESET_TRIES = 5
260
261// A window that runs out mid-session: ask the account for the next one, so the
262// countdown fills without waiting for a reply. Until a new reset time arrives,
263// once a minute, five times at most; then the next reply fills it as before.
264async function fetchOnReset($: EngineInterface) {
265  const now = await $.clock.now()
266  const key = expiredKey(await read($, usageAtom), now)
267  if (!key) return
268  if (key !== live.resetKey) {
269    live.resetKey = key
270    live.resetTries = 0
271    live.resetAt = now - RESET_RETRY_MS + RESET_FIRST_MS
272  }
273  if (live.resetTries >= RESET_TRIES || now - live.resetAt < RESET_RETRY_MS) return
274  live.resetTries += 1
275  live.resetAt = now
276  await setUsage($, await fetchAccountUsage($).catch(() => []))
277}
278
279// Rate limits come from response headers and effort from the turn, so a fresh
280// session has neither until its first reply: start from the last ones seen,
281// then ask the account for both windows as they stand now.
282async function loadUsage($: EngineInterface) {
283  const stored = await $.store.get('usage')
284  const now = await $.clock.now()
285  const cached = resetExpired((stored as Usage | undefined) ?? null, now)
286  if (cached) await update($, usageAtom, (current: Usage | null | undefined) => current ?? cached)
287  const { rateLimits } = await $.session.usage()
288  if (rateLimits.length > 0) return setUsage($, rateLimits)
289  await setUsage($, await fetchAccountUsage($).catch(() => []))
290}
291
292async function loadModel($: EngineInterface) {
293  const name = await $.session.model()
294  const stored = await $.store.get('model')
295  const cached = stored as Model | undefined
296  // The stored effort belongs to the stored model; another model may differ.
297  const effort = cached && cached.name === name ? cached.effort : null
298  await setModel($, { name, effort: effort ?? undefined })
299}
300
301// A /clear goes on in the same process under a new session id, with empty
302// $.state and no session.start: a changed id loads usage and model again.
303async function loadSession($: EngineInterface) {
304  let id = ''
305  try {
306    id = await $.session.id()
307  } catch {
308    // An id that cannot be read still loads once.
309  }
310  if (id === live.sessionId) return
311  live.sessionId = id
312  await Promise.all([loadUsage($).catch(() => undefined), loadModel($).catch(() => undefined)])
313}
314
315// Started by whichever hook runs first: a resumed session can load the module
316// without raising session.start, which left the band undrawn until a reload.
317function ensureStarted($: EngineInterface) {
318  if (live.isStarted) return
319  live.isStarted = true
320  $.clock.every(FRAME_MS, () => tick($))
321  $.clock.every(1000, () => {
322    loadSession($).catch(() => undefined)
323    fetchOnReset($).catch(() => undefined)
324    if (!live.isAsking) $.ui.invalidate('ui.render')
325  })
326  $.clock.after(0, () => {
327    loadSession($).catch(() => undefined)
328  })
329  $.ui.invalidate('ui.render')
330}
331
332export const register: Register = (on, options) => {
333  config = settings(options)
334  frames = config.spriteRgb === CLAUDE_ORANGE ? FRAMES : framesFor(config.spriteRgb)
335
336  on('session.start', async ($, e, next) => {
337    const result = await next(e)
338    ensureStarted($)
339    return result
340  })
341
342  on('session.measure', async ($, e, next) => {
343    ensureStarted($)
344    if (e.changed.includes('rateLimits')) await setUsage($, e.rateLimits)
345    return next(e)
346  })
347
348  on('turn.start', async ($, e, next) => {
349    ensureStarted($)
350    await setPose($, 'working')
351    return next(e)
352  })
353
354  // The main thread's stream says when the model is thinking, writing, or
355  // starting a tool call; subagents' streams are passed through untouched.
356  on('turn.step', async function* ($, e, next) {
357    const stream = next(e)
358    if (e.agentId) return yield* stream
359    await setModel($, { name: e.model, effort: e.effort === undefined ? undefined : String(e.effort) })
360    for await (const chunk of stream) {
361      if (chunk.kind === 'thinking') await setPose($, 'thinking')
362      else if (chunk.kind === 'text') await setPose($, 'working')
363      else if (chunk.kind === 'tool') await setPose($, poseFor(chunk.name))
364      yield chunk
365    }
366    return stream.result
367  })
368
369  // Hold the pose while the tool runs (an AskUserQuestion waits on the person).
370  on('tool.call', async ($, e, next) => {
371    const tool = String(e.tool)
372    await setPose($, poseFor(tool))
373    // The band holds still while the question dialog is open (one redraw for
374    // the pose, then no frame swaps or countdown ticks until it closes).
375    const isQuestion = tool === 'AskUserQuestion'
376    if (isQuestion) {
377      live.isAsking = true
378      $.ui.invalidate('ui.render')
379    }
380    try {
381      return await next(e)
382    } finally {
383      if (isQuestion) {
384        live.isAsking = false
385        $.ui.invalidate('ui.render')
386      }
387      await setPose($, 'working')
388    }
389  }).catch(($, e, next) => next(e))
390
391  on('turn.complete', async ($, e, next) => {
392    await setPose($, 'idle')
393    await refreshUsage($).catch(() => undefined)
394    return next(e)
395  })
396
397  // The sprite is the only thing moving: the native spinner draws empty.
398  on('ui.render', { component: 'Spinner' }, ($, e, next) => {
399    ensureStarted($)
400    if (e.surface !== 'terminal') return next(e)
401    const { Box } = $.ui.resolve(e)
402    return <Box />
403  })
404
405  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
406    ensureStarted($)
407    if (e.surface !== 'terminal' || e.props.hasSurvey) {
408      live.bandId = null
409      return next(e)
410    }
411
412    live.bandId = e.requestId
413    live.isWorking = e.props.isWorking
414    live.pose = await read($, poseAtom)
415    const now = await $.clock.now()
416    // A window that resets mid-session drops to 0% on the next tick, not the next reply.
417    const usage = resetExpired(await read($, usageAtom), now)
418    const model = await read($, modelAtom)
419    const { Box, Text, Image } = $.ui.resolve(e)
420
421    const current = shown()
422    const poseFrames = frames[current]
423    const modelName = model.name ? shortModel(model.name) : '--'
424    const caption = model.effort ? `${modelName} ${model.effort}` : modelName
425    const left = config.showModel ? Math.max(SPRITE_COLUMNS + 1, caption.length) : SPRITE_COLUMNS + 1
426    const barWidth = Math.max(4, e.props.bodyColumns - left - 1 - LABEL - PERCENT - RESET)
427
428    const bar = (label: string, window: Window | null | undefined, withDays = false) => {
429      const percent = window?.percentUsed ?? 0
430      const filled = Math.min(barWidth, Math.round((percent / 100) * barWidth))
431      return (
432        <Box flexDirection="row">
433          <Text dimColor>{label} </Text>
434          <Text color={barColor(percent)}>{'█'.repeat(filled)}</Text>
435          <Text color={config.empty}>{'░'.repeat(barWidth - filled)}</Text>
436          <Text dimColor={!window}>{window ? ` ${String(Math.round(percent)).padStart(3)}%` : '   --'}</Text>
437          <Text dimColor> ↻ </Text>
438          <Text bold={!!window?.resetsAt}>{countdown(window?.resetsAt, now, withDays).padStart(RESET - 3)}</Text>
439        </Box>
440      )
441    }
442
443    return (
444      <Box flexDirection="row" alignItems="center">
445        <Box flexDirection="column" width={left} alignItems="center">
446          {live.isAsking ? (
447            // A kitty image sits on a layer above the text and covered the
448            // question menu; while it is open, Clawd is the CLI's text logo.
449            <Box flexDirection="column">
450              <Text color={config.spriteColor}> ▐▛███▜▌ </Text>
451              <Text color={config.spriteColor}>▝▜█████▛▘</Text>
452              <Text color={config.spriteColor}>  ▘▘ ▝▝  </Text>
453            </Box>
454          ) : (
455            <Image
456              key="clawd"
457              source={{ rgba: poseFrames[live.frame % poseFrames.length], width: PIXEL_WIDTH, height: PIXEL_HEIGHT }}
458              columns={SPRITE_COLUMNS}
459              rows={SPRITE_ROWS}
460              alt={ALT[current]}
461            />
462          )}
463          {config.showModel ? (
464            <Box key="model" flexDirection="row">
465              <Text bold>{modelName}</Text>
466              {model.effort ? <Text dimColor> {model.effort}</Text> : null}
467            </Box>
468          ) : null}
469        </Box>
470        <Box flexDirection="column" marginLeft={1}>
471          {bar('7d', usage?.sevenDay, true)}
472          {bar('5h', usage?.fiveHour)}
473        </Box>
474      </Box>
475    )
476  })
477}
478
hooks/sprite.ts 205 lines
1import type { Pose } from '../types'
2
3// Clawd as the CLI prints it at startup (▐▛███▜▌ / ▝▜█████▛▘ / ▘▘ ▝▝): a
4// quadrant is twice as tall as wide, so each logo pixel is drawn here as one
5// column by two rows of square art pixels. The body sits at the bottom of the
6// canvas; the rows above it and the columns beside it hold the props.
7export const ART_WIDTH = 28
8export const ART_HEIGHT = 14
9export const SCALE = 5
10export const PIXEL_WIDTH = ART_WIDTH * SCALE
11export const PIXEL_HEIGHT = ART_HEIGHT * SCALE
12
13export type Rgb = [number, number, number]
14
15export const CLAUDE_ORANGE: Rgb = [215, 119, 87]
16
17const COLORS: Record<string, Rgb> = {
18  '#': CLAUDE_ORANGE, // the body, replaced by the sprite_color option
19  w: [235, 232, 225], // thought dots, speed lines, ink
20  y: [240, 190, 60], // pencil, "?"
21  k: [70, 60, 55], // pencil tip, glass handle
22  b: [240, 236, 226], // book pages
23  l: [150, 120, 100], // book spine
24  g: [170, 200, 220], // magnifying glass
25}
26
27type Grid = string[][]
28
29const blank = (): Grid => Array.from({ length: ART_HEIGHT }, () => Array<string>(ART_WIDTH).fill('.'))
30
31// Paints a pattern at (x, y): a space leaves the pixel, a dot clears it.
32const stamp = (g: Grid, pattern: string[], x: number, y: number): Grid => {
33  pattern.forEach((row, r) =>
34    row.split('').forEach((ch, c) => {
35      const gy = y + r
36      const gx = x + c
37      if (ch === ' ' || gy < 0 || gy >= ART_HEIGHT || gx < 0 || gx >= ART_WIDTH) return
38      g[gy][gx] = ch
39    }),
40  )
41  return g
42}
43
44const fill = (w: number, h: number, ch = '#'): string[] => Array.from({ length: h }, () => ch.repeat(w))
45
46type Arm = 'out' | 'up' | 'down' | 'none'
47
48type Body = {
49  y?: number
50  eyes?: 'open' | 'shut' | 'left' | 'right' | 'down'
51  left?: Arm
52  right?: Arm
53  legs?: 'stand' | 'stride' | 'long'
54}
55
56const X = 5 // the body's left edge, arms included
57
58const body = ({ y = 4, eyes = 'open', left = 'out', right = 'out', legs = 'stand' }: Body = {}): Grid => {
59  const g = blank()
60  stamp(g, fill(12, 8), X + 3, y)
61
62  const eyeRows = eyes === 'down' ? [y + 3] : [y + 2, y + 3]
63  const shift = eyes === 'left' ? -1 : eyes === 'right' ? 1 : 0
64  if (eyes !== 'shut') for (const r of eyeRows) for (const c of [X + 5, X + 12]) g[r][c + shift] = '.'
65
66  const arm = (side: Arm, col: number) => {
67    if (side === 'out') stamp(g, fill(2, 2), col, y + 4)
68    if (side === 'up') stamp(g, fill(2, 5), col, y - 1)
69    if (side === 'down') stamp(g, fill(2, 2), col, y + 6)
70  }
71  arm(left, X + 1)
72  arm(right, X + 15)
73
74  const feet = [X + 4, X + 6, X + 11, X + 13]
75  const spread = [X + 3, X + 7, X + 10, X + 14]
76  for (const c of feet) stamp(g, ['#'], c, y + 8)
77  for (const c of legs === 'stride' ? spread : feet) stamp(g, ['#'], c, y + 9)
78  if (legs === 'long') for (const c of spread) stamp(g, ['#'], c, y + 10)
79  return g
80}
81
82// Idle: stands, blinks now and then.
83const stand = body()
84const idle = [stand, stand, stand, stand, stand, body({ eyes: 'shut' })]
85
86// Thinking: a hand on the head, scratching, and a thought bubble rising.
87const scratch = (handX: number, dots: number): Grid => {
88  const g = body({ eyes: 'left', right: 'up' })
89  stamp(g, ['###'], handX, 3)
90  if (dots >= 1) stamp(g, ['w'], 6, 2)
91  if (dots >= 2) stamp(g, ['w'], 4, 1)
92  if (dots >= 3) stamp(g, ['ww', 'ww'], 1, 0)
93  return g
94}
95const thinking = [scratch(17, 1), scratch(16, 2), scratch(17, 3), scratch(16, 3)]
96
97// Questioning: a "?" that bobs beside the head.
98const QUESTION = [' yyy ', 'y   y', '    y', '   y ', '  y  ', '     ', '  y  ']
99const asking = (y: number): Grid => stamp(body({ eyes: 'right' }), QUESTION, 22, y)
100const questioning = [asking(0), asking(0), asking(1), asking(1)]
101
102// Working: both arms pumping.
103const working = [body({ left: 'up', right: 'up' }), stand, body({ left: 'down', right: 'down' }), stand]
104
105// Reading: a book held up, the eyes running along the line, then a page turns.
106const BOOK = fill(5, 4, 'b').map(r => `${r}ll${r}`)
107const reader = (eyes: Body['eyes'], turning = false): Grid => {
108  const g = stamp(body({ eyes }), BOOK, X + 3, 8)
109  if (turning) stamp(g, ['  bbbb', ' bbbb'], X + 10, 6)
110  return g
111}
112const reading = [reader('left'), reader('open'), reader('right'), reader('down', true)]
113
114// Writing: a pencil in the right hand, leaving a line of ink as it moves.
115const PENCIL = ['y   ', ' y  ', '  y ', '   k']
116const writer = (step: number): Grid => {
117  const g = body({ eyes: 'down' })
118  const px = 21 + step
119  stamp(g, ['#'.repeat(step + 1)], 21, 8)
120  stamp(g, PENCIL, px, 9)
121  stamp(g, ['w'.repeat(px + 3 - 21)], 21, 13)
122  return g
123}
124const writing = [writer(0), writer(1), writer(2), writer(2)]
125
126// Running: a stride, then a bounce with the legs out, speed lines behind.
127const runA = stamp(stamp(body({ legs: 'stride', left: 'up', right: 'down' }), ['www'], 0, 6), ['ww'], 1, 10)
128const runB = stamp(stamp(body({ y: 3, legs: 'long', left: 'down', right: 'up' }), ['ww'], 1, 5), ['www'], 0, 9)
129const running = [runA, runB]
130
131// Searching: a magnifying glass held up on one side, then the other.
132const GLASS = [' ggg ', 'g   g', 'g   g', 'g   g', ' ggg ']
133const glassRight = stamp(stamp(body({ eyes: 'right', right: 'none' }), GLASS, 22, 0), ['k', '#', '##'], 22, 5)
134const glassLeft = stamp(stamp(body({ eyes: 'left', left: 'none' }), GLASS, 1, 0), [' k', ' #', '##'], 4, 5)
135const searching = [glassRight, glassRight, glassLeft, glassLeft]
136
137// Delegating: waving a small Clawd off on its errand.
138const MINI = ['.###.', '#####', '.###.', '.#.#.']
139const waver = (handX: number, miniX: number, miniY: number): Grid => {
140  const g = body({ left: 'up', eyes: 'right' })
141  stamp(g, ['##'], handX, 2)
142  return stamp(g, MINI, miniX, miniY)
143}
144const delegating = [waver(5, 22, 10), waver(4, 23, 9)]
145
146const ART: Record<Pose, Grid[]> = {
147  idle,
148  thinking,
149  questioning,
150  working,
151  reading,
152  writing,
153  running,
154  searching,
155  delegating,
156}
157
158const toBase64 = (art: Grid, colors: Record<string, Rgb>): string => {
159  const px = new Uint8Array(PIXEL_WIDTH * PIXEL_HEIGHT * 4)
160  for (let y = 0; y < PIXEL_HEIGHT; y++) {
161    const row = art[Math.floor(y / SCALE)]
162    for (let x = 0; x < PIXEL_WIDTH; x++) {
163      const rgb = colors[row[Math.floor(x / SCALE)]]
164      if (!rgb) continue
165      const i = (y * PIXEL_WIDTH + x) * 4
166      px[i] = rgb[0]
167      px[i + 1] = rgb[1]
168      px[i + 2] = rgb[2]
169      px[i + 3] = 255
170    }
171  }
172  return px.toBase64()
173}
174
175// Every frame encoded once at load, so a tick only swaps a string.
176export const framesFor = (body: Rgb): Record<Pose, string[]> => {
177  const colors = { ...COLORS, '#': body }
178  const encode = (art: Grid) => toBase64(art, colors)
179  return {
180    idle: ART.idle.map(encode),
181    thinking: ART.thinking.map(encode),
182    questioning: ART.questioning.map(encode),
183    working: ART.working.map(encode),
184    reading: ART.reading.map(encode),
185    writing: ART.writing.map(encode),
186    running: ART.running.map(encode),
187    searching: ART.searching.map(encode),
188    delegating: ART.delegating.map(encode),
189  }
190}
191
192export const FRAMES = framesFor(CLAUDE_ORANGE)
193
194export const ALT: Record<Pose, string> = {
195  idle: 'Clawd resting',
196  thinking: 'Clawd thinking',
197  questioning: 'Clawd asking',
198  working: 'Clawd working',
199  reading: 'Clawd reading',
200  writing: 'Clawd writing',
201  running: 'Clawd running a command',
202  searching: 'Clawd searching the web',
203  delegating: 'Clawd handing off to a subagent',
204}
205
types/index.d.ts 23 lines
1export type Pose =
2  | 'idle'
3  | 'thinking'
4  | 'questioning'
5  | 'working'
6  | 'reading'
7  | 'writing'
8  | 'running'
9  | 'searching'
10  | 'delegating'
11
12export type Window = { percentUsed: number; resetsAt: string | null }
13
14export type Model = { name: string | null; effort: string | null }
15
16export type Usage = { fiveHour: Window | null; sevenDay: Window | null }
17
18declare module 'claude-code' {
19  interface PluginState {
20    'clawd-band': { pose: Pose; usage: Usage | null; model: Model }
21  }
22}
23