SLOPSHOPPER

Band

Status band, Log pane and Progress pane for Claude Code: draws the session's account, cache, context, rate and model figures above the prompt, and the event…

panebandguardcommandtoastprompt
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · band
│ ┃ Log ✕ › fix the failing auth test and add an audit log call │ ┃ 08:53 band session start · band unknow │ ┃ 08:53 band model claude-opus-5-5 ⏺ 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 │ │ › /band-log │ ⎿ band: Log pane opened. │ │ ──────────────────────────────────────────────────────────────────────────────────────────────────── cache 60m │ opus-5-5 ▾ │ ctx 49% │ 5h 31% │ [ Compact ] [ Clear ] [ Log ] ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
──────────────────────────────────────────────────────────────────────────────────────────────────── cache 60m │ opus-5-5 ▾ │ ctx 49% │ 5h 31% │ [ Compact ] [ Clear ] [ Log ]
Pane · Log
08:53 band session start · band unknown 08:53 band model claude-opus-5-5
Pane · band-progress
no task checklist
README

band

Band is a Claude Code plugin that draws a status row, a task checklist and an event log around the prompt. It only draws; it has no other job. To install it, see Quick install (Claude Code) in the root README.

Band draws three things:

  • The status band above the prompt. It shows the account the session runs on (work or personal), the prompt-cache countdown, the model, the context use, every rate-limit window, the session's cost and the task digest. It also holds the Compact, Clear, Progress and Log buttons.
  • The Progress pane, which shows the task checklist.
  • The event log pane, which lists what the plugins did.

The figures come from the session itself. The checklist and most log lines come from the other plugins in this marketplace, which publish them through $.state. base publishes the resolved task and its own events. slim publishes its compression events. The team plugins on base (fe, qa, be, pm) publish their own start, install and doctor lines. Band reads these lines; it never writes another plugin's state.

Current release: band v0.15.0.

Status

  • Band runs on Claude Code only. It is a hooks module (mods), and other hosts do not run hooks modules. Band ships no Cursor, Codex or OpenCode adapter, and scripts/install.sh --plugin band exits 2.
  • Band works alone. With base, it adds the task digest, the Progress pane and base's log lines. With slim, it adds slim's log lines. With a team plugin (fe, qa, be, pm), it adds that plugin's log lines. None of these plugins is a dependency.
  • The drawing shows in the terminal and in the desktop app's Code tab. Some surfaces draw nothing: a cloud session, the VS Code chat panel and claude -p. There the hooks still run, and /band-log and /band-progress answer as text.

Install

/plugin install band@domaine

To choose which plugins to install for which work, use the matrix in the root README.

Status band

The band is one row, with the most important segment first. This example has 200 columns, a work login (Claude Team), context at 47 %, three rate windows (the two weekly ones share one reset time), and base resolving a task:

────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
work │ cache 42m │ fable-5-1 ▾ │ ctx 47% │ 5h 61% ↻2h05m · 7d 34% · 7d·fable 12% ↻3d4h │ cost $12.40 │ ELC-1591 3/5 ▶ Preview themes for QA review │ [ Compact ]  [ Clear ]  [ Progress ]  [ Log ]

The same session at 120 columns: the row needs 194 cells, so band drops the Log button first, then Clear, then the reset times, then the account, then the digest:

cache 42m │ fable-5-1 ▾ │ ctx 47% │ 5h 61% · 7d 34% · 7d·fable 12% │ cost $12.40 │ [ Compact ]  [ Progress ]

When the band appears. Band draws the row as soon as it holds one figure. At launch it reads the model (the one the settings name, until the first response), the cache TTL and the first usage figures in its session start hook, so the row shows within a second. A /clear opens a new session id. The host keeps plugin state per session id, so every band figure starts empty again, and no session start hook runs. Band reads the same three things, and the account, again a second after the session end a /clear fires, so the row returns within a second. band registers no classic hook: on a Claude Team login the host withholds every classic event from plugins. The 30 s refresh stays the fallback. What only the host's SessionStart event carries on a resume or fork (the time since the last response) reaches band through a command hook, hooks/resume.cjs, which writes it to <log dir>/<session-id>/band-resume.json; the next refresh applies it.

At 60 columns, band also drops the rate windows (the least full one first) and then the model:

cache 42m │ ctx 47% │ [ Compact ]  [ Progress ]

Band drops segments in this order:

  1. The Log button (/band-log still opens the pane).
  2. The Clear button (/clear still works).
  3. The rate windows' reset times (the hover card still names them).
  4. The account.
  5. The digest.
  6. The cost.
  7. The rate windows other than the fullest one, the least full first.
  8. The last rate window.
  9. The model.
  10. The Progress button.

Band never drops cache, ctx or Compact. As a backstop, the row's text truncates, so the band never takes a second row.

SegmentShowsRule
accountwork, personalWhich claude.ai login the session runs on, for a Mac with two (a personal plan in ~/.claude, a company Team in another CLAUDE_CONFIG_DIR). work is a Claude Team or Enterprise organization; personal is any other plan (Max, Pro, free). It comes from the login record the host writes: oauthAccount.organizationType in <CLAUDE_CONFIG_DIR>/.claude.json, or ~/.claude.json when CLAUDE_CONFIG_DIR is unset. A record without oauthAccount falls back to the claude.ai profile endpoint (/api/oauth/profile), asked once per session and never awaited by the band. No claude.ai login (an API key, Bedrock, Vertex, a gateway), a login with no plan, or a failed read: no segment, silently. Read at session start and again every 5 min, so a later /login, or one that switches the account mid-session, shows up; a /clear reads it anew. A ~/ in CLAUDE_CONFIG_DIR stands for HOME; any other relative value is never taken for HOME's record, so only the profile endpoint can name the account. A dim word on the terminal, a glyph on the desktop (🏢 work, 🏠 personal). The hover card reads account: work (Claude Team) · email: … · org: … · role: … · config: ~/.claude-cloudcon · source: login record, with models: opus, sonnet, haiku (fable needs credits) before config while the picker hides a family. BAND_ACCOUNT hides it (0) or forces the word (work, personal; the card then says forced by BAND_ACCOUNT).
cachecache 42m, <1m, cache cold, cache —, cache ●Minutes left of the prompt cache: the last main-thread response plus the TTL. ● while a turn runs; — before the first response and after /clear or resume; cold once the TTL has passed, after a compaction (one the band learns of from a fill below half keeps it warm: the response that measured it wrote the cache again), or after a /model to another family, which forfeits the cache. A resumed or forked session takes its state from the time since the last response (by the next refresh), cold when the host says the cache likely expired. Hidden while any rate window is at or past 100 %: in overage the TTL is unknown. It is an estimate. The host reports no cache state, only the events it is derived from.
modelfable-5-1, opusThe model id as the session reports it, without the claude- prefix every id carries. Until the first response it shows the model the settings name (opus, fable: a bare alias, as /model saved it; nothing for default or no model key), because until a response binds the session it answers the process default rather than the configured model. The first response (its own model id) replaces it with the id; every later measurement re-reads it, so a switch made any other way shows by the next response. A /clear after a response re-reads the session's id. A /model (typed or from the picker) is caught as the command itself, on every login: the band reads the family from the command's own answer (`Set model to Opus 5.5 … → opus), not from the settings, which can still name the old model at that moment, and shows it until the next response names the id. An alias of the family already shown leaves the id in place. A pick made in the dialog a bare /model opens (no such answer) shows by the next 30 s refresh, which re-reads the settings. The session still answers the old id for a moment after a switch to another family, and the measurements after it ignore that answer: they keep the answered family until the session answers something else. On the terminal it is a picker: the segment reads fable-5-1 ▾ and is a button (hotkey m while the band holds the keyboard: ctrl+x tab, or a click). Pressed, the row folds its figures away and holds the models alone, in place: model fable opus sonnet haiku: the families, not dated ids, since /model <alias> resolves to the family's newest model and the list never dates (plus the session's own id first when no alias stands for it, say a pinned [1m] id), the current one bright and the rest dim, each with its first letter as hotkey (f, o, s, h). A family the login cannot use is left out: one with any id (a [1m] one included) the login record lists in additionalModelOptionsCache that the record's cachedGrowthBookFeatures.tengu_saffron_lattice flag also bills to usage credits (plan-wide, or in its perModel entry for that model; say Fable on a Team plan) while extra usage is unusable there (cachedExtraUsageDisabledReason set, say out_of_credits, or oauthAccount.hasExtraUsageEnabled false), so picking it never opens the host's "runs on usage credits" dialog. A plan that includes the model (Fable on Max: the flag off) keeps it listed. The current model stays listed even then; a record without those keys hides nothing, and so does BAND_ACCOUNT=0, which reads no record. Letters are dealt after that, so each family keeps its own. Tab or a letter picks one; the pick runs /model <alias> as typed, toasts its output and folds the row back, which shows the pick's family once the run succeeds (an id of that family already shown stays) and turns the cache cold for another family. The current model only folds the row; so does the × button at its end (hotkey x: Clear is not drawn while the row is unfolded, so the letter is free), and a turn or /clear` folds it too. The band never grows: its region clips anything drawn outside its own two rows, so no list can pop over the transcript. The desktop app has its own model menu, so there the segment stays text.
ctxctx 47%, ctx —Context-window use. It is — on a fresh session until the first response. Right after a compaction it shows the engine's own count of what was kept over the window (ctx 3%), or — when the engine reported no count; that count holds until a response reports a measured fill, as a reading with no fill (only the window) keeps the last one. A compaction reaches the band two ways: the session.compact chain, and the readings themselves (compact inferred), for a login or a press whose compaction skips the chain (the Claude Team login's builtin security plugin, a Compact press on Claude Code 2.1.289). The engine drops the fill from a compaction until the next response, so a reading that loses its fill outside /clear and resume is applied as a compaction (ctx —, cache cold); a measured fill below half of the last one (from at least 20k tokens, or 5 % over the same window where a count is missing) is one whose fill-less moment no reading caught, and is only logged, the new fill standing as the ctx value. Reports within 30 s of each other are one compaction, whichever way they came, and after a compaction no reading is read as another until one reports a fill. The readings are a heuristic: a rewind (Esc Esc) that drops half the context reads as a compaction too. Mid-turn it refreshes on a 30 s tick.
rates5h 61% ↻2h05m · 7d 34% · 7d·fable 12% ↻3d4hEvery window the host measures, in its order, then each window the claude.ai usage endpoint (/api/oauth/usage, the one /usage reads) adds, separated by a dim ·. The host's measurement wins a window both report; the endpoint adds the per-model weekly windows the measurement never carries (7d·sonnet, 7d·fable). On the desktop app the measurement reports no window at all, so there the endpoint supplies every one. band asks the endpoint at most once per 5 min (after a failure too), on a claude.ai login only: an API key, Bedrock, Vertex or a gateway gets none, and CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC blocks the request. A failed request (or one unanswered after 10 s) keeps the last good windows, silently, until a window passes its reset time; logging out of claude.ai drops them. five_hour → 5h, seven_day → 7d, spend_limit → $; an unknown kind keeps a shortened raw name (7d·fable); past 100 % reads >100%. A window the API gives a reset time trails it dim after the percentage: ↻42m, ↻2h05m, ↻3d4h. Adjacent windows whose resets lie within 60 s of each other (the weekly 7d and the per-model 7d·… windows reset together) show it once, after the last of them: 7d 34% · 7d·fable 12% ↻3d4h; each window's hover card still names its own. The labels keep their prefix, so 7d·fable always reads as a weekly window. The reset times are the first figures to go on a narrow row (after the Log and Clear buttons). Empty off a subscription and before the first reading.
costcost $12.40Opt-in: drawn only with BAND_COST=1 in the session's environment. What the session has cost at API prices, as /cost totals it (usage().cost.usd). A subscription is not billed per request, so there it is a measure of work, not a bill. Hidden while it is zero and where the host keeps no ledger.
digestELC-1591 3/5 ▶ Preview themesThe task base resolved, same on the terminal and the desktop: work id · checked/total rows of the workspace's progress.md · the current row as base writes it (cut to 28 characters); ELC-1591 ✓ 5/5 when all are done; the bare id (ELC-1588) while the workspace has no progress.md yet, or while the ticket you named has no workspace at all. Hidden while the Progress pane is open, when base resolves nothing, and without base.
Compact[ Compact ], c: CompactAlways drawn first and always pressable, so the other buttons never shift: before the first reading, while a turn runs and at any context. From 80 % between turns it switches to the accent color. While the band holds the keyboard it reads c: Compact. A press runs /compact and toasts the result (compacted 412,000 → 38,000 tokens, or why it was skipped or refused). When the prompt cache is cold or ends within 5 min, the press first asks Compact / Clear / Cancel through the engine's own dialog (Prompt cache is cold or ends within 5 min: compacting re-reads the whole conversation at full price. If this session is done, Clear is cheaper. Compact anyway?); Clear runs /clear without the second Yes/No, a dismissed dialog is a Cancel. A typed /compact never asks. Where the engine refuses compaction from a plugin (a headless / SDK session such as the desktop app), the press runs the /compact slash command as if typed instead and toasts its output. Pressed while a turn runs it only toasts turn is running — press Compact again when it ends; nothing is queued. While base reports the task workspace stale (unless BASE_AUTOSAVE=0), a press or a typed /compact runs /base:save-task-context first, then the /compact slash command, so the compaction waits for the save's turn; a press toasts saved, then and the command's output. The compaction always follows, as the person asked for it: when the save fails it toasts save failed (<reason>) — compacted anyway, and when base still reports the workspace stale after the save's turn (the turn wrote nothing, or wrote another task's workspace than the one base watches) it toasts <work id> still stale after the save — compacted anyway instead of saved, then …; a typed /compact toasts only these two. One save-then-compact chain runs at a time: a second press while one is still running only toasts compact already queued, and a typed /compact then answers the same.
Clear[ Clear ], x: ClearRuns /clear behind the engine's own Yes/No dialog (Clear the conversation?), always: the dialog takes the keyboard, so a stray click or hotkey never clears, and a dismissed dialog is a No. Toasts the command's output. Pressed while a turn runs it only toasts turn is running — press Clear again when it ends. Dim at rest, x: Clear while the band holds the keyboard.
Progress[ Progress ], p: ProgressDrawn only while base resolves a task (its base.progress carries a work id). Opens or closes the Progress pane; dim at rest, p: Progress while the band holds the keyboard
Log[ Log ], l: LogDrawn only while some event list (band's, base's, slim's or a team plugin's: fe's, qa's, be's, pm's) holds a line. Opens or closes the event log pane; dim at rest, l: Log while the band holds the keyboard

Look. On a terminal, a dim rule (────) separates the band from the transcript above it. The desktop frames its panel itself, so band draws no rule there. On the desktop, the buttons sit on a second row under the figures, left-aligned, with an empty row between the two rows and padding around the panel. The reason: the desktop's native buttons are tall, and in the figures' row they squashed the row and sat far right. The terminal keeps one row, because height is the scarce space there. Each figure is a dim label and a bold value (cache dim, 42m bold; the same for ctx and each rate window). The account word is dim, with no value. The model id is plain; on the terminal it carries the picker's ▾ mark. The digest's work id is bold, and the separators are dim.

Colors. Up to 30 %, ctx is green (the theme's success) and the rate windows are plain. Above 30 %, both use the theme's warning color, and from 80 % they use the alarm look. The cache is plain at 10 min or more, warning below 10 min, and the alarm below 2 min. A 5 min TTL scales both limits: warning below 2 min and the alarm below 24 s. Band uses only theme keys, so the band follows light, dark and high-contrast themes. The alarm look is warning + bold + inverse until a dedicated error key is proven to draw on every theme.

Desktop and hover. In the desktop app's Code tab, every segment carries a glyph instead of a word (🏢 │ ⏱ 42m │ 🤖 fable-5-1 │ 🧠 47% │ ⏳ 5h 61% ↻2h05m · 7d 34% · 7d·fable 12% ↻3d4h │ 💰 $12.40 │ 📋 ELC-1591 3/5 ▶ …). Compact, Clear, Progress and Log are native buttons there. The desktop draws proportional text, so the width rules above do not apply: band drops nothing, and the row clips at the panel's edge. When the pointer rests on the account, the cache, ctx, a rate window or the cost, a one-line card appears. Cards work on the desktop and on terminals that pass the pointer through (kitty, Ghostty, iTerm2, WezTerm; tmux passes none). The cards read: account: personal (Claude Max) · email: me@example.com · config: ~/.claude · source: login record, prompt cache: ~42 min left (estimate: last response + 1 h TTL), context: 47% of 200,000 tokens, 94,000 used, 5h window: 61% used, resets in 2h 05m, session cost: $12.40 at API prices, as /cost counts it (a subscription is not billed per request). The glyph labels, the native buttons and hover still need a live check (desktop and terminal paint).

Toasts. When a rate window first reaches 90 %, one toast shows that window's card for 8 s (5h window: 91% used, resets in 1h 05m). The toast re-arms once every window is back under 90 %, and after /clear. The savings toasts come from slim, not from band (SLIM_TOAST). In fullscreen, toasts sit at the transcript's top-right; otherwise they sit on the notification line under the prompt. Several toasts stack. A click removes a toast, and the pointer over a toast holds it (there is no close button). Toasts never touch the transcript or what the model reads. They keep showing while a pane is open, because a pane is not a dialog and does not hold toasts.

Hotkeys. c, x, p, l and m work only while the band holds the keyboard: after ctrl+x tab or a click on the band. They never fire from the composer, so a typed c stays a c. Band draws the letters only at that time too (c: Compact x: Clear p: Progress l: Log). At rest the buttons read [ Compact ] [ Clear ] [ Progress ] [ Log ], so the band never suggests a key that the composer would swallow. The letters go away again on a press, when a turn starts and on /clear. There is no focus-out event, so Esc alone leaves the letters until the next of those events.

On a terminal, you mainly click the buttons (on pointer-capable terminals) or press ctrl+x tab and then the letter. Esc gives the keyboard back to the prompt. To focus the band with a single chord, rebind abovePrompt:focus (default ctrl+x tab) in ~/.claude/keybindings.json, then press the letter. On the desktop, the buttons are ordinary buttons with no hotkey at all: a desktop draws a hotkey as a badge on its native button, and a click is the way to press it there.

ctrl+x ctrl+a collapses the band. While the band is collapsed, the engine shows one dim line above the prompt: plugin panel hidden · ctrl+x ctrl+a or click to show. That chord or a click on the line brings the band back. The collapsed state belongs to the engine and persists across reloads. The plugin cannot reopen the band by itself, and it does not try.

Debug. /band-debug prints the raw figures behind the band: band.info, the session's usage() answer, the cache state, the usage atom, the usage endpoint's last attempt (endpoint: {"at":…,"ok":true,"status":200,"windows":[{"kind":"seven_day_fable","pct":12}, …]}, or its status or one-line error; never the body), the account atom and its last read (account: {"atom":{…,"hiddenModels":["fable"],"hiddenReason":"out_of_credits","label":"work","source":"login record"},"last":{"mode":"on","at":…,"source":"login record"}}, with hiddenModels the picker families hidden and hiddenReason why, or the last read's one-line error), the task that base resolved (work id and branch, or null), the session root, and the last render's surface and measured columns. When a segment looks wrong on some surface, paste this output.

Progress pane

p: Progress or /band-progress opens a pane with the task that base resolved. The surface decides where the pane goes: beside the transcript in a wide fullscreen terminal, inline otherwise. Esc or a second press closes it.

ELC-1591 · feature/ELC-1591-preview-themes · 3/5
✓ Read the ticket
✓ Plan approved
✓ Header markup
▶ Preview themes for QA review
☐ Steps to Test
- preview theme 141234567890 created for QA
- decision: keep the old toggle behind a setting
- open: confirm the empty-state copy with design

The header shows the work id, the branch and checked/total, in bold. Below it come all rows of progress.md and then the last three - lines of notes.md, dimmed. The row marks are:

  • ✓: a done row, dimmed.
  • ▶: the digest's current row, in bold.
  • ◌: an unchecked row above ▶, dimmed. Such a row waits on someone, not on the queue.
  • ☐: any other row.

A workspace without progress.md shows its id, the branch, one dim line no progress.md yet — /base:save-task-context and the notes tail. A ticket you named that has no workspace shows its id, the branch and no task workspace — /base:save-task-context.

  • Which task. base decides the task, not band. base's resolver (pin, the ticket you named, the branch, the newest progress.md) publishes the result, and band draws it. The order is in base's README.
  • Pinning stays base's command. /base-progress <KEY> pins a task, and /base-progress - clears the pin. /band-progress takes no argument.
  • No task. Band does not draw the Progress button while base resolves nothing or is not installed. /band-progress then answers No task checklist: base resolves no task or is not loaded (/base-progress <KEY> pins one). and opens nothing. If the task goes away
Source 10 files
hooks/mods/register.tsx 20 lines
1// The band hooks module (Claude Code only): the status band, its figures and the Log and Progress panes. band draws
2// and writes only its own atoms; it reads base.*, slim.* and the team plugins' events and never writes them.
3// Each feature file declares its own atoms and keeps its `$` code to itself: the validator follows `$` only within one file.
4import type { Register } from 'claude-code'
5import { registerAccount } from './account.ts'
6import { registerBand } from './band.tsx'
7import { registerChecklist } from './checklist.tsx'
8import { registerInfo } from './info.ts'
9import { registerLog } from './log.tsx'
10import { registerUsage } from './usage.ts'
11
12export const register: Register = (on, options) => {
13  registerInfo(on, options)
14  registerUsage(on, options)
15  registerAccount(on)
16  registerBand(on, options)
17  registerChecklist(on)
18  registerLog(on)
19}
20
hooks/mods/account.ts 172 lines
1// band.account writer: which claude.ai login the session runs on, read from the login record the host writes
2// (`.claude.json` under CLAUDE_CONFIG_DIR, else HOME), else once per process from the OAuth profile endpoint, and
3// the model families that record says the login cannot use. BAND_ACCOUNT=0 reads nothing; `work` / `personal`
4// forces the label and still reads the record for those families. Nothing here draws; the band reads the atom.
5import { atom, read, update } from 'claude-code'
6import type { EngineInterface, On, Timer } from 'claude-code'
7import type { BandAccount } from '../../types'
8import { CLEAR_RESEED_MS, accountLabel, accountMode, creditGate, loginAccount, loginPaths, profileAccount } from './lib.ts'
9import type { AccountFacts, AccountMode } from './lib.ts'
10
11const account = atom({ plugin: 'band', key: 'account' } as const, null)
12
13type $ = EngineInterface
14
15const PROFILE_URL = 'https://api.anthropic.com/api/oauth/profile'
16/** How often the atom is checked: a /login may switch the account, and a /clear empties the atom. */
17const CHECK_MS = 30_000
18/** The login is read again this often: a /login may come later or switch the account mid-session. */
19const RETRY_MS = 5 * 60_000
20const PROFILE_TIMEOUT_MS = 10_000
21
22let mode: AccountMode = 'on'
23/** The profile endpoint's facts: undefined until asked, null while asking or when it gave nothing usable. */
24let profile: AccountFacts | null | undefined
25/** The profile request's state for /band-debug: `not asked`, `asking`, `ok` or why it gave nothing. */
26let profileNote = 'not asked'
27/** The value last written: when set, an empty atom means a /clear emptied it. */
28let known: BandAccount | null = null
29/** The last read, for /band-debug: `at` in clock ms, `error` one line. */
30let attempt: { at: number; source: string; error?: string } | null = null
31let inFlight: Promise<void> | null = null
32
33/** The /band-debug account line's last-read part. */
34export function accountDebug() {
35  return { mode, ...(attempt ?? { at: null }) }
36}
37
38const oneLine = (err: unknown) => (err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200)
39
40/** Asks the profile endpoint once per session, then reads again; never throws, and no read waits on it. */
41async function askProfile($: $, handle: string): Promise<void> {
42  profile = null
43  profileNote = 'asking'
44  let timer: Timer | undefined
45  try {
46    const res = await Promise.race([
47      $.http.fetch(PROFILE_URL, {
48        headers: { 'anthropic-beta': 'oauth-2025-04-20', 'Content-Type': 'application/json' },
49        auth: handle,
50      }),
51      new Promise<never>((_, reject) => {
52        timer = $.clock.after(PROFILE_TIMEOUT_MS, () => reject(new Error('timeout')))
53      }),
54    ]).finally(() => timer?.cancel())
55    if (!res.ok) throw new Error(`status ${res.status}`)
56    profile = profileAccount(JSON.parse(res.text))
57    profileNote = profile === null ? 'no plan or email in the body' : 'ok'
58  } catch (err) {
59    profileNote = oneLine(err)
60  }
61  await inFlight
62  if (profile !== null) await maybeRead($)
63}
64
65/** The login record, `none` (the atom without a login) carrying its credit gate, and why it names no login. */
66async function readRecord($: $) {
67  const where = loginPaths(await $.env.get('HOME'), await $.env.get('CLAUDE_CONFIG_DIR'))
68  let record: unknown
69  let why = 'no login record path'
70  if (where.file !== null) {
71    try {
72      record = JSON.parse(await $.fs.read(where.file))
73      why = 'no oauthAccount'
74    } catch (err) {
75      why = oneLine(err)
76    }
77  }
78  const none = { plan: null, email: null, org: null, role: null, configDir: where.configDir, ...creditGate(record) }
79  return { record, none, why }
80}
81
82/** The login as the record (else the profile endpoint) reports it; sets `attempt`. */
83async function resolve($: $, at: number): Promise<BandAccount | null> {
84  if (mode === 'off') {
85    attempt = { at, source: 'none', error: 'BAND_ACCOUNT=0' }
86    return null
87  }
88  if (mode !== 'on') {
89    const { none } = await readRecord($)
90    attempt = { at, source: 'BAND_ACCOUNT' }
91    return { ...none, label: mode, source: 'BAND_ACCOUNT' }
92  }
93  const auth = await $.session.authorize()
94  if (auth?.kind !== 'bearer') {
95    attempt = { at, source: 'none', error: auth ? 'api-key session' : 'no claude.ai login' }
96    return null
97  }
98  const { record, none, why } = await readRecord($)
99  let facts: AccountFacts | null = loginAccount(record)
100  let source: BandAccount['source'] = 'login record'
101  if (facts === null) {
102    if (profile === undefined) void askProfile($, auth.handle)
103    facts = profile ?? null
104    source = 'profile endpoint'
105  }
106  const label = facts === null ? null : accountLabel(facts.plan)
107  if (facts === null || label === null) {
108    attempt = { at, source: 'none', error: facts === null ? `${why}; profile: ${profileNote}` : 'no plan' }
109    // No segment, but the record's gate still holds for the picker.
110    return none.hiddenModels.length ? { ...none, label: null, source: null } : null
111  }
112  attempt = { at, source }
113  return { ...none, ...facts, label, source }
114}
115
116/** Reads the login and writes the atom; never throws. */
117async function readAccount($: $): Promise<void> {
118  let next: BandAccount | null = null
119  let at = 0
120  try {
121    at = await $.clock.now()
122    next = await resolve($, at)
123  } catch (err) {
124    attempt = { at, source: 'none', error: oneLine(err) }
125  }
126  known = next
127  await update($, account, () => next).catch(() => undefined)
128}
129
130function maybeRead($: $): Promise<void> {
131  inFlight ??= readAccount($).finally(() => {
132    inFlight = null
133  })
134  return inFlight
135}
136
137/** A new read once RETRY_MS has passed since the last, or at once when a /clear emptied a known account. */
138async function recheck($: $): Promise<void> {
139  if (mode === 'off' || inFlight !== null) return
140  const emptied = known !== null && (await read($, account)) === null
141  if (emptied || (await $.clock.now()) - (attempt?.at ?? 0) >= RETRY_MS) await maybeRead($)
142}
143
144export function registerAccount(on: On): void {
145  // One throwing session.start hook skips every band session.start hook: the read never throws.
146  on('session.start', { cwd: /$/ }, async ($, e, next) => {
147    profile = undefined
148    profileNote = 'not asked'
149    try {
150      mode = accountMode(await $.env.get('BAND_ACCOUNT'))
151    } catch {}
152    try {
153      $.clock.every(CHECK_MS, () => {
154        void recheck($).catch(() => undefined)
155      })
156    } catch {}
157    await maybeRead($)
158    return next(e)
159  })
160
161  // /clear starts a new session id with empty state and no session.start; the timer runs in the plugin's
162  // environment and reads into the new session.
163  on('session.end', { reason: /^clear$/ }, async ($, e, next) => {
164    try {
165      $.clock.after(CLEAR_RESEED_MS, () => {
166        void maybeRead($).catch(() => undefined)
167      })
168    } catch {}
169    return next(e)
170  })
171}
172
hooks/mods/band.tsx 450 lines
1// Status band: the AbovePrompt row drawn from the atoms, the Compact and Clear presses (a cold or ending cache asks Compact /
2// Clear / Cancel first) and the terminal's model
3// picker, which unfolds into the row itself: the band region clips anything drawn outside its own rows, so no
4// list can pop over the transcript. A desktop draws the buttons on a second row under the figures.
5// Render only reads: band's atoms (usage.ts, account.ts and checklist.tsx write them), base's task snapshot for the digest and
6// the Progress button, every publisher's event list for the Log button. The Progress and Log presses are
7// answered by the `ui.press` hooks on elements `progress` (checklist.tsx) and `log` (log.tsx). While base reports
8// the task workspace stale, a Compact press or a typed /compact runs base's save-task-context first.
9import { atom, read, update } from 'claude-code'
10import type { EngineInterface, On, PluginOptions, RenderNode } from 'claude-code'
11import type { BandEvent, BandRate, ForeignEvent } from '../../types'
12import {
13  CACHE_INIT,
14  CTX_PROPS,
15  GLYPH,
16  LEVEL_PROPS,
17  MODEL_CLOSE,
18  MODEL_MARK,
19  RULE,
20  SEP,
21  USAGE_INIT,
22  bandSegs,
23  COMPACT_OPTIONS,
24  cacheCard,
25  cells,
26  cacheView,
27  compactQuestion,
28  compactToast,
29  costCard,
30  ctxCard,
31  accountCard,
32  digestOf,
33  glyphText,
34  groupResets,
35  layout,
36  modelOptions,
37  pctLevel,
38  rateCard,
39  rateText,
40  resetMark,
41  splitLabel,
42  toChecklist,
43} from './lib.ts'
44import type { ModelOption } from './lib.ts'
45import { anyEvent, take } from './events.ts'
46import { modelRan } from './usage.ts'
47
48const usage = atom({ plugin: 'band', key: 'usage' } as const, USAGE_INIT)
49const model = atom({ plugin: 'band', key: 'model' } as const, null)
50const cache = atom({ plugin: 'band', key: 'cache' } as const, CACHE_INIT)
51const account = atom({ plugin: 'band', key: 'account' } as const, null)
52const tick = atom({ plugin: 'band', key: 'tick' } as const, 0)
53const paneShown = atom({ plugin: 'band', key: 'paneShown' } as const, false)
54const bandFocused = atom({ plugin: 'band', key: 'bandFocused' } as const, false)
55const modelPicker = atom({ plugin: 'band', key: 'modelPicker' } as const, false)
56const events = atom({ plugin: 'band', key: 'events' } as const, [] as BandEvent[])
57const baseProgress = atom({ plugin: 'base', key: 'progress' } as const, null)
58const baseEvents = atom({ plugin: 'base', key: 'events' } as const, [] as ForeignEvent[])
59const slimEvents = atom({ plugin: 'slim', key: 'events' } as const, [] as ForeignEvent[])
60const feEvents = atom({ plugin: 'fe', key: 'events' } as const, [] as ForeignEvent[])
61const qaEvents = atom({ plugin: 'qa', key: 'events' } as const, [] as ForeignEvent[])
62const beEvents = atom({ plugin: 'be', key: 'events' } as const, [] as ForeignEvent[])
63const pmEvents = atom({ plugin: 'pm', key: 'events' } as const, [] as ForeignEvent[])
64
65type $ = EngineInterface
66
67/** Main-loop turn in flight: turn events flip it, each band draw syncs it; usage.ts clears it, as the engine allows one unmatched turn.complete hook. */
68export const turn = { running: false }
69
70const SAVE = 'base:save-task-context'
71
72/** base's task workspace is stale and BASE_AUTOSAVE is not 0: a compaction now would drop the unsaved findings. */
73async function mustSave($: $): Promise<boolean> {
74  if ((await $.env.get('BASE_AUTOSAVE')) === '0') return false
75  const p = await read($, baseProgress)
76  return p !== null && p.workId !== null && p.stale === true
77}
78
79const errText = (err: unknown) => (err instanceof Error ? err.message : String(err))
80
81/** A Compact press or a typed /compact is running its chain; a second one would queue a second save and compaction. */
82let compactInFlight = false
83
84/**
85 * Saves, then queues /compact behind the save's turn: only a queued command is sure to run after that turn. A failed
86 * save or a workspace base still reports stale never cancels the compaction the person asked for: `note` says why.
87 */
88function saveThenCompact($: $, args: string): Promise<{ text: string; note: string | null }> {
89  const compact = (failed: string | null) =>
90    $.command.run({ command: 'compact', args }).then(async r => {
91      if (failed !== null) return { text: r.text, note: `save failed (${failed}) — compacted anyway` }
92      const p = await read($, baseProgress)
93      const stale = await mustSave($).catch(() => false)
94      return { text: r.text, note: stale ? `${p?.workId} still stale after the save — compacted anyway` : null }
95    })
96  return $.command.run({ command: SAVE }).then(
97    () => compact(null),
98    err => compact(errText(err)),
99  )
100}
101
102function pressCompact($: $): void {
103  if (turn.running) {
104    $.ui.toast('turn is running — press Compact again when it ends')
105    return
106  }
107  if (compactInFlight) {
108    $.ui.toast('compact already queued')
109    return
110  }
111  compactInFlight = true
112  const refused = (err: unknown) => $.ui.toast(`compact refused: ${errText(err)}`)
113  // A headless (SDK, desktop app) session refuses the op but still runs a typed /compact.
114  const compact = () =>
115    $.session.compact().then(
116      r => $.ui.toast(compactToast(r)),
117      () => $.command.run({ command: 'compact' }).then(r => $.ui.toast(r.text || 'compacted'), refused),
118    )
119  const saved = () =>
120    saveThenCompact($, '').then(r => $.ui.toast(r.note ?? `saved, then ${r.text || 'compacted'}`), refused)
121  const go = () => mustSave($).then(stale => (stale ? saved() : compact()), compact)
122  const clear = () => $.command.run({ command: 'clear' }).then(r => $.ui.toast(r.text || 'cleared'), err => $.ui.toast(`clear refused: ${err instanceof Error ? err.message : String(err)}`))
123  // A dismissed dialog rejects: that is a Cancel.
124  const ask = (q: string) => $.ui.ask(q, [...COMPACT_OPTIONS]).then(a => (a === 'Compact' ? go() : a === 'Clear' ? clear() : undefined), () => undefined)
125  Promise.all([read($, cache), $.clock.now()])
126    .then(([c, now]) => {
127      const q = compactQuestion(c, now)
128      return q ? ask(q) : go()
129    }, go)
130    .finally(() => {
131      compactInFlight = false
132    })
133}
134
135const CLEAR_QUESTION = 'Clear the conversation?'
136const CLEAR_YES = 'Yes'
137
138/** Always behind the engine's own Yes/No dialog: it takes the keyboard, so a stray click or hotkey never clears. */
139function pressClear($: $): void {
140  if (turn.running) {
141    $.ui.toast('turn is running — press Clear again when it ends')
142    return
143  }
144  const refused = (err: unknown) => $.ui.toast(`clear refused: ${err instanceof Error ? err.message : String(err)}`)
145  // A dismissed dialog rejects: that is a No.
146  $.ui.ask(CLEAR_QUESTION, [CLEAR_YES, 'No']).then(
147    answer => {
148      if (answer !== CLEAR_YES) return
149      $.command.run({ command: 'clear' }).then(r => $.ui.toast(r.text || 'cleared'), refused)
150    },
151    () => undefined,
152  )
153}
154
155/**
156 * A pick folds the picker and runs `/model <alias>` as typed; once it succeeds the segment shows the pick's family
157 * (an id of that family already shown stays) and another family turns the cache cold. The current one only folds.
158 */
159function pickModel($: $, o: ModelOption): void {
160  void setPicker($, false)
161  if (o.current) return
162  void $.session
163    .model()
164    .catch(() => null)
165    .then(prev =>
166      $.command.run({ command: 'model', args: o.value }).then(
167        async r => {
168          await modelRan($, prev, r.text, o.value).catch(() => undefined)
169          $.ui.toast(r.text || `model ${o.value}`)
170        },
171        err => $.ui.toast(`model refused: ${err instanceof Error ? err.message : String(err)}`),
172      ),
173    )
174}
175
176/** The surface the band last drew on; a desktop has no hotkey letters, so focus moves must not redraw it. */
177let drawnOn: string = 'terminal'
178
179/** The last render's surface and measured props, for /band-debug. */
180export const lastRender: { surface: string | null; bodyColumns: number | undefined; maxRows: number | undefined } = {
181  surface: null,
182  bodyColumns: undefined,
183  maxRows: undefined,
184}
185
186/** Guarded write: a redraw between a click's focus-in and its press would swallow the press. */
187async function setFocused($: $, to: boolean): Promise<void> {
188  if (drawnOn !== 'desktop' && (await read($, bandFocused)) !== to) await update($, bandFocused, () => to)
189}
190
191/** Guarded write, as setFocused; the desktop never unfolds. */
192async function setPicker($: $, to: boolean): Promise<void> {
193  if (drawnOn !== 'desktop' && (await read($, modelPicker)) !== to) await update($, modelPicker, () => to)
194}
195
196export function registerBand(on: On, options: PluginOptions): void {
197  // Hotkey letters are drawn only while the band holds the keyboard. A focus-in sets the flag; a
198  // press, a turn or /clear clears it, as there is no focus-out event. The hotkeys stay armed.
199  on('ui.focus', { component: 'AbovePrompt' }, async ($, e, next) => {
200    if (options.disabled === true) return next(e)
201    await setFocused($, true)
202    return next(e)
203  })
204  // Unfolding the model picker keeps the keyboard on the band: its models take hotkey letters of their own.
205  on('ui.press', { plugin: 'band' }, async ($, e, next) => {
206    if (e.element !== 'model') await setFocused($, false)
207    return next(e)
208  })
209  on('turn.start', async ($, e, next) => {
210    turn.running = true
211    await setFocused($, false)
212    await setPicker($, false)
213    return next(e)
214  })
215  // A typed /compact would compact before a save it awaited could run, and the host refuses $.command.run from this
216  // hook: a stale workspace answers it, and a timer queues the save, then /compact again. band's own runs pass.
217  on('command.run', { command: 'compact' }, async ($, e, next) => {
218    if ((e.origin.kind === 'plugin' && e.origin.name === 'band') || !(await mustSave($).catch(() => false))) return next(e)
219    if (compactInFlight) return { text: 'compact already queued' }
220    compactInFlight = true
221    $.clock.after(1, () => {
222      saveThenCompact($, e.args)
223        .then(r => r.note !== null && $.ui.toast(r.note))
224        .catch(err => $.ui.toast(`compact refused: ${errText(err)}`))
225        .finally(() => {
226          compactInFlight = false
227        })
228    })
229    return { text: 'workspace stale: saving it first, then compacting' }
230  })
231  on('session.end', { reason: 'clear' }, async ($, e, next) => {
232    turn.running = false
233    compactInFlight = false
234    await setFocused($, false)
235    await setPicker($, false)
236    return next(e)
237  })
238
239  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
240    // The engine's own truth: every draw re-aligns a flag a missed turn.complete or a hot reload left wrong.
241    turn.running = e.props.isWorking
242    if (options.disabled === true || e.props.hasSurvey) return next(e)
243    const u = await read($, usage)
244    const m = await read($, model)
245    const c = await read($, cache)
246    const now = await read($, tick)
247    const isPaneShown = await read($, paneShown)
248    const focused = await read($, bandFocused)
249    const unfolded = await read($, modelPicker)
250    const acct = await read($, account)
251    if (u.ctxPct === null && u.rates.length === 0 && m === null && c.anchorMs === null) return next(e)
252
253    const isWorking = e.props.isWorking
254    const snapshot = await read($, baseProgress)
255    const digest = !isPaneShown ? digestOf(snapshot) : null
256    const hasChecklist = toChecklist(snapshot) !== null
257    // Short-circuit: while band's own list holds a line the foreign lists are not read, so their writes do not redraw the band.
258    const hasEvents =
259      take(await read($, events)).length > 0 ||
260      anyEvent(
261        await read($, baseEvents),
262        await read($, slimEvents),
263        await read($, feEvents),
264        await read($, qaEvents),
265        await read($, beEvents),
266        await read($, pmEvents),
267      )
268    const isDesktop = e.surface === 'desktop'
269    drawnOn = e.surface
270    lastRender.surface = e.surface
271    lastRender.bodyColumns = e.props.bodyColumns
272    lastRender.maxRows = e.props.maxRows
273    // A desktop draws proportional text: its bodyColumns do not measure the row, so nothing is dropped there.
274    const segs = layout(bandSegs({ usage: u, model: m, cache: c, nowMs: now, isWorking, digest, hasChecklist, hasEvents, account: acct }), isDesktop ? undefined : e.props.bodyColumns)
275    const { Box, Text, Button } = $.ui.resolve(e)
276
277    const label = (text: string) => (isDesktop ? glyphText(text) : text)
278    // Dim label, bold value (`cache` dim, `42m` bold); a desktop glyph label stays at full strength.
279    const dimLabel = isDesktop ? {} : { dimColor: true }
280    const labeled = (text: string, labelProps: Record<string, unknown>, valueProps: Record<string, unknown>): RenderNode => {
281      const [l, v] = splitLabel(text)
282      return (
283        <Box flexDirection="row">
284          <Text {...labelProps} wrap="truncate-end">
285            {v ? `${l} ` : l}
286          </Text>
287          {v ? (
288            <Text {...valueProps} wrap="truncate-end">
289              {v}
290            </Text>
291          ) : null}
292        </Box>
293      )
294    }
295    const cardMax = e.props.bodyColumns && e.props.bodyColumns > 0 ? e.props.bodyColumns : Infinity
296    // A keyed Box is a hover scope; its hidden child is the card. A surface without a pointer never reveals it.
297    // The card gets its own width: an absolute Box would otherwise shrink to its segment. The terminal clips
298    // it to the segment's columns, so there it pops up a row above, over the rule; the desktop lays it over.
299    const hoverable = (key: string, body: RenderNode, card: string): RenderNode => (
300      <Box key={key}>
301        {body}
302        <Box
303          position="absolute"
304          top={isDesktop ? 0 : -1}
305          left={0}
306          width={Math.min(cells(card), cardMax)}
307          display="none"
308          hover={{ display: 'flex' }}
309        >
310          <Text inverse wrap="truncate-end">
311            {card}
312          </Text>
313        </Box>
314      </Box>
315    )
316    // The reset time trails the bold value, dim, once per group of windows sharing it: rowText measures the same ` ↻2h05m`.
317    const resets = groupResets(segs.rates, segs.resetsNowMs)
318    const rate = (r: BandRate, i: number): RenderNode[] => {
319      const reset = resetMark(resets[i])
320      const pct = labeled(rateText(r), dimLabel, { bold: true, ...LEVEL_PROPS[pctLevel(r.pct)] })
321      const body = reset ? (
322        <Box flexDirection="row">
323          {pct}
324          <Text dimColor wrap="truncate-end">
325            {reset}
326          </Text>
327        </Box>
328      ) : (
329        pct
330      )
331      return [...(i > 0 ? [<Text dimColor> · </Text>] : []), hoverable(`seg-rate-${r.kind}`, body, rateCard(r, now))]
332    }
333
334    // A desktop draws a hotkey as a badge on its native button, and its buttons are clicked: no hotkeys there.
335    const letters = focused && !isDesktop ? { plain: true as const } : null
336    const hot = (k: string) => (isDesktop ? {} : { hotkey: k })
337    const ruleCols = e.props.bodyColumns && e.props.bodyColumns > 0 ? Math.min(e.props.bodyColumns, 400) : 80
338
339    // Unfolded, the row holds the models alone: four names plus letters outgrow a row that also holds the figures.
340    // The current one is at full strength and only folds. Esc reaches no hook (the engine raises no focus-out),
341    // so a close button ends the row; `x` is free here, as Clear is not drawn.
342    if (unfolded && !isDesktop && m !== null) {
343      const options = modelOptions(m, acct?.hiddenModels ?? [])
344      const row: RenderNode[] = [<Text dimColor>model </Text>]
345      options.forEach((o, i) => {
346        if (i > 0) row.push(<Text>{'  '}</Text>)
347        row.push(
348          <Button
349            key={`model:${o.value}`}
350            label={o.label}
351            plain
352            {...(letters && o.hotkey ? { hotkey: o.hotkey } : {})}
353            {...(o.current ? {} : { dimColor: true })}
354            onPress={() => pickModel($, o)}
355          />,
356        )
357      })
358      row.push(<Text>{'  '}</Text>)
359      row.push(<Button key="model-close" label={MODEL_CLOSE} plain {...(letters ? { hotkey: 'x' } : {})} dimColor onPress={() => setPicker($, false)} />)
360      return (
361        <Box flexDirection="column">
362          <Text dimColor>{RULE.repeat(ruleCols)}</Text>
363          <Box flexDirection="row">{row}</Box>
364        </Box>
365      )
366    }
367
368    const groups: RenderNode[][] = []
369    if (segs.account !== null && acct !== null) {
370      const word = isDesktop ? <Text>{GLYPH[segs.account]}</Text> : <Text dimColor>{segs.account}</Text>
371      groups.push([hoverable('seg-account', word, accountCard(acct))])
372    }
373    if (segs.cache !== null) {
374      const level = LEVEL_PROPS[cacheView(c, now, isWorking).level]
375      groups.push([hoverable('seg-cache', labeled(label(segs.cache), dimLabel, { bold: true, ...level }), cacheCard(c, now))])
376    }
377    // The terminal has no model menu of its own in reach, so its segment is the picker's button; the desktop app has one.
378    if (segs.model !== null && m !== null) {
379      groups.push([
380        isDesktop ? (
381          // A bare truncating Text shrinks to nothing on the desktop when the row overflows.
382          <Box key="seg-model" flexDirection="row" flexShrink={0}>
383            <Text>{`${GLYPH.model} ${segs.model}`}</Text>
384          </Box>
385        ) : (
386          <Button key="model" label={`${segs.model}${MODEL_MARK}`} plain {...(letters ? { hotkey: 'm' } : {})} onPress={() => setPicker($, true)} />
387        ),
388      ])
389    }
390    const ctxLevel = u.ctxPct === null ? {} : CTX_PROPS[pctLevel(u.ctxPct)]
391    groups.push([hoverable('seg-ctx', labeled(label(segs.ctx), dimLabel, { bold: true, ...ctxLevel }), ctxCard(u))])
392    if (segs.rates.length) {
393      groups.push([...(isDesktop ? [<Text>{`${GLYPH.rates} `}</Text>] : []), ...segs.rates.flatMap(rate)])
394    }
395    if (segs.cost !== null && u.costUsd !== null) {
396      groups.push([hoverable('seg-cost', labeled(label(segs.cost), dimLabel, { bold: true }), costCard(u.costUsd))])
397    }
398    if (segs.digest !== null) {
399      groups.push([
400        <Box key="seg-digest" flexDirection="row">
401          {isDesktop ? <Text>{`${GLYPH.digest} `}</Text> : null}
402          {labeled(segs.digest, { bold: true }, {})}
403        </Box>,
404      ])
405    }
406    const buttons: RenderNode[] = []
407    const look = letters ?? (segs.compact.plain ? {} : { variant: 'primary' as const })
408    buttons.push(<Button key="compact" label="Compact" {...hot('c')} {...look} onPress={() => pressCompact($)} />)
409    if (segs.clear !== null) {
410      buttons.push(<Text>{'  '}</Text>)
411      buttons.push(<Button key="clear" label="Clear" {...hot('x')} {...(letters ?? { dimColor: true })} onPress={() => pressClear($)} />)
412    }
413    if (segs.progress !== null) {
414      buttons.push(<Text>{'  '}</Text>)
415      buttons.push(<Button key="progress" label="Progress" {...hot('p')} {...(letters ?? { dimColor: true })} onPress={() => {}} />)
416    }
417    if (segs.log !== null) {
418      buttons.push(<Text>{'  '}</Text>)
419      buttons.push(<Button key="log" label="Log" {...hot('l')} {...(letters ?? { dimColor: true })} onPress={() => {}} />)
420    }
421    // A desktop draws native buttons: in the figures' row they squash it and sit far right, so they get a row of
422    // their own below, left-aligned. The terminal keeps one row: its height is the scarce side there.
423    if (!isDesktop) groups.push(buttons)
424
425    const row = groups.flatMap((g, i) => (i === 0 ? g : [<Text dimColor>{SEP}</Text>, ...g]))
426    // No overflow="hidden" here: it would clip the terminal's cards on the rule row above.
427    const rowBox = (
428      <Box flexDirection="row">
429        {row}
430      </Box>
431    )
432    // A dim rule separates the band from the transcript above it; the desktop frames its panel itself.
433    if (isDesktop) {
434      // A row of air between the figures and the buttons, and around the whole, so the panel is not one dense block.
435      return (
436        <Box flexDirection="column" gap={1} padding={1}>
437          {rowBox}
438          <Box flexDirection="row">{buttons}</Box>
439        </Box>
440      )
441    }
442    return (
443      <Box flexDirection="column">
444        <Text dimColor>{RULE.repeat(ruleCols)}</Text>
445        {rowBox}
446      </Box>
447    )
448  })
449}
450
hooks/mods/checklist.tsx 110 lines
1// Progress pane: /band-progress and the band's Progress button toggle it; it draws the task base resolved as the
2// generic checklist (title, subtitle, rows, footer) and never writes base's state. Picking the task stays base's
3// (`/base-progress <KEY>` pins one); band redraws from the subscription.
4import { atom, read, update } from 'claude-code'
5import type { EngineInterface, On } from 'claude-code'
6import type { Checklist, ChecklistMark } from '../../types'
7import { CHECKLIST_COMMAND, CHECKLIST_PANE } from './events.ts'
8import { toChecklist } from './lib.ts'
9
10const paneShown = atom({ plugin: 'band', key: 'paneShown' } as const, false)
11const baseProgress = atom({ plugin: 'base', key: 'progress' } as const, null)
12
13const GLYPH: Record<ChecklistMark, string> = { done: '✓', current: '▶', waiting: '◌', todo: '☐' }
14export const NO_CHECKLIST_TEXT = 'No task checklist: base resolves no task or is not loaded (/base-progress <KEY> pins one).'
15
16type $ = EngineInterface
17
18async function checklist($: $): Promise<Checklist | null> {
19  return toChecklist(await read($, baseProgress))
20}
21
22/** The pane's lines as plain text, for the surfaces that draw no pane. */
23export function checklistText(c: Checklist): string {
24  const head = [c.title, c.subtitle].filter(Boolean).join(' · ')
25  return [head, ...c.rows.map(r => `${GLYPH[r.mark]} ${r.text}`), ...(c.footer ?? [])].join('\n')
26}
27
28/** Only the terminal and the Desktop app draw a mod's panes; elsewhere the checklist goes out as text. */
29async function drawsPanes($: $): Promise<boolean> {
30  return (await $.session.surfaces()).some(s => s === 'terminal' || s === 'desktop')
31}
32
33async function toggle($: $): Promise<string> {
34  if (!(await drawsPanes($))) {
35    const c = await checklist($)
36    return c === null ? NO_CHECKLIST_TEXT : checklistText(c)
37  }
38  if ((await $.ui.panes()).some(p => p.id === CHECKLIST_PANE && p.isShown)) {
39    // The ui.close hook below clears paneShown: this close comes back through it with origin plugin.
40    await $.ui.close({ id: CHECKLIST_PANE })
41    return 'Progress pane closed.'
42  }
43  if ((await checklist($)) === null) return NO_CHECKLIST_TEXT
44  const r = await $.ui.open({ id: CHECKLIST_PANE, title: 'Progress', focus: true, closeOnEscape: true })
45  if (!r.isPlaced) {
46    $.ui.toast(`progress pane not placed: ${r.reason}`)
47    return `Progress pane not placed: ${r.reason}`
48  }
49  await update($, paneShown, () => true)
50  return 'Progress pane opened.'
51}
52
53export function registerChecklist(on: On): void {
54  on('session.start', { cwd: /./ }, async ($, e, next) => {
55    const r = await next(e)
56    try {
57      const shown = (await $.ui.panes()).some(p => p.id === CHECKLIST_PANE && p.isPlaced)
58      await update($, paneShown, () => shown)
59    } catch {}
60    return r
61  })
62
63  on('command.run', { command: CHECKLIST_COMMAND.name }, async $ => ({ text: await toggle($) }))
64
65  // Answers without next, so the band Button's own closure never runs and the pane toggles once.
66  on('ui.press', { plugin: 'band', element: 'progress' }, async ($, e) => {
67    await toggle($)
68    return { element: e.element }
69  })
70
71  on('ui.close', { id: CHECKLIST_PANE }, async ($, e, next) => {
72    const r = await next(e)
73    if (e.origin.kind === 'plugin' || e.origin.kind === 'person') await update($, paneShown, () => false)
74    return r
75  })
76
77  on('ui.render', { component: 'Pane', requestId: CHECKLIST_PANE }, async ($, e) => {
78    const { Box, Text } = $.ui.resolve(e)
79    const c = await checklist($)
80    if (c === null) {
81      return (
82        <Box flexDirection="column" width={e.props.bodyColumns}>
83          <Text dimColor wrap="truncate-end">
84            no task checklist
85          </Text>
86        </Box>
87      )
88    }
89    return (
90      <Box flexDirection="column" width={e.props.bodyColumns}>
91        <Text bold wrap="truncate-end">
92          {[c.title, c.subtitle].filter(Boolean).join(' · ')}
93        </Text>
94        {c.rows.map((row, i) => (
95          <Box key={`row-${i}`}>
96            <Text wrap="truncate-end" dimColor={row.mark === 'done' || row.mark === 'waiting'} bold={row.mark === 'current'}>
97              {`${GLYPH[row.mark]} ${row.text}`}
98            </Text>
99          </Box>
100        ))}
101        {(c.footer ?? []).map(line => (
102          <Text dimColor wrap="truncate-end">
103            {line}
104          </Text>
105        ))}
106      </Box>
107    )
108  })
109}
110
hooks/mods/info.ts 54 lines
1// band.info: the snapshot that tells any plugin that band is loaded, which version, and whether its `disabled`
2// option is on; band's own file lines and /band-debug read the version. Also registers band's slash commands,
3// again after a /clear.
4import type { EngineInterface, On, PluginOptions } from 'claude-code'
5import { CHECKLIST_COMMAND, DEBUG_COMMAND, LOG_COMMAND } from './events.ts'
6
7type $ = EngineInterface
8
9async function version($: $): Promise<string> {
10  try {
11    const v = (JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)) as { version?: unknown }).version
12    return typeof v === 'string' && v ? v : 'unknown'
13  } catch {
14    return 'unknown'
15  }
16}
17
18async function registerCommands($: $): Promise<void> {
19  await $.command.register(LOG_COMMAND).catch(() => undefined)
20  await $.command.register(CHECKLIST_COMMAND).catch(() => undefined)
21  await $.command.register(DEBUG_COMMAND).catch(() => undefined)
22}
23
24export function registerInfo(on: On, options: PluginOptions): void {
25  /** The session the commands were registered for: a /clear starts a new one with no session.start. */
26  let registeredFor: string | null = null
27
28  on('session.start', { cwd: /^/ }, async ($, e, next) => {
29    // One throwing session.start hook skips every band session.start hook: each $ call fails alone.
30    try {
31      await $.state.set({ plugin: 'band', key: 'info' }, { v: 1, version: await version($), disabled: options.disabled === true })
32    } catch {}
33    try {
34      registeredFor = String(await $.session.id())
35    } catch {}
36    await registerCommands($)
37    return next(e)
38  })
39
40  // band's one matcherless prompt.submit: a module holds at most one.
41  on('prompt.submit', async ($, e, next) => {
42    const r = await next(e)
43    let sid: string | null = null
44    try {
45      sid = String(await $.session.id())
46    } catch {}
47    if (sid !== null && sid !== registeredFor) {
48      await registerCommands($)
49      registeredFor = sid
50    }
51    return r
52  })
53}
54
hooks/mods/log.tsx 106 lines
1// Event log pane: /band-log and the band's Log button toggle it; it draws band's own lines merged with base's, slim's
2// and the team plugins' straight from their state (a plugin not loaded adds nothing), and never writes any of them.
3import { atom, read } from 'claude-code'
4import type { EngineInterface, On } from 'claude-code'
5import type { BandEvent, ForeignEvent, LogLine } from '../../types'
6import { LOG_COMMAND, LOG_PANE, PREFIX_COLS, TEXT_LOG_ROWS, hhmm, kindCell, logDir, logRow, merged, newestFitting, pluginCell } from './events.ts'
7
8const events = atom({ plugin: 'band', key: 'events' } as const, [] as BandEvent[])
9const baseEvents = atom({ plugin: 'base', key: 'events' } as const, [] as ForeignEvent[])
10const slimEvents = atom({ plugin: 'slim', key: 'events' } as const, [] as ForeignEvent[])
11const feEvents = atom({ plugin: 'fe', key: 'events' } as const, [] as ForeignEvent[])
12const qaEvents = atom({ plugin: 'qa', key: 'events' } as const, [] as ForeignEvent[])
13const beEvents = atom({ plugin: 'be', key: 'events' } as const, [] as ForeignEvent[])
14const pmEvents = atom({ plugin: 'pm', key: 'events' } as const, [] as ForeignEvent[])
15
16type $ = EngineInterface
17
18/** Only the terminal and the Desktop app draw a mod's panes; elsewhere the log goes out as text. */
19async function drawsPanes($: $): Promise<boolean> {
20  return (await $.session.surfaces()).some(s => s === 'terminal' || s === 'desktop')
21}
22
23async function allEvents($: $): Promise<LogLine[]> {
24  return merged(await read($, events), await read($, baseEvents), await read($, slimEvents), {
25    fe: await read($, feEvents),
26    qa: await read($, qaEvents),
27    be: await read($, beEvents),
28    pm: await read($, pmEvents),
29  })
30}
31
32/** The newest lines as text; an older remainder is counted and pointed at the session's files on disk. */
33async function logText($: $): Promise<string> {
34  const list = await allEvents($)
35  if (list.length === 0) return 'no events yet'
36  const shown = list.slice(-TEXT_LOG_ROWS)
37  if (shown.length === list.length) return shown.map(logRow).join('\n')
38  let dir: string | null = null
39  try {
40    dir = logDir(await $.env.get('HOME'), await $.env.get('DOMAINE_LOG_DIR'), String(await $.session.id()))
41  } catch {}
42  const cut = `… ${list.length - shown.length} earlier${dir === null ? '' : ` — full log: ${dir}/`}`
43  return [cut, ...shown.map(logRow)].join('\n')
44}
45
46async function togglePane($: $): Promise<string> {
47  if (!(await drawsPanes($))) return await logText($)
48  if ((await $.ui.panes()).some(p => p.id === LOG_PANE && p.isShown)) {
49    await $.ui.close({ id: LOG_PANE })
50    return 'Log pane closed.'
51  }
52  const r = await $.ui.open({ id: LOG_PANE, title: 'Log', focus: true, closeOnEscape: true })
53  if (!r.isPlaced) {
54    $.ui.toast(`log pane not placed: ${r.reason}`)
55    return `Log pane not placed: ${r.reason}`
56  }
57  return 'Log pane opened.'
58}
59
60export function registerLog(on: On): void {
61  on('command.run', { command: LOG_COMMAND.name }, async $ => ({ text: await togglePane($) }))
62
63  // Answers without next, so the band Button's own closure never runs and the pane toggles once.
64  on('ui.press', { plugin: 'band', element: 'log' }, async ($, e) => {
65    await togglePane($)
66    return { element: e.element }
67  })
68
69  on('ui.render', { component: 'Pane', requestId: LOG_PANE }, async ($, e) => {
70    const { Box, Text } = $.ui.resolve(e)
71    const list = await allEvents($)
72    if (list.length === 0) {
73      return (
74        <Box flexDirection="column" width={e.props.bodyColumns}>
75          <Text dimColor wrap="truncate-end">
76            no events yet
77          </Text>
78        </Box>
79      )
80    }
81    // The engine's window starts at the top and never follows the end: keep the newest rows in view,
82    // counting the rows a wrapped text takes.
83    const rows = e.props.scroll?.bodyRows ?? 0
84    const textCols = Math.max(1, e.props.bodyColumns - PREFIX_COLS)
85    const shown = newestFitting(list, rows, textCols)
86    const cut = shown.length < list.length
87    return (
88      <Box flexDirection="column" width={e.props.bodyColumns}>
89        {cut ? <Text dimColor wrap="truncate-end">{`… ${list.length - shown.length} earlier`}</Text> : null}
90        {shown.map((ev, i) => (
91          <Box key={`ev-${i}`} flexDirection="row">
92            <Box width={PREFIX_COLS} flexShrink={0}>
93              <Text dimColor>{`${hhmm(ev.atMs)}  `}</Text>
94              <Text dimColor>{`${pluginCell(ev.plugin)}  `}</Text>
95              <Text dimColor>{`${kindCell(ev.kind)}  `}</Text>
96            </Box>
97            <Box width={textCols}>
98              <Text wrap="wrap">{ev.text}</Text>
99            </Box>
100          </Box>
101        ))}
102      </Box>
103    )
104  })
105}
106
hooks/mods/usage.ts 566 lines
1// Status band writers: usage, model, cache and tick atoms plus the tick timer, the claude.ai usage endpoint
2// poll, band's own event lines (session, model, compact, rate) with their file on disk, and /band-debug
3// (account.ts writes the account atom).
4// Nothing here draws; the band reads these atoms.
5import { atom, read, update } from 'claude-code'
6import type { EngineInterface, On, PluginOptions, Timer } from 'claude-code'
7import type { BandEvent, BandEventKind, BandRate, BandUsage } from '../../types'
8import { DEBUG_COMMAND, capLines, fileLine, fmtK, logDir, pushEvent, seedLines } from './events.ts'
9import { CACHE_INIT, CLEAR_RESEED_MS, HOUR_MS, USAGE_INIT, alarmRate, compactedUsage, endpointRates, fillHalved, keepCtx, mergeRates, modelFamily, oneHourCacheTokens, rateCard, seedsTtl, toRates, toUsage, ttlMsOf } from './lib.ts'
10import { lastRender, turn } from './band.tsx'
11import { accountDebug } from './account.ts'
12
13const TICK_MS = 30_000
14const ALARM_TOAST_MS = 8000
15/** A 1 h TTL learned in a billed session; a claude.ai account starts at 1 h anyway, so it stores none. */
16const STORE_TTL = 'billedCacheTtlMs'
17/** Below this much of session.end's shared bound, `session clear` stays off the disk rather than risk an abort. */
18const END_FILE_MIN_MS = 500
19
20const usage = atom({ plugin: 'band', key: 'usage' } as const, USAGE_INIT)
21const model = atom({ plugin: 'band', key: 'model' } as const, null)
22const cache = atom({ plugin: 'band', key: 'cache' } as const, CACHE_INIT)
23const tick = atom({ plugin: 'band', key: 'tick' } as const, 0)
24const rateAlarmed = atom({ plugin: 'band', key: 'rateAlarmed' } as const, false)
25const events = atom({ plugin: 'band', key: 'events' } as const, [] as BandEvent[])
26const info = atom({ plugin: 'band', key: 'info' } as const, null)
27const account = atom({ plugin: 'band', key: 'account' } as const, null)
28const baseProgress = atom({ plugin: 'base', key: 'progress' } as const, null)
29
30type $ = EngineInterface
31
32/** This session's lines of band.jsonl as last written; `path` tells a new session (or a reload) apart. */
33let file: { path: string; lines: string[] } | null = null
34let fileVersion: string | null = null
35let toastedFor: string | null = null
36/** Whole-file writes, one at a time: two hooks writing at once would each drop the other's line. */
37let fileQueue: Promise<void> = Promise.resolve()
38
39/**
40 * Appends one line to `<dir>/<session-id>/band.jsonl`, rewriting the whole file (the engine writes no
41 * append). The first write of a module or of a new session id seeds from the file, so a reload keeps the
42 * record. A session's first line is a start line, as no session.start follows a /clear or a resume; a
43 * start line comes once per session, so a fresh process resuming an id whose file has one adds none. `sid`
44 * pins the session (session.end names the ending one). No HOME and no DOMAINE_LOG_DIR → no file. A
45 * failure toasts once per session unless `quiet`, and goes no further.
46 */
47async function writeFileLine($: $, atMs: number, kind: string, text: string, sid?: string, quiet = false): Promise<void> {
48  let id = sid ?? ''
49  try {
50    id = sid ?? String(await $.session.id())
51    const dir = logDir(await $.env.get('HOME'), await $.env.get('DOMAINE_LOG_DIR'), id)
52    if (dir === null) return
53    const path = `${dir}/band.jsonl`
54    fileVersion ??= (await read($, info).catch(() => null))?.version ?? null
55    const version = fileVersion ?? 'unknown'
56    let prior = file?.path === path ? file.lines : seedLines((await $.fs.exists(path)) ? String(await $.fs.read(path)) : '', id)
57    if (kind === 'start' && prior.some(l => JSON.parse(l).kind === 'start')) {
58      file = { path, lines: prior }
59      return
60    }
61    if (kind !== 'start' && !prior.length) prior = [fileLine(atMs, version, id, 'start', `band ${version}`)]
62    const lines = capLines([...prior, fileLine(atMs, version, id, kind, text)])
63    file = { path, lines }
64    await $.fs.write(path, `${lines.join('\n')}\n`)
65  } catch (err) {
66    if (quiet || toastedFor === id) return
67    toastedFor = id
68    try {
69      $.ui.toast(`band: event log not written: ${err instanceof Error ? err.message : String(err)}`)
70    } catch {}
71  }
72}
73
74/** Queues one file line behind the writes in flight, so no whole-file write drops another's line. */
75function persist($: $, atMs: number, kind: string, text: string, sid?: string, quiet = false): Promise<void> {
76  const job = fileQueue.then(() => writeFileLine($, atMs, kind, text, sid, quiet))
77  fileQueue = job.catch(() => undefined)
78  return job
79}
80
81/**
82 * Appends one event-log line to band.events and band.jsonl; `onDisk` replaces kind and text in the file only.
83 * BAND_EVENT_LOG=0 skips both. It never throws, because a throwing session.start hook would skip every
84 * band session.start hook.
85 */
86async function logEvent($: $, kind: BandEventKind, text: string, onDisk?: { kind: string; text: string }): Promise<void> {
87  try {
88    if ((await $.env.get('BAND_EVENT_LOG')) === '0') return
89    const atMs = await $.clock.now()
90    await update($, events, l => pushEvent(l, { atMs, kind, text }))
91    await persist($, atMs, onDisk?.kind ?? kind, onDisk?.text ?? text)
92  } catch {}
93}
94
95/** BAND_COST=1 (true/yes/on) shows the session's cost; off, the figure is dropped before it reaches the atom. */
96let costShown = false
97const ON = new Set(['1', 'true', 'yes', 'on'])
98const isOn = (v: string | undefined) => ON.has(v?.trim().toLowerCase() ?? '')
99/** The session bills an API key or a cloud provider; read at session start. */
100let billed = false
101
102function withCost(u: BandUsage): BandUsage {
103  return costShown ? u : { ...u, costUsd: null }
104}
105
106/** The model a `/model` run moved away from: $.session.model() still answers it for a while after the run. */
107let leftModel: string | null = null
108/** A main-thread response has arrived: until then $.session.model() answers the process default, not the configured model. */
109let bound = false
110
111/** The $.session.model() answer, or null before a response binds the session or when it is the model a switch just left. */
112async function sessionModel($: $): Promise<string | null> {
113  if (!bound) return null
114  let m: string | null = null
115  try {
116    m = await $.session.model()
117  } catch {
118    return null
119  }
120  if (!m || m === leftModel) return null
121  leftModel = null
122  return m
123}
124
125/** The settings' `model` (an alias such as `opus`, or an id) when it names one; `default`, absent or unreadable → null. */
126async function settingsModel($: $): Promise<string | null> {
127  const s = await $.settings.read().catch(() => null)
128  const m = s?.model
129  return typeof m === 'string' && m.trim() !== '' && m !== 'default' ? m : null
130}
131
132/** Writes the model atom and logs the change once; the same id again is a no-op. */
133async function adoptModel($: $, m: string): Promise<void> {
134  if ((await read($, model)) === m) return
135  await update($, model, () => m)
136  await logEvent($, 'model', m)
137}
138
139/** The settings model last seen, so only a change to it moves the atom. */
140let lastSettingsModel: string | null = null
141
142/** Adopts `m` when the atom holds nothing or another family (a `[1m]` dropped), so an id of the same family stays. */
143async function adoptFamily($: $, m: string): Promise<void> {
144  const current = await read($, model)
145  if (current === null || modelFamily(current.replace(/\[1m\]$/, '')) !== modelFamily(m)) await adoptModel($, m)
146}
147
148/** Follows a pick in the `/model` dialog through the settings it saves: a changed settings model goes to `adoptFamily`. */
149async function syncSettingsModel($: $): Promise<void> {
150  const s = await settingsModel($)
151  if (s === null || s === lastSettingsModel) return
152  lastSettingsModel = s
153  await adoptFamily($, s)
154}
155
156/** The family a `/model` answer names: ``Set model to `Opus 5.5` (1M context) and saved …`` → `opus` (the name bare or quoted); null for any other text. */
157function answeredFamily(text: string | undefined): string | null {
158  const hit = /^Set model to\s+[`'"]?([A-Za-z]+)/i.exec(text ?? '')
159  return hit ? hit[1].toLowerCase() : null
160}
161
162/**
163 * Applies a `/model` run: the family its answer names, else `picked` (the band picker's alias), else the settings it
164 * saved. Caches are per model, so another family than the model before the run forfeits the warm one: `prev`
165 * ($.session.model() before the run) once a response bound the session, else the model atom. A bound session keeps
166 * answering `prev` for a while, which the next measure must not write back.
167 */
168export async function modelRan($: $, prev: string | null, text: string | undefined, picked?: string): Promise<void> {
169  const answered = answeredFamily(text)
170  // The settings may still answer the old model right after: the reading taken now counts as seen.
171  if (answered !== null) lastSettingsModel = await settingsModel($)
172  const family = answered ?? picked ?? null
173  if (family === null) return syncSettingsModel($)
174  const before = bound ? prev : await read($, model)
175  if (before && modelFamily(before) !== modelFamily(family)) {
176    if (bound) leftModel = before
177    await update($, cache, c => ({ ...c, isCold: true }))
178  }
179  await adoptFamily($, family)
180}
181
182const SAME_COMPACTION_MS = 30_000
183let lastCompactMs = 0
184/** Set by every compaction, cleared by the next reading with a fill: until then no reading is read as another one. */
185let awaitingFill = false
186
187/**
188 * Cold cache, the context from the engine's count (absent = no reading), one log line. The
189 * session.compact chain and the readings both report one compaction, in either order: a report within
190 * 30 s of the last is the same compaction, and then only a token count refines the context.
191 */
192async function applyCompaction($: $, trigger: string, tokensAfter?: number, tokensBefore?: number): Promise<void> {
193  awaitingFill = true
194  const now = await $.clock.now()
195  const same = now - lastCompactMs < SAME_COMPACTION_MS
196  lastCompactMs = now
197  await update($, cache, c => ({ ...c, isCold: true }))
198  if (same && tokensAfter === undefined) return
199  await update($, usage, u => compactedUsage(u, tokensAfter))
200  if (same) return
201  const sizes = typeof tokensBefore === 'number' && typeof tokensAfter === 'number' ? ` ${fmtK(tokensBefore)} → ${fmtK(tokensAfter)}` : ''
202  await logEvent($, 'compact', `${trigger}${sizes}`)
203}
204
205/** The host's last measured windows and the endpoint's last good ones: the usage atom's `rates` is their merge. */
206let measured: BandRate[] = []
207let endpoint: BandRate[] = []
208
209/**
210 * Writes the usage atom: `next` is a new measured reading, whose rates become the measured windows; absent,
211 * only the endpoint's windows changed. An endpoint window past its `resetsAt` is dropped. Every write of the
212 * atom's rates goes through here.
213 */
214async function writeUsage($: $, next?: BandUsage): Promise<void> {
215  if (next) {
216    measured = next.rates
217    await inferCompaction($, next)
218  }
219  const now = await $.clock.now()
220  endpoint = endpoint.filter(r => r.resetsAt === null || !(Date.parse(r.resetsAt) <= now))
221  const rates = mergeRates(measured, endpoint)
222  await update($, usage, prev => (next ? keepCtx(prev, { ...next, rates }) : { ...prev, rates }))
223  await adoptSubscriptionTtl($, rates)
224}
225
226/**
227 * A compaction read off a measured reading, for logins whose hooks never see the compact events (a Claude Team
228 * login). The fill gone (the engine drops it until the next response) is applied as one; a fill below half of
229 * the last one, that moment missed, is only logged, as the response that measured it wrote the cache again.
230 */
231async function inferCompaction($: $, next: BandUsage): Promise<void> {
232  const prev = await read($, usage)
233  if (next.ctxPct === null) {
234    if (prev.ctxPct !== null && !awaitingFill) await applyCompaction($, 'inferred')
235    return
236  }
237  const wasAwaiting = awaitingFill
238  awaitingFill = false
239  if (wasAwaiting || !fillHalved(prev, next)) return
240  const now = await $.clock.now()
241  if (now - lastCompactMs < SAME_COMPACTION_MS) return
242  lastCompactMs = now
243  const sizes = prev.ctxTokens !== null && next.ctxTokens !== null ? ` ${fmtK(prev.ctxTokens)} → ${fmtK(next.ctxTokens)}` : ''
244  await logEvent($, 'compact', `inferred${sizes}`)
245}
246
247const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
248/** The host's /usage caches its answer this long; band asks no more often, after a failure too. */
249const ENDPOINT_MIN_MS = 5 * 60_000
250/** A request unanswered this long fails as `timeout`, so a stalled one never blocks the next poll. */
251const ENDPOINT_TIMEOUT_MS = 10_000
252/** BAND_USAGE_ENDPOINT=0 turns the poll off; read at session start. */
253let endpointOn = true
254/** The last endpoint attempt, for /band-debug: `at` in clock ms, `error` one line; the body is never kept. */
255let attempt: { at: number; ok: boolean; status?: number; error?: string } | null = null
256let inFlight: Promise<void> | null = null
257
258/**
259 * Polls the usage endpoint at most once per ENDPOINT_MIN_MS, one request at a time; never throws. Callers do
260 * not await it: the poll writes the atom itself.
261 */
262function maybeFetchLimits($: $): Promise<void> {
263  if (!endpointOn) return Promise.resolve()
264  inFlight ??= fetchLimits($).finally(() => {
265    inFlight = null
266  })
267  return inFlight
268}
269
270async function fetchLimits($: $): Promise<void> {
271  let at: number
272  try {
273    at = await $.clock.now()
274  } catch {
275    return
276  }
277  if (attempt !== null && at - attempt.at < ENDPOINT_MIN_MS) return
278  try {
279    attempt = { at, ok: false }
280    const auth = await $.session.authorize()
281    // The endpoint takes the claude.ai login's token only; a session may log in later, so it asks again.
282    // No such login means no subscription, not a failed request: the windows it gave go.
283    if (auth?.kind !== 'bearer') {
284      attempt = { at, ok: false, error: auth ? 'api-key session' : 'no claude.ai login' }
285      if (!endpoint.length) return
286      endpoint = []
287      await writeUsage($).catch(() => undefined)
288      return
289    }
290    let timer: Timer | undefined
291    const res = await Promise.race([
292      $.http.fetch(USAGE_URL, {
293        headers: { 'anthropic-beta': 'oauth-2025-04-20', 'Content-Type': 'application/json' },
294        auth: auth.handle,
295      }),
296      new Promise<never>((_, reject) => {
297        timer = $.clock.after(ENDPOINT_TIMEOUT_MS, () => reject(new Error('timeout')))
298      }),
299    ]).finally(() => timer?.cancel())
300    if (!res.ok) {
301      attempt = { at, ok: false, status: res.status }
302      return
303    }
304    const body: unknown = JSON.parse(res.text)
305    if (body === null || typeof body !== 'object' || Array.isArray(body)) throw new Error('body is not a JSON object')
306    endpoint = toRates(endpointRates(body))
307    attempt = { at, ok: true, status: res.status }
308  } catch (err) {
309    attempt = { at, ok: false, error: (err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200) }
310    return
311  }
312  await writeUsage($).catch(() => undefined)
313}
314
315/** The /band-debug endpoint line's value: the last attempt and the windows it holds. */
316function endpointDebug() {
317  return {
318    ...(attempt ?? { at: null, ok: false }),
319    ...(endpointOn ? {} : { error: 'BAND_USAGE_ENDPOINT=0' }),
320    windows: endpoint.map(r => ({ kind: r.kind, pct: r.pct })),
321  }
322}
323
324async function refresh($: $): Promise<void> {
325  const now = await $.clock.now()
326  await update($, tick, () => now)
327  await applyResume($, now)
328  await writeUsage($, withCost(toUsage(...(await $.session.usage().then(r => [r.context, r.rateLimits, r.cost] as const)))))
329  void maybeFetchLimits($)
330  // A pick in the dialog a bare `/model` opens is saved after the command returns.
331  await syncSettingsModel($).catch(() => undefined)
332}
333
334/** A band-resume.json older than this when first seen belongs to an earlier start of the session id. */
335const RESUME_FRESH_MS = 60_000
336/** The band-resume.json last seen, as `<session id>@<atMs>`: each file applies once. */
337let resumeSeen: string | null = null
338
339/**
340 * Applies `<log dir>/<session id>/band-resume.json`, which hooks/resume.cjs writes on a resume or fork: one
341 * `session <source>` line, and the cache anchored at the last response (`atMs` less the seconds since it), cold
342 * when the host says the cache likely expired. An anchor older than one already recorded is ignored. Never throws.
343 */
344async function applyResume($: $, now: number): Promise<void> {
345  try {
346    const sid = String(await $.session.id())
347    const dir = logDir(await $.env.get('HOME'), await $.env.get('DOMAINE_LOG_DIR'), sid)
348    if (dir === null) return
349    const r = JSON.parse(String(await $.fs.read(`${dir}/band-resume.json`))) as Record<string, unknown>
350    if (typeof r.atMs !== 'number' || (r.source !== 'resume' && r.source !== 'fork')) return
351    const key = `${sid}@${r.atMs}`
352    if (key === resumeSeen) return
353    resumeSeen = key
354    if (now - r.atMs > RESUME_FRESH_MS) return
355    await logEvent($, 'session', r.source)
356    const secs = r.secondsSinceLastResponse
357    if (typeof secs !== 'number') return
358    const anchorMs = r.atMs - secs * 1000
359    if (((await read($, cache)).anchorMs ?? -Infinity) >= anchorMs) return
360    const isCold = r.promptCacheLikelyExpired === true
361    await update($, cache, c => ({ ...c, anchorMs, isCold }))
362  } catch {}
363}
364
365/**
366 * A non-empty API key or a cloud provider switch that is on (1, true, yes, on) bills per request and gets the
367 * 5 min cache; without them the session runs on a claude.ai account, whose cache lives 1 h.
368 */
369async function isBilled($: $): Promise<boolean> {
370  return (
371    !!(await $.env.get('ANTHROPIC_API_KEY')) ||
372    isOn(await $.env.get('CLAUDE_CODE_USE_BEDROCK')) ||
373    isOn(await $.env.get('CLAUDE_CODE_USE_VERTEX')) ||
374    isOn(await $.env.get('CLAUDE_CODE_USE_FOUNDRY'))
375  )
376}
377
378/**
379 * Rate-limit windows arrive only on a claude.ai subscription, whose prompt cache lives 1 h (5 min
380 * under an API key or in overage). Live evidence beats the default and a remembered value alike.
381 */
382async function adoptSubscriptionTtl($: $, rates: readonly BandRate[]): Promise<void> {
383  if (rates.length === 0) return
384  await update($, cache, c =>
385    c.ttlSource === 'default' || c.ttlSource === 'store' ? { ...c, ttlMs: HOUR_MS, ttlSource: 'subscription' } : c,
386  )
387}
388
389/** Adopts the 1 h TTL a subagent's cache writes showed; a billed session remembers it for the next billed one. */
390async function learnHourTtl($: $): Promise<void> {
391  await update($, cache, c => ({ ...c, ttlMs: HOUR_MS, ttlSource: 'agent' }))
392  if (billed) await $.store.set(STORE_TTL, HOUR_MS)
393}
394
395/** Another plugin writes the snapshot: only a string or null id and branch are shown. */
396function progressLine(p: unknown): { workId: string | null; branch: string | null } | null {
397  if (p === null || typeof p !== 'object') return null
398  const s = p as { workId?: unknown; branch?: unknown }
399  const str = (v: unknown) => (typeof v === 'string' ? v : null)
400  return { workId: str(s.workId), branch: str(s.branch) }
401}
402
403/**
404 * Fills the atoms a fresh session starts without: the TTL (`seedsTtl` decides), the model (the session's once a
405 * response bound it, else the settings' while the atom is empty) and the first usage reading. One throwing
406 * session.start hook skips every band session.start hook: each $ call fails alone.
407 */
408async function seed($: $, reloaded: boolean, forcedTtl: number | null): Promise<void> {
409  if (seedsTtl(reloaded, forcedTtl, (await read($, cache).catch(() => CACHE_INIT)).ttlSource)) {
410    let learned: number | null = null
411    if (forcedTtl === null && billed) {
412      try {
413        const stored = await $.store.get(STORE_TTL)
414        learned = typeof stored === 'number' && stored > 0 ? stored : null
415      } catch {}
416    }
417    const ttlMs = forcedTtl ?? learned ?? (billed ? CACHE_INIT.ttlMs : HOUR_MS)
418    const ttlSource = forcedTtl !== null ? 'option' : learned !== null ? 'store' : 'default'
419    await update($, cache, c => ({ ...c, ttlMs, ttlSource })).catch(() => undefined)
420  }
421  let m = await sessionModel($)
422  if (m === null) {
423    m = lastSettingsModel = await settingsModel($)
424    if ((await read($, model).catch(() => null)) !== null) m = null
425  }
426  if (m !== null) await update($, model, () => m).catch(() => undefined)
427  await refresh($).catch(() => undefined)
428}
429
430export function registerUsage(on: On, options: PluginOptions): void {
431  const forcedTtl = ttlMsOf(options.cacheTtl)
432
433  // A /config change reloads the module and session.start runs again in the same session: the tick, set by
434  // the first one, tells a reload apart, so it logs no second start line and keeps a learned TTL.
435  on('session.start', async ($, e, next) => {
436    $.clock.every(TICK_MS, () => {
437      void refresh($).catch(() => undefined)
438    })
439    const reloaded = (await read($, tick).catch(() => 0)) > 0
440    billed = await isBilled($).catch(() => true)
441    costShown = isOn(await $.env.get('BAND_COST').catch(() => undefined))
442    endpointOn = (await $.env.get('BAND_USAGE_ENDPOINT').catch(() => undefined)) !== '0'
443    bound = false
444    lastSettingsModel = null
445    if (!reloaded) {
446      const v = (await read($, info).catch(() => null))?.version ?? '?'
447      await logEvent($, 'session', `start · band ${v}`, { kind: 'start', text: `band ${v}` })
448    }
449    await seed($, reloaded, forcedTtl)
450    return next(e)
451  })
452
453  on('command.run', { command: DEBUG_COMMAND.name }, async ($) => {
454    const raw = await $.session.usage().catch(err => ({ error: String(err) }))
455    const root = await $.session.root().catch(err => `error: ${String(err)}`)
456    const c = await read($, cache)
457    const u = await read($, usage)
458    const lines = [
459      'band debug',
460      `info: ${JSON.stringify(await read($, info))}`,
461      `usage(): ${JSON.stringify(raw)}`,
462      `cache: ${JSON.stringify(c)}`,
463      `usage atom: ${JSON.stringify(u)}`,
464      `endpoint: ${JSON.stringify(endpointDebug())}`,
465      `account: ${JSON.stringify({ atom: await read($, account), last: accountDebug() })}`,
466      `progress: ${JSON.stringify(progressLine(await read($, baseProgress)))}`,
467      `root: ${root}`,
468      `render: ${JSON.stringify(lastRender)}`,
469      `tick: ${await read($, tick)}`,
470      `now: ${await $.clock.now()}`,
471    ]
472    return { text: lines.join('\n') }
473  })
474
475  on('session.measure', async ($, e, next) => {
476    const r = await next(e)
477    await writeUsage($, withCost(toUsage(e.context, e.rateLimits, e.cost)))
478    // Once a response has bound the session, a switch no `/model` run reported is caught here.
479    const m = await sessionModel($)
480    if (m !== null) await adoptModel($, m)
481    void maybeFetchLimits($)
482    const hot = alarmRate((await read($, usage)).rates)
483    const isAlarmed = await read($, rateAlarmed)
484    if (hot && !isAlarmed) {
485      await update($, rateAlarmed, () => true)
486      const card = rateCard(hot, await $.clock.now())
487      $.ui.toast(card, { timeoutMs: ALARM_TOAST_MS })
488      await logEvent($, 'rate', card)
489    } else if (!hot && isAlarmed) {
490      await update($, rateAlarmed, () => false)
491    }
492    return r
493  })
494
495  on('turn.complete', async ($, e, next) => {
496    if (e.agentId === undefined) turn.running = false
497    if (e.agentId === undefined && e.usage) {
498      const now = await $.clock.now()
499      await update($, cache, c => ({ ...c, anchorMs: now, isCold: false }))
500      await update($, tick, () => now)
501      bound = true
502      // A response names its model without the `[1m]` a pinned session id carries: that id stays.
503      const answered = e.usage.model
504      if (typeof answered === 'string' && answered && (await read($, model))?.replace(/\[1m\]$/, '') !== answered) await adoptModel($, answered)
505    }
506    return next(e)
507  })
508
509  on('session.compact', async ($, e, next) => {
510    const r = await next(e)
511    if (r.skip === undefined && r.messages && e.trigger !== 'precompute' && e.agentId === undefined) {
512      await applyCompaction($, e.trigger, r.tokensAfter, r.tokensBefore)
513    }
514    return r
515  })
516
517  // One short wall-clock bound covers the whole session.end chain, $ waits included: the atoms and the
518  // pane line go first, the disk write only after the chain beneath has run and while time is left.
519  on('session.end', async ($, e, next) => {
520    if (e.reason === 'clear' || e.reason === 'resume') {
521      await update($, cache, c => ({ ...c, anchorMs: null, isCold: false }))
522      await update($, usage, u => ({ ...u, ctxPct: null, ctxTokens: null }))
523      await update($, rateAlarmed, () => false)
524    }
525    // No session.start follows a /clear: this line marks where the conversation restarted.
526    let clearedAt: number | null = null
527    if (e.reason === 'clear') {
528      try {
529        if ((await $.env.get('BAND_EVENT_LOG')) !== '0') {
530          const atMs = await $.clock.now()
531          await update($, events, l => pushEvent(l, { atMs, kind: 'session', text: 'clear' }))
532          clearedAt = atMs
533        }
534      } catch {}
535    }
536    const r = await next(e)
537    // /clear starts a new session id with empty state and no session.start; the timer runs in the plugin's
538    // environment and seeds the new session.
539    if (e.reason === 'clear') {
540      try {
541        $.clock.after(CLEAR_RESEED_MS, () => {
542          void seed($, false, forcedTtl).catch(() => undefined)
543        })
544      } catch {}
545    }
546    if (clearedAt !== null && next.budget.remainingMs >= END_FILE_MIN_MS) {
547      await persist($, clearedAt, 'session', 'clear', e.sessionId, true).catch(() => undefined)
548    }
549    return r
550  })
551
552  // A typed `/model <alias>` lands here on every login; the band picker's own run applies it in band.tsx.
553  on('command.run', { command: 'model' }, async ($, e, next) => {
554    const prev = await $.session.model().catch(() => null)
555    const r = await next(e)
556    await modelRan($, prev, r.text).catch(() => undefined)
557    return r
558  })
559
560  on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
561    const r = await next(e)
562    if (forcedTtl === null && oneHourCacheTokens(r.result) > 0) await learnHourTtl($)
563    return r
564  })
565}
566
hooks/mods/lib.ts 708 lines
1// Pure band helpers: the ctx/rate/cache colour ladders, rate labels, remaining-time text, the one-row
2// width model with its drop order, and base's task snapshot read as the generic checklist. No `$` here:
3// atoms and engine calls stay in the file that hooks the event.
4import type { BandAccount, BandCache, BandRate, BandUsage, Checklist, ChecklistMark, ChecklistRow } from '../../types'
5
6export type Level = 'plain' | 'warning' | 'crit'
7
8/** The alarm look; needs no theme key beyond `warning` until another is proven live on every theme. */
9export const CRIT = { color: 'warning', bold: true, inverse: true } as const
10
11/** Text props per level. */
12export const LEVEL_PROPS: Record<Level, { color?: string; bold?: boolean; inverse?: boolean }> = {
13  plain: {},
14  warning: { color: 'warning' },
15  crit: CRIT,
16}
17/** The ctx value alone is green while fine, as the classic notice's 🟢 was; the rest of the band stays plain there. */
18export const CTX_PROPS: typeof LEVEL_PROPS = { ...LEVEL_PROPS, plain: { color: 'success' } }
19
20/** ctx % and every rate window: ≤ 30 plain, > 30 warning, ≥ 80 crit, judged on the rounded figure the band shows. */
21export function pctLevel(pct: number): Level {
22  const shown = Math.round(pct)
23  if (shown >= 80) return 'crit'
24  if (shown > 30) return 'warning'
25  return 'plain'
26}
27
28const MIN = 60_000
29
30/**
31 * Minutes left of the cache: warning below 10 min, crit below 2 min for a 1 h TTL. A shorter TTL
32 * scales both: warning below 40 % of the TTL (when that is under 10 min), crit at a fifth of that.
33 */
34export function cacheLevel(remainingMs: number, ttlMs: number): Level {
35  const warnMs = Math.min(10 * MIN, 0.4 * ttlMs)
36  if (remainingMs < warnMs / 5) return 'crit'
37  if (remainingMs < warnMs) return 'warning'
38  return 'plain'
39}
40
41/** Remaining cache time at `nowMs`, or null before the first main-thread response. */
42export function cacheRemaining(cache: BandCache, nowMs: number): number | null {
43  return cache.anchorMs === null ? null : cache.anchorMs + cache.ttlMs - nowMs
44}
45
46/** `42m`, `<1m`; null → `—`. Callers render `cold` for remaining ≤ 0 themselves via cacheView. */
47export function fmtRemaining(ms: number | null): string {
48  if (ms === null) return '—'
49  if (ms < MIN) return '<1m'
50  return `${Math.floor(ms / MIN)}m`
51}
52
53/** How long after a /clear's session.end the new session is seeded: by then it is the current one. */
54export const CLEAR_RESEED_MS = 1000
55
56export const COMPACT_OPTIONS = ['Compact', 'Clear', 'Cancel'] as const
57export const COMPACT_WARN_MS = 5 * MIN
58export const COMPACT_COLD = 'Prompt cache is cold or ends within 5 min: compacting re-reads the whole conversation at full price. If this session is done, Clear is cheaper. Compact anyway?'
59
60/** What a Compact press asks first on a cold cache or one ending within 5 min; null while it is warm or unmeasured, when the press compacts at once. */
61export function compactQuestion(cache: BandCache, nowMs: number): string | null {
62  const left = cacheRemaining(cache, nowMs)
63  return left !== null && (cache.isCold || left <= COMPACT_WARN_MS) ? COMPACT_COLD : null
64}
65
66export type CacheView = { text: string; level: Level }
67
68/** The cache segment: `cache ●` mid-turn, `cache —` unmeasured, `cache cold`, else the countdown. */
69export function cacheView(cache: BandCache, nowMs: number, isWorking: boolean): CacheView {
70  if (isWorking) return { text: 'cache ●', level: 'plain' }
71  const left = cacheRemaining(cache, nowMs)
72  if (left === null) return { text: 'cache —', level: 'plain' }
73  if (cache.isCold || left <= 0) return { text: 'cache cold', level: 'plain' }
74  return { text: `cache ${fmtRemaining(left)}`, level: cacheLevel(left, cache.ttlMs) }
75}
76
77export function ctxText(pct: number | null): string {
78  return pct === null ? 'ctx —' : `ctx ${Math.round(pct)}%`
79}
80
81const KNOWN_KINDS: Record<string, string> = { five_hour: '5h', seven_day: '7d', spend_limit: '$' }
82const LABEL_MAX = 10
83
84/** `five_hour` → `5h`; an unknown kind keeps its raw name, shortened (`seven_day_fable` → `7d·fable`). */
85export function rateLabel(kind: string): string {
86  const known = KNOWN_KINDS[kind]
87  if (known !== undefined) return known
88  const short = kind
89    .replace(/^five_hour/, '5h')
90    .replace(/^seven_day/, '7d')
91    .replace(/_+/g, '·')
92    .replace(/^·+|·+$/g, '')
93  return [...(short || kind)].slice(0, LABEL_MAX).join('')
94}
95
96/** Rounded for display; above 100 (a spend limit) reads `>100%`. */
97export function fmtPct(pct: number): string {
98  return pct > 100 ? '>100%' : `${Math.round(pct)}%`
99}
100
101export type RawRate = { kind: string; percentUsed: number; resetsAt?: string }
102
103/** Every window the API reports, in its order. */
104export function toRates(list: readonly RawRate[] | undefined): BandRate[] {
105  return (list ?? []).map(r => ({
106    kind: r.kind,
107    label: rateLabel(r.kind),
108    pct: r.percentUsed,
109    resetsAt: r.resetsAt ?? null,
110  }))
111}
112
113const isRecord = (x: unknown): x is Record<string, unknown> => x !== null && typeof x === 'object' && !Array.isArray(x)
114
115const ENDPOINT_WINDOWS = ['five_hour', 'seven_day', 'seven_day_opus', 'seven_day_sonnet'] as const
116
117/**
118 * The windows of the claude.ai usage endpoint's body (`/api/oauth/usage`): the top-level windows, then each
119 * per-model weekly row of `limits` as `seven_day_<model slug>` (`Fable` → `seven_day_fable`). The body is
120 * untrusted: a window without a finite percentage is skipped, and a kind seen twice keeps the first.
121 */
122export function endpointRates(json: unknown): RawRate[] {
123  if (!isRecord(json)) return []
124  const out: RawRate[] = []
125  const add = (kind: string, pct: unknown, resetsAt: unknown) => {
126    if (typeof pct !== 'number' || !Number.isFinite(pct) || out.some(r => r.kind === kind)) return
127    out.push({ kind, percentUsed: pct, ...(typeof resetsAt === 'string' ? { resetsAt } : {}) })
128  }
129  for (const kind of ENDPOINT_WINDOWS) {
130    const w = json[kind]
131    if (isRecord(w)) add(kind, w.utilization, w.resets_at)
132  }
133  for (const row of Array.isArray(json.limits) ? json.limits : []) {
134    if (!isRecord(row) || row.kind !== 'weekly_scoped' || !isRecord(row.scope) || !isRecord(row.scope.model)) continue
135    const name = row.scope.model.display_name
136    const slug = typeof name === 'string' ? name.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') : ''
137    if (slug) add(`seven_day_${slug}`, row.percent, row.resets_at)
138  }
139  return out
140}
141
142/** The host's measured windows in their order (its live reading wins a kind), then the endpoint's other windows. */
143export function mergeRates(measured: readonly BandRate[], endpoint: readonly BandRate[]): BandRate[] {
144  const kinds = new Set(measured.map(r => r.kind))
145  return [...measured, ...endpoint.filter(r => !kinds.has(r.kind))]
146}
147
148/** ` ↻2h05m` after a rate's percentage; empty without a reset time. */
149export function resetMark(short: string | null): string {
150  return short ? ` ${GLYPH.reset}${short}` : ''
151}
152
153/** `5h 61%`, `5h 61% ↻2h05m` with the window's compact reset time. */
154export function rateText(r: BandRate, resetShort: string | null = null): string {
155  return `${r.label} ${fmtPct(r.pct)}${resetMark(resetShort)}`
156}
157
158/** Resets closer than this are one instant: the weekly windows share theirs. */
159const SAME_RESET_MS = 60_000
160
161const resetMs = (r: BandRate): number => (r.resetsAt ? Date.parse(r.resetsAt) : NaN)
162
163/**
164 * The compact reset time drawn after each window, by index: adjacent windows whose resets lie within 60 s of each
165 * other form a group that shows it once, after its last window (`7d 34% · 7d·fable 12% ↻3d4h`); null = none drawn.
166 * `nowMs` null draws none.
167 */
168export function groupResets(rates: readonly BandRate[], nowMs: number | null): (string | null)[] {
169  if (nowMs === null) return rates.map(() => null)
170  return rates.map((r, i) => {
171    const next = rates[i + 1]
172    const shared = next !== undefined && Math.abs(resetMs(next) - resetMs(r)) < SAME_RESET_MS
173    return shared ? null : fmtResetShort(r.resetsAt, nowMs)
174  })
175}
176
177type BandButton = { key: string; label: string; hotkey: string; plain: boolean }
178
179/** The band's segments in row order; null/empty = not drawn. */
180export type BandSegs = {
181  /** `work` / `personal`: the login the session runs on; null = no segment. */
182  account: 'work' | 'personal' | null
183  /** null while a rate window is at or past 100 %: in overage the TTL is unknown, so nothing is shown. */
184  cache: string | null
185  model: string | null
186  ctx: string
187  rates: BandRate[]
188  /** The clock (ms) each rate's reset countdown reads against; null = no reset times drawn. */
189  resetsNowMs: number | null
190  /** `cost $1.23`; null without a ledger or at zero. */
191  cost: string | null
192  digest: string | null
193  compact: BandButton
194  clear: BandButton | null
195  progress: BandButton | null
196  log: BandButton | null
197}
198
199export const SEP = ' │ '
200/** The dim rule drawn above the row, one cell repeated across the band. */
201export const RULE = '─'
202const RATE_GAP = ' · '
203const BUTTON_GAP = '  '
204
205/** Width sample: the focused form `c: Compact` (letters show only while the band holds the keyboard) or `[ Compact ]`; they differ by one cell. */
206export function buttonText(b: BandButton): string {
207  return b.plain ? `${b.hotkey}: ${b.label}` : `[ ${b.label} ]`
208}
209
210/** The row as the terminal draws it: groups joined by ` │ `. */
211export function rowText(s: BandSegs): string {
212  const groups: string[] = s.account === null ? [] : [s.account]
213  if (s.cache !== null) groups.push(s.cache)
214  if (s.model !== null) groups.push(`${s.model}${MODEL_MARK}`)
215  groups.push(s.ctx)
216  if (s.rates.length) {
217    const resets = groupResets(s.rates, s.resetsNowMs)
218    groups.push(s.rates.map((r, i) => rateText(r, resets[i])).join(RATE_GAP))
219  }
220  if (s.cost !== null) groups.push(s.cost)
221  if (s.digest !== null) groups.push(s.digest)
222  const buttons = [s.compact, s.clear, s.progress, s.log].filter((b): b is BandButton => b !== null)
223  groups.push(buttons.map(buttonText).join(BUTTON_GAP))
224  return groups.join(SEP)
225}
226
227/** Width in cells, one per code point. */
228export function cells(text: string): number {
229  return [...text].length
230}
231
232/**
233 * Drops segments until the row fits `bodyColumns`: the Log button (/band-log stays), the Clear button (/clear
234 * stays), the rates' reset times, the account, the digest, the cost, then rate windows beyond the fullest (least
235 * full first), then the last rate, the model, the Progress button.
236 * Cache, ctx and Compact are never dropped. 0 or absent columns = a surface that did not measure: kept whole.
237 */
238export function layout(segs: BandSegs, bodyColumns: number | undefined): BandSegs {
239  if (!bodyColumns || bodyColumns <= 0) return segs
240  let s: BandSegs = segs
241  const fits = () => cells(rowText(s)) <= bodyColumns
242  if (fits()) return s
243  if (s.log !== null) s = { ...s, log: null }
244  if (!fits() && s.clear !== null) s = { ...s, clear: null }
245  if (!fits() && s.resetsNowMs !== null) s = { ...s, resetsNowMs: null }
246  if (!fits() && s.account !== null) s = { ...s, account: null }
247  if (!fits() && s.digest !== null) s = { ...s, digest: null }
248  if (!fits() && s.cost !== null) s = { ...s, cost: null }
249  while (!fits() && s.rates.length > 1) {
250    const fullest = s.rates.reduce((a, b) => (b.pct > a.pct ? b : a))
251    const victim = s.rates.reduce((a, b) => (b !== fullest && (a === fullest || b.pct <= a.pct) ? b : a))
252    s = { ...s, rates: s.rates.filter(r => r !== victim) }
253  }
254  if (!fits() && s.rates.length) s = { ...s, rates: [] }
255  if (!fits() && s.model !== null) s = { ...s, model: null }
256  if (!fits() && s.progress !== null) s = { ...s, progress: null }
257  return s
258}
259
260const HOUR = 60 * MIN
261const DEFAULT_TTL_MS = 5 * MIN
262
263export const USAGE_INIT: BandUsage = { ctxPct: null, ctxTokens: null, window: 0, rates: [], costUsd: null }
264export const CACHE_INIT: BandCache = { anchorMs: null, ttlMs: DEFAULT_TTL_MS, ttlSource: 'default', isCold: false }
265
266/**
267 * Whether session.start seeds the TTL again. A reload (a /config change) keeps a learned one; a forced TTL is
268 * applied, and leaving a forced one seeds from the store or the default again.
269 */
270export function seedsTtl(reloaded: boolean, forcedTtl: number | null, source: BandCache['ttlSource']): boolean {
271  return !reloaded || forcedTtl !== null || source === 'option'
272}
273
274/** `5m` / `1h` (the userConfig picker) in ms; anything else (`auto`) → null. */
275export function ttlMsOf(v: unknown): number | null {
276  if (v === '5m') return 5 * MIN
277  if (v === '1h') return HOUR
278  return null
279}
280
281export type RawContext = { tokens?: number; window: number; percent?: number }
282
283export type RawCost = { usd: number }
284
285/** `$.session.usage()` / `session.measure` figures as the usage atom holds them. */
286export function toUsage(context: RawContext, rateLimits: readonly RawRate[] | undefined, cost?: RawCost): BandUsage {
287  return {
288    ctxPct: context.percent ?? null,
289    ctxTokens: context.tokens ?? null,
290    window: context.window,
291    rates: toRates(rateLimits),
292    costUsd: typeof cost?.usd === 'number' ? cost.usd : null,
293  }
294}
295
296/** `$0.49`, `$139.14`: the host's /cost total, cents kept so a small session still moves. */
297export function fmtUsd(usd: number): string {
298  return `$${usd.toFixed(2)}`
299}
300
301/** `cost $139.14`; null without a ledger and while the session has cost nothing. */
302export function costText(usd: number | null): string | null {
303  return usd === null || usd <= 0 ? null : `cost ${fmtUsd(usd)}`
304}
305
306/** The cost hover card. */
307export function costCard(usd: number): string {
308  return `session cost: ${fmtUsd(usd)} at API prices, as /cost counts it (a subscription is not billed per request)`
309}
310
311/** `1,234,567`. */
312export function fmtInt(n: number): string {
313  return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
314}
315
316/** Time left until `resetsAt` as its two largest units (`['42m']`, `['2h', '05m']`, `['3d', '4h']`); null when absent or unparsable. */
317function resetParts(resetsAt: string | null, nowMs: number): string[] | null {
318  if (!resetsAt) return null
319  const at = Date.parse(resetsAt)
320  if (Number.isNaN(at)) return null
321  const mins = Math.max(0, Math.round((at - nowMs) / MIN))
322  if (mins < 60) return [`${mins}m`]
323  const h = Math.floor(mins / 60)
324  if (h < 24) return [`${h}h`, `${String(mins % 60).padStart(2, '0')}m`]
325  return [`${Math.floor(h / 24)}d`, `${h % 24}h`]
326}
327
328/** `in 42m`, `in 2h 05m`, `in 3d 4h`; null when absent or unparsable. */
329export function fmtResetIn(resetsAt: string | null, nowMs: number): string | null {
330  const parts = resetParts(resetsAt, nowMs)
331  return parts && `in ${parts.join(' ')}`
332}
333
334/** `42m`, `2h05m`, `3d4h`: the band row's form; null when absent or unparsable. */
335export function fmtResetShort(resetsAt: string | null, nowMs: number): string | null {
336  return resetParts(resetsAt, nowMs)?.join('') ?? null
337}
338
339/** `5h window: 61% used, resets in 2h 05m`: the rate hover card and the ≥ 90 % toast. */
340export function rateCard(r: BandRate, nowMs: number): string {
341  const reset = fmtResetIn(r.resetsAt, nowMs)
342  return `${r.label} window: ${fmtPct(r.pct)} used${reset ? `, resets ${reset}` : ''}`
343}
344
345const RATE_ALARM_PCT = 90
346
347/** The first window whose shown percentage is at or past the alarm line, or null. */
348export function alarmRate(rates: readonly BandRate[]): BandRate | null {
349  return rates.find(r => Math.round(r.pct) >= RATE_ALARM_PCT) ?? null
350}
351
352/** `1 h`, `5 min`. */
353export function ttlText(ms: number): string {
354  return ms % HOUR === 0 ? `${ms / HOUR} h` : `${Math.round(ms / MIN)} min`
355}
356
357export function cacheCard(cache: BandCache, nowMs: number): string {
358  const left = cacheRemaining(cache, nowMs)
359  if (left === null) return 'prompt cache: no response yet'
360  if (cache.isCold || left <= 0) return 'prompt cache: cold, the next request writes it again'
361  const mins = left < MIN ? '<1' : `~${Math.floor(left / MIN)}`
362  return `prompt cache: ${mins} min left (estimate: last response + ${ttlText(cache.ttlMs)} TTL)`
363}
364
365/**
366 * The context right after a compaction: the engine's own count of the kept conversation over the
367 * window already known. It holds until a response reports a measured reading.
368 */
369export function compactedUsage(u: BandUsage, tokensAfter: number | undefined): BandUsage {
370  const known = typeof tokensAfter === 'number' && tokensAfter >= 0
371  return { ...u, ctxTokens: known ? tokensAfter : null, ctxPct: known && u.window > 0 ? (tokensAfter / u.window) * 100 : null }
372}
373
374/** A measurement without a context reading (window only, as right after a compaction) keeps the last one. */
375export function keepCtx(prev: BandUsage, next: BandUsage): BandUsage {
376  return next.ctxPct === null ? { ...next, ctxPct: prev.ctxPct, ctxTokens: prev.ctxTokens } : next
377}
378
379/** The least fill a drop is read from: tokens, or percent where either reading has no count. */
380const HALVED_MIN_TOKENS = 20_000
381const HALVED_MIN_PCT = 5
382
383/**
384 * Whether the measured fill fell below half of the last one, as a compaction leaves it: by tokens when both
385 * readings count them (from at least 20k), else by percent over the same window (from at least 5 %). False
386 * when either has no fill. A rewind that drops as much reads the same.
387 */
388export function fillHalved(prev: BandUsage, next: BandUsage): boolean {
389  if (prev.ctxPct === null || next.ctxPct === null) return false
390  if (prev.ctxTokens !== null && next.ctxTokens !== null) return prev.ctxTokens >= HALVED_MIN_TOKENS && next.ctxTokens < prev.ctxTokens / 2
391  return prev.window === next.window && prev.ctxPct >= HALVED_MIN_PCT && next.ctxPct < prev.ctxPct / 2
392}
393
394export function ctxCard(u: BandUsage): string {
395  if (u.ctxPct === null) return 'context: no reading yet (fresh session or just compacted)'
396  const used = u.ctxTokens === null ? '' : `, ${fmtInt(u.ctxTokens)} used`
397  return `context: ${Math.round(u.ctxPct)}% of ${fmtInt(u.window)} tokens${used}`
398}
399
400/** Single code points only: a VS16/ZWJ sequence has no settled cell width. */
401export const GLYPH = {
402  cache: '⏱',
403  ctx: '\u{1F9E0}',
404  rates: '⏳',
405  model: '\u{1F916}',
406  digest: '\u{1F4CB}',
407  cost: '\u{1F4B0}',
408  reset: '↻',
409  work: '\u{1F3E2}',
410  personal: '\u{1F3E0}',
411} as const
412
413/** The desktop label: the leading word of `cache 42m` / `ctx 47%` / `cost $1.23` becomes its glyph. */
414export function glyphText(text: string): string {
415  return text
416    .replace(/^cache /, `${GLYPH.cache} `)
417    .replace(/^ctx /, `${GLYPH.ctx} `)
418    .replace(/^cost /, `${GLYPH.cost} `)
419}
420
421const COMPACT_LOUD_PCT = 80
422
423/** Always drawn first and always pressable, so the buttons never shift; `plain` = the normal look (never dim), the primary button from 80 % between turns. */
424export function compactButton(ctxPct: number | null, isWorking: boolean): BandButton {
425  const loud = ctxPct !== null && !isWorking && Math.round(ctxPct) >= COMPACT_LOUD_PCT
426  return { key: 'compact', label: 'Compact', hotkey: 'c', plain: !loud }
427}
428
429export const CLEAR_BUTTON: BandButton = { key: 'clear', label: 'Clear', hotkey: 'x', plain: true }
430export const PROGRESS_BUTTON: BandButton = { key: 'progress', label: 'Progress', hotkey: 'p', plain: true }
431export const LOG_BUTTON: BandButton = { key: 'log', label: 'Log', hotkey: 'l', plain: true }
432
433export type CompactOutcome = { skip?: string; tokensBefore?: number; tokensAfter?: number }
434
435export function compactToast(r: CompactOutcome): string {
436  if (r.skip !== undefined) return `compact skipped: ${r.skip}`
437  const n = (v: number | undefined) => (v === undefined ? '?' : fmtInt(v))
438  return `compacted ${n(r.tokensBefore)} → ${n(r.tokensAfter)} tokens`
439}
440
441export type BandInput = {
442  usage: BandUsage
443  model: string | null
444  cache: BandCache
445  nowMs: number
446  isWorking: boolean
447  digest: string | null
448  /** a task checklist is published: the Progress button is drawn only then */
449  hasChecklist: boolean
450  /** some event list is non-empty: the Log button is drawn only then */
451  hasEvents: boolean
452  /** the band.account atom; absent or null = no account segment */
453  account?: BandAccount | null
454}
455
456/** `claude-fable-5-1` → `fable-5-1`: every model id carries the prefix, so it says nothing. */
457export function shortModel(m: string | null): string | null {
458  return m === null ? null : m.replace(/^claude-/, '')
459}
460
461/** The families the terminal's model picker offers: `/model <alias>` resolves to the family's newest model, so the list never dates. */
462export const MODEL_ALIASES = ['fable', 'opus', 'sonnet', 'haiku'] as const
463
464/** `claude-haiku-5-5` → `haiku`, `claude-opus-5-5[1m]` → `opus`: the family of a model id. */
465export function modelFamily(id: string): string {
466  return (shortModel(id) as string).split('-')[0]
467}
468
469/** The mark after the model id on the terminal: the segment is the picker's button. */
470export const MODEL_MARK = ' ▾'
471
472/** The unfolded picker's close button: folds the row without a pick. */
473export const MODEL_CLOSE = '×'
474
475/** `value` is what `/model` runs; `current` marks the session's own model, which only folds the picker. */
476export type ModelOption = { value: string; label: string; current: boolean; hotkey?: string }
477
478/**
479 * The picker's options: the aliases, the one of the session's family marked current; the session's own id leads
480 * them when no alias stands for it (a pinned `[1m]` id, a family outside the list). A `hidden` family is left out
481 * unless it is the current one. Each takes its label's first letter as hotkey when it is one and still free
482 * (`f`, `o`, `s`, `h`).
483 */
484export function modelOptions(current: string | null, hidden: readonly string[] = []): ModelOption[] {
485  const aliased = current !== null && !/\[/.test(current) && MODEL_ALIASES.includes(modelFamily(current) as (typeof MODEL_ALIASES)[number])
486  const own: ModelOption[] = current !== null && !aliased ? [{ value: current, label: shortModel(current) as string, current: true }] : []
487  const aliases = MODEL_ALIASES.map(a => ({ value: a, label: a, current: aliased && modelFamily(current as string) === a })).filter(o => o.current || !hidden.includes(o.value))
488  const taken = new Set<string>()
489  return [...own, ...aliases].map(o => {
490    const letter = o.label[0]
491    if (!/^[a-z]$/.test(letter) || taken.has(letter)) return o
492    taken.add(letter)
493    return { ...o, hotkey: letter }
494  })
495}
496
497/** `cache 42m` → [`cache`, `42m`]: the dim label and the bold value; no space → the whole text is the label. */
498export function splitLabel(text: string): [string, string] {
499  const i = text.indexOf(' ')
500  return i < 0 ? [text, ''] : [text.slice(0, i), text.slice(i + 1)]
501}
502
503/** Every segment before the width drop. */
504export function bandSegs(i: BandInput): BandSegs {
505  return {
506    account: i.account?.label ?? null,
507    cache: i.usage.rates.some(r => r.pct >= 100) ? null : cacheView(i.cache, i.nowMs, i.isWorking).text,
508    model: shortModel(i.model),
509    ctx: ctxText(i.usage.ctxPct),
510    rates: i.usage.rates,
511    resetsNowMs: i.nowMs,
512    cost: costText(i.usage.costUsd),
513    digest: i.digest,
514    compact: compactButton(i.usage.ctxPct, i.isWorking),
515    clear: CLEAR_BUTTON,
516    progress: i.hasChecklist ? PROGRESS_BUTTON : null,
517    log: i.hasEvents ? LOG_BUTTON : null,
518  }
519}
520
521export const HOUR_MS = HOUR
522
523/** `ephemeral_1h_input_tokens` of an Agent result's usage; 0 when absent. */
524export function oneHourCacheTokens(result: unknown): number {
525  const usage = (result as { usage?: { cache_creation?: { ephemeral_1h_input_tokens?: unknown } | null } } | null)?.usage
526  const n = usage?.cache_creation?.ephemeral_1h_input_tokens
527  return typeof n === 'number' ? n : 0
528}
529
530const NO_WORKSPACE_HINT = 'no task workspace — /base:save-task-context'
531const NO_PROGRESS_HINT = 'no progress.md yet — /base:save-task-context'
532
533const MARKS: ReadonlySet<string> = new Set<ChecklistMark>(['done', 'current', 'waiting', 'todo'])
534
535type Snapshot = Record<string, unknown> & { workId: string }
536
537/** Another plugin writes the snapshot, so every field is checked: a value that is not a finite number reads 0. */
538function snapshotOf(p: unknown): Snapshot | null {
539  if (p === null || typeof p !== 'object') return null
540  const s = p as Record<string, unknown>
541  return typeof s.workId === 'string' && s.workId !== '' ? (s as Snapshot) : null
542}
543
544const num = (x: unknown): number => (typeof x === 'number' && Number.isFinite(x) ? x : 0)
545
546/** base's published task as the generic checklist the Progress pane draws; null while no task resolves. */
547export function toChecklist(p: unknown): Checklist | null {
548  const s = snapshotOf(p)
549  if (s === null) return null
550  const done = num(s.done)
551  const total = num(s.total)
552  const branch = typeof s.branch === 'string' && s.branch !== '' ? s.branch : null
553  const subtitle = [branch, total ? `${done}/${total}` : null].filter(Boolean).join(' · ')
554  const rows: ChecklistRow[] = (Array.isArray(s.rows) ? s.rows : [])
555    .filter((r): r is { mark?: unknown; text: string } => r !== null && typeof r === 'object' && typeof (r as { text?: unknown }).text === 'string')
556    .map(r => ({ mark: typeof r.mark === 'string' && MARKS.has(r.mark) ? (r.mark as ChecklistMark) : 'todo', text: r.text }))
557  const hint = s.hasWorkspace === false ? NO_WORKSPACE_HINT : total === 0 ? NO_PROGRESS_HINT : null
558  const notes = Array.isArray(s.notesTail) ? s.notesTail.filter((l): l is string => typeof l === 'string') : []
559  const footer = [...(hint === null ? [] : [hint]), ...notes]
560  return { v: 1, title: s.workId, ...(subtitle ? { subtitle } : {}), rows, ...(footer.length ? { footer } : {}) }
561}
562
563/** Band digest: `ELC-1591 3/5 ▶ Preview themes`, `ELC-1591 ✓ 5/5` when every row is checked, the id alone with no rows. */
564export function digestOf(p: unknown): string | null {
565  const s = snapshotOf(p)
566  if (s === null) return null
567  const done = num(s.done)
568  const total = num(s.total)
569  const current = typeof s.current === 'string' ? s.current : null
570  if (total === 0) return s.workId
571  if (current === null) return `${s.workId} ✓ ${done}/${total}`
572  return `${s.workId} ${done}/${total} ▶ ${current}`
573}
574
575/** The plan and the person behind a login, as a login record or the profile endpoint reports them. */
576export type AccountFacts = Pick<BandAccount, 'plan' | 'email' | 'org' | 'role'>
577
578const FACT_MAX = 120
579
580/** A non-empty string field of an untrusted record, on one line and capped; anything else → null. */
581function fact(x: unknown): string | null {
582  if (typeof x !== 'string') return null
583  const v = x.replace(/[\u0000-\u001f\u007f]+/g, ' ').trim()
584  return v ? [...v].slice(0, FACT_MAX).join('') : null
585}
586
587/** `oauthAccount` of the host's login record (`.claude.json`); null without that object. */
588export function loginAccount(json: unknown): AccountFacts | null {
589  if (!isRecord(json) || !isRecord(json.oauthAccount)) return null
590  const a = json.oauthAccount
591  return { plan: fact(a.organizationType), email: fact(a.emailAddress), org: fact(a.organizationName), role: fact(a.organizationRole) }
592}
593
594/** The picker families a login cannot use: `hiddenModels` in MODEL_ALIASES order, `hiddenReason` why (null when none is hidden). */
595export type CreditGate = Pick<BandAccount, 'hiddenModels' | 'hiddenReason'>
596
597/**
598 * Whether the host bills `id` to usage credits, from the login record's `cachedGrowthBookFeatures.tengu_saffron_lattice`
599 * flag: its `perModel` entry for the id (a key matched by family, a trailing `[1m]` dropped) decides by `enabled`; else
600 * plan-wide `enabled: false` → no; else `overageConsentRequired: true` or a `planLimitsEndDate` → yes. No flag → no.
601 */
602function billedToCredits(json: Record<string, unknown>, id: string): boolean {
603  const flags = json.cachedGrowthBookFeatures
604  const lattice = isRecord(flags) ? flags.tengu_saffron_lattice : undefined
605  if (!isRecord(lattice)) return false
606  const family = modelFamily(id.replace(/\[1m\]$/, ''))
607  if (isRecord(lattice.perModel)) {
608    const key = Object.keys(lattice.perModel).find(k => modelFamily(k.replace(/\[1m\]$/, '')) === family)
609    const per = key === undefined ? undefined : lattice.perModel[key]
610    if (isRecord(per)) return per.enabled === true
611  }
612  if (lattice.enabled === false) return false
613  return lattice.overageConsentRequired === true || lattice.planLimitsEndDate !== undefined
614}
615
616/**
617 * The login record's credit-gated families: those of `additionalModelOptionsCache[].value` (a trailing `[1m]` dropped)
618 * that the record's lattice flag bills to usage credits (`billedToCredits`), hidden while extra usage is unusable:
619 * `cachedExtraUsageDisabledReason` is a non-empty string (it is the reason), or `oauthAccount.hasExtraUsageEnabled` is
620 * false (`extra_usage_off`). A plan that includes the model (Fable on Max) hides nothing; so do missing or malformed keys.
621 */
622export function creditGate(json: unknown): CreditGate {
623  const none: CreditGate = { hiddenModels: [], hiddenReason: null }
624  if (!isRecord(json)) return none
625  const reason = fact(json.cachedExtraUsageDisabledReason) ?? (isRecord(json.oauthAccount) && json.oauthAccount.hasExtraUsageEnabled === false ? 'extra_usage_off' : null)
626  if (reason === null || !Array.isArray(json.additionalModelOptionsCache)) return none
627  const gated = new Set(
628    json.additionalModelOptionsCache.flatMap(o =>
629      isRecord(o) && typeof o.value === 'string' && billedToCredits(json, o.value) ? [modelFamily(o.value.replace(/\[1m\]$/, ''))] : [],
630    ),
631  )
632  const hiddenModels = MODEL_ALIASES.filter(a => gated.has(a))
633  return hiddenModels.length ? { hiddenModels, hiddenReason: reason } : none
634}
635
636/** The OAuth profile endpoint's body (`account.email`, `organization.organization_type` / `name`); null when it names neither plan nor email. */
637export function profileAccount(json: unknown): AccountFacts | null {
638  if (!isRecord(json)) return null
639  const account = isRecord(json.account) ? json.account : {}
640  const org = isRecord(json.organization) ? json.organization : {}
641  const facts = { plan: fact(org.organization_type), email: fact(account.email), org: fact(org.name), role: null }
642  return facts.plan === null && facts.email === null ? null : facts
643}
644
645/** `claude_team` / `claude_enterprise` → work; any other plan → personal; no plan → null. */
646export function accountLabel(plan: string | null): BandAccount['label'] {
647  if (plan === null) return null
648  return plan === 'claude_team' || plan === 'claude_enterprise' ? 'work' : 'personal'
649}
650
651export type AccountMode = 'on' | 'off' | 'work' | 'personal'
652
653/** BAND_ACCOUNT: `0` hides the segment, `work` / `personal` forces it; anything else (unset included) reads the login. */
654export function accountMode(v: string | undefined): AccountMode {
655  const t = v?.trim().toLowerCase()
656  return t === '0' ? 'off' : t === 'work' || t === 'personal' ? t : 'on'
657}
658
659const isAbsolute = (p: string): boolean => /^(\/|[A-Za-z]:[\\/])/.test(p)
660
661/**
662 * Where the host keeps the login: `<CLAUDE_CONFIG_DIR>/.claude.json` when that is set, else `<HOME>/.claude.json`;
663 * `configDir` is the config directory as the card shows it (`~` for HOME). An empty CLAUDE_CONFIG_DIR counts as unset; a
664 * leading `~/` stands for HOME; any other relative value gives `file` null (the host reads it under its cwd), never HOME's.
665 */
666export function loginPaths(home: string | undefined, configDir: string | undefined): { file: string | null; configDir: string | null } {
667  const h = home && isAbsolute(home) ? home.replace(/\/+$/, '') : null
668  const tilde = (p: string) => (h !== null && (p === h || p.startsWith(`${h}/`)) ? `~${p.slice(h.length)}` : p)
669  if (configDir) {
670    const raw = configDir === '~' || configDir.startsWith('~/') ? (h === null ? null : h + configDir.slice(1)) : configDir
671    if (raw === null || !isAbsolute(raw)) return { file: null, configDir }
672    const dir = raw.replace(/\/+$/, '')
673    return { file: `${dir}/.claude.json`, configDir: tilde(dir) }
674  }
675  if (h !== null) return { file: `${h}/.claude.json`, configDir: '~/.claude' }
676  return { file: null, configDir: null }
677}
678
679/** `claude_max` → `Claude Max`. */
680export function planName(plan: string): string {
681  return plan
682    .split('_')
683    .filter(Boolean)
684    .map(w => w[0].toUpperCase() + w.slice(1))
685    .join(' ')
686}
687
688/**
689 * `account: work (Claude Team) · email: … · org: … · role: … · models: opus, sonnet, haiku (fable needs credits) ·
690 * config: ~/.claude-x · source: login record`; `models` only while a family is hidden.
691 */
692export function accountCard(a: BandAccount): string {
693  const why = a.source === 'BAND_ACCOUNT' ? 'forced by BAND_ACCOUNT' : a.plan !== null ? planName(a.plan) : null
694  const hidden = a.hiddenModels
695  const models = hidden.length
696    ? `models: ${MODEL_ALIASES.filter(m => !hidden.includes(m)).join(', ')} (${hidden.join(', ')} ${hidden.length > 1 ? 'need' : 'needs'} credits)`
697    : null
698  return [
699    `account: ${a.label ?? 'none'}${why ? ` (${why})` : ''}`,
700    ...(a.email !== null ? [`email: ${a.email}`] : []),
701    ...(a.org !== null ? [`org: ${a.org}`] : []),
702    ...(a.role !== null ? [`role: ${a.role}`] : []),
703    ...(models !== null ? [models] : []),
704    ...(a.configDir !== null ? [`config: ${a.configDir}`] : []),
705    ...(a.source !== null ? [`source: ${a.source}`] : []),
706  ].join(' · ')
707}
708
hooks/mods/events.ts 162 lines
1// Pure event-log and pane helpers: band's own ring buffer, the merge of every publisher's list, the
2// pane's row model and the lines of band's file on disk. No `$` here: the writer keeps its own
3// `logEvent` wrapper, as the validator follows `$` only within one file.
4import type { BandEvent, ForeignEvent, LogLine, LogSource, TeamSource } from '../../types'
5
6export const EVENT_CAP = 200
7export const LOG_PANE = 'band-log'
8export const LOG_COMMAND = { name: 'band-log', description: 'Open the band event log pane', immediate: true } as const
9export const CHECKLIST_PANE = 'band-progress'
10export const CHECKLIST_COMMAND = { name: 'band-progress', description: 'Open the band task checklist pane', immediate: true } as const
11export const DEBUG_COMMAND = { name: 'band-debug', description: 'Show the raw figures behind the status band (debug)' } as const
12
13/** Appends `ev`, oldest first, at most EVENT_CAP: past the cap the oldest line goes. */
14export function pushEvent(list: readonly BandEvent[], ev: BandEvent): BandEvent[] {
15  return list.length < EVENT_CAP ? [...list, ev] : [...list.slice(1), ev]
16}
17
18/** Another plugin writes the list: an entry without a finite `atMs` or a string `kind`/`text` is dropped, extra fields too. */
19export function take(list: unknown): ForeignEvent[] {
20  if (!Array.isArray(list)) return []
21  const out: ForeignEvent[] = []
22  for (const ev of list) {
23    const e = ev as Partial<ForeignEvent> | null
24    if (e && typeof e === 'object' && Number.isFinite(e.atMs) && typeof e.kind === 'string' && typeof e.text === 'string') {
25      out.push({ atMs: e.atMs as number, kind: e.kind, text: e.text })
26    }
27  }
28  return out
29}
30
31const tag = (plugin: LogSource) => (e: ForeignEvent): LogLine => ({ ...e, plugin })
32
33/** The team plugins on base, in the order their lines follow slim's on a tie. */
34export const TEAM_SOURCES: readonly TeamSource[] = ['fe', 'qa', 'be', 'pm']
35
36/**
37 * band's, base's, slim's and the team plugins' lines in one list, oldest first, each tagged with the list it
38 * came from; on equal times band → base → slim → fe → qa → be → pm, each list in its own order.
39 */
40export function merged(own: unknown, base: unknown, slim: unknown, teams: Partial<Record<TeamSource, unknown>> = {}): LogLine[] {
41  const t = TEAM_SOURCES.flatMap(p => take(teams[p]).map(tag(p)))
42  return [...take(own).map(tag('band')), ...take(base).map(tag('base')), ...take(slim).map(tag('slim')), ...t]
43    .map((e, i) => ({ e, i }))
44    .sort((a, b) => a.e.atMs - b.e.atMs || a.i - b.i)
45    .map(x => x.e)
46}
47
48/** Whether any of the lists holds a valid line, without merging them. */
49export function anyEvent(...lists: unknown[]): boolean {
50  return lists.some(l => take(l).length > 0)
51}
52
53const pad2 = (n: number) => String(n).padStart(2, '0')
54
55/** Local `09:05`. */
56export function hhmm(ms: number): string {
57  const d = new Date(ms)
58  return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`
59}
60
61/** 412_345 → `412k`; below 1000 the number as is. */
62export function fmtK(n: number): string {
63  return n < 1000 ? String(n) : `${Math.round(n / 1000)}k`
64}
65
66/** The source list padded to 5, so the kinds line up. */
67export function pluginCell(plugin: string): string {
68  return plugin.padEnd(5)
69}
70
71/** The kind padded to the longest kind, `workspace`, so the texts line up. */
72export function kindCell(kind: string): string {
73  return kind.padEnd(9)
74}
75
76/** The newest lines `/band-log` answers with as text, where no pane draws. */
77export const TEXT_LOG_ROWS = 40
78
79/** One line of `/band-log`'s text answer: `09:05  base   guard      Bash: --no-verify`. */
80export function logRow(ev: LogLine): string {
81  return `${hhmm(ev.atMs)}  ${pluginCell(ev.plugin)}  ${kindCell(ev.kind)}  ${ev.text}`
82}
83
84/** Cells the time, plugin and kind columns take before the text: `09:05  `, `base   ` and `workspace  `. */
85export const PREFIX_COLS = 7 + 7 + 9 + 2
86
87/** Rows one text takes wrapped at `cols` cells, at least one. */
88export function textRows(text: string, cols: number): number {
89  return Math.max(1, Math.ceil(text.length / Math.max(1, cols)))
90}
91
92/**
93 * The newest events whose wrapped rows fit in `rows` (all of them when `rows` is 0 or they all fit);
94 * when some are left out, one row is kept for the `… N earlier` line.
95 */
96export function newestFitting<T extends { text: string }>(list: readonly T[], rows: number, cols: number): T[] {
97  if (rows <= 0) return [...list]
98  let used = 0
99  let i = list.length
100  while (i > 0 && used + textRows(list[i - 1]!.text, cols) <= rows) used += textRows(list[--i]!.text, cols)
101  if (i === 0) return [...list]
102  while (i < list.length && used > rows - 1) used -= textRows(list[i++]!.text, cols)
103  return list.slice(i)
104}
105
106export const FILE_CAP_LINES = 2000
107export const FILE_CAP_BYTES = 256 * 1024
108
109const trimSlash = (p: string) => p.replace(/\/+$/, '')
110
111/**
112 * `<DOMAINE_LOG_DIR>/<session>` when the override is absolute, else `$HOME/.claude/domaine/log/<session>`; null
113 * with neither, or for a session id that is no plain name. Same rule as base and slim, so one session's files
114 * share one directory.
115 */
116export function logDir(home: string | undefined, override: string | undefined, sessionId: string): string | null {
117  if (!/^[\w.-]+$/.test(sessionId) || /^\.+$/.test(sessionId)) return null
118  const o = override?.trim() ?? ''
119  const h = home?.trim() ?? ''
120  const root = o.startsWith('/') ? trimSlash(o) : h.startsWith('/') ? `${trimSlash(h)}/.claude/domaine/log` : null
121  return root === null ? null : `${root}/${sessionId}`
122}
123
124/** One line of `band.jsonl`; `plugin` is band's own name, never taken from another plugin's state. */
125export function fileLine(atMs: number, version: string, session: string, kind: string, text: string): string {
126  return JSON.stringify({ ts: new Date(atMs).toISOString(), plugin: 'band', version, session, kind, agent: 'main', text })
127}
128
129/** The lines of an existing file that belong to `session`; anything unparsable or another session's goes. */
130export function seedLines(fileText: string, session: string): string[] {
131  return fileText.split('\n').filter(l => {
132    try {
133      return (JSON.parse(l) as { session?: unknown }).session === session
134    } catch {
135      return false
136    }
137  })
138}
139
140function utf8Bytes(s: string): number {
141  let n = 0
142  for (let i = 0; i < s.length; i++) {
143    const c = s.charCodeAt(i)
144    if (c < 0x80) n += 1
145    else if (c < 0x800) n += 2
146    else if (c >= 0xd800 && c < 0xdc00) {
147      n += 4
148      i++
149    } else n += 3
150  }
151  return n
152}
153
154/** Oldest lines dropped until at most FILE_CAP_LINES remain and the file, newlines counted, fits FILE_CAP_BYTES. */
155export function capLines(lines: readonly string[]): string[] {
156  const out = lines.slice(-FILE_CAP_LINES)
157  let bytes = out.reduce((n, l) => n + utf8Bytes(l) + 1, 0)
158  let drop = 0
159  while (bytes > FILE_CAP_BYTES && drop < out.length) bytes -= utf8Bytes(out[drop++]!) + 1
160  return out.slice(drop)
161}
162
types/index.d.ts 112 lines
1// The band plugin's $.state contract: the keys band owns and writes, and the other plugins' keys it reads,
2// typed locally (no `dependencies`). Values are JSON; a value never written reads as the atom's initial.
3
4/** One rate-limit window as the band draws it; `pct` is the raw percentUsed (may pass 100). */
5export type BandRate = { kind: string; label: string; pct: number; resetsAt: string | null }
6
7/** Context, rate and cost figures; `ctxPct`/`ctxTokens` are null until the first reading and after a compaction; `costUsd` is null where the host keeps no ledger or BAND_COST is off. */
8export type BandUsage = { ctxPct: number | null; ctxTokens: number | null; window: number; rates: BandRate[]; costUsd: number | null }
9
10/** Prompt-cache estimate: `anchorMs` = clock time of the last main-thread response, null before one. */
11export type BandCache = {
12  anchorMs: number | null
13  ttlMs: number
14  ttlSource: 'option' | 'store' | 'agent' | 'subscription' | 'default'
15  isCold: boolean
16}
17
18/**
19 * The claude.ai login the session runs on. `label`: `work` for a Team or Enterprise organization, `personal` for any
20 * other plan, null when the plan is unknown (no segment). `plan` is the raw organization type (`claude_team`);
21 * `configDir` the config directory as shown (`~/.claude`); `source` where the label came from. `hiddenModels`: the
22 * model-picker families the login cannot use (credit-gated while extra usage is unusable), [] when none or unknown;
23 * `hiddenReason`: why, one word (`out_of_credits`, `extra_usage_off`), null when nothing is hidden.
24 */
25export type BandAccount = {
26  label: 'work' | 'personal' | null
27  plan: string | null
28  email: string | null
29  org: string | null
30  role: string | null
31  configDir: string | null
32  source: 'login record' | 'profile endpoint' | 'BAND_ACCOUNT' | null
33  hiddenModels: string[]
34  hiddenReason: string | null
35}
36
37export type BandEventKind = 'session' | 'model' | 'compact' | 'rate'
38/** One of band's own event-log lines; `atMs` = `$.clock.now()` when written, `text` is one line. */
39export type BandEvent = { atMs: number; kind: BandEventKind; text: string }
40
41/** Written at every session.start of band, so non-null iff band is loaded; `disabled` = userConfig `disabled`. */
42export type BandInfo = { v: 1; version: string; disabled: boolean }
43
44/** A line from another plugin's event log; band reads only these fields and drops an entry missing one. */
45export type ForeignEvent = { atMs: number; kind: string; text: string }
46
47/** A team plugin on base whose event list band reads. */
48export type TeamSource = 'fe' | 'qa' | 'be' | 'pm'
49/** The list a log line came from: the PLUGIN column of the Log pane and `/band-log`. */
50export type LogSource = 'band' | 'base' | 'slim' | TeamSource
51/** One line of the merged log, tagged with its source list. */
52export type LogLine = ForeignEvent & { plugin: LogSource }
53
54export type ChecklistMark = 'done' | 'current' | 'waiting' | 'todo'
55export type ChecklistRow = { mark: ChecklistMark; text: string }
56/** The generic shape the Progress pane draws; band maps the published task snapshot into it. */
57export type Checklist = { v: 1; title: string; subtitle?: string; rows: ChecklistRow[]; footer?: string[] }
58
59/**
60 * base's resolved task (its BaseProgress) as band reads it; every field is checked before use.
61 * `stale`: a workspace with savable work and no write within base's window.
62 */
63export type ProgressSnapshot =
64  | { workId: string; branch: string | null; hasWorkspace: boolean; done: number; total: number; current: string | null; rows: ChecklistRow[]; notesTail: string[]; mtimeMs: number; stale?: boolean }
65  | { workId: null; branch: string | null }
66
67declare module 'claude-code' {
68  interface PluginState {
69    band: {
70      info: BandInfo | null
71      usage: BandUsage
72      model: string | null
73      cache: BandCache
74      /** clock time of the last refresh; 0 until the first session.start of this process */
75      tick: number
76      rateAlarmed: boolean
77      /** the login the session runs on; null without a claude.ai login, under BAND_ACCOUNT=0, or before the first read */
78      account: BandAccount | null
79      /** the band-progress pane is placed and not closed; the band hides its digest then */
80      paneShown: boolean
81      /** the band holds the keyboard; hotkey letters are drawn only then */
82      bandFocused: boolean
83      /** the terminal's model picker is unfolded: the band row holds the models alone */
84      modelPicker: boolean
85      /** band's own event lines, oldest first, at most 200; stays [] under BAND_EVENT_LOG=0 */
86      events: BandEvent[]
87    }
88    /** Owned and written by the base plugin; band only reads it (null / [] without base). */
89    base: {
90      events: ForeignEvent[]
91      progress: ProgressSnapshot | null
92    }
93    /** Owned and written by the slim plugin; band only reads it. */
94    slim: {
95      events: ForeignEvent[]
96    }
97    /** Owned and written by the team plugins (fe, qa, be, pm); band only reads their event lists ([] without the plugin). */
98    fe: {
99      events: ForeignEvent[]
100    }
101    qa: {
102      events: ForeignEvent[]
103    }
104    be: {
105      events: ForeignEvent[]
106    }
107    pm: {
108      events: ForeignEvent[]
109    }
110  }
111}
112