Progress bar above the prompt plus an agents panel (/subagent-progress) for any subagent work: running, finished and planned subagents with model, task…

A Claude Code mod: a progress bar above the prompt and a live panel of subagents, each drawn as a crab whose costume follows the model and effort it runs on. Forked from johnnyvizz's savvy-progress 1.2.0 (MIT, see LICENSE) and renamed from savvy-progress in 2.0.0, since it shows any subagent work, with or without the savvy-flow skill.
a presses it while the band holds the focus). It appears when a subagent of any type starts, or when something reports progress. When the work ends it turns into a green Done row that stays until you dismiss it with ✕./subagent-progress toggles it): running, finished and planned subagents with model, effort, task progress, context, estimated cost and time. It opens by itself whenever a new batch of subagent work starts. Collapse shrinks it to one line per agent.prefers-reduced-motion stops them. In the terminal each card has a small half-block crab beside it (6×2 cells) in the same costumes and colors, and the animation setting controls its motion (see Terminal look).The costume follows what the agent runs on, so every subagent gets one without any special agent definitions:
| Costume | Who | Its prop |
|---|---|---|
| astronaut | Fable at any effort; Opus at high, xhigh or max | floats in a glass dome; the antenna and the star blink |
| detective | Opus at medium or low | the magnifier sweeps and glints |
| engineer | Sonnet at high, xhigh or max | the wrench turns a bolt |
| chef | Sonnet at medium or low | tosses the omelette |
| racer | Haiku | runs at double pace; the checkered flag flutters |
| pirate | the Explore agent, whatever it runs on | the cutlass fences |
| plain crab | any other model | walks |
turn.step), so a general-purpose agent switched to Haiku turns into a racer. An effort not known yet (before the run's first request) or a numeric budget counts as below high.sonnet), full ids and a [1m] suffix all work.savvy-* agent from upstream's savvy-flow follows the same rule from its model and effort. Only while its model is unknown does it fall back to its tier (savvy-fable Fable/high, savvy-heavy Opus/xhigh, savvy-careful Opus/high, savvy-medium Opus/medium, savvy-light Opus/low).general-purpose, savvy-careful), then model and effort.The mapping lives in hooks/crew.ts, a pure module with its own tests.
Upstream shows the bar only for savvy-* workers or an explicit progress report. Here:
Explore, general-purpose, a custom one, ...) opens an auto flow titled "Subagents". Its counters come from spawns and completions, in hooks/auto.ts: every start adds to the total, every finish adds to done, and once every agent of the batch has finished the row closes. Only the batch's own agents count, so an agent left "running" by an interrupted earlier batch cannot hold it open.savvy-* workers as before). Close it mid-batch and it stays closed until the next batch; /subagent-progress or the crew button reopens it any time.progress tool, or a savvy-* worker) is never touched by this: its counters stay the orchestrator's. Once an explicit report arrives it takes the flow over.The desktop gets SVG crabs; the terminal draws its own:
▣ layout. At most the 8 newest running agents animate.● is a braille spinner in its costume's color; there is no crab at one row (a crab that small was unreadable).full, a sparkle runs along it once, then it settles into the green Done row. A flow that was already finished when Claude Code started does not sparkle.▣ in the band: a spinner while running, then ✓, ✗ or a dim ○ for planned, in the agent's costume color, up to 8 and then +n.It needs a font with block elements and braille, as Cascadia and Nerd Fonts have. Why it is built this way, and what the spike on a live terminal showed: DESIGN.md.
/subagent-progressAnyone who types the command needs the new name: /agents-info is gone. It was savvy-progress's command, kept through the 2.0.0 rename; named after the plugin it says where it comes from, like the other mods' commands (/work-report, /prompt-upgrade).
/agents-info to /subagent-progress. It does the same thing: it shows or hides the agents panel. The crew button and the panel's auto-open are unchanged.savvy-progress. The two still draw the same bar and panel, so install only one of them.The desktop drawings are unchanged; this release is the terminal. See Terminal look.
▣, and heat on the context bar.palette and animation, both follow by default: they take agent-pulse's palette and animation level (ember and subtle when it is not installed), so the mods agree. Set your own to stop following. The palette colors the band's bar, its head, the sparkle and the heat; the crabs, spinners and glyphs keep their costume colors. animation: off keeps the terminal still, subtle walks the crabs and pulses the bar, full also moves their props and plays the finish sparkle. It does not reach the desktop, which keeps its own motion and prefers-reduced-motion.follow, the card, compact, the band's glyphs, shading and sparkle, and a check that the desktop draws no terminal-only element.While a flow was active, the bar took the whole band above the prompt: it never drew what the plugins beneath it draw there, so another mod's box (agent-pulse, say) disappeared under it. The bar now stacks above them.
A breaking release: the plugin's name is its tool and settings namespace, so see Moving from savvy-progress.
savvy-progress to subagent-progress: the plugin, the folder, the tool names (mcp__subagent-progress__progress, mcp__subagent-progress__step), the state, the pane and the pluginConfigs key. The /agents-info command is unchanged.savvy-* agents got a prop, and with savvy-flow not installed only the Explore pirate did. Now every subagent does.progress takes a model and effort per task: tier is optional now, and a planned task can say model (sonnet, haiku, a model id) and effort. Planned rows show "Sonnet · high" and wear the matching costume. A savvy tier, or a costume name, still works.progress and step no longer say they are for savvy-flow, and an untitled report is "Subagents".hooks/crew.test.ts (15 tests) and four costume render tests in hooks/render.test.ts.The desktop drawings are unchanged; this release is the terminal's text rendering.
'Svg' in ui too, which sent the band down its desktop path; the plugin test kit drew it as ×N ✕ alone. On the terminal it now always draws its text row: title, bar, phase, percent and crew.1:20 · ≈$0.42 · ctx 12% · 120k, then the step count and its note. A line cut at the pane's edge loses the note, not the cost and time. The panel's totals read the same way.◷ on planned rows (they sit under "Planned" already).▏▎▍▌▋▊▉), so a 6-cell bar moves in about 2% steps. It needs a font with block elements, as Cascadia and Nerd Fonts have.▣ use the theme keys success, error and claude, so they follow the theme and skin. Costume colors stay as they are.✓ in place of ● once the work ends.a, drawn a: ×N.Tasks 1 running, or the Russian labels), so the row no longer wraps at 80 columns.hooks/render.test.ts: the pane and the band drawn on the terminal at several widths, and the band's SVG on desktop (12 tests).The fork itself; see What this fork changes.
mcp__subagent-progress__progress: an orchestrator reports the plan, phase and accepted tasks. Optional: without it the bar follows spawns and completions. Each planned task is a title (the Agent description it will be delegated with) and, optionally, model, effort, a savvy tier, and after.mcp__subagent-progress__step: a worker reports its own steps (done, total, note). A worker that does not report shows its context fill in grey instead. A subagent only calls it if its prompt tells it to.Cost is a rough estimate from token counts and a built-in per-model price table (PRICES in hooks/register.tsx), not a bill.
All three are in /config under this mod.
language: auto (default), en or ru. auto follows Claude Code's language setting, then the system locale, and falls back to English.palette: follow (default), ember, claude, neon or mono. follow uses agent-pulse's palette, or ember when it is not installed. Colors the terminal band's bar, head and sparkle and the context heat.animation: follow (default), off, subtle or full. follow uses agent-pulse's level, or subtle without it. Terminal only. off keeps the crabs, spinners and bar still; subtle walks the crabs and pulses the bar; full also moves their props and plays the finish sparkle.For a mod loaded by hand, set them in ~/.claude/settings.json:
{ "pluginConfigs": { "subagent-progress": { "options": { "language": "ru", "palette": "neon", "animation": "full" } } } }
/plugin install subagent-progress --marketplace afterever/claude-mods
Install instructions for the whole repository are in the repository README.
claude plugin uninstall savvy-progress@afterever-mods
claude plugin marketplace update afterever-mods
claude plugin install subagent-progress@afterever-mods
Then restart Claude Code.
savvy-progress: both draw a progress bar above the prompt and an agents panel, so you would get two of each. This applies to upstream's savvy-progress@claude-kit too. Upstream's command is still /agents-info; here it is /subagent-progress since 2.2.0.language setting under pluginConfigs.savvy-progress has to move to pluginConfigs.subagent-progress.mcp__savvy-progress__progress and __step, which no longer exist; they skip those calls silently, so the flow still runs and the bar follows the spawns. To keep its step reporting, change those two tool names in its skills/ and agents/ files.hooks/register.tsx 1342 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AgentRun, Flow, Panel, Phase, PlannedTask } from '../types'
5import { AUTO_TITLE, isCounted, isSavvyType, onFinish, onSpawn, openKey, startsBatch } from './auto'
6import { COSTUME_COLOR, bareType, costumeOf, plannedCostume, plannedProfile } from './crew'
7import type { Costume } from './crew'
8import { paletteOf, resolveLook, shadeOf, shimmerOf } from './palette'
9import type { Look } from './palette'
10import { VERSION } from './version'
11
12const flow = atom({ plugin: 'subagent-progress', key: 'flow' } as const, null)
13const agents = atom({ plugin: 'subagent-progress', key: 'agents' } as const, [])
14const panel = atom({ plugin: 'subagent-progress', key: 'panel' } as const, {
15 isCompact: false,
16 isDoneCollapsed: false,
17 autoOpenedFor: '',
18})
19const now = atom({ plugin: 'subagent-progress', key: 'now' } as const, 0)
20
21const TOOL = 'mcp__subagent-progress__progress'
22const STEP_TOOL = 'mcp__subagent-progress__step'
23const PANE = 'subagents'
24const PHASES: readonly Phase[] = ['plan', 'design', 'delegate', 'review', 'close']
25const ACCENT = '#8f8cf4'
26const DONE = '#5fbf8f'
27
28type ProgressInput = {
29 title?: string
30 total?: number
31 done?: number
32 phase?: Phase
33 finished?: boolean
34 tasks?: { title?: string; tier?: string; model?: string; effort?: string; after?: number[] }[]
35}
36
37// ---------------------------------------------------------------------------
38// Language: the `language` option, else Claude Code's `language` setting, else the
39// process locale; English when nothing says Russian.
40
41type Lang = 'en' | 'ru'
42
43const STRINGS = {
44 en: {
45 pane: 'Agents',
46 cost: 'Cost',
47 tokens: 'Tokens',
48 time: 'Time',
49 collapse: 'Collapse',
50 expand: 'Expand',
51 running: 'Running',
52 finished: 'Finished',
53 planned: 'Planned',
54 empty: 'No subagents yet.',
55 round: 'round',
56 failed: 'error',
57 after: 'after',
58 tokensWord: 'tokens',
59 agentsCount: 'agents',
60 isRunning: 'running',
61 isFinished: 'finished',
62 isPlanned: 'planned',
63 opened: 'Agents panel opened.',
64 closed: 'Agents panel closed.',
65 done: 'Done',
66 plan: 'Plan',
67 design: 'Design',
68 tasks: 'Tasks',
69 review: 'Review',
70 busy: 'running',
71 },
72 ru: {
73 pane: 'Агенты',
74 cost: 'Стоимость',
75 tokens: 'Токены',
76 time: 'Время',
77 collapse: 'Свернуть',
78 expand: 'Развернуть',
79 running: 'Работают',
80 finished: 'Завершены',
81 planned: 'Запланированы',
82 empty: 'Субагентов пока нет.',
83 round: 'раунд',
84 failed: 'ошибка',
85 after: 'после',
86 tokensWord: 'токенов',
87 agentsCount: 'агентов',
88 isRunning: 'работает',
89 isFinished: 'завершён',
90 isPlanned: 'запланирована',
91 opened: 'Панель агентов открыта.',
92 closed: 'Панель агентов закрыта.',
93 done: 'Готово',
94 plan: 'План',
95 design: 'Дизайн',
96 tasks: 'Задачи',
97 review: 'Ревью',
98 busy: 'в работе',
99 },
100} as const
101
102// Module scope is fine here: session.start sets it again on every (re)load.
103let lang: Lang = 'en'
104const tr = () => STRINGS[lang]
105
106// The terminal look's palette and animation level; register() and session.start set it again on every (re)load.
107let look: Look = { palette: 'ember', level: 'subtle' }
108// The `palette` and `animation` options, for refreshLook to read; register() sets them.
109let configured: { palette?: unknown; animation?: unknown } = {}
110
111const isRussian = (v: unknown): boolean => typeof v === 'string' && /^(ru|russian|рус)/i.test(v.trim())
112
113async function detectLang($: EngineInterface, option: unknown): Promise<Lang> {
114 if (option === 'en' || option === 'ru') return option
115 try {
116 const settings = (await $.settings.read()) as Record<string, unknown>
117 if (typeof settings.language === 'string' && settings.language.trim()) return isRussian(settings.language) ? 'ru' : 'en'
118 } catch {
119 // No settings: fall through to the locale.
120 }
121 const locale = (await $.env.get('LC_ALL')) || (await $.env.get('LC_MESSAGES')) || (await $.env.get('LANG'))
122 return isRussian(locale) ? 'ru' : 'en'
123}
124
125const blank = (): Flow => ({
126 title: AUTO_TITLE,
127 total: 0,
128 done: 0,
129 running: 0,
130 phase: 'plan',
131 isFinished: false,
132 tasks: [],
133})
134
135const isNewFlow = (prev: Flow | null, input: ProgressInput): boolean =>
136 !prev || prev.isFinished || (input.title !== undefined && input.title.trim() !== prev.title)
137
138const cleanTasks = (tasks: ProgressInput['tasks']): PlannedTask[] | undefined =>
139 tasks
140 ?.filter(t => t.title?.trim())
141 .map(t => ({
142 title: (t.title ?? '').trim(),
143 tier: (t.tier ?? '').replace(/^savvy-/, '').trim().toLowerCase(),
144 model: t.model?.trim() || undefined,
145 effort: t.effort?.trim().toLowerCase() || undefined,
146 after: (t.after ?? []).filter(n => Number.isInteger(n) && n > 0),
147 }))
148
149const merge = (prev: Flow | null, input: ProgressInput): Flow => {
150 // A new title means a new flow: never carry counters over from an earlier one.
151 const base = isNewFlow(prev, input) || !prev ? blank() : { ...blank(), ...prev }
152 const tasks = cleanTasks(input.tasks) ?? base.tasks
153 const total = Math.max(0, Math.round(input.total ?? (input.tasks ? tasks.length : base.total)))
154 const done = Math.min(total || Infinity, Math.max(0, Math.round(input.done ?? base.done)))
155 const phase = input.phase && PHASES.includes(input.phase) ? input.phase : base.phase
156 return {
157 ...base,
158 title: input.title?.trim() || base.title,
159 total,
160 done,
161 phase: input.finished ? 'close' : phase,
162 isFinished: input.finished === true,
163 tasks,
164 // An explicit report takes the flow over from the spawn-derived one.
165 isAuto: false,
166 }
167}
168
169const label = (f: Flow): string => {
170 const s = tr()
171 if (f.isFinished) return s.done
172 if (f.phase === 'plan') return s.plan
173 if (f.phase === 'design') return s.design
174 const count = f.total ? `${f.done}/${f.total}` : `${f.running} ${s.busy}`
175 return `${f.phase === 'review' ? s.review : s.tasks} ${count}`
176}
177
178const ratio = (f: Flow): number => (f.isFinished ? 1 : f.total ? f.done / f.total : 0)
179
180// Deterministic noise so the dither does not shimmer between redraws.
181const noise = (x: number, y: number): number => {
182 const s = Math.sin(x * 12.9898 + y * 78.233) * 43758.5453
183 return s - Math.floor(s)
184}
185
186// The whole row is one SVG: the desktop wraps sibling elements onto new lines,
187// so title, bar, percent and the crab live in one drawing; only the count and
188// the dismiss are Buttons beside it.
189const H = 22
190const BAR_H = 16
191const CRAB_W = 26
192const CELL = 3
193const FONT = "-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',sans-serif"
194
195const xml = (s: string): string =>
196 s.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] ?? c)
197
198const clip = (s: string, max: number): string => (s.length > max ? s.slice(0, Math.max(1, max - 1)) + '…' : s)
199
200// Rough advance of system UI text, in em; good enough to size the title's slot.
201const charEm = (ch: string): number =>
202 /[\s.,:;'|!il1()[\]]/.test(ch) ? 0.3 : /[A-ZА-ЯЁmwшщжюМШЩЖЮ@%]/.test(ch) ? 0.72 : 0.56
203
204const textWidth = (s: string, size: number): number => [...s].reduce((w, ch) => w + charEm(ch) * size, 0)
205
206// Cuts `s` to fit `maxW` pixels, with an ellipsis when it had to cut.
207const fitText = (s: string, size: number, maxW: number): string => {
208 if (textWidth(s, size) <= maxW) return s
209 let out = ''
210 for (const ch of s) {
211 if (textWidth(out + ch + '…', size) > maxW) break
212 out += ch
213 }
214 return out + '…'
215}
216
217const rowSvg = (f: Flow, W: number, isWorking: boolean): string => {
218 // The title takes what it needs, up to 40% of the row; the bar takes the rest.
219 const title = fitText(f.title, 13, Math.max(60, W * 0.4))
220 const BAR_X = Math.round(16 + textWidth(title, 13) + 12)
221 const BAR_W = Math.max(60, W - BAR_X - 46 - CRAB_W)
222 const color = f.isFinished ? DONE : ACCENT
223 const y0 = (H - BAR_H) / 2
224 const fillW = Math.round(BAR_W * ratio(f))
225 const runW = f.total ? Math.round((BAR_W * Math.min(f.total, f.done + f.running)) / f.total) : 0
226 const dots: string[] = []
227
228 // Dithered fill: sparse at the start, dense toward the head.
229 const cols = Math.floor(fillW / CELL)
230 const rows = Math.floor(BAR_H / CELL)
231 for (let c = 0; c < cols; c++) {
232 const density = 0.35 + 0.6 * Math.pow(c / Math.max(1, cols), 1.2)
233 for (let r = 0; r < rows; r++) {
234 if (noise(c, r) < density) dots.push(`<rect class="t${Math.floor(noise(r, c) * 4)}" x="${c * CELL + 1}" y="${r * CELL + 1}" width="2" height="2"/>`)
235 }
236 }
237 // Handed to workers, not yet accepted: a faint second layer.
238 const faint: string[] = []
239 for (let c = cols; c < Math.floor(runW / CELL); c++) {
240 for (let r = 0; r < rows; r++) {
241 if (noise(c + 7, r + 3) < 0.2) faint.push(`<rect class="t${Math.floor(noise(r + 5, c) * 4)}" x="${c * CELL + 1}" y="${r * CELL + 1}" width="1.7" height="1.7"/>`)
242 }
243 }
244
245 const ticks: string[] = []
246 for (let i = 1; i < f.total; i++) {
247 const x = Math.round((BAR_W * i) / f.total)
248 if (x > fillW + 4) ticks.push(`<rect x="${x}" y="${BAR_H / 2 - 4}" width="1.5" height="8" rx="0.75"/>`)
249 }
250
251 const text = label(f)
252 const pillW = Math.round(18 + text.length * 6.6)
253 const pillX = Math.max(0, Math.min(BAR_W - pillW, fillW - pillW))
254 const percent = `${Math.round(ratio(f) * 100)}%`
255
256 return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
257<style>
258.t{fill:#1f1f1f}.m{fill:#8a8a8a}.k{fill:#e4e4e2}.tk{fill:#b4b4b0}
259@media (prefers-color-scheme: dark){.t{fill:#ececec}.m{fill:#9a9a9a}.k{fill:#2c2c2c}.tk{fill:#5a5a5a}}
260/* Pixels twinkle in four out-of-phase groups; a finished bar settles to a slow glow. */
261.t0,.t1,.t2,.t3{animation:tw ${f.isFinished ? 3.2 : 2.2}s ease-in-out infinite}
262.t1{animation-duration:${f.isFinished ? 3.8 : 2.8}s;animation-delay:-.7s}.t2{animation-duration:${f.isFinished ? 4.4 : 1.9}s;animation-delay:-1.3s}.t3{animation-duration:${f.isFinished ? 3.5 : 3.3}s;animation-delay:-.4s}
263@keyframes tw{0%,100%{opacity:1}50%{opacity:${f.isFinished ? 0.8 : 0.3}}}
264@media (prefers-reduced-motion: reduce){.t0,.t1,.t2,.t3{animation:none}}
265</style>
266<defs><clipPath id="c"><rect x="0" y="0" width="${BAR_W}" height="${BAR_H}" rx="${BAR_H / 2}"/></clipPath></defs>
267<circle cx="5" cy="${H / 2}" r="4" fill="${color}"/>
268<text class="t" x="16" y="${H / 2 + 4.5}" font-family="${FONT}" font-size="13" font-weight="500">${xml(title)}</text>
269<g transform="translate(${BAR_X},${y0})">
270<rect class="k" width="${BAR_W}" height="${BAR_H}" rx="${BAR_H / 2}"/>
271<g clip-path="url(#c)">
272<g fill="${color}">${dots.join('')}</g>
273<g fill="${color}" opacity="0.45">${faint.join('')}</g>
274<g class="tk">${ticks.join('')}</g>
275</g>
276<rect x="${pillX}" width="${pillW}" height="${BAR_H}" rx="${BAR_H / 2}" fill="${color}"/>
277<text x="${pillX + pillW / 2}" y="${BAR_H / 2 + 4}" text-anchor="middle" font-family="${FONT}" font-size="11" font-weight="600" fill="#ffffff">${xml(text)}</text>
278</g>
279<text class="m" x="${W - CRAB_W - 6}" y="${H / 2 + 4.5}" text-anchor="end" font-family="${FONT}" font-size="12.5" font-variant-numeric="tabular-nums">${percent}</text>
280${CRAB_CSS}${crab(W - CRAB_W + 1, 0, 'other', false, isWorking, 0.8)}
281</svg>`
282}
283
284// Text bar for the terminal, in eighths of a cell: a 6-cell bar still moves in ~2% steps.
285const EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉']
286const barCells = (fraction: number, width: number): string[] => {
287 const eighths = Math.round(Math.max(0, Math.min(1, fraction)) * width * 8)
288 const full = Math.floor(eighths / 8)
289 const part = EIGHTHS[eighths % 8]
290 return [...Array<string>(full).fill('█'), ...(part ? [part] : []), ...Array<string>(Math.max(0, width - full - (part ? 1 : 0))).fill('░')]
291}
292
293const bar = (fraction: number, width: number): string => barCells(fraction, width).join('')
294
295// The terminal look (DESIGN.md): the spinner's frames, and how many crabs, crew glyphs and spinners to draw.
296const SPIN = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
297const SPIN_MS = 100
298const MAX_CREW = 8
299const MAX_ANIMATED = 8
300// Narrower than this the card drops its crab and keeps the old text layout.
301const CRAB_MIN_COLS = 24
302// The context bar of a worker that reports no steps turns amber from here, then red.
303const HEAT_AT = [70, 90] as const
304
305// A render that sees the flow go from running to finished counts one finish, which keys the sparkle so it plays once.
306let isFlowSeenRunning = false
307let finishSeq = 0
308// The finish the sparkle plays for, 0 when this flow did not finish in sight.
309let sweepKey = 0
310
311// ---------------------------------------------------------------------------
312// Agents panel: every subagent of the session, plus the tasks the flow planned.
313
314const colorOf = (costume: Costume): string => COSTUME_COLOR[costume]
315
316// "Opus · xhigh": what a planned task will run on, when it says (its model, or its savvy tier).
317const profileLabel = (p: PlannedTask): string => {
318 const { model, effort } = plannedProfile(p)
319 if (!model) return ''
320 const name = modelName(model)
321 return [name.charAt(0).toUpperCase() + name.slice(1), effort].filter(Boolean).join(' · ')
322}
323
324// USD per million tokens: input, output, cache read, cache write (5-minute TTL).
325// The engine reports tokens, not money, so the panel's cost is an estimate.
326const PRICES: [RegExp, [number, number, number, number]][] = [
327 [/fable|mythos/, [10, 50, 0.25, 12.5]],
328 [/opus-5-5/, [4, 20, 0.2, 5]],
329 [/opus/, [5, 25, 0.5, 6.25]],
330 [/sonnet/, [2, 10, 0.2, 2.5]],
331 [/haiku/, [1, 5, 0.1, 1.25]],
332]
333
334type Usage = {
335 input_tokens: number
336 output_tokens: number
337 cache_read_input_tokens: number
338 cache_creation_input_tokens: number
339}
340
341const priceOf = (model: string): [number, number, number, number] =>
342 PRICES.find(([re]) => re.test(model.toLowerCase()))?.[1] ?? [4, 20, 0.2, 5]
343
344const costOf = (model: string, u: Usage): number => {
345 const [i, o, r, w] = priceOf(model)
346 return (
347 ((u.input_tokens || 0) * i +
348 (u.output_tokens || 0) * o +
349 (u.cache_read_input_tokens || 0) * r +
350 (u.cache_creation_input_tokens || 0) * w) /
351 1e6
352 )
353}
354
355const windowOf = (model: string): number => (/haiku/i.test(model) ? 200_000 : 1_000_000)
356
357const modelName = (id: string): string => {
358 const m = /(fable|mythos|opus|sonnet|haiku)-(\d+)(?:-(\d{1,2})(?!\d))?/i.exec(id)
359 const [, family = '', major = '', minor] = m ?? []
360 if (!family) return id.replace(/^claude-/, '').replace(/\[.*\]$/, '') || '—'
361 return `${family.charAt(0).toUpperCase()}${family.slice(1).toLowerCase()} ${major}${minor ? '.' + minor : ''}`
362}
363
364const norm = (s: string): string => s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim()
365
366const fmtTokens = (n: number): string =>
367 n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : `${Math.round(n)}`
368
369const fmtCost = (usd: number): string => `$${usd < 10 ? usd.toFixed(2) : usd.toFixed(1)}`
370
371const fmtTime = (ms: number): string => {
372 const s = Math.max(0, Math.round(ms / 1000))
373 const h = Math.floor(s / 3600)
374 const m = Math.floor((s % 3600) / 60)
375 const ss = String(s % 60).padStart(2, '0')
376 return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`
377}
378
379const elapsed = (a: AgentRun, at: number): number => (a.endedAt ?? Math.max(at, a.startedAt)) - a.startedAt
380
381type Planned = PlannedTask & { n: number }
382
383const plannedOf = (f: Flow | null, list: AgentRun[]): Planned[] => {
384 if (!f || f.isFinished) return []
385 const started = new Set(list.map(a => norm(a.description)))
386 return (f.tasks ?? []).map((t, i) => ({ ...t, n: i + 1 })).filter(t => !started.has(norm(t.title)))
387}
388
389const totals = (list: AgentRun[], at: number) => {
390 const cost = list.reduce((s, a) => s + a.costUsd, 0)
391 const tokens = list.reduce((s, a) => s + a.tokens, 0)
392 const start = Math.min(...list.map(a => a.startedAt))
393 const end = Math.max(...list.map(a => a.endedAt ?? Math.max(at, a.startedAt)))
394 return { cost, tokens, time: list.length ? end - start : 0 }
395}
396
397// --- desktop drawings: each row is one SVG, as the band above the prompt is.
398
399const PANE_CSS = `<style>
400.t{fill:#1f1f1f}.s{fill:#6b6b68}.m{fill:#9a9a96}.k{fill:#ecebe8}.ln{stroke:#e4e4e1}.tile{fill:#f4f3f0}
401@media (prefers-color-scheme: dark){.t{fill:#ececec}.s{fill:#a8a8a4}.m{fill:#7d7d79}.k{fill:#2c2c2b}.ln{stroke:#333331}.tile{fill:#262625}}
402.live{animation:p 1.6s ease-in-out infinite}@keyframes p{50%{opacity:.3}}
403@media (prefers-reduced-motion: reduce){.live{animation:none}}
404</style>`
405
406// Pixel Clawd from DockCrab (Clawdy): a 24×18 crab on a 30×28 grid, one costume per kind
407// of agent (hooks/crew.ts). The body keeps the brand clay; the costume's color lives in its accent.
408const CLAY = '#D97757'
409const INK = '#1F1E1D'
410
411// `cls` puts a pixel in a named group: `bd` (the default) is the body and its
412// costume, `la`/`lb` the leg pairs, anything else a prop with its own motion.
413type Fill = (x: number, y: number, w: number, h: number, c: string, cls?: string) => void
414
415const stamp = (f: Fill, x: number, y: number, rows: string[], map: Record<string, string>, cls?: string): void =>
416 rows.forEach((row, dy) => [...row].forEach((ch, dx) => map[ch] && f(x + dx, y + dy, 1, 1, map[ch] ?? '', cls)))
417
418// `armCls` lets a raised claw travel with the prop it holds.
419const crabBody = (f: Fill, armFront = 0, armCls?: string): void => {
420 f(7, 10, 16, 12, CLAY)
421 f(3, 14, 4, 4, CLAY)
422 f(23, 14 + armFront, 4, 4, CLAY, armCls)
423 f(9, 12, 2, 2, INK)
424 f(19, 12, 2, 2, INK)
425 f(7, 22, 2, 4, CLAY, 'la')
426 f(17, 22, 2, 4, CLAY, 'la')
427 f(11, 22, 2, 4, CLAY, 'lb')
428 f(21, 22, 2, 4, CLAY, 'lb')
429}
430
431// Pure CSS, run by the compositor: no redraws. Periods divide one second, so the
432// once-a-second redraw of a running row restarts them in phase. Every crab walks;
433// each costume adds its prop's own motion on top.
434const CRAB_CSS = `<style>
435.run .la{animation:st .5s steps(1) infinite}.run .lb{animation:st .5s steps(1) infinite -.25s}
436.run .bd{animation:bob .5s steps(1) infinite -.125s}
437.run g{transform-box:fill-box}
438@keyframes st{50%{transform:translateY(-1px)}}@keyframes bob{50%{transform:translateY(1px)}}
439.c-astronaut.run{animation:float 1s ease-in-out infinite}
440.c-astronaut.run .la,.c-astronaut.run .lb,.c-astronaut.run .bd{animation:none}
441.c-astronaut.run .ant{animation:blink 1s steps(1) infinite}
442.c-astronaut.run .star{animation:blink .5s steps(1) infinite -.25s}
443@keyframes float{50%{transform:translateY(-2px)}}@keyframes blink{50%{opacity:.15}}
444.c-detective.run .it{animation:scan 1s steps(1) infinite}
445.c-detective.run .gl{animation:blink 1s steps(1) infinite -.5s}
446@keyframes scan{25%{transform:translate(-1px,1px)}50%{transform:translate(-2px,2px)}75%{transform:translate(-1px,1px)}}
447.c-engineer.run .it{transform-origin:100% 100%;animation:twist .5s ease-in-out infinite}
448@keyframes twist{50%{transform:rotate(-35deg)}}
449.c-chef.run .pan{transform-origin:0 50%;animation:tilt 1s ease-in-out infinite}
450.c-chef.run .egg{animation:flip 1s ease-in-out infinite}
451@keyframes tilt{20%,40%{transform:rotate(-12deg)}}@keyframes flip{30%{transform:translateY(-5px) scaleY(-1)}60%{transform:translateY(0)}}
452.c-racer.run .la{animation-duration:.25s}.c-racer.run .lb{animation-duration:.25s;animation-delay:-.125s}
453.c-racer.run .flag{transform-origin:0 50%;animation:wave .25s steps(1) infinite}
454@keyframes wave{50%{transform:skewY(-12deg) scaleX(.85)}}
455.c-pirate.run .it{transform-origin:50% 100%;animation:fence .5s ease-in-out infinite}
456@keyframes fence{50%{transform:rotate(25deg)}}
457@media (prefers-reduced-motion: reduce){.run,.run g{animation:none!important}}
458</style>`
459
460const WARDROBE: Record<Costume, (f: Fill, t: string) => void> = {
461 // Fable, Opus at high or above: astronaut in a glass dome; floats instead of walking, the antenna and the star blink.
462 astronaut: (f, t) => {
463 crabBody(f)
464 f(6, 7, 18, 1, '#E6E8EE'); f(5, 8, 1, 14, '#E6E8EE'); f(24, 8, 1, 14, '#E6E8EE'); f(6, 22, 18, 1, '#C9CCD2')
465 f(6, 8, 18, 14, 'rgba(169,214,245,.32)'); f(8, 9, 2, 1, '#fff'); f(8, 10, 1, 2, '#fff')
466 f(14, 4, 2, 3, '#C9CCD2'); f(14, 2, 2, 2, t, 'ant'); f(13, 18, 4, 2, t)
467 f(27, 3, 1, 3, '#F5C542', 'star'); f(26, 4, 3, 1, '#F5C542', 'star')
468 },
469 // Opus below high: detective with a deerstalker; the magnifier sweeps and glints.
470 detective: (f, t) => {
471 crabBody(f, -4, 'it')
472 stamp(f, 6, 3, ['......bbbbbb......', '....bbcbbcbbbb....', '...bbbbbbbbbbbb...', '..bcbbcbbcbbcbbb..', '.bbbbbbbbbbbbbbbb.', 'dddddddddddddddddd'], { b: '#7A4A26', c: '#A0703F', d: '#5A3519' })
473 f(6, 9, 18, 1, t)
474 stamp(f, 23, 1, ['.kkk.', 'k...k', 'k...k', 'k...k', '.kkk.'], { k: '#3A3A3C' }, 'it')
475 f(24, 2, 3, 3, 'rgba(169,214,245,.7)', 'it'); f(25, 6, 1, 4, '#7A4A26', 'it'); f(24, 2, 1, 1, '#fff', 'gl')
476 },
477 // Sonnet at high or above: engineer in a hard hat; the wrench turns a bolt.
478 engineer: (f, t) => {
479 crabBody(f)
480 stamp(f, 6, 4, ['.....yyyyyyyy.....', '...yyyyyhhyyyyy...', '..yyyyyyhhyyyyyy..', '..yyyyyyhhyyyyyy..', '.yyyyyyyhhyyyyyyy.', 'dddddddddddddddddd'], { y: '#F5C542', h: '#FBE08A', d: '#C99A1E' })
481 f(13, 5, 4, 2, t)
482 stamp(f, 0, 10, ['.s.s', 'sss.', '.s..', '.s..'], { s: '#8E929A' }, 'it')
483 },
484 // Sonnet below high: chef, the toque traced from DockCrab's Sprites.chefHat; tosses the omelette.
485 chef: (f, t) => {
486 crabBody(f, -4, 'pan')
487 stamp(f, 6, 0, ['........lll.......', '.......lllll......', '.wwwwgwwwwwwgwwwww', 'wwwwwwwwwwwwwwwwww', 'wwwwwwwwwwwwwwwwww', 'wwwwwgwwwwwggwwwww', '.wwwwgwwwwwggwwwww', '.dddbbbbbbbbbbbbb.', '.dddbbbbbbbbbbbbb.', '.dddbbbbbbbbbbbbb.'], { w: '#F4F3EE', l: '#F7F6F2', g: '#D2D1C8', b: t, d: '#B45F43' })
488 f(22, 8, 7, 2, '#4A4A48', 'pan'); f(26, 10, 1, 1, '#4A4A48', 'pan'); f(24, 7, 3, 1, '#F5B731', 'egg')
489 },
490 // Haiku: racer in a helmet; runs at double pace, the checkered flag flutters.
491 racer: (f, t) => {
492 crabBody(f, -4)
493 stamp(f, 6, 5, ['....rrrrrrrrrr....', '..rrrrrrwwrrrrrr..', '.rrrrrrrwwrrrrrrr.', '.rrrrrrrwwrrrrrrr.', '.rrrrrrrwwrrrrrrr.', '.kkkkkkkkkkkkkkkkr'], { r: t, w: '#F8F6F1', k: INK })
494 f(25, 1, 1, 9, '#8E929A')
495 stamp(f, 26, 1, ['wkwk', 'kwkw', 'wkwk'], { w: '#F8F6F1', k: INK }, 'flag')
496 },
497 // The Explore agent: pirate scouting the code; the cutlass fences.
498 pirate: f => {
499 crabBody(f)
500 stamp(f, 5, 3, ['.kk..............kk.', '.kkk....kkkk....kkk.', '..kkkkkkkwwkkkkkkk..', '..kkkkkkkkkkkkkkkk..', '.gggggggggggggggggg.'], { k: '#55514C', w: '#F8F6F1', g: '#F5C542' })
501 f(7, 11, 11, 1, INK); f(18, 11, 4, 3, INK)
502 f(27, 6, 1, 9, '#C9CCD2', 'it'); f(26, 15, 3, 1, '#7A4A26', 'it')
503 },
504 other: f => crabBody(f),
505}
506
507const CRAB_SCALE = 1.1
508
509// Body and props nest inside `bd` so a prop rides the bob and adds its own motion;
510// legs stay outside it and step on their own.
511const crab = (x: number, y: number, costume: Costume, dim = false, isWalking = false, scale = CRAB_SCALE): string => {
512 const groups = new Map<string, string[]>([['bd', []]])
513 const f: Fill = (cx, cy, w, h, c, cls = 'bd') => {
514 if (!groups.has(cls)) groups.set(cls, [])
515 groups.get(cls)?.push(`<rect x="${cx}" y="${cy}" width="${w}" height="${h}" fill="${c}"/>`)
516 }
517 const draw = WARDROBE[costume] ?? ((g: Fill) => crabBody(g))
518 draw(f, colorOf(costume))
519 const group = (cls: string) => `<g class="${cls}">${(groups.get(cls) ?? []).join('')}</g>`
520 const props = [...groups.keys()].filter(k => k !== 'bd' && k !== 'la' && k !== 'lb')
521 const body = `<g class="bd">${(groups.get('bd') ?? []).join('')}${props.map(group).join('')}</g>`
522 return `<g transform="translate(${x},${y}) scale(${scale})" opacity="${dim ? 0.45 : 1}" shape-rendering="crispEdges"><g class="c-${costume}${isWalking ? ' run' : ''}">${body}${group('la')}${group('lb')}</g></g>`
523}
524
525const statusMark = (x: number, y: number, status: string, color: string): string => {
526 if (status === 'running') return `<circle class="live" cx="${x}" cy="${y}" r="3.5" fill="${color}"/>`
527 if (status === 'done') return `<path d="M${x - 5} ${y}l3.5 3.5 6.5-7" fill="none" stroke="#3B9C5F" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>`
528 if (status === 'failed') return `<path d="M${x - 4} ${y - 4}l8 8M${x + 4} ${y - 4}l-8 8" stroke="#D0453F" stroke-width="1.8" stroke-linecap="round"/>`
529 return `<circle cx="${x}" cy="${y}" r="5" fill="none" stroke="#9a9a96" stroke-width="1.4"/><path d="M${x} ${y - 2.5}v2.8l1.8 1.2" fill="none" stroke="#9a9a96" stroke-width="1.4" stroke-linecap="round"/>`
530}
531
532const svg = (W: number, H: number, body: string): string =>
533 `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">${PANE_CSS}${CRAB_CSS}${body}</svg>`
534
535// The pane's own title already says "Agents": the header names the flow, if any.
536const headerSvg = (W: number, title: string, t: ReturnType<typeof totals>): string => {
537 const s = tr()
538 const gap = 6
539 const tw = (W - gap * 2) / 3
540 const top = title ? 28 : 0
541 const tile = (i: number, k: string, v: string) =>
542 `<rect class="tile" x="${i * (tw + gap)}" y="${top}" width="${tw}" height="40" rx="8"/>
543<text class="s" x="${i * (tw + gap) + 9}" y="${top + 16}" font-family="${FONT}" font-size="11">${k}</text>
544<text class="t" x="${i * (tw + gap) + 9}" y="${top + 33}" font-family="${FONT}" font-size="15" font-weight="600" font-variant-numeric="tabular-nums">${v}</text>`
545 return svg(
546 W,
547 headerHeight(title),
548 `${title ? `<text class="t" x="0" y="15" font-family="${FONT}" font-size="14" font-weight="600">${xml(fitText(title, 14, W))}</text>` : ''}
549${tile(0, s.cost, '≈' + fmtCost(t.cost))}${tile(1, s.tokens, fmtTokens(t.tokens))}${tile(2, s.time, fmtTime(t.time))}`,
550 )
551}
552
553const headerHeight = (title: string): number => (title ? 72 : 44)
554
555// The task's own progress when the worker reports steps; a finished run is full.
556const progressOf = (a: AgentRun): number | null => {
557 if (a.status === 'done') return 1
558 if (a.stepTotal) return Math.min(1, (a.stepDone ?? 0) / a.stepTotal)
559 return null
560}
561
562const ctxOf = (a: AgentRun): number => (a.contextMax ? Math.min(100, Math.round((a.contextTokens / a.contextMax) * 100)) : 0)
563
564const agentSvg = (W: number, a: AgentRun, at: number): string => {
565 const s = tr()
566 const costume = costumeOf(a)
567 const color = colorOf(costume)
568 const ctx = ctxOf(a)
569 const textW = W - 42 - 22
570 const meta = [a.effort ? `${modelName(a.model)} · ${a.effort}` : modelName(a.model)]
571 if (a.round > 1) meta.push(`${s.round} ${a.round}`)
572 if (a.status === 'failed') meta.push(s.failed)
573 const barW = textW
574 const progress = progressOf(a)
575 const stats = `ctx ${ctx}% · ${fmtTokens(a.contextTokens)} ≈${fmtCost(a.costUsd)} ${fmtTime(elapsed(a, at))}`
576 const steps = a.stepTotal ? `${a.stepDone ?? 0}/${a.stepTotal}${a.stepNote ? ' · ' + a.stepNote : ''}` : ''
577 const stepsW = Math.max(0, barW - textWidth(stats, 11) - 12)
578 // Without reported steps the bar falls back to the context, drawn grey.
579 const fillW = Math.round(barW * (progress ?? ctx / 100))
580 return svg(
581 W,
582 66,
583 `${crab(0, 14, costume, false, a.status === 'running')}
584<text class="t" x="42" y="18" font-family="${FONT}" font-size="13" font-weight="600">${xml(fitText(a.description || a.type, 13, textW))}</text>
585<text x="42" y="34" font-family="${FONT}" font-size="11"><tspan fill="${color}">${xml(bareType(a.type))}</tspan><tspan class="s"> ${xml(meta.join(' · '))}</tspan></text>
586${steps && stepsW > 30 ? `<text class="t" x="42" y="49" font-family="${FONT}" font-size="11" font-variant-numeric="tabular-nums">${xml(fitText(steps, 11, stepsW))}</text>` : ''}
587<text class="s" x="${42 + barW}" y="49" text-anchor="end" font-family="${FONT}" font-size="11" font-variant-numeric="tabular-nums">${stats}</text>
588<rect class="k" x="42" y="55" width="${barW}" height="4" rx="2"/><rect${progress === null ? ' class="m"' : ''} x="42" y="55" width="${fillW}" height="4" rx="2"${progress === null ? '' : ` fill="${color}"`}/>
589${statusMark(W - 8, 16, a.status, color)}
590<line class="ln" x1="0" y1="65.5" x2="${W}" y2="65.5"/>`,
591 )
592}
593
594const plannedSvg = (W: number, p: Planned): string => {
595 const costume = plannedCostume(p)
596 const color = colorOf(costume)
597 const textW = W - 42 - 22
598 const meta = [profileLabel(p)]
599 if (p.after.length) meta.push(`${tr().after} ${p.after.join(', ')}`)
600 return svg(
601 W,
602 46,
603 `${crab(0, 6, costume, true)}
604<text class="s" x="42" y="18" font-family="${FONT}" font-size="13" font-weight="600">${xml(fitText(`${p.n}. ${p.title}`, 13, textW))}</text>
605<text x="42" y="34" font-family="${FONT}" font-size="11"><tspan fill="${color}">${xml(p.tier)}</tspan><tspan class="m"> ${xml(meta.filter(Boolean).join(' · '))}</tspan></text>
606${statusMark(W - 8, 16, 'planned', color)}
607<line class="ln" x1="0" y1="45.5" x2="${W}" y2="45.5"/>`,
608 )
609}
610
611const compactSvg = (W: number, list: AgentRun[], planned: Planned[], t: ReturnType<typeof totals>): string => {
612 const icon = (k: Costume, s: string, dim: boolean) => ({ k, c: colorOf(k), s, dim })
613 const icons = [
614 ...list.filter(a => a.status === 'running').map(a => icon(costumeOf(a), 'running', false)),
615 ...list.filter(a => a.status !== 'running').map(a => icon(costumeOf(a), a.status, false)),
616 ...planned.map(p => icon(plannedCostume(p), 'planned', true)),
617 ]
618 const fit = Math.max(1, Math.floor((W - 150) / 36))
619 const shown = icons.slice(0, fit)
620 const more = icons.length - shown.length
621 const body = shown
622 .map((ic, i) => crab(i * 36, 0, ic.k, ic.dim, ic.s === 'running') + (ic.s === 'running' ? `<circle class="live" cx="${i * 36 + 32}" cy="4" r="3" fill="${ic.c}"/>` : ''))
623 .join('')
624 const x = shown.length * 36 + (more ? 4 : 0)
625 return svg(
626 W,
627 32,
628 `${body}${more ? `<text class="s" x="${x}" y="21" font-family="${FONT}" font-size="12">+${more}</text>` : ''}
629<text class="s" x="${W}" y="21" text-anchor="end" font-family="${FONT}" font-size="12" font-variant-numeric="tabular-nums">≈${fmtCost(t.cost)} · ${fmtTokens(t.tokens)} · ${fmtTime(t.time)}</text>`,
630 )
631}
632
633// --- terminal drawing: the same rows in text.
634
635const STATUS_GLYPH: Record<string, string> = { running: '●', done: '✓', failed: '✗', planned: '◷' }
636// The band's crew row says planned with an open circle; the panel keeps its clock.
637const CREW_GLYPH: Record<string, string> = { ...STATUS_GLYPH, planned: '○' }
638
639// Opens the agents pane, or closes it when it is up; true when it ends up open.
640async function togglePane($: EngineInterface): Promise<boolean> {
641 const isOpen = (await $.ui.panes()).some(p => p.id === PANE)
642 if (isOpen) {
643 await $.ui.close({ id: PANE })
644 return false
645 }
646 const at = await $.clock.now()
647 await update($, now, () => at)
648 await $.ui.open({ id: PANE, title: tr().pane })
649 return true
650}
651
652async function autoOpen($: EngineInterface, key: string): Promise<void> {
653 const p = await read($, panel)
654 if (p.autoOpenedFor === key) return
655 await update($, panel, prev => ({ ...prev, autoOpenedFor: key }))
656 void $.ui.open({ id: PANE, title: tr().pane })
657}
658
659// This mod's own setting, or 'follow' Agent-Pulse's /config rows (ember / subtle without it).
660async function refreshLook($: EngineInterface): Promise<void> {
661 let rows: unknown = []
662 try {
663 rows = await $.config.list()
664 } catch {
665 // No rows: follow falls back to ember / subtle.
666 }
667 const next = resolveLook(configured, rows)
668 if (next.palette === look.palette && next.level === look.level) return
669 look = next
670 $.ui.invalidate('ui.render')
671}
672
673export const register: Register = (on, options) => {
674 configured = options
675 look = resolveLook(options, [])
676 // A (re)load has seen no flow run yet, so a flow already finished does not sparkle.
677 isFlowSeenRunning = false
678 sweepKey = 0
679
680 on('session.start', async ($, e, next) => {
681 const started = await next(e)
682 lang = await detectLang($, options.language)
683 await refreshLook($)
684 // The fallback for a change of Agent-Pulse's that never reached config.set.
685 $.clock.every(15_000, () => void refreshLook($))
686 await $.tool.register({
687 name: 'progress',
688 description:
689 "Report a multi-agent plan to the progress bar above the prompt and the agents panel. " +
690 'Call it after presenting the plan (title, total, tasks, phase "delegate"), each time a task is accepted (done), ' +
691 'when switching phase or re-planning (tasks), and once at the end with finished: true. Fields left out keep their previous value. ' +
692 'Optional: without it the bar follows subagent spawns and completions by itself.',
693 inputSchema: {
694 type: 'object',
695 properties: {
696 title: { type: 'string', description: 'Short name of the overall task, a few words.' },
697 total: { type: 'integer', minimum: 0, description: 'Number of planned worker tasks.' },
698 done: { type: 'integer', minimum: 0, description: 'Number of tasks accepted after review.' },
699 phase: { type: 'string', enum: [...PHASES] },
700 finished: { type: 'boolean', description: 'True once the flow is closed.' },
701 tasks: {
702 type: 'array',
703 description:
704 'The planned worker tasks in order, numbered from 1. Each title must equal the Agent tool `description` the task will be delegated with, so the panel can match runs to tasks.',
705 items: {
706 type: 'object',
707 properties: {
708 title: { type: 'string', description: 'A few words; reused verbatim as the Agent description.' },
709 model: {
710 type: 'string',
711 description: 'What the task will run on: `opus`, `sonnet`, `haiku`, `fable` or a model id. With `effort` it picks the crab\'s costume.',
712 },
713 effort: { type: 'string', enum: ['low', 'medium', 'high', 'xhigh', 'max'] },
714 tier: {
715 type: 'string',
716 enum: ['fable', 'heavy', 'careful', 'medium', 'light'],
717 description: 'A savvy-flow worker tier, for when `model` is left out.',
718 },
719 after: { type: 'array', items: { type: 'integer' }, description: 'Numbers of the tasks this one waits for.' },
720 },
721 required: ['title'],
722 },
723 },
724 },
725 },
726 })
727 await $.tool.register({
728 name: 'step',
729 description:
730 'For subagents: report progress on your own task to the agents panel. ' +
731 'Right after reading the brief, call it with `total` (your plan in 3-8 steps) and `done: 0`; ' +
732 'call it again as each step finishes. Cheap and silent: it only draws a bar.',
733 inputSchema: {
734 type: 'object',
735 properties: {
736 done: { type: 'integer', minimum: 0, description: 'Steps finished so far.' },
737 total: { type: 'integer', minimum: 1, description: 'Steps planned; may change if the plan changes.' },
738 note: { type: 'string', description: 'The step in progress, a few words.' },
739 },
740 required: ['done'],
741 },
742 })
743 await $.command.register({
744 name: 'subagent-progress',
745 description: 'Show or hide the panel of subagents: running, finished and planned, with model, context, cost and time',
746 })
747
748 // Ticks the running agents' clocks; quiet when nothing runs.
749 $.clock.every(1000, () => {
750 void (async () => {
751 const list = await read($, agents)
752 if (!list.some(a => a.status === 'running')) return
753 const at = await $.clock.now()
754 await update($, now, () => at)
755 })()
756 })
757 return started
758 })
759
760 // Another plugin's /config change that this mod follows: the new value is in the rows once it went through.
761 // Literals, so the engine can read the matcher off the source.
762 on('config.set', { key: ['agent-pulse.palette', 'agent-pulse.animation'] }, async ($, e, next) => {
763 const result = await next(e)
764 if (result.deny === undefined) await refreshLook($)
765 return result
766 })
767
768 on('command.run', { command: 'subagent-progress' }, async $ => {
769 const isOpen = await togglePane($)
770 return { text: isOpen ? tr().opened : tr().closed }
771 })
772
773 on('tool.call', { tool: TOOL }, async ($, e) => {
774 const input = e as unknown as ProgressInput
775 const prev = await read($, flow)
776 if (isNewFlow(prev, input) && input.title !== undefined) {
777 // A new flow starts with a clean list; agents still running stay.
778 await update($, agents, list => list.filter(a => a.status === 'running'))
779 }
780 const next = await update($, flow, p => merge(p, input))
781 if (next && input.tasks?.length) await autoOpen($, next.title)
782 return { result: `ok: ${label(next ?? blank())}` }
783 })
784
785 // A worker's own progress: the call runs in the worker's loop, so agentId names it.
786 on('tool.call', { tool: STEP_TOOL }, async ($, e) => {
787 const input = e as unknown as { done?: number; total?: number; note?: string }
788 const agentId = e.agentId
789 if (!agentId) return { result: 'ignored: only subagents report steps' }
790 await update($, agents, list =>
791 list.map(a => {
792 if (a.agentId !== agentId) return a
793 const total = Math.max(0, Math.round(input.total ?? a.stepTotal ?? 0))
794 const done = Math.max(0, Math.round(input.done ?? a.stepDone ?? 0))
795 return { ...a, stepTotal: total, stepDone: total ? Math.min(total, done) : done, stepNote: input.note?.trim() || undefined }
796 }),
797 )
798 return { result: 'ok' }
799 })
800
801 // Safety net: worker launches move the faint layer even if the orchestrator forgets to report.
802 on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
803 const type = String(e.subagent_type ?? '')
804 if (!type.startsWith('savvy-')) return next(e)
805
806 await update($, flow, prev => {
807 const base = prev && !prev.isFinished ? { ...blank(), ...prev } : blank()
808 return { ...base, running: base.running + 1, phase: base.phase === 'plan' ? 'delegate' : base.phase }
809 })
810 try {
811 return await next(e)
812 } finally {
813 await update($, flow, prev => (prev ? { ...prev, running: Math.max(0, prev.running - 1) } : prev))
814 }
815 })
816
817 on('agent.spawn', async ($, e, next) => {
818 const started = await next(e)
819 if (started.deny !== undefined) return started
820
821 const at = await $.clock.now()
822 // Outside a /savvy-flow, every non-savvy agent drives the flow row itself (auto.ts).
823 const isSavvy = isSavvyType(e.subagentType)
824 const isFreshBatch = !isSavvy && startsBatch(await read($, flow))
825 const runId = started.agentId ?? e.tool_use_id
826 await update($, agents, list => {
827 const round = 1 + list.filter(a => norm(a.description) === norm(e.description) && e.description).length
828 const run: AgentRun = {
829 id: runId,
830 agentId: started.agentId,
831 type: e.subagentType,
832 description: e.description,
833 model: started.model,
834 status: 'running',
835 startedAt: at,
836 contextTokens: 0,
837 contextMax: windowOf(started.model),
838 tokens: 0,
839 costUsd: 0,
840 steps: 0,
841 round,
842 }
843 // A new batch starts with a clean list, as a new flow does; agents still running stay.
844 const kept = isFreshBatch ? list.filter(a => a.status === 'running') : list
845 return [...kept.filter(a => a.id !== run.id), run].slice(-200)
846 })
847 await update($, now, () => at)
848 if (!isSavvy) await update($, flow, prev => onSpawn(prev, runId))
849 const f = await read($, flow)
850 await autoOpen($, f && !f.isFinished ? openKey(f) : isSavvy ? 'flow' : AUTO_TITLE)
851 return started
852 })
853
854 // Each model request of a subagent: live context, tokens and cost.
855 on('turn.step', async function* ($, e, next) {
856 const result = yield* next(e)
857 const agentId = e.agentId
858 const usage = result.usage
859 if (!agentId || !usage) return result
860
861 const model = usage.model || e.model
862 await update($, agents, list =>
863 list.map(a =>
864 a.agentId !== agentId
865 ? a
866 : {
867 ...a,
868 model,
869 effort: typeof e.effort === 'string' ? e.effort : a.effort,
870 status: 'running',
871 endedAt: undefined,
872 contextTokens:
873 (usage.input_tokens || 0) +
874 (usage.cache_read_input_tokens || 0) +
875 (usage.cache_creation_input_tokens || 0) +
876 (usage.output_tokens || 0),
877 contextMax: windowOf(model),
878 tokens:
879 a.tokens +
880 (usage.input_tokens || 0) +
881 (usage.output_tokens || 0) +
882 (usage.cache_read_input_tokens || 0) +
883 (usage.cache_creation_input_tokens || 0),
884 costUsd: a.costUsd + costOf(model, usage),
885 steps: a.steps + 1,
886 },
887 ),
888 )
889 return result
890 })
891
892 on('turn.complete', async ($, e, next) => {
893 const agentId = e.agentId
894 if (agentId) {
895 const at = await $.clock.now()
896 const counted = isCounted((await read($, agents)).find(a => a.agentId === agentId))
897 await update($, agents, list =>
898 list.map(a => {
899 if (a.agentId !== agentId) return a
900 // A run whose steps went unseen still gets the turn's own sum.
901 const fallback = a.steps === 0 && e.usage
902 return {
903 ...a,
904 status: e.reason === 'answer' ? 'done' : 'failed',
905 endedAt: at,
906 ...(fallback && e.usage
907 ? {
908 model: e.usage.model || a.model,
909 tokens:
910 e.usage.input_tokens +
911 e.usage.output_tokens +
912 e.usage.cache_read_input_tokens +
913 e.usage.cache_creation_input_tokens,
914 costUsd: costOf(e.usage.model || a.model, e.usage),
915 }
916 : {}),
917 }
918 }),
919 )
920 await update($, now, () => at)
921 // The batch's own agents all finished: a spawn-derived flow closes into the green "Done" row.
922 const runs = await read($, agents)
923 await update($, flow, prev => onFinish(prev, counted, runs))
924 }
925 return next(e)
926 })
927
928 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
929 const s = tr()
930 const ui = $.ui.resolve(e)
931 const { Box, Text, Button } = ui
932 const list = await read($, agents)
933 const f = await read($, flow)
934 const p: Panel = await read($, panel)
935 const at = Math.max(await read($, now), ...list.map(a => a.startedAt), 0)
936
937 const running = list.filter(a => a.status === 'running').reverse()
938 const finished = list.filter(a => a.status !== 'running').reverse()
939 const planned = plannedOf(f, list)
940 const t = totals(list, at)
941 // The pane's title says "Agents"; inside, only the flow's own name.
942 const title = f && !f.isFinished ? f.title : ''
943
944 const toggleCompact = (
945 <Button
946 key="compact"
947 label={p.isCompact ? s.expand : s.collapse}
948 plain
949 onPress={() => update($, panel, prev => ({ ...prev, isCompact: !prev.isCompact }))}
950 />
951 )
952 const toggleDone = (
953 <Button
954 key="done"
955 label={`${p.isDoneCollapsed ? '▸' : '▾'} ${s.finished} · ${finished.length}`}
956 plain
957 onPress={() => update($, panel, prev => ({ ...prev, isDoneCollapsed: !prev.isDoneCollapsed }))}
958 />
959 )
960 const isEmpty = list.length === 0 && planned.length === 0
961 const versionRow = (
962 <Text key="version" color="inactive" dimColor>
963 {`subagent-progress v${VERSION}`}
964 </Text>
965 )
966 const summary = `≈${fmtCost(t.cost)}, ${fmtTokens(t.tokens)} ${s.tokensWord}, ${fmtTime(t.time)}`
967
968 if (e.surface === 'desktop' && 'Svg' in ui) {
969 const { Svg } = ui
970 const W = Math.max(240, Math.min(900, (e.props.bodyColumns || 40) * 8 - 8))
971 const section = (key: string, text: string) => (
972 <Text key={key} dimColor>
973 {text}
974 </Text>
975 )
976
977 if (p.isCompact) {
978 return (
979 <Box flexDirection="column" gap={1}>
980 <Svg source={compactSvg(W, list, planned, t)} alt={`${list.length} ${s.agentsCount}, ${summary}`} width={W} height={32} />
981 {toggleCompact}
982 {versionRow}
983 </Box>
984 )
985 }
986 return (
987 <Box flexDirection="column">
988 <Svg source={headerSvg(W, title, t)} alt={title ? `${title}: ${summary}` : summary} width={W} height={headerHeight(title)} />
989 {toggleCompact}
990 {isEmpty && <Text dimColor>{s.empty}</Text>}
991 {running.length > 0 && section('h-run', `${s.running} · ${running.length}`)}
992 {running.map(a => (
993 <Svg key={a.id} source={agentSvg(W, a, at)} alt={`${a.description}: ${modelName(a.model)}, ${s.isRunning}`} width={W} height={66} />
994 ))}
995 {finished.length > 0 && toggleDone}
996 {!p.isDoneCollapsed &&
997 finished.map(a => (
998 <Svg key={a.id} source={agentSvg(W, a, at)} alt={`${a.description}: ${modelName(a.model)}, ${s.isFinished}`} width={W} height={66} />
999 ))}
1000 {planned.length > 0 && section('h-plan', `${s.planned} · ${planned.length}`)}
1001 {planned.map(pl => (
1002 <Svg key={`plan-${pl.n}`} source={plannedSvg(W, pl)} alt={`${pl.n}. ${pl.title}: ${s.isPlanned}`} width={W} height={46} />
1003 ))}
1004 {versionRow}
1005 </Box>
1006 )
1007 }
1008
1009 // Terminal: the same content in text rows, with a crab beside each card (DESIGN.md).
1010 const cols = Math.max(24, e.props.bodyColumns || 40)
1011 const barW = Math.max(6, Math.min(20, cols - 34))
1012 const palette = paletteOf(look.palette)
1013 const Client = 'Client' in ui ? ui.Client : undefined
1014 // The crab needs room beside the text; on a narrower pane the old glyph layout stays.
1015 const hasCrab = Client !== undefined && (e.props.bodyColumns || 40) >= CRAB_MIN_COLS
1016 // Only the newest running agents walk and spin: a big batch must not start a clock per agent.
1017 const walking = new Set(running.slice(0, MAX_ANIMATED).map(a => a.id))
1018 // A crab is always this one Client, a still one included (it starts no clock). Its key names the mode,
1019 // so an agent that finishes gets a fresh instance instead of a timer left running.
1020 const crabOf = (id: string, costume: Costume, isRunning: boolean) =>
1021 Client && (
1022 <Client
1023 key={`crab-${id}-${isRunning ? 'run' : 'still'}`}
1024 module="./crab.tsx"
1025 props={{ costume, accent: colorOf(costume), running: isRunning, dim: !isRunning, level: look.level }}
1026 width={6}
1027 height={2}
1028 />
1029 )
1030 // Theme keys, so done and failed follow the person's theme; running keeps the costume's color.
1031 const statusColor = (a: AgentRun, color: string) => (a.status === 'failed' ? 'error' : a.status === 'done' ? 'success' : color)
1032 // The bar shows steps when the worker reports them, else its context fill in grey, amber then red as it fills.
1033 const runBar = (a: AgentRun, color: string, width: number) => {
1034 const progress = progressOf(a)
1035 if (progress !== null) return <Text color={color}>{bar(progress, width)}</Text>
1036 const ctx = ctxOf(a)
1037 const heat = ctx >= HEAT_AT[1] ? palette.heat[2] : ctx >= HEAT_AT[0] ? palette.heat[0] : undefined
1038 return heat ? <Text color={heat}>{bar(ctx / 100, width)}</Text> : <Text dimColor>{bar(ctx / 100, width)}</Text>
1039 }
1040 const row = (a: AgentRun) => {
1041 const costume = costumeOf(a)
1042 const color = colorOf(costume)
1043 const model = a.effort ? `${modelName(a.model)} · ${a.effort}` : modelName(a.model)
1044 // Steps and their free-text note go last: a cut line loses them, not the time and cost.
1045 const steps = a.stepTotal ? ` · ${a.stepDone ?? 0}/${a.stepTotal}${a.stepNote ? ' ' + a.stepNote : ''}` : ''
1046 const name = (
1047 <Box flexDirection="row" gap={1}>
1048 {!hasCrab && <Text color={color}>▣</Text>}
1049 <Text bold wrap="truncate-end">
1050 {a.description || a.type}
1051 </Text>
1052 <Text color={statusColor(a, color)}>{STATUS_GLYPH[a.status]}</Text>
1053 </Box>
1054 )
1055 const type = (
1056 <Text dimColor wrap="truncate-end">
1057 {hasCrab ? '' : ' '}
1058 {bareType(a.type)} · {model}
1059 {a.round > 1 ? ` · ${s.round} ${a.round}` : ''}
1060 </Text>
1061 )
1062 return (
1063 <Box key={a.id} flexDirection="column">
1064 {hasCrab ? (
1065 <Box flexDirection="row" gap={1}>
1066 {crabOf(a.id, costume, a.status === 'running' && walking.has(a.id))}
1067 <Box flexDirection="column" flexGrow={1} flexShrink={1}>
1068 {name}
1069 {type}
1070 </Box>
1071 </Box>
1072 ) : (
1073 name
1074 )}
1075 {!hasCrab && type}
1076 <Text wrap="truncate-end">
1077 {hasCrab ? '' : ' '}
1078 {runBar(a, color, barW)}
1079 <Text dimColor>
1080 {' '}
1081 {fmtTime(elapsed(a, at))} · ≈{fmtCost(a.costUsd)} · ctx {ctxOf(a)}% · {fmtTokens(a.contextTokens)}
1082 {steps}
1083 </Text>
1084 </Text>
1085 </Box>
1086 )
1087 }
1088 // Compact: one line per agent, the bar only where it fits. A running agent's glyph is a spinner.
1089 const lineBarW = cols >= 40 ? Math.min(10, cols - 30) : 0
1090 const line = (a: AgentRun) => {
1091 const color = colorOf(costumeOf(a))
1092 return (
1093 <Box key={a.id} flexDirection="row" gap={1}>
1094 {Client && a.status === 'running' && walking.has(a.id) && look.level !== 'off' ? (
1095 <Client
1096 key={`spin-${a.id}`}
1097 module="./pulse.tsx"
1098 props={{ kind: 'spin', frames: SPIN, ms: SPIN_MS, colors: [color] }}
1099 width={1}
1100 height={1}
1101 />
1102 ) : (
1103 <Text color={statusColor(a, color)}>{STATUS_GLYPH[a.status]}</Text>
1104 )}
1105 <Box flexGrow={1} flexShrink={1}>
1106 <Text wrap="truncate-end">{a.description || a.type}</Text>
1107 </Box>
1108 {lineBarW > 0 && runBar(a, color, lineBarW)}
1109 <Text dimColor>
1110 {fmtTime(elapsed(a, at))} ≈{fmtCost(a.costUsd)}
1111 </Text>
1112 </Box>
1113 )
1114 }
1115
1116 return (
1117 <Box flexDirection="column">
1118 <Box flexDirection="row" justifyContent="space-between">
1119 <Text bold wrap="truncate-end">
1120 {title}
1121 </Text>
1122 {toggleCompact}
1123 </Box>
1124 <Text dimColor>
1125 {fmtTime(t.time)} · ≈{fmtCost(t.cost)} · {fmtTokens(t.tokens)} {s.tokensWord}
1126 </Text>
1127 {p.isCompact ? (
1128 <Box flexDirection="column">
1129 {running.map(line)}
1130 {finished.length > 0 && toggleDone}
1131 {!p.isDoneCollapsed && finished.map(line)}
1132 {planned.map(pl => (
1133 <Text key={`plan-${pl.n}`} dimColor wrap="truncate-end">
1134 {STATUS_GLYPH.planned} {pl.n}. {pl.title}
1135 </Text>
1136 ))}
1137 </Box>
1138 ) : (
1139 <Box flexDirection="column" marginTop={1}>
1140 {isEmpty && <Text dimColor>{s.empty}</Text>}
1141 {running.length > 0 && <Text dimColor>{s.running} · {running.length}</Text>}
1142 {running.map(row)}
1143 {finished.length > 0 && toggleDone}
1144 {!p.isDoneCollapsed && finished.map(row)}
1145 {planned.length > 0 && <Text dimColor>{s.planned} · {planned.length}</Text>}
1146 {planned.map(pl => {
1147 const meta = `${[pl.tier, profileLabel(pl)].filter(Boolean).join(' · ')}${pl.after.length ? ` · ${s.after} ${pl.after.join(', ')}` : ''}`
1148 // A still, dim crab replaces the leading ▢.
1149 return hasCrab ? (
1150 <Box key={`plan-${pl.n}`} flexDirection="row" gap={1}>
1151 {crabOf(`plan-${pl.n}`, plannedCostume(pl), false)}
1152 <Box flexDirection="column" flexGrow={1} flexShrink={1}>
1153 <Text dimColor wrap="truncate-end">
1154 {pl.n}. {pl.title}
1155 </Text>
1156 <Text dimColor wrap="truncate-end">
1157 {meta}
1158 </Text>
1159 </Box>
1160 </Box>
1161 ) : (
1162 <Box key={`plan-${pl.n}`} flexDirection="column">
1163 <Text dimColor wrap="truncate-end">
1164 <Text color={colorOf(plannedCostume(pl))}>▢</Text> {pl.n}. {pl.title}
1165 </Text>
1166 <Text dimColor wrap="truncate-end">
1167 {' '}
1168 {meta}
1169 </Text>
1170 </Box>
1171 )
1172 })}
1173 </Box>
1174 )}
1175 {versionRow}
1176 </Box>
1177 )
1178 })
1179
1180 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1181 const f = await read($, flow)
1182 if (f === null || e.props.hasSurvey) return next(e)
1183
1184 // A render that sees the flow go from running to finished keys the sparkle once; a flow already
1185 // finished when the module loads (a resume, a reload) never does, and a new flow clears it.
1186 if (f.isFinished) {
1187 if (isFlowSeenRunning) {
1188 isFlowSeenRunning = false
1189 finishSeq += 1
1190 sweepKey = finishSeq
1191 }
1192 } else {
1193 isFlowSeenRunning = true
1194 sweepKey = 0
1195 }
1196
1197 // The band is one site for every plugin: what the plugins beneath draw
1198 // stays, under the bar, so another mod's band is never hidden.
1199 const below = await next(e)
1200 const ui = $.ui.resolve(e)hooks/auto.ts 73 lines1import type { AgentRun, Flow } from '../types'
2
3// Subagent work nobody reports a plan for: the flow row is derived from spawns and
4// completions. An orchestrated flow (the `progress` tool, or a `savvy-*` worker of an
5// upstream savvy-flow) is never touched here.
6
7export const AUTO_TITLE = 'Subagents'
8
9/** `savvy-careful`, or `savvy-flow:savvy-careful` when the agents ship in a plugin. */
10export const isSavvyType = (type: string): boolean => type.startsWith('savvy-')
11
12const fresh = (): Flow => ({
13 title: AUTO_TITLE,
14 total: 0,
15 done: 0,
16 running: 0,
17 phase: 'delegate',
18 isFinished: false,
19 tasks: [],
20 isAuto: true,
21 ids: [],
22})
23
24/**
25 * What `autoOpen` dedupes on: the panel opens again whenever this changes. An auto
26 * flow keys on its first agent, so every new batch opens it, but the agents joining
27 * a batch do not reopen what the person closed; an orchestrated flow keys on its title.
28 */
29export const openKey = (f: Flow): string => (f.isAuto ? (f.ids?.[0] ?? AUTO_TITLE) : f.title)
30
31/** No flow, or the last one is closed: the next spawn opens a new batch. */
32export const startsBatch = (prev: Flow | null): boolean => prev === null || prev.isFinished
33
34/** A non-savvy agent `id` started: join the running auto flow, or open a new one. */
35export const onSpawn = (prev: Flow | null, id: string): Flow | null => {
36 if (prev && !prev.isFinished && !prev.isAuto) return prev
37 const base = prev && !prev.isFinished ? prev : fresh()
38 const ids = base.ids ?? []
39 return {
40 ...base,
41 total: base.total + 1,
42 running: base.running + 1,
43 ids: ids.includes(id) ? ids : [...ids, id],
44 }
45}
46
47/** Whether a run's completion counts toward an auto flow: it was running and not a savvy worker. */
48export const isCounted = (run: Pick<AgentRun, 'status' | 'type'> | undefined): boolean =>
49 run !== undefined && run.status === 'running' && !isSavvyType(run.type)
50
51/**
52 * Only this batch's own agents decide it is over: a run left `running` by an earlier
53 * batch (an interrupted agent never reports back) must not hold it open.
54 */
55const isBatchIdle = (f: Flow, runs: Pick<AgentRun, 'id' | 'status'>[]): boolean =>
56 (f.ids ?? []).every(id => runs.find(r => r.id === id)?.status !== 'running')
57
58/**
59 * An agent finished. Count it when it was one this flow spawned; once none of the
60 * batch is running any more, close the flow, which draws as the green "Done" row
61 * until dismissed.
62 */
63export const onFinish = (
64 prev: Flow | null,
65 counted: boolean,
66 runs: Pick<AgentRun, 'id' | 'status'>[],
67): Flow | null => {
68 if (!prev || !prev.isAuto || prev.isFinished) return prev
69 if (isBatchIdle(prev, runs)) return { ...prev, done: prev.total, running: 0, phase: 'close', isFinished: true }
70 if (!counted) return prev
71 return { ...prev, done: Math.min(prev.total, prev.done + 1), running: Math.max(0, prev.running - 1) }
72}
73hooks/crew.ts 98 lines1// Which costume a subagent's crab wears. The costume follows what the agent runs on, so
2// every subagent gets a prop, with or without savvy-flow:
3//
4// Fable (any effort), Opus at high or above astronaut
5// Opus below high detective
6// Sonnet at high or above engineer
7// Sonnet below high chef
8// Haiku racer
9// the Explore agent pirate
10// anything else a plain crab
11//
12// `high` and above is `high`, `xhigh` and `max`. An effort not known yet (a run's first
13// request has not gone out) or a numeric budget counts as below high.
14
15export type Costume = 'astronaut' | 'detective' | 'engineer' | 'chef' | 'racer' | 'pirate' | 'other'
16
17export const COSTUMES: readonly Costume[] = ['astronaut', 'detective', 'engineer', 'chef', 'racer', 'pirate', 'other']
18
19export const COSTUME_COLOR: Record<Costume, string> = {
20 astronaut: '#7F77DD',
21 detective: '#D85A30',
22 engineer: '#BA7517',
23 chef: '#378ADD',
24 racer: '#1D9E75',
25 pirate: '#888780',
26 other: '#888780',
27}
28
29type Family = 'fable' | 'opus' | 'sonnet' | 'haiku'
30
31/** `claude-sonnet-5-5`, `sonnet`, `claude-opus-5-5[1m]`: the family by substring; `inherit` and unknown ids are none. */
32export const familyOf = (model: string | undefined): Family | undefined => {
33 const m = (model ?? '').toLowerCase()
34 if (/fable|mythos/.test(m)) return 'fable'
35 if (/opus/.test(m)) return 'opus'
36 if (/sonnet/.test(m)) return 'sonnet'
37 if (/haiku/.test(m)) return 'haiku'
38 return undefined
39}
40
41const HIGH = new Set(['high', 'xhigh', 'max'])
42
43export const isHighEffort = (effort: unknown): boolean => typeof effort === 'string' && HIGH.has(effort.trim().toLowerCase())
44
45const byFamily = (family: Family, effort: unknown): Costume => {
46 if (family === 'fable') return 'astronaut'
47 if (family === 'haiku') return 'racer'
48 if (family === 'opus') return isHighEffort(effort) ? 'astronaut' : 'detective'
49 return isHighEffort(effort) ? 'engineer' : 'chef'
50}
51
52/** `savvy-flow:savvy-careful` is `savvy-careful`; `general-purpose` is itself. */
53export const bareType = (type: string): string => type.replace(/^[^:]*:/, '')
54
55// savvy-flow's workers are a model and an effort each (its agents/*.md frontmatter).
56// Kept for what has no model yet: a planned task named by tier, a `savvy-*` run before
57// its first request. A run's own model and effort always decide first.
58export const LEGACY_TIERS: Record<string, { model: string; effort: string }> = {
59 fable: { model: 'fable', effort: 'high' },
60 heavy: { model: 'opus', effort: 'xhigh' },
61 careful: { model: 'opus', effort: 'high' },
62 medium: { model: 'opus', effort: 'medium' },
63 light: { model: 'opus', effort: 'low' },
64}
65
66const legacyOf = (name: string): { model: string; effort: string } | undefined =>
67 Object.prototype.hasOwnProperty.call(LEGACY_TIERS, name) ? LEGACY_TIERS[name] : undefined
68
69/** A run's costume: the Explore pirate, else its model and effort, else its savvy tier, else plain. */
70export const costumeOf = (run: { type: string; model?: string; effort?: string }): Costume => {
71 const bare = bareType(run.type)
72 if (bare === 'Explore') return 'pirate'
73 const family = familyOf(run.model)
74 if (family) return byFamily(family, run.effort)
75 const legacy = bare.startsWith('savvy-') ? legacyOf(bare.slice('savvy-'.length).toLowerCase()) : undefined
76 const legacyFamily = legacy && familyOf(legacy.model)
77 return legacy && legacyFamily ? byFamily(legacyFamily, legacy.effort) : 'other'
78}
79
80export type PlannedLike = { tier?: string; model?: string; effort?: string }
81
82const isCostume = (name: string): name is Costume => (COSTUMES as readonly string[]).includes(name)
83
84/** What a planned task will run on: its own model and effort, else its tier (a savvy tier or a costume name). */
85export const plannedProfile = (p: PlannedLike): { model?: string; effort?: string } => {
86 if (p.model && familyOf(p.model)) return { model: p.model, effort: p.effort }
87 const legacy = legacyOf((p.tier ?? '').trim().toLowerCase())
88 return legacy ? { ...legacy } : {}
89}
90
91export const plannedCostume = (p: PlannedLike): Costume => {
92 const profile = plannedProfile(p)
93 const family = familyOf(profile.model)
94 if (family) return byFamily(family, profile.effort)
95 const name = (p.tier ?? '').trim().toLowerCase()
96 return isCostume(name) ? name : 'other'
97}
98hooks/palette.ts 121 lines1// The terminal look's colours. The four palettes below are COPIED from agent-pulse/hooks/palette.ts
2// (each mod is installed alone, so there is no import across mods): keep the values in step with
3// Agent-Pulse. palette.test.ts pins a few, so a drift is a deliberate edit. Only the phases this mod
4// paints with are copied: idle, tool, agent, approval.
5
6/** How much the terminal look moves: `userConfig.animation`. */
7export type Level = 'off' | 'subtle' | 'full'
8
9export type PaletteName = 'ember' | 'claude' | 'neon' | 'mono'
10
11type Phase = 'idle' | 'tool' | 'agent' | 'approval'
12type Outcome = 'ok' | 'error' | 'denied' | 'interrupted'
13
14/**
15 * `phase` and `outcome` are what `Text` takes, theme keys where one means the same, so they follow the
16 * person's theme; `hex` and `glow` are the same colours as hex strings, for what mixes. `glow` is a
17 * phase's second stop and equals `hex` in a flat palette.
18 */
19export type Palette = {
20 phase: Record<Phase, string>
21 hex: Record<Phase, string>
22 glow: Record<Phase, string>
23 outcome: Record<Outcome, string>
24 sparkle: readonly string[]
25 /** Amber, orange, red. */
26 heat: readonly [string, string, string]
27}
28
29const CLAUDE_HEX: Record<Phase, string> = { idle: '#8a8a8a', tool: '#d97757', agent: '#2ec4b6', approval: '#ffc107' }
30const EMBER_HEX: Record<Phase, string> = { idle: '#857a74', tool: '#d97757', agent: '#8cc7b5', approval: '#ffcf5c' }
31const EMBER_GLOW: Record<Phase, string> = { idle: '#9a8f88', tool: '#f3a97c', agent: '#b6d99a', approval: '#ffb347' }
32const NEON_HEX: Record<Phase, string> = { idle: '#5b6785', tool: '#22e5f0', agent: '#4ade80', approval: '#ffd166' }
33const NEON_GLOW: Record<Phase, string> = { idle: '#6f7a99', tool: '#6ef0c8', agent: '#bef264', approval: '#ff9f6e' }
34const MONO_HEX: Record<Phase, string> = { idle: '#7a7a7a', tool: '#d0d0d0', agent: '#d0d0d0', approval: '#ffc107' }
35
36const OUTCOME_THEME: Record<Outcome, string> = { ok: 'success', error: 'error', denied: 'warning', interrupted: 'inactive' }
37const EMBER_OUTCOME: Record<Outcome, string> = { ok: '#8fd694', error: '#ff6b6b', denied: '#ffcf5c', interrupted: '#857a74' }
38const NEON_OUTCOME: Record<Outcome, string> = { ok: '#4ade80', error: '#ff5c7a', denied: '#ffd166', interrupted: '#6f7a99' }
39
40const SHIMMER_STEPS = 12
41
42const PALETTES: Record<PaletteName, Palette> = {
43 ember: {
44 phase: EMBER_HEX,
45 hex: EMBER_HEX,
46 glow: EMBER_GLOW,
47 outcome: EMBER_OUTCOME,
48 sparkle: ['#d97757', '#e8957a', '#f3a97c', '#f6c177', '#ffe3b0', '#f6c177', '#f3a97c', '#e8957a'],
49 heat: ['#f6d36b', '#ff9a4d', '#ff5c5c'],
50 },
51 claude: {
52 phase: { idle: 'inactive', tool: 'claude', agent: CLAUDE_HEX.agent, approval: 'warning' },
53 hex: CLAUDE_HEX,
54 glow: CLAUDE_HEX,
55 outcome: OUTCOME_THEME,
56 sparkle: ['#d97757', '#e48a66', '#f0a47f', '#fbc8a8', '#ffe6d5', '#fbc8a8', '#f0a47f', '#e48a66'],
57 heat: ['#e0af68', '#ff9e64', 'error'],
58 },
59 neon: {
60 phase: NEON_HEX,
61 hex: NEON_HEX,
62 glow: NEON_GLOW,
63 outcome: NEON_OUTCOME,
64 sparkle: ['#22e5f0', '#5eead4', '#7dd3fc', '#b39dff', '#ff8ad8', '#c4a1ff', '#7aa2ff', '#38bdf8'],
65 heat: ['#ffd166', '#ff9f6e', '#ff5c7a'],
66 },
67 mono: {
68 phase: { idle: 'inactive', tool: 'text', agent: 'text', approval: 'warning' },
69 hex: MONO_HEX,
70 glow: MONO_HEX,
71 outcome: OUTCOME_THEME,
72 sparkle: ['#6e6e6e', '#8a8a8a', '#a8a8a8', '#c8c8c8', '#e8e8e8', '#c8c8c8', '#a8a8a8', '#8a8a8a'],
73 heat: ['warning', 'warning', 'error'],
74 },
75}
76
77export const PALETTE_NAMES: readonly PaletteName[] = ['ember', 'claude', 'neon', 'mono']
78
79export const paletteOf = (name: unknown): Palette =>
80 PALETTES[name === 'claude' || name === 'neon' || name === 'mono' ? name : 'ember']
81
82export const levelOf = (value: unknown): Level => (value === 'off' || value === 'full' ? value : 'subtle')
83
84/** Mixes two hex colours, `t` 0 being `a` and 1 being `b`. */
85export const mix = (a: string, b: string, t: number): string => {
86 const channels = (hex: string) => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16))
87 const [from, to] = [channels(a), channels(b)]
88 const k = Math.min(1, Math.max(0, t))
89 return `#${from.map((c, i) => Math.round(c + ((to[i] ?? c) - c) * k).toString(16).padStart(2, '0')).join('')}`
90}
91
92/** A phase's colour `t` of the way from its core to its glow. A flat palette keeps its own colour, which may be a theme key. */
93export const shadeOf = (palette: Palette, phase: Phase, t: number): string => {
94 const core = palette.hex[phase]
95 return core === palette.glow[phase] ? palette.phase[phase] : mix(core, palette.glow[phase], t)
96}
97
98/** A cycle of colours, core to glow and back, or the one colour of a flat palette. */
99export const shimmerOf = (palette: Palette, phase: Phase): string[] =>
100 palette.hex[phase] === palette.glow[phase]
101 ? [palette.phase[phase]]
102 : Array.from({ length: SHIMMER_STEPS }, (_, i) => shadeOf(palette, phase, (1 - Math.cos((i / SHIMMER_STEPS) * 2 * Math.PI)) / 2))
103
104/** The rows this mod follows in /config; the keys are Agent-Pulse's own userConfig fields. */
105export const FOLLOW_KEYS = { palette: 'agent-pulse.palette', animation: 'agent-pulse.animation' } as const
106
107export type Look = { palette: PaletteName; level: Level }
108
109/**
110 * The look to draw with. `options`: the userConfig values ('follow' or explicit); `rows`: `$.config.list()`.
111 * 'follow' takes Agent-Pulse's own value, or ember / subtle without it.
112 */
113export const resolveLook = (options: { palette?: unknown; animation?: unknown } | undefined, rows: unknown): Look => {
114 const o = options ?? {}
115 const list = Array.isArray(rows) ? (rows as { key?: unknown; value?: unknown }[]) : []
116 const fromRow = (key: string): unknown => list.find(r => r && r.key === key)?.value
117 const palette = o.palette && o.palette !== 'follow' ? o.palette : fromRow(FOLLOW_KEYS.palette)
118 const animation = o.animation && o.animation !== 'follow' ? o.animation : fromRow(FOLLOW_KEYS.animation)
119 return { palette: PALETTE_NAMES.find(n => n === palette) ?? 'ember', level: levelOf(animation) }
120}
121hooks/version.ts 6 lines1// The host gives a hooks module no way to read its own manifest (not through
2// "node:fs", not as a JSON import), so the pane's last row carries a copy.
3// Bump it with plugin.json on every release; CI fails a pull request where the
4// two differ (.github/scripts/check-versions.mjs).
5export const VERSION = '2.2.1'
6hooks/crab.tsx 130 lines1import type { ClientModule } from 'claude-code'
2
3import type { Level } from './palette'
4
5// The terminal crab: 6 cells wide, 2 rows tall. Each cell holds two pixels, top and bottom, so the
6// sprite is 6x4 pixels drawn in half blocks. Every crab goes through this one Client, a still one
7// included: it starts no timer. See DESIGN.md, "The sprite".
8
9export type CrabProps = {
10 costume: string
11 /** The costume's colour (`COSTUME_COLOR`), for the hat pixels marked `a`. */
12 accent: string
13 running: boolean
14 /** Finished, failed and planned crabs are drawn dim. */
15 dim?: boolean
16 level: Level
17}
18
19type State = { frame: number }
20
21export type Cell = { ch: ' ' | '▀' | '▄' | '█'; fg?: string; bg?: string }
22
23const FRAME_MS = 250
24
25// b body, c claw, l leg (all the brand clay), e eye, w white, h brown, y yellow, k grey, a the accent.
26const COLORS: Record<string, string> = {
27 b: '#D97757',
28 c: '#D97757',
29 l: '#D97757',
30 e: '#1F1E1D',
31 w: '#F4F3EE',
32 h: '#7A4A26',
33 y: '#F5C542',
34 k: '#55514C',
35}
36
37const NO_HAT = '......'
38
39// Pixel row 0, by costume.
40const HAT: Record<string, string> = {
41 astronaut: '.waaw.',
42 detective: '.hhhh.',
43 engineer: '.yyyy.',
44 chef: 'wwwwww',
45 racer: '.aaaa.',
46 pirate: '.kwwk.',
47 other: NO_HAT,
48}
49
50const put = (g: string[][], row: number, col: number, key: string): void => {
51 const r = g[row]
52 if (r) r[col] = key
53}
54
55// The prop is one pixel that moves with the frame (the astronaut's star blinks instead).
56const PROP: Record<string, (frame: number, g: string[][]) => void> = {
57 astronaut: (f, g) => {
58 if (f % 2 === 0) put(g, 0, 5, 'y')
59 },
60 detective: (f, g) => put(g, f % 2, 5, 'k'),
61 engineer: (f, g) => put(g, f % 2, 0, 'k'),
62 chef: (f, g) => put(g, f % 2, 5, 'y'),
63 racer: (f, g) => put(g, f % 2, 5, f % 2 ? 'w' : 'k'),
64 pirate: (f, g) => put(g, f % 2, 5, 'k'),
65}
66
67/**
68 * The four pixel rows of a crab, `.` for nothing. `off` holds still on frame 0; `subtle` walks the
69 * legs and holds the prop at its first position; `full` moves both.
70 */
71export const spriteOf = (costume: string, frame: number, level: Level): string[] => {
72 const legs = level === 'off' ? 0 : frame
73 const prop = level === 'full' ? frame : 0
74 const g = [HAT[costume] ?? NO_HAT, 'cebbec', '.bbbb.', legs % 2 ? '..ll..' : '.l..l.'].map(row => [...row])
75 PROP[costume]?.(prop, g)
76 return g.map(row => row.join(''))
77}
78
79/** The sprite as 2 rows of 6 terminal cells: `▀` carries the top pixel, a background the bottom one. */
80export const cellsOf = (costume: string, accent: string, frame: number, level: Level): Cell[][] => {
81 const sprite = spriteOf(costume, frame, level)
82 const colorAt = (x: number, y: number): string | undefined => {
83 const key = sprite[y]?.[x]
84 return key === undefined || key === '.' ? undefined : key === 'a' ? accent : COLORS[key]
85 }
86 return [0, 1].map(r =>
87 Array.from({ length: 6 }, (_, x): Cell => {
88 const top = colorAt(x, r * 2)
89 const bottom = colorAt(x, r * 2 + 1)
90 if (top && bottom) return top === bottom ? { ch: '█', fg: top } : { ch: '▀', fg: top, bg: bottom }
91 if (top) return { ch: '▀', fg: top }
92 if (bottom) return { ch: '▄', fg: bottom }
93 return { ch: ' ' }
94 }),
95 )
96}
97
98const Crab: ClientModule<CrabProps, State> = (props, surface) => {
99 const { Text, Box } = surface.elements
100 const isMoving = props.running && props.level !== 'off'
101
102 // Started once, while there is no state yet. A crab that stops running is a new instance (its key
103 // names the mode), and a still one draws frame 0 whatever its state says.
104 if (surface.state === undefined && isMoving) {
105 let frame = 0
106 surface.every(FRAME_MS, () => {
107 frame += 1
108 surface.setState({ frame })
109 })
110 }
111
112 const frame = isMoving ? (surface.state?.frame ?? 0) : 0
113
114 return (
115 <Box flexDirection="column">
116 {cellsOf(props.costume, props.accent, frame, props.level).map((row, r) => (
117 <Text key={`r${r}`}>
118 {row.map((c, x) => (
119 <Text key={`c${x}`} color={c.fg} backgroundColor={c.bg} dimColor={props.dim}>
120 {c.ch}
121 </Text>
122 ))}
123 </Text>
124 ))}
125 </Box>
126 )
127}
128
129export default Crab
130hooks/pulse.tsx 76 lines1import type { ClientModule } from 'claude-code'
2
3// The terminal's other animations, one Client region each and all a fixed width, so the band's layout
4// never moves under them. Each runs on the surface's frame clock; the hooks never run per frame.
5//
6// - spin: a cell cycling `frames` every `ms`, with `colors` alongside (one frame and one colour hold still)
7// - sweep: the finish, played once: the sparkle `colors` run along the bar's `chars`, then it rests on the
8// solid bar in the `done` colours (one per char)
9
10export type PulseProps =
11 | { kind: 'spin'; frames: string[]; ms: number; colors: string[] }
12 | { kind: 'sweep'; chars: string[]; done: string[]; colors: string[] }
13
14type PulseState = { frame: number }
15
16const SWEEP_MS = 60
17const SWEEP_FRAMES = 25 // 1.5 s
18const TAIL = 4 // cells the sparkle trails behind the head
19
20const Pulse: ClientModule<PulseProps, PulseState> = (props, surface) => {
21 const { Text } = surface.elements
22
23 if (surface.state === undefined) {
24 const isStill = props.kind === 'spin' && props.frames.length <= 1 && props.colors.length <= 1
25
26 if (!isStill) {
27 let frame = 0
28 const stop = surface.every(props.kind === 'spin' ? props.ms : SWEEP_MS, () => {
29 frame += 1
30
31 // The sweep plays once, then rests.
32 if (props.kind === 'sweep' && frame >= SWEEP_FRAMES) {
33 stop()
34 }
35
36 surface.setState({ frame })
37 })
38 }
39 }
40
41 const frame = surface.state?.frame ?? 0
42
43 if (props.kind === 'spin') {
44 return <Text color={props.colors[frame % props.colors.length]}>{props.frames[frame % props.frames.length] ?? ' '}</Text>
45 }
46
47 // The head runs from the start to past the end; behind it the sparkle, ahead of it the solid bar.
48 const head = Math.round((frame / SWEEP_FRAMES) * (props.chars.length + TAIL))
49 const n = props.colors.length
50 const runs: { text: string; color: string | undefined }[] = []
51
52 props.chars.forEach((ch, i) => {
53 const isLit = frame < SWEEP_FRAMES && i <= head && i > head - TAIL
54 const color = isLit ? props.colors[(i + frame) % n] : props.done[i]
55 const last = runs[runs.length - 1]
56
57 if (last && last.color === color) {
58 last.text += ch
59 } else {
60 runs.push({ text: ch, color })
61 }
62 })
63
64 return (
65 <Text>
66 {runs.map((r, i) => (
67 <Text key={`s${i}`} color={r.color}>
68 {r.text}
69 </Text>
70 ))}
71 </Text>
72 )
73}
74
75export default Pulse
76types/index.d.ts 67 lines1export type Phase = 'plan' | 'design' | 'delegate' | 'review' | 'close'
2
3export type PlannedTask = {
4 title: string
5 /** A savvy-flow tier or a costume name; empty when the plan names a model instead. */
6 tier: string
7 /** What the task will run on: an alias or a model id. Picks the costume with `effort`. */
8 model?: string
9 effort?: string
10 after: number[]
11}
12
13export type Flow = {
14 title: string
15 total: number
16 done: number
17 running: number
18 phase: Phase
19 isFinished: boolean
20 tasks: PlannedTask[]
21 /** Derived from subagent spawns and completions, not reported by an orchestrator. */
22 isAuto?: boolean
23 /** Ids of the agents an auto flow spawned: only these decide it is over. */
24 ids?: string[]
25}
26
27export type AgentStatus = 'running' | 'done' | 'failed'
28
29export type AgentRun = {
30 id: string
31 agentId?: string
32 type: string
33 description: string
34 model: string
35 effort?: string
36 status: AgentStatus
37 startedAt: number
38 endedAt?: number
39 contextTokens: number
40 contextMax: number
41 tokens: number
42 costUsd: number
43 steps: number
44 round: number
45 /** Self-reported by the worker through the `step` tool. */
46 stepDone?: number
47 stepTotal?: number
48 stepNote?: string
49}
50
51export type Panel = {
52 isCompact: boolean
53 isDoneCollapsed: boolean
54 autoOpenedFor: string
55}
56
57declare module 'claude-code' {
58 interface PluginState {
59 'subagent-progress': {
60 flow: Flow | null
61 agents: AgentRun[]
62 panel: Panel
63 now: number
64 }
65 }
66}
67