SLOPSHOPPER

status-panel

A framed panel above the prompt showing context, rate limits, session cost against a monthly budget, prompt-cache state with a live TTL countdown, git branch…

panebandguardtoastmodelprocess
v1.3.0MITupdated 2026-10-16tichara1/ai.claude-status-panel
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · status-panel
│ ┃ session ✕ › fix the failing auth test and add an audit log call │ ┃ 🔥 0 tokens · ≈0.00$ by price list · │ ┃ engine 0.42$ ⏺ Read(src/auth.ts) │ ┃ ────────────────────────────────────────── ⎿ Read 6 lines │ ┃ ──────────── ⏺ Update(src/auth.ts) │ ┃ Subagents ⎿ Added 2 lines, removed 1 line │ ┃ No subagents in this session yet. ⏺ 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 │ │ │ │ ╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ k-folder feat/auth-refresh – · – │ │ │ │ context ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 49% 97k [200k] k-5h ▐▛█▜▌ │ │ k-keep– Σ –% – k-claude k-mcp ▝▜█▛▘ │ │ k-session │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
╭──────────────────────────────────────────────────────────────────────────────────────────────────╮ │ k-folder feat/auth-refresh – · – │ │ │ │ context ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 49% 97k [200k] k-5h ▐▛█▜▌ │ │ k-keep– Σ –% – k-claude k-mcp ▝▜█▛▘ │ │ k-session │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
Pane · session
🔥 0 tokens · ≈0.00$ by price list · engine 0.42$ ────────────────────────────────────────────────────── Subagents No subagents in this session yet.
Pane · memory
In load order: a later row overrides an earlier one. CLAUDE․md 0 No CLAUDE․md or AGENTS․md in context. ────────────────────────────────────────────────────── RULES 0 No rules file in context. ────────────────────────────────────────────────────── MEMORY 0 No auto memory in context. ────────────────────────────────────────────────────── HOOKS 0 No hook in the settings. ────────────────────────────────────────────────────── MODS 0 No mod installed.
Pane · tools
⚠ Any switch changes the tools and skills listed to the model: the next request writes the prompt cache again. MCP servers 0 No MCP server. ────────────────────────────────────────────────────── Skills 0 No skill.
README

status-panel

A Claude Code mod that draws a quiet, framed panel above the prompt with everything you want to keep an eye on during a session. Labels are dim; colour appears only where it tells you something.

Preview

Personal plan (Max 20x) with extra usage switched on:

╭──────────────────────────────────────────────────────────────────────────────────────────╮
│ www-trainers  main ↓5  PR#1067                                 opus-5-5 · high · Max 20x │
│                                                                                          │
│ context  ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬  33%  638k [1M]             5h     13%  38m                     │
│ cache ●  100%  Σ 98%  56:32    CLAUDE.md 3   MCP 10  7d     16%  5d4h                    │
│                                                    extra  ━━━━━━━── 84%  42.00$ / 50.00$ │
│ session  11.02$                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────╯

Enterprise with a 250$ monthly budget: the 5-hour and weekly limits are hidden (Enterprise pays per token); in their place the month's spend: the bar with its percentage, and the amount against the budget on the row below.

╭──────────────────────────────────────────────────────────────────────────────────────────╮
│ repo-x  feature/abc ✓  PR#5541                              opus-5-5 · high · Enterprise │
│                                                                                          │
│ context  ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬  18%  185k [1M]                             month  ━━━━━━── 76% │
│ cache ●  97%  Σ 96%  42:10     CLAUDE.md 2   MCP 4                   190.40$ / 250.00$   │
│ session  12.40$                                                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────╯

On a personal plan with extra usage switched off (or without a limit) the money row is hidden; the session cost always stays.

What it shows

  • Header: the folder (click to open it), the git branch with ahead/behind against upstream (↑2 ↓1, ✓ in sync), a clickable PR#n link when the branch has an open pull request (GitHub via gh, Azure DevOps via az with the azure-devops extension), model, effort and plan.
  • Click ↓n to fast-forward with git pull --ff-only: it never merges, and a diverged branch or conflicting local changes are left untouched; a toast says what happened.
  • Context: tokens in use against the window (333k [1M]), with a bar and percentage coloured by fill (green → yellow → orange → red).
  • Prompt cache: hit rate of the last request and of the session, and a live countdown until the cache expires. A cache miss line explains the most likely cause and disappears once the cache is warm again.
  • Keep-alive: click the word cache to switch it on; the dot next to it turns green. A minute before the TTL runs out it sends one tiny request over the session's own transcript ($.model.fork), which reads the prefix from the cache and starts the TTL again. It skips a running turn and an expired cache, switches itself off when a request fails, and shows how many requests it sent and what they cost.
  • Rate limits: 5-hour and weekly windows with the time left until reset; click one to show the exact reset times. Hidden on Enterprise.
  • Money, under the limits, with the same colour scale (/login to another account is picked up within 30 s):
  • personal plan: extra usage beyond the subscription against its monthly limit, from your account; hidden while extra usage is off or has no limit,
  • Enterprise: month, all spend this calendar month against the account's limit or budgetUsd, from your account once it reports it, otherwise estimated from the price list.
  • CLAUDE.md and MCP on the cache row, under the token count, each open a side pane.
  • Bottom row: the session cost (always), prepaid credits when the account has any, and what keep-alive has sent and cost.
  • Clawd: a mini Claude Code robot, grey at rest, in colour and animated while a turn is running.
  • Alerts: the frame turns orange when the cache expired with the context above 35 %, and red above 65 %.
  • Currency: amounts carry the sign after the number (3.71$, 3.71€). Account amounts use the currency the account reports; the session cost and price-list estimates are in US dollars, as Claude Code computes them.

Side panes

session, CLAUDE.md and MCP each open a pane docked to the right of the transcript (fullscreen from 110 columns, otherwise above the prompt). Only one is open at a time; click the same button again to close it.

Session pane:

  🔥 47.2M tokens · ≈14.96$ by price list · engine 16.15$
  ────────────────────────────────────────────────────────────────
  Subagents  clear
  ▸ ● Color test: csharp-reviewer (csharp-reviewer)  haiku-5-5 (XH)  🔥 96k  ✅ 13s  ≈0.01$
  ▾   Feedback on error message (Explore)            haiku-5-5 (XH)  🔥 25k  ✅ 12s  ≈0.00$
      ╭────────────────────────────────────────────────────────────╮
      │ ▌ request                                                  │
      │   A client of a personal trainer tries to cancel …         │
      │ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ │
      │ ▌ response                                                 │
      │   - Tone: "Error" and "Operation not permitted" …          │
      ╰────────────────────────────────────────────────────────────╯
  ════════════════════════════════════════════════════════════════
  Σ subagents 12 spawned · 🔥 609k of 47.2M tokens · ≈0.28$ of 16.15$ this session
  • Each subagent with its type, model, effort, tokens, status (✻ running 1m20s or ✅ 8s) and estimated cost, in aligned columns.
  • The coloured dot is the color from the agent's definition (~/.claude/agents, the project's .claude/agents; symbolic links are followed). Built-in types have none.
  • Click a subagent to expand its request and response; clear drops the finished ones (running ones stay); the summary counts every subagent spawned this session.

CLAUDE.md pane: the loaded CLAUDE.md, CLAUDE.local.md and AGENTS.md files with where they come from and their tokens. Click a file to read it in an indented frame right in the pane (the first 60 lines); ↗ open opens it in your editor.

  ▾ CLAUDE.md  Project · 5k tok   ↗ open
      ╭──────────────────────────────────────────────────────────╮
      │ # www-trainers                                           │
      │                                                          │
      │ ## Než začneš                                            │
      │ - Pracuješ na oblasti NNN: přečti spec.md a design.md.   │
      │ … 112 more lines · ↗ open shows the whole file           │
      ╰──────────────────────────────────────────────────────────╯

  ▸ ~/.claude/CLAUDE.md  User · 3k tok   ↗ open

MCP & skills pane: MCP servers, then skills, each list with the active ones first and the most called first. Every row has an ON/OFF switch at the right edge.

  ⚠ Any switch changes the tools and skills listed to the model: the next request
    writes the prompt cache again.

  MCP servers
  claude_ai_Claude_Docs [claude.ai]  12 calls · 3/3 tools · 4k tok          ON
  restapi                            0 calls · 0/2 tools · 1k tok           ON
  ────────────────────────────────────────────────────────────────────────────
  Skills
  plugin-authoring [system]          3 calls · built-in · 2k tok            ON
  superpowers:brainstorming [plugin] 0 calls · plugin · 1k tok              ON
  spec-write                         0 calls · projectSettings · 1k tok    OFF
  • A switch writes to the project's .claude/settings.local.json (personal, not committed), the same file /skills writes:
  • MCP server: deniedMcpServers: [{ "serverName": … }]; it takes effect when the server reconnects (/mcp or a new session),
  • skill: skillOverrides: { "<name>": "off" }.
  • Plugin skills have no switch: skillOverrides does not apply to them.
  • [system] marks Claude Code's own skills, [plugin] and [claude.ai] where a server or skill comes from. Any switch changes what the model is told it has, so the next request writes the prompt cache again.
  • A settings file that is not valid JSON is never overwritten; the toast says so.

Install

In a Claude Code terminal session:

/plugin install status-panel --marketplace tichara1/ai.claude-status-panel

Answer y to add the marketplace and pick the user scope so the panel shows in every project.

Configure

/plugin configure status-panel
OptionDefaultMeaning
ttlMinutes60Prompt-cache TTL your requests use (5 or 60). Drives the countdown, keep-alive and the cache-write price.
budgetUsd250Monthly Enterprise budget in USD that the month bar is measured against when the account reports no limit of its own.

Update and uninstall

claude plugin update status-panel@status-panel
claude plugin uninstall status-panel@status-panel

Run /reload-plugins in sessions that are already open.

Good to know

  • Costs are estimates. The session cost comes from Claude Code itself; per-kind, per-subagent and keep-alive costs are computed from public API prices. On a subscription plan they show the value of what you used, not money you are billed.
  • The monthly total is local on Enterprise without account figures: it sums the sessions this mod has seen on this machine.
  • The plan label is read from oauthAccount.organizationType and organizationRateLimitTier in ~/.claude.json; nothing else from that file is used.
  • Opening files and folders uses start on Windows, open on macOS and xdg-open on Linux.
  • Tested with Claude Code 2.1.301 in the terminal.

Development

claude plugin validate .
claude plugin test .

The band is in hooks/band.tsx, the session pane in hooks/lists.tsx, the CLAUDE.md pane in hooks/memory.tsx, the MCP & skills pane in hooks/tools.tsx, state and hooks in hooks/register.tsx, pure helpers (with tests) in hooks/format.ts.

License

MIT

Source 9 files
hooks/register.tsx 1051 lines
1import { atom, read, update } from "claude-code";
2import type { EngineInterface, Register } from "claude-code";
3
4import type {
5  AccountSpend,
6  Billing,
7  KeepAlive,
8  Kind,
9  McpServer,
10  MemFile,
11  Miss,
12  PullRequest,
13  Repo,
14  SkillInfo,
15  Snap,
16  SubagentInfo,
17  SubagentUsage,
18  Tally,
19} from "../types";
20import { renderBand } from "./band";
21import type { Disabled } from "./format";
22import { renderList } from "./lists";
23import type { HookRow, ModRow, SettingsScope } from "./context";
24import { hookRows, importsOf, pluginRows, SETTINGS_ORDER } from "./context";
25import type { FileDetail } from "./memory";
26import { renderMemory } from "./memory";
27import { renderTools } from "./tools";
28import {
29  addAgentStep,
30  baseName,
31  effortShort,
32  emptyAgent,
33  groupMcp,
34  disabledFromSettings,
35  toggleInSettings,
36  parseAgentDefinition,
37  isKeepAliveDue,
38  missReason,
39  moneyLine,
40  monthKey,
41  isAzureRemote,
42  parseAheadBehind,
43  parseAzurePullRequest,
44  parseAccountSpend,
45  parsePullRequest,
46  percentOf,
47  accountFromClaudeJson,
48  addCostParts,
49  stepCost,
50  stepCostParts,
51} from "./format";
52
53const snapAtom = atom(
54  { plugin: "status-panel", key: "snap" } as const,
55  null as Snap | null,
56);
57const tallyAtom = atom(
58  { plugin: "status-panel", key: "tally" } as const,
59  {
60    input: 0,
61    output: 0,
62    read: 0,
63    write: 0,
64    lastHit: null,
65    turns: 0,
66  } as Tally,
67);
68const cacheAtAtom = atom(
69  { plugin: "status-panel", key: "cacheAt" } as const,
70  0,
71);
72const nowAtom = atom({ plugin: "status-panel", key: "now" } as const, 0);
73const missAtom = atom(
74  { plugin: "status-panel", key: "miss" } as const,
75  null as Miss,
76);
77const repoAtom = atom(
78  { plugin: "status-panel", key: "repo" } as const,
79  { cwd: "", branch: "", sync: null, pr: null } as Repo,
80);
81const memAtom = atom(
82  { plugin: "status-panel", key: "mem" } as const,
83  [] as MemFile[],
84);
85const mcpAtom = atom(
86  { plugin: "status-panel", key: "mcp" } as const,
87  [] as McpServer[],
88);
89const callsAtom = atom(
90  { plugin: "status-panel", key: "calls" } as const,
91  {} as Record<string, number>,
92);
93const skillsAtom = atom(
94  { plugin: "status-panel", key: "skills" } as const,
95  [] as SkillInfo[],
96);
97const skillCallsAtom = atom(
98  { plugin: "status-panel", key: "skillCalls" } as const,
99  {} as Record<string, number>,
100);
101/** MCP servers and skills switched off in the project's .claude/settings.local.json. */
102const disabledAtom = atom(
103  { plugin: "status-panel", key: "disabled" } as const,
104  { mcp: [], skills: [] } as Disabled,
105);
106/** Where the switches are written: personal, not committed, as `/skills` writes it. */
107const LOCAL_SETTINGS = ".claude/settings.local.json";
108
109/** The project's local settings text; `null` when there is no such file yet. */
110async function readLocalSettings($: EngineInterface) {
111  const cwd = await $.session.cwd();
112  const text = await $.fs.read(`${cwd}/${LOCAL_SETTINGS}`).catch(() => null);
113
114  return typeof text === "string" ? text : null;
115}
116
117/**
118 * Switches an MCP server (`deniedMcpServers`) or a skill (`skillOverrides`) on or off in the
119 * project's local settings. A file that is no JSON is left as it is and the toast says so.
120 */
121async function switchInSettings(
122  $: EngineInterface,
123  kind: "mcp" | "skill",
124  name: string,
125) {
126  const text = await readLocalSettings($);
127  const isOff =
128    disabledFromSettings(text)[kind === "mcp" ? "mcp" : "skills"].includes(
129      name,
130    );
131  const next = toggleInSettings(text, kind, name, isOff);
132  if (next === null) {
133    $.ui.toast(`${LOCAL_SETTINGS} is not valid JSON: nothing written`);
134
135    return;
136  }
137  const cwd = await $.session.cwd();
138  await $.fs.write(`${cwd}/${LOCAL_SETTINGS}`, next);
139  await update($, disabledAtom, () => disabledFromSettings(next));
140  $.ui.toast(
141    kind === "mcp"
142      ? `MCP ${name} ${isOff ? "on" : "off"}: applies when it reconnects (/mcp or a new session)`
143      : `Skill ${name} ${isOff ? "on" : "off"}`,
144  );
145}
146const modelAtom = atom({ plugin: "status-panel", key: "model" } as const, "");
147const effortAtom = atom(
148  { plugin: "status-panel", key: "effort" } as const,
149  "–",
150);
151const planAtom = atom({ plugin: "status-panel", key: "plan" } as const, "");
152/** Local estimate of this organization's spend for the current month across sessions (USD). */
153const spentAtom = atom({ plugin: "status-panel", key: "spent" } as const, 0);
154/** Usage beyond the plan as the account reports it; `null` until read. */
155const accountAtom = atom(
156  { plugin: "status-panel", key: "account" } as const,
157  null as AccountSpend | null,
158);
159const billingAtom = atom(
160  { plugin: "status-panel", key: "billing" } as const,
161  { orgId: "", isUsageBased: false } as Billing,
162);
163const agentsAtom = atom(
164  { plugin: "status-panel", key: "agents" } as const,
165  [] as SubagentInfo[],
166);
167const agentUsageAtom = atom(
168  { plugin: "status-panel", key: "agentUsage" } as const,
169  {} as Record<string, SubagentUsage>,
170);
171/** Robot animation frame counter; grows only during a turn. */
172const frameAtom = atom({ plugin: "status-panel", key: "frame" } as const, 0);
173const showResetsAtom = atom(
174  { plugin: "status-panel", key: "showResets" } as const,
175  false,
176);
177const keepAliveAtom = atom(
178  { plugin: "status-panel", key: "keepAlive" } as const,
179  { isOn: false, pings: 0, usd: 0 } as KeepAlive,
180);
181/** How long before the cache expires the keep-alive request goes out. */
182const KEEP_ALIVE_LEAD_MS = 60_000;
183/** The keep-alive request: the shortest question with the shortest answer. */
184const KEEP_ALIVE_PROMPT = "Reply with the single word: ok";
185/** Estimated session cost by token kind (main thread and subagents). */
186const costPartsAtom = atom(
187  { plugin: "status-panel", key: "costParts" } as const,
188  {
189    input: 0,
190    output: 0,
191    read: 0,
192    write: 0,
193  },
194);
195
196/**
197 * With keep-alive on, sends one tiny request over the session's own transcript shortly before
198 * the cache expires, so the API reads the prefix from the cache and its TTL starts again.
199 * Not once the cache expired: the request would write the whole context again.
200 * A failed request switches keep-alive off.
201 */
202async function keepCacheAlive(
203  $: EngineInterface,
204  now: number,
205  ttlMs: number,
206  ttlMinutes: number,
207) {
208  const keep = await read($, keepAliveAtom);
209  const cacheAt = await read($, cacheAtAtom);
210  if (!isKeepAliveDue(keep.isOn, cacheAt, ttlMs, KEEP_ALIVE_LEAD_MS, now)) {
211    return;
212  }
213  const r = await $.model.fork({ prompt: KEEP_ALIVE_PROMPT });
214  const usage = "usage" in r ? r.usage : null;
215  const cost =
216    usage === null
217      ? 0
218      : (stepCost(await read($, modelAtom), usage, ttlMinutes) ?? 0);
219  await update($, keepAliveAtom, (k) => ({
220    ...k,
221    isOn: r.isAnswered && k.isOn,
222    pings: k.pings + 1,
223    usd: k.usd + cost,
224  }));
225  if (!r.isAnswered) {
226    $.ui.toast(`keep-alive off: ${r.reason}`);
227  } else if (
228    r.usage.cache_read_input_tokens + r.usage.cache_creation_input_tokens >
229    0
230  ) {
231    const doneAt = await $.clock.now();
232    await update($, cacheAtAtom, () => doneAt);
233  }
234}
235
236/** Opens a path with the OS opener: `start` on Windows, `open` on macOS, `xdg-open` elsewhere. */
237async function openWithOs($: EngineInterface, path: string) {
238  if ((await $.env.get("OS")) === "Windows_NT") {
239    await $.process.run(["cmd", "/c", "start", "", path]);
240
241    return;
242  }
243  const isMac =
244    (await $.env.get("OSTYPE"))?.startsWith("darwin") ||
245    (await $.process.run(["uname"]).catch(() => null))?.stdout.startsWith(
246      "Darwin",
247    );
248  await $.process.run([isMac ? "open" : "xdg-open", path]);
249}
250
251/** How long a looked-up pull request is trusted before `gh` or `az` is asked again. */
252const PR_TTL_MS = 2 * 60_000;
253/** Last `gh` / `az` answer: the network call runs on a branch change or after PR_TTL_MS. */
254let prCache: { key: string; at: number; pr: PullRequest | null } | null = null;
255
256async function lookupPr($: EngineInterface, cwd: string, branch: string) {
257  const key = `${cwd}|${branch}`;
258  const now = await $.clock.now();
259  if (prCache?.key === key && now - prCache.at < PR_TTL_MS) return prCache.pr;
260  // Without the CLI, without a login or without a PR it fails: no link is shown.
261  const run = (argv: string[]) =>
262    $.process.run(argv, { cwd }).catch(() => null);
263  const remote = await run(["git", "remote", "get-url", "origin"]);
264  let pr: PullRequest | null;
265  if (remote?.exitCode === 0 && isAzureRemote(remote.stdout)) {
266    // `az` is a .cmd script on Windows, which only a shell starts.
267    const az =
268      (await $.env.get("OS")) === "Windows_NT" ? ["cmd", "/c", "az"] : ["az"];
269    const out = await run([
270      ...az,
271      "repos",
272      "pr",
273      "list",
274      "--detect",
275      "true",
276      "--source-branch",
277      branch,
278      "--status",
279      "active",
280      "--top",
281      "1",
282      "-o",
283      "json",
284    ]);
285    pr =
286      out?.exitCode === 0
287        ? parseAzurePullRequest(out.stdout, remote.stdout)
288        : null;
289  } else {
290    const out = await run(["gh", "pr", "view", "--json", "number,url,state"]);
291    pr = out?.exitCode === 0 ? parsePullRequest(out.stdout) : null;
292  }
293  prCache = { key, at: now, pr };
294
295  return pr;
296}
297
298async function refreshRepo($: EngineInterface) {
299  const cwd = await $.session.cwd();
300  // Outside a git repository this is expected; the branch simply stays empty.
301  const run = (argv: string[]) =>
302    $.process.run(argv, { cwd }).catch(() => null);
303  const named = await run(["git", "branch", "--show-current"]);
304  let branch = named?.exitCode === 0 ? named.stdout.trim() : "";
305  if (named?.exitCode === 0 && branch === "") {
306    const sha = await run(["git", "rev-parse", "--short", "HEAD"]);
307    branch = sha?.exitCode === 0 ? `(${sha.stdout.trim()})` : "";
308  }
309  // Without an upstream branch it exits non-zero: the arrows are then not shown.
310  const counts = await run([
311    "git",
312    "rev-list",
313    "--left-right",
314    "--count",
315    "@{upstream}...HEAD",
316  ]);
317  const sync = counts?.exitCode === 0 ? parseAheadBehind(counts.stdout) : null;
318  // A detached HEAD has no pull request.
319  const pr =
320    named?.exitCode === 0 && named.stdout.trim() !== ""
321      ? await lookupPr($, cwd, branch)
322      : null;
323  await update($, repoAtom, () => ({ cwd, branch, sync, pr }));
324}
325
326/** Subagents spawned this session, the cleared ones included. */
327const spawnedAgentsAtom = atom(
328  { plugin: "status-panel", key: "spawnedAgents" } as const,
329  0,
330);
331/** Subagents whose request and response are expanded in the session pane. */
332const expandedAgentsAtom = atom(
333  { plugin: "status-panel", key: "expandedAgents" } as const,
334  [] as string[],
335);
336/** Longest response kept per subagent; the pane is for a look, the transcript has the rest. */
337const MAX_AGENT_TEXT = 20_000;
338
339/** Agent type → the `color` of its definition (user's, then the project's, which wins). */
340const agentColorsAtom = atom(
341  { plugin: "status-panel", key: "agentColors" } as const,
342  {} as Record<string, string>,
343);
344
345/** Reads the colors of the agent definitions in ~/.claude/agents and the project's .claude/agents. */
346async function refreshAgentColors($: EngineInterface) {
347  const configDir = await $.env.get("CLAUDE_CONFIG_DIR");
348  const home = (await $.env.get("USERPROFILE")) ?? (await $.env.get("HOME"));
349  const userDir =
350    configDir ?? (home === undefined ? undefined : `${home}/.claude`);
351  const cwd = await $.session.cwd();
352  const dirs = [
353    ...(userDir === undefined ? [] : [`${userDir}/agents`]),
354    `${cwd}/.claude/agents`,
355  ];
356  const colors: Record<string, string> = {};
357  for (const dir of dirs) {
358    // A missing folder just has no agents.
359    const entries = await $.fs.list(dir).catch(() => []);
360    for (const f of entries) {
361      // A symbolic link is listed as `other`: read it too, the read follows it.
362      if (f.kind === "dir" || !f.name.endsWith(".md")) continue;
363      const text = await $.fs.read(`${dir}/${f.name}`).catch(() => null);
364      const def = typeof text === "string" ? parseAgentDefinition(text) : null;
365      if (def !== null) colors[def.name] = def.color;
366    }
367  }
368  await update($, agentColorsAtom, () => colors);
369}
370
371/** The pane with the session's tokens and subagents, docked beside the transcript in fullscreen. */
372const SESSION_PANE = "session";
373/** Wide enough for a subagent row: description, model, tokens, status and cost. */
374const SESSION_PANE_COLUMNS = 96;
375
376/** Line count and modification time per memory file. */
377const fileDetailsAtom = atom(
378  { plugin: "status-panel", key: "fileDetails" } as const,
379  {} as Record<string, FileDetail>,
380);
381/** Hook commands of every settings source, in load order. */
382const hooksAtom = atom(
383  { plugin: "status-panel", key: "hooks" } as const,
384  [] as HookRow[],
385);
386/** Installed plugins that bring a hooks module, in load order. */
387const modsAtom = atom(
388  { plugin: "status-panel", key: "mods" } as const,
389  [] as ModRow[],
390);
391/** The settings file of each source, for the hooks' `↗ open`. */
392const settingsPathsAtom = atom(
393  { plugin: "status-panel", key: "settingsPaths" } as const,
394  {} as Partial<Record<SettingsScope, string>>,
395);
396/** The pane with the CLAUDE.md and AGENTS.md files in context. */
397const MEMORY_PANE = "memory";
398/** Files whose preview is open in the CLAUDE.md pane. */
399const expandedFilesAtom = atom(
400  { plugin: "status-panel", key: "expandedFiles" } as const,
401  [] as string[],
402);
403/** File text by path, read when its preview opens. */
404const previewsAtom = atom(
405  { plugin: "status-panel", key: "previews" } as const,
406  {} as Record<string, string>,
407);
408
409/** Opens or closes a file's preview; opening reads the file again, so the preview is current. */
410async function togglePreview($: EngineInterface, path: string) {
411  const isOpen = (await read($, expandedFilesAtom)).includes(path);
412  await update($, expandedFilesAtom, (paths) =>
413    isOpen ? paths.filter((x) => x !== path) : [...paths, path],
414  );
415  if (isOpen) return;
416  const text = await $.fs.read(path).catch(() => null);
417  await update($, previewsAtom, (all) => ({
418    ...all,
419    [path]: typeof text === "string" ? text : "– the file could not be read",
420  }));
421}
422
423/** The pane with MCP servers and skills, next to the session pane. */
424const TOOLS_PANE = "tools";
425
426/**
427 * Opens a pane by id, or closes it when it is already up. Only one of this mod's panes is up
428 * at a time: opening one closes the other, so closing it never leaves the other behind.
429 */
430async function togglePane($: EngineInterface, id: string, title: string) {
431  const up = (await $.ui.panes()).map((pane) => pane.id);
432  if (up.includes(id)) {
433    await $.ui.close({ id });
434
435    return;
436  }
437  for (const other of up) await $.ui.close({ id: other });
438  const opened = await $.ui.open({ id, title, columns: SESSION_PANE_COLUMNS });
439  if (!opened.isPlaced) $.ui.toast(`${title} pane: ${opened.reason}`);
440}
441
442/** A pull is on its way; another click waits for it rather than starting a second one. */
443let isPulling = false;
444
445/**
446 * Brings the branch level with its upstream: `git pull --ff-only` moves it forward and never
447 * merges, so a diverged branch or local changes in the way leave everything as it was and the
448 * toast says why.
449 */
450async function pullUpstream($: EngineInterface) {
451  if (isPulling) return;
452  isPulling = true;
453  try {
454    const cwd = await $.session.cwd();
455    $.ui.toast("git pull --ff-only…");
456    const r = await $.process
457      .run(["git", "pull", "--ff-only"], { cwd })
458      .catch(() => null);
459    const firstLine = (text: string) => text.trim().split("\n")[0] ?? "";
460    $.ui.toast(
461      r === null
462        ? "git pull: git did not run"
463        : r.exitCode === 0
464          ? "Pulled: up to date with upstream"
465          : `git pull failed: ${firstLine(r.stderr) || firstLine(r.stdout)}`,
466    );
467    await refreshRepo($);
468  } finally {
469    isPulling = false;
470  }
471}
472
473/** How long the first click on ↑n waits for the second, confirming one. */
474const PUSH_CONFIRM_MS = 5_000;
475/** When ↑n was clicked first; 0 while no push waits for its confirmation. */
476let pushArmedAt = 0;
477
478/**
479 * Pushes the branch to its upstream with a plain `git push` (never forced). The first click
480 * only asks for a second one within 5 s, so a stray click sends nothing out.
481 */
482async function pushUpstream($: EngineInterface) {
483  const now = await $.clock.now();
484  if (now - pushArmedAt > PUSH_CONFIRM_MS) {
485    pushArmedAt = now;
486    $.ui.toast("Click ↑ again within 5 s to git push");
487
488    return;
489  }
490  pushArmedAt = 0;
491  if (isPulling) return;
492  isPulling = true;
493  try {
494    const cwd = await $.session.cwd();
495    $.ui.toast("git push…");
496    const r = await $.process.run(["git", "push"], { cwd }).catch(() => null);
497    const firstLine = (text: string) => text.trim().split("\n")[0] ?? "";
498    $.ui.toast(
499      r === null
500        ? "git push: git did not run"
501        : r.exitCode === 0
502          ? "Pushed to upstream"
503          : `git push failed: ${firstLine(r.stderr) || firstLine(r.stdout)}`,
504    );
505    await refreshRepo($);
506  } finally {
507    isPulling = false;
508  }
509}
510
511async function refreshContext($: EngineInterface) {
512  const b = (await $.session.usage({ breakdown: "summary" })).context.breakdown;
513  const model = b?.model ?? "";
514  await update($, modelAtom, () => model);
515  const files = (b?.memoryFiles ?? []).map((f) => ({
516    path: f.path,
517    type: f.type,
518    tokens: f.tokens,
519  }));
520  await update($, memAtom, () => files);
521  const servers = groupMcp(b?.mcpTools ?? []);
522  await update($, mcpAtom, () => servers);
523  const skills = (b?.skills?.skillFrontmatter ?? []).map((s) => ({
524    name: s.name,
525    source: String(s.source),
526    tokens: s.tokens,
527  }));
528  await update($, skillsAtom, () => skills);
529  const local = await readLocalSettings($);
530  await update($, disabledAtom, () => disabledFromSettings(local));
531  await refreshContextFiles($, files);
532}
533
534/**
535 * Line counts and modification times of the memory files, and the hooks of every settings
536 * source with the file each lives in: what the CLAUDE.md pane shows.
537 */
538async function refreshContextFiles(
539  $: EngineInterface,
540  files: readonly MemFile[],
541) {
542  const details: Record<string, FileDetail> = {};
543  const homeDir =
544    (await $.env.get("USERPROFILE")) ?? (await $.env.get("HOME")) ?? "";
545  for (const f of files) {
546    const text = await $.fs.read(f.path).catch(() => null);
547    const stat = await $.fs.stat(f.path).catch(() => null);
548    details[f.path] = {
549      lines: typeof text === "string" ? text.split(/\r?\n/).length : 0,
550      mtimeMs: stat?.mtimeMs ?? 0,
551      // The files it pulls in with `@path`: the pane shows them under it.
552      imports: typeof text === "string" ? importsOf(text, f.path, homeDir) : [],
553    };
554  }
555  await update($, fileDetailsAtom, () => details);
556  const hooks: HookRow[] = [];
557  const enabled: [SettingsScope, unknown][] = [];
558  for (const scope of SETTINGS_ORDER) {
559    const settings = (await $.settings
560      .read({ source: scope })
561      .catch(() => null)) as {
562      hooks?: unknown;
563      enabledPlugins?: unknown;
564    } | null;
565    hooks.push(...hookRows(scope, settings?.hooks));
566    enabled.push([scope, settings?.enabledPlugins]);
567  }
568  await update($, hooksAtom, () => hooks);
569  const configDir = await $.env.get("CLAUDE_CONFIG_DIR");
570  const home = (await $.env.get("USERPROFILE")) ?? (await $.env.get("HOME"));
571  const userDir =
572    configDir ?? (home === undefined ? undefined : `${home}/.claude`);
573  const cwd = await $.session.cwd();
574  // Mods: the installed plugins that bring a hooks module, in the order the settings load.
575  const installed = await $.fs
576    .read(`${userDir ?? "~/.claude"}/plugins/installed_plugins.json`)
577    .catch(() => null);
578  const mods: ModRow[] = [];
579  for (const row of pluginRows(
580    typeof installed === "string" ? installed : null,
581    enabled,
582  )) {
583    const manifest =
584      row.path === ""
585        ? null
586        : await $.fs.read(`${row.path}/hooks/hooks.json`).catch(() => null);
587    if (typeof manifest === "string" && manifest.includes('"modules"')) {
588      mods.push(row);
589    }
590  }
591  await update($, modsAtom, () => mods);
592  await update($, settingsPathsAtom, () => ({
593    ...(userDir === undefined ? {} : { user: `${userDir}/settings.json` }),
594    project: `${cwd}/.claude/settings.json`,
595    local: `${cwd}/.claude/settings.local.json`,
596  }));
597}
598
599async function refreshPlan($: EngineInterface) {
600  const dir =
601    (await $.env.get("CLAUDE_CONFIG_DIR")) ??
602    (await $.env.get("USERPROFILE")) ??
603    (await $.env.get("HOME"));
604  if (dir === undefined) return;
605  // A missing file just means we do not show the subscription.
606  const text = await $.fs.read(`${dir}/.claude.json`).catch(() => null);
607  const account = typeof text === "string" ? accountFromClaudeJson(text) : null;
608  if (account === null) return;
609  await update($, planAtom, () => account.plan);
610  const prev = await read($, billingAtom);
611  await update($, billingAtom, () => ({
612    orgId: account.orgId,
613    isUsageBased: account.isUsageBased,
614  }));
615  // After /login into another account the old figures do not apply.
616  if (prev.orgId !== "" && prev.orgId !== account.orgId) {
617    await update($, accountAtom, () => null);
618    await refreshAccount($);
619  }
620}
621
622const USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
623
624/** Reads usage beyond the plan and prepaid credits of the signed-in account. */
625async function refreshAccount($: EngineInterface) {
626  // Null with an API key, a 3P provider or no login: there is no account to ask.
627  const auth = await $.session.authorize();
628  if (auth === null) return;
629  // Offline or rate limited: the line keeps the last figures.
630  const res = await $.http
631    .fetch(USAGE_URL, {
632      auth: auth.handle,
633      headers: {
634        Accept: "application/json",
635        "anthropic-beta": "oauth-2025-04-20",
636      },
637    })
638    .catch(() => null);
639  if (res?.ok !== true) return;
640  const spend = parseAccountSpend(res.text);
641  await update($, accountAtom, () => spend);
642}
643
644/**
645 * Writes this session's cost into the organization's monthly total in `$.store` and reflects
646 * the total in state. Only an Enterprise seat pays for every request, so only it is counted.
647 */
648async function refreshSpend(
649  $: EngineInterface,
650  startedAt: number,
651  usd: number,
652) {
653  const billing = await read($, billingAtom);
654  if (!billing.isUsageBased) return;
655  const key = monthKey(await $.clock.now(), billing.orgId);
656  const stored = (await $.store.get(key)) as Record<string, number> | undefined;
657  const sessions = { ...stored, [String(startedAt)]: usd };
658  await $.store.set(key, sessions);
659  const spent = Object.values(sessions).reduce((sum, v) => sum + v, 0);
660  await update($, spentAtom, () => spent);
661}
662
663async function refresh($: EngineInterface) {
664  const u = await $.session.usage();
665  const snap: Snap = {
666    ctxTokens: u.context.tokens ?? 0,
667    ctxWindow: u.context.window,
668    ctxPercent: u.context.percent ?? 0,
669    usd: u.cost?.usd ?? 0,
670    limits: u.rateLimits.map((l) => ({
671      kind: l.kind,
672      percentUsed: l.percentUsed,
673      resetsAt: l.resetsAt,
674    })),
675  };
676  await update($, snapAtom, () => snap);
677  await refreshSpend($, u.startedAt, snap.usd);
678}
679
680export const register: Register = (on, options) => {
681  const ttlMinutes = Number(options.ttlMinutes ?? "60");
682  const ttlMs = ttlMinutes * 60_000;
683  const budget = Number(options.budgetUsd ?? "250");
684  let prevTotal = 0;
685  let prevModel = "";
686  let prevEffort: unknown;
687  let isCompacted = false;
688  let ticks = 0;
689  let isWorking = false;
690  /** A keep-alive request is on its way; the next tick does not send another. */
691  let isPinging = false;
692  /** Subagents that sent a request and whose turn has not ended yet. */
693  const runningAgents = new Set<string>();
694
695  on("turn.start", ($, e, next) => {
696    isWorking = true;
697
698    return next(e);
699  });
700
701  on("session.start", async ($, e, next) => {
702    const startedAt = await $.clock.now();
703    await update($, nowAtom, () => startedAt);
704    // The plan decides whether this session's cost counts toward the month.
705    await refreshPlan($);
706    await refresh($);
707    await refreshRepo($);
708    await refreshContext($);
709    await refreshAccount($);
710    await refreshAgentColors($);
711    $.clock.every(250, async () => {
712      // The animation (Clawd, asterisks of running subagents) runs while anyone is working.
713      if (isWorking || runningAgents.size > 0) {
714        await update($, frameAtom, (f) => f + 1);
715      }
716    });
717    $.clock.every(1000, async () => {
718      const tickAt = await $.clock.now();
719      await update($, nowAtom, () => tickAt);
720      ticks += 1;
721      if (ticks % 15 === 0) await refresh($);
722      if (ticks % 30 === 0) {
723        await refreshRepo($);
724        await refreshContext($);
725        await refreshPlan($);
726      }
727      if (ticks % 120 === 0) await refreshAccount($);
728      // Not while a turn runs (the turn refreshes the cache itself) or a request is on its way.
729      if (!isWorking && !isPinging) {
730        isPinging = true;
731        try {
732          await keepCacheAlive($, tickAt, ttlMs, ttlMinutes);
733        } finally {
734          isPinging = false;
735        }
736      }
737    });
738
739    return next(e);
740  });
741
742  on("turn.complete", async ($, e, next) => {
743    const agentId = e.agentId;
744    if (agentId === undefined) {
745      isWorking = false;
746    } else {
747      runningAgents.delete(agentId);
748      // Subagent run time = sum of its completed turns.
749      await update($, agentUsageAtom, (all) => {
750        const cur = all[agentId] ?? emptyAgent();
751
752        return {
753          ...all,
754          [agentId]: {
755            ...cur,
756            // A record from an older version of the mod has no durationMs.
757            durationMs:
758              (Number.isFinite(cur.durationMs) ? cur.durationMs : 0) +
759              e.durationMs,
760            isDone: true,
761          },
762        };
763      });
764    }
765    await refreshRepo($);
766    await refreshContext($);
767    const r = await next(e);
768    // A subagent's last answer is its response; the session pane shows it under its request.
769    if (agentId !== undefined && r.text !== "") {
770      const result = r.text.slice(0, MAX_AGENT_TEXT);
771      await update($, agentsAtom, (list) =>
772        list.map((a) => (a.id === agentId ? { ...a, result } : a)),
773      );
774    }
775
776    return r;
777  });
778
779  on("tool.call", async ($, e, next) => {
780    await update($, callsAtom, (c) => ({
781      ...c,
782      [e.tool]: (c[e.tool] ?? 0) + 1,
783    }));
784    if (e.tool === "Skill") {
785      const name = e.skill;
786      await update($, skillCallsAtom, (c) => ({
787        ...c,
788        [name]: (c[name] ?? 0) + 1,
789      }));
790    }
791
792    return next(e);
793  });
794
795  on("session.compact", ($, e, next) => {
796    isCompacted = true;
797
798    return next(e);
799  });
800
801  on("agent.spawn", async ($, e, next) => {
802    const startedAt = await $.clock.now();
803    // An agent defined or recoloured since the session started gets its colour too.
804    await refreshAgentColors($);
805    const r = await next(e);
806    const id = r.agentId;
807    if (id !== undefined) {
808      const info = {
809        id,
810        description: e.description,
811        type: e.subagentType,
812        startedAt,
813        prompt: e.prompt,
814      };
815      await update($, agentsAtom, (list) => [
816        ...list.filter((a) => a.id !== id),
817        info,
818      ]);
819      await update($, spawnedAgentsAtom, (n) => n + 1);
820    }
821
822    return r;
823  });
824
825  on("turn.step", async function* ($, e, next) {
826    const sentAt = await $.clock.now();
827    const r = yield* next(e);
828    const u = r.usage;
829
830    if (u !== null) {
831      const total =
832        u.input_tokens +
833        u.cache_read_input_tokens +
834        u.cache_creation_input_tokens;
835      const hit = percentOf(
836        u.cache_read_input_tokens,
837        u.cache_creation_input_tokens,
838        u.input_tokens,
839      );
840      await update($, tallyAtom, (t) => ({
841        input: t.input + u.input_tokens,
842        output: t.output + u.output_tokens,
843        read: t.read + u.cache_read_input_tokens,
844        write: t.write + u.cache_creation_input_tokens,
845        lastHit: e.agentId === undefined ? hit : t.lastHit,
846        turns: t.turns + 1,
847      }));
848
849      const parts = stepCostParts(e.model, u, ttlMinutes);
850      await update($, costPartsAtom, (sum) => addCostParts(sum, parts));
851
852      const agentId = e.agentId;
853      if (agentId !== undefined) {
854        runningAgents.add(agentId);
855        const cost = stepCost(e.model, u, ttlMinutes);
856        await update($, agentUsageAtom, (all) => ({
857          ...all,
858          [agentId]: addAgentStep(
859            all[agentId],
860            e.model,
861            u,
862            cost,
863            effortShort(e.effort),
864          ),
865        }));
866      } else {
867        const lastAt = await read($, cacheAtAtom);
868        if (prevTotal > 0 && u.cache_read_input_tokens < prevTotal * 0.5) {
869          const reason = missReason({
870            isCompacted,
871            total,
872            prevTotal,
873            model: e.model,
874            prevModel,
875            isEffortChanged: e.effort !== prevEffort,
876            gapMs: lastAt > 0 ? sentAt - lastAt : 0,
877            ttlMs,
878          });
879          await update($, missAtom, () => ({ at: sentAt, reason }));
880        } else if (u.cache_read_input_tokens > 0) {
881          // The request reads from the cache again: the cache is refreshed, the message no longer applies.
882          await update($, missAtom, () => null);
883        }
884        isCompacted = false;
885        prevTotal = total;
886        prevModel = e.model;
887        prevEffort = e.effort;
888        await update($, effortAtom, () => effortShort(e.effort));
889        if (u.cache_read_input_tokens + u.cache_creation_input_tokens > 0) {
890          const doneAt = await $.clock.now();
891          await update($, cacheAtAtom, () => doneAt);
892        }
893      }
894    }
895    await refresh($);
896
897    return r;
898  });
899
900  on(
901    "ui.render",
902    { component: "Pane", requestId: SESSION_PANE },
903    async ($, e) => {
904      const snap = await read($, snapAtom);
905      const el = $.ui.resolve(e);
906      const { Text } = el;
907      const list = renderList(el, {
908        open: "session",
909        agents: await read($, agentsAtom),
910        agentUsage: await read($, agentUsageAtom),
911        sessionUsd: snap?.usd ?? 0,
912        now: await read($, nowAtom),
913        frame: await read($, frameAtom),
914        tally: await read($, tallyAtom),
915        costParts: await read($, costPartsAtom),
916        columns: e.props.bodyColumns,
917        expanded: await read($, expandedAgentsAtom),
918        agentColors: await read($, agentColorsAtom),
919        spawnedAgents: await read($, spawnedAgentsAtom),
920        onToggleAgent: async (id: string) => {
921          await update($, expandedAgentsAtom, (ids) =>
922            ids.includes(id) ? ids.filter((x) => x !== id) : [...ids, id],
923          );
924        },
925        onClearAgents: async () => {
926          // Running subagents stay, so their live status is not lost.
927          const usage = await read($, agentUsageAtom);
928          const isRunning = (id: string) => usage[id]?.isDone !== true;
929          await update($, agentsAtom, (list) =>
930            list.filter((a) => isRunning(a.id)),
931          );
932          await update($, agentUsageAtom, (all) =>
933            Object.fromEntries(
934              Object.entries(all).filter(([id]) => isRunning(id)),
935            ),
936          );
937          await update($, expandedAgentsAtom, (ids) => ids.filter(isRunning));
938        },
939      });
940
941      // The session kind always draws a list; the fallback only satisfies the type.
942      return list ?? <Text dimColor>No session data yet.</Text>;
943    },
944  );
945
946  on("ui.render", { component: "Pane", requestId: MEMORY_PANE }, async ($, e) =>
947    renderMemory($.ui.resolve(e), {
948      columns: e.props.bodyColumns,
949      cwd: (await read($, repoAtom)).cwd,
950      now: await read($, nowAtom),
951      files: await read($, memAtom),
952      details: await read($, fileDetailsAtom),
953      hooks: await read($, hooksAtom),
954      mods: await read($, modsAtom),
955      settingsPaths: await read($, settingsPathsAtom),
956      expanded: await read($, expandedFilesAtom),
957      previews: await read($, previewsAtom),
958      onToggle: async (path: string) => {
959        await togglePreview($, path);
960      },
961      onOpenFolder: async (path: string) => {
962        const folder = path.replace(/[\\/][^\\/]*$/, "");
963        await openWithOs($, folder);
964        $.ui.toast(`Opening ${folder}`);
965      },
966    }),
967  );
968
969  on("ui.render", { component: "Pane", requestId: TOOLS_PANE }, async ($, e) =>
970    renderTools($.ui.resolve(e), {
971      columns: e.props.bodyColumns,
972      mcp: await read($, mcpAtom),
973      calls: await read($, callsAtom),
974      skills: await read($, skillsAtom),
975      skillCalls: await read($, skillCallsAtom),
976      disabledMcp: (await read($, disabledAtom)).mcp,
977      disabledSkills: (await read($, disabledAtom)).skills,
978      onToggleMcp: async (server: string) => {
979        await switchInSettings($, "mcp", server);
980      },
981      onToggleSkill: async (skill: string) => {
982        await switchInSettings($, "skill", skill);
983      },
984    }),
985  );
986
987  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
988    const snap = await read($, snapAtom);
989    if (e.props.hasSurvey || snap === null) return next(e);
990
991    const toggle = async (kind: Kind) => {
992      // The session breakdown is long: it opens in its own pane, not in the band.
993      if (kind === "session") {
994        await togglePane($, SESSION_PANE, "Session");
995
996        return;
997      }
998      // MCP servers and skills open in a pane of their own as well.
999      if (kind === "mcp") {
1000        await togglePane($, TOOLS_PANE, "MCP & skills");
1001
1002        return;
1003      }
1004      // CLAUDE.md and AGENTS.md files open in a pane too.
1005      await togglePane($, MEMORY_PANE, "Settings");
1006    };
1007    // A file in the default app, a folder in the file manager.
1008    const openPath = async (path: string) => {
1009      await openWithOs($, path);
1010      $.ui.toast(`Opening ${baseName(path)}`);
1011    };
1012
1013    return renderBand($.ui.resolve(e), {
1014      now: await read($, nowAtom),
1015      ttlMs,
1016      snap,
1017      money: moneyLine(
1018        await read($, billingAtom),
1019        await read($, accountAtom),
1020        await read($, spentAtom),
1021        budget,
1022      ),
1023      tally: await read($, tallyAtom),
1024      cacheAt: await read($, cacheAtAtom),
1025      miss: await read($, missAtom),
1026      repo: await read($, repoAtom),
1027      model: await read($, modelAtom),
1028      effort: await read($, effortAtom),
1029      plan: await read($, planAtom),
1030      onToggle: toggle,
1031      onOpen: openPath,
1032      isWorking: e.props.isWorking,
1033      frame: await read($, frameAtom),
1034      showResets: await read($, showResetsAtom),
1035      keepAlive: await read($, keepAliveAtom),
1036      onPush: async () => {
1037        await pushUpstream($);
1038      },
1039      onPull: async () => {
1040        await pullUpstream($);
1041      },
1042      onToggleKeepAlive: async () => {
1043        await update($, keepAliveAtom, (k) => ({ ...k, isOn: !k.isOn }));
1044      },
1045      onToggleResets: async () => {
1046        await update($, showResetsAtom, (shown) => !shown);
1047      },
1048    });
1049  });
1050};
1051
hooks/band.tsx 359 lines
1import type { ElementTable } from "claude-code";
2
3import type {
4  CostParts,
5  SubagentInfo,
6  SubagentUsage,
7  KeepAlive,
8  Kind,
9  Miss,
10  Money,
11  Repo,
12  Snap,
13  Tally,
14} from "../types";
15import {
16  baseName,
17  clock,
18  countdown,
19  green,
20  orange,
21  red,
22  percentCell,
23  relIn,
24  resetAt,
25  scale,
26  shortModel,
27  thinBar,
28  tokens,
29  ttlScale,
30  usd,
31  money as formatMoney,
32  yellow,
33} from "./format";
34import { renderRobot } from "./robot";
35
36export type BandProps = {
37  now: number;
38  ttlMs: number;
39  snap: Snap;
40  /** Extra usage beyond a personal plan, or all spend this month on Enterprise. */
41  money: Money;
42  tally: Tally;
43  cacheAt: number;
44  miss: Miss;
45  repo: Repo;
46  model: string;
47  effort: string;
48  /** Subscription, e.g. `Max 5x`; empty when unknown. */
49  plan: string;
50  onToggle: (kind: Kind) => void;
51  /** Opens a file or folder in the system. */
52  onOpen: (path: string) => void;
53  /** A turn is running (`e.props.isWorking`): the robot is working. */
54  isWorking: boolean;
55  /** Robot animation frame counter. */
56  frame: number;
57  /** Show the absolute reset time next to limits. */
58  showResets: boolean;
59  onToggleResets: () => void;
60  keepAlive: KeepAlive;
61  onToggleKeepAlive: () => void;
62  /** Fast-forwards the branch to its upstream (`git pull --ff-only`). */
63  onPull: () => void;
64  /** Pushes the branch to its upstream after a confirming second click (`git push`). */
65  onPush: () => void;
66};
67
68/** Width of the context and money bars in cells. */
69const BAR_CELLS = 15;
70/** The money bar sits beside the short time limits: a shorter bar keeps that column narrow. */
71const MONEY_BAR_CELLS = 8;
72/** Width of a row label (`context`, `cache`) including the gap after it. */
73const LABEL_CELLS = 9;
74/**
75 * Column where CLAUDE.md (cache row) and keep-alive's spend (bottom row) start: under the token count
76 * on the context row (label, bar, a space, the four-cell percentage and two spaces).
77 */
78const KEEP_ALIVE_COLUMN = LABEL_CELLS + BAR_CELLS + 1 + 4 + 2;
79/** Width of the relative time (`1.5h`, `45m`) including a space so absolute times line up. */
80const REL_CELLS = 6;
81/** Above this context fill a cold cache is expensive: the frame turns orange. */
82const ALERT_CTX_PERCENT = 35;
83/** Above this context fill the frame always turns red, even with an active cache. */
84const FULL_CTX_PERCENT = 65;
85/** Calm: no background, border in the theme's muted color. */
86const CALM = { background: undefined, border: "subtle", style: "round" };
87const ALERT = { background: "#4a0a0a", border: red, style: "bold" };
88const WARN = { background: "#3d2305", border: orange, style: "round" };
89
90const hitColor = (hit: number) =>
91  hit >= 80 ? green : hit >= 50 ? yellow : red;
92
93const resetsAtMs = (resetsAt?: string) =>
94  resetsAt ? Date.parse(resetsAt) : null;
95
96/** The money row shows only with a known limit and extra usage not switched off. */
97export const hasMoneyRow = (money: Money) =>
98  money.limit !== null && !money.isOff;
99
100/** The whole band above the prompt in a quiet frame: header, meters with limits, links and the expanded list. */
101export function renderBand(el: ElementTable, p: BandProps) {
102  const { Box, Button, Link, Text } = el;
103
104  const five = p.snap.limits.find((l) => l.kind === "five_hour");
105  const week = p.snap.limits.find((l) => l.kind === "seven_day");
106  const fiveAt = resetsAtMs(five?.resetsAt);
107  const weekAt = resetsAtMs(week?.resetsAt);
108
109  const left = p.cacheAt > 0 ? p.cacheAt + p.ttlMs - p.now : 0;
110  const isExpired = p.cacheAt > 0 && left <= 0;
111  // Above 65 % always red; 35–65 % with a cold cache orange.
112  const theme =
113    p.snap.ctxPercent > FULL_CTX_PERCENT
114      ? ALERT
115      : isExpired && p.snap.ctxPercent > ALERT_CTX_PERCENT
116        ? WARN
117        : CALM;
118  const sum = p.tally.read + p.tally.write + p.tally.input;
119  const sessionHit = sum === 0 ? null : Math.round((p.tally.read / sum) * 100);
120  const { money } = p;
121  // Usage-based billing (Enterprise) pays per token: the 5h and 7d windows say nothing there.
122  const showsLimits = money.label !== "month";
123  const moneyPercent =
124    money.spent !== null && money.limit !== null && money.limit > 0
125      ? (money.spent / money.limit) * 100
126      : 0;
127
128  /** A row label, dim and padded so the bars start in one column. */
129  const label = (text: string) => (
130    <Text dimColor>{text.padEnd(LABEL_CELLS)}</Text>
131  );
132  /** A thin bar and its percentage, both in the fill's color. */
133  const meter = (percent: number, cells = BAR_CELLS, isTall = false) => {
134    const thin = thinBar(percent, cells);
135    // The tall bar draws the same cells as ▬, a block centred in the row (the eighth blocks
136    // ▁–▇ grow from the bottom and sit low); the empty part keeps the height, only dim.
137    const filled = isTall ? thin.filled.replaceAll("━", "▬") : thin.filled;
138    const empty = isTall ? thin.empty.replaceAll("─", "▬") : thin.empty;
139
140    return (
141      <Text>
142        <Text color={scale(percent)}>{filled}</Text>
143        <Text dimColor>{empty}</Text>
144        <Text color={scale(percent)}> {percentCell(percent)}</Text>
145      </Text>
146    );
147  };
148  const header = [
149    p.model === "" ? "–" : shortModel(p.model),
150    p.effort,
151    p.plan,
152  ].filter((part) => part !== "");
153
154  return (
155    <Box
156      flexDirection="column"
157      borderStyle={theme.style}
158      borderColor={theme.border}
159      backgroundColor={theme.background}
160      paddingX={1}
161    >
162      <Box justifyContent="space-between" columnGap={4}>
163        <Box columnGap={2}>
164          <Button key="k-folder" plain onPress={() => p.onOpen(p.repo.cwd)}>
165            <Text bold underline>
166              {baseName(p.repo.cwd)}
167            </Text>
168          </Button>
169          {p.repo.branch ? (
170            <Box>
171              <Text>
172                <Text color={green}>{p.repo.branch}</Text>
173                {p.repo.sync === null ? null : p.repo.sync.ahead === 0 &&
174                  p.repo.sync.behind === 0 ? (
175                  <Text dimColor> ✓</Text>
176                ) : p.repo.sync.ahead > 0 && p.repo.sync.behind > 0 ? (
177                  <Text color={green}> ↑{p.repo.sync.ahead}</Text>
178                ) : null}{" "}
179              </Text>
180              {/* Only ahead of upstream: a click (confirmed by a second one) pushes. */}
181              {p.repo.sync !== null &&
182              p.repo.sync.ahead > 0 &&
183              p.repo.sync.behind === 0 ? (
184                <Button key="k-push" plain onPress={p.onPush}>
185                  <Text color={green} underline>
186                    ↑{p.repo.sync.ahead}
187                  </Text>
188                </Button>
189              ) : null}
190              {/* Behind upstream: a click fast-forwards the branch. */}
191              {p.repo.sync !== null && p.repo.sync.behind > 0 ? (
192                <Button key="k-pull" plain onPress={p.onPull}>
193                  <Text color={orange} underline>
194                    ↓{p.repo.sync.behind}
195                  </Text>
196                </Button>
197              ) : null}
198              {p.repo.pr ? (
199                <Text>
200                  {"  "}
201                  <Link href={p.repo.pr.url} label={`PR#${p.repo.pr.number}`} />
202                </Text>
203              ) : null}
204            </Box>
205          ) : null}
206        </Box>
207        <Text dimColor>{header.join(" · ")}</Text>
208      </Box>
209      <Text> </Text>
210
211      <Box justifyContent="space-between" flexWrap="wrap" columnGap={3}>
212        <Box flexDirection="column">
213          <Text>
214            {label("context")}
215            {meter(p.snap.ctxPercent, BAR_CELLS, true)}
216            <Text dimColor>
217              {"  "}
218              {tokens(p.snap.ctxTokens)} [{tokens(p.snap.ctxWindow)}]
219            </Text>
220          </Text>
221          <Box>
222            <Box width={KEEP_ALIVE_COLUMN}>
223              {/* The word cache switches keep-alive: a tiny request shortly before the TTL
224                  runs out keeps the cache warm. The dot is green while it is on. */}
225              <Button key="k-keep" plain onPress={p.onToggleKeepAlive}>
226                <Text dimColor underline>
227                  cache
228                </Text>
229                {p.keepAlive.isOn ? (
230                  <Text color={green}> ●</Text>
231                ) : (
232                  <Text dimColor> ●</Text>
233                )}
234                <Text>{" ".repeat(LABEL_CELLS - "cache ●".length)}</Text>
235              </Button>
236              <Text>
237                {p.tally.lastHit === null ? (
238                  <Text dimColor>–</Text>
239                ) : (
240                  <Text color={hitColor(p.tally.lastHit)}>
241                    {p.tally.lastHit}%
242                  </Text>
243                )}
244                <Text dimColor>
245                  {"  "}Σ {sessionHit ?? "–"}%{"  "}
246                </Text>
247                {p.cacheAt === 0 ? (
248                  <Text dimColor>–</Text>
249                ) : left > 0 ? (
250                  <Text color={ttlScale(left, p.ttlMs)}>{countdown(left)}</Text>
251                ) : (
252                  <Text bold color={red}>
253                    expired
254                  </Text>
255                )}
256              </Text>
257            </Box>
258            {/* The side panes start under the token count of the context row. */}
259            <Box columnGap={3}>
260              {/* CLAUDE.md, rules, hooks and mods: the counts are in the pane. */}
261              <Button key="k-claude" plain onPress={() => p.onToggle("claude")}>
262                <Text underline>SETTINGS</Text>
263              </Button>
264              <Button key="k-mcp" plain onPress={() => p.onToggle("mcp")}>
265                <Text underline>MCP</Text>
266              </Button>
267            </Box>
268          </Box>
269          {p.miss ? (
270            <Text color={orange}>
271              {" ".repeat(LABEL_CELLS)}cache miss {clock(p.miss.at)} ·{" "}
272              {p.miss.reason}
273            </Text>
274          ) : null}
275        </Box>
276        <Box columnGap={3}>
277          {/* Clicking a limit shows or hides when the windows reset. */}
278          <Box flexDirection="column">
279            {showsLimits && five ? (
280              <Button key="k-5h" plain onPress={p.onToggleResets}>
281                <Text dimColor>5h </Text>
282                <Text color={scale(five.percentUsed)}>
283                  {percentCell(five.percentUsed)}
284                </Text>
285                <Text dimColor>
286                  {"  "}
287                  {(fiveAt ? relIn(fiveAt, p.now) : "").padEnd(REL_CELLS)}
288                  {p.showResets && fiveAt ? `[${clock(fiveAt)}]` : ""}
289                </Text>
290              </Button>
291            ) : null}
292            {showsLimits && week ? (
293              <Button key="k-7d" plain onPress={p.onToggleResets}>
294                <Text dimColor>7d </Text>
295                <Text color={scale(week.percentUsed)}>
296                  {percentCell(week.percentUsed)}
297                </Text>
298                <Text dimColor>
299                  {"  "}
300                  {(weekAt ? relIn(weekAt, p.now) : "").padEnd(REL_CELLS)}
301                  {p.showResets && weekAt ? resetAt(weekAt) : ""}
302                </Text>
303              </Button>
304            ) : null}
305            {/* Money under the time limits: both say how much of an allowance is used. */}
306            {hasMoneyRow(money) ? (
307              // With no limits above it (Enterprise) the amounts go on a row of their own
308              // under the bar, so the block stays narrow; otherwise all on one row.
309              <Box flexDirection={showsLimits ? "row" : "column"}>
310                <Text>
311                  <Text dimColor>{money.label} </Text>
312                  {meter(moneyPercent, MONEY_BAR_CELLS)}
313                  {showsLimits ? <Text>{"  "}</Text> : null}
314                </Text>
315                <Text dimColor>
316                  {money.spent === null
317                    ? "–"
318                    : formatMoney(money.spent, money.currency)}{" "}
319                  / {formatMoney(money.limit ?? 0, money.currency)}
320                </Text>
321              </Box>
322            ) : null}
323          </Box>
324          {renderRobot(el, {
325            isWorking: p.isWorking,
326            frame: p.frame,
327            now: p.now,
328          })}
329        </Box>
330      </Box>
331
332      <Box>
333        {/* Session cost and credits on the left, keep-alive's spend from the token column on. */}
334        <Box width={KEEP_ALIVE_COLUMN} columnGap={3}>
335          <Button key="k-session" plain onPress={() => p.onToggle("session")}>
336            {/* The same label width as context and cache: the amount sits under their values. */}
337            {label("session")}
338            <Text bold underline>
339              {usd(p.snap.usd)}
340            </Text>
341          </Button>
342          {money.balance === null ? null : (
343            <Text>
344              <Text dimColor>credits </Text>
345              {formatMoney(money.balance, money.currency)}
346            </Text>
347          )}
348        </Box>
349        {/* What keep-alive has sent and cost; nothing until its first request. */}
350        {p.keepAlive.pings === 0 ? null : (
351          <Text dimColor>
352            keep-alive {p.keepAlive.pings}× {usd(p.keepAlive.usd)}
353          </Text>
354        )}
355      </Box>
356    </Box>
357  );
358}
359
hooks/format.ts 721 lines
1import type {
2  AccountSpend,
3  Billing,
4  CostParts,
5  Money,
6  PullRequest,
7} from "../types";
8
9const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
10
11const pad = (n: number) => String(n).padStart(2, "0");
12
13export const green = "#22c55e";
14export const yellow = "#eab308";
15export const orange = "#f97316";
16export const red = "#ef4444";
17
18/** Usage color scale: green < 50, yellow < 75, orange < 90, red. */
19export const scale = (percent: number) =>
20  percent < 50 ? green : percent < 75 ? yellow : percent < 90 ? orange : red;
21
22/** Remaining cache time scale: the less is left, the redder. */
23export const ttlScale = (remainingMs: number, ttlMs: number) => {
24  const left = remainingMs / ttlMs;
25
26  return left > 0.5 ? green : left > 0.2 ? yellow : left > 0.05 ? orange : red;
27};
28
29export const tokens = (n: number) =>
30  n >= 1_000_000
31    ? `${Number((n / 1_000_000).toFixed(1))}M`
32    : n >= 1000
33      ? `${Math.round(n / 1000)}k`
34      : String(n);
35
36/** Amounts in US dollars (the engine's session cost, price-list estimates): `3.71$`. */
37export const usd = (n: number) => `${n.toFixed(2)}$`;
38
39const CURRENCY_SIGNS: Readonly<Record<string, string>> = {
40  USD: "$",
41  EUR: "€",
42  GBP: "£",
43  CZK: " Kč",
44};
45
46/** An amount in the account's currency, the sign after the number: `3.71€`; `null` is dollars. */
47export const money = (n: number, currency: string | null) =>
48  `${n.toFixed(2)}${currency === null ? "$" : (CURRENCY_SIGNS[currency] ?? ` ${currency}`)}`;
49
50export const clock = (ms: number) => {
51  const d = new Date(ms);
52
53  return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
54};
55
56/** Time left until reset: from a day `5d5h`, from an hour `1.5h`, otherwise `45m`. */
57export const relIn = (resetsAtMs: number, nowMs: number) => {
58  const minutes = Math.max(0, (resetsAtMs - nowMs) / 60000);
59  if (minutes >= 24 * 60) {
60    const hours = Math.floor(minutes / 60);
61
62    return `${Math.floor(hours / 24)}d${hours % 24}h`;
63  }
64
65  return minutes >= 60
66    ? `${(minutes / 60).toFixed(1)}h`
67    : `${Math.round(minutes)}m`;
68};
69
70/** Percentage right-aligned to 4 cells (`  7%`, ` 31%`, `100%`) so the time after it lines up. */
71export const percentCell = (percent: number) =>
72  `${Math.round(percent)}%`.padStart(4);
73
74/** Absolute time only: `[Mon 12.10. 08:00]`. */
75export const resetAt = (resetsAtMs: number) => {
76  const d = new Date(resetsAtMs);
77
78  return `[${DAYS[d.getDay()]} ${d.getDate()}.${d.getMonth() + 1}. ${clock(resetsAtMs)}]`;
79};
80
81/** `mm:ss` until cache invalidation, `h:mm:ss` above an hour. */
82export const countdown = (ms: number) => {
83  const s = Math.max(0, Math.floor(ms / 1000));
84  const h = Math.floor(s / 3600);
85  const m = Math.floor((s % 3600) / 60);
86
87  return h > 0 ? `${h}:${pad(m)}:${pad(s % 60)}` : `${pad(m)}:${pad(s % 60)}`;
88};
89
90export const percentOf = (read: number, write: number, input: number) => {
91  const total = read + write + input;
92
93  return total === 0 ? null : Math.round((read / total) * 100);
94};
95
96const slashes = (p: string) => p.replace(/\\/g, "/");
97
98export const baseName = (path: string) =>
99  slashes(path).split("/").filter(Boolean).pop() ?? path;
100
101/** Path relative to the session folder, otherwise the last three segments. */
102export const shortPath = (path: string, cwd: string) => {
103  const p = slashes(path);
104  const root = slashes(cwd).replace(/\/$/, "");
105
106  return root !== "" && p.toLowerCase().startsWith(`${root.toLowerCase()}/`)
107    ? p.slice(root.length + 1)
108    : `…/${p.split("/").slice(-3).join("/")}`;
109};
110
111const EFFORT: Record<string, string> = {
112  low: "L",
113  medium: "M",
114  high: "H",
115  xhigh: "XH",
116  max: "MAX",
117};
118
119/** `low`→L, `medium`→M, `high`→H, `xhigh`→XH, `max`→MAX; a numeric budget as `8k`. */
120export const effortShort = (effort: string | number | undefined) =>
121  effort === undefined
122    ? "–"
123    : typeof effort === "number"
124      ? tokens(effort)
125      : (EFFORT[effort] ?? effort);
126
127/** `git rev-list --left-right --count @{u}...HEAD` → `{ behind, ahead }`. */
128export const parseAheadBehind = (out: string) => {
129  const [behind, ahead] = out.trim().split(/\s+/).map(Number);
130
131  return behind !== undefined &&
132    ahead !== undefined &&
133    Number.isFinite(behind) &&
134    Number.isFinite(ahead)
135    ? { behind, ahead }
136    : null;
137};
138
139const wire = (server: string) => server.replace(/[^a-zA-Z0-9_-]/g, "_");
140
141/** Sum of tool calls of one MCP server (server name as /mcp writes it). */
142export const serverCalls = (
143  calls: Readonly<Record<string, number>>,
144  server: string,
145) =>
146  Object.entries(calls)
147    .filter(([name]) => name.startsWith(`mcp__${wire(server)}__`))
148    .reduce((sum, [, n]) => sum + n, 0);
149
150/** An `origin` URL of Azure DevOps (`dev.azure.com`, `*.visualstudio.com`, also over SSH). */
151export const isAzureRemote = (url: string) =>
152  /(^|[@./])(dev\.azure\.com|visualstudio\.com)[:/]/i.test(url.trim());
153
154/**
155 * `az repos pr list --status active -o json` → the first pull request with its web page;
156 * an empty list or broken JSON → `null`.
157 */
158/**
159 * Web page of an Azure DevOps repository from its `origin` URL:
160 * `https://org@dev.azure.com/o/p/_git/r` or `git@ssh.dev.azure.com:v3/o/p/r` → `https://dev.azure.com/o/p/_git/r`.
161 */
162export const azureWebUrl = (remote: string) => {
163  const url = remote.trim().replace(/\.git$/, "");
164  const ssh = /[:/]v3\/([^/]+)\/([^/]+)\/([^/]+)$/.exec(url);
165  if (ssh) return `https://dev.azure.com/${ssh[1]}/${ssh[2]}/_git/${ssh[3]}`;
166
167  return url.replace(/^https:\/\/[^@/]+@/, "https://");
168};
169
170/**
171 * `az repos pr list --status active -o json` → the first pull request with its web page
172 * (the repository's `webUrl`, else derived from `origin`); an empty list or broken JSON → `null`.
173 */
174export const parseAzurePullRequest = (
175  out: string,
176  remote: string,
177): PullRequest | null => {
178  let list: unknown;
179  try {
180    list = JSON.parse(out);
181  } catch (error) {
182    if (!(error instanceof SyntaxError)) throw error;
183
184    return null;
185  }
186  const pr = (Array.isArray(list) ? list[0] : undefined) as
187    | { pullRequestId?: unknown; repository?: { webUrl?: unknown } }
188    | undefined;
189  const id = pr?.pullRequestId;
190  const webUrl = pr?.repository?.webUrl;
191  const web = typeof webUrl === "string" ? webUrl : azureWebUrl(remote);
192
193  return typeof id === "number"
194    ? { number: id, url: `${web}/pullrequest/${id}` }
195    : null;
196};
197
198/** `gh pr view --json number,url,state` → the open pull request; closed, merged or broken JSON → `null`. */
199export const parsePullRequest = (out: string): PullRequest | null => {
200  let pr: { number?: unknown; url?: unknown; state?: unknown };
201  try {
202    pr = JSON.parse(out) as typeof pr;
203  } catch (error) {
204    if (!(error instanceof SyntaxError)) throw error;
205
206    return null;
207  }
208
209  return pr.state === "OPEN" &&
210    typeof pr.number === "number" &&
211    typeof pr.url === "string"
212    ? { number: pr.number, url: pr.url }
213    : null;
214};
215
216/** `claude_max` + `default_claude_max_5x` → `Max 5x`; without an OAuth account `API`. */
217export const planLabel = (
218  organizationType?: string,
219  rateLimitTier?: string,
220) => {
221  if (!organizationType) return "API";
222  const base = organizationType.replace(/^claude_/, "");
223  const name = base.charAt(0).toUpperCase() + base.slice(1);
224  const multiplier = /(\d+x)$/.exec(rateLimitTier ?? "")?.[1];
225
226  return multiplier ? `${name} ${multiplier}` : name;
227};
228
229/**
230 * Replaces dots with `․` (U+2024), which looks the same but the terminal does
231 * not recognize the text as a file path, so clicking it opens nothing.
232 */
233export const noLink = (text: string) => text.replaceAll(".", "․");
234
235type Price = { input: number; output: number; read: number };
236
237/** USD per MTok (price list 2026-10); a longer prefix must come before a shorter one. */
238const PRICES: readonly (readonly [string, Price])[] = [
239  ["claude-fable-5-1", { input: 10, output: 50, read: 0.25 }],
240  ["claude-mythos-5-1", { input: 10, output: 50, read: 0.25 }],
241  ["claude-fable-5", { input: 10, output: 50, read: 1 }],
242  ["claude-opus-5-5", { input: 4, output: 20, read: 0.2 }],
243  ["claude-opus-5", { input: 5, output: 25, read: 0.5 }],
244  ["claude-opus-4", { input: 5, output: 25, read: 0.5 }],
245  ["claude-sonnet-5-5", { input: 2, output: 10, read: 0.2 }],
246  ["claude-sonnet-5", { input: 2, output: 10, read: 0.2 }],
247  ["claude-sonnet-4", { input: 3, output: 15, read: 0.3 }],
248  ["claude-haiku-5-5", { input: 0.1, output: 0.5, read: 0.01 }],
249  ["claude-haiku-4", { input: 1, output: 5, read: 0.1 }],
250];
251
252export type StepUsage = {
253  input_tokens: number;
254  output_tokens: number;
255  cache_read_input_tokens: number;
256  cache_creation_input_tokens: number;
257};
258
259/**
260 * Estimated cost of one request by token kind; `null` for a model not in the price list.
261 * A cache write costs 1.25× input at a 5 min TTL and 2× at a 1 h TTL.
262 */
263export const stepCostParts = (
264  model: string,
265  u: StepUsage,
266  ttlMinutes: number,
267): CostParts | null => {
268  const id = model.replace(/\[.*\]$/, "");
269  const price = PRICES.find(([prefix]) => id.startsWith(prefix))?.[1];
270  if (price === undefined) return null;
271  const write = price.input * (ttlMinutes >= 60 ? 2 : 1.25);
272
273  return {
274    input: (u.input_tokens * price.input) / 1_000_000,
275    output: (u.output_tokens * price.output) / 1_000_000,
276    read: (u.cache_read_input_tokens * price.read) / 1_000_000,
277    write: (u.cache_creation_input_tokens * write) / 1_000_000,
278  };
279};
280
281/** Estimated cost of one request in USD; `null` for a model not in the price list. */
282export const stepCost = (model: string, u: StepUsage, ttlMinutes: number) => {
283  const parts = stepCostParts(model, u, ttlMinutes);
284
285  return parts === null
286    ? null
287    : parts.input + parts.output + parts.read + parts.write;
288};
289
290/** Adds one request's breakdown to the sum; an unpriced request leaves the sum unchanged. */
291export const addCostParts = (
292  sum: CostParts,
293  parts: CostParts | null,
294): CostParts =>
295  parts === null
296    ? sum
297    : {
298        input: sum.input + parts.input,
299        output: sum.output + parts.output,
300        read: sum.read + parts.read,
301        write: sum.write + parts.write,
302      };
303
304/** Month key in `$.store` for one organization's spend total: `spend:2026-10:<org>`. */
305export const monthKey = (ms: number, orgId: string) => {
306  const d = new Date(ms);
307
308  return `spend:${d.getFullYear()}-${pad(d.getMonth() + 1)}:${orgId}`;
309};
310
311export type MissInput = {
312  isCompacted: boolean;
313  total: number;
314  prevTotal: number;
315  model: string;
316  prevModel: string;
317  isEffortChanged: boolean;
318  gapMs: number;
319  ttlMs: number;
320};
321
322/** `45 min`, from an hour `11.7 h`. */
323export const duration = (ms: number) => {
324  const minutes = ms / 60_000;
325
326  return minutes < 60
327    ? `${Math.round(minutes)} min`
328    : `${(minutes / 60).toFixed(1)} h`;
329};
330
331/** Most likely cause of a cache miss; it is a guess based on the order of signals. */
332export const missReason = (m: MissInput) =>
333  m.isCompacted
334    ? "compact"
335    : m.total < m.prevTotal * 0.5
336      ? "context shrank (/clear)"
337      : m.model !== m.prevModel
338        ? `model changed (${m.model})`
339        : m.isEffortChanged
340          ? "effort changed"
341          : m.gapMs > m.ttlMs
342            ? `idle ${duration(m.gapMs)} (TTL ${duration(m.ttlMs)}), cache expired`
343            : "unknown cause (system prompt / tools / MCP?)";
344
345export type McpTool = { serverName: string; isLoaded: boolean; tokens: number };
346
347/** Tools from the breakdown grouped by server; an active server has a tool in context. */
348export const groupMcp = (tools: readonly McpTool[]) => {
349  const servers = new Map<
350    string,
351    { server: string; tools: number; loaded: number; tokens: number }
352  >();
353  for (const t of tools) {
354    const cur = servers.get(t.serverName) ?? {
355      server: t.serverName,
356      tools: 0,
357      loaded: 0,
358      tokens: 0,
359    };
360    servers.set(t.serverName, {
361      ...cur,
362      tools: cur.tools + 1,
363      loaded: cur.loaded + (t.isLoaded ? 1 : 0),
364      tokens: cur.tokens + t.tokens,
365    });
366  }
367
368  return [...servers.values()];
369};
370
371export type AgentTotals = {
372  model: string;
373  /** All tokens burned: input, cache read, cache write and output. */
374  tokens: number;
375  usd: number | null;
376  /** Sum of the durations of the subagent's completed turns. */
377  durationMs: number;
378  /** The subagent finished: its turn ended and no further request has arrived yet. */
379  isDone: boolean;
380  /** Effort abbreviation of the last request; `–` for a model without effort. */
381  effort: string;
382};
383
384/** Empty subagent total that requests and turns are added to. */
385export const emptyAgent = (model = ""): AgentTotals => ({
386  model,
387  tokens: 0,
388  usd: 0,
389  durationMs: 0,
390  isDone: false,
391  effort: "–",
392});
393
394/**
395 * Subagent status for the list: icon `✅` and run time once finished, an asterisk and
396 * `running 1m20s` while running. The icon is always two cells (`✅` is wide, the
397 * asterisk gets a space) so the status text lines up. A missing or invalid
398 * value (record from an older version of the mod) gives an empty time, never `NaN`.
399 */
400export const agentStatus = (
401  startedAt: number | undefined,
402  usage: Partial<Pick<AgentTotals, "isDone" | "durationMs">> | undefined,
403  now: number,
404  frame: number,
405) => {
406  const isValid = (ms: number | undefined): ms is number =>
407    ms !== undefined && Number.isFinite(ms);
408  if (usage?.isDone === true) {
409    const text =
410      isValid(usage.durationMs) && usage.durationMs > 0
411        ? elapsed(usage.durationMs)
412        : "";
413
414    return { icon: "✅", text };
415  }
416  const text = isValid(startedAt)
417    ? `running ${elapsed(now - startedAt)}`
418    : "running";
419
420  return { icon: `${spinner(frame)} `, text };
421};
422
423/** Spinner asterisks as in Claude Code. */
424const SPIN = ["·", "✢", "✳", "✶", "✻", "✽", "✻", "✶", "✳", "✢"];
425
426/** Animated asterisk frame for the given frame counter. */
427export const spinner = (frame: number) => SPIN[frame % SPIN.length] ?? "·";
428
429/** Adds one subagent request; the cost stays `null` once a single request could not be priced. */
430export const addAgentStep = (
431  cur: AgentTotals | undefined,
432  model: string,
433  u: StepUsage,
434  cost: number | null,
435  effort = "–",
436): AgentTotals => {
437  const base = cur ?? emptyAgent(model);
438
439  return {
440    model,
441    tokens:
442      base.tokens +
443      u.input_tokens +
444      u.output_tokens +
445      u.cache_read_input_tokens +
446      u.cache_creation_input_tokens,
447    usd: base.usd === null || cost === null ? null : base.usd + cost,
448    durationMs: base.durationMs,
449    // A new request means the subagent (even a resumed one) is running again.
450    isDone: false,
451    effort,
452  };
453};
454
455/** `5s`, `3m12s`, od hodiny `1h05m`. */
456export const elapsed = (ms: number) => {
457  const s = Math.max(0, Math.round(ms / 1000));
458  if (s < 60) return `${s}s`;
459  const m = Math.floor(s / 60);
460  if (m < 60) return `${m}m${pad(s % 60)}s`;
461
462  return `${Math.floor(m / 60)}h${pad(m % 60)}m`;
463};
464
465/**
466 * Takes the plan label and billing from the contents of `~/.claude.json`; broken JSON → `null`.
467 * An Enterprise seat pays for every request, a personal subscription only for extra usage.
468 */
469export const accountFromClaudeJson = (
470  text: string,
471): ({ plan: string } & Billing) | null => {
472  type Account = {
473    organizationUuid?: string;
474    organizationType?: string;
475    organizationRateLimitTier?: string;
476  };
477  let account: Account | undefined;
478  try {
479    account = (JSON.parse(text) as { oauthAccount?: Account }).oauthAccount;
480  } catch (error) {
481    if (!(error instanceof SyntaxError)) throw error;
482
483    return null;
484  }
485
486  return {
487    plan: planLabel(
488      account?.organizationType,
489      account?.organizationRateLimitTier,
490    ),
491    orgId: account?.organizationUuid ?? "",
492    isUsageBased: account?.organizationType === "claude_enterprise",
493  };
494};
495
496/** `{ amount_minor: 1234, exponent: 2 }` or a plain number → USD; anything else → `null`. */
497const dollars = (value: unknown) => {
498  if (typeof value === "number") return value;
499  const m = value as { amount_minor?: unknown; exponent?: unknown } | null;
500  if (typeof m?.amount_minor !== "number") return null;
501
502  return (
503    m.amount_minor / 10 ** (typeof m.exponent === "number" ? m.exponent : 2)
504  );
505};
506
507/** The ISO currency code of a `{ amount_minor, currency }` amount; `null` without one. */
508const currencyOf = (value: unknown) => {
509  const c = (value as { currency?: unknown } | null)?.currency;
510
511  return typeof c === "string" && c !== "" ? c.toUpperCase() : null;
512};
513
514/** The `spend` block of `api/oauth/usage` (usage beyond the plan); missing or broken JSON → `null`. */
515export const parseAccountSpend = (text: string): AccountSpend | null => {
516  let spend: Record<string, unknown> | null | undefined;
517  try {
518    spend = (JSON.parse(text) as { spend?: Record<string, unknown> | null })
519      .spend;
520  } catch (error) {
521    if (!(error instanceof SyntaxError)) throw error;
522
523    return null;
524  }
525  if (spend === null || spend === undefined) return null;
526
527  return {
528    used: dollars(spend.used) ?? 0,
529    limit: dollars(spend.limit) ?? dollars(spend.cap),
530    balance: dollars(spend.balance),
531    isEnabled: spend.enabled === true,
532    currency:
533      currencyOf(spend.used) ??
534      currencyOf(spend.limit) ??
535      currencyOf(spend.balance),
536  };
537};
538
539/**
540 * What the money line shows. A personal subscription: only extra usage beyond the plan
541 * from the account (`null` until it is read). Enterprise: all spend this month against the
542 * budget, from the account once it reports it, otherwise the local estimate.
543 */
544export const moneyLine = (
545  billing: Billing,
546  account: AccountSpend | null,
547  localSpent: number,
548  budget: number,
549): Money =>
550  billing.isUsageBased
551    ? {
552        label: "month",
553        spent: account?.isEnabled === true ? account.used : localSpent,
554        limit: account?.limit ?? budget,
555        balance: account?.balance ?? null,
556        isOff: false,
557        // Without the account's own figures the amounts are the local estimate in dollars.
558        currency: account?.isEnabled === true ? account.currency : null,
559      }
560    : {
561        label: "extra",
562        spent: account?.used ?? null,
563        limit: account?.limit ?? null,
564        balance: account?.balance ?? null,
565        isOff: account !== null && !account.isEnabled,
566        currency: account?.currency ?? null,
567      };
568
569/** Thin bar `━━━───` split into a filled and an empty part so they can be colored separately. */
570export const thinBar = (percent: number, cells: number) => {
571  const filled = Math.max(
572    0,
573    Math.min(cells, Math.round((percent / 100) * cells)),
574  );
575
576  return { filled: "━".repeat(filled), empty: "─".repeat(cells - filled) };
577};
578
579/** `claude-opus-5-5` → `opus-5-5`. */
580export const shortModel = (model: string) => model.replace(/^claude-/, "");
581
582/**
583 * Whether keep-alive should send its request now: switched on, a cache to keep, not expired
584 * yet (a request would write the whole context again) and at most `leadMs` left of its TTL.
585 */
586export const isKeepAliveDue = (
587  isOn: boolean,
588  cacheAt: number,
589  ttlMs: number,
590  leadMs: number,
591  now: number,
592) => {
593  const left = cacheAt + ttlMs - now;
594
595  return isOn && cacheAt > 0 && left > 0 && left <= leadMs;
596};
597
598/** `name` and `color` from an agent definition's frontmatter; `null` without both. */
599export const parseAgentDefinition = (text: string) => {
600  const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1];
601  if (front === undefined) return null;
602  const field = (key: string) =>
603    new RegExp(`^${key}:\\s*["']?([^"'\\r\\n]+?)["']?\\s*$`, "m")
604      .exec(front)?.[1]
605      ?.trim();
606  const name = field("name");
607  const color = field("color");
608
609  return name && color ? { name, color } : null;
610};
611
612/** Agent colors are names Claude Code knows; the terminal knows purple as magenta. */
613const AGENT_COLORS: Readonly<Record<string, string>> = {
614  purple: "magenta",
615  pink: "magentaBright",
616  orange: "#ff8c00",
617};
618
619/** The terminal color an agent definition's `color` is drawn in. */
620export const agentTerminalColor = (color: string) =>
621  AGENT_COLORS[color.toLowerCase()] ?? color.toLowerCase();
622
623/** Active first, then the most called, then by name: the order of the MCP & skills pane. */
624export const sortByUse = <
625  T extends { name: string; calls: number; isOn: boolean },
626>(
627  items: readonly T[],
628): T[] =>
629  [...items].sort(
630    (a, b) =>
631      Number(b.isOn) - Number(a.isOn) ||
632      b.calls - a.calls ||
633      a.name.localeCompare(b.name),
634  );
635
636/** Switched-off MCP servers and skills, as a settings file holds them. */
637export type Disabled = { mcp: string[]; skills: string[] };
638
639/** Parses a settings file as an object; `null` when it is no JSON object. */
640const settingsObject = (text: string): Record<string, unknown> | null => {
641  try {
642    const value: unknown = JSON.parse(text);
643
644    return typeof value === "object" && value !== null && !Array.isArray(value)
645      ? (value as Record<string, unknown>)
646      : null;
647  } catch (error) {
648    if (!(error instanceof SyntaxError)) throw error;
649
650    return null;
651  }
652};
653
654/** MCP servers named in `deniedMcpServers` and skills set to `"off"` in `skillOverrides`. */
655export const disabledFromSettings = (text: string | null): Disabled => {
656  const s = text === null ? null : settingsObject(text);
657  const denied = Array.isArray(s?.deniedMcpServers) ? s.deniedMcpServers : [];
658  const overrides =
659    typeof s?.skillOverrides === "object" && s.skillOverrides !== null
660      ? (s.skillOverrides as Record<string, unknown>)
661      : {};
662
663  return {
664    mcp: denied
665      .map((d) => (d as { serverName?: unknown } | null)?.serverName)
666      .filter((n): n is string => typeof n === "string"),
667    skills: Object.entries(overrides)
668      .filter(([, v]) => v === "off")
669      .map(([k]) => k),
670  };
671};
672
673/**
674 * The settings text with one MCP server or skill switched on or off; every other key kept.
675 * `null` when the existing text is no JSON object: nothing is written over it then.
676 */
677export const toggleInSettings = (
678  text: string | null,
679  kind: "mcp" | "skill",
680  name: string,
681  isOn: boolean,
682): string | null => {
683  const s = text === null || text.trim() === "" ? {} : settingsObject(text);
684  if (s === null) return null;
685  const next: Record<string, unknown> = { ...s };
686  if (kind === "mcp") {
687    const denied = (
688      Array.isArray(s.deniedMcpServers) ? s.deniedMcpServers : []
689    ).filter(
690      (d) => (d as { serverName?: unknown } | null)?.serverName !== name,
691    );
692    const list = isOn ? denied : [...denied, { serverName: name }];
693    if (list.length === 0) delete next.deniedMcpServers;
694    else next.deniedMcpServers = list;
695  } else {
696    const overrides = {
697      ...(typeof s.skillOverrides === "object" && s.skillOverrides !== null
698        ? (s.skillOverrides as Record<string, unknown>)
699        : {}),
700    };
701    if (isOn) delete overrides[name];
702    else overrides[name] = "off";
703    if (Object.keys(overrides).length === 0) delete next.skillOverrides;
704    else next.skillOverrides = overrides;
705  }
706
707  return `${JSON.stringify(next, null, 2)}\n`;
708};
709
710/** Where an MCP server comes from, as far as its name tells: `plugin`, `claude.ai`, or nothing. */
711export const mcpTag = (server: string) =>
712  /^plugin[_:]/i.test(server)
713    ? "plugin"
714    : /^claude[_.]ai[_ ]/i.test(server)
715      ? "claude.ai"
716      : "";
717
718/** A skill's origin worth a tag: Claude Code's own (`system`) or a plugin's. */
719export const skillTag = (source: string) =>
720  source === "built-in" ? "system" : source === "plugin" ? "plugin" : "";
721
hooks/lists.tsx 228 lines
1import type { ElementTable } from "claude-code";
2
3import type {
4  CostParts,
5  SubagentInfo,
6  SubagentUsage,
7  Kind,
8  Tally,
9} from "../types";
10import {
11  agentStatus,
12  agentTerminalColor,
13  shortModel,
14  tokens,
15  usd,
16} from "./format";
17
18/** Longest subagent description including its type; longer ones are cut to "…". */
19const MAX_LABEL = 40;
20
21export type ListProps = {
22  open: Kind | null;
23  agents: readonly SubagentInfo[];
24  agentUsage: Readonly<Record<string, SubagentUsage>>;
25  sessionUsd: number;
26  /** Current time in milliseconds, for the run time of a subagent that has not finished yet. */
27  now: number;
28  /** Animation frame counter for the asterisk of a running subagent. */
29  frame: number;
30  /** Session tokens by kind (main thread and subagents). */
31  tally: Tally;
32  costParts: CostParts;
33  /** Width of the area the list is drawn in, for the separator lines. */
34  columns?: number;
35  /** Subagents whose request and response are shown. */
36  expanded?: readonly string[];
37  /** Expands or collapses one subagent. */
38  onToggleAgent?: (id: string) => void;
39  /** Agent type → the `color` of its definition. */
40  agentColors?: Readonly<Record<string, string>>;
41  /** Removes the finished subagents from the list. */
42  onClearAgents?: () => void;
43  /** Subagents spawned this session, the cleared ones included. */
44  spawnedAgents?: number;
45};
46
47/** Expanded list below the button row; `null` when nothing is open. */
48export function renderList(el: ElementTable, p: ListProps) {
49  const { Box, Button, Text } = el;
50
51  if (p.open === "session") {
52    // A subagent without a spawn record (e.g. started before the mod loaded) has only an id.
53    const ids = [
54      ...new Set([...p.agents.map((a) => a.id), ...Object.keys(p.agentUsage)]),
55    ];
56    const info = new Map(p.agents.map((a) => [a.id, a]));
57    const agentsUsd = ids.reduce(
58      (sum, id) => sum + (p.agentUsage[id]?.usd ?? 0),
59      0,
60    );
61    const agentsTokens = ids.reduce(
62      (sum, id) => sum + (p.agentUsage[id]?.tokens ?? 0),
63      0,
64    );
65
66    const totalTokens =
67      p.tally.input + p.tally.read + p.tally.write + p.tally.output;
68    const totalUsd =
69      p.costParts.input +
70      p.costParts.output +
71      p.costParts.read +
72      p.costParts.write;
73
74    // Subagent rows in columns: description, model, tokens, status and cost aligned.
75    const rows = ids.map((id) => {
76      const a = info.get(id);
77      const u = p.agentUsage[id];
78      const type = ` (${a?.type ?? "?"})`;
79      const rawDesc = a?.description ?? id;
80      const room = Math.max(1, MAX_LABEL - type.length);
81      const desc =
82        rawDesc.length > room ? `${rawDesc.slice(0, room - 1)}…` : rawDesc;
83
84      return {
85        id,
86        desc,
87        type,
88        model: u !== undefined && u.model !== "" ? shortModel(u.model) : "–",
89        effort:
90          u?.effort !== undefined && u.effort !== "–" ? ` (${u.effort})` : "",
91        tokens: tokens(u?.tokens ?? 0),
92        status: agentStatus(a?.startedAt, u, p.now, p.frame),
93        cost: u?.usd === null || u === undefined ? "?" : `≈${usd(u.usd)}`,
94      };
95    });
96    const widest = (values: readonly string[]) =>
97      Math.max(0, ...values.map((v) => v.length));
98    const labelWidth = widest(rows.map((r) => r.desc + r.type));
99    const modelWidth = widest(rows.map((r) => r.model + r.effort));
100    const tokensWidth = widest(rows.map((r) => r.tokens));
101    const statusWidth = widest(rows.map((r) => r.status.text));
102    const costWidth = widest(rows.map((r) => r.cost));
103    // The list sits 2 cells in from the left edge.
104    const rule = (glyph: string) =>
105      glyph.repeat(Math.max(1, (p.columns ?? 80) - 2));
106    const expanded = p.expanded ?? [];
107    // Inside the detail frame: the list's 2, the frame's indent of 4, its border 2 and padding 2.
108    const detailWidth = Math.max(1, (p.columns ?? 80) - 10);
109
110    return (
111      <Box flexDirection="column" paddingLeft={2}>
112        <Text>
113          🔥 {tokens(totalTokens)}
114          <Text dimColor>
115            {" "}
116            tokens · ≈{usd(totalUsd)} by price list · engine {usd(p.sessionUsd)}
117          </Text>
118        </Text>
119        <Text dimColor>{rule("─")}</Text>
120        <Box columnGap={2}>
121          <Text dimColor>Subagents</Text>
122          {/* Drops the finished subagents from the list; running ones stay. */}
123          {ids.length > 0 && p.onClearAgents !== undefined ? (
124            <Button key="k-clear-agents" plain onPress={p.onClearAgents}>
125              <Text dimColor underline>
126                clear
127              </Text>
128            </Button>
129          ) : null}
130        </Box>
131        {ids.length === 0 ? (
132          <Text dimColor>No subagents in this session yet.</Text>
133        ) : (
134          rows.map((r) => {
135            const isOpen = expanded.includes(r.id);
136            const a = info.get(r.id);
137            const agentColor =
138              a === undefined ? undefined : p.agentColors?.[a.type];
139
140            return (
141              <Box key={r.id} flexDirection="column">
142                <Button
143                  key={`a:${r.id}`}
144                  plain
145                  onPress={() => p.onToggleAgent?.(r.id)}
146                >
147                  <Text>
148                    {isOpen ? "▾" : "▸"}{" "}
149                    {/* The agent's own color from its definition; a blank keeps the columns. */}
150                    {agentColor === undefined ? (
151                      "  "
152                    ) : (
153                      <Text color={agentTerminalColor(agentColor)}>● </Text>
154                    )}
155                    <Text bold color="suggestion">
156                      {r.desc}
157                    </Text>
158                    <Text dimColor>
159                      {r.type.padEnd(labelWidth - r.desc.length)}
160                      {"  "}
161                    </Text>
162                    {r.model}
163                    <Text dimColor>
164                      {r.effort.padEnd(modelWidth - r.model.length)}
165                      {"  "}🔥{" "}
166                    </Text>
167                    {r.tokens.padStart(tokensWidth)}
168                    {"  "}
169                    {r.status.icon} {r.status.text.padEnd(statusWidth)}
170                    {"  "}
171                    {r.cost.padStart(costWidth)}
172                  </Text>
173                </Button>
174                {isOpen ? (
175                  // Its own dim frame, indented under the row: request and response stand apart
176                  // from the list of subagents, with an empty row before the next one.
177                  <Box flexDirection="column" paddingLeft={4} paddingBottom={1}>
178                    <Box
179                      flexDirection="column"
180                      borderStyle="round"
181                      borderColor="subtle"
182                      paddingX={1}
183                    >
184                      <Text bold color="suggestion">
185                        ▌ request
186                      </Text>
187                      <Box paddingLeft={2}>
188                        <Text>
189                          {a?.prompt ??
190                            "– (started before the mod recorded requests)"}
191                        </Text>
192                      </Box>
193                      {/* A dotted line between the two halves, as wide as the frame's inside. */}
194                      <Text dimColor>{"┄".repeat(detailWidth)}</Text>
195                      <Text bold color="success">
196                        ▌ response
197                      </Text>
198                      <Box paddingLeft={2}>
199                        <Text>
200                          {a?.result ??
201                            (p.agentUsage[r.id]?.isDone
202                              ? "–"
203                              : "still running…")}
204                        </Text>
205                      </Box>
206                    </Box>
207                  </Box>
208                ) : null}
209              </Box>
210            );
211          })
212        )}
213        {ids.length > 0 ? <Text dimColor>{rule("═")}</Text> : null}
214        {ids.length > 0 ? (
215          <Text dimColor>
216            Σ subagents {p.spawnedAgents ?? ids.length} spawned · 🔥{" "}
217            {tokens(agentsTokens)} of {tokens(totalTokens)} tokens · ≈
218            {usd(agentsUsd)} of {usd(p.sessionUsd)} this session (estimate from
219            model prices)
220          </Text>
221        ) : null}
222      </Box>
223    );
224  }
225
226  return null;
227}
228
hooks/context.ts 238 lines
1import type { MemFile } from "../types";
2
3/** Where a memory file comes from, in the order Claude Code loads them; a later one overrides. */
4const SCOPE_ORDER = ["Managed", "User", "Project", "Local", "AutoMem"];
5
6/** Settings sources in the order they load; a later source overrides an earlier one. */
7export const SETTINGS_ORDER = [
8  "user",
9  "project",
10  "local",
11  "flag",
12  "policy",
13] as const;
14export type SettingsScope = (typeof SETTINGS_ORDER)[number];
15
16/** One configured hook command, from one settings source. */
17export type HookRow = {
18  scope: SettingsScope;
19  event: string;
20  /** Tool pattern the hook reacts to; empty for every call or an event without one. */
21  matcher: string;
22  command: string;
23};
24
25/** A rules file lives in a `.claude/rules` folder. */
26export const isRule = (path: string) =>
27  /[\\/]\.claude[\\/]rules[\\/]/i.test(path);
28
29const depth = (path: string) => path.split(/[\\/]/).length;
30
31/**
32 * Memory files in load order: by scope (managed, user, project, local, auto memory), then
33 * from the root down (a parent folder's file before a nested one), then by path.
34 */
35export const sortByLoadOrder = (files: readonly MemFile[]) =>
36  [...files].sort((a, b) => {
37    const rank = (f: MemFile) => {
38      const i = SCOPE_ORDER.indexOf(f.type);
39
40      return i === -1 ? SCOPE_ORDER.length : i;
41    };
42
43    return (
44      rank(a) - rank(b) ||
45      depth(a.path) - depth(b.path) ||
46      a.path.localeCompare(b.path)
47    );
48  });
49
50/** The hook commands of one settings source's `hooks` block; anything malformed is skipped. */
51export const hookRows = (scope: SettingsScope, hooks: unknown): HookRow[] => {
52  if (typeof hooks !== "object" || hooks === null) return [];
53  const rows: HookRow[] = [];
54  for (const [event, groups] of Object.entries(hooks)) {
55    if (!Array.isArray(groups)) continue;
56    for (const group of groups) {
57      const g = group as { matcher?: unknown; hooks?: unknown } | null;
58      const matcher = typeof g?.matcher === "string" ? g.matcher : "";
59      if (!Array.isArray(g?.hooks)) continue;
60      for (const hook of g.hooks) {
61        const h = hook as { command?: unknown; type?: unknown } | null;
62        const command =
63          typeof h?.command === "string"
64            ? h.command
65            : typeof h?.type === "string"
66              ? `(${h.type})`
67              : "";
68        if (command !== "") rows.push({ scope, event, matcher, command });
69      }
70    }
71  }
72
73  return rows;
74};
75
76/** `just now`, `5m ago`, `3h ago`, `2d ago` for a modification time; `–` when unknown. */
77export const ago = (mtimeMs: number | undefined, now: number) => {
78  if (mtimeMs === undefined || mtimeMs <= 0) return "–";
79  const minutes = Math.max(0, Math.floor((now - mtimeMs) / 60_000));
80  if (minutes < 1) return "just now";
81  if (minutes < 60) return `${minutes}m ago`;
82  const hours = Math.floor(minutes / 60);
83
84  return hours < 48 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago`;
85};
86
87/** Cuts a text to `width` cells from the left, keeping its end: `…ude/rules/api.md`. */
88export const cutLeft = (text: string, width: number) =>
89  text.length <= width ? text : `…${text.slice(text.length - width + 1)}`;
90
91/** Cuts a text to `width` cells from the right: `node hooks/guard…`. */
92export const cutRight = (text: string, width: number) =>
93  text.length <= width ? text : `${text.slice(0, width - 1)}…`;
94
95/** One installed plugin with a hooks module (a mod), as the settings enable it. */
96export type ModRow = {
97  /** `name@marketplace`. */
98  id: string;
99  version: string;
100  /** The last settings source that switches it on or off: the one that wins. */
101  scope: SettingsScope | "";
102  isOn: boolean;
103  /** The folder the plugin is installed in; empty when unknown. */
104  path: string;
105};
106
107/**
108 * Installed plugins from `installed_plugins.json` with the settings that switch them, in
109 * load order: the last source naming a plugin decides whether it is on.
110 */
111export const pluginRows = (
112  installedJson: string | null,
113  enabledBySource: readonly (readonly [SettingsScope, unknown])[],
114): ModRow[] => {
115  let installed: Record<string, unknown> = {};
116  try {
117    const parsed = JSON.parse(installedJson ?? "{}") as { plugins?: unknown };
118    if (typeof parsed.plugins === "object" && parsed.plugins !== null) {
119      installed = parsed.plugins as Record<string, unknown>;
120    }
121  } catch (error) {
122    if (!(error instanceof SyntaxError)) throw error;
123  }
124  const state = new Map<string, { scope: SettingsScope; isOn: boolean }>();
125  for (const [scope, enabled] of enabledBySource) {
126    if (typeof enabled !== "object" || enabled === null) continue;
127    for (const [id, value] of Object.entries(enabled)) {
128      state.set(id, { scope, isOn: value === true });
129    }
130  }
131  const ids = [...new Set([...Object.keys(installed), ...state.keys()])];
132  const order = (id: string) => {
133    const s = state.get(id)?.scope;
134
135    return s === undefined ? SETTINGS_ORDER.length : SETTINGS_ORDER.indexOf(s);
136  };
137
138  return ids
139    .map((id): ModRow => {
140      const entry = (Array.isArray(installed[id]) ? installed[id] : [])[0] as
141        | { version?: unknown; installPath?: unknown }
142        | undefined;
143
144      return {
145        id,
146        version: typeof entry?.version === "string" ? entry.version : "",
147        scope: state.get(id)?.scope ?? "",
148        isOn: state.get(id)?.isOn ?? false,
149        path: typeof entry?.installPath === "string" ? entry.installPath : "",
150      };
151    })
152    .sort((a, b) => order(a.id) - order(b.id) || a.id.localeCompare(b.id));
153};
154
155/** A path compared the Windows way: forward slashes, no case. */
156export const samePath = (path: string) =>
157  path.replaceAll("\\", "/").toLowerCase();
158
159/**
160 * The files a memory file imports with `@path` lines (outside code fences), resolved: relative
161 * to the importing file's folder, `~/` to the home folder, an absolute path as it is.
162 */
163export const importsOf = (text: string, filePath: string, home: string) => {
164  const dir = filePath.replaceAll("\\", "/").replace(/\/[^/]*$/, "");
165  const found: string[] = [];
166  let isCode = false;
167  for (const line of text.split(/\r?\n/)) {
168    if (/^\s*```/.test(line)) isCode = !isCode;
169    if (isCode) continue;
170    const refs = line.matchAll(
171      /(?:^|\s)@((?:~\/|\.{1,2}\/|[A-Za-z]:[\\/]|\/)?[\w.\-/\\]+\.\w+)/g,
172    );
173    for (const m of refs) {
174      const ref = (m[1] ?? "").replaceAll("\\", "/");
175      const resolved = ref.startsWith("~/")
176        ? `${home.replaceAll("\\", "/")}/${ref.slice(2)}`
177        : /^([A-Za-z]:)?\//.test(ref)
178          ? ref
179          : `${dir}/${ref}`;
180      // Collapse `./` and `../` so the path matches the one Claude Code reports.
181      const parts: string[] = [];
182      for (const part of resolved.split("/")) {
183        if (part === "." || part === "") {
184          if (parts.length === 0) parts.push(part);
185          continue;
186        }
187        if (part === "..") parts.pop();
188        else parts.push(part);
189      }
190      found.push(parts.join("/"));
191    }
192  }
193
194  return found;
195};
196
197/** A file in the order it is read, with who imported it (`@path`) and how deep. */
198export type NestedFile<T> = { file: T; depth: number; importedBy: string };
199
200/**
201 * Puts each imported file right under the file that imports it, as Claude Code inlines it;
202 * the rest stay in load order. A file imported by several keeps its first place.
203 */
204export const nestImports = <T extends { path: string }>(
205  files: readonly T[],
206  importsByPath: Readonly<Record<string, readonly string[]>>,
207): NestedFile<T>[] => {
208  const byKey = new Map(files.map((f) => [samePath(f.path), f]));
209  const importedKeys = new Set(
210    Object.values(importsByPath)
211      .flat()
212      .map(samePath)
213      .filter((k) => byKey.has(k)),
214  );
215  const out: NestedFile<T>[] = [];
216  const placed = new Set<string>();
217  const place = (f: T, depth: number, importedBy: string) => {
218    const key = samePath(f.path);
219    if (placed.has(key)) return;
220    placed.add(key);
221    out.push({ file: f, depth, importedBy });
222    const imports =
223      Object.entries(importsByPath).find(([p]) => samePath(p) === key)?.[1] ??
224      [];
225    for (const ref of imports) {
226      const child = byKey.get(samePath(ref));
227      if (child !== undefined) place(child, depth + 1, f.path);
228    }
229  };
230  for (const f of files) {
231    if (!importedKeys.has(samePath(f.path))) place(f, 0, "");
232  }
233  // Imported files whose importer is not in context still show, at the top level.
234  for (const f of files) place(f, 0, "");
235
236  return out;
237};
238
hooks/memory.tsx 342 lines
1import type { ElementTable } from "claude-code";
2
3import type { MemFile } from "../types";
4import type { HookRow, ModRow, SettingsScope } from "./context";
5import {
6  ago,
7  cutLeft,
8  cutRight,
9  isRule,
10  nestImports,
11  sortByLoadOrder,
12} from "./context";
13import type { NestedFile } from "./context";
14import { baseName, noLink, shortPath, tokens } from "./format";
15
16/** Line count and modification time of a memory file, read when the context refreshes. */
17export type FileDetail = {
18  lines: number;
19  mtimeMs: number;
20  /** Files it imports with `@path`, resolved. */
21  imports: string[];
22};
23
24export type MemoryProps = {
25  /** Width of the pane body. */
26  columns: number;
27  cwd: string;
28  now: number;
29  /** Every memory file in context: CLAUDE.md, AGENTS.md, rules, auto memory. */
30  files: readonly MemFile[];
31  details: Readonly<Record<string, FileDetail>>;
32  hooks: readonly HookRow[];
33  /** Installed plugins that bring a hooks module, in load order. */
34  mods: readonly ModRow[];
35  /** The settings file of each source, for the hooks' `↗ open`; absent when unknown. */
36  settingsPaths: Readonly<Partial<Record<SettingsScope, string>>>;
37  /** Files whose preview is open. */
38  expanded: readonly string[];
39  /** File text by path, read when its preview opened. */
40  previews: Readonly<Record<string, string>>;
41  onToggle: (path: string) => void;
42  /** Opens the folder a file is in. */
43  onOpenFolder: (path: string) => void;
44};
45
46/**
47 * A file's text as markdown: a leading `---` frontmatter block becomes a yaml fence,
48 * and each table (a run of lines starting with `|`) outside a fence becomes a plain
49 * fence, so it shows as written instead of being drawn as a table.
50 */
51export const asMarkdown = (text: string) =>
52  rawTables(
53    text.replace(/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/, "```yaml\n$1\n```\n"),
54  );
55
56function rawTables(text: string) {
57  const out: string[] = [];
58  let fence: string | undefined;
59  let table = false;
60  for (const line of text.split(/\r?\n/)) {
61    const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
62    const isRow = fence === undefined && /^\s*\|/.test(line);
63    if (table && !isRow) {
64      out.push("```");
65      table = false;
66    }
67    if (marker !== undefined) {
68      if (fence === undefined) fence = marker;
69      else if (marker[0] === fence[0] && marker.length >= fence.length)
70        fence = undefined;
71    } else if (isRow && !table) {
72      out.push("```");
73      table = true;
74    }
75    out.push(line);
76  }
77  if (table) out.push("```");
78  return out.join("\n");
79}
80
81/** Fixed column widths; the first column takes the rest of the row. */
82const SCOPE = 9;
83const LINES = 7;
84const TOKENS = 8;
85const MODIFIED = 10;
86const OPEN = 7;
87
88/** The settings pane: CLAUDE.md, RULES, HOOKS and MODS tables, each in load order (a later row overrides). */
89export function renderMemory(el: ElementTable, p: MemoryProps) {
90  const { Box, Button, Markdown, Text } = el;
91  const width = Math.max(40, p.columns - 2);
92  const nameWidth = width - SCOPE - LINES - TOKENS - MODIFIED - OPEN;
93  const ordered = sortByLoadOrder(p.files);
94  const importsByPath = Object.fromEntries(
95    Object.entries(p.details).map(([path, d]) => [path, d.imports]),
96  );
97  const isAutoMemory = (f: MemFile) => f.type === "AutoMem";
98  const memory = ordered.filter((f) => !isRule(f.path) && !isAutoMemory(f));
99  const autoMemory = ordered.filter((f) => !isRule(f.path) && isAutoMemory(f));
100  const rules = ordered.filter((f) => isRule(f.path));
101
102  const cell = (text: string, cells: number, isRight = false) =>
103    isRight ? text.padStart(cells - 1).padEnd(cells) : text.padEnd(cells);
104
105  const heading = (title: string, count: number) => (
106    <Text bold>
107      {title}
108      <Text dimColor> {count}</Text>
109    </Text>
110  );
111
112  const fileHeader = (
113    <Text dimColor>
114      {cell("  path", nameWidth)}
115      {cell("scope", SCOPE)}
116      {cell("lines", LINES, true)}
117      {cell("tokens", TOKENS, true)}
118      {cell("modified", MODIFIED, true)}
119    </Text>
120  );
121
122  const fileRow = (n: NestedFile<MemFile>) => {
123    const f = n.file;
124    // Pulled in with `@path`: indented under the file that imports it, in another colour.
125    const indent = n.depth === 0 ? "" : `${"  ".repeat(n.depth - 1)}↳ `;
126    // The path comes first; the importer is named only where it still fits.
127    const room = nameWidth - 2 - indent.length;
128    const name = cutLeft(shortPath(f.path, p.cwd), Math.max(4, room - 1));
129    const fullVia = n.importedBy === "" ? "" : ` ← ${baseName(n.importedBy)}`;
130    const via = name.length + fullVia.length < room ? fullVia : "";
131    const isOpen = p.expanded.includes(f.path);
132    const detail = p.details[f.path];
133    const text = p.previews[f.path];
134
135    return (
136      <Box key={f.path} flexDirection="column">
137        <Box>
138          {/* noLink: the terminal would turn a file name into a link that opens the file. */}
139          <Button key={`m:${f.path}`} plain onPress={() => p.onToggle(f.path)}>
140            <Text>
141              {isOpen ? "▾ " : "▸ "}
142              <Text dimColor>{indent}</Text>
143              <Text
144                bold={n.depth === 0}
145                color={n.depth === 0 ? "suggestion" : "claude"}
146              >
147                {noLink(name)}
148              </Text>
149              <Text dimColor>
150                {noLink(via).padEnd(Math.max(0, room - name.length))}
151              </Text>
152              <Text dimColor>{cell(f.type, SCOPE)}</Text>
153              {cell(
154                detail === undefined ? "–" : String(detail.lines),
155                LINES,
156                true,
157              )}
158              {cell(tokens(f.tokens), TOKENS, true)}
159              <Text dimColor>
160                {cell(ago(detail?.mtimeMs, p.now), MODIFIED, true)}
161              </Text>
162            </Text>
163          </Button>
164          <Button
165            key={`o:${f.path}`}
166            plain
167            onPress={() => p.onOpenFolder(f.path)}
168          >
169            <Text dimColor underline>
170              ↗ open
171            </Text>
172          </Button>
173        </Box>
174        {isOpen ? (
175          // The text in its own dim frame, indented under the row, with an empty row after.
176          <Box flexDirection="column" paddingLeft={4} paddingBottom={1}>
177            <Box
178              flexDirection="column"
179              borderStyle="round"
180              borderColor="subtle"
181              paddingX={1}
182              width={Math.max(20, width - 4)}
183            >
184              {text === undefined ? (
185                <Text dimColor>reading…</Text>
186              ) : (
187                // The whole file, drawn as markdown: headings, emphasis, links, lists, code.
188                <Markdown text={asMarkdown(text)} />
189              )}
190            </Box>
191          </Box>
192        ) : null}
193      </Box>
194    );
195  };
196
197  const files = (title: string, list: readonly MemFile[], empty: string) => (
198    <Box flexDirection="column">
199      {heading(title, list.length)}
200      {list.length === 0 ? (
201        <Text dimColor>{empty}</Text>
202      ) : (
203        <Box flexDirection="column">
204          {fileHeader}
205          {nestImports(list, importsByPath).map(fileRow)}
206        </Box>
207      )}
208    </Box>
209  );
210
211  // Hooks: event, matcher, command, scope; the command takes what the others leave.
212  const EVENT = 18;
213  const MATCHER = 14;
214  const commandWidth = width - EVENT - MATCHER - SCOPE - OPEN;
215  const hookTable = (
216    <Box flexDirection="column">
217      {heading("HOOKS", p.hooks.length)}
218      {p.hooks.length === 0 ? (
219        <Text dimColor>No hook in the settings.</Text>
220      ) : (
221        <Box flexDirection="column">
222          <Text dimColor>
223            {cell("  event", EVENT)}
224            {cell("matcher", MATCHER)}
225            {cell("command", commandWidth)}
226            {cell("scope", SCOPE)}
227          </Text>
228          {/* Not `h`: that is the JSX factory. */}
229          {p.hooks.map((hook, i) => {
230            const file = p.settingsPaths[hook.scope];
231
232            return (
233              <Box key={`h:${i}`}>
234                <Text>
235                  {"  "}
236                  <Text bold>
237                    {cell(cutRight(hook.event, EVENT - 3), EVENT - 2)}
238                  </Text>
239                  <Text dimColor>
240                    {cell(
241                      cutRight(
242                        hook.matcher === "" ? "*" : hook.matcher,
243                        MATCHER - 1,
244                      ),
245                      MATCHER,
246                    )}
247                  </Text>
248                  {cell(cutRight(hook.command, commandWidth - 1), commandWidth)}
249                  <Text dimColor>{cell(hook.scope, SCOPE)}</Text>
250                </Text>
251                {file === undefined ? null : (
252                  <Button
253                    key={`ho:${i}`}
254                    plain
255                    onPress={() => p.onOpenFolder(file)}
256                  >
257                    <Text dimColor underline>
258                      ↗ open
259                    </Text>
260                  </Button>
261                )}
262              </Box>
263            );
264          })}
265        </Box>
266      )}
267    </Box>
268  );
269
270  // Mods: plugin, version, the source that switches it, and whether it is on.
271  const VERSION = 10;
272  const STATE = 6;
273  const modWidth = width - VERSION - SCOPE - STATE - OPEN;
274  const modTable = (
275    <Box flexDirection="column">
276      {heading("MODS", p.mods.length)}
277      {p.mods.length === 0 ? (
278        <Text dimColor>No mod installed.</Text>
279      ) : (
280        <Box flexDirection="column">
281          <Text dimColor>
282            {cell("  plugin", modWidth)}
283            {cell("version", VERSION)}
284            {cell("scope", SCOPE)}
285            {cell("state", STATE)}
286          </Text>
287          {p.mods.map((m) => (
288            <Box key={`mod:${m.id}`}>
289              <Text>
290                {"  "}
291                <Text bold={m.isOn} dimColor={!m.isOn}>
292                  {cell(cutRight(m.id, modWidth - 3), modWidth - 2)}
293                </Text>
294                <Text dimColor>
295                  {cell(m.version === "" ? "–" : m.version, VERSION)}
296                </Text>
297                <Text dimColor>
298                  {cell(m.scope === "" ? "–" : m.scope, SCOPE)}
299                </Text>
300                <Text color={m.isOn ? "success" : undefined} dimColor={!m.isOn}>
301                  {cell(m.isOn ? "on" : "off", STATE)}
302                </Text>
303              </Text>
304              {m.path === "" ? null : (
305                <Button
306                  key={`mo:${m.id}`}
307                  plain
308                  onPress={() => p.onOpenFolder(`${m.path}/.`)}
309                >
310                  <Text dimColor underline>
311                    ↗ open
312                  </Text>
313                </Button>
314              )}
315            </Box>
316          ))}
317        </Box>
318      )}
319    </Box>
320  );
321
322  return (
323    <Box flexDirection="column" paddingX={1}>
324      <Text dimColor>In load order: a later row overrides an earlier one.</Text>
325      <Text> </Text>
326      {files(
327        noLink("CLAUDE.md"),
328        memory,
329        `No ${noLink("CLAUDE.md")} or ${noLink("AGENTS.md")} in context.`,
330      )}
331      <Text dimColor>{"─".repeat(width)}</Text>
332      {files("RULES", rules, "No rules file in context.")}
333      <Text dimColor>{"─".repeat(width)}</Text>
334      {files("MEMORY", autoMemory, "No auto memory in context.")}
335      <Text dimColor>{"─".repeat(width)}</Text>
336      {hookTable}
337      <Text dimColor>{"─".repeat(width)}</Text>
338      {modTable}
339    </Box>
340  );
341}
342
hooks/tools.tsx 163 lines
1import type { ElementTable } from "claude-code";
2
3import type { McpServer, SkillInfo } from "../types";
4import {
5  green,
6  mcpTag,
7  serverCalls,
8  skillTag,
9  sortByUse,
10  tokens,
11  yellow,
12} from "./format";
13
14export type ToolsProps = {
15  /** Width of the pane body, for the right-aligned switches and the separator. */
16  columns: number;
17  mcp: readonly McpServer[];
18  /** Calls per tool name (`mcp__server__tool`). */
19  calls: Readonly<Record<string, number>>;
20  skills: readonly SkillInfo[];
21  /** Calls per skill name. */
22  skillCalls: Readonly<Record<string, number>>;
23  /** MCP servers switched off: listed after the active ones, drawn OFF. */
24  disabledMcp: readonly string[];
25  /** Skills switched off: listed after the active ones, drawn OFF. */
26  disabledSkills: readonly string[];
27  onToggleMcp?: (server: string) => void;
28  onToggleSkill?: (skill: string) => void;
29};
30
31/** One row: name and details on the left, the ON/OFF switch at the right edge. */
32type Row = {
33  key: string;
34  name: string;
35  detail: string;
36  isOn: boolean;
37  /** `system`, `plugin`, `claude.ai`; empty for the person's own. */
38  tag: string;
39  onToggle?: () => void;
40};
41
42/** The MCP & skills pane: MCP servers, a separator, then skills; each list active first, most called first. */
43export function renderTools(el: ElementTable, p: ToolsProps) {
44  const { Box, Button, Text } = el;
45  // The rows sit 1 cell in from each side of the pane body.
46  const width = Math.max(20, p.columns - 2);
47
48  const mcpRows: Row[] = sortByUse([
49    ...p.mcp.map((s) => ({
50      name: s.server,
51      calls: serverCalls(p.calls, s.server),
52      isOn: !p.disabledMcp.includes(s.server),
53      detail: `${s.loaded}/${s.tools} tools · ${tokens(s.tokens)} tok`,
54      tag: mcpTag(s.server),
55    })),
56    // A server switched off is no longer in the context: it is only named.
57    ...p.disabledMcp
58      .filter((name) => !p.mcp.some((s) => s.server === name))
59      .map((name) => ({
60        name,
61        calls: 0,
62        isOn: false,
63        detail: "",
64        tag: mcpTag(name),
65      })),
66  ]).map((r) => ({
67    key: `mcp:${r.name}`,
68    name: r.name,
69    detail: `${r.calls} calls${r.detail === "" ? "" : ` · ${r.detail}`}`,
70    isOn: r.isOn,
71    tag: r.tag,
72    onToggle:
73      p.onToggleMcp === undefined ? undefined : () => p.onToggleMcp?.(r.name),
74  }));
75
76  const skillRows: Row[] = sortByUse([
77    ...p.skills.map((s) => ({
78      name: s.name,
79      calls: p.skillCalls[s.name] ?? 0,
80      isOn: !p.disabledSkills.includes(s.name),
81      detail: `${s.source} · ${tokens(s.tokens)} tok`,
82      tag: skillTag(s.source),
83      // skillOverrides does not apply to a plugin's skills: no switch for them.
84      isSwitchable: s.source !== "plugin",
85    })),
86    ...p.disabledSkills
87      .filter((name) => !p.skills.some((s) => s.name === name))
88      .map((name) => ({
89        name,
90        calls: 0,
91        isOn: false,
92        detail: "",
93        tag: "",
94        isSwitchable: true,
95      })),
96  ]).map((r) => ({
97    key: `skill:${r.name}`,
98    name: r.name,
99    detail: `${r.calls} calls${r.detail === "" ? "" : ` · ${r.detail}`}`,
100    isOn: r.isOn,
101    tag: r.tag,
102    onToggle:
103      p.onToggleSkill === undefined || !r.isSwitchable
104        ? undefined
105        : () => p.onToggleSkill?.(r.name),
106  }));
107
108  const row = (r: Row) => (
109    <Box key={r.key} justifyContent="space-between" width={width}>
110      <Text>
111        <Text bold={r.isOn} dimColor={!r.isOn}>
112          {r.name}
113        </Text>
114        {r.tag === "" ? null : (
115          <Text
116            color={r.tag === "system" ? yellow : undefined}
117            dimColor={r.tag !== "system"}
118          >
119            {" "}
120            [{r.tag}]
121          </Text>
122        )}
123        <Text dimColor> {r.detail}</Text>
124      </Text>
125      {r.onToggle === undefined ? (
126        <Text dimColor={!r.isOn} color={r.isOn ? green : undefined}>
127          {r.isOn ? " ON" : "OFF"}
128        </Text>
129      ) : (
130        <Button key={`t:${r.key}`} plain onPress={r.onToggle}>
131          <Text dimColor={!r.isOn} color={r.isOn ? green : undefined}>
132            {r.isOn ? " ON" : "OFF"}
133          </Text>
134        </Button>
135      )}
136    </Box>
137  );
138
139  return (
140    <Box flexDirection="column" paddingX={1}>
141      {/* Every switch changes what the model is told it has, so the prompt prefix changes. */}
142      <Text color={yellow}>
143        ⚠ Any switch changes the tools and skills listed to the model: the next
144        request writes the prompt cache again.
145      </Text>
146      <Text> </Text>
147      <Text dimColor>MCP servers {p.mcp.length}</Text>
148      {mcpRows.length === 0 ? (
149        <Text dimColor>No MCP server.</Text>
150      ) : (
151        mcpRows.map(row)
152      )}
153      <Text dimColor>{"─".repeat(width)}</Text>
154      <Text dimColor>Skills {p.skills.length}</Text>
155      {skillRows.length === 0 ? (
156        <Text dimColor>No skill.</Text>
157      ) : (
158        skillRows.map(row)
159      )}
160    </Box>
161  );
162}
163
hooks/robot.tsx 48 lines
1import type { ElementTable } from "claude-code";
2
3import { spinner } from "./format";
4
5/** Mini Clawd from the Claude Code welcome screen: head and body, two rows of 5 cells. */
6const IDLE = ["▐▛█▜▌", "▝▜█▛▘"];
7const BLINK = ["▐███▌", "▝▜█▛▘"];
8/** While working it waves its arms and darts its eyes; the fourth frame blinks. */
9const WORKING = [
10  ["▐▛█▜▌", "▝▜█▛▘"],
11  ["▐▛█▜▌", "▗▟█▙▖"],
12  ["▐▜█▛▌", "▝▜█▛▘"],
13  ["▐███▌", "▗▟█▙▖"],
14];
15
16export type RobotProps = {
17  isWorking: boolean;
18  /** Frame counter; while working it grows four times per second. */
19  frame: number;
20  /** Current time in milliseconds; when idle the robot blinks once every few seconds. */
21  now: number;
22};
23
24/** Animated mini robot next to the limits: works while a turn is running, otherwise stands still and blinks now and then. */
25export function renderRobot(el: ElementTable, p: RobotProps) {
26  const { Box, Text } = el;
27  const isBlink = Math.floor(p.now / 1000) % 6 === 0;
28  const rows = p.isWorking
29    ? (WORKING[p.frame % WORKING.length] ?? IDLE)
30    : isBlink
31      ? BLINK
32      : IDLE;
33  const spin = p.isWorking ? spinner(p.frame) : " ";
34  // In color only while working; at rest it stays in the background.
35  const color = p.isWorking ? "claude" : undefined;
36
37  return (
38    <Box flexDirection="column">
39      <Text color={color} dimColor={!p.isWorking}>
40        {rows[0]}
41      </Text>
42      <Text color={color} dimColor={!p.isWorking}>
43        {rows[1]} {spin}
44      </Text>
45    </Box>
46  );
47}
48
types/index.d.ts 193 lines
1export type Snap = {
2  ctxTokens: number;
3  ctxWindow: number;
4  ctxPercent: number;
5  usd: number;
6  limits: { kind: string; percentUsed: number; resetsAt?: string }[];
7};
8
9export type Tally = {
10  input: number;
11  output: number;
12  read: number;
13  write: number;
14  lastHit: number | null;
15  turns: number;
16};
17
18export type Miss = { at: number; reason: string } | null;
19
20/** An open pull request of the current branch as `gh pr view` reports it. */
21export type PullRequest = { number: number; url: string };
22
23/**
24 * `sync` is the state against the upstream branch as of the last fetch; `null` without an upstream.
25 * `pr` is the branch's open pull request; `null` without one, outside GitHub or without `gh`.
26 */
27export type Repo = {
28  cwd: string;
29  branch: string;
30  sync: { ahead: number; behind: number } | null;
31  pr?: PullRequest | null;
32};
33
34export type MemFile = { path: string; type: string; tokens: number };
35
36export type Kind = "claude" | "mcp" | "session";
37
38/** A skill the session lists, from the context breakdown. */
39export type SkillInfo = {
40  name: string;
41  /** Where it comes from (`userSettings`, `plugin`, `built-in`, …). */
42  source: string;
43  tokens: number;
44};
45
46export type McpServer = {
47  server: string;
48  tools: number;
49  loaded: number;
50  tokens: number;
51};
52
53/** Subagent as reported by `agent.spawn`; `startedAt` is the start time (ms). */
54export type SubagentInfo = {
55  id: string;
56  description: string;
57  type: string;
58  startedAt: number;
59  /** The task it was given; absent in a record from an older version of the mod. */
60  prompt?: string;
61  /** Its final answer, once it finished. */
62  result?: string;
63};
64
65/** Usage of one subagent: tokens and a price estimate from the model price list. */
66export type SubagentUsage = {
67  model: string;
68  /** All tokens burned. */
69  tokens: number;
70  /** `null` when the model is not in the price list. */
71  usd: number | null;
72  /** Sum of the durations of completed turns. */
73  durationMs: number;
74  /** The subagent finished. */
75  isDone: boolean;
76  /** Effort abbreviation of the last request (`L`, `M`, `H`…); `–` for a model without effort. */
77  effort: string;
78};
79
80/** Cost in USD split by token kind. */
81export type CostParts = {
82  input: number;
83  output: number;
84  read: number;
85  write: number;
86};
87
88/** Usage beyond the plan as `api/oauth/usage` reports it under `spend`, in USD. */
89export type AccountSpend = {
90  used: number;
91  /** Monthly cap; `null` without one. */
92  limit: number | null;
93  /** Prepaid credits left; `null` when the account reports none. */
94  balance: number | null;
95  /** Extra usage is switched on. */
96  isEnabled: boolean;
97  /** ISO code the account bills in (`USD`, `EUR`); `null` when it says none. */
98  currency: string | null;
99};
100
101/** The signed-in organization; an Enterprise seat pays for every request. */
102export type Billing = { orgId: string; isUsageBased: boolean };
103
104/** The money line: `extra` beyond a personal plan, or all of `month` on Enterprise. */
105/** Keeps the prompt cache warm with a tiny request shortly before the TTL runs out. */
106export type KeepAlive = {
107  isOn: boolean;
108  /** Requests sent this session. */
109  pings: number;
110  /** Their estimated cost in USD. */
111  usd: number;
112};
113
114export type Money = {
115  label: "extra" | "month";
116  /** `null` while unknown. */
117  spent: number | null;
118  limit: number | null;
119  balance: number | null;
120  /** Extra usage is switched off. */
121  isOff: boolean;
122  /** ISO code of the amounts; `null` for US dollars from the price list or the budget. */
123  currency: string | null;
124};
125
126declare module "claude-code" {
127  interface PluginState {
128    "status-panel": {
129      snap: Snap | null;
130      tally: Tally;
131      cacheAt: number;
132      now: number;
133      miss: Miss;
134      repo: Repo;
135      mem: MemFile[];
136      model: string;
137      effort: string;
138      plan: string;
139      mcp: McpServer[];
140      calls: Record<string, number>;
141      spent: number;
142      account: AccountSpend | null;
143      billing: Billing;
144      agents: SubagentInfo[];
145      agentUsage: Record<string, SubagentUsage>;
146      showResets: boolean;
147      keepAlive: KeepAlive;
148      /** Subagents whose request and response are expanded in the session pane. */
149      expandedAgents: string[];
150      /** Agent type → the `color` of its definition, for the dot in the session pane. */
151      agentColors: Record<string, string>;
152      /** Subagents spawned this session, the cleared ones included. */
153      spawnedAgents: number;
154      /** Files whose preview is open in the CLAUDE.md pane. */
155      expandedFiles: string[];
156      /** Line count and modification time per memory file. */
157      fileDetails: Record<
158        string,
159        { lines: number; mtimeMs: number; imports: string[] }
160      >;
161      /** Hook commands of every settings source, in load order. */
162      hooks: {
163        scope: "user" | "project" | "local" | "flag" | "policy";
164        event: string;
165        matcher: string;
166        command: string;
167      }[];
168      /** Installed plugins that bring a hooks module, in load order. */
169      mods: {
170        id: string;
171        version: string;
172        scope: "user" | "project" | "local" | "flag" | "policy" | "";
173        isOn: boolean;
174        path: string;
175      }[];
176      /** The settings file of each source. */
177      settingsPaths: Partial<
178        Record<"user" | "project" | "local" | "flag" | "policy", string>
179      >;
180      /** File text by path, read when its preview opens. */
181      previews: Record<string, string>;
182      /** Skills the session lists. */
183      skills: SkillInfo[];
184      /** Calls per skill name. */
185      skillCalls: Record<string, number>;
186      /** MCP servers and skills switched off in the project's local settings. */
187      disabled: { mcp: string[]; skills: string[] };
188      costParts: CostParts;
189      frame: number;
190    };
191  }
192}
193