SLOPSHOPPER

agent-board

Writes each session's subagents, activity, context fill and subscription usage to ~/.claude/agent-board for the Agent Board VS Code extension, and draws a…

panebandguardcommandstatusnetwork
v0.9.1MITupdated 2026-10-18JeremyHo1123/claude-code-agent-board
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · agent-board
│ ┃ Subagents ✕ › fix the failing auth test and add an audit log call │ ┃ 0 running · 0 ended │ ┃ No subagents in this session yet. Once one ⏺ Read(src/auth.ts) │ ┃ starts, its progress shows here as it ⎿ Read 6 lines │ ┃ happens. ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /agent-board │ ⎿ agent-board: 0 running · 0 ended │ ⎿ agent-board: │ ⎿ agent-board: No subagents in this session yet. Once one starts, │ ⎿ agent-board: │ ⎿ agent-board: Key: ● running · ⏸ quiet for over 2 min · ✓ done · │ ⎿ agent-board: │ │ Context ██████████░░░░░░░░░░ 49% · 97k / 200k ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
Context ██████████░░░░░░░░░░ 49% · 97k / 200k
Pane · Subagents
0 running · 0 ended No subagents in this session yet. Once one starts, its progress shows here as it happens.
README

<h1 align="center">Agent Board for Claude Code</h1>

<b>See what every Claude Code subagent is doing, right inside VS Code.</b><br> Live subagent cards, full task details, subscription usage and context fill, across all your open conversations.

<img alt="version 0.9.1" src="https://img.shields.io/badge/version-0.9.1-2a78d6"> <img alt="MIT license" src="https://img.shields.io/badge/license-MIT-199e70"> <img alt="Claude Code 2.1.289 or later" src="https://img.shields.io/badge/Claude%20Code-2.1.289%2B-d97757"> <img alt="VS Code 1.90 or later" src="https://img.shields.io/badge/VS%20Code-1.90%2B-007acc">

<table> <tr> <td width="33%" valign="top"><img src="docs/images/board-dark.png" alt="The board: usage meters, conversations that need you, running subagents"></td> <td width="33%" valign="top"><img src="docs/images/detail-running.png" alt="A running subagent's detail: what it does now, its task and its steps"></td> <td width="33%" valign="top"><img src="docs/images/detail-done.png" alt="An ended subagent's detail in the light theme, with its report"></td> </tr> <tr> <td valign="top"><sub><b>The board.</b> Usage, the conversations waiting for you, every running subagent.</sub></td> <td valign="top"><sub><b>A subagent mid-run.</b> What it does this second, the task it was given, each step with its input and result.</sub></td> <td valign="top"><sub><b>The same subagent, ended.</b> Its report, rendered. (Light theme.)</sub></td> </tr> </table>

<sub>All screenshots use made-up data.</sub>

Why this exists

Claude Code can run several subagents at once, and several conversations at once. In VS Code it is hard to see what each of them is doing.

Claude Code mods (plugins made of function hooks) can draw panes and bars, but VS Code's Claude Code extension does not draw them (checked up to 2.1.289). Its webview takes no mod interface, so a mod's pane or its bar above the prompt never shows there. They show in the terminal and in the desktop app only.

Agent Board gets around this by splitting the job in two:

HalfWhat it isWhat it does
The modA Claude Code plugin, loaded into every sessionWatches the session and writes small JSON files to ~/.claude/agent-board/
The extensionA VS Code extension with its own sidebar viewReads those files once a second and draws the board

What you get

A live board of subagents. One card per running subagent: its state, type, step count, the tool call it is on, and the time it has run. Ended subagents keep a row with their token breakdown. A subagent with no tool call for two minutes is flagged as quiet, and one whose session stopped reporting as possibly cut off.

Task details, like the built-in agent card. Click a card or row to open that subagent's detail:

  • the task it was given, in full
  • every tool call on a timeline, with its input, its result, how long it took, and ✓ or ✕
  • what it said between steps
  • its final report, rendered as Markdown (tables, lists, code)
  • tokens, counted once per request

Open in editor opens the same detail wide in an editor tab. A workflow's agents show their real labels and phases.

A "needs you" section. Conversations waiting for a permission or an answer, subagents gone quiet, and recent failures are grouped at the top. The status bar says which conversation is waiting while one waits.

Subscription usage that keeps up. The 5-hour and weekly windows of your Claude plan, with per-model buckets and extra usage when you have them. Resets are worded as claude.ai's usage page words them. The status bar always shows 5h % · wk %. Two accounts on one machine (VS Code signed in to one, the desktop app to another) are never mixed: the board shows the account VS Code and the terminal use, and leaves out one that only the desktop app is signed in to. agentBoard.usageOfDesktopApp shows that one too, each account with its own meters headed by its sign-in's email.

The right conversation's context. Each conversation's context fill, computed the way /context computes it. The meter follows the Claude tab you are looking at, and the status bar shows it too.

A context bar above the prompt, in the terminal and the desktop app. There the mod draws the conversation's context fill in the band directly above the prompt, as Context ███░░░░░░░ 16% · 157k / 1.0M. The bar is green, yellow from 70% and red from 90%, and steps aside while a survey holds the band. VS Code's Claude panel draws no such band, so there the fill stays in the status bar.

Your prompts, as chapters. My prompts lists every prompt you typed in the conversation in view. Click one and the board shows that conversation's Claude tab, opens VS Code's find there and searches for the prompt, so the panel lands on it (Enter goes to the next match). The start of the prompt is left on the clipboard. The list is closed until you open it.

Notifications when a conversation has waited 15 seconds, a subagent ends or fails, a long turn finishes, or usage crosses 80% or 90%. Each kind has its own switch.

How it works

flowchart LR
    subgraph session["Each Claude Code session"]
        mod["agent-board mod<br/>(function hooks)"]
    end
    api["api.anthropic.com<br/>/api/oauth/usage"]
    board[("~/.claude/agent-board/<br/>sessions/&lt;id&gt;.json<br/>plan-&lt;account&gt;.json")]
    transcripts[("~/.claude/projects/…<br/>subagent transcripts<br/>workflow run files")]
    ext["Agent Board<br/>VS Code extension"]
    ui["Sidebar board<br/>Detail panel<br/>Status bar<br/>Notifications"]

    mod -- "a snapshot, at most once a second" --> board
    api -. "one shared read every 30 s" .-> mod
    board -- "read every second" --> ext
    transcripts -- "read while a detail is open" --> ext
    ext --> ui
  • Snapshots. The mod hooks session, turn, tool-call and agent events. It writes sessions/<sessionId>.json whenever something changed, at most once a second, and once a minute as a heartbeat. The file holds the subagent rows, the session's activity (working, waiting, idle), its context fill and its rate-limit readings.
  • Usage, from two sources. Every API reply carries rate-limit readings, which are fresh but run slightly behind. The usage endpoint that /usage reads is exact, so one session reads it for all of its account's every 30 seconds, through plan-<account>.json. Use within a window only grows, so the board shows the highest reading of the window in force. After a reset or a change of account, the earlier window's readings fall away at once. Each snapshot and each shared read names its account, and two accounts' readings are never settled together. After /login to another account, a reading whose weekly window ends at another time tells each session to ask whose credential it holds at once.
  • Task details. Claude Code already writes each subagent's transcript next to its session's. The extension reads that file while a detail is open, and again whenever it grows. It also reads workflow run files for agent labels and phases.
  • Which conversation is "current". VS Code does not tell one extension which Claude conversation another extension's tab shows. The board matches the focused tab's title against the title Claude Code writes into each transcript, or, for a conversation Claude Code has not titled, against its first prompt, which is what such a tab shows. Two untitled conversations whose first prompts begin with the same 24 characters show the same tab title, and the board cannot tell them apart.

Requirements

  • Claude Code 2.1.289 or later, with mods (function-hook plugins) available to your account. This is the build it was developed against.
  • VS Code 1.90 or later with the Claude Code extension.
  • A Claude subscription for the usage meters. A session on an API key shows no usage windows; everything else works.
  • git, and the code command on your PATH.

Developed and tested on Windows 11. The paths are resolved for macOS and Linux as well, but those are untested.

Install

Let Claude Code do it

Paste this into Claude Code on the machine you want it on:

Install Agent Board from https://github.com/JeremyHo1123/claude-code-agent-board.
Follow the "Install" section of its README step by step, then run every check
under "Verify" and tell me the result of each one.

Or do it by hand

1. Clone the repository into Claude Code's mods folder.

# macOS, Linux, Git Bash
git clone https://github.com/JeremyHo1123/claude-code-agent-board.git ~/.claude/mods/agent-board
# Windows PowerShell
git clone https://github.com/JeremyHo1123/claude-code-agent-board.git "$env:USERPROFILE\.claude\mods\agent-board"

2. Tell Claude Code to load the mod. Add CLAUDE_CODE_PLUGIN_DIRS to the env block of ~/.claude/settings.json. Keep every other key in the file as it is.

{
  "env": {
    "CLAUDE_CODE_PLUGIN_DIRS": "~/.claude/mods/agent-board"
  }
}

If CLAUDE_CODE_PLUGIN_DIRS already has a value, append this folder to it. Separate the paths with ; on Windows and : elsewhere.

3. Install the VS Code extension. A built package ships in dist/, so nothing needs compiling.

# macOS, Linux, Git Bash
code --install-extension ~/.claude/mods/agent-board/dist/agent-board.vsix --force
# Windows PowerShell
code --install-extension "$env:USERPROFILE\.claude\mods\agent-board\dist\agent-board.vsix" --force

4. Reload. In VS Code, run Developer: Reload Window from the Command Palette. This restarts the Claude Code sessions in that window, so do it while none of them is mid-task. Each session loads the mod as it starts.

Verify

CheckExpected
claude plugin validate ~/.claude/mods/agent-boardends with Validation passed
Type /agent-board in a Claude Code conversationit answers with the subagent board
List ~/.claude/agent-board/sessions/one <sessionId>.json per open conversation, modified within the last minute
code --list-extensions --show-versionslists jeremy-local.agent-board@0.9.1
Look at VS Codean Agent Board icon in the activity bar; 5h …% · wk …% and Context …% in the status bar once a conversation has had one reply

Update

git -C ~/.claude/mods/agent-board pull
code --install-extension ~/.claude/mods/agent-board/dist/agent-board.vsix --force

Then reload the window. A change to the mod alone needs no window reload: interactive sessions watch the folder and reload the mod themselves, and /reload-plugins forces it.

Uninstall

code --uninstall-extension jeremy-local.agent-board

Remove the folder from CLAUDE_CODE_PLUGIN_DIRS, then delete ~/.claude/mods/agent-board and ~/.claude/agent-board.

Reading the board

The board's parts, from the top:

On screenWhat it holds
Subscription usageThe 5-hour session and the weekly windows, with when each resets
Current conversation · ContextThe conversation in view and its context fill (Latest conversation until a Claude tab is matched)
My promptsThe prompts you typed in that conversation, closed until you open it
Needs youConversations waiting for you, subagents gone quiet, recent failures
ConversationsListed when more than one is open; current marks the one the context meter shows
Running / EndedRunning and ended subagents
waiting · running · done · failed · stoppedThe counts at the top
Task · Steps · ReportIn a detail: the task it was given, its steps, its report
Open in editor · Back · CopyIn a detail: open it wide in an editor tab, go back to the board, copy the report

Settings

All of them live under agentBoard.* in VS Code's settings.

SettingDefaultWhat it does
agentBoard.autoRevealtrueShows the board when two or more subagents run at once, without taking the keyboard
agentBoard.usageInStatusBartrueKeeps 5h % · wk % in the status bar; it turns yellow from 70% and red from 90%
agentBoard.usageOfDesktopAppfalseAlso shows the usage of an account that only the Claude desktop app is signed in to
agentBoard.contextInStatusBartrueKeeps the current conversation's context fill in the status bar
agentBoard.notify.waitingtrueNotifies when a conversation has waited 15 seconds for an answer or a permission
agentBoard.notify.subagentstrueNotifies when a subagent ends or fails; three or more at once fold into one
agentBoard.notify.turnDonetrueNotifies when a turn that ran over two minutes finishes
agentBoard.notify.usagetrueNotifies when the 5-hour or weekly window crosses 80% or 90%
agentBoard.dataDirectory""Where the snapshots are; empty means ~/.claude/agent-board/sessions

In a terminal session the mod also answers /agent-board with a pane of that session's subagents.

Its answer ends with three [context bar] lines for when the bar above the prompt does not show: the surfaces attached to the session, how many times one asked for the bar (and which), and the figures the bar would draw.

What it reads and what it sends

  • It reads, on your machine only: the snapshots the mod writes, and Claude Code's own transcripts under ~/.claude/projects/ (for conversation titles and subagent details). It writes nothing there.
  • It makes two kinds of network request, both to api.anthropic.com: GET /api/oauth/usage, the endpoint Claude Code's /usage reads, and GET /api/oauth/profile, which says whose credential the session holds. The requests go through Claude Code's credential handle ($.session.authorize()), so the token never reaches the mod's code. All sessions of an account together read the usage at most once every 30 seconds, and back off for up to 10 minutes when refused; each session asks for the profile once every 10 minutes.
  • It keeps the account's email on your machine. The profile's email and the start of its organization id go into the board's files, to keep two accounts' usage apart and to head each account's meters. They are sent nowhere.
  • No telemetry. Nothing else leaves your machine.

claude plugin validate prints everything the mod hooks, calls and reads, so you can check this yourself.

Limitations

  • No bar above the prompt in VS Code. The Claude panel there takes no mod interface, so the context fill sits in the status bar instead.
  • A workflow's agents get their real names when the run ends. Claude Code writes the run file only then. Until then each agent goes by the first line of its task.
  • No thinking text. Transcripts keep only a signature for thinking blocks, so a detail shows how long it thought, not what.
  • "Waiting for permission" can linger while a tool you approved runs for a long time.
  • Conversations are matched by title. Two conversations with the same title cannot be told apart, and a brand-new untitled one is matched only when it is the only one.
  • The usage endpoint is not a public API. Its shape may change. If it does, the board falls back to the readings API replies carry.
  • Long content is clipped in the sidebar (1,500 characters per step result, 20,000 per report). The editor tab shows far more. A transcript over 8 MB is read in part.
  • English only. The strings are in hooks/format.ts, hooks/register.tsx, vscode-extension/extension.js and vscode-extension/media/*.js.

Troubleshooting

What you seeWhat it meansWhat to do
No data yet on the boardNo snapshot yet: the mod is not loadedCheck CLAUDE_CODE_PLUGIN_DIRS, reload the window, type /agent-board
/agent-board is unknownMods are not available in this sessionUpdate Claude Code; run claude plugin validate on the folder and read what it says
⚠ Usage read rate-limitedThe usage endpoint refused (HTTP 429)Nothing: it retries by itself, and replies keep the 5-hour and weekly figures moving
The context meter shows another conversationNo Claude tab matched yetClick the Claude tab you mean
A detail says the transcript is not foundA subagent's transcript appears after its first replyWait a moment; old sessions whose files were cleared stay missing
A subagent called Unnamed agentA workflow agent whose transcript is not written yetIt takes its task's first line within a second or two

Development

agent-board/                  the repository, and the mod's own folder
├─ .claude-plugin/plugin.json the mod's manifest
├─ .claude/CLAUDE.md          notes for whoever works on this
├─ hooks/                     the mod: register.tsx (hooks), format.ts (pure helpers)
├─ types/                     the mod's $.state contract
├─ tests/                     the mod's tests
├─ vscode-extension/          the extension
│  ├─ extension.js            polling, merging usage, transcripts, status bar, notifications
│  ├─ media/                  the webviews: board.js, detail.js, panel.js, board.css
│  ├─ test/                   extension tests, and two read-only checks against real data
│  └─ preview/                the webviews in a plain browser, with made-up data
├─ dist/agent-board.vsix      the built extension
└─ docs/images/               the screenshots above

The mod. Claude Code lays its API types into .claude-plugin/types/ the first time the mod loads; tsc needs them.

claude plugin validate .                    # what the engine would accept or refuse
claude plugin test .                        # the tests under tests/
npx -y -p typescript@5.8 tsc -p . --noEmit  # type-check, once the types are laid

The extension. Plain JavaScript with no dependencies.

cd vscode-extension
node test/extension.test.js        # logic tests, with a stand-in vscode module
node test/real-transcripts.js 30   # parses your 30 latest subagent transcripts (read-only)
node test/live-smoke.js            # one poll over your real snapshots (read-only)

Open vscode-extension/preview/index.html in a browser to see the board without VS Code; its header lists the query parameters. preview/shoot.sh takes screenshots with headless Chrome.

Packaging.

cd vscode-extension
npx -y @vscode/vsce@latest package --no-dependencies --skip-license -o ../dist/agent-board.vsix
code --install-extension ../dist/agent-board.vsix --force

.claude/CLAUDE.md holds the notes an agent needs to work on this: the data formats, the rules the code follows, and what was learned the hard way.

Credits

License

MIT

Source 3 files
hooks/register.tsx 721 lines
1import { atom, read, update } from 'claude-code'
2import type { AgentInfo, EngineInterface, Register } from 'claude-code'
3
4import type { AgentBoardRow, AgentBoardStatus } from '../types'
5import {
6  addUsage,
7  boardRootOf,
8  clip,
9  countRows,
10  describeCall,
11  fillBar,
12  fillTone,
13  formatElapsed,
14  formatTokens,
15  isAnotherAccountsWeek,
16  orderRows,
17  parseAccount,
18  parsePlanUsage,
19  planFileOf,
20  renderMarkdown,
21  rowDetail,
22  statusIcon,
23  summaryText,
24  weekEndOf,
25} from './format'
26import type { PlanAccount, PlanUsage, SessionActivity } from './format'
27
28/**
29 * Where the board's files go, read by the Agent Board VS Code extension: `agent-board` under
30 * Claude Code's own folder (CLAUDE_CONFIG_DIR, else ~/.claude). VS Code's Claude extension draws
31 * no mod pane (it never attaches as a ui_render surface), so there the board is that extension's
32 * webview. Outside every project, so the rewrites never reach a repository.
33 *
34 * `sessions/<sessionId>.json` is one snapshot per session; `plan-<account>.json` the read of the
35 * subscription's usage all sessions of that account share (`plan.json` while the account is not
36 * known). Undefined until first asked; null with no home known.
37 */
38let boardRoot: string | null | undefined
39const PANE = 'agent-board'
40const TITLE = 'Subagents'
41const TICK_MS = 5_000
42const FLUSH_MS = 1_000
43const MAX_ROWS = 100
44const SHOWN_ENDED = 30
45/** Opened unasked once this many subagents run at the same time. */
46const AUTO_OPEN_AT = 2
47
48const rows = atom({ plugin: 'agent-board', key: 'rows' } as const, [])
49const now = atom({ plugin: 'agent-board', key: 'now' } as const, 0)
50const isDismissed = atom({ plugin: 'agent-board', key: 'isDismissed' } as const, false)
51/** What the band above the prompt draws; each snapshot refreshes it. */
52const context = atom({ plugin: 'agent-board', key: 'context' } as const, null)
53/** The band's bar: at most this many cells, fewer in a narrow column. */
54const BAND_BAR_CELLS = 20
55
56/** How `$.agent.list()` statuses map onto a row's, for runs whose turn.complete never came (killed). */
57const LIST_STATUS: Readonly<Record<string, AgentBoardStatus>> = {
58  completed: 'done',
59  failed: 'failed',
60  killed: 'stopped',
61}
62
63/**
64 * The subscription's usage, from the endpoint Claude Code's /usage reads. The session's credential
65 * rides through `$.session.authorize()`: the host sets the header, the secret never reaches here.
66 */
67const PLAN_USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
68/**
69 * Who the credential belongs to, from the endpoint Claude Code's own sign-in reads. Sessions of two
70 * accounts can run on one machine (VS Code signed in to one, the desktop app to another), and their
71 * usage must not be merged: each account has its own shared read, and each snapshot names its account.
72 */
73const PROFILE_URL = 'https://api.anthropic.com/api/oauth/profile'
74/**
75 * Asked again this often, for a sign-in changed mid-session; sooner while it has not answered yet.
76 * A /login is mostly caught long before: a reading whose weekly window is another account's asks at once.
77 */
78const ACCOUNT_RECHECK_MS = 600_000
79const ACCOUNT_RETRY_MS = 60_000
80/**
81 * Every session of an account shares one read through `planFileOf(account)` (under the board's
82 * folder): whichever finds it due claims it, reads, and writes the answer back. One read per interval
83 * however many Claude tabs are open; each session polling on its own got the endpoint to refuse most of them.
84 */
85/** One read across all sessions this often; while Claude works, each API response's own readings are fresher. */
86const PLAN_INTERVAL_MS = 30_000
87/**
88 * After a refusal without Retry-After, or any other failure, nobody asks again for this long,
89 * doubled for each failure in a row up to the cap; a success starts it over.
90 */
91const PLAN_BACKOFF_MS = 60_000
92const PLAN_BACKOFF_MAX_MS = 600_000
93/** How often a session looks at the shared file. */
94const PLAN_CHECK_MS = 5_000
95/** An idle session rewrites its snapshot this often, so the board can tell it from a closed one. */
96const HEARTBEAT_MS = 60_000
97
98type SharedPlan = {
99  /** Whose usage this is; absent while the account is not known. */
100  account?: PlanAccount
101  plan?: PlanUsage
102  /** No session reads before this time: the next interval, or a backoff after a failure. */
103  nextAttemptAt: number
104  lastAttemptAt?: number
105  lastError?: { at: number; status?: number; message?: string }
106  /** Failed reads in a row: each one doubles the wait. */
107  failures?: number
108}
109
110/** Set by frequent events (tool calls, main turns); the flush timer writes the snapshot at most once a second. */
111let isDirty = false
112let isFlushing = false
113let planCheckedAt = 0
114/** The account this session is signed in to, once the profile endpoint has said; and when to ask next. */
115let account: PlanAccount | undefined
116let accountNextAt = 0
117/** When the weekly window of this session's last reply reading ends: a jump says the account changed. */
118let replyWeekEnd: string | undefined
119/** When this session last saw an API response arrive (a tool call follows one): how fresh its rate-limit readings are. */
120let lastResponseAt = 0
121/** For /agent-board's diagnosis: how often a surface asked for the band, and on which surfaces. */
122let bandAsks = 0
123const bandSurfaces = new Set<string>()
124/** Module state, as the board reads it: a reload starts it over as idle, the next turn corrects it. */
125let activity: SessionActivity = { state: 'idle', since: Date.now() }
126
127function setActivity(state: SessionActivity['state'], wait?: { reason: string; kind: 'question' | 'permission' }): void {
128  if (activity.state === state && activity.reason === wait?.reason) {
129    return
130  }
131  activity = wait === undefined ? { state, since: Date.now() } : { state, since: Date.now(), ...wait }
132  isDirty = true
133}
134
135/** A permission dialog was answered once the next step starts or the approved tool returns. */
136function endPermissionWait(): void {
137  if (activity.state === 'waiting' && activity.kind === 'permission') {
138    setActivity('working')
139  }
140}
141
142function freshRow(id: string, at: number): AgentBoardRow {
143  return {
144    id,
145    label: `Unnamed agent ${id.slice(0, 7)}`,
146    type: 'other (workflow…)',
147    isListed: false,
148    status: 'running',
149    startedAt: at,
150    lastAt: at,
151    steps: 0,
152    lastAction: '',
153  }
154}
155
156function asRunning(row: AgentBoardRow): AgentBoardRow {
157  const { endedAt: _endedAt, ...rest } = row
158
159  return { ...rest, status: 'running' }
160}
161
162/** Applies `change` to the row of `id` (made first when `create`), stamping it with the time. */
163async function upsert(
164  $: EngineInterface,
165  id: string,
166  change: (row: AgentBoardRow, at: number) => AgentBoardRow,
167  create: boolean,
168): Promise<void> {
169  const at = await $.clock.now()
170
171  await update($, rows, list => {
172    const found = list.find(row => row.id === id)
173
174    if (found === undefined && !create) {
175      return list
176    }
177
178    const changed = change({ ...(found ?? freshRow(id, at)), lastAt: at }, at)
179
180    return found === undefined
181      ? [...list, changed].slice(-MAX_ROWS)
182      : list.map(row => (row.id === id ? changed : row))
183  })
184  await update($, now, () => at)
185}
186
187/**
188 * A file of the board's, by its path under the board's folder. The home folder comes from the
189 * environment (the hooks environment has no `os`): USERPROFILE on Windows, HOME elsewhere.
190 * Rejects where neither is set: a caller's own catch leaves that file unwritten.
191 */
192async function boardPath($: EngineInterface, name: string): Promise<string> {
193  if (boardRoot === undefined) {
194    boardRoot =
195      boardRootOf(await $.env.get('CLAUDE_CONFIG_DIR'), await $.env.get('USERPROFILE'), await $.env.get('HOME')) ?? null
196  }
197  if (boardRoot === null) {
198    throw new Error('agent-board: no home folder to keep the board in')
199  }
200
201  return `${boardRoot}/${name}`
202}
203
204async function readSharedPlan($: EngineInterface, name: string): Promise<SharedPlan | undefined> {
205  try {
206    return JSON.parse(await $.fs.read(await boardPath($, name))) as SharedPlan
207  } catch {
208    return undefined
209  }
210}
211
212/**
213 * Asks now whose this session's credential is, and keeps the answer: the account, or undefined when
214 * the profile did not answer (what was known stands, and it is asked again after the retry interval).
215 */
216async function askAccount($: EngineInterface, at: number): Promise<PlanAccount | undefined> {
217  accountNextAt = at + ACCOUNT_RETRY_MS
218  try {
219    const auth = await $.session.authorize()
220    if (auth === null || auth.kind !== 'bearer') {
221      return undefined
222    }
223    const response = await $.http.fetch(PROFILE_URL, {
224      auth: auth.handle,
225      headers: { 'anthropic-beta': 'oauth-2025-04-20', 'Content-Type': 'application/json' },
226    })
227    const parsed = response.ok ? parseAccount(JSON.parse(response.text)) : undefined
228    if (parsed !== undefined) {
229      // the snapshot names the account: written again when it is learnt, or changes
230      isDirty = isDirty || parsed.id !== account?.id || parsed.label !== account?.label
231      account = parsed
232      accountNextAt = at + ACCOUNT_RECHECK_MS
233    }
234
235    return parsed
236  } catch {
237    return undefined
238  }
239}
240
241/**
242 * The account behind this session's credential, asked when due. A failed read keeps what was known:
243 * the usage then goes on under that account, or under none until the first answer.
244 */
245async function readAccount($: EngineInterface, at: number): Promise<PlanAccount | undefined> {
246  if (at >= accountNextAt) {
247    await askAccount($, at)
248  }
249
250  return account
251}
252
253/** One read of the endpoint: the windows, or the failure and how long everyone should wait. */
254async function fetchPlan($: EngineInterface, at: number, failuresBefore: number): Promise<Partial<SharedPlan>> {
255  const failures = failuresBefore + 1
256  const backoff = Math.min(PLAN_BACKOFF_MS * 2 ** (failures - 1), PLAN_BACKOFF_MAX_MS)
257  const failed = (lastError: NonNullable<SharedPlan['lastError']>, wait = backoff): Partial<SharedPlan> => ({
258    lastError,
259    nextAttemptAt: at + wait,
260    failures,
261  })
262  try {
263    const auth = await $.session.authorize()
264    if (auth === null || auth.kind !== 'bearer') {
265      // an API key or a third-party provider: no subscription windows to read
266      return failed({ at, message: 'no subscription sign-in' })
267    }
268    const response = await $.http.fetch(PLAN_USAGE_URL, {
269      auth: auth.handle,
270      headers: { 'anthropic-beta': 'oauth-2025-04-20', 'Content-Type': 'application/json' },
271    })
272    if (!response.ok) {
273      const retryAfter = Number(response.headers['retry-after'])
274      const isTold = response.status === 429 && Number.isFinite(retryAfter) && retryAfter > 0
275
276      return failed({ at, status: response.status }, isTold ? Math.max(retryAfter * 1000, PLAN_INTERVAL_MS) : backoff)
277    }
278    const parsed = parsePlanUsage(JSON.parse(response.text), at)
279    if (parsed === undefined) {
280      return failed({ at, message: 'reply in an unknown shape' })
281    }
282
283    // a success clears the error and the streak: JSON drops an undefined field
284    return { plan: parsed, lastError: undefined, failures: undefined }
285  } catch (error) {
286    return failed({ at, message: String(error).slice(0, 160) })
287  }
288}
289
290/** Reads the subscription's usage when the shared file says it is due, claiming the read first. */
291async function maybeReadPlan($: EngineInterface): Promise<void> {
292  const at = await $.clock.now()
293  if (at - planCheckedAt < PLAN_CHECK_MS) {
294    return
295  }
296  planCheckedAt = at
297
298  const who = await readAccount($, at)
299  const name = planFileOf(who)
300  const shared = await readSharedPlan($, name)
301  if (shared !== undefined && at < shared.nextAttemptAt) {
302    return
303  }
304
305  // claimed before the request, so another session checking now skips this round
306  const file = await boardPath($, name)
307  const claimed: SharedPlan = { ...shared, account: who, nextAttemptAt: at + PLAN_INTERVAL_MS, lastAttemptAt: at }
308  await $.fs.write(file, JSON.stringify(claimed))
309  const outcome = await fetchPlan($, at, shared?.failures ?? 0)
310  if (who !== undefined && isAnotherAccountsWeek(weekEndOf(shared?.plan), weekEndOf(outcome.plan), at)) {
311    // Another account's week: after a /login the credential is someone else's before this session
312    // asks again, and its read must not land in this account's file. Asked now; only the same
313    // account confirmed (the file's figures were the odd ones) lets the read in. The claim stands,
314    // so a profile that does not answer costs one read a round, not one every check.
315    const asked = await askAccount($, at)
316    if (asked === undefined || asked.id !== who.id) {
317      return
318    }
319  }
320  await $.fs.write(file, JSON.stringify({ ...claimed, ...outcome }))
321}
322
323/** Once a second: read the shared plan usage when it is due, then write the snapshot when anything changed. */
324async function flush($: EngineInterface): Promise<void> {
325  if (isFlushing) {
326    return
327  }
328  isFlushing = true
329  try {
330    await maybeReadPlan($).catch(() => undefined)
331    if (isDirty) {
332      isDirty = false
333      await writeSnapshot($)
334    }
335  } finally {
336    isFlushing = false
337  }
338}
339
340/** Writes this session's snapshot; a failed write leaves the previous one for the extension. */
341async function writeSnapshot($: EngineInterface, ending?: { sessionId: string }): Promise<void> {
342  try {
343    const list = await read($, rows)
344    const at = Math.max(await $.clock.now(), ...list.map(row => row.lastAt))
345    const sessionId = ending?.sessionId ?? (await $.session.id())
346    // `summary` is /context's own figure: the last response's usage plus a local estimate of what
347    // came after it (tool results, the new prompt), so the meter does not trail a step behind
348    const [cwd, model, usage] = await Promise.all([
349      $.session.cwd(),
350      $.session.model(),
351      $.session
352        .usage({ breakdown: 'summary', columns: 40 })
353        .catch(() => $.session.usage())
354        .catch(() => undefined),
355    ])
356    const breakdown = usage?.context.breakdown
357    const weekEnd = usage?.rateLimits.find(limit => limit.kind === 'seven_day')?.resetsAt
358    if (isAnotherAccountsWeek(replyWeekEnd, weekEnd, at)) {
359      // a reply through another account's credential (a /login): whose, asked before the snapshot names one
360      await askAccount($, at)
361    }
362    replyWeekEnd = weekEnd ?? replyWeekEnd
363    const snapshot = {
364      version: 1,
365      sessionId,
366      cwd,
367      model,
368      account,
369      updatedAt: at,
370      isClosed: ending !== undefined,
371      usage:
372        usage === undefined
373          ? undefined
374          : {
375              contextPercent: breakdown?.percentage ?? usage.context.percent,
376              contextTokens: breakdown?.totalTokens ?? usage.context.tokens,
377              contextWindow: breakdown?.rawMaxTokens ?? usage.context.window,
378              isContextEstimate: breakdown !== undefined,
379              rateLimits: usage.rateLimits.map(limit => ({
380                kind: limit.kind,
381                percentUsed: limit.percentUsed,
382                resetsAt: limit.resetsAt,
383              })),
384              // the readings are as fresh as the last response this session saw
385              rateLimitsAt: usage.rateLimits.length > 0 && lastResponseAt > 0 ? lastResponseAt : undefined,
386            },
387      activity,
388      agents: list,
389    }
390
391    const percent = snapshot.usage?.contextPercent
392    const tokens = snapshot.usage?.contextTokens
393    const window = snapshot.usage?.contextWindow
394    if (percent !== undefined && tokens !== undefined && window !== undefined && ending === undefined) {
395      // the band redraws only when a figure moved
396      await update($, context, last =>
397        last !== null && last.percent === percent && last.tokens === tokens && last.window === window
398          ? last
399          : { percent, tokens, window },
400      )
401    }
402
403    await $.fs.write(await boardPath($, `sessions/${sessionId}.json`), JSON.stringify(snapshot))
404  } catch {
405    // the terminal pane, where there is one, still stands
406  }
407}
408
409async function refreshStatusLine($: EngineInterface): Promise<void> {
410  const { running, ended } = countRows(await read($, rows))
411
412  $.ui.status(running === 0 ? undefined : `Subagents ${running} running · ${ended} ended — /agent-board`)
413}
414
415async function maybeAutoOpen($: EngineInterface): Promise<void> {
416  if (await read($, isDismissed)) {
417    return
418  }
419  if (countRows(await read($, rows)).running >= AUTO_OPEN_AT) {
420    void $.ui.open({ id: PANE, title: TITLE }).catch(() => undefined)
421  }
422}
423
424/** Every few seconds while something runs: move the clock the pane draws from, settle killed runs. */
425async function tick($: EngineInterface): Promise<void> {
426  const list = await read($, rows)
427
428  if (!list.some(row => row.status === 'running')) {
429    return
430  }
431
432  let listed: readonly AgentInfo[] = []
433  try {
434    listed = await $.agent.list()
435  } catch {
436    listed = []
437  }
438
439  const at = await $.clock.now()
440  const settled = new Map<string, AgentBoardStatus>()
441  for (const info of listed) {
442    const status = LIST_STATUS[info.status]
443    if (status !== undefined) {
444      settled.set(info.id, status)
445    }
446  }
447
448  if (settled.size > 0) {
449    await update($, rows, current =>
450      current.map(row => {
451        const status = row.isListed && row.status === 'running' ? settled.get(row.id) : undefined
452
453        return status === undefined ? row : { ...row, status, endedAt: row.endedAt ?? at }
454      }),
455    )
456  }
457  await update($, now, () => at)
458  await refreshStatusLine($)
459  isDirty = false
460  await writeSnapshot($)
461}
462
463export const register: Register = on => {
464  on('session.start', async ($, e, next) => {
465    await $.command.register({
466      name: 'agent-board',
467      description: 'Subagents: the state, steps, last step, time and tokens of each',
468      immediate: true,
469    })
470    $.clock.every(TICK_MS, () => {
471      void tick($).catch(() => undefined)
472    })
473    $.clock.every(FLUSH_MS, () => {
474      void flush($).catch(() => undefined)
475    })
476    $.clock.every(HEARTBEAT_MS, () => {
477      // an idle session's snapshot stays young, so the board can tell it from a closed one
478      isDirty = true
479    })
480    await writeSnapshot($)
481
482    return next(e)
483  })
484
485  // Pushed by the engine after each main-thread turn and whenever a rate-limit window moves a whole
486  // point: the usage meters follow it without polling (the idea comes from Learning Hacker's working-memory mod).
487  on('session.measure', async ($, e, next) => {
488    isDirty = true
489    lastResponseAt = Date.now()
490
491    return next(e)
492  })
493
494  on('session.end', async ($, e, next) => {
495    await writeSnapshot($, { sessionId: e.sessionId })
496    if (e.reason === 'clear') {
497      // the process goes on under a new session id: its board starts empty
498      await update($, rows, () => [])
499    }
500
501    return next(e)
502  })
503
504  on('command.run', { command: 'agent-board' }, async $ => {
505    const at = await $.clock.now()
506    await update($, now, () => at)
507    await update($, isDismissed, () => false)
508
509    // Draws the pane in a terminal; VS Code draws nothing for it, hence the text and the extension.
510    void $.ui.open({ id: PANE, title: TITLE }).catch(() => undefined)
511    await writeSnapshot($)
512
513    const list = await read($, rows)
514    const board = renderMarkdown(list, Math.max(at, ...list.map(row => row.lastAt)), SHOWN_ENDED, false)
515    const surfaces = await $.session.surfaces().catch(() => [] as readonly string[])
516    const fill = await read($, context)
517    const diagnosis = [
518      `[context bar] surfaces attached: ${surfaces.join(', ') || '(none)'}`,
519      `[context bar] asked to draw ${bandAsks === 1 ? '1 time' : `${bandAsks} times`}${bandSurfaces.size > 0 ? ` (${[...bandSurfaces].join(', ')})` : ''}`,
520      `[context bar] figures: ${fill === null ? '(none read yet)' : `${fill.percent}% · ${formatTokens(fill.tokens)} / ${formatTokens(fill.window)}`}`,
521    ].join('\n')
522
523    return {
524      text: `${board}\nThe graphical board: the Agent Board icon in VS Code's activity bar, or Ctrl+Shift+P → "Agent Board: Open Subagent Board".\n\n${diagnosis}`,
525    }
526  })
527
528  on('ui.close', { id: PANE }, async ($, e, next) => {
529    if (e.origin.kind === 'person') {
530      await update($, isDismissed, () => true)
531    }
532
533    return next(e)
534  })
535
536  on('agent.spawn', async ($, e, next) => {
537    const started = await next(e)
538    const id = started.agentId
539
540    if (id !== undefined) {
541      const label = clip(e.description === '' ? e.subagentType : e.description, 60)
542
543      await upsert(
544        $,
545        id,
546        row => ({
547          ...asRunning(row),
548          label,
549          type: e.subagentType,
550          isListed: true,
551          lastAction: row.lastAction === '' ? 'starting' : row.lastAction,
552        }),
553        true,
554      )
555      await refreshStatusLine($)
556      await maybeAutoOpen($)
557      await writeSnapshot($)
558    }
559
560    return started
561  })
562
563  on('tool.call', async ($, e, next) => {
564    const id = e.agentId
565    endPermissionWait()
566
567    // a tool call follows a fresh API response: its rate-limit readings are as of now
568    lastResponseAt = Date.now()
569
570    if (id === undefined) {
571      isDirty = true
572
573      if (String(e.tool) === 'AskUserQuestion') {
574        setActivity('waiting', { reason: 'has a question for you', kind: 'question' })
575        try {
576          return await next(e)
577        } finally {
578          setActivity('working')
579        }
580      }
581
582      const result = await next(e)
583      endPermissionWait()
584      // the tool's result joins the context: the meter follows within a second
585      isDirty = true
586
587      return result
588    }
589
590    const action = describeCall(e as unknown as Readonly<Record<string, unknown>>)
591
592    await upsert($, id, row => ({ ...asRunning(row), steps: row.steps + 1, lastAction: action }), true)
593    await refreshStatusLine($)
594    isDirty = true
595
596    const result = await next(e)
597    endPermissionWait()
598
599    return result
600  })
601
602  on('turn.start', async ($, e, next) => {
603    setActivity('working')
604
605    return next(e)
606  })
607
608  // Raised just before a permission dialog opens (the classic PermissionRequest hook's moment).
609  on('classic.PermissionRequest', async ($, e, next) => {
610    setActivity('waiting', { reason: `needs your OK for ${e.tool_name}`, kind: 'permission' })
611
612    return next(e)
613  })
614
615  on('classic.PermissionDenied', async ($, e, next) => {
616    endPermissionWait()
617
618    return next(e)
619  })
620
621  on('turn.complete', async ($, e, next) => {
622    const result = await next(e)
623    const id = e.agentId
624
625    if (id === undefined) {
626      // a main-loop turn moved the context window and the rate limits, and the session now waits for a prompt
627      isDirty = true
628      lastResponseAt = Date.now()
629      setActivity('idle')
630
631      return result
632    }
633
634    const status: AgentBoardStatus = e.reason === 'answer' ? 'done' : e.reason === 'aborted' ? 'stopped' : 'failed'
635    const usage = e.usage
636
637    await upsert(
638      $,
639      id,
640      (row, at) => ({
641        ...row,
642        status,
643        endedAt: at,
644        ...(usage === undefined ? {} : { tokens: addUsage(row.tokens, usage) }),
645      }),
646      false,
647    )
648    await refreshStatusLine($)
649    await writeSnapshot($)
650
651    return result
652  })
653
654  // The context fill directly above the prompt, in the terminal and the desktop app (VS Code's
655  // Claude panel draws no band: there the extension's status bar shows it).
656  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
657    bandAsks += 1
658    bandSurfaces.add(e.surface)
659    const fill = await read($, context)
660    if (e.props.hasSurvey || fill === null) {
661      return next(e)
662    }
663
664    const { Box, Text } = $.ui.resolve(e)
665    // the label and the figures take about 30 cells; the bar gets what is left, up to its cap
666    const cells = Math.max(5, Math.min(BAND_BAR_CELLS, e.props.bodyColumns - 30))
667
668    return (
669      <Box flexDirection="row">
670        <Text dimColor>Context </Text>
671        <Text color={fillTone(fill.percent)}>{fillBar(fill.percent, cells)}</Text>
672        <Text bold>{` ${Math.round(fill.percent)}%`}</Text>
673        <Text dimColor>{` · ${formatTokens(fill.tokens)} / ${formatTokens(fill.window)}`}</Text>
674      </Box>
675    )
676  })
677
678  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
679    const { Box, Button, Text } = $.ui.resolve(e)
680    const list = await read($, rows)
681    const at = Math.max(await read($, now), ...list.map(row => row.lastAt))
682    const { ended } = countRows(list)
683    const summary = summaryText(list)
684
685    return (
686      <Box flexDirection="column">
687        <Box flexDirection="row" justifyContent="space-between">
688          <Text bold>{summary}</Text>
689          {ended > 0 && (
690            <Button
691              key="clear"
692              label="Clear ended"
693              dimColor
694              onPress={async () => {
695                await update($, rows, current => current.filter(row => row.status === 'running'))
696                await writeSnapshot($)
697              }}
698            />
699          )}
700        </Box>
701        {list.length === 0 && (
702          <Text dimColor>No subagents in this session yet. Once one starts, its progress shows here as it happens.</Text>
703        )}
704        {orderRows(list, SHOWN_ENDED).map(row => (
705          <Box flexDirection="column" marginTop={1}>
706            <Box flexDirection="row" justifyContent="space-between">
707              <Text bold={row.status === 'running'} wrap="truncate-end">
708                {`${statusIcon(row, at)} ${row.label}`}
709              </Text>
710              <Text dimColor>{formatElapsed((row.endedAt ?? at) - row.startedAt)}</Text>
711            </Box>
712            <Text dimColor wrap="truncate-end">
713              {rowDetail(row, at)}
714            </Text>
715          </Box>
716        ))}
717      </Box>
718    )
719  })
720}
721
hooks/format.ts 394 lines
1import type { ModelUsage } from 'claude-code'
2
3import type { AgentBoardRow, AgentBoardTokens } from '../types'
4
5export const IDLE_MS = 120_000
6
7/**
8 * What the session is doing, for a board that watches several at once: working on a turn, waiting
9 * on the person (a question, a permission dialog), or idle with its turn done.
10 */
11export type SessionActivity = {
12  state: 'working' | 'waiting' | 'idle'
13  /** Milliseconds since the epoch the state began (Date.now(): the board compares it with its own clock). */
14  since: number
15  /** For `waiting`: what it waits on, to show. */
16  reason?: string
17  /** For `waiting`: a question clears when it is answered; a permission when the next step starts. */
18  kind?: 'question' | 'permission'
19}
20
21/** One window of the subscription's usage limits, as claude.ai's usage page shows it. */
22export type PlanWindow = {
23  key: string
24  label: string
25  /** Share of the window used, 0-100. */
26  percent: number
27  resetsAt?: string
28}
29
30/** Extra usage (overage) for the billing period; amounts in minor units of `currency` (cents for USD). */
31export type PlanExtra = {
32  percent: number | null
33  usedCredits: number | null
34  monthlyLimit: number | null
35  currency: string | null
36}
37
38export type PlanUsage = {
39  fetchedAt: number
40  windows: PlanWindow[]
41  extra?: PlanExtra
42}
43
44const PLAN_WINDOWS: ReadonlyArray<readonly [string, string]> = [
45  ['five_hour', '5-hour session'],
46  ['seven_day', 'Weekly · all models'],
47  ['seven_day_opus', 'Weekly · Opus'],
48  ['seven_day_sonnet', 'Weekly · Sonnet'],
49]
50
51function asRecord(value: unknown): Record<string, unknown> | undefined {
52  return value !== null && typeof value === 'object' && !Array.isArray(value)
53    ? (value as Record<string, unknown>)
54    : undefined
55}
56
57function numberOrNull(value: unknown): number | null {
58  return typeof value === 'number' && Number.isFinite(value) ? value : null
59}
60
61function windowOf(key: string, label: string, value: unknown): PlanWindow | undefined {
62  const record = asRecord(value)
63  const percent = numberOrNull(record?.utilization)
64  if (record === undefined || percent === null) {
65    return undefined
66  }
67  const resetsAt = record.resets_at
68
69  return typeof resetsAt === 'string' ? { key, label, percent, resetsAt } : { key, label, percent }
70}
71
72/**
73 * Reads the body of `GET /api/oauth/usage` (what Claude Code's /usage reads): the 5-hour and weekly
74 * windows, any per-model weekly bucket, and extra usage. The endpoint is not a public API and its
75 * shape may change: whatever does not read as a window is left out, and no window at all is undefined.
76 */
77export function parsePlanUsage(body: unknown, fetchedAt: number): PlanUsage | undefined {
78  const record = asRecord(body)
79  if (record === undefined) {
80    return undefined
81  }
82
83  const windows: PlanWindow[] = []
84  for (const [key, label] of PLAN_WINDOWS) {
85    const window = windowOf(key, label, record[key])
86    if (window !== undefined) {
87      windows.push(window)
88    }
89  }
90  for (const list of [record.model_scoped, record.limits]) {
91    if (!Array.isArray(list)) {
92      continue
93    }
94    for (const item of list) {
95      const name = asRecord(item)?.display_name
96      if (typeof name === 'string' && !windows.some(window => window.key === `model:${name}`)) {
97        const window = windowOf(`model:${name}`, `Weekly · ${name}`, item)
98        if (window !== undefined) {
99          windows.push(window)
100        }
101      }
102    }
103  }
104  if (windows.length === 0) {
105    return undefined
106  }
107
108  const extra = asRecord(record.extra_usage)
109  if (extra?.is_enabled === true) {
110    return {
111      fetchedAt,
112      windows,
113      extra: {
114        percent: numberOrNull(extra.utilization),
115        usedCredits: numberOrNull(extra.used_credits),
116        monthlyLimit: numberOrNull(extra.monthly_limit),
117        currency: typeof extra.currency === 'string' ? extra.currency : null,
118      },
119    }
120  }
121
122  return { fetchedAt, windows }
123}
124
125/** The subscription a session is signed in to: what tells one account's usage from another's. */
126export type PlanAccount = {
127  /** Short and safe in a file name: the start of the organization's id (the limits are the organization's). */
128  id: string
129  /** The sign-in's email, to show. */
130  label?: string
131}
132
133/**
134 * Reads the body of `GET /api/oauth/profile`: who the session's credential belongs to. Not a public
135 * API either: undefined where no id reads.
136 */
137export function parseAccount(body: unknown): PlanAccount | undefined {
138  const record = asRecord(body)
139  const account = asRecord(record?.account)
140  const uuid = asRecord(record?.organization)?.uuid ?? account?.uuid
141  const id = typeof uuid === 'string' ? uuid.toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 12) : ''
142  if (id === '') {
143    return undefined
144  }
145  const label = [account?.email, account?.email_address, account?.display_name].find(
146    (value): value is string => typeof value === 'string' && value.trim() !== '',
147  )
148
149  return label === undefined ? { id } : { id, label: label.trim() }
150}
151
152/** The shared read's file: one per account, so two sign-ins on one machine never overwrite each other's. */
153export function planFileOf(account: PlanAccount | undefined): string {
154  return account === undefined ? 'plan.json' : `plan-${account.id}.json`
155}
156
157/** When a read's weekly window ends: what tells one account's readings from another's. */
158export function weekEndOf(plan: PlanUsage | undefined): string | undefined {
159  return plan?.windows.find(window => window.key === 'seven_day')?.resetsAt
160}
161
162/** Two readings of one weekly window: its end moves by no more than a few minutes between reads. */
163const SAME_WEEK_MS = 10 * 60_000
164
165/**
166 * Whether a reading of the weekly window is another account's than an earlier one. An account's week
167 * ends at one time until it has ended, so a week that ends elsewhere while the earlier one still runs
168 * came through another sign-in: a /login moved the credential the session holds to another account.
169 * With either end unknown, nothing says so.
170 */
171export function isAnotherAccountsWeek(earlier: string | undefined, later: string | undefined, at: number): boolean {
172  const before = Date.parse(earlier ?? '')
173  const after = Date.parse(later ?? '')
174
175  return (
176    Number.isFinite(before) &&
177    Number.isFinite(after) &&
178    at < before - SAME_WEEK_MS &&
179    Math.abs(after - before) > SAME_WEEK_MS
180  )
181}
182
183/**
184 * The board's folder: `agent-board` under Claude Code's own folder, which is CLAUDE_CONFIG_DIR
185 * where that is set and `.claude` in the home folder otherwise (USERPROFILE on Windows, HOME
186 * elsewhere). Forward slashes throughout; undefined with no home known.
187 */
188export function boardRootOf(
189  configDir: string | undefined,
190  userProfile: string | undefined,
191  home: string | undefined,
192): string | undefined {
193  const set = (value: string | undefined): string | undefined =>
194    value === undefined || value.trim() === '' ? undefined : value.trim()
195  const person = set(userProfile) ?? set(home)
196  const base = set(configDir) ?? (person === undefined ? undefined : `${person.replace(/[\\/]+$/, '')}/.claude`)
197
198  return base === undefined ? undefined : `${base.replace(/\\/g, '/').replace(/\/+$/, '')}/agent-board`
199}
200
201/** One line, at most `max` characters. */
202export function clip(text: string, max: number): string {
203  const line = text.replace(/\s+/g, ' ').trim()
204
205  return line.length > max ? `${line.slice(0, max - 1)}…` : line
206}
207
208/** The last two segments of a path, either slash. */
209export function tailPath(path: string): string {
210  return path.replace(/\\/g, '/').split('/').filter(Boolean).slice(-2).join('/')
211}
212
213/** What a subagent's tool call is doing, short enough for one row. */
214export function describeCall(args: Readonly<Record<string, unknown>>): string {
215  const tool = String(args.tool)
216  const text = (key: string): string => {
217    const value = args[key]
218
219    return typeof value === 'string' ? value : ''
220  }
221
222  switch (tool) {
223    case 'Bash':
224    case 'PowerShell':
225      return `${tool} ${clip(text('command'), 60)}`
226    case 'Read':
227    case 'Edit':
228    case 'Write':
229      return `${tool} ${tailPath(text('file_path'))}`
230    case 'NotebookEdit':
231      return `${tool} ${tailPath(text('notebook_path'))}`
232    case 'Grep':
233      return `Grep "${clip(text('pattern'), 40)}"`
234    case 'Glob':
235      return `Glob ${clip(text('pattern'), 50)}`
236    case 'WebSearch':
237      return `WebSearch "${clip(text('query'), 50)}"`
238    case 'WebFetch':
239      return `WebFetch ${clip(text('url'), 60)}`
240    case 'Agent':
241      return `Agent ${clip(text('description'), 40)}`
242    default:
243      return clip(tool.replace(/^mcp__/, ''), 50)
244  }
245}
246
247export function addUsage(base: AgentBoardTokens | undefined, usage: ModelUsage): AgentBoardTokens {
248  return {
249    input: (base?.input ?? 0) + usage.input_tokens,
250    output: (base?.output ?? 0) + usage.output_tokens,
251    cacheRead: (base?.cacheRead ?? 0) + usage.cache_read_input_tokens,
252    cacheWrite: (base?.cacheWrite ?? 0) + usage.cache_creation_input_tokens,
253  }
254}
255
256export function totalTokens(tokens: AgentBoardTokens): number {
257  return tokens.input + tokens.output + tokens.cacheRead + tokens.cacheWrite
258}
259
260export function formatTokens(count: number): string {
261  if (count >= 1_000_000) {
262    return `${(count / 1_000_000).toFixed(1)}M`
263  }
264  if (count >= 1_000) {
265    return `${Math.round(count / 1_000)}k`
266  }
267
268  return String(count)
269}
270
271/** A bar of `width` cells, filled in proportion to `percent`. */
272export function fillBar(percent: number, width: number): string {
273  const cells = Math.max(1, Math.floor(width))
274  const filled = Math.max(0, Math.min(cells, Math.round((percent / 100) * cells)))
275
276  return '█'.repeat(filled) + '░'.repeat(cells - filled)
277}
278
279/** The theme color of a fill: calm below 70%, a warning from there, an error from 90%. */
280export function fillTone(percent: number): 'success' | 'warning' | 'error' {
281  return percent >= 90 ? 'error' : percent >= 70 ? 'warning' : 'success'
282}
283
284/** m:ss, or h:mm:ss from an hour. */
285export function formatElapsed(ms: number): string {
286  const seconds = Math.max(0, Math.round(ms / 1000))
287  const minutes = Math.floor(seconds / 60)
288  const ss = String(seconds % 60).padStart(2, '0')
289
290  if (minutes >= 60) {
291    return `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, '0')}:${ss}`
292  }
293
294  return `${minutes}:${ss}`
295}
296
297export function isIdle(row: AgentBoardRow, now: number): boolean {
298  return row.status === 'running' && now - row.lastAt > IDLE_MS
299}
300
301export function statusIcon(row: AgentBoardRow, now: number): string {
302  if (isIdle(row, now)) {
303    return '⏸'
304  }
305
306  return { running: '●', done: '✓', failed: '✗', stopped: '■' }[row.status]
307}
308
309/** "1 step", "3 steps". */
310export function stepsText(count: number): string {
311  return count === 1 ? '1 step' : `${count} steps`
312}
313
314/** What a row is doing now, or what it cost once it ended. */
315export function rowNote(row: AgentBoardRow, now: number): string {
316  const last = row.lastAction === '' ? '—' : row.lastAction
317
318  switch (row.status) {
319    case 'running': {
320      const idle = isIdle(row, now) ? `quiet for ${Math.floor((now - row.lastAt) / 60_000)} min · ` : ''
321
322      return `${idle}last: ${last}`
323    }
324    case 'done':
325      return row.tokens === undefined
326        ? 'token —'
327        : `token ${formatTokens(totalTokens(row.tokens))} (cache read ${formatTokens(row.tokens.cacheRead)})`
328    case 'failed':
329      return `failed, last step: ${last}`
330    case 'stopped':
331      return 'stopped'
332  }
333}
334
335/** The second line of a row: type, steps, and its note. */
336export function rowDetail(row: AgentBoardRow, now: number): string {
337  return `${row.type} · ${stepsText(row.steps)} · ${rowNote(row, now)}`
338}
339
340/** "2 running · 3 ended", with the failed ones when there are any. */
341export function summaryText(list: readonly AgentBoardRow[]): string {
342  const { running, ended, failed } = countRows(list)
343
344  return `${running} running · ${ended} ended${failed > 0 ? ` · ${failed} failed` : ''}`
345}
346
347function tableCell(text: string): string {
348  return text.replace(/\|/g, '\\|').replace(/\r?\n/g, ' ')
349}
350
351/**
352 * The board as Markdown: a status file VS Code's Markdown preview shows live (VS Code draws no
353 * mod pane), and the text `/agent-board` prints.
354 */
355export function renderMarkdown(list: readonly AgentBoardRow[], now: number, keep: number, withHeading: boolean): string {
356  const lines = withHeading ? ['# Subagents', ''] : []
357
358  // no clock time: the hooks environment's time zone is not the person's
359  lines.push(summaryText(list), '')
360
361  if (list.length === 0) {
362    lines.push('No subagents in this session yet. Once one starts, this updates by itself.')
363  } else {
364    lines.push('| State | Subagent | Type | Time | Steps | Last step / token |', '|:-:|---|---|--:|--:|---|')
365    for (const row of orderRows(list, keep)) {
366      const elapsed = formatElapsed((row.endedAt ?? now) - row.startedAt)
367
368      lines.push(
369        `| ${statusIcon(row, now)} | ${tableCell(row.label)} | ${tableCell(row.type)} | ${elapsed} | ${row.steps} | ${tableCell(rowNote(row, now))} |`,
370      )
371    }
372  }
373
374  lines.push('', 'Key: ● running · ⏸ quiet for over 2 min · ✓ done · ✗ failed · ■ stopped', '')
375
376  return lines.join('\n')
377}
378
379/** Running rows in start order, then up to `keep` ended rows, newest first. */
380export function orderRows(list: readonly AgentBoardRow[], keep: number): AgentBoardRow[] {
381  const ended = list
382    .filter(row => row.status !== 'running')
383    .sort((a, b) => (b.endedAt ?? b.lastAt) - (a.endedAt ?? a.lastAt))
384
385  return [...list.filter(row => row.status === 'running'), ...ended.slice(0, keep)]
386}
387
388export function countRows(list: readonly AgentBoardRow[]): { running: number; ended: number; failed: number } {
389  const running = list.filter(row => row.status === 'running').length
390  const failed = list.filter(row => row.status === 'failed').length
391
392  return { running, ended: list.length - running, failed }
393}
394
types/index.d.ts 44 lines
1export type AgentBoardStatus = 'running' | 'done' | 'failed' | 'stopped'
2
3export type AgentBoardTokens = {
4  input: number
5  output: number
6  cacheRead: number
7  cacheWrite: number
8}
9
10export type AgentBoardRow = {
11  /** The agent loop's id: what its tool.call / turn.complete events carry as agentId. */
12  id: string
13  label: string
14  type: string
15  /** True when the Agent tool started it (agent.spawn); false for loops seen only through their tool calls (workflow agents). */
16  isListed: boolean
17  status: AgentBoardStatus
18  startedAt: number
19  lastAt: number
20  endedAt?: number
21  steps: number
22  lastAction: string
23  tokens?: AgentBoardTokens
24}
25
26/** The context window's fill as /context estimates it, for the band above the prompt. */
27export type AgentBoardContext = {
28  percent: number
29  tokens: number
30  window: number
31}
32
33declare module 'claude-code' {
34  interface PluginState {
35    'agent-board': {
36      rows: AgentBoardRow[]
37      now: number
38      isDismissed: boolean
39      /** Null until the first snapshot has read the session's usage. */
40      context: AgentBoardContext | null
41    }
42  }
43}
44