Progress bar above the prompt and an agents panel (/agents-info): running, finished and planned subagents with model, progress, context, cost and time. Crabs…

berkays-mods copy of johnnyvizz/claude-kit 1.2.0 (MIT, johnnyvizz). Added: the claude-config agents
scout(Haiku),builder(Sonnet) andreviewer(Opus) are tiers of their own, with their own crabs, and count for the bar and the panel's auto-open the waysavvy-*workers do. The progress bar's crab is the orchestrator (the main session): a conductor in a top hat whose baton keeps time. The panel also lists the related background sessions (workers started with the CLI's background flag, in a worktree of this repository or launched by this session), with their state and branch, and in a terminal without graphics each crab is Claude Code's own Clawd in block characters, holding its tier's prop. Install withclaude plugin install savvy-progress@berkays-mods.
A Claude Code mod: a progress bar above the prompt and a live panel of subagents. Made for the savvy-flow skill, and useful with any subagents.
savvy-* worker starts./agents-info toggles it): running, finished and planned subagents with model, effort, task progress, context, estimated cost and time. Working crabs walk, and each savvy tier animates its prop: the astronaut floats, the detective sweeps the magnifier, the engineer turns the wrench, the chef tosses the omelette, the racer runs with a fluttering flag. prefers-reduced-motion stops them.claude agents --json and git worktree list every 5 s, only while the panel is open or a flow's bar is up. Model and effort are known only for sessions this session launched with --name (read off the Bash or PowerShell command); the crab comes from --agent scout|builder|reviewer, else the model (Haiku scout, Sonnet builder, Opus reviewer), else the plain crab. No cost or tokens: they are not visible from here.❯), replies (●) and one row per tool call (⎿ done, ◌ running, ✗ failed). A subagent is read from this session; a background session from its transcript file (the last 3.5 MB, via tail -c or a PowerShell seek when the file is bigger than a plain read allows), with the claude attach <id> line to take it over, and from claude logs only when no transcript is found. It scrolls (wheel, or ↑↓ PgUp PgDn Home End while the pane has the keys) over the last 1500 rows: at the bottom it follows new lines, scrolled up it stays put until you scroll back down or press End. On the desktop each row gets a View button.mcp__savvy-progress__progress: the orchestrator reports the plan, phase and accepted tasks.mcp__savvy-progress__step: a worker reports its own steps (done, total, note). A worker that does not report shows its context fill in grey instead.Cost is a rough estimate from token counts and a built-in per-model price table (PRICES in hooks/register.tsx), not a bill.
language: auto (default), en or ru. auto follows Claude Code's language setting, then the system locale, and falls back to English. Set it in /config, or, for a mod loaded by hand, in ~/.claude/settings.json:
{ "pluginConfigs": { "savvy-progress": { "options": { "language": "ru" } } } }
Install instructions are in the berkays-mods README.
hooks/register.tsx 1590 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AgentRun, BgSession, Flow, Panel, Phase, PlannedTask, ViewLine, ViewTarget } from '../types'
5import { aliasLabel, bgLaunches, bgState, branchOf, isRelated, parseAgents, parseWorktrees, tierFor } from './bg'
6import { clean, logLines, messageLines, transcriptMessages, wrapLines } from './view'
7import { SPRITE_W, clawd } from './sprite'
8import type { Fill, Run } from './sprite'
9
10const flow = atom({ plugin: 'savvy-progress', key: 'flow' } as const, null)
11const agents = atom({ plugin: 'savvy-progress', key: 'agents' } as const, [])
12const panel = atom({ plugin: 'savvy-progress', key: 'panel' } as const, {
13 isCompact: false,
14 isDoneCollapsed: false,
15 autoOpenedFor: '',
16})
17const now = atom({ plugin: 'savvy-progress', key: 'now' } as const, 0)
18const frame = atom({ plugin: 'savvy-progress', key: 'frame' } as const, 0)
19const bg = atom({ plugin: 'savvy-progress', key: 'bg' } as const, [])
20const launches = atom({ plugin: 'savvy-progress', key: 'launches' } as const, {})
21const view = atom({ plugin: 'savvy-progress', key: 'view' } as const, null)
22const viewFollow = atom({ plugin: 'savvy-progress', key: 'viewFollow' } as const, true)
23
24const TOOL = 'mcp__savvy-progress__progress'
25const STEP_TOOL = 'mcp__savvy-progress__step'
26const PANE = 'savvy-agents'
27const VIEW_PANE = 'savvy-view'
28const VIEW_EVERY_MS = 2000
29// The rows the view pane draws at most, newest last; the window scrolls over them.
30const VIEW_MAX_ROWS = 1500
31const BG_EVERY_MS = 5000
32const CRAB_EVERY_MS = 500
33const PHASES: readonly Phase[] = ['plan', 'design', 'delegate', 'review', 'close']
34const ACCENT = '#8f8cf4'
35const DONE = '#5fbf8f'
36
37type ProgressInput = {
38 title?: string
39 total?: number
40 done?: number
41 phase?: Phase
42 finished?: boolean
43 tasks?: { title?: string; tier?: string; after?: number[] }[]
44}
45
46// ---------------------------------------------------------------------------
47// Language: the `language` option, else Claude Code's `language` setting, else the
48// process locale; English when nothing says Russian.
49
50type Lang = 'en' | 'ru'
51
52const STRINGS = {
53 en: {
54 pane: 'Agents',
55 cost: 'Cost',
56 tokens: 'Tokens',
57 time: 'Time',
58 collapse: 'Collapse',
59 expand: 'Expand',
60 running: 'Running',
61 finished: 'Finished',
62 planned: 'Planned',
63 empty: 'No subagents yet.',
64 round: 'round',
65 failed: 'error',
66 after: 'after',
67 tokensWord: 'tokens',
68 agentsCount: 'agents',
69 isRunning: 'running',
70 isFinished: 'finished',
71 isPlanned: 'planned',
72 opened: 'Agents panel opened.',
73 closed: 'Agents panel closed.',
74 done: 'Done',
75 plan: 'Plan',
76 design: 'Design',
77 tasks: 'Tasks',
78 review: 'Review',
79 busy: 'running',
80 background: 'Background',
81 bgBusy: 'busy',
82 bgIdle: 'idle',
83 bgWaiting: 'waiting for you',
84 session: 'session',
85 view: 'View',
86 viewEmpty: 'Nothing yet.',
87 attach: 'take it over:',
88 fromLogs: 'from its terminal (no transcript found)',
89 scrollHint: 'wheel or ↑↓ PgUp PgDn to scroll · following new lines',
90 scrollBack: 'scrolled up: End (or scroll to the bottom) follows new lines again',
91 },
92 ru: {
93 pane: 'Агенты',
94 cost: 'Стоимость',
95 tokens: 'Токены',
96 time: 'Время',
97 collapse: 'Свернуть',
98 expand: 'Развернуть',
99 running: 'Работают',
100 finished: 'Завершены',
101 planned: 'Запланированы',
102 empty: 'Субагентов пока нет.',
103 round: 'раунд',
104 failed: 'ошибка',
105 after: 'после',
106 tokensWord: 'токенов',
107 agentsCount: 'агентов',
108 isRunning: 'работает',
109 isFinished: 'завершён',
110 isPlanned: 'запланирована',
111 opened: 'Панель агентов открыта.',
112 closed: 'Панель агентов закрыта.',
113 done: 'Готово',
114 plan: 'План',
115 design: 'Дизайн',
116 tasks: 'Задачи',
117 review: 'Ревью',
118 busy: 'в работе',
119 background: 'Фоновые',
120 bgBusy: 'работает',
121 bgIdle: 'простаивает',
122 bgWaiting: 'ждёт вас',
123 session: 'сессия',
124 view: 'Открыть',
125 viewEmpty: 'Пока пусто.',
126 attach: 'перехватить:',
127 fromLogs: 'из терминала (транскрипт не найден)',
128 scrollHint: 'колесо или ↑↓ PgUp PgDn для прокрутки · следует за новыми строками',
129 scrollBack: 'прокручено вверх: End (или вниз до конца) снова следует за новыми строками',
130 },
131} as const
132
133// Module scope is fine here: session.start sets it again on every (re)load.
134let lang: Lang = 'en'
135const tr = () => STRINGS[lang]
136
137const isRussian = (v: unknown): boolean => typeof v === 'string' && /^(ru|russian|рус)/i.test(v.trim())
138
139async function detectLang($: EngineInterface, option: unknown): Promise<Lang> {
140 if (option === 'en' || option === 'ru') return option
141 try {
142 const settings = (await $.settings.read()) as Record<string, unknown>
143 if (typeof settings.language === 'string' && settings.language.trim()) return isRussian(settings.language) ? 'ru' : 'en'
144 } catch {
145 // No settings: fall through to the locale.
146 }
147 const locale = (await $.env.get('LC_ALL')) || (await $.env.get('LC_MESSAGES')) || (await $.env.get('LANG'))
148 return isRussian(locale) ? 'ru' : 'en'
149}
150
151const blank = (): Flow => ({
152 title: 'savvy-flow',
153 total: 0,
154 done: 0,
155 running: 0,
156 phase: 'plan',
157 isFinished: false,
158 tasks: [],
159})
160
161const isNewFlow = (prev: Flow | null, input: ProgressInput): boolean =>
162 !prev || prev.isFinished || (input.title !== undefined && input.title.trim() !== prev.title)
163
164const cleanTasks = (tasks: ProgressInput['tasks']): PlannedTask[] | undefined =>
165 tasks
166 ?.filter(t => t.title?.trim())
167 .map(t => ({
168 title: (t.title ?? '').trim(),
169 tier: (t.tier ?? '').replace(/^savvy-/, '').trim().toLowerCase(),
170 after: (t.after ?? []).filter(n => Number.isInteger(n) && n > 0),
171 }))
172
173const merge = (prev: Flow | null, input: ProgressInput): Flow => {
174 // A new title means a new flow: never carry counters over from an earlier one.
175 const base = isNewFlow(prev, input) || !prev ? blank() : { ...blank(), ...prev }
176 const tasks = cleanTasks(input.tasks) ?? base.tasks
177 const total = Math.max(0, Math.round(input.total ?? (input.tasks ? tasks.length : base.total)))
178 const done = Math.min(total || Infinity, Math.max(0, Math.round(input.done ?? base.done)))
179 const phase = input.phase && PHASES.includes(input.phase) ? input.phase : base.phase
180 return {
181 ...base,
182 title: input.title?.trim() || base.title,
183 total,
184 done,
185 phase: input.finished ? 'close' : phase,
186 isFinished: input.finished === true,
187 tasks,
188 }
189}
190
191const label = (f: Flow): string => {
192 const s = tr()
193 if (f.isFinished) return s.done
194 if (f.phase === 'plan') return s.plan
195 if (f.phase === 'design') return s.design
196 const count = f.total ? `${f.done}/${f.total}` : `${f.running} ${s.busy}`
197 return `${f.phase === 'review' ? s.review : s.tasks} ${count}`
198}
199
200const ratio = (f: Flow): number => (f.isFinished ? 1 : f.total ? f.done / f.total : 0)
201
202// Deterministic noise so the dither does not shimmer between redraws.
203const noise = (x: number, y: number): number => {
204 const s = Math.sin(x * 12.9898 + y * 78.233) * 43758.5453
205 return s - Math.floor(s)
206}
207
208// The whole row is one SVG: the desktop wraps sibling elements onto new lines,
209// so title, bar, percent and the crab live in one drawing; only the count and
210// the dismiss are Buttons beside it.
211const H = 22
212const BAR_H = 16
213const CRAB_W = 26
214const CELL = 3
215const FONT = "-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',sans-serif"
216
217const xml = (s: string): string =>
218 s.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] ?? c)
219
220const clip = (s: string, max: number): string => (s.length > max ? s.slice(0, Math.max(1, max - 1)) + '…' : s)
221
222// Rough advance of system UI text, in em; good enough to size the title's slot.
223const charEm = (ch: string): number =>
224 /[\s.,:;'|!il1()[\]]/.test(ch) ? 0.3 : /[A-ZА-ЯЁmwшщжюМШЩЖЮ@%]/.test(ch) ? 0.72 : 0.56
225
226const textWidth = (s: string, size: number): number => [...s].reduce((w, ch) => w + charEm(ch) * size, 0)
227
228// Cuts `s` to fit `maxW` pixels, with an ellipsis when it had to cut.
229const fitText = (s: string, size: number, maxW: number): string => {
230 if (textWidth(s, size) <= maxW) return s
231 let out = ''
232 for (const ch of s) {
233 if (textWidth(out + ch + '…', size) > maxW) break
234 out += ch
235 }
236 return out + '…'
237}
238
239const rowSvg = (f: Flow, W: number, isWorking: boolean): string => {
240 // The title takes what it needs, up to 40% of the row; the bar takes the rest.
241 const title = fitText(f.title, 13, Math.max(60, W * 0.4))
242 const BAR_X = Math.round(16 + textWidth(title, 13) + 12)
243 const BAR_W = Math.max(60, W - BAR_X - 46 - CRAB_W)
244 const color = f.isFinished ? DONE : ACCENT
245 const y0 = (H - BAR_H) / 2
246 const fillW = Math.round(BAR_W * ratio(f))
247 const runW = f.total ? Math.round((BAR_W * Math.min(f.total, f.done + f.running)) / f.total) : 0
248 const dots: string[] = []
249
250 // Dithered fill: sparse at the start, dense toward the head.
251 const cols = Math.floor(fillW / CELL)
252 const rows = Math.floor(BAR_H / CELL)
253 for (let c = 0; c < cols; c++) {
254 const density = 0.35 + 0.6 * Math.pow(c / Math.max(1, cols), 1.2)
255 for (let r = 0; r < rows; r++) {
256 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"/>`)
257 }
258 }
259 // Handed to workers, not yet accepted: a faint second layer.
260 const faint: string[] = []
261 for (let c = cols; c < Math.floor(runW / CELL); c++) {
262 for (let r = 0; r < rows; r++) {
263 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"/>`)
264 }
265 }
266
267 const ticks: string[] = []
268 for (let i = 1; i < f.total; i++) {
269 const x = Math.round((BAR_W * i) / f.total)
270 if (x > fillW + 4) ticks.push(`<rect x="${x}" y="${BAR_H / 2 - 4}" width="1.5" height="8" rx="0.75"/>`)
271 }
272
273 const text = label(f)
274 const pillW = Math.round(18 + text.length * 6.6)
275 const pillX = Math.max(0, Math.min(BAR_W - pillW, fillW - pillW))
276 const percent = `${Math.round(ratio(f) * 100)}%`
277
278 return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
279<style>
280.t{fill:#1f1f1f}.m{fill:#8a8a8a}.k{fill:#e4e4e2}.tk{fill:#b4b4b0}
281@media (prefers-color-scheme: dark){.t{fill:#ececec}.m{fill:#9a9a9a}.k{fill:#2c2c2c}.tk{fill:#5a5a5a}}
282/* Pixels twinkle in four out-of-phase groups; a finished bar settles to a slow glow. */
283.t0,.t1,.t2,.t3{animation:tw ${f.isFinished ? 3.2 : 2.2}s ease-in-out infinite}
284.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}
285@keyframes tw{0%,100%{opacity:1}50%{opacity:${f.isFinished ? 0.8 : 0.3}}}
286@media (prefers-reduced-motion: reduce){.t0,.t1,.t2,.t3{animation:none}}
287</style>
288<defs><clipPath id="c"><rect x="0" y="0" width="${BAR_W}" height="${BAR_H}" rx="${BAR_H / 2}"/></clipPath></defs>
289<circle cx="5" cy="${H / 2}" r="4" fill="${color}"/>
290<text class="t" x="16" y="${H / 2 + 4.5}" font-family="${FONT}" font-size="13" font-weight="500">${xml(title)}</text>
291<g transform="translate(${BAR_X},${y0})">
292<rect class="k" width="${BAR_W}" height="${BAR_H}" rx="${BAR_H / 2}"/>
293<g clip-path="url(#c)">
294<g fill="${color}">${dots.join('')}</g>
295<g fill="${color}" opacity="0.45">${faint.join('')}</g>
296<g class="tk">${ticks.join('')}</g>
297</g>
298<rect x="${pillX}" width="${pillW}" height="${BAR_H}" rx="${BAR_H / 2}" fill="${color}"/>
299<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>
300</g>
301<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>
302${CRAB_CSS}${crab(W - CRAB_W + 1, 0, 'orchestrator', false, isWorking, 0.8)}
303</svg>`
304}
305
306const barText = (f: Flow, width: number): string => {
307 const filled = Math.round(width * ratio(f))
308 return '█'.repeat(filled) + '░'.repeat(Math.max(0, width - filled))
309}
310
311// ---------------------------------------------------------------------------
312// Agents panel: every subagent of the session, plus the tasks the flow planned.
313
314const TIER_COLOR: Record<string, string> = {
315 fable: '#7F77DD',
316 heavy: '#D85A30',
317 careful: '#BA7517',
318 medium: '#378ADD',
319 light: '#1D9E75',
320 // berkays-mods: the claude-config agents.
321 scout: '#5E8C3A',
322 builder: '#E07B39',
323 reviewer: '#8F6BD8',
324 // The main session, drawn on the progress bar.
325 orchestrator: '#C8A13A',
326 other: '#888780',
327}
328
329// What each savvy tier runs on, for planned tasks that have no run yet.
330const colorOf = (tier: string): string => TIER_COLOR[tier] ?? '#888780'
331
332const TIER_MODEL: Record<string, string> = {
333 fable: 'Fable · high',
334 heavy: 'Opus · xhigh',
335 careful: 'Opus · high',
336 medium: 'Opus · medium',
337 light: 'Opus · low',
338 scout: 'Haiku · medium',
339 builder: 'Sonnet · high',
340 reviewer: 'Opus · medium',
341}
342
343// USD per million tokens: input, output, cache read, cache write (5-minute TTL).
344// The engine reports tokens, not money, so the panel's cost is an estimate.
345const PRICES: [RegExp, [number, number, number, number]][] = [
346 [/fable|mythos/, [10, 50, 0.25, 12.5]],
347 [/opus-5-5/, [4, 20, 0.2, 5]],
348 [/opus/, [5, 25, 0.5, 6.25]],
349 [/sonnet/, [2, 10, 0.2, 2.5]],
350 [/haiku/, [1, 5, 0.1, 1.25]],
351]
352
353type Usage = {
354 input_tokens: number
355 output_tokens: number
356 cache_read_input_tokens: number
357 cache_creation_input_tokens: number
358}
359
360const priceOf = (model: string): [number, number, number, number] =>
361 PRICES.find(([re]) => re.test(model.toLowerCase()))?.[1] ?? [4, 20, 0.2, 5]
362
363const costOf = (model: string, u: Usage): number => {
364 const [i, o, r, w] = priceOf(model)
365 return (
366 ((u.input_tokens || 0) * i +
367 (u.output_tokens || 0) * o +
368 (u.cache_read_input_tokens || 0) * r +
369 (u.cache_creation_input_tokens || 0) * w) /
370 1e6
371 )
372}
373
374const windowOf = (model: string): number => (/haiku/i.test(model) ? 200_000 : 1_000_000)
375
376// The claude-config agents are their own tiers, without the savvy- prefix.
377const CREW = ['scout', 'builder', 'reviewer']
378
379// `savvy-careful`, or `savvy-flow:savvy-careful` when the agents ship in a plugin; `scout`, `builder`, `reviewer`.
380export const tierOf = (type: string): string => {
381 const bare = type.replace(/^[^:]*:/, '')
382 const t = bare.replace(/^savvy-/, '').toLowerCase()
383 return t in TIER_COLOR && (bare.startsWith('savvy-') || CREW.includes(bare.toLowerCase())) ? t : 'other'
384}
385
386// A worker the bar counts and the panel opens for.
387const isCrew = (type: string): boolean => type.startsWith('savvy-') || CREW.includes(tierOf(type))
388
389const modelName = (id: string): string => {
390 const m = /(fable|mythos|opus|sonnet|haiku)-(\d+)(?:-(\d{1,2})(?!\d))?/i.exec(id)
391 const [, family = '', major = '', minor] = m ?? []
392 if (!family) return id.replace(/^claude-/, '').replace(/\[.*\]$/, '') || '—'
393 return `${family.charAt(0).toUpperCase()}${family.slice(1).toLowerCase()} ${major}${minor ? '.' + minor : ''}`
394}
395
396const norm = (s: string): string => s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim()
397
398const fmtTokens = (n: number): string =>
399 n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : `${Math.round(n)}`
400
401const fmtCost = (usd: number): string => `$${usd < 10 ? usd.toFixed(2) : usd.toFixed(1)}`
402
403const fmtTime = (ms: number): string => {
404 const s = Math.max(0, Math.round(ms / 1000))
405 const h = Math.floor(s / 3600)
406 const m = Math.floor((s % 3600) / 60)
407 const ss = String(s % 60).padStart(2, '0')
408 return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`
409}
410
411const elapsed = (a: AgentRun, at: number): number => (a.endedAt ?? Math.max(at, a.startedAt)) - a.startedAt
412
413type Planned = PlannedTask & { n: number }
414
415const plannedOf = (f: Flow | null, list: AgentRun[]): Planned[] => {
416 if (!f || f.isFinished) return []
417 const started = new Set(list.map(a => norm(a.description)))
418 return (f.tasks ?? []).map((t, i) => ({ ...t, n: i + 1 })).filter(t => !started.has(norm(t.title)))
419}
420
421const totals = (list: AgentRun[], at: number) => {
422 const cost = list.reduce((s, a) => s + a.costUsd, 0)
423 const tokens = list.reduce((s, a) => s + a.tokens, 0)
424 const start = Math.min(...list.map(a => a.startedAt))
425 const end = Math.max(...list.map(a => a.endedAt ?? Math.max(at, a.startedAt)))
426 return { cost, tokens, time: list.length ? end - start : 0 }
427}
428
429// --- desktop drawings: each row is one SVG, as the band above the prompt is.
430
431const PANE_CSS = `<style>
432.t{fill:#1f1f1f}.s{fill:#6b6b68}.m{fill:#9a9a96}.k{fill:#ecebe8}.ln{stroke:#e4e4e1}.tile{fill:#f4f3f0}
433@media (prefers-color-scheme: dark){.t{fill:#ececec}.s{fill:#a8a8a4}.m{fill:#7d7d79}.k{fill:#2c2c2b}.ln{stroke:#333331}.tile{fill:#262625}}
434.live{animation:p 1.6s ease-in-out infinite}@keyframes p{50%{opacity:.3}}
435@media (prefers-reduced-motion: reduce){.live{animation:none}}
436</style>`
437
438// Pixel Clawd from DockCrab (Clawdy): a 24×18 crab on a 30×28 grid, one costume per tier.
439// The body keeps the brand clay; the tier's color lives in the costume's accent.
440const CLAY = '#D97757'
441const INK = '#1F1E1D'
442
443// `cls` puts a pixel in a named group: `bd` (the default) is the body and its
444// costume, `la`/`lb` the leg pairs, anything else a prop with its own motion (type Fill, in sprite.ts).
445
446const stamp = (f: Fill, x: number, y: number, rows: string[], map: Record<string, string>, cls?: string): void =>
447 rows.forEach((row, dy) => [...row].forEach((ch, dx) => map[ch] && f(x + dx, y + dy, 1, 1, map[ch] ?? '', cls)))
448
449// `armCls` lets a raised claw travel with the prop it holds.
450const crabBody = (f: Fill, armFront = 0, armCls?: string): void => {
451 f(7, 10, 16, 12, CLAY)
452 f(3, 14, 4, 4, CLAY)
453 f(23, 14 + armFront, 4, 4, CLAY, armCls)
454 f(9, 12, 2, 2, INK)
455 f(19, 12, 2, 2, INK)
456 f(7, 22, 2, 4, CLAY, 'la')
457 f(17, 22, 2, 4, CLAY, 'la')
458 f(11, 22, 2, 4, CLAY, 'lb')
459 f(21, 22, 2, 4, CLAY, 'lb')
460}
461
462// Pure CSS, run by the compositor: no redraws. Periods divide one second, so the
463// once-a-second redraw of a running row restarts them in phase. Every crab walks;
464// each costume adds its prop's own motion on top.
465const CRAB_CSS = `<style>
466.run .la{animation:st .5s steps(1) infinite}.run .lb{animation:st .5s steps(1) infinite -.25s}
467.run .bd{animation:bob .5s steps(1) infinite -.125s}
468.run g{transform-box:fill-box}
469@keyframes st{50%{transform:translateY(-1px)}}@keyframes bob{50%{transform:translateY(1px)}}
470.c-fable.run{animation:float 1s ease-in-out infinite}
471.c-fable.run .la,.c-fable.run .lb,.c-fable.run .bd{animation:none}
472.c-fable.run .ant{animation:blink 1s steps(1) infinite}
473.c-fable.run .star{animation:blink .5s steps(1) infinite -.25s}
474@keyframes float{50%{transform:translateY(-2px)}}@keyframes blink{50%{opacity:.15}}
475.c-heavy.run .it{animation:scan 1s steps(1) infinite}
476.c-heavy.run .gl{animation:blink 1s steps(1) infinite -.5s}
477@keyframes scan{25%{transform:translate(-1px,1px)}50%{transform:translate(-2px,2px)}75%{transform:translate(-1px,1px)}}
478.c-careful.run .it{transform-origin:100% 100%;animation:twist .5s ease-in-out infinite}
479@keyframes twist{50%{transform:rotate(-35deg)}}
480.c-medium.run .pan{transform-origin:0 50%;animation:tilt 1s ease-in-out infinite}
481.c-medium.run .egg{animation:flip 1s ease-in-out infinite}
482@keyframes tilt{20%,40%{transform:rotate(-12deg)}}@keyframes flip{30%{transform:translateY(-5px) scaleY(-1)}60%{transform:translateY(0)}}
483.c-light.run .la{animation-duration:.25s}.c-light.run .lb{animation-duration:.25s;animation-delay:-.125s}
484.c-light.run .flag{transform-origin:0 50%;animation:wave .25s steps(1) infinite}
485@keyframes wave{50%{transform:skewY(-12deg) scaleX(.85)}}
486.c-explore.run .it{transform-origin:50% 100%;animation:fence .5s ease-in-out infinite}
487@keyframes fence{50%{transform:rotate(25deg)}}
488.c-scout.run .it{animation:look 1s steps(1) infinite}
489@keyframes look{25%{transform:translateX(-1px)}75%{transform:translateX(1px)}}
490.c-builder.run .it{transform-origin:50% 100%;animation:hammer .5s steps(1) infinite}
491@keyframes hammer{50%{transform:rotate(35deg)}}
492.c-reviewer.run .ck{animation:blink 1s steps(1) infinite}
493.c-reviewer.run .tas{transform-origin:50% 0;animation:sway 1s ease-in-out infinite}
494@keyframes sway{50%{transform:rotate(20deg)}}
495.c-orchestrator.run .it{transform-origin:0 100%;animation:conduct 1s ease-in-out infinite}
496@keyframes conduct{25%{transform:rotate(-20deg)}75%{transform:rotate(15deg)}}
497@media (prefers-reduced-motion: reduce){.run,.run g{animation:none!important}}
498</style>`
499
500const COSTUMES: Record<string, (f: Fill, t: string) => void> = {
501 // Fable: astronaut in a glass dome; floats instead of walking, the antenna and the star blink.
502 fable: (f, t) => {
503 crabBody(f)
504 f(6, 7, 18, 1, '#E6E8EE'); f(5, 8, 1, 14, '#E6E8EE'); f(24, 8, 1, 14, '#E6E8EE'); f(6, 22, 18, 1, '#C9CCD2')
505 f(6, 8, 18, 14, 'rgba(169,214,245,.32)'); f(8, 9, 2, 1, '#fff'); f(8, 10, 1, 2, '#fff')
506 f(14, 4, 2, 3, '#C9CCD2'); f(14, 2, 2, 2, t, 'ant'); f(13, 18, 4, 2, t)
507 f(27, 3, 1, 3, '#F5C542', 'star'); f(26, 4, 3, 1, '#F5C542', 'star')
508 },
509 // Heavy: detective with a deerstalker; the magnifier sweeps and glints.
510 heavy: (f, t) => {
511 crabBody(f, -4, 'it')
512 stamp(f, 6, 3, ['......bbbbbb......', '....bbcbbcbbbb....', '...bbbbbbbbbbbb...', '..bcbbcbbcbbcbbb..', '.bbbbbbbbbbbbbbbb.', 'dddddddddddddddddd'], { b: '#7A4A26', c: '#A0703F', d: '#5A3519' })
513 f(6, 9, 18, 1, t)
514 stamp(f, 23, 1, ['.kkk.', 'k...k', 'k...k', 'k...k', '.kkk.'], { k: '#3A3A3C' }, 'it')
515 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')
516 },
517 // Careful: engineer in a hard hat; the wrench turns a bolt.
518 careful: (f, t) => {
519 crabBody(f)
520 stamp(f, 6, 4, ['.....yyyyyyyy.....', '...yyyyyhhyyyyy...', '..yyyyyyhhyyyyyy..', '..yyyyyyhhyyyyyy..', '.yyyyyyyhhyyyyyyy.', 'dddddddddddddddddd'], { y: '#F5C542', h: '#FBE08A', d: '#C99A1E' })
521 f(13, 5, 4, 2, t)
522 stamp(f, 0, 10, ['.s.s', 'sss.', '.s..', '.s..'], { s: '#8E929A' }, 'it')
523 },
524 // Medium: chef, the toque traced from DockCrab's Sprites.chefHat; tosses the omelette.
525 medium: (f, t) => {
526 crabBody(f, -4, 'pan')
527 stamp(f, 6, 0, ['........lll.......', '.......lllll......', '.wwwwgwwwwwwgwwwww', 'wwwwwwwwwwwwwwwwww', 'wwwwwwwwwwwwwwwwww', 'wwwwwgwwwwwggwwwww', '.wwwwgwwwwwggwwwww', '.dddbbbbbbbbbbbbb.', '.dddbbbbbbbbbbbbb.', '.dddbbbbbbbbbbbbb.'], { w: '#F4F3EE', l: '#F7F6F2', g: '#D2D1C8', b: t, d: '#B45F43' })
528 f(22, 8, 7, 2, '#4A4A48', 'pan'); f(26, 10, 1, 1, '#4A4A48', 'pan'); f(24, 7, 3, 1, '#F5B731', 'egg')
529 },
530 // Light: racer in a helmet; runs at double pace, the checkered flag flutters.
531 light: (f, t) => {
532 crabBody(f, -4)
533 stamp(f, 6, 5, ['....rrrrrrrrrr....', '..rrrrrrwwrrrrrr..', '.rrrrrrrwwrrrrrrr.', '.rrrrrrrwwrrrrrrr.', '.rrrrrrrwwrrrrrrr.', '.kkkkkkkkkkkkkkkkr'], { r: t, w: '#F8F6F1', k: INK })
534 f(25, 1, 1, 9, '#8E929A')
535 stamp(f, 26, 1, ['wkwk', 'kwkw', 'wkwk'], { w: '#F8F6F1', k: INK }, 'flag')
536 },
537 // Explore: pirate scouting the code; the cutlass fences.
538 explore: f => {
539 crabBody(f)
540 stamp(f, 5, 3, ['.kk..............kk.', '.kkk....kkkk....kkk.', '..kkkkkkkwwkkkkkkk..', '..kkkkkkkkkkkkkkkk..', '.gggggggggggggggggg.'], { k: '#55514C', w: '#F8F6F1', g: '#F5C542' })
541 f(7, 11, 11, 1, INK); f(18, 11, 4, 3, INK)
542 f(27, 6, 1, 9, '#C9CCD2', 'it'); f(26, 15, 3, 1, '#7A4A26', 'it')
543 },
544 // Scout (Haiku): ranger in a campaign hat; sweeps the binoculars left and right.
545 scout: (f, t) => {
546 crabBody(f, -4, 'it')
547 stamp(f, 6, 4, ['.......kkkk.......', '......kkkkkk......', '.....kkkkkkkk.....', '.....bbbbbbbb.....', 'dddddddddddddddddd'], { k: '#B89A5E', b: t, d: '#8C7140' })
548 stamp(f, 22, 7, ['kk.kk', 'kkkkk', 'll.ll'], { k: '#3A3A3C', l: 'rgba(169,214,245,.8)' }, 'it')
549 },
550 // Builder (Sonnet): hard hat in the tier color and a tool belt; the hammer swings.
551 builder: (f, t) => {
552 crabBody(f, -4, 'it')
553 stamp(f, 6, 5, ['.....hhhhhhhh.....', '...hhhhhwwhhhhh...', '..hhhhhhwwhhhhhh..', '.hhhhhhhwwhhhhhhh.', 'dddddddddddddddddd'], { h: t, w: 'rgba(255,255,255,.45)', d: '#5A3519' })
554 f(7, 19, 16, 1, '#7A4A26'); f(14, 19, 2, 1, '#F5C542')
555 f(25, 3, 1, 8, '#A0703F', 'it'); f(23, 1, 5, 2, '#8E929A', 'it')
556 },
557 // Reviewer (Opus): mortarboard and round glasses; the clipboard's check mark ticks, the tassel sways.
558 reviewer: (f, t) => {
559 crabBody(f, -4)
560 stamp(f, 6, 4, ['.......bbbb.......', '....bbbbbbbbbb....', '.bbbbbbbbbbbbbbbb.', '....bbbbbbbbbb....', '.....cccccccc.....', '.....cccccccc.....'], { b: '#2C2C2E', c: '#3A3A3C' })
561 f(21, 6, 1, 4, t, 'tas'); f(20, 10, 3, 1, t, 'tas')
562 const k = '#3A3A3C'
563 f(8, 11, 4, 1, k); f(8, 14, 4, 1, k); f(8, 11, 1, 4, k); f(11, 11, 1, 4, k)
564 f(18, 11, 4, 1, k); f(18, 14, 4, 1, k); f(18, 11, 1, 4, k); f(21, 11, 1, 4, k); f(12, 12, 6, 1, k)
565 f(24, 3, 5, 8, '#A0703F'); f(25, 4, 3, 6, '#F8F6F1'); f(25, 2, 3, 2, '#8E929A')
566 f(25, 6, 1, 1, t, 'ck'); f(26, 7, 1, 1, t, 'ck'); f(27, 5, 1, 2, t, 'ck')
567 },
568 // Orchestrator (the main session, on the progress bar): conductor in a top hat and bow tie; the baton keeps time.
569 orchestrator: (f, t) => {
570 crabBody(f, -4, 'it')
571 stamp(f, 8, 3, ['...hhhhhhhh...', '...hhhhhhhh...', '...hhhhhhhh...', '...hhhhhhhh...', '...bbbbbbbb...', '...hhhhhhhh...', 'hhhhhhhhhhhhhh'], { h: '#2C2C2E', b: t })
572 stamp(f, 12, 16, ['tt..tt', 'tttttt', 'tt..tt'], { t })
573 stamp(f, 25, 3, ['....w', '....k', '...k.', '...k.', '..k..', '..k..', '.k...'], { k: '#3A3A3C', w: t }, 'it')
574 },
575 other: f => crabBody(f),
576}
577
578const costumeOf = (type: string): string => (type === 'Explore' ? 'explore' : tierOf(type))
579
580// --- terminal crabs: Clawd with the tier's prop (sprite.ts).
581
582export const spriteOf = (costume: string, frame = 0): Run[][] => clawd(costume, colorOf(costume), frame)
583
584const CRAB_SCALE = 1.1
585
586// Body and props nest inside `bd` so a prop rides the bob and adds its own motion;
587// legs stay outside it and step on their own.
588export const crab = (x: number, y: number, costume: string, dim = false, isWalking = false, scale = CRAB_SCALE): string => {
589 const groups = new Map<string, string[]>([['bd', []]])
590 const f: Fill = (cx, cy, w, h, c, cls = 'bd') => {
591 if (!groups.has(cls)) groups.set(cls, [])
592 groups.get(cls)?.push(`<rect x="${cx}" y="${cy}" width="${w}" height="${h}" fill="${c}"/>`)
593 }
594 const draw = COSTUMES[costume] ?? ((g: Fill) => crabBody(g))
595 draw(f, colorOf(costume))
596 const group = (cls: string) => `<g class="${cls}">${(groups.get(cls) ?? []).join('')}</g>`
597 const props = [...groups.keys()].filter(k => k !== 'bd' && k !== 'la' && k !== 'lb')
598 const body = `<g class="bd">${(groups.get('bd') ?? []).join('')}${props.map(group).join('')}</g>`
599 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>`
600}
601
602const statusMark = (x: number, y: number, status: string, color: string): string => {
603 if (status === 'running') return `<circle class="live" cx="${x}" cy="${y}" r="3.5" fill="${color}"/>`
604 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"/>`
605 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"/>`
606 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"/>`
607}
608
609const svg = (W: number, H: number, body: string): string =>
610 `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">${PANE_CSS}${CRAB_CSS}${body}</svg>`
611
612// The pane's own title already says "Agents": the header names the flow, if any.
613const headerSvg = (W: number, title: string, t: ReturnType<typeof totals>): string => {
614 const s = tr()
615 const gap = 6
616 const tw = (W - gap * 2) / 3
617 const top = title ? 28 : 0
618 const tile = (i: number, k: string, v: string) =>
619 `<rect class="tile" x="${i * (tw + gap)}" y="${top}" width="${tw}" height="40" rx="8"/>
620<text class="s" x="${i * (tw + gap) + 9}" y="${top + 16}" font-family="${FONT}" font-size="11">${k}</text>
621<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>`
622 return svg(
623 W,
624 headerHeight(title),
625 `${title ? `<text class="t" x="0" y="15" font-family="${FONT}" font-size="14" font-weight="600">${xml(fitText(title, 14, W))}</text>` : ''}
626${tile(0, s.cost, '≈' + fmtCost(t.cost))}${tile(1, s.tokens, fmtTokens(t.tokens))}${tile(2, s.time, fmtTime(t.time))}`,
627 )
628}
629
630const headerHeight = (title: string): number => (title ? 72 : 44)
631
632// The task's own progress when the worker reports steps; a finished run is full.
633const progressOf = (a: AgentRun): number | null => {
634 if (a.status === 'done') return 1
635 if (a.stepTotal) return Math.min(1, (a.stepDone ?? 0) / a.stepTotal)
636 return null
637}
638
639const ctxOf = (a: AgentRun): number => (a.contextMax ? Math.min(100, Math.round((a.contextTokens / a.contextMax) * 100)) : 0)
640
641const agentSvg = (W: number, a: AgentRun, at: number): string => {
642 const s = tr()
643 const tier = tierOf(a.type)
644 const color = colorOf(tier)
645 const ctx = ctxOf(a)
646 const textW = W - 42 - 22
647 const meta = [a.effort ? `${modelName(a.model)} · ${a.effort}` : modelName(a.model)]
648 if (a.round > 1) meta.push(`${s.round} ${a.round}`)
649 if (a.status === 'failed') meta.push(s.failed)
650 const barW = textW
651 const progress = progressOf(a)
652 const stats = `ctx ${ctx}% · ${fmtTokens(a.contextTokens)} ≈${fmtCost(a.costUsd)} ${fmtTime(elapsed(a, at))}`
653 const steps = a.stepTotal ? `${a.stepDone ?? 0}/${a.stepTotal}${a.stepNote ? ' · ' + a.stepNote : ''}` : ''
654 const stepsW = Math.max(0, barW - textWidth(stats, 11) - 12)
655 // Without reported steps the bar falls back to the context, drawn grey.
656 const fillW = Math.round(barW * (progress ?? ctx / 100))
657 return svg(
658 W,
659 66,
660 `${crab(0, 14, costumeOf(a.type), false, a.status === 'running')}
661<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>
662<text x="42" y="34" font-family="${FONT}" font-size="11"><tspan fill="${color}">${xml(tier === 'other' ? a.type : tier)}</tspan><tspan class="s"> ${xml(meta.join(' · '))}</tspan></text>
663${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>` : ''}
664<text class="s" x="${42 + barW}" y="49" text-anchor="end" font-family="${FONT}" font-size="11" font-variant-numeric="tabular-nums">${stats}</text>
665<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}"`}/>
666${statusMark(W - 8, 16, a.status, color)}
667<line class="ln" x1="0" y1="65.5" x2="${W}" y2="65.5"/>`,
668 )
669}
670
671const plannedSvg = (W: number, p: Planned): string => {
672 const tier = p.tier in TIER_COLOR ? p.tier : 'other'
673 const color = colorOf(tier)
674 const textW = W - 42 - 22
675 const meta = [TIER_MODEL[tier] ?? '']
676 if (p.after.length) meta.push(`${tr().after} ${p.after.join(', ')}`)
677 return svg(
678 W,
679 46,
680 `${crab(0, 6, tier, true)}
681<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>
682<text x="42" y="34" font-family="${FONT}" font-size="11"><tspan fill="${color}">${xml(tier)}</tspan><tspan class="m"> ${xml(meta.filter(Boolean).join(' · '))}</tspan></text>
683${statusMark(W - 8, 16, 'planned', color)}
684<line class="ln" x1="0" y1="45.5" x2="${W}" y2="45.5"/>`,
685 )
686}
687
688const WAITING = '#E0A030'
689
690const bgModel = (b: BgSession): string => [b.model ? (aliasLabel(b.model) ?? modelName(b.model)) : '—', b.effort].filter(Boolean).join(' · ')
691
692const bgStateText = (b: BgSession): string => (b.state === 'waiting' ? tr().bgWaiting : b.state === 'busy' ? tr().bgBusy : tr().bgIdle)
693
694// A session of its own, not a subagent: no cost, tokens or context (they are not visible from here).
695const bgSvg = (W: number, b: BgSession): string => {
696 const color = colorOf(b.tier)
697 const state = bgStateText(b)
698 const textW = W - 42 - 22
699 const branch = b.branch ? fitText(b.branch, 11, textW / 2) : ''
700 const tier = b.tier === 'other' ? tr().session : b.tier
701 const mark =
702 b.state === 'busy'
703 ? statusMark(W - 8, 16, 'running', color)
704 : b.state === 'waiting'
705 ? `<circle class="live" cx="${W - 8}" cy="16" r="3.5" fill="${WAITING}"/>`
706 : `<circle cx="${W - 8}" cy="16" r="3.5" fill="none" stroke="#9a9a96" stroke-width="1.4"/>`
707 return svg(
708 W,
709 46,
710 `${crab(0, 6, b.tier, b.state === 'idle', b.state === 'busy')}
711<text class="t" x="42" y="18" font-family="${FONT}" font-size="13" font-weight="600">${xml(fitText(b.name, 13, textW - textWidth(state, 11) - 8))}</text>
712<text class="s" x="${W - 22}" y="18" text-anchor="end" font-family="${FONT}" font-size="11"${b.state === 'waiting' ? ` fill="${WAITING}"` : ''}>${xml(state)}</text>
713<text x="42" y="34" font-family="${FONT}" font-size="11"><tspan fill="${color}">${xml(tier)}</tspan><tspan class="s"> · ${xml(fitText(bgModel(b), 11, Math.max(30, textW - textWidth(tier, 11) - textWidth(branch, 11) - 24)))}</tspan></text>
714${branch ? `<text class="m" x="${W - 22}" y="34" text-anchor="end" font-family="${FONT}" font-size="11">${xml(branch)}</text>` : ''}
715${mark}
716<line class="ln" x1="0" y1="45.5" x2="${W}" y2="45.5"/>`,
717 )
718}
719
720const compactSvg = (W: number, list: AgentRun[], planned: Planned[], sessions: BgSession[], t: ReturnType<typeof totals>): string => {
721 const icons = [
722 ...list.filter(a => a.status === 'running').map(a => ({ k: costumeOf(a.type), c: colorOf(tierOf(a.type)), s: 'running', dim: false })),
723 ...list.filter(a => a.status !== 'running').map(a => ({ k: costumeOf(a.type), c: colorOf(tierOf(a.type)), s: a.status, dim: false })),
724 ...planned.map(p => ({ k: p.tier in TIER_COLOR ? p.tier : 'other', c: colorOf(p.tier), s: 'planned', dim: true })),
725 ...sessions.map(b => ({ k: b.tier, c: colorOf(b.tier), s: b.state === 'busy' ? 'running' : 'idle', dim: b.state === 'idle' })),
726 ]
727 const fit = Math.max(1, Math.floor((W - 150) / 36))
728 const shown = icons.slice(0, fit)
729 const more = icons.length - shown.length
730 const body = shown
731 .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}"/>` : ''))
732 .join('')
733 const x = shown.length * 36 + (more ? 4 : 0)
734 return svg(
735 W,
736 32,
737 `${body}${more ? `<text class="s" x="${x}" y="21" font-family="${FONT}" font-size="12">+${more}</text>` : ''}
738<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>`,
739 )
740}
741
742// --- terminal drawing: the same rows in text.
743
744type TextTag = ReturnType<EngineInterface['ui']['resolve']>['Text']
745
746// A sprite as lines of text: each run of cells is one Text in its color.
747const crabLines = (Text: TextTag, lines: Run[][], key: string) =>
748 lines.map((line, y) => (
749 <Text key={`${key}-${y}`}>
750 {line.map((r, x) => (
751 <Text key={`${x}`} color={r.fg}>
752 {r.text}
753 </Text>
754 ))}
755 </Text>
756 ))
757
758const BG_GLYPH = { busy: '●', waiting: '▲', idle: '○' } as const
759
760const ctxBar = (pct: number, width: number): string => {
761 const filled = Math.round((width * pct) / 100)
762 return '█'.repeat(filled) + '░'.repeat(Math.max(0, width - filled))
763}
764
765const STATUS_GLYPH: Record<string, string> = { running: '●', done: '✓', failed: '✗', planned: '◷' }
766
767// Background sessions: `claude agents --json` plus one `git worktree list` per poll, so the branch costs no
768// extra call per session. Runs only while the pane is open or a flow's bar is up (the clock in session.start).
769let isPolling = false
770
771async function pollBg($: EngineInterface): Promise<void> {
772 if (isPolling) return
773 isPolling = true
774 try {
775 const self = await $.session.id()
776 const repo = await $.session.repo()
777 const ran = await $.process.run(['claude', 'agents', '--json'], { timeoutMs: 10_000 })
778 if (ran.exitCode !== 0) return
779 const tree = repo ? await $.process.run(['git', '-C', repo.root, 'worktree', 'list', '--porcelain'], { timeoutMs: 5000 }).catch(() => null) : null
780 const trees = tree?.exitCode === 0 ? parseWorktrees(tree.stdout) : []
781 const launched = await read($, launches)
782 const list: BgSession[] = parseAgents(ran.stdout)
783 .filter(a => a.sessionId !== self && a.kind !== 'interactive' && isRelated(a, trees, launched))
784 .slice(0, 24)
785 .map(a => {
786 const l = launched[a.name.toLowerCase()]
787 return { id: a.sessionId, name: a.name, state: bgState(a), tier: tierFor(l), model: l?.model, effort: l?.effort, branch: branchOf(a, trees), cwd: a.cwd }
788 })
789 const prev = await read($, bg)
790 if (JSON.stringify(prev) !== JSON.stringify(list)) await update($, bg, () => list)
791 } catch {
792 // The list stays as it was; the next poll tries again.
793 } finally {
794 isPolling = false
795 }
796}
797
798// Opens the agents pane, or closes it when it is up; true when it ends up open.
799async function togglePane($: EngineInterface): Promise<boolean> {
800 const isOpen = (await $.ui.panes()).some(p => p.id === PANE)
801 if (isOpen) {
802 await $.ui.close({ id: PANE })
803 return false
804 }
805 const at = await $.clock.now()
806 await update($, now, () => at)
807 await $.ui.open({ id: PANE, title: tr().pane })
808 await pollBg($)
809 return true
810}
811
812async function autoOpen($: EngineInterface, key: string): Promise<void> {
813 const p = await read($, panel)
814 if (p.autoOpenedFor === key) return
815 await update($, panel, prev => ({ ...prev, autoOpenedFor: key }))
816 void $.ui.open({ id: PANE, title: tr().pane })
817 void pollBg($)
818}
819
820// The view pane re-reads its target every VIEW_EVERY_MS while shown: an agent's transcript from this
821// session; a background session's transcript file (its tail), else its terminal through `claude logs`.
822let isViewing = false
823// Where each background session's transcript was found, and its mtime at the last read (skip when unchanged).
824const transcriptPaths = new Map<string, string>()
825let lastRead = ''
826
827// Bytes from the end: screenshots make single entries hundreds of KB, so a line count would see too little.
828const TAIL_BYTES = 3_500_000
829
830async function findTranscript($: EngineInterface, id: string, cwd?: string): Promise<string | null> {
831 const known = transcriptPaths.get(id)
832 if (known) return known
833 const config = await $.env.get('CLAUDE_CONFIG_DIR')
834 const home = (await $.env.get('USERPROFILE')) || (await $.env.get('HOME'))
835 const root = `${config || `${home}/.claude`}/projects`
836 // The folder is the cwd with every other character a dash; a scan covers a name the engine shortened.
837 const guess = cwd ? [cwd.replace(/[^a-zA-Z0-9]/g, '-')] : []
838 const dirs = [...guess, ...(await $.fs.list(root).catch(() => [])).filter(d => d.kind === 'dir').map(d => d.name)]
839 for (const d of dirs) {
840 const path = `${root}/${d}/${id}.jsonl`
841 if (await $.fs.exists(path)) {
842 transcriptPaths.set(id, path)
843 return path
844 }
845 }
846 return null
847}
848
849// The file's last TAIL_BYTES: read whole when small, else `tail -c` (a seek in PowerShell on Windows, raw
850// bytes so no code page touches them); a file read rejects over 4 MiB. Null when unchanged since the last read.
851async function readTail($: EngineInterface, path: string): Promise<string | null> {
852 const st = await $.fs.stat(path)
853 const stamp = `${path}:${st.mtimeMs}:${st.size}`
854 if (stamp === lastRead) return null
855 let text: string
856 if (st.size <= TAIL_BYTES) text = await $.fs.read(path)
857 else {
858 const isWindows = /^[A-Za-z]:/.test(path)
859 const ps =
860 `$f=[IO.File]::Open('${path.replace(/'/g, "''")}','Open','Read','ReadWrite'); $n=[Math]::Min($f.Length,${TAIL_BYTES}); ` +
861 `[void]$f.Seek(-$n,'End'); $b=New-Object byte[] $n; [void]$f.Read($b,0,$n); $f.Close(); ` +
862 `$o=[Console]::OpenStandardOutput(); $o.Write($b,0,$n); $o.Flush()`
863 const argv = isWindows ? ['powershell', '-NoProfile', '-Command', ps] : ['tail', '-c', String(TAIL_BYTES), path]
864 const ran = await $.process.run(argv, { timeoutMs: 10_000 })
865 if (ran.exitCode !== 0) throw new Error(ran.stderr.trim() || 'tail failed')
866 text = ran.stdout
867 }
868 lastRead = stamp
869 return text
870}
871
872async function refreshView($: EngineInterface): Promise<void> {
873 const v = await read($, view)
874 if (!v || isViewing) return
875 isViewing = true
876 try {
877 let lines: ViewLine[]
878 let source: 'transcript' | 'logs' = 'transcript'
879 if (v.kind === 'agent') {
880 const found = await $.session.messages({ agentId: v.id })
881 lines = Array.isArray(found) ? messageLines(found) : [{ kind: 'error', text: found.deny }]
882 } else {
883 const path = await findTranscript($, v.id, v.cwd)
884 const text = path ? await readTail($, path) : undefined
885 if (text === null) return // unchanged
886 if (text !== undefined) lines = messageLines(transcriptMessages(text))
887 else {
888 // `claude logs` takes the short id `claude agents` prints, not the session id.
889 const ran = await $.process.run(['claude', 'logs', v.id.slice(0, 8)], { timeoutMs: 10_000 })
890 lines = ran.exitCode === 0 ? logLines(ran.stdout) : [{ kind: 'error', text: `claude logs: ${clean(ran.stderr || ran.stdout).trim()}` }]
891 source = 'logs'
892 }
893 }
894 let isChanged = false
895 await update($, view, prev => {
896 isChanged = !!prev && prev.id === v.id && (prev.source !== source || JSON.stringify(prev.lines) !== JSON.stringify(lines))
897 return isChanged && prev ? { ...prev, lines, source } : prev
898 })
899 if (isChanged && (await read($, viewFollow))) await $.ui.scroll({ in: VIEW_PANE, to: 'end' }).catch(() => undefined)
900 } catch (err) {
901 const lines: ViewLine[] = [{ kind: 'error', text: clean(String(err)) }]
902 await update($, view, prev => (prev && prev.id === v.id ? { ...prev, lines } : prev))
903 } finally {
904 isViewing = false
905 }
906}
907
908async function openView($: EngineInterface, raw: ViewTarget): Promise<void> {
909 // A session names itself: the name reaches the tab title and the header, so it is cleaned too.
910 const target = { ...raw, name: clean(raw.name) }
911 lastRead = ''
912 await update($, view, () => ({ ...target, lines: [] }))
913 await update($, viewFollow, () => true)
914 await $.ui.open({ id: VIEW_PANE, title: target.name.slice(0, 40) || target.id.slice(0, 8), focus: true, closeOnEscape: true })
915 await refreshView($)
916}
917
918export const register: Register = (on, options) => {
919 on('session.start', async ($, e, next) => {
920 const started = await next(e)
921 lang = await detectLang($, options.language)
922 await $.tool.register({
923 name: 'progress',
924 description:
925 'Report /savvy-flow progress to the progress bar above the prompt and the agents panel. ' +
926 'Call it after presenting the plan (title, total, tasks, phase "delegate"), each time a task is accepted (done), ' +
927 'when switching phase or re-planning (tasks), and once at the end with finished: true. Fields left out keep their previous value.',
928 inputSchema: {
929 type: 'object',
930 properties: {
931 title: { type: 'string', description: 'Short name of the overall task, a few words.' },
932 total: { type: 'integer', minimum: 0, description: 'Number of planned worker tasks.' },
933 done: { type: 'integer', minimum: 0, description: 'Number of tasks accepted after review.' },
934 phase: { type: 'string', enum: [...PHASES] },
935 finished: { type: 'boolean', description: 'True once the flow is closed.' },
936 tasks: {
937 type: 'array',
938 description:
939 '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.',
940 items: {
941 type: 'object',
942 properties: {
943 title: { type: 'string', description: 'A few words; reused verbatim as the Agent description.' },
944 tier: { type: 'string', enum: ['fable', 'heavy', 'careful', 'medium', 'light', ...CREW] },
945 after: { type: 'array', items: { type: 'integer' }, description: 'Numbers of the tasks this one waits for.' },
946 },
947 required: ['title', 'tier'],
948 },
949 },
950 },
951 },
952 })
953 await $.tool.register({
954 name: 'step',
955 description:
956 'For savvy-flow workers: report progress on your own task to the agents panel. ' +
957 'Right after reading the brief, call it with `total` (your plan in 3-8 steps) and `done: 0`; ' +
958 'call it again as each step finishes. Cheap and silent: it only draws a bar.',
959 inputSchema: {
960 type: 'object',
961 properties: {
962 done: { type: 'integer', minimum: 0, description: 'Steps finished so far.' },
963 total: { type: 'integer', minimum: 1, description: 'Steps planned; may change if the plan changes.' },
964 note: { type: 'string', description: 'The step in progress, a few words.' },
965 },
966 required: ['done'],
967 },
968 })
969 await $.command.register({
970 name: 'agents-info',
971 description: 'Show or hide the panel of subagents: running, finished and planned, with model, context, cost and time',
972 })
973
974 // Polls the background sessions, but only with the pane open or a flow's bar up: otherwise nothing runs.
975 $.clock.every(BG_EVERY_MS, () => {
976 void (async () => {
977 const f = await read($, flow)
978 if ((await $.ui.panes()).some(p => p.id === PANE) || (f && !f.isFinished)) await pollBg($)
979 })()
980 })
981
982 $.clock.every(VIEW_EVERY_MS, () => {
983 void (async () => {
984 if ((await $.ui.panes()).some(p => p.id === VIEW_PANE && p.isShown)) await refreshView($)
985 })()
986 })
987
988 // Ticks the running agents' clocks; quiet when nothing runs.
989 $.clock.every(1000, () => {
990 void (async () => {
991 const list = await read($, agents)
992 if (!list.some(a => a.status === 'running')) return
993 const at = await $.clock.now()
994 await update($, now, () => at)
995 })()
996 })
997 // Flips the running crabs' pose; quiet unless the pane is open and something runs.
998 $.clock.every(CRAB_EVERY_MS, () => {
999 void (async () => {
1000 const isBusy = (await read($, agents)).some(a => a.status === 'running') || (await read($, bg)).some(b => b.state === 'busy')
1001 if (isBusy && (await $.ui.panes()).some(p => p.id === PANE)) await update($, frame, n => 1 - n)
1002 })()
1003 })
1004 return started
1005 })
1006
1007 on('command.run', { command: 'agents-info' }, async $ => {
1008 const isOpen = await togglePane($)
1009 return { text: isOpen ? tr().opened : tr().closed }
1010 })
1011
1012 on('tool.call', { tool: TOOL }, async ($, e) => {
1013 const input = e as unknown as ProgressInput
1014 const prev = await read($, flow)
1015 if (isNewFlow(prev, input) && input.title !== undefined) {
1016 // A new flow starts with a clean list; agents still running stay.
1017 await update($, agents, list => list.filter(a => a.status === 'running'))
1018 }
1019 const next = await update($, flow, p => merge(p, input))
1020 if (next && input.tasks?.length) await autoOpen($, next.title)
1021 return { result: `ok: ${label(next ?? blank())}` }
1022 })
1023
1024 // A worker's own progress: the call runs in the worker's loop, so agentId names it.
1025 on('tool.call', { tool: STEP_TOOL }, async ($, e) => {
1026 const input = e as unknown as { done?: number; total?: number; note?: string }
1027 const agentId = e.agentId
1028 if (!agentId) return { result: 'ignored: only subagents report steps' }
1029 await update($, agents, list =>
1030 list.map(a => {
1031 if (a.agentId !== agentId) return a
1032 const total = Math.max(0, Math.round(input.total ?? a.stepTotal ?? 0))
1033 const done = Math.max(0, Math.round(input.done ?? a.stepDone ?? 0))
1034 return { ...a, stepTotal: total, stepDone: total ? Math.min(total, done) : done, stepNote: input.note?.trim() || undefined }
1035 }),
1036 )
1037 return { result: 'ok' }
1038 })
1039
1040 // This session's own background launches: the only place their model, effort and agent can be learned.
1041 on('tool.call', { tool: ['Bash', 'PowerShell'] }, async ($, e, next) => {
1042 try {
1043 const found = bgLaunches(String(e.command ?? '')).filter(l => l.name)
1044 if (found.length) {
1045 await update($, launches, all => ({
1046 ...all,
1047 ...Object.fromEntries(found.map(l => [(l.name ?? '').toLowerCase(), { model: l.model, effort: l.effort, agent: l.agent }])),
1048 }))
1049 }
1050 } catch {
1051 // Only a label for the panel: never worth failing the call.
1052 }
1053 return next(e)
1054 })
1055
1056 // Safety net: worker launches move the faint layer even if the orchestrator forgets to report.
1057 on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
1058 const type = String(e.subagent_type ?? '')
1059 if (!isCrew(type)) return next(e)
1060
1061 await update($, flow, prev => {
1062 const base = prev && !prev.isFinished ? { ...blank(), ...prev } : blank()
1063 return { ...base, running: base.running + 1, phase: base.phase === 'plan' ? 'delegate' : base.phase }
1064 })
1065 try {
1066 return await next(e)
1067 } finally {
1068 await update($, flow, prev => (prev ? { ...prev, running: Math.max(0, prev.running - 1) } : prev))
1069 }
1070 })
1071
1072 on('agent.spawn', async ($, e, next) => {
1073 const started = await next(e)
1074 if (started.deny !== undefined) return started
1075
1076 const at = await $.clock.now()
1077 await update($, agents, list => {
1078 const round = 1 + list.filter(a => norm(a.description) === norm(e.description) && e.description).length
1079 const run: AgentRun = {
1080 id: started.agentId ?? e.tool_use_id,
1081 agentId: started.agentId,
1082 type: e.subagentType,
1083 description: e.description,
1084 model: started.model,
1085 status: 'running',
1086 startedAt: at,
1087 contextTokens: 0,
1088 contextMax: windowOf(started.model),
1089 tokens: 0,
1090 costUsd: 0,
1091 steps: 0,
1092 round,
1093 }
1094 return [...list.filter(a => a.id !== run.id), run].slice(-200)
1095 })
1096 await update($, now, () => at)
1097 if (isCrew(e.subagentType)) {
1098 const f = await read($, flow)
1099 await autoOpen($, f && !f.isFinished ? f.title : 'savvy-flow')
1100 }
1101 return started
1102 })
1103
1104 // Each model request of a subagent: live context, tokens and cost.
1105 on('turn.step', async function* ($, e, next) {
1106 const result = yield* next(e)
1107 const agentId = e.agentId
1108 const usage = result.usage
1109 if (!agentId || !usage) return result
1110
1111 const model = usage.model || e.model
1112 await update($, agents, list =>
1113 list.map(a =>
1114 a.agentId !== agentId
1115 ? a
1116 : {
1117 ...a,
1118 model,
1119 effort: typeof e.effort === 'string' ? e.effort : a.effort,
1120 status: 'running',
1121 endedAt: undefined,
1122 contextTokens:
1123 (usage.input_tokens || 0) +
1124 (usage.cache_read_input_tokens || 0) +
1125 (usage.cache_creation_input_tokens || 0) +
1126 (usage.output_tokens || 0),
1127 contextMax: windowOf(model),
1128 tokens:
1129 a.tokens +
1130 (usage.input_tokens || 0) +
1131 (usage.output_tokens || 0) +
1132 (usage.cache_read_input_tokens || 0) +
1133 (usage.cache_creation_input_tokens || 0),
1134 costUsd: a.costUsd + costOf(model, usage),
1135 steps: a.steps + 1,
1136 },
1137 ),
1138 )
1139 return result
1140 })
1141
1142 on('turn.complete', async ($, e, next) => {
1143 const agentId = e.agentId
1144 if (agentId) {
1145 const at = await $.clock.now()
1146 await update($, agents, list =>
1147 list.map(a => {
1148 if (a.agentId !== agentId) return a
1149 // A run whose steps went unseen still gets the turn's own sum.
1150 const fallback = a.steps === 0 && e.usage
1151 return {
1152 ...a,
1153 status: e.reason === 'answer' ? 'done' : 'failed',
1154 endedAt: at,
1155 ...(fallback && e.usage
1156 ? {
1157 model: e.usage.model || a.model,
1158 tokens:
1159 e.usage.input_tokens +
1160 e.usage.output_tokens +
1161 e.usage.cache_read_input_tokens +
1162 e.usage.cache_creation_input_tokens,
1163 costUsd: costOf(e.usage.model || a.model, e.usage),
1164 }
1165 : {}),
1166 }
1167 }),
1168 )
1169 await update($, now, () => at)
1170 }
1171 return next(e)
1172 })
1173
1174 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1175 const s = tr()
1176 const ui = $.ui.resolve(e)
1177 const { Box, Text, Button } = ui
1178 const list = await read($, agents)
1179 const sessions = await read($, bg)
1180 const f = await read($, flow)
1181 const p: Panel = await read($, panel)
1182 const at = Math.max(await read($, now), ...list.map(a => a.startedAt), 0)
1183
1184 const running = list.filter(a => a.status === 'running').reverse()
1185 const finished = list.filter(a => a.status !== 'running').reverse()
1186 const planned = plannedOf(f, list)
1187 const t = totals(list, at)
1188 // The pane's title says "Agents"; inside, only the flow's own name.
1189 const title = f && !f.isFinished ? f.title : ''
1190
1191 const toggleCompact = (
1192 <Button
1193 key="compact"
1194 label={p.isCompact ? s.expand : s.collapse}
1195 plain
1196 onPress={() => update($, panel, prev => ({ ...prev, isCompact: !prev.isCompact }))}
1197 />
1198 )
1199 const toggleDone = (
1200 <Buttonhooks/bg.ts 184 lines1// Background sessions (`claude --bg`) for the agents panel. Plugins cannot import each other, so these
2// helpers are copies: parseAgents from plugins/workers/hooks/lib.ts, split and bgLaunches from
3// plugins/effort-gate/hooks/register.ts (route-ledger carries the same parser).
4
5import type { BgState } from '../types'
6
7/** One entry of `claude agents --json`. `status` is busy/idle/waiting, `state` working/done/blocked; either may be absent. */
8export type AgentEntry = {
9 pid?: number
10 cwd: string
11 kind?: string
12 sessionId: string
13 name: string
14 status?: string
15 state?: string
16}
17
18export const parseAgents = (stdout: string): AgentEntry[] => {
19 try {
20 const list: unknown = JSON.parse(stdout)
21 if (!Array.isArray(list)) return []
22 return list.filter(
23 (a): a is AgentEntry =>
24 typeof a === 'object' && a !== null && typeof a.sessionId === 'string' && typeof a.name === 'string',
25 )
26 } catch {
27 return []
28 }
29}
30
31/** Waiting for you beats busy; a session that reports a status is read by it, one that does not by its state. */
32export const bgState = (a: AgentEntry): BgState =>
33 a.status === 'waiting' || a.state === 'blocked'
34 ? 'waiting'
35 : a.status === 'busy' || (a.status === undefined && a.state === 'working')
36 ? 'busy'
37 : 'idle'
38
39// ---- reading `claude ... --bg` out of a shell command ----
40
41type Tok = { text: string; quoted: boolean } // quoted: the word began inside quotes (a prompt, never a flag)
42
43// Splits a command into segments (at unquoted ; | & newline) of words (at unquoted whitespace).
44// ponytail: no heredocs, backticks, $(...) or backslash escapes outside quotes; an odd apostrophe swallows the rest, which only hides flags.
45function split(cmd: string): Tok[][] {
46 const segs: Tok[][] = [[]]
47 let cur = ''
48 let has = false
49 let startQ = false
50 let q: string | null = null
51 const word = () => {
52 if (has) segs[segs.length - 1]!.push({ text: cur, quoted: startQ })
53 cur = ''
54 has = false
55 startQ = false
56 }
57 for (let i = 0; i < cmd.length; i++) {
58 const c = cmd[i]!
59 if (q) {
60 if (c === q) q = null
61 else if (c === '\\' && q === '"' && cmd[i + 1] === '"') cur += cmd[++i]
62 else cur += c
63 } else if (c === '"' || c === "'") {
64 if (!has) startQ = true
65 has = true
66 q = c
67 } else if (c === '\n' || c === ';' || c === '|' || c === '&') {
68 word()
69 if (segs[segs.length - 1]!.length) segs.push([])
70 } else if (/\s/.test(c)) word()
71 else {
72 cur += c
73 has = true
74 }
75 }
76 word()
77 return segs.filter(s => s.length)
78}
79
80/** What a `claude --bg` launch asked for. */
81export type Launch = { model?: string; effort?: string; agent?: string; name?: string }
82
83const VALUE_FLAGS: Record<string, keyof Launch> = {
84 '--model': 'model',
85 '--effort': 'effort',
86 '--agent': 'agent',
87 '--name': 'name',
88 '-n': 'name',
89}
90
91const SHELL = /^(?:(?:ba|z|da|k|c)?sh|pwsh|powershell|cmd)(?:\.exe)?$/i
92
93// Every `claude ... --bg/--background` segment. `claude` must be the segment's command word (after FOO=bar
94// assignments; a path ending in claude or claude.exe is fine); flags are read only from unquoted words, and a
95// quoted word counts only as the value right after a flag that takes one. `sh -c "..."` is read inside.
96export function bgLaunches(cmd: string): Launch[] {
97 const out: Launch[] = []
98 for (const seg of split(cmd)) {
99 let i = 0
100 while (i < seg.length && !seg[i]!.quoted && /^[A-Za-z_]\w*=/.test(seg[i]!.text)) i++
101 const word = seg[i]?.text.split(/[\\/]/).pop() ?? ''
102 if (SHELL.test(word)) {
103 const k = seg.findIndex((t, n) => n > i && !t.quoted && /^(?:-[a-z]*c|-command|\/c)$/i.test(t.text))
104 if (k >= 0) {
105 const rest = seg.slice(k + 1)
106 out.push(...bgLaunches(rest.length === 1 ? rest[0]!.text : rest.map(t => (t.quoted ? JSON.stringify(t.text) : t.text)).join(' ')))
107 }
108 continue
109 }
110 if (!/^claude(?:\.(?:exe|cmd|ps1))?$/i.test(word)) continue
111 const found: Launch = {}
112 let bg = false
113 for (let j = i + 1; j < seg.length; j++) {
114 const t = seg[j]!
115 if (t.quoted) continue
116 if (t.text === '--') break
117 const m = /^(--[a-z-]+|-n)(?:=(.*))?$/i.exec(t.text)
118 if (!m) continue
119 if (m[1] === '--bg' || m[1] === '--background') {
120 bg = true
121 continue
122 }
123 const key = VALUE_FLAGS[m[1]!.toLowerCase()]
124 if (!key) continue
125 let v = m[2]
126 const next = seg[j + 1]
127 if (v === undefined && next && (next.quoted || !next.text.startsWith('-'))) {
128 v = next.text
129 j++
130 }
131 if (v !== undefined) found[key] = v
132 }
133 if (bg) out.push(found)
134 }
135 return out
136}
137
138// ---- which sessions belong to this repository ----
139
140export type Worktree = { path: string; branch: string | null }
141
142/** `git worktree list --porcelain`: blocks of `worktree <path>` / `branch refs/heads/<name>`. */
143export const parseWorktrees = (porcelain: string): Worktree[] =>
144 porcelain
145 .split(/\r?\n\r?\n/)
146 .map(block => ({
147 path: /^worktree (.+)$/m.exec(block)?.[1]?.trim() ?? '',
148 branch: /^branch refs\/heads\/(.+)$/m.exec(block)?.[1]?.trim() ?? null,
149 }))
150 .filter(w => w.path)
151
152// Windows and git disagree on slashes, and on case; compare in one spelling.
153const norm = (p: string): string => p.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
154
155const worktreeOf = (cwd: string, trees: Worktree[]): Worktree | undefined => {
156 const c = norm(cwd)
157 return trees
158 .filter(w => c === norm(w.path) || c.startsWith(norm(w.path) + '/'))
159 .sort((a, b) => b.path.length - a.path.length)[0]
160}
161
162/** Related: launched from this session (by name), or running in a worktree of this repository. */
163export const isRelated = (a: AgentEntry, trees: Worktree[], launched: Record<string, Launch>): boolean =>
164 a.name.toLowerCase() in launched || worktreeOf(a.cwd, trees) !== undefined
165
166/** The branch checked out where the session runs, from the one worktree list per poll. */
167export const branchOf = (a: AgentEntry, trees: Worktree[]): string | undefined => worktreeOf(a.cwd, trees)?.branch ?? undefined
168
169// ---- crab and label ----
170
171const CREW = ['scout', 'builder', 'reviewer']
172
173/** `--agent scout|builder|reviewer` picks that crab; else the model's family: haiku scout, sonnet builder, opus reviewer. */
174export const tierFor = (l?: Launch): string => {
175 const agent = l?.agent?.replace(/^[^:]*:/, '').toLowerCase() ?? ''
176 if (CREW.includes(agent)) return agent
177 const m = l?.model?.toLowerCase() ?? ''
178 return /haiku/.test(m) ? 'scout' : /sonnet/.test(m) ? 'builder' : /opus/.test(m) ? 'reviewer' : 'other'
179}
180
181/** `sonnet` -> `Sonnet`; a full id is left to the caller's modelName. */
182export const aliasLabel = (model: string): string | undefined =>
183 /^[a-z]+$/i.test(model) ? model.charAt(0).toUpperCase() + model.slice(1).toLowerCase() : undefined
184hooks/view.ts 153 lines1// The view pane: what one subagent or background session is doing, as styled lines.
2
3import type { SessionMessage } from 'claude-code'
4
5import type { ViewLine } from '../types'
6
7const MAX_LINES = 2000
8
9// `claude logs` prints a terminal recording: keep the text, drop colors and cursor moves.
10// Only the fallback for a background session whose transcript cannot be found.
11export const logLines = (raw: string): ViewLine[] => {
12 const text = raw
13 .replace(/\x1b\[(\d*)C/g, (_, n: string) => ' '.repeat(Number(n) || 1))
14 .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '')
15 .replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '')
16 .replace(/\x1b[@-_]/g, '')
17 const out: ViewLine[] = []
18 for (const l of text.split('\n')) {
19 // A carriage return mid-line redrew the line: the last write is what showed.
20 const line = (l.replace(/\r+$/, '').split('\r').pop() ?? '')
21 .replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '')
22 .replace(/\s+$/, '')
23 // Right-aligned status and the prompt box's rules are sized to its terminal, not this pane.
24 .replace(/(\S) {3,}/g, '$1 ')
25 .replace(/─{4,}/g, '───')
26 if (/^[─\s]+$/.test(line)) continue
27 if (line === '' && (out.length === 0 || out[out.length - 1]!.kind === 'gap')) continue
28 out.push(line === '' ? { kind: 'gap', text: '' } : { kind: 'log', text: line })
29 }
30 while (out[out.length - 1]?.kind === 'gap') out.pop()
31 return out.slice(-MAX_LINES)
32}
33
34type Use = { tool_use_id: string; tool: string; input: Record<string, unknown>; text?: string; isError?: true }
35type Block = { type?: string; text?: string; id?: string; name?: string; input?: unknown; tool_use_id?: string; is_error?: boolean }
36
37/**
38 * A session transcript file (JSONL, one content block per entry) as `$.session.messages()` rows: replies,
39 * tool calls marked answered or failed by their results, and the person's prompts (not the engine's own
40 * `<tag>` messages, meta rows, compaction summaries or sidechains). A partial first line, from reading only the tail, is skipped.
41 */
42export const transcriptMessages = (jsonl: string): SessionMessage[] => {
43 const msgs: SessionMessage[] = []
44 const uses = new Map<string, Use>()
45 for (const raw of jsonl.split('\n')) {
46 let o: { type?: string; isMeta?: boolean; isSidechain?: boolean; isCompactSummary?: boolean; message?: { content?: unknown } }
47 try {
48 o = JSON.parse(raw)
49 } catch {
50 continue
51 }
52 if (!o || typeof o !== 'object' || o.isMeta || o.isSidechain || o.isCompactSummary) continue
53 const c = o.message?.content
54 const blocks: Block[] = typeof c === 'string' ? [{ type: 'text', text: c }] : Array.isArray(c) ? c : []
55 const text = blocks
56 .filter(b => b.type === 'text' && typeof b.text === 'string')
57 .map(b => b.text)
58 .join('\n')
59 if (o.type === 'assistant') {
60 const toolUses = blocks
61 .filter(b => b.type === 'tool_use' && b.id && b.name)
62 .map(b => {
63 const u: Use = { tool_use_id: b.id!, tool: b.name!, input: (b.input as Record<string, unknown>) ?? {} }
64 uses.set(u.tool_use_id, u)
65 return u
66 })
67 if (text.trim() || toolUses.length) msgs.push({ role: 'assistant', text, toolUses })
68 } else if (o.type === 'user') {
69 for (const b of blocks) {
70 const u = b.type === 'tool_result' && b.tool_use_id ? uses.get(b.tool_use_id) : undefined
71 if (!u) continue
72 u.text = ''
73 if (b.is_error) u.isError = true
74 }
75 if (text.trim() && !text.trimStart().startsWith('<')) msgs.push({ role: 'user', text, toolUses: [] })
76 }
77 }
78 return msgs
79}
80
81// Transcript text is whatever the model, a tool or a file wrote: escape sequences and other control
82// characters are dropped so none reaches the terminal as a command; tabs become spaces.
83export const clean = (s: string): string =>
84 s
85 .replace(/(?:\x1b\[|\x9b)[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?|\x1b.?/g, '')
86 .replace(/\t/g, ' ')
87 .replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g, '')
88
89const KEYS = ['description', 'command', 'file_path', 'path', 'pattern', 'url', 'query', 'skill', 'prompt']
90
91/** A tool call in a few words: its first telling argument. */
92export const brief = (input: Record<string, unknown>): string => {
93 const k = KEYS.find(k => typeof input[k] === 'string' && input[k])
94 const v = k ? String(input[k]) : JSON.stringify(input)
95 return clean(v.replace(/\s+/g, ' ')).trim()
96}
97
98/** `mcp__server__tool` reads as `tool (server)`. */
99const toolName = (t: string): string => {
100 const m = /^mcp__(.+?)__(.+)$/.exec(t)
101 return clean(m ? `${m[2]} (${m[1]!.replace(/^plugin_[^_]+_/, '')})` : t)
102}
103
104/** An agent's transcript as lines: prompts, replies, and one line per tool call, a gap before each block. */
105export const messageLines = (msgs: readonly SessionMessage[]): ViewLine[] => {
106 const out: ViewLine[] = []
107 const block = (kind: 'user' | 'text', text: string, max = Infinity) => {
108 const lines = clean(text.replace(/\r\n?/g, '\n')).trim().split('\n')
109 if (out.length) out.push({ kind: 'gap', text: '' })
110 // Only a block's first line carries the mark.
111 lines.slice(0, max).forEach((l, i) => out.push({ kind, text: l.replace(/\s+$/, ''), ...(i ? { isCont: true } : {}) }))
112 if (lines.length > max) out.push({ kind, text: `… ${lines.length - max} more lines`, isCont: true })
113 }
114 for (const m of msgs) {
115 if (m.role === 'user') {
116 if (m.text.trim() && !m.toolResults?.length) block('user', m.text, 6)
117 continue
118 }
119 if (m.text.trim()) block('text', m.text)
120 // Tool calls run on under the reply that led to them; after a prompt they start a block of their own.
121 else if (m.toolUses.length && out[out.length - 1]?.kind === 'user') out.push({ kind: 'gap', text: '' })
122 for (const u of m.toolUses)
123 out.push({ kind: u.isError ? 'error' : u.text === undefined ? 'pending' : 'tool', tool: toolName(u.tool), text: brief(u.input) })
124 }
125 return out.slice(-MAX_LINES)
126}
127
128/**
129 * Wraps prose, prompt and log lines to `width`, at a space when one is near, marking the continuations; a
130 * tool line stays one row (the pane truncates it). The pane then shows the tail that fits.
131 */
132export const wrapLines = (lines: readonly ViewLine[], width: number): ViewLine[] => {
133 const w = Math.max(10, width)
134 const out: ViewLine[] = []
135 for (const line of lines) {
136 if (line.kind !== 'text' && line.kind !== 'user' && line.kind !== 'log') {
137 out.push(line)
138 continue
139 }
140 let s = line.text
141 let isCont = false
142 while (s.length > w) {
143 let k = s.lastIndexOf(' ', w)
144 if (k < w / 2) k = w
145 out.push({ ...line, text: s.slice(0, k), ...(isCont ? { isCont } : {}) })
146 s = s.slice(k).replace(/^ /, '')
147 isCont = true
148 }
149 out.push({ ...line, text: s, ...(isCont ? { isCont } : {}) })
150 }
151 return out
152}
153hooks/sprite.ts 42 lines1// Terminal crabs: Claude Code's own mascot, Clawd, in quadrant blocks as the CLI draws it (2.1.295),
2// with the tier's prop in the tier's color just right of it. The desktop SVG crabs (COSTUMES in register.tsx) are separate.
3
4export type Fill = (x: number, y: number, w: number, h: number, c: string, cls?: string) => void
5
6/** One run of cells in one color: what a `<Text color>` draws. */
7export type Run = { text: string; fg: string }
8
9/** Clawd's 9 columns and the prop's 2, by 3 lines: as tall as a row's three lines of text. */
10export const SPRITE_W = 11
11export const SPRITE_H = 3
12
13const BODY = '#D97757'
14// Clawd's default pose (eyes open, arms down); frame 1 swings the feet half a cell, so it walks.
15const CLAWD = [' ▐▛███▛█ ', '▝▜██████▀']
16const FEET = [' ▝▝ ▝▝ ', ' ▘▘ ▘▘ ']
17
18// What each tier holds, per frame: three lines of two columns. Line 1 is the arm's, so a prop there sits in Clawd's hand.
19const PROPS: Record<string, [string[], string[]]> = {
20 // Binoculars up to the eyes, then down.
21 scout: [['◉◉', ' ', ' '], [' ', '◉◉', ' ']],
22 // A hammer raised, then struck.
23 builder: [['▜▀', '▝ ', ' '], [' ▄', '▀█', ' ']],
24 // A check mark that blinks.
25 reviewer: [['✓ ', ' ', ' '], [' ', ' ', ' ']],
26 // A baton up, then down.
27 orchestrator: [['╱ ', ' ', ' '], [' ', '╲ ', ' ']],
28}
29const EMPTY = [' ', ' ', ' ']
30
31/** Clawd holding `tier`'s prop, in `color`; frame 1 is the second pose of a running crab. */
32export const clawd = (tier: string, color: string, frame = 0): Run[][] => {
33 const prop = PROPS[tier]?.[frame ? 1 : 0] ?? EMPTY
34 return [...CLAWD, FEET[frame ? 1 : 0]!].map((body, y) => [
35 { text: body, fg: BODY },
36 { text: prop[y]!, fg: color },
37 ])
38}
39
40/** The sprite as plain text, for tests and a quick look. */
41export const toText = (lines: Run[][]): string => lines.map(l => l.map(r => r.text).join('')).join('\n')
42types/index.d.ts 98 lines1export type Phase = 'plan' | 'design' | 'delegate' | 'review' | 'close'
2
3export type PlannedTask = {
4 title: string
5 tier: string
6 after: number[]
7}
8
9export type Flow = {
10 title: string
11 total: number
12 done: number
13 running: number
14 phase: Phase
15 isFinished: boolean
16 tasks: PlannedTask[]
17}
18
19export type AgentStatus = 'running' | 'done' | 'failed'
20
21export type AgentRun = {
22 id: string
23 agentId?: string
24 type: string
25 description: string
26 model: string
27 effort?: string
28 status: AgentStatus
29 startedAt: number
30 endedAt?: number
31 contextTokens: number
32 contextMax: number
33 tokens: number
34 costUsd: number
35 steps: number
36 round: number
37 /** Self-reported by the worker through the `step` tool. */
38 stepDone?: number
39 stepTotal?: number
40 stepNote?: string
41}
42
43export type BgState = 'busy' | 'idle' | 'waiting'
44
45/** A background session related to this one, as the last poll of the agents list saw it. */
46export type BgSession = {
47 id: string
48 name: string
49 state: BgState
50 /** The crab: scout, builder, reviewer or other. */
51 tier: string
52 /** Known only for sessions this one launched. */
53 model?: string
54 effort?: string
55 branch?: string
56 /** Where it runs: its transcript lives under the projects folder named after it. */
57 cwd?: string
58}
59
60/** What the view pane shows: a subagent of this session (by agentId) or a background session (by session id). */
61export type ViewTarget = { kind: 'agent' | 'bg'; id: string; name: string; cwd?: string }
62
63/** One row of the view pane: a prompt, reply prose, a tool call (done, in flight, failed), raw log text, or a gap. */
64export type ViewLine = {
65 kind: 'user' | 'text' | 'tool' | 'pending' | 'error' | 'log' | 'gap'
66 text: string
67 /** A tool line's tool. */
68 tool?: string
69 /** A wrapped line's later rows: drawn without the mark. */
70 isCont?: boolean
71}
72
73export type Panel = {
74 isCompact: boolean
75 isDoneCollapsed: boolean
76 autoOpenedFor: string
77}
78
79declare module 'claude-code' {
80 interface PluginState {
81 'savvy-progress': {
82 flow: Flow | null
83 agents: AgentRun[]
84 panel: Panel
85 now: number
86 /** Which of the two crab frames the running rows show; flips while something runs. */
87 frame: number
88 bg: BgSession[]
89 /** What this session's own background launches asked for, by lowercase `--name`. */
90 launches: Record<string, { model?: string; effort?: string; agent?: string }>
91 /** The view pane's target and its last read, as lines. */
92 view: (ViewTarget & { lines: ViewLine[]; source?: 'transcript' | 'logs' }) | null
93 /** The view pane's window sits at the end: new lines scroll it down. Off once the person scrolls up. */
94 viewFollow: boolean
95 }
96 }
97}
98