SLOPSHOPPER

usage-bar

See your Claude Code session at a glance: context left, cost, today's and month-to-date spend, rate limits, git diff and PR status, right above the prompt. Set…

bandguardcommandtoastpromptprocess
★ 4v1.1.0no licenseupdated 2026-10-23abyigiter/claude-usage-bar/usage-bar
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · usage-bar
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /budget ⎿ usage-bar: No budget set. /budget 10 sets a session budget, /budget day 50 a daily one. 5h ━━━━━━ 31% ctx ━━━━━━ 49% 97.4k/200k $0.42 $0.00/h 9 calls 382d 8h opus-5.5 ▾ more ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
5h ━━━━━━ 31% ctx ━━━━━━ 49% 97.4k/200k $0.42 $0.00/h 9 calls 382d 8h opus-5.5 ▾ more
README

usage-bar

A Claude Code mod: a live band above the prompt with your context window, spend, rate limits, git state and pull request, plus a ▾ more panel that shows where the context and the money went.

Works in the Claude Code CLI, the desktop app's Code tab (Claude Code 2.1.287 or later), and pi.

Desktop header

Desktop detail panel

Terminal header

Terminal detail panel

Install

/plugin marketplace add abyigiter/claude-usage-bar
/plugin install usage-bar@abyigiter-mods
/reload-plugins

Update later with /plugin marketplace update abyigiter-mods, then /reload-plugins.

pi

The same bar runs in pi as a widget above the editor:

pi install git:github.com/abyigiter/claude-usage-bar

Chips for context, cost (against your budget), today's and month-to-date spend, the running turn, git diff, the branch's PR, tool calls, session time and model. /usage toggles the detail panel, as does alt+u (context forecast, spend per turn, turns and cache hit, top tools, edited files, failing checks); /usage text prints the figures. /budget works as below, stored in ~/.pi/agent/usage-bar.json.

Today, the last 7 days and the month to date are exact in pi: they are summed from the cost pi records on every message in every session file under ~/.pi/agent/sessions. There is no rate-limit chip, since pi talks to many providers. It sits happily next to a custom footer such as pi-powerline-footer.

Tests: npm test (the drawing and parsing in pi/core.ts).

The header

Each figure is a pill colored by what it is, turning yellow or red when it needs attention. Pills flow in one row and wrap as units.

PillShows
5H / 7DRate-limit use with a bar, a pace tick at the window's elapsed time, and the reset countdown. Yellow when your pace would hit 100% before reset, red past 150% pace or 90% used. Hidden off a subscription.
CTXContext window fill, tokens, and the last turn's growth.
● 0:42A live timer while Claude works.
gitBranch, lines added and removed against HEAD (+421 −68), untracked files (?1), ahead and behind.
PRThe branch's pull request through gh: state, review, CI (✓ pass, ✗ fail, ● running). Re-checked every 5 minutes, every minute while CI runs, with a toast when it finishes. Needs the GitHub CLI signed in.
COSTSession spend and burn rate ($/h), against your budget when one is set.
TODAYSpend across every session today, a bar per day for the last 7 days, the 7-day total and month to date (mtd). Hover it on desktop for the day-by-day figures.

In the terminal the same figures are tinted chips.

The detail panel

▾ more opens four cards on desktop (aligned rows in the terminal). Cards with nothing to show yet are left out.

  • Context: a stacked bar by /context category (messages, tools, MCP, memory, skills) and how many turns are left before auto-compact at your average growth.
  • Spend: total, today, last 7 days, month to date, last turn, average per turn, a bar per turn.
  • Turns: count, average and longest duration, prompt cache hit rate, tokens written, a bar per turn.
  • Tools: the top five tools (MCP names shortened). Failing CI checks are listed under the panel.

Budgets

/budget 10          session budget of $10
/budget day 50      daily budget of $50
/budget off         clear both (or /budget off day, /budget off session)
/budget             show where you stand

A toast fires at 80% and at 100% of each budget, and once when your burn rate will cross the session budget within 15 minutes.

Daily and monthly spend

Each session keeps its own running total per local day in the plugin store (kept 35 days); today is the sum over sessions, month to date the sum since the 1st. A session that began today counts in full, one carried over from an earlier day counts from its first reading today.

/usage

Prints everything above as text: limits with pace, context, session cost, today, the last 7 days and month to date, budgets, turns and cache hit rate, tools, edited files, git and PR with failing checks, model.

What it reads and runs

No API calls of its own, no keys, no telemetry. Everything is local except the PR lookup, which goes through your own gh login.

Claude Codepi
Usage and costClaude Code's own figures ($.session.usage()), the same numbers as /cost and the status lineThe cost pi records on each message, read from your session files under ~/.pi/agent/sessions
Context breakdownClaude Code's local /context estimate (breakdown: "summary", no token-count requests)Not available
Commands it runs, in the session's directorygit status --porcelain=v1 -b, git diff HEAD --shortstat, gh pr view --json number,url,state,isDraft,reviewDecision,statusCheckRollupThe same three
What it writesBudgets and per-day totals in the plugin's own storeBudgets in ~/.pi/agent/usage-bar.json

git runs every minute and after each turn. gh runs at most every 5 minutes (every minute while CI runs) and only on a branch, and it does nothing when gh is missing or signed out. It never reads .env files, credentials or the contents of your repo; the git commands only return file counts and line totals.

Building it

A standard mod plugin: .claude-plugin/plugin.json, hooks/hooks.json, one hooks module. Readings come from $.session.usage() on session.measure, turn.complete and a one-minute timer; the context breakdown from $.session.usage({ breakdown: "summary" }), a local estimate. The header and cards on desktop are SVG drawings; the terminal draws Ink text. State lives in $.state so it survives hot reloads; budgets and the day totals in $.store.

Tests: claude plugin test ./usage-bar.

Source 2 files
hooks/usage-bar.mjs 1265 lines
1// Usage bar: a strip above the prompt with rate limits, context, cost, git,
2// a live turn timer, activity, and model. ▾ opens a detail panel (context
3// breakdown and compaction forecast, spend per turn, turn timing and cache hit
4// rate, top tools); /usage prints the same as text.
5
6const READING = { plugin: "usage-bar", key: "last" };
7const ACTIVITY = { plugin: "usage-bar", key: "activity" };
8const GIT = { plugin: "usage-bar", key: "git" };
9const TURN = { plugin: "usage-bar", key: "turn" };
10const UI = { plugin: "usage-bar", key: "ui" };
11const TURNS = { plugin: "usage-bar", key: "turns" };
12const CTXMAP = { plugin: "usage-bar", key: "ctxmap" };
13const BUDGET = { plugin: "usage-bar", key: "budget" };
14const LEDGER = { plugin: "usage-bar", key: "ledger" };
15const ALERTS = { plugin: "usage-bar", key: "alerts" };
16const BAR_FILLED = "▰";
17const BAR_EMPTY = "▱";
18const BAR_WIDTH = 8;
19const BARS = "▁▂▃▄▅▆▇█";
20const HISTORY = 12;
21const TURN_LOG = 24;
22const PR_TTL = 5 * 60_000;
23const PR_TTL_PENDING = 60_000; // while CI runs, so its result toasts soon after
24const LEDGER_DAYS = 35; // a whole month back, so month to date always reaches the 1st
25const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
26let commandName;
27let turnStart = 0; // ms, 0 when no turn is running
28
29export function register(on) {
30  on("session.start", async ($, e, next) => {
31    const result = await next(e);
32    await takeReading($);
33    await $.state.set(BUDGET, (await storeGet($, "budget")) ?? {});
34    await syncLedger($);
35    try { await $.store.delete("ledger"); } catch { /* 0.9.0's shared ledger, replaced */ }
36    $.clock.every(60_000, () => takeReading($)); // keep reset countdowns fresh
37    $.clock.every(1000, () => { // live turn timer: redraw each second while a turn runs
38      if (turnStart && Date.now() - turnStart < 2 * 3_600_000) $.state.get(TURN).then(({ value: t }) => $.state.set(TURN, { ...t, startedAt: turnStart, tick: Date.now() }));
39    });
40    try {
41      await $.command.register({ name: "budget", description: "Spend budget: /budget 10 (session), /budget day 50, /budget off" });
42    } catch {
43      // taken by another plugin
44    }
45    for (const name of ["usage", "context"]) {
46      try {
47        await $.command.register({ name, description: "Rate limits, context forecast, cost, and activity" });
48        commandName = name;
49        break;
50      } catch {
51        // name taken; try the next one
52      }
53    }
54    return result;
55  });
56
57  on("command.run", { command: "usage" }, ($, e, next) => answerUsage($, e, next));
58  on("command.run", { command: "context" }, ($, e, next) => answerUsage($, e, next));
59  on("command.run", { command: "budget" }, ($, e) => answerBudget($, e));
60
61  on("prompt.submit", async ($, e, next) => {
62    turnStart = Date.now();
63    const { value: u } = await $.state.get(READING);
64    await $.state.set(TURN, { startedAt: turnStart, tick: turnStart, costAt: u?.cost?.usd });
65    return next(e);
66  });
67
68  on("tool.call", async ($, e, next) => {
69    const result = await next(e);
70    const { value: a = { calls: 0, files: [] } } = await $.state.get(ACTIVITY);
71    const files = [...a.files];
72    const p = e.input?.file_path ?? e.input?.notebook_path;
73    if (EDIT_TOOLS.has(e.tool) && p && !files.includes(p)) files.push(p);
74    const tools = { ...a.tools, [e.tool]: (a.tools?.[e.tool] ?? 0) + 1 };
75    await $.state.set(ACTIVITY, { calls: a.calls + 1, files: files.slice(-50), tools });
76    return result;
77  });
78
79  on("session.measure", async ($, e, next) => {
80    const result = await next(e);
81    const { value: prev } = await $.state.get(READING);
82    await $.state.set(READING, mergeReading(prev, {
83      context: e.context,
84      rateLimits: e.rateLimits,
85      cost: e.cost,
86      model: prev?.model,
87    }));
88    return result;
89  });
90
91  on("turn.complete", async ($, e, next) => {
92    const result = await next(e);
93    if (!e.agentId) { // main-loop turns only
94      turnStart = 0;
95      await takeReading($);
96      const { value: after } = await $.state.get(READING);
97      const { value: turn } = await $.state.get(TURN);
98      await logTurn($, e, turn?.costAt, after);
99      await checkBudget($);
100      const { value: ui } = await $.state.get(UI);
101      if (ui?.expanded) await takeBreakdown($);
102    }
103    return result;
104  });
105
106  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
107    const { value: u } = await $.state.get(READING);
108    const { value: a } = await $.state.get(ACTIVITY);
109    const hasUsage = u && (u.rateLimits?.length || u.context?.window || typeof u.cost?.usd === "number");
110    if (!hasUsage && !a?.calls) return next(e);
111    if (e.props.hasSurvey) return next(e);
112    const { value: git } = await $.state.get(GIT);
113    const { value: turn } = await $.state.get(TURN);
114    const { value: ui } = await $.state.get(UI);
115    const { value: budget = {} } = await $.state.get(BUDGET);
116    const { value: ledger } = await $.state.get(LEDGER);
117    const view = {
118      u, a, git, budget, ledger,
119      working: e.props.isWorking && turn?.startedAt ? Date.now() - turn.startedAt : null,
120      columns: e.props.bodyColumns,
121    };
122    const els = $.ui.resolve(e);
123    const isDesktop = e.surface === "desktop";
124    const { Box, Button } = els;
125    const expanded = !!ui?.expanded;
126    const more = Button({
127      key: "more",
128      label: expanded ? "▴ less" : "▾ more",
129      plain: true,
130      dimColor: true,
131      onPress: async () => {
132        await $.state.set(UI, { expanded: !expanded });
133        if (!expanded) await takeBreakdown($);
134      },
135    });
136    let header;
137    if (isDesktop) {
138      const { left, right } = desktopRow(els, view);
139      if (!left.length && !right.length) return next(e);
140      // one even flow: pills wrap as units in a fixed order, never as two
141      // ragged groups when one pill (a long branch, a PR) grows
142      header = Box({ flexDirection: "row", flexWrap: "wrap", alignItems: "center", columnGap: 1, paddingX: 1, children: [...left, ...right, more] });
143    } else {
144      const row = terminalRow(els, view);
145      if (!row.length) return next(e);
146      header = Box({ flexDirection: "row", flexWrap: "wrap", alignItems: "center", columnGap: 1, paddingX: 1, children: [...row, more] });
147    }
148    const body = [header];
149    if (expanded) {
150      const { value: turns = [] } = await $.state.get(TURNS);
151      const { value: map } = await $.state.get(CTXMAP);
152      const d = { ...insights(u, a, turns, map), budget, ledger };
153      // the panel sits on the header's own inset, so cards line up with the pills
154      body.push(isDesktop
155        ? Box({ key: "details-box", flexDirection: "column", paddingX: 1, paddingTop: 1, children: [desktopDetails(els, d, git, u)] })
156        : terminalDetails(els, d, git, u, view.columns));
157      const links = failingChecks(els, git?.pr);
158      if (links) body.push(links);
159    }
160    return Box({ flexDirection: "column", children: body });
161  });
162}
163
164// Failing checks by name, under the detail panel; only when something failed.
165function failingChecks({ Box, Text }, pr) {
166  if (!pr?.failing?.length) return null;
167  const kids = [Text({ children: "✗ failing ", color: "red", bold: true }), Text({ children: pr.failing.map((c) => c.name).join(" · "), dimColor: true })];
168  return Box({ key: "pr-links", flexDirection: "row", flexWrap: "wrap", alignItems: "center", paddingX: 1, children: kids });
169}
170
171// One record per main-loop turn: how long, what it cost, what it read and wrote.
172// The cost is measured from the prompt's submit: session.measure has already
173// moved the reading by the time the turn completes.
174async function logTurn($, e, costAt, after) {
175  const usd = typeof after?.cost?.usd === "number" && typeof costAt === "number" ? Math.max(0, after.cost.usd - costAt) : null;
176  const k = e.usage ?? {};
177  const rec = {
178    ms: e.durationMs ?? 0,
179    usd,
180    in: k.input_tokens ?? 0,
181    out: k.output_tokens ?? 0,
182    cr: k.cache_read_input_tokens ?? 0,
183    cw: k.cache_creation_input_tokens ?? 0,
184  };
185  const { value: turns = [] } = await $.state.get(TURNS);
186  await $.state.set(TURNS, [...turns, rec].slice(-TURN_LOG));
187  await syncLedger($, true);
188}
189
190// $.store, failing soft: a host without it keeps budgets and the ledger off.
191async function storeGet($, key) {
192  try {
193    return await $.store.get(key);
194  } catch {
195    return undefined;
196  }
197}
198
199async function storeSet($, key, value) {
200  try {
201    await $.store.set(key, value);
202  } catch {
203    // no store on this host
204  }
205}
206
207// ---- budgets and the daily ledger ----------------------------------------------
208// Each session keeps its own running total per local day in $.store, under
209// `day:<date>:<session>`, so parallel sessions never overwrite each other.
210// A session that began today counts in full; one carried over from an earlier
211// day counts from its first reading today. Today is the sum over sessions.
212let sessionKey;
213
214function dayKey(t = Date.now()) {
215  const d = new Date(t);
216  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
217}
218
219async function syncLedger($, isTurn = false) {
220  const { value: u } = await $.state.get(READING);
221  const cost = u?.cost?.usd;
222  if (typeof cost !== "number") return;
223  if (!sessionKey) {
224    try {
225      sessionKey = await $.session.id();
226    } catch {
227      sessionKey = `s${u.startedAt ?? Date.now()}`;
228    }
229  }
230  const day = dayKey();
231  const key = `day:${day}:${sessionKey}`;
232  const prev = await storeGet($, key);
233  const startedToday = typeof u.startedAt === "number" && dayKey(u.startedAt) === day;
234  const entry = prev ?? { spent: startedToday ? cost : 0, last: cost, turns: 0 };
235  if (prev) {
236    const delta = cost - prev.last;
237    entry.spent = prev.spent + (delta < 0 ? cost : delta); // a reset cost counts from zero
238    entry.last = cost;
239  }
240  if (isTurn) entry.turns += 1;
241  if (!prev || prev.spent !== entry.spent || prev.last !== entry.last || isTurn) await storeSet($, key, entry);
242  await refreshLedger($);
243}
244
245// day:<date>:<session> entries before today never change again, so their
246// values are cached between refreshes instead of re-read from the store.
247const pastDays = new Map();
248
249async function refreshLedger($) {
250  let keys = [];
251  try {
252    keys = (await $.store.keys()).filter((k) => k.startsWith("day:"));
253  } catch {
254    return;
255  }
256  const days = [...Array(7)].map((_, i) => dayKey(Date.now() - i * 86_400_000)).reverse();
257  const totals = Object.fromEntries(days.map((d) => [d, { usd: 0, turns: 0 }]));
258  const today = days.at(-1);
259  const month = today.slice(0, 7);
260  const oldest = dayKey(Date.now() - LEDGER_DAYS * 86_400_000);
261  let mtd = 0;
262  for (const k of keys) {
263    const d = k.split(":")[1];
264    if (d < oldest) {
265      pastDays.delete(k);
266      try { await $.store.delete(k); } catch { /* keep */ }
267      continue;
268    }
269    const inMonth = d.startsWith(month);
270    if (!totals[d] && !inMonth) continue;
271    const v = pastDays.has(k) ? pastDays.get(k) : await storeGet($, k);
272    if (d < today) pastDays.set(k, v);
273    if (inMonth) mtd += v?.spent ?? 0;
274    if (!totals[d]) continue;
275    totals[d].usd += v?.spent ?? 0;
276    totals[d].turns += v?.turns ?? 0;
277  }
278  await $.state.set(LEDGER, {
279    date: today,
280    today: totals[today].usd,
281    todayTurns: totals[today].turns,
282    week: days.reduce((s, d) => s + totals[d].usd, 0),
283    month: mtd,
284    days: days.map((d) => totals[d].usd),
285  });
286}
287
288async function answerBudget($, e) {
289  const [a, b] = String(e.args ?? "").trim().toLowerCase().split(/\s+/).filter(Boolean);
290  const budget = (await storeGet($, "budget")) ?? {};
291  const amount = (v) => (v != null && Number.isFinite(+v.replace("$", "")) && +v.replace("$", "") > 0 ? +v.replace("$", "") : null);
292  if (a === "off" || a === "clear") {
293    if (b === "day") delete budget.day;
294    else if (b === "session") delete budget.session;
295    else { delete budget.day; delete budget.session; }
296  } else if (a === "day" && amount(b)) budget.day = amount(b);
297  else if (a === "session" && amount(b)) budget.session = amount(b);
298  else if (amount(a)) budget.session = amount(a);
299  else if (a) return { text: "Usage: /budget 10 (session), /budget day 50, /budget off [day|session]" };
300  await storeSet($, "budget", budget);
301  await $.state.set(BUDGET, budget);
302  await $.state.set(ALERTS, {});
303  await checkBudget($);
304  const { value: u } = await $.state.get(READING);
305  const { value: l } = await $.state.get(LEDGER);
306  return { text: budgetLines(budget, u, l).join("\n") || "No budget set. /budget 10 sets a session budget, /budget day 50 a daily one." };
307}
308
309function budgetLines(budget = {}, u, l) {
310  const lines = [];
311  const cost = u?.cost?.usd ?? 0;
312  if (budget.session) lines.push(`Session budget: $${cost.toFixed(2)} of $${budget.session.toFixed(2)} (${Math.round((cost / budget.session) * 100)}%)`);
313  if (budget.day) lines.push(`Daily budget: $${(l?.today ?? 0).toFixed(2)} of $${budget.day.toFixed(2)} (${Math.round(((l?.today ?? 0) / budget.day) * 100)}%)`);
314  return lines;
315}
316
317// Toast once per level (80%, 100%) per scope, and once when the burn rate will
318// cross the session budget within 15 minutes.
319async function checkBudget($) {
320  const { value: budget = {} } = await $.state.get(BUDGET);
321  if (!budget.session && !budget.day) return;
322  const { value: u } = await $.state.get(READING);
323  const { value: l } = await $.state.get(LEDGER);
324  const { value: seen = {} } = await $.state.get(ALERTS);
325  const next = { ...seen };
326  const burn = burnRate(u);
327  const scopes = [
328    ["session", budget.session, u?.cost?.usd ?? 0, "Session"],
329    ["day", budget.day, l?.today ?? 0, "Today's"],
330  ];
331  for (const [key, limit, spent, name] of scopes) {
332    if (!limit) continue;
333    const level = spent >= limit ? 100 : spent >= limit * 0.8 ? 80 : 0;
334    if (level > (seen[key] ?? 0)) {
335      $.ui.toast(level === 100
336        ? `${name} spend $${spent.toFixed(2)} is over the $${limit.toFixed(2)} budget`
337        : `${name} spend $${spent.toFixed(2)} is at ${Math.round((spent / limit) * 100)}% of the $${limit.toFixed(2)} budget`, { timeoutMs: 8000 });
338      next[key] = level;
339    }
340    if (key === "session" && !seen.pace && level < 80 && burn) {
341      const mins = ((limit - spent) / burn) * 60;
342      if (mins <= 15) {
343        $.ui.toast(`At $${burn.toFixed(2)}/h the $${limit.toFixed(2)} session budget is reached in ~${fmtMinutes(mins)}`, { timeoutMs: 8000 });
344        next.pace = true;
345      }
346    }
347  }
348  await $.state.set(ALERTS, next);
349}
350
351// 0..1+ of the tighter budget, and which one, for the cost figure's color.
352function budgetUse(budget = {}, u, l) {
353  const uses = [
354    budget.session && { scope: "session", limit: budget.session, frac: (u?.cost?.usd ?? 0) / budget.session },
355    budget.day && { scope: "day", limit: budget.day, frac: (l?.today ?? 0) / budget.day },
356  ].filter(Boolean);
357  return uses.sort((x, y) => y.frac - x.frac)[0] ?? null;
358}
359
360function budgetTone(use) {
361  return !use ? null : use.frac >= 1 ? "red" : use.frac >= 0.8 ? "yellow" : "green";
362}
363
364// /context's category rows, estimated locally (no token-count requests).
365async function takeBreakdown($) {
366  try {
367    const usage = await $.session.usage({ breakdown: "summary" });
368    const b = usage?.context?.breakdown;
369    if (!b?.categories) return;
370    await $.state.set(CTXMAP, {
371      at: Date.now(),
372      cats: b.categories.filter((c) => !c.isDeferred).map((c) => ({ name: c.name, tokens: c.tokens, kind: c.kind })),
373    });
374  } catch {
375    // no breakdown on this host
376  }
377}
378
379// Figures the detail views share, derived once per draw.
380function insights(u = {}, a = { calls: 0, files: [] }, turns = [], map) {
381  const ctx = u.context?.window ? { tokens: u.context.tokens ?? 0, window: u.context.window, pct: ctxPct(u.context) } : null;
382  const used = (map?.cats ?? []).filter((c) => c.kind === "used" && c.tokens > 0).sort((x, y) => y.tokens - x.tokens);
383  const free = (map?.cats ?? []).find((c) => c.kind === "free")?.tokens;
384  const growth = (u.history ?? []).slice(1).map((v, i) => v - u.history[i]).filter((d) => d > 0);
385  const perTurn = growth.length ? growth.reduce((s, d) => s + d, 0) / growth.length : null;
386  const turnsLeft = free != null && perTurn ? Math.floor(free / perTurn) : null;
387  const priced = turns.filter((t) => t.usd != null);
388  const spent = priced.reduce((s, t) => s + t.usd, 0);
389  const read = turns.reduce((s, t) => s + t.cr, 0);
390  const fed = turns.reduce((s, t) => s + t.in + t.cr + t.cw, 0);
391  const tools = Object.entries(a.tools ?? {}).sort((x, y) => y[1] - x[1]).slice(0, 5).map(([n, c]) => [toolName(n), c]);
392  return {
393    ctx, used, free, perTurn, turnsLeft,
394    cost: typeof u.cost?.usd === "number" ? u.cost.usd : null,
395    burn: burnRate(u),
396    lastCost: u.costDelta > 0 ? u.costDelta : null,
397    avgCost: priced.length ? spent / priced.length : null,
398    turnCosts: priced.map((t) => t.usd),
399    turns: turns.length,
400    avgMs: turns.length ? turns.reduce((s, t) => s + t.ms, 0) / turns.length : null,
401    maxMs: turns.length ? Math.max(...turns.map((t) => t.ms)) : null,
402    turnMs: turns.map((t) => t.ms),
403    out: turns.reduce((s, t) => s + t.out, 0),
404    cacheHit: fed ? Math.round((read / fed) * 100) : null,
405    calls: a.calls,
406    tools,
407    files: a.files.slice(-4).map((f) => f.split("/").pop()),
408    session: duration(u.startedAt),
409  };
410}
411
412// mcp__Claude_Browser__browser_batch -> browser_batch
413function toolName(n) {
414  return n.startsWith("mcp__") ? n.split("__").pop() : n;
415}
416
417function secs(ms) {
418  if (ms == null) return "–";
419  const s = Math.round(ms / 1000);
420  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
421}
422
423async function answerUsage($, e, next) {
424  if (e.command !== commandName) return next(e);
425  await takeReading($);
426  const { value: u = {} } = await $.state.get(READING);
427  const { value: a = { calls: 0, files: [] } } = await $.state.get(ACTIVITY);
428  const { value: git } = await $.state.get(GIT);
429  const { value: turns = [] } = await $.state.get(TURNS);
430  const { value: budget } = await $.state.get(BUDGET);
431  const { value: ledger } = await $.state.get(LEDGER);
432  return { text: usageLines(u, a, git, turns, budget, ledger).join("\n") };
433}
434
435function usageLines(u = {}, a = { calls: 0, files: [] }, git, turns = [], budget, ledger) {
436  const lines = [];
437  if (u.rateLimits?.length) {
438    lines.push("Rate limits:");
439    for (const rl of u.rateLimits) {
440      const p = clampPct(rl.percentUsed);
441      const reset = resetsIn(rl.resetsAt);
442      const pace = paceOf(rl);
443      const note = pace?.projected != null && pace.projected >= 100
444        ? `  ·  on pace for ${Math.round(pace.projected)}%, hits limit in ~${fmtMinutes(pace.minutesToLimit)}`
445        : pace ? "  ·  pace ok" : "";
446      lines.push(`  ${limitLabel(rl)}  ${bar(p, pace?.elapsed)}  ${p}%${reset ? `  ·  resets in ${reset}` : ""}${note}`);
447    }
448  }
449  if (u.context?.window) {
450    const pct = ctxPct(u.context);
451    const spark = sparkline(u.history);
452    lines.push(`Context: ${short(u.context.tokens ?? 0)} / ${short(u.context.window)} (${pct}%)${spark ? `  ${spark}` : ""}`);
453    if (u.delta) lines.push(`  last turn: ${u.delta > 0 ? `▲ +${short(u.delta)}` : `▼ ${short(-u.delta)}`}`);
454  }
455  const cost = typeof u.cost?.usd === "number" ? `$${u.cost.usd.toFixed(2)}` : null;
456  const dur = duration(u.startedAt);
457  const burn = burnRate(u);
458  const extras = [cost, burn && `$${burn.toFixed(2)}/h`, u.costDelta > 0 && `last turn +$${u.costDelta.toFixed(2)}`, dur].filter(Boolean);
459  if (extras.length) lines.push(`Session: ${extras.join("  ·  ")}`);
460  if (turns.length) {
461    const d = insights(u, a, turns);
462    lines.push(`Turns: ${d.turns}  ·  avg ${secs(d.avgMs)}  ·  longest ${secs(d.maxMs)}${d.cacheHit != null ? `  ·  cache hit ${d.cacheHit}%` : ""}${d.avgCost != null ? `  ·  avg $${d.avgCost.toFixed(2)}/turn` : ""}`);
463  }
464  lines.push(`Activity: ${a.calls} tool call${a.calls === 1 ? "" : "s"}${a.files.length ? `  ·  ${a.files.length} file${a.files.length === 1 ? "" : "s"} edited` : ""}`);
465  const top = Object.entries(a.tools ?? {}).sort((x, y) => y[1] - x[1]).slice(0, 5);
466  if (top.length) lines.push(`  tools: ${top.map(([n, c]) => `${n}×${c}`).join("  ")}`);
467  if (a.files.length) lines.push(`  edited: ${a.files.slice(-5).map((f) => f.split("/").pop()).join(", ")}`);
468  if (ledger) lines.push(`Today: $${ledger.today.toFixed(2)} over ${ledger.todayTurns} turn${ledger.todayTurns === 1 ? "" : "s"}  ·  last 7 days $${ledger.week.toFixed(2)}${ledger.month != null ? `  ·  month to date $${ledger.month.toFixed(2)}` : ""}`);
469  lines.push(...budgetLines(budget, u, ledger));
470  if (git?.branch) lines.push(`Git: ${gitText(git)}`);
471  for (const c of git?.pr?.failing ?? []) lines.push(`  ✗ ${c.name}  ${c.url}`);
472  if (git?.pr?.url) lines.push(`  ${git.pr.url}`);
473  if (u.model) lines.push(`Model: ${shortModel(u.model)}`);
474  return lines;
475}
476
477function gitText(g) {
478  return [
479    g.branch,
480    (g.added || g.removed) && `+${g.added ?? 0} −${g.removed ?? 0}`,
481    g.untracked && `${g.untracked} new`,
482    g.ahead && `↑${g.ahead}`,
483    g.behind && `↓${g.behind}`,
484    g.pr && prText(g.pr),
485  ].filter(Boolean).join("  ·  ");
486}
487
488function prText(pr) {
489  const checks = { pass: "✓ checks", fail: "✗ checks", pending: "● checks" }[pr.checks];
490  const review = { approved: "approved", changes: "changes requested" }[pr.review];
491  return [`PR #${pr.number} ${pr.state}`, review, checks].filter(Boolean).join(" ");
492}
493
494// PR tone: what needs attention first (failing checks, requested changes).
495function prTone(pr) {
496  if (pr.checks === "fail" || pr.review === "changes" || pr.state === "closed") return "red";
497  if (pr.state === "merged") return "purple";
498  if (pr.state === "draft") return "slate";
499  if (pr.checks === "pending") return "yellow";
500  return "green";
501}
502
503// dollars per hour since the session began; needs a few minutes to mean anything
504function burnRate(u) {
505  if (typeof u?.cost?.usd !== "number" || typeof u.startedAt !== "number") return null;
506  const hours = (Date.now() - u.startedAt) / 3_600_000;
507  return hours >= 0.05 && u.cost.usd > 0 ? u.cost.usd / hours : null;
508}
509
510function mmss(ms) {
511  const t = Math.floor(ms / 1000);
512  return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`;
513}
514
515async function takeReading($) {
516  const usage = await $.session.usage();
517  const { value: prev } = await $.state.get(READING);
518  await $.state.set(READING, mergeReading(prev, { ...usage, model: await $.session.model() }));
519  await syncLedger($);
520  await takeGit($);
521}
522
523async function takeGit($) {
524  let git = {};
525  try {
526    const r = await $.process.run(["git", "status", "--porcelain=v1", "-b"], { timeoutMs: 3000 });
527    if (r.exitCode === 0) {
528      const [head, ...rest] = r.stdout.split("\n");
529      const m = /^## (?:No commits yet on |Initial commit on )?(.+?)(?:\.\.\.\S+)?(?: \[(.*)\])?$/.exec(head);
530      const track = m?.[2] ?? "";
531      const files = rest.filter(Boolean);
532      git = {
533        branch: m?.[1]?.startsWith("HEAD (no branch)") ? "detached" : m?.[1],
534        dirty: files.length,
535        untracked: files.filter((l) => l.startsWith("??")).length,
536        ahead: +(/ahead (\d+)/.exec(track)?.[1] ?? 0),
537        behind: +(/behind (\d+)/.exec(track)?.[1] ?? 0),
538        ...(await diffStat($)),
539      };
540    }
541  } catch {
542    // not a repo, or no git
543  }
544  const { value: prev } = await $.state.get(GIT);
545  // the PR changes rarely: look again on a branch switch or every few minutes
546  const ttl = prev?.pr?.checks === "pending" ? PR_TTL_PENDING : PR_TTL;
547  const stale = !prev?.prCheckedAt || prev.branch !== git.branch || Date.now() - prev.prCheckedAt > ttl;
548  if (git.branch && git.branch !== "detached" && stale) {
549    Object.assign(git, await lookupPr($));
550    const was = prev?.branch === git.branch ? prev?.pr : null;
551    if (was?.checks === "pending" && git.pr?.number === was.number && git.pr.checks && git.pr.checks !== "pending") {
552      $.ui.toast(git.pr.checks === "pass"
553        ? `PR #${git.pr.number}: CI passed`
554        : `PR #${git.pr.number}: CI failed (${git.pr.failing.map((c) => c.name).join(", ")})`, { timeoutMs: 10_000 });
555    }
556  }
557  else if (git.branch && prev?.branch === git.branch) Object.assign(git, { pr: prev.pr, prCheckedAt: prev.prCheckedAt });
558  await $.state.set(GIT, git);
559}
560
561// Lines added and removed against HEAD, staged and unstaged together.
562async function diffStat($) {
563  try {
564    const r = await $.process.run(["git", "diff", "HEAD", "--shortstat"], { timeoutMs: 3000 });
565    if (r.exitCode !== 0) return {};
566    return {
567      added: +(/(\d+) insertion/.exec(r.stdout)?.[1] ?? 0),
568      removed: +(/(\d+) deletion/.exec(r.stdout)?.[1] ?? 0),
569    };
570  } catch {
571    return {};
572  }
573}
574
575// The branch's pull request through the GitHub CLI; nothing when gh is missing,
576// signed out, or the branch has none.
577async function lookupPr($) {
578  const checkedAt = Date.now();
579  try {
580    const r = await $.process.run(["gh", "pr", "view", "--json", "number,url,state,isDraft,reviewDecision,statusCheckRollup"], { timeoutMs: 8000 });
581    if (r.exitCode !== 0) return { pr: null, prCheckedAt: checkedAt };
582    const p = JSON.parse(r.stdout);
583    const rollup = p.statusCheckRollup ?? [];
584    const verdict = (c) => (c.conclusion || c.state || c.status || "").toUpperCase();
585    const runs = rollup.map(verdict);
586    const failing = rollup
587      .filter((c) => ["FAILURE", "ERROR", "CANCELLED", "TIMED_OUT", "ACTION_REQUIRED"].includes(verdict(c)))
588      .slice(0, 5)
589      .map((c) => ({ name: c.name || c.context || "check", url: c.detailsUrl || c.targetUrl || p.url }));
590    const checks = !runs.length ? null
591      : runs.some((x) => ["FAILURE", "ERROR", "CANCELLED", "TIMED_OUT", "ACTION_REQUIRED"].includes(x)) ? "fail"
592      : runs.every((x) => ["SUCCESS", "NEUTRAL", "SKIPPED"].includes(x)) ? "pass" : "pending";
593    return {
594      pr: {
595        number: p.number,
596        url: p.url,
597        failing,
598        pending: runs.filter((x) => !["SUCCESS", "NEUTRAL", "SKIPPED", "FAILURE", "ERROR", "CANCELLED", "TIMED_OUT", "ACTION_REQUIRED"].includes(x)).length,
599        state: p.isDraft ? "draft" : String(p.state ?? "").toLowerCase(),
600        review: p.reviewDecision === "APPROVED" ? "approved" : p.reviewDecision === "CHANGES_REQUESTED" ? "changes" : null,
601        checks,
602      },
603      prCheckedAt: checkedAt,
604    };
605  } catch {
606    return { pr: null, prCheckedAt: checkedAt };
607  }
608}
609
610// Deltas are how much the last turn added to context and to cost. Both
611// session.measure and turn.complete refresh the reading in one turn, so only move
612// a delta (and the sparkline history) when its figure actually changed.
613function mergeReading(prev, next) {
614  const startedAt = next.startedAt ?? prev?.startedAt;
615  const usd = next.cost?.usd;
616  const costMoved = usd != null && prev?.cost?.usd != null && usd !== prev.cost.usd;
617  const costDelta = costMoved ? usd - prev.cost.usd : prev?.costDelta;
618  const prevTokens = prev?.context?.tokens;
619  const tokens = next.context?.tokens;
620  if (tokens == null || prevTokens == null || tokens === prevTokens) {
621    return { ...next, startedAt, costDelta, prevTokens: prev?.prevTokens, delta: prev?.delta, history: prev?.history };
622  }
623  return {
624    ...next,
625    startedAt,
626    costDelta,
627    prevTokens,
628    delta: tokens - prevTokens,
629    history: [...(prev?.history ?? []), tokens].slice(-HISTORY),
630  };
631}
632
633// ---- terminal: tinted chips ---------------------------------------------------
634// Each chip is one Box of Texts on a shared tint, glued with no gap inside, so
635// the row wraps between chips and never through one.
636const STATUS_COLOR = { ok: "green", warn: "yellow", crit: "red" };
637const TERM_BAR = 6;
638// [tint, text, accent, muted]
639const CHIP = {
640  green:  ["#1c3328", "#d6f2e1", "#5fcf9a", "#7fa892"],
641  yellow: ["#372f15", "#f5e8b8", "#e6b830", "#ad9b62"],
642  red:    ["#432020", "#fadad4", "#f47563", "#b8837b"],
643  blue:   ["#1f2a46", "#d9e3fa", "#7b9cf2", "#8190b3"],
644  purple: ["#2b2645", "#e0daf8", "#a996ff", "#8f88b3"],
645  cyan:   ["#16323a", "#d0eef2", "#5cc9d6", "#76a3a9"],
646  slate:  ["#29292f", "#e2e2e8", "#a3a3b0", "#82828e"],
647};
648const CTX_TONE = (pct) => (pct < 50 ? "blue" : pct < 75 ? "yellow" : "red");
649
650// parts: [text, "label" | "value" | "aside" | "accent" | "off" | "mark"]
651function chip(Text, tone, parts, key) {
652  const [bg, fg, ac, mu] = CHIP[tone];
653  const style = {
654    label: { color: ac, bold: true },
655    value: { color: fg, bold: true },
656    aside: { color: mu },
657    accent: { color: ac },
658    off: { color: mu, dimColor: true },
659    mark: { color: fg, bold: true },
660    add: { color: "#6fdc9a", bold: true },
661    del: { color: "#f5806f", bold: true },
662  };
663  const last = parts.length - 1;
664  return {
665    key,
666    children: parts.map(([s, kind], i) => Text({
667      backgroundColor: bg,
668      ...style[kind],
669      children: `${i === 0 ? " " : ""}${s}${i === last ? " " : ""}`,
670    })),
671  };
672}
673
674function chipBar(p, elapsed, width = TERM_BAR) {
675  const filled = Math.round((p / 100) * width);
676  const mark = elapsed == null ? -1 : Math.min(width - 1, Math.floor(elapsed * width));
677  const runs = [];
678  for (let i = 0; i < width; i++) {
679    const kind = i === mark ? "mark" : i < filled ? "accent" : "off";
680    const g = kind === "mark" ? "╋" : "━";
681    if (runs.at(-1)?.[1] === kind) runs.at(-1)[0] += g;
682    else runs.push([g, kind]);
683  }
684  return runs;
685}
686
687function terminalRow({ Box, Text }, { u, a, git, working, columns, budget, ledger }) {
688  const wide = columns == null || columns >= 100;
689  const chips = [];
690
691  for (const rl of u?.rateLimits ?? []) {
692    const p = clampPct(rl.percentUsed);
693    const reset = resetsIn(rl.resetsAt);
694    const parts = [[`${limitLabel(rl)} `, "label"], ...chipBar(p, paceOf(rl)?.elapsed), [` ${p}%`, "value"]];
695    if (reset && wide) parts.push([` ↻ ${reset}`, "aside"]);
696    chips.push(chip(Text, STATUS_COLOR[limitStatus(rl)], parts, `rl-${rl.kind}`));
697  }
698
699  if (u?.context?.window) {
700    const pct = ctxPct(u.context);
701    const parts = [["ctx ", "label"], ...chipBar(pct), [` ${pct}%`, "value"], [` ${short(u.context.tokens ?? 0)}/${short(u.context.window)}`, "aside"]];
702    const spark = sparkline(u.history);
703    if (spark && (columns == null || columns >= 110)) parts.push([` ${spark}`, "accent"]);
704    if (u.delta) parts.push([u.delta > 0 ? ` ▲ +${short(u.delta)}` : ` ▼ ${short(-u.delta)}`, "aside"]);
705    chips.push(chip(Text, CTX_TONE(pct), parts, "ctx"));
706  }
707
708  if (typeof u?.cost?.usd === "number") {
709    const use = budgetUse(budget, u, ledger);
710    const parts = [[`$${u.cost.usd.toFixed(2)}`, "value"]];
711    if (use?.scope === "session") parts.push([` / $${use.limit.toFixed(0)}`, "aside"]);
712    const burn = burnRate(u);
713    if (burn && wide) parts.push([` $${burn.toFixed(2)}/h`, "aside"]);
714    if (ledger?.today > 0 && wide) parts.push([` today $${ledger.today.toFixed(2)}${budget?.day ? ` / $${budget.day.toFixed(0)}` : ""}`, "aside"]);
715    if (ledger?.month > ledger?.today && wide) parts.push([` mtd $${ledger.month.toFixed(2)}`, "aside"]);
716    chips.push(chip(Text, budgetTone(use) ?? "yellow", parts, "cost"));
717  }
718
719  if (working != null) chips.push(chip(Text, "purple", [["● ", "accent"], [mmss(working), "value"]], "turn"));
720
721  if (git?.branch && wide) {
722    const parts = [["git ", "label"], [git.branch.length > 24 ? `${git.branch.slice(0, 23)}…` : git.branch, "value"]];
723    if (git.added || git.removed) parts.push([` +${git.added ?? 0}`, "add"], [` −${git.removed ?? 0}`, "del"]);
724    else if (git.dirty) parts.push([` ±${git.dirty}`, "accent"]);
725    if (git.untracked) parts.push([` ?${git.untracked}`, "aside"]);
726    const sync = [git.ahead && `↑${git.ahead}`, git.behind && `↓${git.behind}`].filter(Boolean).join(" ");
727    if (sync) parts.push([` ${sync}`, "aside"]);
728    chips.push(chip(Text, "cyan", parts, "git"));
729  }
730
731  if (git?.pr && wide) {
732    const pr = git.pr;
733    const parts = [["PR ", "label"], [`#${pr.number}`, "value"], [` ${pr.state}`, "aside"]];
734    if (pr.review) parts.push([pr.review === "approved" ? " ✓ approved" : " ✗ changes", pr.review === "approved" ? "add" : "del"]);
735    if (pr.checks) parts.push([{ pass: " ✓ ci", fail: " ✗ ci", pending: " ● ci" }[pr.checks], { pass: "add", fail: "del", pending: "accent" }[pr.checks]]);
736    chips.push(chip(Text, prTone(pr), parts, "pr"));
737  }
738
739  if (a?.calls && wide) {
740    const parts = [[`${a.calls} calls`, "value"]];
741    if (a.files.length) parts.push([` ✎ ${a.files.length}`, "accent"]);
742    chips.push(chip(Text, "purple", parts, "tools"));
743  }
744
745  const dur = duration(u?.startedAt);
746  if (dur && wide) chips.push(chip(Text, "slate", [[dur, "value"]], "time"));
747  if (u?.model) chips.push(chip(Text, "slate", [[shortModel(u.model), "aside"]], "model"));
748
749  return chips.map((c) => Box({ key: c.key, flexDirection: "row", flexShrink: 0, children: c.children }));
750}
751
752// ---- terminal: detail panel ------------------------------------------------
753// Aligned rows under a rule: a colored label column, then figures and charts.
754const CAT_COLORS = ["blue", "magenta", "cyan", "green", "yellow", "red", "white"];
755
756function terminalDetails({ Box, Text }, d, git, u, columns = 100) {
757  const T = (children, o = {}) => Text({ children, ...o });
758  const rows = [];
759  const row = (label, color, kids) => rows.push(Box({ key: `d-${label}`, flexDirection: "row", children: [T(label.padEnd(9), { color, bold: true }), ...kids] }));
760  const barW = Math.max(12, Math.min(30, columns - 60));
761
762  rows.push(T("─".repeat(Math.max(10, Math.min(columns - 4, 96))), { dimColor: true }));
763
764  if (d.ctx) {
765    const kids = [];
766    if (d.used.length) {
767      // stacked: one colored run per category, then the free part dim
768      let drawn = 0;
769      d.used.forEach((c, i) => {
770        const n = Math.round((c.tokens / d.ctx.window) * barW);
771        if (n > 0) kids.push(T("━".repeat(n), { color: CAT_COLORS[i % CAT_COLORS.length] }));
772        drawn += n;
773      });
774      kids.push(T("━".repeat(Math.max(0, barW - drawn)), { dimColor: true }));
775    } else {
776      const n = Math.round((d.ctx.pct / 100) * barW);
777      kids.push(T("━".repeat(n), { color: STATUS_TERM[CTX_TONE(d.ctx.pct)] }), T("━".repeat(barW - n), { dimColor: true }));
778    }
779    kids.push(T(` ${d.ctx.pct}%`, { bold: true }), T(`  ${short(d.ctx.tokens)} / ${short(d.ctx.window)}`, { dimColor: true }));
780    if (d.free != null) kids.push(T(`  compacts in ${short(d.free)}${d.turnsLeft != null ? ` · ≈${d.turnsLeft} turns` : ""}`, { color: d.turnsLeft != null && d.turnsLeft < 5 ? "red" : undefined, dimColor: !(d.turnsLeft != null && d.turnsLeft < 5) }));
781    row("Context", "blue", kids);
782    if (d.used.length) {
783      const legend = [];
784      d.used.slice(0, 6).forEach((c, i) => legend.push(T("● ", { color: CAT_COLORS[i % CAT_COLORS.length] }), T(`${c.name} ${short(c.tokens)}   `, { dimColor: true })));
785      rows.push(Box({ key: "d-legend", flexDirection: "row", flexWrap: "wrap", paddingLeft: 9, children: legend }));
786    }
787  }
788
789  if (d.cost != null) {
790    const kids = [T(`$${d.cost.toFixed(2)}`, { bold: true })];
791    if (d.burn) kids.push(T(`  $${d.burn.toFixed(2)}/h`, { dimColor: true }));
792    if (d.lastCost) kids.push(T(`  last +$${d.lastCost.toFixed(2)}`, { dimColor: true }));
793    if (d.avgCost != null) kids.push(T(`  avg $${d.avgCost.toFixed(2)}/turn`, { dimColor: true }));
794    if (d.ledger) {
795      const daily = sparkline(d.ledger.days);
796      kids.push(T(`  today $${d.ledger.today.toFixed(2)}  7d `, { dimColor: true }));
797      if (daily) kids.push(T(`${daily} `, { color: "green" }));
798      kids.push(T(`$${d.ledger.week.toFixed(2)}${d.ledger.month != null ? `  mtd $${d.ledger.month.toFixed(2)}` : ""}`, { dimColor: true }));
799    }
800    const use = budgetUse(d.budget, u, d.ledger);
801    if (use) kids.push(T(`  ${Math.round(use.frac * 100)}% of $${use.limit.toFixed(0)} ${use.scope} budget`, { color: { green: "green", yellow: "yellow", red: "red" }[budgetTone(use)] }));
802    const spark = sparkline(d.turnCosts);
803    if (spark) kids.push(T(`  ${spark}`, { color: "yellow" }));
804    row("Spend", "yellow", kids);
805  }
806
807  if (d.turns) {
808    const kids = [T(`${d.turns}`, { bold: true }), T(`  avg ${secs(d.avgMs)}  longest ${secs(d.maxMs)}`, { dimColor: true })];
809    if (d.cacheHit != null) kids.push(T("  cache ", { dimColor: true }), T(`${d.cacheHit}%`, { color: d.cacheHit >= 70 ? "green" : d.cacheHit >= 40 ? "yellow" : "red" }));
810    if (d.out) kids.push(T(`  out ${short(d.out)}`, { dimColor: true }));
811    const spark = sparkline(d.turnMs);
812    if (spark) kids.push(T(`  ${spark}`, { color: "magenta" }));
813    row("Turns", "magenta", kids);
814  }
815
816  if (d.tools.length) {
817    const top = d.tools[0][1];
818    const kids = [];
819    d.tools.forEach(([n, c], i) => {
820      kids.push(T(`${i ? "   " : ""}${n} `, { dimColor: true }), T("━".repeat(Math.max(1, Math.round((c / top) * 8))), { color: "cyan" }), T(` ${c}`, { bold: true }));
821    });
822    row("Tools", "cyan", kids);
823  }
824
825  if (d.files.length) row("Edited", "green", [T(d.files.join(", "), { dimColor: true })]);
826  const meta = [git?.branch && gitText(git), u?.model && shortModel(u.model), d.session && `session ${d.session}`].filter(Boolean);
827  if (meta.length) row("Session", "white", [T(meta.join("  ·  "), { dimColor: true })]);
828
829  return Box({ key: "details", flexDirection: "column", paddingX: 1, children: rows });
830}
831const STATUS_TERM = { blue: "blue", yellow: "yellow", red: "red" };
832
833function bar(p, elapsed) {
834  const filled = Math.round((p / 100) * BAR_WIDTH);
835  const cells = [...(BAR_FILLED.repeat(filled) + BAR_EMPTY.repeat(BAR_WIDTH - filled))];
836  if (elapsed != null) cells[Math.min(BAR_WIDTH - 1, Math.floor(elapsed * BAR_WIDTH))] = "┃"; // pace marker
837  return cells.join("");
838}
839
840function sparkline(history) {
841  if (!history || history.length < 2) return null;
842  const top = Math.max(...history, 1);
843  return history.map((v) => BARS[Math.min(BARS.length - 1, Math.floor((v / top) * (BARS.length - 1)))]).join("");
844}
845
846function clampPct(p) {
847  return Math.max(0, Math.min(100, Math.round(p ?? 0)));
848}
849
850function ctxPct(ctx) {
851  return ctx.percent ?? Math.round(((ctx.tokens ?? 0) / ctx.window) * 100);
852}
853
854function resetsIn(resetsAt) {
855  if (typeof resetsAt !== "string") return null;
856  const t = Date.parse(resetsAt);
857  if (Number.isNaN(t)) return null;
858  const m = Math.round((t - Date.now()) / 60_000);
859  if (m <= 0) return null;
860  if (m < 60) return `${m}m`;
861  const h = Math.floor(m / 60);
862  if (h < 24) return `${h}h ${m % 60}m`;
863  return `${Math.floor(h / 24)}d ${h % 24}h`;
864}
865
866function duration(startedAt) {
867  if (typeof startedAt !== "number") return null;
868  const m = Math.floor((Date.now() - startedAt) / 60_000);
869  if (m < 1) return null;
870  if (m < 60) return `${m}m`;
871  const h = Math.floor(m / 60);
872  if (h < 24) return `${h}h ${m % 60}m`;
873  return `${Math.floor(h / 24)}d ${h % 24}h`;
874}
875
876function shortModel(id) {
877  return String(id)
878    .replace(/^claude-/, "")
879    .replace(/-\d{8}$/, "")
880    .replace(/-(\d+)-(\d+)$/, "-$1.$2");
881}
882
883function short(n) {
884  if (n >= 1_000_000) return `${+(n / 1_000_000).toFixed(1)}M`;
885  if (n >= 1_000) return `${+(n / 1_000).toFixed(1)}k`;
886  return String(n);
887}
888
889// ---- pace logic -----------------------------------------------------------
890const WINDOW_MS = { five_hour: 5 * 3_600_000, seven_day: 7 * 24 * 3_600_000 };
891
892function limitLabel(rl) {
893  return rl.kind === "five_hour" ? "5h" : rl.kind === "seven_day" ? "7d" : rl.kind;
894}
895
896// How far into the window we are, and where the current burn rate lands at reset.
897function paceOf(rl) {
898  const win = WINDOW_MS[rl.kind];
899  const t = Date.parse(rl.resetsAt ?? "");
900  if (!win || Number.isNaN(t)) return null;
901  const left = Math.max(0, t - Date.now());
902  const elapsed = Math.min(1, Math.max(0, 1 - left / win));
903  if (elapsed < 0.1) return { elapsed };
904  const p = clampPct(rl.percentUsed);
905  const projected = p / elapsed;
906  const minutesToLimit = p > 0 && projected > 100 ? ((100 - p) / p) * elapsed * (win / 60_000) : null;
907  return { elapsed, projected, minutesToLimit };
908}
909
910// ok / warn / crit: absolute level, or burning faster than the window allows.
911function limitStatus(rl) {
912  const p = clampPct(rl.percentUsed);
913  if (p >= 90) return "crit";
914  const pace = paceOf(rl);
915  if (pace?.projected != null && pace.projected >= 150 && p >= 30) return "crit";
916  if (p >= 70 || (pace?.projected != null && pace.projected >= 100 && p >= 20)) return "warn";
917  return "ok";
918}
919
920function fmtMinutes(m) {
921  m = Math.max(1, Math.round(m));
922  if (m < 60) return `${m}m`;
923  const h = Math.floor(m / 60);
924  return h < 24 ? `${h}h ${m % 60}m` : `${Math.floor(h / 24)}d ${h % 24}h`;
925}
926
927// ---- desktop: one SVG strip ------------------------------------------------
928// The whole band is a single drawing, so it never wraps into ragged rows. It
929// sits on the host's own band background: no tile fills, color only on the
930// figures that carry status. Monospace, so widths are exact without stretching.
931const H = 30;
932const MID = H / 2;
933const FONT = "ui-monospace,SFMono-Regular,Menlo,Consolas,monospace";
934const CW = 0.6; // monospace advance, em
935const SIZE = { label: 9, value: 12, aside: 10.5 };
936const TRACK = { label: 0.8, value: 0, aside: 0 };
937const BAR_W = 34;
938const PAL = {
939  card: ["#0000000a", "#ffffff0a"],
940  // [light, dark]
941  fg: ["#1f1f24", "#ececf1"],
942  mu: ["#74747f", "#9b9ba8"],
943  lb: ["#8b8b96", "#7d7d8a"],
944  rule: ["#00000018", "#ffffff1c"],
945  track: ["#0000001a", "#ffffff1f"],
946  green: ["#23875a", "#5fd19c"],
947  yellow: ["#a87708", "#e8bd3f"],
948  red: ["#c4402b", "#ff7b67"],
949  blue: ["#3563d1", "#86a6ff"],
950  purple: ["#6a52cc", "#a996ff"],
951  cyan: ["#167f8c", "#5cc9d6"],
952  slate: ["#6b6b78", "#a3a3b0"],
953};
954const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
955const textW = (kind, s) => [...s].length * (SIZE[kind] * CW + TRACK[kind]);
956
957// item: {label} | {value, tone} | {aside, tone?} | {bar:{pct,pace,tone}} | {spark, tone} | {dot, tone}
958function itemWidth(it) {
959  if (it.label != null) return textW("label", it.label);
960  if (it.value != null) return textW("value", it.value);
961  if (it.aside != null) return textW("aside", it.aside);
962  if (it.bar) return BAR_W;
963  if (it.spark) return it.spark.length * 3.5 - 1.5;
964  if (it.dot) return 7;
965  if (it.icon) return 10;
966  return 0;
967}
968
969function drawItem(it, x) {
970  const text = (kind, s, cls) => {
971    const fs = SIZE[kind];
972    const weight = kind === "value" ? 650 : kind === "label" ? 700 : 500;
973    const ls = TRACK[kind] ? ` letter-spacing="${TRACK[kind]}"` : "";
974    return `<text class="${cls}" x="${x.toFixed(1)}" y="${(MID + fs * 0.36).toFixed(1)}" font-size="${fs}" font-weight="${weight}"${ls}>${esc(s)}</text>`;
975  };
976  if (it.label != null) return text("label", it.label, it.cls ?? "lb");
977  if (it.value != null) return text("value", it.value, it.tone ?? "fg");
978  if (it.aside != null) return text("aside", it.aside, it.tone ?? "mu");
979  if (it.icon) {
980    const t = MID - 5.5, b = MID + 5.5;
981    return `<g class="mu-s" fill="none" stroke-width="1.4" stroke-linecap="round"><circle cx="${x + 2.5}" cy="${b - 1.5}" r="1.5"/><circle cx="${x + 2.5}" cy="${t + 1.5}" r="1.5"/><circle cx="${x + 8}" cy="${t + 3}" r="1.5"/><path d="M${x + 2.5} ${t + 3}V${b - 3}M${x + 8} ${t + 4.5}c0 3-5.5 2.5-5.5 5"/></g>`;
982  }
983  if (it.dot) return `<circle class="${it.tone}" cx="${x + 3.5}" cy="${MID}" r="3.5"/>`;
984  if (it.bar) {
985    const w = BAR_W, y = MID - 2;
986    const fill = it.bar.pct > 0 ? Math.max(4, (it.bar.pct / 100) * w) : 0;
987    let s = `<rect class="track" x="${x}" y="${y}" width="${w}" height="4" rx="2"/>`;
988    if (fill) s += `<rect class="${it.bar.tone}" x="${x}" y="${y}" width="${fill.toFixed(1)}" height="4" rx="2"/>`;
989    if (it.bar.pace != null) {
990      const px = x + Math.min(w - 1, Math.max(1, it.bar.pace * w));
991      s += `<rect class="fg" x="${(px - 0.75).toFixed(1)}" y="${y - 3}" width="1.5" height="10" rx=".75"/>`;
992    }
993    return s;
994  }
995  if (it.spark) {
996    const lo = Math.min(...it.spark), hi = Math.max(...it.spark);
997    return it.spark.map((v, j) => {
998      const h = 3 + (hi === lo ? 0.5 : (v - lo) / (hi - lo)) * 9;
999      const op = j === it.spark.length - 1 ? 1 : 0.45;
1000      return `<rect class="${it.tone}" x="${x + j * 3.5}" y="${(MID + 6 - h).toFixed(1)}" width="2" height="${h.toFixed(1)}" rx="1" opacity="${op}"/>`;
1001    }).join("");
1002  }
1003  return "";
1004}
1005
1006// "1h 40m" -> "1h40m", "3d 0h" -> "3d"
1007function compactSpan(s) {
1008  return s.replace(/ 0[hm]$/, "").replace(" ", "");
1009}
1010
1011// A pill: one figure on a soft tint of its tone with a hairline edge. Each pill
1012// is its own drawing, so the band's flex layout wraps them as units.
1013const PILL_TONES = ["green", "yellow", "red", "blue", "purple", "cyan", "slate"];
1014function pillCss(i) {
1015  const fg = PAL.fg[i];
1016  return PILL_TONES.map((k) => `.pb-${k}{fill:${PAL[k][i]};fill-opacity:${i ? 0.17 : 0.12};stroke:${PAL[k][i]};stroke-opacity:${i ? 0.42 : 0.35}}`).join("") +
1017    `.pb-n{fill:${fg};fill-opacity:${i ? 0.06 : 0.045};stroke:${fg};stroke-opacity:${i ? 0.14 : 0.12}}`;
1018}
1019
1020// Card tints: fainter than a pill, so four of them side by side stay calm.
1021function cardCss(i) {
1022  return PILL_TONES.map((k) => `.cb-${k}{fill:${PAL[k][i]};fill-opacity:${i ? 0.07 : 0.05};stroke:${PAL[k][i]};stroke-opacity:${i ? 0.2 : 0.18}}`).join("");
1023}
1024
1025function svgPill(tone, items, title) {
1026  const GAP = 5, PADX = 10;
1027  let x = PADX, body = "";
1028  items = items.map((it) => (it.label != null && tone && !it.cls ? { ...it, cls: tone } : it));
1029  items.forEach((it, j) => {
1030    if (j) x += it.tight ? 3 : GAP;
1031    body += drawItem(it, x);
1032    x += itemWidth(it);
1033  });
1034  const width = Math.ceil(x + PADX);
1035  const cls = (i) => Object.entries(PAL).map(([k, v]) => `.${k}{fill:${v[i]}}.${k}-s{stroke:${v[i]}}`).join("") + pillCss(i);
1036  // a titled pill greys its tint on hover, hinting the tooltip that the host
1037  // shows for <title>; only such pills are interactive
1038  const hover = title ? ".pill{transition:fill-opacity .15s,stroke-opacity .15s}svg:hover .pill{fill-opacity:.3;stroke-opacity:.65}" : "";
1039  const source = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${H}" viewBox="0 0 ${width} ${H}" font-family="${FONT}">` +
1040    (title ? `<title>${esc(title)}</title>` : "") +
1041    `<style>${cls(0)}@media (prefers-color-scheme:dark){${cls(1)}}${hover}</style>` +
1042    `<rect class="${title ? "pill " : ""}pb-${tone ?? "n"}" x=".5" y="3.5" width="${width - 1}" height="${H - 7}" rx="${(H - 7) / 2}" stroke-width="1"/>${body}</svg>`;
1043  return { source, width };
1044}
1045
1046// Session figures on the left (limits, context, live turn); work and money on
1047// the right (git, PR, cost, today). Each side wraps on its own.
1048function desktopRow({ Svg }, { u, git, working, budget, ledger }) {
1049  const left = [];
1050  const right = [];
1051  const add = (side, key, tone, items, alt, title) => {
1052    const { source, width } = svgPill(tone, items, title);
1053    side.push(Svg({ key, source, alt, width, height: H, ...(title ? { isInteractive: true } : {}) }));
1054  };
1055
1056  for (const rl of u?.rateLimits ?? []) {
1057    const p = clampPct(rl.percentUsed);
1058    const pace = paceOf(rl);
1059    const reset = resetsIn(rl.resetsAt);
1060    const tone = STATUS_COLOR[limitStatus(rl)];
1061    const items = [{ label: limitLabel(rl).toUpperCase() }, { bar: { pct: p, pace: pace?.elapsed, tone } }, { value: `${p}%`, tone }];
1062    if (pace?.projected != null && pace.projected >= 100) items.push({ aside: `→${Math.min(999, Math.round(pace.projected))}%`, tone, tight: true });
1063    if (reset) items.push({ aside: `↻${compactSpan(reset)}` });
1064    add(left, `rl-${rl.kind}`, tone, items, `${limitLabel(rl)} ${p}%${reset ? ` resets in ${reset}` : ""}`);
1065  }
1066
1067  if (u?.context?.window) {
1068    const pct = ctxPct(u.context);
1069    const tone = CTX_TONE(pct);
1070    const items = [{ label: "CTX" }, { bar: { pct, tone } }, { value: `${pct}%`, tone }, { aside: `${short(u.context.tokens ?? 0)}/${short(u.context.window)}` }];
1071    if (u.delta) items.push({ aside: u.delta > 0 ? `+${short(u.delta)}` : `−${short(-u.delta)}`, tone });
1072    add(left, "ctx", tone, items, `context ${pct}%`);
1073  }
1074
1075  if (working != null) add(left, "turn", "purple", [{ dot: true, tone: "purple" }, { value: mmss(working), tone: "purple", tight: true }], `turn ${mmss(working)}`);
1076
1077  if (git?.branch) {
1078    const items = [{ icon: "branch" }, { value: git.branch.length > 22 ? `${git.branch.slice(0, 21)}…` : git.branch, tight: true }];
1079    if (git.added || git.removed) items.push({ aside: `+${git.added ?? 0}`, tone: "green" }, { aside: `−${git.removed ?? 0}`, tone: "red", tight: true });
1080    else if (git.dirty) items.push({ aside: `±${git.dirty}`, tone: "yellow" });
1081    if (git.untracked) items.push({ aside: `?${git.untracked}` });
1082    const sync = [git.ahead && `↑${git.ahead}`, git.behind && `↓${git.behind}`].filter(Boolean).join(" ");
1083    if (sync) items.push({ aside: sync });
1084    add(right, "git", "cyan", items, `git ${gitText(git)}`);
1085  }
1086
1087  if (git?.pr) {
1088    const pr = git.pr, tone = prTone(pr);
1089    const items = [{ dot: true, tone }, { value: `#${pr.number}`, tone, tight: true }, { aside: pr.state }];
1090    if (pr.review) items.push({ aside: pr.review === "approved" ? "✓ approved" : "✗ changes", tone: pr.review === "approved" ? "green" : "red" });
1091    if (pr.checks) items.push({ aside: { pass: "✓ ci", fail: `✗ ${pr.failing?.length || ""} ci`.replace("  ", " "), pending: "● ci" }[pr.checks], tone: { pass: "green", fail: "red", pending: "yellow" }[pr.checks] });
1092    // no link here: the desktop app draws its own clickable PR bar above the band
1093    add(right, "pr", tone, items, prText(pr));
1094  }
1095
1096  if (typeof u?.cost?.usd === "number") {
1097    const use = budgetUse(budget, u, ledger);
1098    const tone = budgetTone(use);
1099    const items = [{ label: "COST" }, { value: `$${u.cost.usd.toFixed(2)}`, tone: tone && tone !== "green" ? tone : undefined }];
1100    if (use?.scope === "session") items.push({ aside: `/ $${use.limit.toFixed(0)}`, tight: true });
1101    const burn = burnRate(u);
1102    if (burn) items.push({ aside: `$${burn.toFixed(2)}/h` });
1103    add(right, "cost", tone && tone !== "green" ? tone : "yellow", items, `cost $${u.cost.usd.toFixed(2)}`);
1104  }
1105
1106  if (ledger && (ledger.today > 0 || ledger.month > 0)) {
1107    const use = budget?.day ? ledger.today / budget.day : null;
1108    const tone = use == null ? null : use >= 1 ? "red" : use >= 0.8 ? "yellow" : null;
1109    const items = [{ label: "TODAY" }, { value: `$${ledger.today.toFixed(2)}`, tone: tone ?? undefined }];
1110    if (budget?.day) items.push({ aside: `/ $${budget.day.toFixed(0)}`, tight: true });
1111    if (ledger.days?.slice(0, -1).some((v) => v > 0)) items.push({ spark: ledger.days, tone: tone ?? "green" });
1112    if (ledger.week > ledger.today) items.push({ aside: `7d $${ledger.week.toFixed(0)}` });
1113    if (ledger.month > ledger.today) items.push({ aside: `mtd $${ledger.month.toFixed(0)}` });
1114    const tip = [
1115      ...(ledger.days ?? []).map((v, i) => `${dayKey(Date.now() - (6 - i) * 86_400_000).slice(5)}  $${v.toFixed(2)}`),
1116      `last 7 days  $${ledger.week.toFixed(2)}`,
1117      ledger.month != null && `month to date  $${ledger.month.toFixed(2)}`,
1118    ].filter(Boolean).join("\n");
1119    add(right, "today", tone ?? "green", items, `today $${ledger.today.toFixed(2)}${ledger.month != null ? `, month to date $${ledger.month.toFixed(2)}` : ""}`, tip);
1120  }
1121
1122  return { left, right };
1123}
1124
1125// ---- desktop: detail cards ---------------------------------------------------
1126// Four compact cards in one row (context, spend, turns, tools) over a footer
1127// line, as one SVG about 130px tall so the band shows it whole.
1128const CARD_W = 184;
1129const CARD_H = 108;
1130const GRID_GAP = 8;
1131const CAT_TONES = ["blue", "purple", "cyan", "green", "yellow", "red", "mu"];
1132
1133function desktopDetails({ Svg }, d, git, u) {
1134  const cardsShown = [d.ctx, d.cost != null, d.turns > 0, d.tools.length > 0].filter(Boolean).length || 1;
1135  const W = Math.max(CARD_W * 2 + GRID_GAP, CARD_W * cardsShown + GRID_GAP * (cardsShown - 1));
1136  const t = (x, y, s, { size = 10, weight = 500, cls = "fg", anchor, ls } = {}) =>
1137    `<text class="${cls}" x="${x.toFixed(1)}" y="${y.toFixed(1)}" font-size="${size}" font-weight="${weight}"${anchor ? ` text-anchor="${anchor}"` : ""}${ls ? ` letter-spacing="${ls}"` : ""}>${esc(s)}</text>`;
1138  const w = (s, size) => [...s].length * size * CW;
1139  const fit = (s, size, room) => {
1140    const max = Math.floor(room / (size * CW));
1141    return s.length > max ? `${s.slice(0, Math.max(1, max - 1))}…` : s;
1142  };
1143  const P = 12; // card padding
1144  const title = (x, s, right, tone = "lb") => t(x + P, 19, s, { size: 8.5, weight: 700, cls: tone, ls: 0.8 }) +
1145    (right ? t(x + CARD_W - P, 19, fit(right.s, 9.5, CARD_W - 2 * P - w(s, 8.5) - 10), { size: 9.5, cls: right.cls ?? "mu", anchor: "end" }) : "");
1146  const big = (x, s, cls = "fg", side) => t(x + P, 45, s, { size: 19, weight: 700, cls }) +
1147    (side ? t(x + P + w(s, 19) + 6, 45, fit(side, 9.5, CARD_W - 2 * P - w(s, 19) - 6), { size: 9.5, cls: "mu" }) : "");
1148  const line = (x, s, cls = "mu") => t(x + P, 62, fit(s, 9.5, CARD_W - 2 * P), { size: 9.5, cls });
1149  const cols = (x, values, cls, maxH = 26) => {
1150    if (values.length < 2) return "";
1151    const top = Math.max(...values, 1e-9), n = values.length, gw = CARD_W - 2 * P, bw = Math.min(8, (gw - (n - 1) * 2.5) / n);
1152    return values.map((v, i) => {
1153      const h = Math.max(2, (v / top) * maxH);
1154      return `<rect class="${cls}" x="${(x + P + i * (bw + 2.5)).toFixed(1)}" y="${(CARD_H - 10 - h).toFixed(1)}" width="${bw.toFixed(1)}" height="${h.toFixed(1)}" rx="1.5" opacity="${i === n - 1 ? 1 : 0.55}"/>`;
1155    }).join("");
1156  };
1157  const card = (x, tone) => `<rect class="cb-${tone}" x="${x + 0.5}" y=".5" width="${CARD_W - 1}" height="${CARD_H - 1}" rx="11"/>`;
1158  const at = (i) => i * (CARD_W + GRID_GAP);
1159  let body = "";
1160  // only the cards with something to say, packed left
1161  const show = [d.ctx && "context", d.cost != null && "spend", d.turns > 0 && "turns", d.tools.length > 0 && "tools"].filter(Boolean);
1162  const slot = (name) => show.indexOf(name);
1163
1164  // context
1165  if (slot("context") >= 0) {
1166    const x = at(slot("context"));
1167    body += card(x, "blue") + title(x, "CONTEXT", d.ctx ? { s: `${short(d.ctx.tokens)}/${short(d.ctx.window)}` } : null, "blue");
1168    if (d.ctx) {
1169      const warn = d.turnsLeft != null && d.turnsLeft < 5;
1170      body += big(x, `${d.ctx.pct}%`, CTX_TONE(d.ctx.pct), d.turnsLeft != null ? `≈${d.turnsLeft} turns left` : d.free != null ? `${short(d.free)} free` : null);
1171      if (warn) body += t(x + CARD_W - P, 45, "compact soon", { size: 9, cls: "red", anchor: "end" });
1172      const bx = x + P, by = 54, bw = CARD_W - 2 * P;
1173      body += `<rect class="track" x="${bx}" y="${by}" width="${bw}" height="6" rx="3"/>`;
1174      if (d.used.length) {
1175        let cx = bx;
1176        body += `<clipPath id="cb"><rect x="${bx}" y="${by}" width="${bw}" height="6" rx="3"/></clipPath><g clip-path="url(#cb)">`;
1177        d.used.forEach((c, i) => {
1178          const cw = (c.tokens / d.ctx.window) * bw;
1179          if (cw > 0.5) body += `<rect class="${CAT_TONES[i % CAT_TONES.length]}" x="${cx.toFixed(1)}" y="${by}" width="${Math.max(1, cw - 1).toFixed(1)}" height="6"/>`;
1180          cx += cw;
1181        });
1182        body += "</g>";
1183        d.used.slice(0, 3).forEach((c, i) => {
1184          const ly = 76 + i * 12.5;
1185          body += `<circle class="${CAT_TONES[i % CAT_TONES.length]}" cx="${bx + 3}" cy="${ly - 3.2}" r="2.6"/>`;
1186          body += t(bx + 10, ly, fit(c.name, 9, bw - 50), { size: 9, cls: "mu" }) + t(bx + bw, ly, short(c.tokens), { size: 9, weight: 650, anchor: "end" });
1187        });
1188      } else {
1189        body += `<rect class="${CTX_TONE(d.ctx.pct)}" x="${bx}" y="${by}" width="${Math.max(d.ctx.pct > 0 ? 3 : 0, (d.ctx.pct / 100) * bw).toFixed(1)}" height="6" rx="3"/>`;
1190        body += t(bx, 80, "breakdown after next turn", { size: 9, cls: "lb" });
1191      }
1192    }
1193  }
1194
1195  // spend
1196  if (slot("spend") >= 0) {
1197    const x = at(slot("spend"));
1198    const use = budgetUse(d.budget, u, d.ledger);
1199    body += card(x, "yellow") + title(x, "SPEND", use ? { s: `${Math.round(use.frac * 100)}% of $${use.limit.toFixed(0)}`, cls: budgetTone(use) } : d.burn ? { s: `$${d.burn.toFixed(2)}/h` } : null, "yellow");
1200    if (d.cost != null) {
types/index.d.ts 49 lines
1export type UsageRateLimit = { kind: string; percentUsed: number; resetsAt?: string };
2export type UsageReading = {
3  startedAt?: number;
4  context?: { tokens?: number; window: number; percent?: number };
5  rateLimits?: UsageRateLimit[];
6  cost?: { usd?: number };
7  model?: string;
8  prevTokens?: number;
9  costDelta?: number;
10  delta?: number;
11  history?: number[];
12};
13export type UsageActivity = { calls: number; files: string[]; tools?: Record<string, number> };
14export type UsageTurn = { ms: number; usd: number | null; in: number; out: number; cr: number; cw: number };
15export type UsageContextMap = { at: number; cats: { name: string; tokens: number; kind: string }[] };
16export type UsagePr = {
17  number: number;
18  url?: string;
19  failing?: { name: string; url: string }[];
20  pending?: number;
21  state: string; review: "approved" | "changes" | null; checks: "pass" | "fail" | "pending" | null };
22export type UsageGit = {
23  branch?: string;
24  dirty?: number;
25  untracked?: number;
26  added?: number;
27  removed?: number;
28  ahead?: number;
29  behind?: number;
30  pr?: UsagePr | null;
31  prCheckedAt?: number;
32};
33
34declare module "claude-code" {
35  interface PluginState {
36    "usage-bar": {
37      last?: UsageReading;
38      activity?: UsageActivity;
39      git?: UsageGit;
40      turn?: { startedAt: number; tick: number; costAt?: number };
41      ui?: { expanded: boolean };
42      turns?: UsageTurn[];
43      ctxmap?: UsageContextMap;
44      budget?: { session?: number; day?: number };
45      ledger?: { date: string; today: number; todayTurns: number; week: number; month?: number; days: number[] };
46      alerts?: { session?: number; day?: number; pace?: boolean };
47    };
48  }
49}