Every running subagent with the tool it is on and its last sentence, and /whisper slips one of them a note without stopping the turn

Small cards that sit under the Claude Code prompt, or docked beside the transcript in fullscreen. Each widget is its own mod, toggled with a slash command.
It started with a few useful ones (context, usage, file tree) and then got carried away: there are now 95 widgets, from git status and a turn timer to a pixel crab, a dungeon crawl and Tetris.
Try every widget in its own little terminal on the demo page: the real widget code runs in the browser against a simulated session, so you can type its slash commands, run a turn and play the games. It is a static page in docs/, published to GitHub Pages on every push to main that changes it; opening docs/index.html from a checkout works too.
Add the marketplace, then install the layout plugin and whichever widgets you want:
/plugin marketplace add oMaN-Rod/claude-code-widgets
/plugin install widgets@claude-code-widgets
/plugin install context-widget@claude-code-widgets
Every widget needs widgets, the layout plugin that places the cards.
Requires a Claude Code version with mod (function hook) support. The mod API is early access and may change between releases.
Required by every widget.
| Plugin | Command | What it shows | ||||||
|---|---|---|---|---|---|---|---|---|
widgets | `/widgets [side\ | above\ | below\ | close\ | <columns>\ | width <widget> <columns\ | reset>]` | Places the cards: below the prompt, above it, or docked beside the transcript in fullscreen |
What Claude is doing and what it is costing.
| Plugin | Command | What it shows | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
context-widget | `/context-widget [auto\ | detailed\ | grid\ | top\ | bar\ | line]` | The context window as a stacked bar, one colour per /context category | |||
usage-widget | /usage-widget | A bar per rate-limit window, time to reset, session cost | ||||||||
timer-widget | `/timer-widget [on\ | off\ | clear]` | The running turn's elapsed time, plus last, average and longest turn and a sparkline | ||||||
activity-widget | `/activity-widget [on\ | off\ | clear]` | The latest tool calls with their duration and whether they failed | ||||||
tasks-widget | `/tasks-widget [on\ | off\ | clear]` | The task list Claude is working through, with a progress bar | ||||||
checks-widget | `/checks-widget [on\ | off\ | clear]` | The latest test, lint and build runs: pass or fail, duration and how long ago | ||||||
timeline-widget | `/timeline-widget [on\ | off]` | The turn as a chart: one bar per tool call on a time axis, parallel calls stacked | |||||||
board-widget | `/board-widget [on\ | off\ | clear]` | A status board Claude writes itself through a pin tool: goal, findings and open questions | ||||||
forecast-widget | `/forecast-widget [on\ | off\ | clear]` | Context growth per turn as a chart, with the turns left before compaction; warns once when three or fewer are left | ||||||
guard-widget | `/guard-widget [on\ | off\ | clear]` | Permission checks this session: allowed, asked and denied, with what you keep being asked about | ||||||
stream-widget | `/stream-widget [on\ | off]` | A live tokens-per-second gauge and sparkline while Claude is writing (estimated from text length) | |||||||
sessions-widget | /relay <number> <message>, `/sessions-widget [on\ | off]` | Every Claude Code session open on this machine: folder, branch, working or waiting and for how long; /relay 1 <message> sends a line to one | |||||||
collision-widget | `/collision-widget [on\ | off\ | clear]` | Stops an edit to a file another Claude Code session on this machine changed since this one last read it, and has Claude read it again first | ||||||
sieve-widget | `/sieve-widget [on\ | off]` | A compaction that keeps every word you and Claude said and folds only the old tool traffic, with no summary and no tokens spent | |||||||
redact-widget | `/redact-widget [on\ | off\ | clear]` | Replaces API keys, tokens, private keys and passwords in command output and file reads before Claude sees them | ||||||
notebook-widget | `/notebook-widget [on\ | off\ | show\ | drop <number>\ | clear]` | Gives Claude a jot tool for writing down what its future self should know about this project, and reads the notes back next session | ||||
footnotes-widget | `/footnotes-widget [on\ | off\ | show\ | clear]` | Checks every file path, cited line and code symbol in Claude's last reply against the working tree, with no model call, and flags the ones that are not there | |||||
witness-widget | `/witness-widget [on\ | off\ | show\ | clear]` | Every line of hidden context the other widgets add to your prompts, word for word, with a running size | |||||
queue-widget | `/queue-widget [on\ | off\ | add <prompt>\ | until <command\ | off>\ | start\ | drop <number>\ | report\ | clear]` | A queue of prompts that run back to back while you are away, a gate command each must pass before the next starts, and a report of how each one ended |
done-widget | `/done-widget [on\ | off\ | add <criterion>\ | drop <number>\ | show\ | clear]` | A definition of done you write once: Claude ticks each item with evidence through its tick tool, and is pulled up when it says done with items open | |||
trial-widget | `/trial-widget [on\ | off\ | test <widget>\ | clear]` | A fair test of another widget: sessions alternate with it on and off, and the card compares how many turns end clean | |||||
aside-widget | `/aside-widget [on\ | off\ | ask <question>\ | clear]` | Ask a side question about the conversation, even mid-turn, and get the answer on a card without adding a turn to the transcript | |||||
tap-widget | `/tap-widget [on\ | off\ | list [word]\ | add <server> <tool> [json] [anyway]\ | run <n>\ | show <n>\ | drop <n>\ | clear]` | One line per tool of your connected MCP servers, called by the widget on a clock with no model: pull requests, errors, the next meeting | |
margin-widget | `/margin-widget [on\ | off\ | mark [remark]\ | drop <n>\ | send\ | clear]` | Mark passages of Claude's reply with the mouse, write a remark against each, and send them back as one quoted prompt | |||
loupe-widget | `/loupe-widget [on\ | off\ | look [text]\ | copy]` | Select a hash, path, name, timestamp or colour in the transcript with the mouse and the card says what it is, with no model call | |||||
strays-widget | `/strays-widget [on\ | off\ | stop <port>\ | forget <port>\ | clear]` | Servers this session started that still hold a port, with age and turn, one verb to stop one, and the survivors shown when the next session opens | ||||
premise-widget | `/premise-widget [on\ | off\ | show\ | fix <n>\ | clear]` | Quotes thinking-summary sentences that name a gap and a choice made anyway, unless the reply flags it, and starts your correction; no model call; needs "showThinkingSummaries": true in settings.json | ||||
earpiece-widget | `/earpiece-widget [on\ | off], /whisper <number> <note>` | Every running subagent with the tool it is on and its last sentence, and /whisper slips one of them a note without stopping the turn | |||||||
pen-widget | `/pen-widget [on\ | off\ | show\ | clear]` | The file, edit or command Claude is writing right now, drawn line by line as the tool call's arguments stream in, before the tool runs | |||||
outage-widget | `/outage-widget [on\ | off\ | check\ | clear]` | When a push or install fails on the network, checks the provider's status page and says whether GitHub, npm, PyPI or crates.io reports an incident | |||||
landmarks-widget | `/landmarks-widget [on\ | off\ | list\ | go <n>\ | clear]` | A numbered table of contents for the session, built as it happens from prompts, first edits, checks turning red or green, commits and questions; press a line to scroll the transcript to it | ||||
seen-widget | `/seen-widget [on\ | off\ | show\ | open [n]\ | clear]` | The pictures Claude looked at this session, image files it read and screenshots that came back from tools, drawn as Claude received them and opened full size with one command | ||||
amendments-widget | `/amendments-widget [on\ | off\ | show [n]\ | clear]` | What changed in the system prompt and the built-in tool descriptions Claude Code gives Claude since the version you last ran, with the before and after one command away | |||||
skimmed-widget | `/skimmed-widget [on\ | off\ | show\ | clear]` | The caveats in Claude's replies that left your screen while Claude was still writing and have not been back, quoted in full; it never claims that what was on screen was read | |||||
attic-widget | `/attic-widget [on\ | off\ | show\ | keep <tool>\ | stow <tool>\ | clear]` | Counts which tools Claude calls in this project, puts the unused ones behind ToolSearch, lists the daily ones up front, and reports how many schema tokens each request no longer carries | |||
rehearsal-widget | `/rehearsal-widget [on\ | off\ | show\ | forget <n>\ | clear]` | Which of the commands and edits Claude has made in this project would stop for permission or be refused right now, asked of the engine's own permission check without running anything | ||||
aim-widget | `/aim-widget [on\ | off\ | prod <word>\ | unprod <word>\ | show\ | clear]` | Where a command lands outside this folder: the kube context, cloud profile, Terraform workspace or database it is aimed at, named in the permission dialog | |||
earshot-widget | `/earshot-widget [on\ | off\ | last\ | clear]` | Whether Claude has got the message you typed while it was working: how late a request first carried it, and what Claude changed before it heard you |
The state of the working tree.
| Plugin | Command | What it shows | |||||
|---|---|---|---|---|---|---|---|
file-tree-widget | /file-tree-widget | The project directory; folders expand on click | |||||
git-widget | /git-widget | Branch, ahead/behind, staged, changed and untracked counts, and the last commit | |||||
changes-widget | `/changes-widget [on\ | off\ | clear]` | Files edited this session, most recent first, with an edit count each | |||
commits-widget | /commits-widget | The commits made since the session started | |||||
todos-widget | /todos-widget | TODO, FIXME, HACK and XXX comments in tracked files, counted and listed | |||||
diff-widget | `/diff-widget [on\ | off\ | clear]` | The last edit as a syntax-highlighted diff | |||
watch-widget | `/watch-widget [on\ | off\ | run\ | stop], /watch <command>` | /watch bun test reruns the command after every edit: a pass or fail light and the last failing lines | ||
map-widget | `/map-widget [on\ | off\ | clear]` | A pixel map of the tracked files, lit blue where Claude has read and green where it has edited | |||
stakes-widget | `/stakes-widget [on\ | off\ | clear]` | What a yes would lose, measured from git and written under the permission dialog for a destructive command | |||
ledger-widget | `/ledger-widget [on\ | off\ | scan\ | show\ | clear]` | What a project has cost across every session, from any folder or worktree in it: measured as each turn ends, and read back from the sessions Claude Code saved | |
squiggle-widget | `/squiggle-widget [on\ | off\ | check [text]]` | Underlines file names that do not exist, as you type them in the prompt box, and paints the ones that do green | |||
critic-widget | `/critic-widget [on\ | off\ | review\ | tell\ | clear]` | A second pair of eyes: a separate model reads the uncommitted diff and lists only real defects, which you can hand to Claude | |
customs-widget | `/customs-widget [on\ | off\ | show\ | trust <name>\ | clear]` | Looks up every package Claude installs on npm or PyPI before the command runs, and holds the install for a yes when the name is missing or under 30 days old. Scoped names and installs that name a registry, or sit beside a project .npmrc that does, are not looked up; user-level and environment registry settings, bunfig.toml, .yarnrc.yml and pip and uv config files are not seen | |
provenance-widget | `/provenance-widget [on\ | off\ | scan\ | look [<path>:<line>]\ | copy\ | clear]` | The conversation behind a line of code: for lines Claude is about to edit, or a path:line you ask about, the prompt you typed before they were written and the command that resumes that session |
green-widget | `/green-widget [on\ | off\ | tell\ | clear]` | What changed in the working tree since each test, lint or build command last passed, measured against a hidden git snapshot taken at that moment and handed to Claude on request |
Clocks, timers and reminders that do not depend on the session.
| Plugin | Command | What it shows | |||||
|---|---|---|---|---|---|---|---|
pomodoro-widget | `/pomodoro-widget [on\ | off\ | start\ | break\ | stop\ | <minutes>]` | A focus timer with a countdown, a progress bar and a count of finished sessions |
countdown-widget | `/countdown-widget [on\ | off\ | clear], /countdown <HH:MM\ | <n>m\ | <n>h> [label]` | Time left to a deadline you set, with a progress bar and a toast when it arrives | |
clocks-widget | `/clocks-widget [on\ | off\ | add <zone>\ | remove <zone>\ | clear]` | Your local time beside the time zones you add, such as Asia/Tokyo | |
notes-widget | `/notes-widget [on\ | off\ | clear], /note <text\ | done <n>>` | Pinned notes kept across sessions; /note <text> adds one, /note done <n> removes it | ||
coffee-widget | `/coffee-widget [on\ | off\ | refill\ | <minutes>]` | A cup that empties over 90 minutes and nudges you to take a break |
Pixel art that reacts to turns, tool calls, checks and context usage.
| Plugin | Command | What it shows | |||
|---|---|---|---|---|---|
pet-widget | `/pet-widget [on\ | off\ | <mood>]` | Clawd, a pixel crab: works during a turn, dizzy when a tool call fails, happy when tests pass. Earns XP and levels up across sessions, wears a hat once badges-widget has awarded a badge, and with two sessions open stays in the one you last prompted. Remembers each project and greets you with how long you were away and whether the checks were red | |
aquarium-widget | `/aquarium-widget [on\ | off\ | demo]` | A fish for every running tool call and agent | |
skyline-widget | `/skyline-widget [on\ | off\ | demo\ | clear]` | One building per turn, one floor per tool call |
train-widget | `/train-widget [on\ | off]` | A locomotive pulling one wagon per tool call this turn, coloured by tool | ||
garden-widget | `/garden-widget [on\ | off\ | reset]` | A plant: a leaf per tool call, a flower when checks pass, wilting when a call fails | |
campfire-widget | `/campfire-widget [on\ | off\ | stoke]` | A campfire that burns higher with tool calls and dies down to embers when idle | |
constellation-widget | `/constellation-widget [on\ | off\ | clear]` | A star per turn, joined into a constellation that gets a name after nine | |
fireworks-widget | `/fireworks-widget [on\ | off\ | demo]` | A night sky that sets off fireworks when checks pass, and a dud when they fail | |
invaders-widget | `/invaders-widget [on\ | off\ | demo\ | clear]` | An invader arrives for every failing check; passing checks shoot them down |
weather-widget | `/weather-widget [on\ | off\ | live\ | <percent>]` | Clear sky when context has room, a storm near compaction |
boss-widget | `/boss-widget [on\ | off]` | Context usage as a boss health bar; compaction defeats it and starts the next level | ||
sky-widget | `/sky-widget [on\ | off]` | The sky at your local time: sun by day, moon by night, more stars the longer the session runs | ||
world-widget | `/world-widget [on\ | off\ | clear]` | One scene for everything: sky by the clock, weather by context, a tower per turn, a train of tool calls and a wandering crab | |
quest-widget | `/quest-widget [on\ | off\ | reset]` | The session as a dungeon crawl: a room per turn, a monster per tool call, loot when checks pass; the hero is kept across sessions | |
race-widget | `/race-widget [on\ | off\ | clear]` | Parallel subagents as cars on a track, one stride per tool call, with a podium as they finish | |
moon-widget | `/moon-widget [on\ | off\ | north\ | south]` | The real moon right now, drawn for your hemisphere, with a countdown to the next full moon and what it means for your deploy |
Abstract pictures driven by tool activity.
| Plugin | Command | What it shows | |||
|---|---|---|---|---|---|
mosaic-widget | `/mosaic-widget [on\ | off\ | clear]` | One tile per tool call, coloured by tool; failures are red | |
sorting-widget | `/sorting-widget [on\ | off\ | step]` | A bar chart being sorted, one swap per tool call | |
equalizer-widget | `/equalizer-widget [on\ | off]` | Level meters that jump with each tool call and fall back to rest | ||
rain-widget | `/rain-widget [on\ | off]` | Falling code rain that speeds up the busier the turn gets | ||
orbit-widget | `/orbit-widget [on\ | off]` | A small solar system; the planets speed up while tool calls run | ||
life-widget | `/life-widget [on\ | off\ | reset]` | Conway's Game of Life; every tool call drops a glider | |
donut-widget | `/donut-widget [on\ | off]` | The spinning 3D donut; it spins faster while tool calls run | ||
pipes-widget | `/pipes-widget [on\ | off]` | The pipes screensaver; it grows while the session is idle and pauses while Claude works | ||
maze-widget | `/maze-widget [on\ | off\ | new]` | A first-person walk through a maze seeded by the project folder | |
marquee-widget | `/marquee-widget [on\ | off\ | clear\ | <text>]` | An LED ticker scrolling session events; any other text posts your own headline |
Snake, 2048 and Tetris play themselves until you click the board and take the keys.
| Plugin | Command | What it shows | ||
|---|---|---|---|---|
snake-widget | `/snake-widget [on\ | off]` | Snake; it plays itself until you take the keys | |
2048-widget | `/2048-widget [on\ | off]` | 2048; it plays itself until you take the keys | |
tetris-widget | `/tetris-widget [on\ | off]` | Tetris; it plays itself until you take the keys | |
minesweeper-widget | `/minesweeper-widget [on\ | off]` | Minesweeper: click to reveal, right-click or f to flag, r to restart | |
breakout-widget | `/breakout-widget [on\ | off\ | reset]` | A self-playing brick breaker; every tool call adds a row of bricks |
typer-widget | `/typer-widget [on\ | off]` | A typing game: words from your own file names fall, and you type them before they land |
| Plugin | Command | What it shows | |||
|---|---|---|---|---|---|
fortune-widget | `/fortune-widget [on\ | off\ | next]` | A one-line fortune that changes with every turn | |
8ball-widget | `/8ball-widget [on\ | off], /8ball <question>` | /8ball <question> gives an answer of doubtful reliability | ||
badges-widget | `/badges-widget [on\ | off\ | reset]` | Achievements earned across sessions, with a toast when one unlocks | |
sigil-widget | `/sigil-widget [on\ | off\ | clear]` | A pixel emblem generated from this session's activity, beside a gallery of the ones from earlier sessions | |
sound-widget | `/sound-widget [on\ | off\ | mute\ | test]` | A note per tool call, a chord when checks pass, a buzz on failure, with a piano roll (audio plays on macOS only) |
Placement, which widgets are on, and view modes are saved and restored in every session.
/widgets width pet 60 sets how wide one widget's card may grow (the default is 40 columns); /widgets width pet reset puts it back./widgets side docks the cards beside the transcript only in the fullscreen layout (/tui fullscreen). In the default layout it falls back to below the prompt.sound-widget plays audio on macOS only; elsewhere it stays silent and just draws the piano roll.board-widget registers a pin tool that Claude can call, so its description is part of the context while the board is on.watch-widget runs your command through sh -c, falling back to cmd /c.Each plugin under plugins/ is a mod: a manifest, a hooks module and its tests.
claude --plugin-dir plugins # load every plugin from this checkout
claude plugin validate plugins/<name> # check a manifest and hooks module
claude plugin test plugins/<name> # run its tests
Plugin storage ($.store) is read once per session, so a widget that has to see other live sessions keeps a file under its own folder instead ($.plugin.root).
Plugins cannot import from one another, so widgets shares card stacking and the pixel renderer as $.widgets (plugins/widgets/hooks/kit.tsx), which every widget calls.
docs/ is the demo page. bun run site/build.ts bundles every widget's hooks module into docs/mods.js and writes docs/catalog.js from the tables above, so a new widget appears on the page once it has a row here. docs/engine.js is a small stand-in for the mod engine (state, store, clock, commands, a made-up project and a scripted turn), and docs/view.js draws the card trees. bun run site/smoke.ts boots every widget in that engine and runs a turn; a widget that needs an engine call the stand-in lacks shows up there. docs/widgets.js holds recordings from the real interface, shown only if a widget fails to start.
New widgets are made by the Widget Factory in factory/: a crew of Claude Code agents that takes each widget through ideation, design, build, inspection and shipping, with a different agent inspecting than built it. Clone the repository and you can run your own:
https://github.com/user-attachments/assets/6833eb82-8b2e-4b4c-80ca-4194d48d10e7
bun run --cwd factory setup # checks what you need and prepares the floor
bun run --cwd factory floor # the factory floor in your browser
bun run --cwd factory line # opens a Claude Code session that runs the line
https://github.com/user-attachments/assets/d0953871-4935-4fa9-8ab3-f58b51739a17
factory/README.md explains the stations, the crew, the widget standard and how to contribute a widget.
MIT
hooks/register.tsx 489 lines1import { atom, read, update } from 'claude-code'
2import type { AgentInfo, AgentStatus, Elements, EngineInterface, Register, RenderElement, RenderSurface, SessionMessage, Timer } from 'claude-code'
3import type { WidgetsPlace } from 'widgets'
4
5import type { EarpieceRow } from '../types'
6import { fit } from './lib'
7
8type Tags = Pick<Elements[RenderSurface], 'Box' | 'Text'>
9type Said = SessionMessage[] | { deny: string } | null
10type Whisper = EarpieceRow['whisper']
11
12const PANE = 'widgets'
13const CARD_COLUMNS = 40
14const USAGE = 'Usage: /earpiece-widget [on|off]'
15const WHISPER_USAGE = 'Usage: /whisper <number> <note>'
16const HINT = '/whisper <number> <note>'
17const EMPTY = `No agents running. When Claude starts subagents, each gets a row here, and ${HINT} slips one a note.`
18const BLIND = 'Could not read the agents.'
19const OFF = 'Earpiece is off.'
20const FRAME = 'Note from the person running this session, typed while you work (sent with /whisper): '
21const LIVE: readonly AgentStatus[] = ['pending', 'running', 'waiting']
22const BLANK = { rows: [], next: 1, skipped: [], readAt: 0, isBlind: false }
23const UNRUN = { begun: 0, landed: 0 }
24const MOST = 4
25const PERIOD_MS = 3000
26const WAIT_MS = 3000
27const SEEK_MS = 4000
28const GAP_MS = 750
29const LOOKS = 3
30const THROTTLE_MS = 1000
31const WIDE = 30
32const ROOMY = 18
33const HINT_COLUMNS = 24
34const LINE_MAX = 200
35const TOOL_MAX = 10
36const NOTE_MAX = 300
37const REASON_MAX = 120
38const LISTED_MAX = 80
39const DESCRIPTION_MAX = 80
40const site = { plugin: 'widgets', key: 'site' } as const
41const widths = { plugin: 'widgets', key: 'widths' } as const
42const isOn = atom({ plugin: 'earpiece-widget', key: 'isOn' } as const, false)
43const roster = atom({ plugin: 'earpiece-widget', key: 'roster' } as const, BLANK)
44const lap = atom({ plugin: 'earpiece-widget', key: 'lap' } as const, UNRUN)
45
46let timer: Timer | undefined
47
48const flat = (text: string): string => text.replace(/\s+/g, ' ').trim()
49
50const cut = (text: string, room: number): string => {
51 if (text.length <= room) return text
52
53 return room < 1 ? '' : `${text.slice(0, room - 1).trimEnd()}…`
54}
55
56const wrapped = (text: string, room: number): string[] =>
57 text.split(' ').reduce<string[]>((lines, word) => {
58 const last = lines.at(-1)
59
60 return last !== undefined && last.length + 1 + word.length <= room ? [...lines.slice(0, -1), `${last} ${word}`] : [...lines, word]
61 }, [])
62
63const named = (agent: AgentInfo): string => {
64 const name = flat(agent.description) || flat(agent.type) || 'agent'
65
66 return name.length <= DESCRIPTION_MAX ? name : `${name.slice(0, DESCRIPTION_MAX - 1)}…`
67}
68
69const isLive = (row: EarpieceRow): boolean => row.status === 'live' || row.status === 'waiting'
70
71const ranked = (rows: readonly EarpieceRow[]): EarpieceRow[] =>
72 [...rows].sort((one, other) => Number(isLive(other)) - Number(isLive(one)) || one.number - other.number)
73
74const wordOf = (row: EarpieceRow): string => {
75 if (!isLive(row)) return row.status
76
77 return row.tool || (row.status === 'waiting' ? 'waiting' : '')
78}
79
80const lineOf = (said: readonly SessionMessage[]): string => {
81 const last = said.findLast(message => message.role === 'assistant' && message.text.trim() !== '')
82
83 return last === undefined ? '' : (flat(last.text).split(/(?<=[.!?])\s+/).at(-1) ?? '').slice(0, LINE_MAX)
84}
85
86const toolOf = (said: readonly SessionMessage[]): string => {
87 const use = said.findLast(message => message.role === 'assistant')?.toolUses.at(-1)
88 if (use === undefined || use.text !== undefined) return ''
89
90 return (use.tool.startsWith('mcp__') ? use.tool.split('__').slice(2).join('__') || use.tool : use.tool).slice(0, TOOL_MAX)
91}
92
93const weigh = (whisper: Whisper, said: readonly SessionMessage[] | undefined, isOver: boolean): Whisper => {
94 if (whisper?.status !== 'sent') return whisper
95
96 const answers = said?.filter(message => message.role === 'assistant').length
97 if (answers !== undefined && whisper.seen !== null && answers > whisper.seen) return { ...whisper, status: 'heard' }
98
99 return { ...whisper, seen: whisper.seen ?? answers ?? null, status: isOver ? 'missed' : 'sent' }
100}
101
102const statusOf = (agent: AgentInfo | undefined): EarpieceRow['status'] => {
103 if (agent === undefined) return 'done'
104 if (agent.status === 'waiting') return 'waiting'
105 if (LIVE.includes(agent.status)) return 'live'
106 if (agent.status === 'failed') return 'failed'
107
108 return agent.status === 'killed' ? 'stopped' : 'done'
109}
110
111const settle = (row: EarpieceRow, agent: AgentInfo | undefined, said: Said | undefined): EarpieceRow => {
112 const status = isLive(row) ? statusOf(agent) : row.status
113 const isOver = status !== 'live' && status !== 'waiting'
114 const texts = Array.isArray(said) ? said : undefined
115
116 return {
117 ...row,
118 status,
119 line: texts === undefined ? row.line : lineOf(texts),
120 tool: isOver ? '' : texts === undefined ? row.tool : toolOf(texts),
121 isUnread: said === undefined ? row.isUnread : texts === undefined,
122 whisper: weigh(row.whisper, texts, isOver),
123 }
124}
125
126const listing = (row: EarpieceRow): string =>
127 [`${row.number} ${row.description}`, wordOf(row), row.whisper?.status ?? '', row.isUnread ? 'unread' : '', cut(row.line, LISTED_MAX)].filter(part => part !== '').join(' · ')
128
129const face = ({ Box, Text }: Tags, row: EarpieceRow, inner: number): RenderElement[] => {
130 const isOver = !isLive(row)
131 const heard = row.whisper?.status ?? ''
132 const mark = inner >= WIDE ? [wordOf(row), heard].filter(part => part !== '').join(' · ') : heard || wordOf(row)
133 const head = `${row.number}`
134 const room = Math.max(0, inner - head.length - 1 - (mark === '' ? 0 : mark.length + 1))
135
136 return [
137 <Box key={`agent-${row.number}`} justifyContent="space-between">
138 <Text key={`name-${row.number}`} wrap="truncate-end" dimColor={isOver}>
139 <Text bold>{head}</Text>
140 {` ${cut(row.description, room)}`}
141 </Text>
142 <Text key={`mark-${row.number}`} wrap="truncate-end" dimColor={isOver} color={isOver ? undefined : heard === 'heard' ? 'green' : heard === 'sent' ? 'yellow' : 'cyan'}>
143 {mark}
144 </Text>
145 </Box>,
146 <Text key={`line-${row.number}`} wrap="truncate-end" dimColor>
147 {` ${cut(row.line || 'starting…', inner - 2)}`}
148 </Text>,
149 ]
150}
151
152const roll = async ($: EngineInterface): Promise<AgentInfo[] | undefined> => {
153 try {
154 return await $.agent.list()
155 } catch {
156 return undefined
157 }
158}
159
160const peek = async ($: EngineInterface, agentId: string): Promise<Said> => {
161 try {
162 return await $.session.messages({ agentId })
163 } catch {
164 return null
165 }
166}
167
168const slip = async ($: EngineInterface, agentId: string, note: string): Promise<string | undefined> => {
169 try {
170 const kept = await $.session.append({ agentId, message: { type: 'user', content: [{ type: 'text', text: note }] } })
171
172 return typeof kept.uuid === 'string' ? undefined : (kept.deny ?? '')
173 } catch (error) {
174 return error instanceof Error ? error.message : String(error)
175 }
176}
177
178const begin = async ($: EngineInterface): Promise<number> =>
179 (await update($, lap, kept => ({ ...(kept ?? UNRUN), begun: (kept ?? UNRUN).begun + 1 }))).begun
180
181const land = async ($: EngineInterface, ticket: number): Promise<boolean> =>
182 (await update($, lap, kept => ((kept ?? UNRUN).landed > ticket ? (kept ?? UNRUN) : { ...(kept ?? UNRUN), landed: ticket }))).landed === ticket
183
184const outdate = async ($: EngineInterface): Promise<void> => {
185 await land($, await begin($))
186}
187
188const refresh = async ($: EngineInterface): Promise<number> => {
189 if (!(await read($, isOn))) return 0
190
191 const ticket = await begin($)
192 const held = await read($, roster)
193 const listed = await roll($)
194 if (listed === undefined) {
195 if (await land($, ticket)) await update($, roster, kept => ({ ...(kept ?? BLANK), isBlind: true }))
196
197 return 0
198 }
199
200 const agents = new Map(listed.map(agent => [agent.id, agent]))
201 const isRunning = (id: string): boolean => LIVE.includes(agents.get(id)?.status ?? 'completed')
202 const wanted = new Set([
203 ...listed.filter(agent => isRunning(agent.id) && !held.skipped.includes(agent.id) && !held.rows.some(row => row.id === agent.id)).map(agent => agent.id),
204 ...ranked(held.rows.filter(row => isLive(row) && isRunning(row.id))).slice(0, MOST).map(row => row.id),
205 ...held.rows.filter(row => isLive(row) && (!isRunning(row.id) || row.whisper?.status === 'sent')).map(row => row.id),
206 ])
207 const seen = new Map(await Promise.all([...wanted].map(async id => [id, await peek($, id)] as const)))
208 if (!(await land($, ticket))) return 0
209
210 let found = 0
211 await update($, roster, kept => {
212 const base = kept ?? BLANK
213 const fresh = listed.filter(
214 agent => seen.has(agent.id) && isRunning(agent.id) && !base.skipped.includes(agent.id) && !base.rows.some(row => row.id === agent.id),
215 )
216 found = fresh.length
217 const isDenied = (agent: AgentInfo): boolean => {
218 const said = seen.get(agent.id)
219
220 return said !== undefined && said !== null && !Array.isArray(said)
221 }
222 const added = fresh
223 .filter(agent => !isDenied(agent))
224 .map((agent, at) =>
225 settle(
226 { id: agent.id, number: base.next + at, description: named(agent), status: 'live', tool: '', line: '', isUnread: true, whisper: null },
227 agent,
228 seen.get(agent.id),
229 ),
230 )
231
232 return {
233 rows: [...base.rows.map(row => settle(row, agents.get(row.id), seen.get(row.id))), ...added],
234 next: base.next + added.length,
235 skipped: [...base.skipped, ...fresh.filter(isDenied).map(agent => agent.id)],
236 readAt: base.readAt,
237 isBlind: false,
238 }
239 })
240 await sync($)
241
242 return found
243}
244
245const kick = ($: EngineInterface): void => {
246 void refresh($).catch(() => undefined)
247}
248
249const within = async ($: EngineInterface, ms: number, work: () => Promise<unknown>): Promise<void> => {
250 await new Promise<void>(done => {
251 const wait = $.clock.after(ms, done)
252 void work()
253 .catch(() => undefined)
254 .then(() => {
255 wait.cancel()
256 done()
257 })
258 })
259}
260
261const pause = async ($: EngineInterface, ms: number): Promise<void> => {
262 await new Promise<void>(done => {
263 $.clock.after(ms, done)
264 })
265}
266
267const catchUp = async ($: EngineInterface): Promise<void> => within($, WAIT_MS, () => refresh($))
268
269const seek = async ($: EngineInterface, number: number): Promise<void> => {
270 let isSought = true
271 await within($, SEEK_MS, async () => {
272 for (let look = 0; look < LOOKS; look += 1) {
273 if (look > 0) await pause($, GAP_MS)
274 if (!isSought) return
275
276 await refresh($)
277 const held = await read($, roster)
278 if (held.isBlind || held.rows.some(row => row.number === number)) return
279 }
280 })
281 isSought = false
282}
283
284const follow = async ($: EngineInterface): Promise<void> => {
285 for (let look = 0; look < LOOKS; look += 1) {
286 if (look > 0) await pause($, GAP_MS)
287 if (!(await read($, isOn)) || (await refresh($)) > 0) return
288 }
289}
290
291const sync = async ($: EngineInterface): Promise<void> => {
292 const isWanted = (await read($, isOn)) && (await read($, roster)).rows.some(isLive)
293 if (isWanted && timer === undefined) {
294 timer = $.clock.every(PERIOD_MS, () => kick($))
295 }
296 if (!isWanted && timer !== undefined) {
297 timer.cancel()
298 timer = undefined
299 }
300}
301
302const glance = async ($: EngineInterface): Promise<void> => {
303 const now = await $.clock.now()
304 let isDue = false
305 await update($, roster, kept => {
306 const base = kept ?? BLANK
307 isDue = now - base.readAt >= THROTTLE_MS
308
309 return isDue ? { ...base, readAt: now } : base
310 })
311 if (isDue) kick($)
312}
313
314const show = async (
315 $: EngineInterface,
316 { Box, Text }: Tags,
317 beneath: RenderElement,
318 place: WidgetsPlace,
319 columns: number,
320): Promise<RenderElement> => {
321 if (!(await read($, isOn))) return beneath
322 if ((await $.state.get(site)).value !== place) return beneath
323
324 const width = fit((await $.state.get(widths)).value?.['earpiece-widget'] ?? CARD_COLUMNS, columns)
325 const inner = width - 4
326 const held = await read($, roster)
327 const live = held.rows.filter(isLive).length
328 const drawn = ranked(held.rows)
329 const isQuiet = held.isBlind || held.rows.length === 0
330
331 return $.widgets.card({
332 beneath,
333 width,
334 title: 'Earpiece',
335 ...(isQuiet ? {} : { note: live === 0 ? 'done' : live <= 99 ? `${live} live` : inner < ROOMY ? '99+' : '99+ live' }),
336 body: isQuiet ? (
337 <Box key={held.isBlind ? 'blind' : 'empty'} flexDirection="column">
338 {wrapped(held.isBlind ? BLIND : EMPTY, inner).map((line, at) => (
339 <Text key={`say-${at}`} wrap="truncate-end" color={held.isBlind ? 'red' : undefined}>
340 {line}
341 </Text>
342 ))}
343 </Box>
344 ) : (
345 <Box key="agents" flexDirection="column">
346 {drawn.slice(0, MOST).flatMap(row => face({ Box, Text }, row, inner))}
347 {drawn.length > MOST && (
348 <Text key="more" wrap="truncate-end" dimColor>
349 +{drawn.length - MOST} more
350 </Text>
351 )}
352 {live > 0 && inner >= HINT_COLUMNS && (
353 <Text key="hint" wrap="truncate-end" dimColor>
354 {HINT}
355 </Text>
356 )}
357 </Box>
358 ),
359 })
360}
361
362export const register: Register = on => {
363 on('session.start', async ($, e, next) => {
364 await $.command.register({
365 name: 'earpiece-widget',
366 description: 'Toggle the Earpiece card',
367 argumentHint: '[on|off]',
368 })
369 await $.command.register({
370 name: 'whisper',
371 description: 'Slip a note to one running subagent on the Earpiece card',
372 argumentHint: '<number> <note>',
373 immediate: true,
374 })
375 if ((await $.store.get('isOn')) === true) await update($, isOn, () => true)
376 if (await read($, isOn)) await catchUp($)
377 await sync($)
378
379 return next(e)
380 })
381
382 on('command.run', { command: 'earpiece-widget' }, async ($, e) => {
383 const arg = e.args.trim().toLowerCase()
384 if (arg !== '' && arg !== 'on' && arg !== 'off') return { text: USAGE }
385
386 const isShown = await update($, isOn, shown => (arg === '' ? !(shown ?? false) : arg === 'on'))
387 await $.store.set('isOn', isShown)
388 if (isShown) await catchUp($)
389 else {
390 await outdate($)
391 await update($, roster, () => BLANK)
392 }
393 await sync($)
394
395 return { text: isShown ? 'Earpiece on; /widgets places it.' : 'Earpiece off.' }
396 })
397
398 on('command.run', { command: 'whisper' }, async ($, e) => {
399 if (!(await read($, isOn))) return { text: OFF }
400
401 const args = e.args.trim()
402 if (args === '') {
403 await catchUp($)
404 const shown = await read($, roster)
405 if (shown.isBlind) return { text: BLIND }
406
407 return { text: shown.rows.length === 0 ? 'No agents on the card.' : shown.rows.map(listing).join('\n') }
408 }
409
410 const asked = /^(\d{1,4})\s+(\S[\s\S]*)$/.exec(args)
411 if (asked === null) return { text: WHISPER_USAGE }
412
413 const text = asked[2] ?? ''
414 if (text.length > NOTE_MAX) return { text: `A whisper is at most ${NOTE_MAX} characters.` }
415
416 const number = Number(asked[1])
417 if (!(await read($, roster)).rows.some(kept => kept.number === number)) await seek($, number)
418
419 const held = await read($, roster)
420 const row = held.rows.find(kept => kept.number === number)
421 if (row === undefined && !held.isBlind) return { text: `No agent ${number} on the card.` }
422
423 const listed = await roll($)
424 if (listed === undefined) return { text: BLIND }
425 if (row === undefined) return { text: `No agent ${number} on the card.` }
426 if (!listed.some(agent => agent.id === row.id && LIVE.includes(agent.status))) return { text: `Agent ${number} has finished.` }
427
428 const note = `${FRAME}${text}`
429 const refusal = await slip($, row.id, note)
430 if (refusal !== undefined) return { text: `Agent ${number} could not be reached: ${cut(flat(refusal), REASON_MAX) || 'no reason given'}` }
431
432 await outdate($)
433 await update($, roster, kept => ({
434 ...(kept ?? BLANK),
435 rows: (kept ?? BLANK).rows.map(other => (other.id === row.id ? { ...other, whisper: { note, status: 'sent' as const, seen: null } } : other)),
436 }))
437 kick($)
438
439 return { text: `Whispered to agent ${number} (${row.description}). The card says heard once it has answered.` }
440 })
441
442 on('agent.spawn', async ($, e, next) => {
443 const started = await next(e)
444 if (await read($, isOn)) void follow($).catch(() => undefined)
445
446 return started
447 })
448
449 on('tool.call', ($, e, next) => {
450 if (e.agentId !== undefined) {
451 void read($, isOn)
452 .then(shown => (shown ? glance($) : undefined))
453 .catch(() => undefined)
454 }
455
456 return next(e)
457 })
458
459 on('turn.complete', async ($, e, next) => {
460 if (e.agentId !== undefined && (await read($, isOn))) kick($)
461
462 return next(e)
463 })
464
465 on('turn.start', async ($, e, next) => {
466 if (await read($, isOn)) {
467 await update($, roster, kept => {
468 const rows = (kept ?? BLANK).rows.filter(isLive)
469
470 return { ...(kept ?? BLANK), rows, next: rows.length === 0 ? 1 : (kept ?? BLANK).next }
471 })
472 }
473
474 return next(e)
475 })
476
477 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) =>
478 show($, $.ui.resolve(e), await next(e), 'side', e.props.bodyColumns),
479 )
480
481 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) =>
482 e.props.hasSurvey ? next(e) : show($, $.ui.resolve(e), await next(e), 'above', e.props.bodyColumns),
483 )
484
485 on('ui.render', { component: 'PromptHint' }, async ($, e, next) =>
486 show($, $.ui.resolve(e), await next(e), 'below', e.viewport?.columns ?? 80),
487 )
488}
489hooks/lib.ts 45 lines1const MIN_CARD = 20
2const BARS = '▁▂▃▄▅▆▇█'
3
4export const fit = (wanted: number, columns: number): number => Math.min(wanted, Math.max(MIN_CARD, columns))
5
6export const plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? '' : 's'}`
7
8export const span = (ms: number): string => {
9 const seconds = Math.max(0, Math.round(ms / 1000))
10 if (seconds < 60) return `${seconds}s`
11 const minutes = Math.floor(seconds / 60)
12 if (minutes < 60) return `${minutes}m ${String(seconds % 60).padStart(2, '0')}s`
13 const hours = Math.floor(minutes / 60)
14 if (hours < 24) return `${hours}h ${String(minutes % 60).padStart(2, '0')}m`
15
16 return `${Math.floor(hours / 24)}d ${hours % 24}h`
17}
18
19export const spark = (values: readonly number[], width: number): string => {
20 const shown = width > 0 ? values.slice(-width) : []
21 const top = Math.max(...shown, 0)
22
23 return shown
24 .map(value => (top <= 0 ? BARS[0] : BARS[Math.min(BARS.length - 1, Math.round((Math.max(0, value) / top) * (BARS.length - 1)))]))
25 .join('')
26}
27
28export const hash = (text: string): number => {
29 let held = 2166136261
30 for (const letter of text) held = Math.imul(held ^ (letter.codePointAt(0) ?? 0), 16777619)
31
32 return held >>> 0
33}
34
35export const shade = (color: number, factor: number): number =>
36 (Math.round((color >> 16) * factor) << 16) |
37 (Math.round(((color >> 8) & 255) * factor) << 8) |
38 Math.round((color & 255) * factor)
39
40export const folder = (path: string): string => {
41 const flat = path.replaceAll('\\', '/').replace(/\/+$/, '')
42
43 return /^[a-z]:/i.test(flat) ? flat.toLowerCase() : flat
44}
45types/index.d.ts 23 lines1export type EarpieceSwitch = boolean
2
3export type EarpieceRow = {
4 id: string
5 number: number
6 description: string
7 status: 'live' | 'waiting' | 'done' | 'failed' | 'stopped'
8 tool: string
9 line: string
10 isUnread: boolean
11 whisper: { note: string; status: 'sent' | 'heard' | 'missed'; seen: number | null } | null
12}
13
14declare module 'claude-code' {
15 interface PluginState {
16 'earpiece-widget': {
17 isOn: EarpieceSwitch
18 roster: { rows: EarpieceRow[]; next: number; skipped: string[]; readAt: number; isBlind: boolean }
19 lap: { begun: number; landed: number }
20 }
21 }
22}
23