Progress bar above the prompt and a live agents panel, drawn in colour with pixel crabs on the desktop and in any truecolor terminal. Fork of…

Our fork of johnnyvizz/claude-kit savvy-progress (MIT, see LICENSE). It adds a terminal drawing (hooks/terminal.tsx): the bar, the pill and small crabs in each tier's hat colour, painted in 24-bit coloured cells, so any truecolor terminal shows the desktop's look.
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.hooks/motion.ts) that runs only while something moves, so an idle session keeps no timer.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. With its last step it can send summary and followUp; without them the open card is cut from its final report.The header shows Active, what the running agents have cost so far, and Session, the whole session as /cost totals it (main thread included, from $.session.usage()). Each agent's own cost is an estimate from its token counts and the per-model list prices in hooks/pricing.ts, at the 5-minute cache-write rate.
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 repository README.
hooks/register.tsx 858 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AgentRun, Flow, Panel, Phase, PlannedTask } from '../types'
5
6import { cardTitle, digestBlock, isFinished } from './digest'
7import { frameOf, partyFrame, startMotion } from './motion'
8import type { Motion } from './motion'
9import { digestRows } from './summary'
10import { H, agentSvg, compactSvg, headerHeight, headerSvg, plannedSvg, rowSvg } from './svg'
11import { costOf, windowOf } from './pricing'
12import { paneRows, terminalBand, terminalPane } from './terminal'
13import type { Look } from './terminal'
14
15const flow = atom({ plugin: 'savvy-progress', key: 'flow' } as const, null)
16const agents = atom({ plugin: 'savvy-progress', key: 'agents' } as const, [])
17const panel = atom({ plugin: 'savvy-progress', key: 'panel' } as const, {
18 isCompact: false,
19 isDoneCollapsed: false,
20 autoOpenedFor: '',
21 expanded: [] as string[],
22})
23const now = atom({ plugin: 'savvy-progress', key: 'now' } as const, 0)
24
25const TOOL = 'mcp__savvy-progress__progress'
26const STEP_TOOL = 'mcp__savvy-progress__step'
27const PANE = 'savvy-agents'
28const PHASES: readonly Phase[] = ['plan', 'design', 'delegate', 'review', 'close']
29const ACCENT = '#8f8cf4'
30const DONE = '#5fbf8f'
31
32type ProgressInput = {
33 title?: string
34 total?: number
35 done?: number
36 phase?: Phase
37 finished?: boolean
38 tasks?: { title?: string; tier?: string; after?: number[] }[]
39}
40
41// ---------------------------------------------------------------------------
42// Language: the `language` option, else Claude Code's `language` setting, else the
43// process locale; English when nothing says Russian.
44
45type Lang = 'en' | 'ru'
46
47const STRINGS = {
48 en: {
49 pane: 'Agents',
50 active: 'Active',
51 session: 'Session',
52 tokens: 'Tokens',
53 time: 'Time',
54 collapse: 'Collapse',
55 expand: 'Expand',
56 running: 'Running',
57 finished: 'Finished',
58 planned: 'Planned',
59 empty: 'No subagents yet.',
60 round: 'round',
61 failed: 'error',
62 after: 'after',
63 tokensWord: 'tokens',
64 agentsCount: 'agents',
65 isRunning: 'running',
66 isFinished: 'finished',
67 isPlanned: 'planned',
68 opened: 'Agents panel opened.',
69 closed: 'Agents panel closed.',
70 done: 'Done',
71 plan: 'Plan',
72 design: 'Design',
73 tasks: 'Tasks',
74 review: 'Review',
75 busy: 'running',
76 noReport: 'No report yet',
77 },
78 ru: {
79 pane: 'Агенты',
80 active: 'Активные',
81 session: 'Сессия',
82 tokens: 'Токены',
83 time: 'Время',
84 collapse: 'Свернуть',
85 expand: 'Развернуть',
86 running: 'Работают',
87 finished: 'Завершены',
88 planned: 'Запланированы',
89 empty: 'Субагентов пока нет.',
90 round: 'раунд',
91 failed: 'ошибка',
92 after: 'после',
93 tokensWord: 'токенов',
94 agentsCount: 'агентов',
95 isRunning: 'работает',
96 isFinished: 'завершён',
97 isPlanned: 'запланирована',
98 opened: 'Панель агентов открыта.',
99 closed: 'Панель агентов закрыта.',
100 done: 'Готово',
101 plan: 'План',
102 design: 'Дизайн',
103 tasks: 'Задачи',
104 review: 'Ревью',
105 busy: 'в работе',
106 noReport: 'Отчёта пока нет',
107 },
108} as const
109
110// Module scope is fine here: session.start sets it again on every (re)load.
111let lang: Lang = 'en'
112const tr = () => STRINGS[lang]
113
114const isRussian = (v: unknown): boolean => typeof v === 'string' && /^(ru|russian|рус)/i.test(v.trim())
115
116async function detectLang($: EngineInterface, option: unknown): Promise<Lang> {
117 if (option === 'en' || option === 'ru') return option
118 try {
119 const settings = (await $.settings.read()) as Record<string, unknown>
120 if (typeof settings.language === 'string' && settings.language.trim()) return isRussian(settings.language) ? 'ru' : 'en'
121 } catch {
122 // No settings: fall through to the locale.
123 }
124 const locale = (await $.env.get('LC_ALL')) || (await $.env.get('LC_MESSAGES')) || (await $.env.get('LANG'))
125 return isRussian(locale) ? 'ru' : 'en'
126}
127
128const blank = (): Flow => ({
129 title: 'savvy-flow',
130 total: 0,
131 done: 0,
132 running: 0,
133 phase: 'plan',
134 isFinished: false,
135 tasks: [],
136})
137
138const isNewFlow = (prev: Flow | null, input: ProgressInput): boolean =>
139 !prev || prev.isFinished || (input.title !== undefined && input.title.trim() !== prev.title)
140
141const cleanTasks = (tasks: ProgressInput['tasks']): PlannedTask[] | undefined =>
142 tasks
143 ?.filter(t => t.title?.trim())
144 .map(t => ({
145 title: (t.title ?? '').trim(),
146 tier: (t.tier ?? '').replace(/^savvy-/, '').trim().toLowerCase(),
147 after: (t.after ?? []).filter(n => Number.isInteger(n) && n > 0),
148 }))
149
150const merge = (prev: Flow | null, input: ProgressInput): Flow => {
151 // A new title means a new flow: never carry counters over from an earlier one.
152 const base = isNewFlow(prev, input) || !prev ? blank() : { ...blank(), ...prev }
153 const tasks = cleanTasks(input.tasks) ?? base.tasks
154 const total = Math.max(0, Math.round(input.total ?? (input.tasks ? tasks.length : base.total)))
155 const done = Math.min(total || Infinity, Math.max(0, Math.round(input.done ?? base.done)))
156 const phase = input.phase && PHASES.includes(input.phase) ? input.phase : base.phase
157 return {
158 ...base,
159 title: input.title?.trim() || base.title,
160 total,
161 done,
162 phase: input.finished ? 'close' : phase,
163 isFinished: input.finished === true,
164 tasks,
165 }
166}
167
168const label = (f: Flow): string => {
169 const s = tr()
170 if (f.isFinished) return s.done
171 if (f.phase === 'plan') return s.plan
172 if (f.phase === 'design') return s.design
173 const count = f.total ? `${f.done}/${f.total}` : `${f.running} ${s.busy}`
174 return `${f.phase === 'review' ? s.review : s.tasks} ${count}`
175}
176
177const ratio = (f: Flow): number => (f.isFinished ? 1 : f.total ? f.done / f.total : 0)
178
179// ---------------------------------------------------------------------------
180// Agents panel: every subagent of the session, plus the tasks the flow planned.
181
182const TIER_COLOR: Record<string, string> = {
183 fable: '#7F77DD',
184 heavy: '#D85A30',
185 careful: '#BA7517',
186 medium: '#378ADD',
187 light: '#1D9E75',
188 other: '#888780',
189}
190
191// What each savvy tier runs on, for planned tasks that have no run yet.
192const colorOf = (tier: string): string => TIER_COLOR[tier] ?? '#888780'
193
194const TIER_MODEL: Record<string, string> = {
195 fable: 'Fable · high',
196 heavy: 'Opus · xhigh',
197 careful: 'Opus · high',
198 medium: 'Opus · medium',
199 light: 'Opus · low',
200}
201
202// `savvy-careful`, or `savvy-flow:savvy-careful` when the agents ship in a plugin.
203const tierOf = (type: string): string => {
204 const bare = type.replace(/^[^:]*:/, '')
205 const t = bare.replace(/^savvy-/, '').toLowerCase()
206 return t in TIER_COLOR && bare.startsWith('savvy-') ? t : 'other'
207}
208
209const modelName = (id: string): string => {
210 const m = /(fable|mythos|opus|sonnet|haiku)-(\d+)(?:-(\d{1,2})(?!\d))?/i.exec(id)
211 const [, family = '', major = '', minor] = m ?? []
212 if (!family) return id.replace(/^claude-/, '').replace(/\[.*\]$/, '') || '—'
213 return `${family.charAt(0).toUpperCase()}${family.slice(1).toLowerCase()} ${major}${minor ? '.' + minor : ''}`
214}
215
216const norm = (s: string): string => s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim()
217
218const fmtTokens = (n: number): string =>
219 n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : `${Math.round(n)}`
220
221const fmtCost = (usd: number): string => `$${usd < 10 ? usd.toFixed(2) : usd.toFixed(1)}`
222
223const fmtTime = (ms: number): string => {
224 const s = Math.max(0, Math.round(ms / 1000))
225 const h = Math.floor(s / 3600)
226 const m = Math.floor((s % 3600) / 60)
227 const ss = String(s % 60).padStart(2, '0')
228 return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`
229}
230
231const elapsed = (a: AgentRun, at: number): number => (a.endedAt ?? Math.max(at, a.startedAt)) - a.startedAt
232
233type Planned = PlannedTask & { n: number }
234
235const plannedOf = (f: Flow | null, list: AgentRun[]): Planned[] => {
236 if (!f || f.isFinished) return []
237 const started = new Set(list.map(a => norm(a.description)))
238 return (f.tasks ?? []).map((t, i) => ({ ...t, n: i + 1 })).filter(t => !started.has(norm(t.title)))
239}
240
241// `active` is what the running agents have cost so far; `session` is the whole
242// session as /cost totals it, main thread included, or the agents' sum when the
243// host keeps no ledger.
244const totals = (list: AgentRun[], at: number, sessionUsd: number | undefined) => {
245 const active = list.filter(a => a.status === 'running').reduce((s, a) => s + a.costUsd, 0)
246 const session = sessionUsd ?? list.reduce((s, a) => s + a.costUsd, 0)
247 const tokens = list.reduce((s, a) => s + a.tokens, 0)
248 const start = Math.min(...list.map(a => a.startedAt))
249 const end = Math.max(...list.map(a => a.endedAt ?? Math.max(at, a.startedAt)))
250 return { active, session, tokens, time: list.length ? end - start : 0 }
251}
252
253async function sessionCost($: EngineInterface): Promise<number | undefined> {
254 try {
255 return (await $.session.usage()).cost?.usd
256 } catch {
257 return undefined
258 }
259}
260
261const costumeOf = (type: string): string => (type === 'Explore' ? 'explore' : tierOf(type))
262// The task's own progress when the worker reports steps; a finished run is full.
263const progressOf = (a: AgentRun): number | null => {
264 if (a.status === 'done') return 1
265 if (a.stepTotal) return Math.min(1, (a.stepDone ?? 0) / a.stepTotal)
266 return null
267}
268
269const ctxOf = (a: AgentRun): number => (a.contextMax ? Math.min(100, Math.round((a.contextTokens / a.contextMax) * 100)) : 0)
270
271// --- terminal drawing: the same rows in text.
272
273const ctxBar = (pct: number, width: number): string => {
274 const filled = Math.round((width * pct) / 100)
275 return '█'.repeat(filled) + '░'.repeat(Math.max(0, width - filled))
276}
277
278const STATUS_GLYPH: Record<string, string> = { running: '●', done: '✓', failed: '✗', planned: '◷' }
279
280// What the terminal drawing borrows from here: strings, palette and formatters.
281const look = (): Look => ({
282 s: tr(),
283 accent: ACCENT,
284 done: DONE,
285 tierColor: TIER_COLOR,
286 tierModel: TIER_MODEL,
287 colorOf,
288 tierOf,
289 costumeOf,
290 modelName,
291 fmtTokens,
292 fmtCost,
293 fmtTime,
294 elapsed,
295 ctxOf,
296 progressOf,
297})
298
299// The agents pane as the surface holds it; undefined when it is closed or the
300// host cannot say, so a failed lookup never costs the bar or the spawn.
301async function paneOf($: EngineInterface): Promise<{ isPlaced: boolean } | undefined> {
302 try {
303 return (await $.ui.panes()).find(p => p.id === PANE)
304 } catch {
305 return undefined
306 }
307}
308
309// Opens the pane, or resizes an open one, tall enough for every card.
310async function openPane($: EngineInterface): Promise<void> {
311 const list = await read($, agents)
312 const f = await read($, flow)
313 const p = await read($, panel)
314 const running = list.filter(a => a.status === 'running').length
315 const rows = paneRows({
316 title: f && !f.isFinished ? f.title : '',
317 running,
318 finished: list.length - running,
319 planned: plannedOf(f, list).length,
320 isCompact: p.isCompact,
321 isDoneCollapsed: p.isDoneCollapsed,
322 open: list.filter(a => isFinished(a) && (p.expanded ?? []).includes(a.id)).reduce((n, a) => n + digestRows(a), 0),
323 })
324 await $.ui.open({ id: PANE, title: tr().pane, rows })
325}
326
327// Opens the agents pane, or closes it when it is up; true when it ends up open.
328async function togglePane($: EngineInterface): Promise<boolean> {
329 const isOpen = (await $.ui.panes()).some(p => p.id === PANE)
330 if (isOpen) {
331 await $.ui.close({ id: PANE })
332 return false
333 }
334 const at = await $.clock.now()
335 await update($, now, () => at)
336 await openPane($)
337 return true
338}
339
340// Opens or closes a finished card's digest, then fits the pane to it.
341async function toggleOpen($: EngineInterface, id: string): Promise<void> {
342 await update($, panel, prev => {
343 const ids = prev.expanded ?? []
344 return { ...prev, expanded: ids.includes(id) ? ids.filter(x => x !== id) : [...ids, id].slice(-50) }
345 })
346 if ((await paneOf($))?.isPlaced) await openPane($)
347}
348
349async function autoOpen($: EngineInterface, key: string): Promise<void> {
350 const p = await read($, panel)
351 if (p.autoOpenedFor === key) return
352 await update($, panel, prev => ({ ...prev, autoOpenedFor: key }))
353 void openPane($)
354}
355
356export const register: Register = (on, options) => {
357 // Module scope is fine: session.start runs again on every (re)load, and a hot
358 // reload cancels the old module's timers with its environment; `stop` covers a
359 // second session.start within one load.
360 let motion: Motion | null = null
361 // When the flow last closed, so the band celebrates it for a moment.
362 let finishedAt = 0
363 const kick = (): void => motion?.kick()
364
365 on('session.start', async ($, e, next) => {
366 const started = await next(e)
367 lang = await detectLang($, options.language)
368 await $.tool.register({
369 name: 'progress',
370 description:
371 'Report /savvy-flow progress to the progress bar above the prompt and the agents panel. ' +
372 'Call it after presenting the plan (title, total, tasks, phase "delegate"), each time a task is accepted (done), ' +
373 'when switching phase or re-planning (tasks), and once at the end with finished: true. Fields left out keep their previous value.',
374 inputSchema: {
375 type: 'object',
376 properties: {
377 title: { type: 'string', description: 'Short name of the overall task, a few words.' },
378 total: { type: 'integer', minimum: 0, description: 'Number of planned worker tasks.' },
379 done: { type: 'integer', minimum: 0, description: 'Number of tasks accepted after review.' },
380 phase: { type: 'string', enum: [...PHASES] },
381 finished: { type: 'boolean', description: 'True once the flow is closed.' },
382 tasks: {
383 type: 'array',
384 description:
385 '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.',
386 items: {
387 type: 'object',
388 properties: {
389 title: { type: 'string', description: 'A few words; reused verbatim as the Agent description.' },
390 tier: { type: 'string', enum: ['fable', 'heavy', 'careful', 'medium', 'light'] },
391 after: { type: 'array', items: { type: 'integer' }, description: 'Numbers of the tasks this one waits for.' },
392 },
393 required: ['title', 'tier'],
394 },
395 },
396 },
397 },
398 })
399 await $.tool.register({
400 name: 'step',
401 description:
402 'For savvy-flow workers: report progress on your own task to the agents panel. ' +
403 'Right after reading the brief, call it with `total` (your plan in 3-8 steps) and `done: 0`; ' +
404 'call it again as each step finishes. Cheap and silent: it only draws a bar. ' +
405 'With your last step, send `summary` and, when you need the person, `followUp`.',
406 inputSchema: {
407 type: 'object',
408 properties: {
409 done: { type: 'integer', minimum: 0, description: 'Steps finished so far.' },
410 total: { type: 'integer', minimum: 1, description: 'Steps planned; may change if the plan changes.' },
411 note: { type: 'string', description: 'The step in progress, a few words.' },
412 summary: { type: 'string', description: 'What you did, one or two plain sentences, sent with your last step.' },
413 followUp: { type: 'string', description: 'What the person must do or decide, one sentence; leave out when nothing.' },
414 },
415 required: ['done'],
416 },
417 })
418 await $.command.register({
419 name: 'agents-info',
420 description: 'Show or hide the panel of subagents: running, finished and planned, with model, context, cost and time',
421 })
422
423 // Ticks the running agents' clocks and every animation; no timer when nothing moves.
424 motion?.stop()
425 motion = startMotion($, {
426 state: async () => ({ f: await read($, flow), list: await read($, agents), finishedAt }),
427 draw: async at => void (await update($, now, () => at)),
428 })
429 kick()
430 return started
431 })
432
433 on('command.run', { command: 'agents-info' }, async $ => {
434 const isOpen = await togglePane($)
435 return { text: isOpen ? tr().opened : tr().closed }
436 })
437
438 on('tool.call', { tool: TOOL }, async ($, e) => {
439 const input = e as unknown as ProgressInput
440 const prev = await read($, flow)
441 if (isNewFlow(prev, input) && input.title !== undefined) {
442 // A new flow starts with a clean list; agents still running stay.
443 await update($, agents, list => list.filter(a => a.status === 'running'))
444 }
445 const next = await update($, flow, p => merge(p, input))
446 if (next?.isFinished && !prev?.isFinished) {
447 finishedAt = await $.clock.now()
448 await update($, now, () => finishedAt)
449 }
450 kick()
451 if (next && input.tasks?.length) await autoOpen($, next.title)
452 return { result: `ok: ${label(next ?? blank())}` }
453 })
454
455 // A worker's own progress: the call runs in the worker's loop, so agentId names it.
456 on('tool.call', { tool: STEP_TOOL }, async ($, e) => {
457 const input = e as unknown as { done?: number; total?: number; note?: string; summary?: string; followUp?: string }
458 const agentId = e.agentId
459 if (!agentId) return { result: 'ignored: only subagents report steps' }
460 await update($, agents, list =>
461 list.map(a => {
462 if (a.agentId !== agentId) return a
463 const total = Math.max(0, Math.round(input.total ?? a.stepTotal ?? 0))
464 const done = Math.max(0, Math.round(input.done ?? a.stepDone ?? 0))
465 const told = { summary: input.summary?.trim() || a.summary, followUp: input.followUp?.trim() || a.followUp }
466 return { ...a, ...told, stepTotal: total, stepDone: total ? Math.min(total, done) : done, stepNote: input.note?.trim() || undefined }
467 }),
468 )
469 return { result: 'ok' }
470 })
471
472 // Safety net: worker launches move the faint layer even if the orchestrator forgets to report.
473 on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
474 const type = String(e.subagent_type ?? '')
475 if (!type.startsWith('savvy-')) return next(e)
476
477 await update($, flow, prev => {
478 const base = prev && !prev.isFinished ? { ...blank(), ...prev } : blank()
479 return { ...base, running: base.running + 1, phase: base.phase === 'plan' ? 'delegate' : base.phase }
480 })
481 kick()
482 try {
483 return await next(e)
484 } finally {
485 await update($, flow, prev => (prev ? { ...prev, running: Math.max(0, prev.running - 1) } : prev))
486 }
487 })
488
489 on('agent.spawn', async ($, e, next) => {
490 const started = await next(e)
491 if (started.deny !== undefined) return started
492
493 const at = await $.clock.now()
494 await update($, agents, list => {
495 const round = 1 + list.filter(a => norm(a.description) === norm(e.description) && e.description).length
496 const run: AgentRun = {
497 id: started.agentId ?? e.tool_use_id,
498 agentId: started.agentId,
499 type: e.subagentType,
500 description: e.description,
501 model: started.model,
502 status: 'running',
503 startedAt: at,
504 contextTokens: 0,
505 contextMax: windowOf(started.model),
506 tokens: 0,
507 costUsd: 0,
508 steps: 0,
509 round,
510 }
511 return [...list.filter(a => a.id !== run.id), run].slice(-200)
512 })
513 await update($, now, () => at)
514 kick()
515 if (e.subagentType.startsWith('savvy-')) {
516 const f = await read($, flow)
517 await autoOpen($, f && !f.isFinished ? f.title : 'savvy-flow')
518 }
519 if ((await paneOf($))?.isPlaced) await openPane($)
520 return started
521 })
522
523 // Each model request of a subagent: live context, tokens and cost.
524 on('turn.step', async function* ($, e, next) {
525 const result = yield* next(e)
526 const agentId = e.agentId
527 const usage = result.usage
528 if (!usage) return result
529 if (!agentId) {
530 // A main-thread request moves only the session total: redraw for it.
531 const at = await $.clock.now()
532 await update($, now, () => at)
533 return result
534 }
535
536 const model = usage.model || e.model
537 await update($, agents, list =>
538 list.map(a =>
539 a.agentId !== agentId
540 ? a
541 : {
542 ...a,
543 model,
544 effort: typeof e.effort === 'string' ? e.effort : a.effort,
545 status: 'running',
546 endedAt: undefined,
547 contextTokens:
548 (usage.input_tokens || 0) +
549 (usage.cache_read_input_tokens || 0) +
550 (usage.cache_creation_input_tokens || 0) +
551 (usage.output_tokens || 0),
552 contextMax: windowOf(model),
553 tokens:
554 a.tokens +
555 (usage.input_tokens || 0) +
556 (usage.output_tokens || 0) +
557 (usage.cache_read_input_tokens || 0) +
558 (usage.cache_creation_input_tokens || 0),
559 costUsd: a.costUsd + costOf(model, usage),
560 steps: a.steps + 1,
561 },
562 ),
563 )
564 return result
565 })
566
567 // A subagent's last turn: its final answer is kept, capped, for the digest.
568 on('turn.complete', async ($, e, next) => {
569 const result = await next(e)
570 const agentId = e.agentId
571 const text = typeof result?.text === 'string' && result.text.trim() ? result.text : e.answer
572 const report = text?.trim() ? text.slice(0, 6000) : undefined
573 if (agentId) {
574 const at = await $.clock.now()
575 await update($, agents, list =>
576 list.map(a => {
577 if (a.agentId !== agentId) return a
578 // A run whose steps went unseen still gets the turn's own sum.
579 const fallback = a.steps === 0 && e.usage
580 return {
581 ...a,
582 status: e.reason === 'answer' ? 'done' : 'failed',
583 endedAt: at,
584 report: report ?? a.report,
585 ...(fallback && e.usage
586 ? {
587 model: e.usage.model || a.model,
588 tokens:
589 e.usage.input_tokens +
590 e.usage.output_tokens +
591 e.usage.cache_read_input_tokens +
592 e.usage.cache_creation_input_tokens,
593 costUsd: costOf(e.usage.model || a.model, e.usage),
594 }
595 : {}),
596 }
597 }),
598 )
599 await update($, now, () => at)
600 kick()
601 }
602 return result
603 })
604
605 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
606 const s = tr()
607 const ui = $.ui.resolve(e)
608 const { Box, Text, Button } = ui
609 const list = await read($, agents)
610 const f = await read($, flow)
611 const p: Panel = await read($, panel)
612 const expanded = p.expanded ?? []
613 const at = Math.max(await read($, now), ...list.map(a => a.startedAt), 0)
614
615 const running = list.filter(a => a.status === 'running').reverse()
616 const finished = list.filter(a => a.status !== 'running').reverse()
617 const planned = plannedOf(f, list)
618 const t = totals(list, at, await sessionCost($))
619 // The pane's title says "Agents"; inside, only the flow's own name.
620 const title = f && !f.isFinished ? f.title : ''
621
622 const toggleCompact = (
623 <Button
624 key="compact"
625 label={p.isCompact ? s.expand : s.collapse}
626 plain
627 onPress={() => update($, panel, prev => ({ ...prev, isCompact: !prev.isCompact }))}
628 />
629 )
630 const toggleDone = (
631 <Button
632 key="done"
633 label={`${p.isDoneCollapsed ? '▸' : '▾'} ${s.finished} · ${finished.length}`}
634 plain
635 onPress={() => update($, panel, prev => ({ ...prev, isDoneCollapsed: !prev.isDoneCollapsed }))}
636 />
637 )
638 const isEmpty = list.length === 0 && planned.length === 0
639 const summary = `${s.active} ≈${fmtCost(t.active)}, ${s.session} ${fmtCost(t.session)}, ${fmtTokens(t.tokens)} ${s.tokensWord}, ${fmtTime(t.time)}`
640
641 if (e.surface === 'desktop' && 'Svg' in ui) {
642 const { Svg } = ui
643 const W = Math.max(240, Math.min(900, (e.props.bodyColumns || 40) * 8 - 8))
644 const section = (key: string, text: string) => (
645 <Text key={key} dimColor>
646 {text}
647 </Text>
648 )
649
650 if (p.isCompact) {
651 return (
652 <Box flexDirection="column" gap={1}>
653 <Svg source={compactSvg(W, list, planned, t, at, look())} alt={`${list.length} ${s.agentsCount}, ${summary}`} width={W} height={32} />
654 {toggleCompact}
655 </Box>
656 )
657 }
658 return (
659 <Box flexDirection="column">
660 <Svg source={headerSvg(W, title, t, look())} alt={title ? `${title}: ${summary}` : summary} width={W} height={headerHeight(title)} />
661 {toggleCompact}
662 {isEmpty && <Text dimColor>{s.empty}</Text>}
663 {running.length > 0 && section('h-run', `${s.running} · ${running.length}`)}
664 {running.map(a => (
665 <Svg key={a.id} source={agentSvg(W, a, at, look())} alt={`${a.description}: ${modelName(a.model)}, ${s.isRunning}`} width={W} height={66} />
666 ))}
667 {finished.length > 0 && toggleDone}
668 {!p.isDoneCollapsed &&
669 finished.map(a => (
670 <Box key={`card-${a.id}`} flexDirection="column">
671 <Svg key={a.id} source={agentSvg(W, a, at, look())} alt={`${a.description}: ${modelName(a.model)}, ${s.isFinished}`} width={W} height={66} />
672 {cardTitle(ui, a, expanded.includes(a.id), Math.floor(W / 8), () => void toggleOpen($, a.id))}
673 {expanded.includes(a.id) && digestBlock(ui, a, Math.floor(W / 8), s.noReport)}
674 </Box>
675 ))}
676 {planned.length > 0 && section('h-plan', `${s.planned} · ${planned.length}`)}
677 {planned.map(pl => (
678 <Svg key={`plan-${pl.n}`} source={plannedSvg(W, pl, look())} alt={`${pl.n}. ${pl.title}: ${s.isPlanned}`} width={W} height={46} />
679 ))}
680 </Box>
681 )
682 }
683
684 if (e.surface === 'terminal') {
685 return terminalPane($.ui.resolve(e), {
686 title,
687 running,
688 finished,
689 planned,
690 totals: t,
691 at,
692 frame: frameOf(at),
693 columns: Math.max(24, e.props.bodyColumns || 40),
694 isCompact: p.isCompact,
695 isDoneCollapsed: p.isDoneCollapsed,
696 toggleCompact,
697 toggleDone,
698 look: look(),
699 expanded,
700 toggleOpen: id => void toggleOpen($, id),
701 })
702 }
703
704 // Other surfaces without the desktop's SVG rows: the same content in text rows.
705 const cols = Math.max(24, e.props.bodyColumns || 40)
706 const barW = Math.max(6, Math.min(20, cols - 34))
707 const row = (a: AgentRun) => {
708 const tier = tierOf(a.type)
709 const color = colorOf(tier)
710 const ctx = ctxOf(a)
711 const progress = progressOf(a)
712 const model = a.effort ? `${modelName(a.model)} · ${a.effort}` : modelName(a.model)
713 const steps = a.stepTotal ? `${a.stepDone ?? 0}/${a.stepTotal}${a.stepNote ? ' ' + a.stepNote : ''} · ` : ''
714 return (
715 <Box key={a.id} flexDirection="column" marginBottom={1}>
716 <Box flexDirection="row" gap={1}>
717 <Text color={color}>▣</Text>
718 {cardTitle(ui, a, expanded.includes(a.id), cols - 4, () => void toggleOpen($, a.id))}
719 <Text color={a.status === 'failed' ? 'red' : a.status === 'done' ? 'green' : color}>{STATUS_GLYPH[a.status]}</Text>
720 </Box>
721 <Text dimColor wrap="truncate-end">
722 {' '}
723 {tier === 'other' ? a.type : tier} · {model}
724 {a.round > 1 ? ` · ${s.round} ${a.round}` : ''}
725 </Text>
726 <Text wrap="truncate-end">
727 {' '}
728 {progress === null ? <Text dimColor>{ctxBar(ctx, barW)}</Text> : <Text color={color}>{ctxBar(progress * 100, barW)}</Text>}
729 <Text dimColor>
730 {' '}
731 {steps}ctx {ctx}% · {fmtTokens(a.contextTokens)} ≈{fmtCost(a.costUsd)} {fmtTime(elapsed(a, at))}
732 </Text>
733 </Text>
734 {isFinished(a) && expanded.includes(a.id) && digestBlock(ui, a, cols - 2, s.noReport)}
735 </Box>
736 )
737 }
738
739 return (
740 <Box flexDirection="column">
741 <Box flexDirection="row" justifyContent="space-between">
742 <Text bold wrap="truncate-end">
743 {title}
744 </Text>
745 {toggleCompact}
746 </Box>
747 <Text dimColor>
748 {s.active} ≈{fmtCost(t.active)} · {s.session} {fmtCost(t.session)} · {fmtTokens(t.tokens)} {s.tokensWord} · {fmtTime(t.time)}
749 </Text>
750 {p.isCompact ? (
751 <Text wrap="truncate-end">
752 {[...running, ...finished].map(a => (
753 <Text key={a.id} color={colorOf(tierOf(a.type))}>
754 {STATUS_GLYPH[a.status]}{' '}
755 </Text>
756 ))}
757 {planned.map(pl => (
758 <Text key={`plan-${pl.n}`} dimColor>
759 ◷{' '}
760 </Text>
761 ))}
762 </Text>
763 ) : (
764 <Box flexDirection="column" marginTop={1}>
765 {isEmpty && <Text dimColor>{s.empty}</Text>}
766 {running.length > 0 && <Text dimColor>{s.running} · {running.length}</Text>}
767 {running.map(row)}
768 {finished.length > 0 && toggleDone}
769 {!p.isDoneCollapsed && finished.map(row)}
770 {planned.length > 0 && <Text dimColor>{s.planned} · {planned.length}</Text>}
771 {planned.map(pl => {
772 const tier = pl.tier in TIER_COLOR ? pl.tier : 'other'
773 return (
774 <Box key={`plan-${pl.n}`} flexDirection="column" marginBottom={1}>
775 <Text dimColor wrap="truncate-end">
776 <Text color={colorOf(tier)}>▢</Text> {pl.n}. {pl.title} ◷
777 </Text>
778 <Text dimColor wrap="truncate-end">
779 {' '}
780 {tier} · {TIER_MODEL[tier] ?? ''}
781 {pl.after.length ? ` · ${s.after} ${pl.after.join(', ')}` : ''}
782 </Text>
783 </Box>
784 )
785 })}
786 </Box>
787 )}
788 </Box>
789 )
790 })
791
792 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
793 const f = await read($, flow)
794 if (f === null || e.props.hasSurvey) return next(e)
795
796 const ui = $.ui.resolve(e)
797 const { Box, Button } = ui
798 const list = await read($, agents)
799 const crew = list.length + plannedOf(f, list).length
800 const isWorking = list.some(a => a.status === 'running')
801 const crewButton = (
802 <Button key="savvy-agents" label={`×${crew}`} plain onPress={() => void togglePane($)} />
803 )
804 const percent = `${Math.round(ratio(f) * 100)}%`
805 const dismiss = (
806 <Button
807 key="savvy-dismiss"
808 label="✕"
809 plain
810 role="dismiss"
811 onPress={() => update($, flow, () => null)}
812 />
813 )
814
815 // Every surface's table names every element (a missing one draws an empty
816 // fragment), so the terminal is told apart by name, not by 'Svg' in ui.
817 const at = Math.max(await read($, now), ...list.map(a => a.startedAt), 0)
818 // Frames into the finish's celebration, or null once it settled.
819 const party = f.isFinished ? partyFrame(finishedAt, at) : null
820
821 if (e.surface === 'terminal') {
822 // Too narrow to seat the pane: its agents go under the bar instead.
823 const isWaiting = (await paneOf($))?.isPlaced === false
824 return terminalBand($.ui.resolve(e), {
825 waiting: isWaiting ? list.filter(a => a.status === 'running').reverse() : [],
826 at,
827 f,
828 label: label(f),
829 ratio: ratio(f),
830 percent,
831 isWorking,
832 frame: frameOf(at),
833 party,
834 columns: e.props.bodyColumns,
835 crewButton,
836 dismiss,
837 look: look(),
838 })
839 }
840
841 if ('Svg' in ui) {
842 const { Svg } = ui
843 // About 8 CSS px per reported column; the rest is the count, the dismiss
844 // and their gaps. No floor above the slot: a row wider than it would wrap.
845 const width = Math.max(180, Math.min(1600, (e.props.bodyColumns || 100) * 8 - 96))
846 return (
847 <Box flexDirection="row" alignItems="center" gap={1}>
848 <Svg source={rowSvg(f, width, isWorking, look(), label(f), ratio(f), party !== null)} alt={`${f.title}: ${label(f)}, ${percent}`} width={width} height={H} />
849 {crewButton}
850 {dismiss}
851 </Box>
852 )
853 }
854
855 return next(e)
856 })
857}
858hooks/digest.tsx 55 lines1// A finished card's click target and, once open, what the agent did: a few dim
2// plain lines, then each follow-up flagged in the callouts mod's yellow (it
3// waits on the person) or violet (it only asks). No borders and no tables, so
4// the open card stays a quiet note under the stats. Every surface draws it.
5import type { Elements } from 'claude-code'
6
7import type { AgentRun } from '../types'
8
9import { clip, digestOf } from './summary'
10
11type Parts = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'>
12
13const BLOCKING = '#fde047'
14const ASKING = '#a78bfa'
15
16export const isFinished = (a: AgentRun): boolean => a.status === 'done' || a.status === 'failed'
17
18// A card's title: for a finished run a plain Button whose glyph says whether
19// its digest is open; a running one keeps its bold text.
20export function cardTitle(ui: Parts, a: AgentRun, isOpen: boolean, width: number, onPress: () => void): JSX.Element {
21 const { Button, Text } = ui
22 if (!isFinished(a)) {
23 return (
24 <Text bold wrap="truncate-end">
25 {a.description || a.type}
26 </Text>
27 )
28 }
29 return (
30 <Button key={`open-${a.id}`} plain onPress={onPress}>
31 {isOpen ? '▾' : '▸'} <Text bold>{clip(a.description || a.type, Math.max(4, width - 2))}</Text>
32 </Button>
33 )
34}
35
36// The open card's lines, indented to sit under the title past its glyph.
37export function digestBlock(ui: Parts, a: AgentRun, width: number, empty: string): JSX.Element {
38 const { Box, Text } = ui
39 const d = digestOf(a, width - 2, empty)
40 return (
41 <Box key={`digest-${a.id}`} flexDirection="column" marginLeft={2}>
42 {d.lines.map((line, i) => (
43 <Text key={`sum-${a.id}-${i}`} dimColor>
44 {line}
45 </Text>
46 ))}
47 {d.follow.map((f, i) => (
48 <Text key={`ask-${a.id}-${i}`} color={f.isBlocking ? BLOCKING : ASKING} wrap="truncate-end">
49 ⚑ {f.text}
50 </Text>
51 ))}
52 </Box>
53 )
54}
55hooks/motion.ts 88 lines1// The frame clock: one 125 ms tick that redraws the band and the pane while
2// something moves (a worker runs, a finish is celebrated), and no timer at all
3// while nothing does. The drawings read the frame from the time, so a frame is
4// the same picture on every redraw.
5import type { EngineInterface, Timer } from 'claude-code'
6
7import type { AgentRun, Flow } from '../types'
8
9export const FRAME_MS = 125
10// How long a finish is celebrated before the crab and the bar settle.
11export const CELEBRATE_MS = 3000
12
13export const frameOf = (at: number): number => Math.floor(at / FRAME_MS)
14
15// Frames since `endedAt` while the finish is still celebrated, else null.
16export const partyFrame = (endedAt: number | undefined, at: number): number | null =>
17 endedAt !== undefined && endedAt > 0 && at >= endedAt && at - endedAt < CELEBRATE_MS ? Math.floor((at - endedAt) / FRAME_MS) : null
18
19// True while anything on screen animates: a worker runs, the flow has work out,
20// a run finished or the flow closed under CELEBRATE_MS ago.
21export function isMoving(f: Flow | null, list: AgentRun[], at: number, finishedAt: number): boolean {
22 if (list.some(a => a.status === 'running')) return true
23 if (f && !f.isFinished && f.running > 0) return true
24 if (list.some(a => a.status === 'done' && partyFrame(a.endedAt, at) !== null)) return true
25 return f?.isFinished === true && partyFrame(finishedAt, at) !== null
26}
27
28export type MotionSource = {
29 // Read fresh on every frame: what is on screen and when the flow last closed.
30 state: () => Promise<{ f: Flow | null; list: AgentRun[]; finishedAt: number }>
31 // Draws the frame at `at`, by writing the time the drawings read.
32 draw: (at: number) => Promise<void>
33}
34
35export type Motion = {
36 // Something may have started moving: runs the clock if it is not running.
37 kick: () => void
38 stop: () => void
39}
40
41/**
42 * One module load's frame clock. The tick that finds nothing moving still draws
43 * its frame, so the settled pose reaches the screen, then cancels itself; the
44 * next kick that finds something moving starts a fresh one.
45 */
46export function startMotion($: EngineInterface, src: MotionSource): Motion {
47 let timer: Timer | null = null
48 // Set by a kick, so a frame in flight that read the state before it does not
49 // stop the clock under the change.
50 let isKicked = false
51 let isStopped = false
52
53 const frame = async (mine: Timer): Promise<void> => {
54 // A tick that resolves after a newer clock started leaves that one alone.
55 if (timer !== mine || isStopped) return mine.cancel()
56 isKicked = false
57 const at = await $.clock.now()
58 const { f, list, finishedAt } = await src.state()
59 if (timer !== mine || isStopped) return mine.cancel()
60 await src.draw(at)
61 if (timer === mine && !isKicked && !isMoving(f, list, at, finishedAt)) {
62 mine.cancel()
63 timer = null
64 }
65 }
66
67 // Starts a clock only when something moves: an idle kick costs two reads, no timer.
68 const kick = (): void => {
69 isKicked = true
70 if (timer !== null || isStopped) return
71 void (async () => {
72 const at = await $.clock.now()
73 const { f, list, finishedAt } = await src.state()
74 if (timer !== null || isStopped || !isMoving(f, list, at, finishedAt)) return
75 const t: Timer = $.clock.every(FRAME_MS, () => void frame(t).catch(() => undefined))
76 timer = t
77 })().catch(() => undefined)
78 }
79
80 const stop = (): void => {
81 isStopped = true
82 timer?.cancel()
83 timer = null
84 }
85
86 return { kick, stop }
87}
88hooks/summary.ts 203 lines1// What a finished agent did, in a few plain lines: the summary it sent with its
2// last step, else the gist of its final report with the markdown, code and
3// tables taken out; and what it wants from the person, flagged. Pure functions,
4// so the card that shows them and the pane's height agree.
5import type { AgentRun } from '../types'
6
7export type Follow = { text: string; isBlocking: boolean }
8export type Digest = { lines: string[]; follow: Follow[] }
9
10const MAX_LINES = 3
11const MAX_FOLLOW = 3
12// The width the pane's height is reckoned at: the narrowest card (a 24 column
13// pane less the crab and gaps), so an open card may get a spare row but never
14// loses one.
15const ROWS_WIDTH = 12
16
17// Callouts that wait on the person (yellow) and those that only ask (violet).
18const BLOCKING = new Set(['ACTION', 'SECRET'])
19const ASKING = new Set(['ASK', 'INPUT', 'REVIEW'])
20const FOLLOW_LEAD = /open questions?|follow[- ]?ups?|next steps?|needs? you|risks?/i
21const NONE = /^(none|n\/a|nothing)\b/i
22
23type Line = {
24 text: string
25 indent: number
26 isHeading: boolean
27 isItem: boolean
28 isBold: boolean
29 // The callout this line opens, or the one whose quoted body it is in.
30 callout?: string
31 isBody: boolean
32}
33
34// Inline markdown to plain words: links keep their text, markers go. Escape
35// sequences and control bytes go first: a report quoting tool output must not
36// recolour the pane or reach the clipboard.
37export const plain = (s: string): string =>
38 s
39 .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]|\u001b[@-_]/g, '')
40 .replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')
41 .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
42 .replace(/\*\*|__|~~|`/g, '')
43 .replace(/(^|[\s(])[*_]([^*_\s][^*_]*?)[*_](?=[\s).,;:!?]|$)/g, '$1$2')
44 .replace(/\*/g, '')
45 .replace(/\s+/g, ' ')
46 .trim()
47
48export const clip = (s: string, w: number): string => (s.length <= w ? s : `${s.slice(0, Math.max(1, w - 1)).trimEnd()}…`)
49
50// Words into lines of `width`; past `max` lines the last one ends in an ellipsis.
51export function wrap(text: string, width: number, max: number): string[] {
52 const out: string[] = []
53 let line = ''
54 for (const word of text.split(/\s+/).filter(Boolean)) {
55 const next = line ? `${line} ${word}` : word
56 if (next.length <= width) {
57 line = next
58 continue
59 }
60 if (line) out.push(line)
61 line = clip(word, width)
62 }
63 if (line) out.push(line)
64 if (out.length <= max) return out
65 const kept = out.slice(0, max)
66 const last = kept[max - 1] ?? ''
67 kept[max - 1] = last.length < width ? `${last}…` : clip(last, width)
68 return kept
69}
70
71// The first `n` sentences; a full stop inside a word (a file name) is not an end.
72const sentences = (s: string, n: number): string => s.split(/(?<=[.!?])\s+(?=[A-Z0-9"'(])/).slice(0, n).join(' ')
73
74function linesOf(report: string): Line[] {
75 const out: Line[] = []
76 let fence = ''
77 let open: string | undefined
78 for (const raw of report.split(/\r?\n/)) {
79 const t = raw.trim()
80 const f = /^(```|~~~)/.exec(t)
81 if (fence) {
82 if (f && t.startsWith(fence)) fence = ''
83 continue
84 }
85 if (f) {
86 fence = f[1] ?? '```'
87 continue
88 }
89 const isQuote = t.startsWith('>')
90 if (!isQuote) open = undefined
91 // Table rows and rules end a paragraph and show nothing.
92 if (t.startsWith('|') || /^([-*_]\s*){3,}$/.test(t)) {
93 out.push({ text: '', indent: 0, isHeading: false, isItem: false, isBold: false, isBody: false })
94 continue
95 }
96 let s = t.replace(/^(>\s*)+/, '')
97 const isHeading = /^#{1,6}\s/.test(s)
98 s = s.replace(/^#{1,6}\s+/, '')
99 const isItem = /^([-*+]|\d+[.)])\s+/.test(s)
100 s = s.replace(/^([-*+]|\d+[.)])\s+/, '').replace(/^\[[ xX]\]\s+/, '')
101 const isBold = /^(\*\*|__)/.test(s)
102 const mark = /^\[!([A-Za-z]+)\]\s*/.exec(s)
103 if (mark) s = s.slice(mark[0].length)
104 const callout = mark ? (mark[1] ?? '').toUpperCase() : isQuote ? open : undefined
105 if (mark) open = callout
106 const indent = raw.length - raw.trimStart().length
107 out.push({ text: plain(s), indent, isHeading, isItem, isBold, callout, isBody: !mark && callout !== undefined })
108 }
109 return out
110}
111
112const isProse = (l: Line): boolean => l.text !== '' && !l.isHeading && l.callout === undefined
113
114// The first plain paragraph at or after `from`: a lead ending in a colon is
115// skipped, and a list item stands alone.
116function paragraphAt(lines: Line[], from: number): string {
117 const start = lines.findIndex((l, i) => i >= from && isProse(l) && !l.text.endsWith(':'))
118 if (start < 0) return ''
119 const words = [lines[start]?.text ?? '']
120 for (let i = start + 1; i < lines.length; i++) {
121 const l = lines[i]
122 if (!l || !isProse(l) || l.isItem) break
123 words.push(l.text)
124 }
125 return words.join(' ')
126}
127
128function summaryFrom(lines: Line[]): string {
129 const done = lines.find(l => l.callout === 'DONE' && !l.isBody && l.text)
130 if (done) return done.text
131 for (const word of ['summary', 'result']) {
132 const lead = new RegExp(`^${word}s?(?:\\s*[:\\-]\\s*|\\s*$)(.*)$`, 'i')
133 const i = lines.findIndex(l => l.callout === undefined && lead.test(l.text))
134 if (i < 0) continue
135 const rest = (lead.exec(lines[i]?.text ?? '')?.[1] ?? '').trim()
136 // A bare status ("done.") reads better with the paragraph after it.
137 const text = rest.split(' ').length > 3 ? rest : `${rest} ${paragraphAt(lines, i + 1)}`.trim()
138 if (text) return text.charAt(0).toUpperCase() + text.slice(1)
139 }
140 return paragraphAt(lines, 0)
141}
142
143// What a callout or a follow-up section asks of the person.
144function followsFrom(lines: Line[]): Follow[] {
145 const out: Follow[] = []
146 const add = (text: string, isBlocking: boolean): void => {
147 if (text && !NONE.test(text) && !out.some(f => f.text === text)) out.push({ text, isBlocking })
148 }
149 lines.forEach((l, i) => {
150 if (l.callout && !l.isBody && (BLOCKING.has(l.callout) || ASKING.has(l.callout))) {
151 // A marker alone on its line: its first quoted line says it.
152 const body = lines[i + 1]?.isBody && lines[i + 1]?.callout === l.callout ? (lines[i + 1]?.text ?? '') : ''
153 add(l.text || body, BLOCKING.has(l.callout))
154 return
155 }
156 const isLead = l.isHeading || l.isBold || l.isItem || l.text.endsWith(':')
157 const hit = FOLLOW_LEAD.exec(l.text)
158 if (!isLead || !hit || hit.index > 40 || l.callout !== undefined) return
159 const colon = l.text.indexOf(':', hit.index)
160 if (colon >= 0) add(l.text.slice(colon + 1).trim(), false)
161 // The items under it: deeper than the lead when the lead is an item itself.
162 const depth = l.isItem ? l.indent : -1
163 for (let j = i + 1; j < lines.length; j++) {
164 const m = lines[j]
165 if (!m || m.text === '') continue
166 if (!m.isItem || m.isHeading || m.indent <= depth) break
167 if (m.callout === undefined) add(m.text, false)
168 }
169 })
170 return out
171}
172
173// A follow-up reads as a question or a choice (violet) unless it says to act (yellow).
174const isAction = (s: string): boolean =>
175 !/\?\s*$/.test(s) && !/^(decide|choose|pick|should|which|whether|do|does|is|are|can|could|would)\b/i.test(s)
176
177/**
178 * A finished run's summary wrapped to `width`, at most three lines, and up to
179 * three one-line follow-ups. The step tool's `summary` and `followUp` win over
180 * the report; with neither a report nor a summary the line is `empty`.
181 */
182export function digestOf(run: Pick<AgentRun, 'report' | 'summary' | 'followUp'>, width: number, empty = 'No report yet'): Digest {
183 const w = Math.max(12, Math.floor(width))
184 const lines = run.report ? linesOf(run.report) : []
185 const summary = run.summary?.trim() ? plain(run.summary) : summaryFrom(lines)
186 const ask = run.followUp?.trim() ? plain(run.followUp) : ''
187 const follow = ask ? [{ text: ask, isBlocking: isAction(ask) }] : followsFrom(lines)
188 const digest: Digest = {
189 lines: summary ? wrap(sentences(summary, 2), w, MAX_LINES) : [],
190 follow: follow.slice(0, MAX_FOLLOW).map(f => ({ ...f, text: clip(f.text, w - 2) })),
191 }
192 if ((!run.report && !run.summary?.trim()) || digest.lines.length + digest.follow.length === 0) {
193 digest.lines = [empty]
194 }
195 return digest
196}
197
198// The rows an open card adds under its stats, as the pane's height reckons them.
199export const digestRows = (run: Pick<AgentRun, 'report' | 'summary' | 'followUp'>): number => {
200 const d = digestOf(run, ROWS_WIDTH)
201 return d.lines.length + d.follow.length
202}
203hooks/svg.ts 288 lines1// Desktop drawing: each row is one SVG, as the band above the prompt is. The
2// strings, palette and formatters come in through `Look`, as the terminal's do.
3import type { AgentRun, Flow, PlannedTask } from '../types'
4
5import { partyFrame } from './motion'
6import { CLAY, COSTUMES, crabBody, doneCrab } from './sprites'
7import type { Fill } from './sprites'
8import type { Look } from './terminal'
9
10type Planned = PlannedTask & { n: number }
11type Totals = { active: number; session: number; tokens: number; time: number }
12
13// Deterministic noise so the dither does not shimmer between redraws.
14const noise = (x: number, y: number): number => {
15 const s = Math.sin(x * 12.9898 + y * 78.233) * 43758.5453
16 return s - Math.floor(s)
17}
18
19// The whole row is one SVG: the desktop wraps sibling elements onto new lines,
20// so title, bar, percent and the crab live in one drawing; only the count and
21// the dismiss are Buttons beside it.
22export const H = 22
23const BAR_H = 16
24const CRAB_W = 26
25const CELL = 3
26const FONT = "-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',sans-serif"
27
28const xml = (s: string): string =>
29 s.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] ?? c)
30
31// Rough advance of system UI text, in em; good enough to size the title's slot.
32const charEm = (ch: string): number =>
33 /[\s.,:;'|!il1()[\]]/.test(ch) ? 0.3 : /[A-ZА-ЯЁmwшщжюМШЩЖЮ@%]/.test(ch) ? 0.72 : 0.56
34
35const textWidth = (s: string, size: number): number => [...s].reduce((w, ch) => w + charEm(ch) * size, 0)
36
37// Cuts `s` to fit `maxW` pixels, with an ellipsis when it had to cut.
38const fitText = (s: string, size: number, maxW: number): string => {
39 if (textWidth(s, size) <= maxW) return s
40 let out = ''
41 for (const ch of s) {
42 if (textWidth(out + ch + '…', size) > maxW) break
43 out += ch
44 }
45 return out + '…'
46}
47
48// `isParty`: the flow finished under three seconds ago, so the crab waves its flag.
49export const rowSvg = (f: Flow, W: number, isWorking: boolean, look: Look, text: string, r: number, isParty: boolean): string => {
50 // The title takes what it needs, up to 40% of the row; the bar takes the rest.
51 const title = fitText(f.title, 13, Math.max(60, W * 0.4))
52 const BAR_X = Math.round(16 + textWidth(title, 13) + 12)
53 const BAR_W = Math.max(60, W - BAR_X - 46 - CRAB_W)
54 const color = f.isFinished ? look.done : look.accent
55 const y0 = (H - BAR_H) / 2
56 const fillW = Math.round(BAR_W * r)
57 const runW = f.total ? Math.round((BAR_W * Math.min(f.total, f.done + f.running)) / f.total) : 0
58 const dots: string[] = []
59
60 // Dithered fill: sparse at the start, dense toward the head.
61 const cols = Math.floor(fillW / CELL)
62 const rows = Math.floor(BAR_H / CELL)
63 for (let c = 0; c < cols; c++) {
64 const density = 0.35 + 0.6 * Math.pow(c / Math.max(1, cols), 1.2)
65 for (let r = 0; r < rows; r++) {
66 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"/>`)
67 }
68 }
69 // Handed to workers, not yet accepted: a faint second layer.
70 const faint: string[] = []
71 for (let c = cols; c < Math.floor(runW / CELL); c++) {
72 for (let r = 0; r < rows; r++) {
73 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"/>`)
74 }
75 }
76
77 const ticks: string[] = []
78 for (let i = 1; i < f.total; i++) {
79 const x = Math.round((BAR_W * i) / f.total)
80 if (x > fillW + 4) ticks.push(`<rect x="${x}" y="${BAR_H / 2 - 4}" width="1.5" height="8" rx="0.75"/>`)
81 }
82
83 const pillW = Math.round(18 + text.length * 6.6)
84 const pillX = Math.max(0, Math.min(BAR_W - pillW, fillW - pillW))
85 const percent = `${Math.round(r * 100)}%`
86 const done = f.isFinished ? { color: look.done, isParty } : undefined
87
88 return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
89<style>
90.t{fill:#1f1f1f}.m{fill:#8a8a8a}.k{fill:#e4e4e2}.tk{fill:#b4b4b0}
91@media (prefers-color-scheme: dark){.t{fill:#ececec}.m{fill:#9a9a9a}.k{fill:#2c2c2c}.tk{fill:#5a5a5a}}
92/* Pixels twinkle in four out-of-phase groups; a finished bar settles to a slow glow. */
93.t0,.t1,.t2,.t3{animation:tw ${f.isFinished ? 3.2 : 2.2}s ease-in-out infinite}
94.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}
95@keyframes tw{0%,100%{opacity:1}50%{opacity:${f.isFinished ? 0.8 : 0.3}}}
96@media (prefers-reduced-motion: reduce){.t0,.t1,.t2,.t3{animation:none}}
97</style>
98<defs><clipPath id="c"><rect x="0" y="0" width="${BAR_W}" height="${BAR_H}" rx="${BAR_H / 2}"/></clipPath></defs>
99<circle cx="5" cy="${H / 2}" r="4" fill="${color}"/>
100<text class="t" x="16" y="${H / 2 + 4.5}" font-family="${FONT}" font-size="13" font-weight="500">${xml(title)}</text>
101<g transform="translate(${BAR_X},${y0})">
102<rect class="k" width="${BAR_W}" height="${BAR_H}" rx="${BAR_H / 2}"/>
103<g clip-path="url(#c)">
104<g fill="${color}">${dots.join('')}</g>
105<g fill="${color}" opacity="0.45">${faint.join('')}</g>
106<g class="tk">${ticks.join('')}</g>
107</g>
108<rect x="${pillX}" width="${pillW}" height="${BAR_H}" rx="${BAR_H / 2}" fill="${color}"/>
109<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>
110</g>
111<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>
112${CRAB_CSS}${crab(W - CRAB_W + 1, 0, 'other', look.colorOf('other'), false, isWorking, 0.8, done)}
113</svg>`
114}
115
116// --- the agents pane.
117
118const PANE_CSS = `<style>
119.t{fill:#1f1f1f}.s{fill:#6b6b68}.m{fill:#9a9a96}.k{fill:#ecebe8}.ln{stroke:#e4e4e1}.tile{fill:#f4f3f0}
120@media (prefers-color-scheme: dark){.t{fill:#ececec}.s{fill:#a8a8a4}.m{fill:#7d7d79}.k{fill:#2c2c2b}.ln{stroke:#333331}.tile{fill:#262625}}
121.live{animation:p 1.6s ease-in-out infinite}@keyframes p{50%{opacity:.3}}
122@media (prefers-reduced-motion: reduce){.live{animation:none}}
123</style>`
124
125// Pure CSS, run by the compositor: no redraws. Periods divide one second, so the
126// once-a-second redraw of a running row restarts them in phase. Every crab walks;
127// each costume adds its prop's own motion on top. A crab done under three seconds
128// ago (`cel`) waves its far claw and its pennant flutters in three steps.
129const CRAB_CSS = `<style>
130.run .la{animation:st .5s steps(1) infinite}.run .lb{animation:st .5s steps(1) infinite -.25s}
131.run .bd{animation:bob .5s steps(1) infinite -.125s}
132.run g{transform-box:fill-box}
133@keyframes st{50%{transform:translateY(-1px)}}@keyframes bob{50%{transform:translateY(1px)}}
134.c-fable.run{animation:float 1s ease-in-out infinite}
135.c-fable.run .la,.c-fable.run .lb,.c-fable.run .bd{animation:none}
136.c-fable.run .ant{animation:blink 1s steps(1) infinite}
137.c-fable.run .star{animation:blink .5s steps(1) infinite -.25s}
138@keyframes float{50%{transform:translateY(-2px)}}@keyframes blink{50%{opacity:.15}}
139.c-heavy.run .it{animation:scan 1s steps(1) infinite}
140.c-heavy.run .gl{animation:blink 1s steps(1) infinite -.5s}
141@keyframes scan{25%{transform:translate(-1px,1px)}50%{transform:translate(-2px,2px)}75%{transform:translate(-1px,1px)}}
142.c-careful.run .it{transform-origin:100% 100%;animation:twist .5s ease-in-out infinite}
143@keyframes twist{50%{transform:rotate(-35deg)}}
144.c-medium.run .pan{transform-origin:0 50%;animation:tilt 1s ease-in-out infinite}
145.c-medium.run .egg{animation:flip 1s ease-in-out infinite}
146@keyframes tilt{20%,40%{transform:rotate(-12deg)}}@keyframes flip{30%{transform:translateY(-5px) scaleY(-1)}60%{transform:translateY(0)}}
147.c-light.run .la{animation-duration:.25s}.c-light.run .lb{animation-duration:.25s;animation-delay:-.125s}
148.c-light.run .flag{transform-origin:0 50%;animation:wave .25s steps(1) infinite}
149@keyframes wave{50%{transform:skewY(-12deg) scaleX(.85)}}
150.c-explore.run .it{transform-origin:50% 100%;animation:fence .5s ease-in-out infinite}
151@keyframes fence{50%{transform:rotate(25deg)}}
152.cel g{transform-box:fill-box}
153.c-done.cel .wv{animation:hi .5s steps(1) infinite}
154.c-done.cel .fl{transform-origin:100% 50%;animation:flap .375s steps(1) infinite}
155@keyframes hi{50%{transform:translateY(4px)}}
156@keyframes flap{33%{transform:skewY(12deg) scaleX(.85)}67%{transform:skewY(-8deg) scaleX(.92)}}
157@media (prefers-reduced-motion: reduce){.run,.run g,.cel,.cel g{animation:none!important}}
158</style>`
159
160const CRAB_SCALE = 1.1
161
162type DonePose = { color: string; isParty: boolean }
163
164// Body and props nest inside `bd` so a prop rides the bob and adds its own motion;
165// legs stay outside it and step on their own. `done` swaps the costume for the
166// finished pose: the body in the done green, a flag in the tier's color.
167const crab = (x: number, y: number, costume: string, tint: string, dim = false, isWalking = false, scale = CRAB_SCALE, done?: DonePose): string => {
168 const groups = new Map<string, string[]>([['bd', []]])
169 const f: Fill = (cx, cy, w, h, c, cls = 'bd') => {
170 if (!groups.has(cls)) groups.set(cls, [])
171 groups.get(cls)?.push(`<rect x="${cx}" y="${cy}" width="${w}" height="${h}" fill="${done && c === CLAY ? done.color : c}"/>`)
172 }
173 const draw = done ? doneCrab : (COSTUMES[costume] ?? ((g: Fill) => crabBody(g)))
174 draw(f, tint)
175 const group = (cls: string) => `<g class="${cls}">${(groups.get(cls) ?? []).join('')}</g>`
176 const props = [...groups.keys()].filter(k => k !== 'bd' && k !== 'la' && k !== 'lb')
177 const body = `<g class="bd">${(groups.get('bd') ?? []).join('')}${props.map(group).join('')}</g>`
178 const cls = done ? `c-done${done.isParty ? ' cel' : ''}` : `c-${costume}${isWalking ? ' run' : ''}`
179 return `<g transform="translate(${x},${y}) scale(${scale})" opacity="${dim ? 0.45 : 1}" shape-rendering="crispEdges"><g class="${cls}">${body}${group('la')}${group('lb')}</g></g>`
180}
181
182// The finished pose of a run, or undefined while it runs or after it failed.
183const donePose = (a: AgentRun, at: number, look: Look): DonePose | undefined =>
184 a.status === 'done' ? { color: look.done, isParty: partyFrame(a.endedAt, at) !== null } : undefined
185
186const statusMark = (x: number, y: number, status: string, color: string): string => {
187 if (status === 'running') return `<circle class="live" cx="${x}" cy="${y}" r="3.5" fill="${color}"/>`
188 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"/>`
189 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"/>`
190 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"/>`
191}
192
193const svg = (W: number, H: number, body: string): string =>
194 `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">${PANE_CSS}${CRAB_CSS}${body}</svg>`
195
196// The pane's own title already says "Agents": the header names the flow, if any.
197export const headerSvg = (W: number, title: string, t: Totals, look: Look): string => {
198 const s = look.s
199 const gap = 6
200 const tw = (W - gap * 3) / 4
201 const top = title ? 28 : 0
202 const tile = (i: number, k: string | undefined, v: string) =>
203 `<rect class="tile" x="${i * (tw + gap)}" y="${top}" width="${tw}" height="40" rx="8"/>
204<text class="s" x="${i * (tw + gap) + 9}" y="${top + 16}" font-family="${FONT}" font-size="11">${k}</text>
205<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>`
206 return svg(
207 W,
208 headerHeight(title),
209 `${title ? `<text class="t" x="0" y="15" font-family="${FONT}" font-size="14" font-weight="600">${xml(fitText(title, 14, W))}</text>` : ''}
210${tile(0, s.active, '≈' + look.fmtCost(t.active))}${tile(1, s.session, look.fmtCost(t.session))}${tile(2, s.tokens, look.fmtTokens(t.tokens))}${tile(3, s.time, look.fmtTime(t.time))}`,
211 )
212}
213
214export const headerHeight = (title: string): number => (title ? 72 : 44)
215
216export const agentSvg = (W: number, a: AgentRun, at: number, look: Look): string => {
217 const s = look.s
218 const tier = look.tierOf(a.type)
219 const color = look.colorOf(tier)
220 const ctx = look.ctxOf(a)
221 const textW = W - 42 - 22
222 const meta = [a.effort ? `${look.modelName(a.model)} · ${a.effort}` : look.modelName(a.model)]
223 if (a.round > 1) meta.push(`${s.round} ${a.round}`)
224 if (a.status === 'failed') meta.push(s.failed ?? '')
225 const barW = textW
226 const progress = look.progressOf(a)
227 const stats = `ctx ${ctx}% · ${look.fmtTokens(a.contextTokens)} ≈${look.fmtCost(a.costUsd)} ${look.fmtTime(look.elapsed(a, at))}`
228 const steps = a.stepTotal ? `${a.stepDone ?? 0}/${a.stepTotal}${a.stepNote ? ' · ' + a.stepNote : ''}` : ''
229 const stepsW = Math.max(0, barW - textWidth(stats, 11) - 12)
230 // Without reported steps the bar falls back to the context, drawn grey.
231 const fillW = Math.round(barW * (progress ?? ctx / 100))
232 const costume = look.costumeOf(a.type)
233 return svg(
234 W,
235 66,
236 `${crab(0, 14, costume, look.colorOf(costume), false, a.status === 'running', CRAB_SCALE, donePose(a, at, look))}
237<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>
238<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>
239${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>` : ''}
240<text class="s" x="${42 + barW}" y="49" text-anchor="end" font-family="${FONT}" font-size="11" font-variant-numeric="tabular-nums">${stats}</text>
241<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}"`}/>
242${statusMark(W - 8, 16, a.status, color)}
243<line class="ln" x1="0" y1="65.5" x2="${W}" y2="65.5"/>`,
244 )
245}
246
247export const plannedSvg = (W: number, p: Planned, look: Look): string => {
248 const tier = p.tier in look.tierColor ? p.tier : 'other'
249 const color = look.colorOf(tier)
250 const textW = W - 42 - 22
251 const meta = [look.tierModel[tier] ?? '']
252 if (p.after.length) meta.push(`${look.s.after} ${p.after.join(', ')}`)
253 return svg(
254 W,
255 46,
256 `${crab(0, 6, tier, look.colorOf(tier), true)}
257<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>
258<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>
259${statusMark(W - 8, 16, 'planned', color)}
260<line class="ln" x1="0" y1="45.5" x2="${W}" y2="45.5"/>`,
261 )
262}
263
264export const compactSvg = (W: number, list: AgentRun[], planned: Planned[], t: Totals, at: number, look: Look): string => {
265 const icons = [
266 ...list.filter(a => a.status === 'running').map(a => ({ k: look.costumeOf(a.type), c: look.colorOf(look.tierOf(a.type)), s: 'running', dim: false, done: undefined })),
267 ...list.filter(a => a.status !== 'running').map(a => ({ k: look.costumeOf(a.type), c: look.colorOf(look.tierOf(a.type)), s: a.status, dim: false, done: donePose(a, at, look) })),
268 ...planned.map(p => ({ k: p.tier in look.tierColor ? p.tier : 'other', c: look.colorOf(p.tier), s: 'planned', dim: true, done: undefined })),
269 ]
270 const fit = Math.max(1, Math.floor((W - 150) / 36))
271 const shown = icons.slice(0, fit)
272 const more = icons.length - shown.length
273 const body = shown
274 .map(
275 (ic, i) =>
276 crab(i * 36, 0, ic.k, look.colorOf(ic.k), ic.dim, ic.s === 'running', CRAB_SCALE, ic.done) +
277 (ic.s === 'running' ? `<circle class="live" cx="${i * 36 + 32}" cy="4" r="3" fill="${ic.c}"/>` : ''),
278 )
279 .join('')
280 const x = shown.length * 36 + (more ? 4 : 0)
281 return svg(
282 W,
283 32,
284 `${body}${more ? `<text class="s" x="${x}" y="21" font-family="${FONT}" font-size="12">+${more}</text>` : ''}
285<text class="s" x="${W}" y="21" text-anchor="end" font-family="${FONT}" font-size="12" font-variant-numeric="tabular-nums">≈${look.fmtCost(t.active)} / ${look.fmtCost(t.session)} · ${look.fmtTokens(t.tokens)} · ${look.fmtTime(t.time)}</text>`,
286 )
287}
288hooks/pricing.ts 48 lines1// What a model request costs. The engine reports tokens per agent, not money,
2// so an agent's cost is an estimate; the session total comes from the engine.
3
4type Usage = {
5 input_tokens: number
6 output_tokens: number
7 cache_read_input_tokens: number
8 cache_creation_input_tokens: number
9}
10
11// USD per million tokens: input, output, cache read, cache write (5-minute TTL,
12// 1.25x input). First match wins, so a bare family name means its newest model.
13// Anthropic list prices as of 2026-10.
14const PRICES: [RegExp, [number, number, number, number]][] = [
15 [/(fable|mythos)-5-1/, [10, 50, 0.25, 12.5]],
16 [/fable|mythos/, [10, 50, 1, 12.5]],
17 [/opus-5-5/, [4, 20, 0.2, 5]],
18 [/opus-4-(1|2025)|opus-3/, [15, 75, 1.5, 18.75]],
19 [/opus/, [5, 25, 0.5, 6.25]],
20 [/sonnet-[34]/, [3, 15, 0.3, 3.75]],
21 [/sonnet/, [2, 10, 0.2, 2.5]],
22 [/haiku-[34]/, [1, 5, 0.1, 1.25]],
23 [/haiku/, [0.1, 0.5, 0.01, 0.125]],
24]
25
26// Claude Haiku 5.5 charges 5x on a prompt over 100K tokens.
27const LONG_PROMPT = 100_000
28
29export const priceOf = (model: string): [number, number, number, number] =>
30 PRICES.find(([re]) => re.test(model.toLowerCase()))?.[1] ?? [4, 20, 0.2, 5]
31
32export const costOf = (model: string, u: Usage): number => {
33 const [i, o, r, w] = priceOf(model)
34 const prompt = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0)
35 const scale = /haiku/i.test(model) && !/haiku-[34]/i.test(model) && prompt > LONG_PROMPT ? 5 : 1
36 return (
37 (scale *
38 ((u.input_tokens || 0) * i +
39 (u.output_tokens || 0) * o +
40 (u.cache_read_input_tokens || 0) * r +
41 (u.cache_creation_input_tokens || 0) * w)) /
42 1e6
43 )
44}
45
46// Haiku 4.5 and older have 200K; every current model has 1M.
47export const windowOf = (model: string): number => (/haiku-[34]/i.test(model) ? 200_000 : 1_000_000)
48hooks/terminal.tsx 559 lines1// Terminal drawing: the desktop's look painted in colored cells. A Raster cell
2// holds a glyph with a 24-bit foreground and background, so half blocks give two
3// square pixels per cell and the crabs, the gradient bar and the pill survive in
4// any truecolor terminal, with no image protocol. Every drawing is a pure
5// function of its inputs and the frame, so a redraw never shimmers.
6import type { Elements } from 'claude-code'
7
8import type { AgentRun, Flow, PlannedTask } from '../types'
9
10import { cardTitle, digestBlock, isFinished } from './digest'
11import { CELEBRATE_MS, FRAME_MS, partyFrame } from './motion'
12import { CLAY, COSTUMES, INK, crabBody } from './sprites'
13import type { Fill } from './sprites'
14
15type Ui = Elements['terminal']
16type Planned = PlannedTask & { n: number }
17
18export type Look = {
19 s: Record<string, string>
20 accent: string
21 done: string
22 tierColor: Record<string, string>
23 tierModel: Record<string, string>
24 colorOf: (tier: string) => string
25 tierOf: (type: string) => string
26 costumeOf: (type: string) => string
27 modelName: (id: string) => string
28 fmtTokens: (n: number) => string
29 fmtCost: (usd: number) => string
30 fmtTime: (ms: number) => string
31 elapsed: (a: AgentRun, at: number) => number
32 ctxOf: (a: AgentRun) => number
33 progressOf: (a: AgentRun) => number | null
34}
35
36const DEFAULT = 0x01000000
37const BG = 0x1e1e22
38const TRACK = 0x313139
39const FAINT = 0x4a4a52
40const WHITE = 0xffffff
41const POLE = 0xc9ccd2
42
43const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
44
45function base64(bytes: Uint8Array): string {
46 let out = ''
47 for (let i = 0; i < bytes.length; i += 3) {
48 const a = bytes[i] ?? 0
49 const b = bytes[i + 1] ?? 0
50 const c = bytes[i + 2] ?? 0
51 const n = (a << 16) | (b << 8) | c
52 out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]!
53 out += i + 1 < bytes.length ? B64[(n >> 6) & 63]! : '='
54 out += i + 2 < bytes.length ? B64[n & 63]! : '='
55 }
56 return out
57}
58
59const rgbOf = (hex: string): number => {
60 const h = hex.replace('#', '')
61 const full = h.length === 3 ? [...h].map(c => c + c).join('') : h
62 return parseInt(full, 16) & 0xffffff
63}
64
65const mix = (a: number, b: number, t: number): number => {
66 const ch = (shift: number) => Math.round(((a >> shift) & 255) * (1 - t) + ((b >> shift) & 255) * t)
67 return (ch(16) << 16) | (ch(8) << 8) | ch(0)
68}
69
70class Grid {
71 readonly words: Uint32Array
72
73 constructor(
74 readonly columns: number,
75 readonly rows: number,
76 ) {
77 this.words = new Uint32Array(columns * rows * 3)
78 for (let i = 0; i < columns * rows; i++) this.words.set([0x20, DEFAULT, DEFAULT], i * 3)
79 }
80
81 set(x: number, y: number, glyph: string, fg: number, bg: number): void {
82 if (x < 0 || y < 0 || x >= this.columns || y >= this.rows) return
83 this.words.set([glyph.codePointAt(0) ?? 0x20, fg, bg], (y * this.columns + x) * 3)
84 }
85
86 cells(): string {
87 return base64(new Uint8Array(this.words.buffer))
88 }
89}
90
91// --- crabs: hand-drawn minis colored from the shared 30×28 sprites.
92
93const SPRITE_W = 30
94const SPRITE_H = 28
95const INK_RGB = rgbOf(INK)
96
97function spritePixels(costume: string, tint: string): Int32Array {
98 const px = new Int32Array(SPRITE_W * SPRITE_H).fill(-1)
99 const fill: Fill = (x, y, w, h, c) => {
100 const rgba = /rgba\((\d+),(\d+),(\d+),([.\d]+)\)/.exec(c.replace(/\s/g, ''))
101 for (let yy = y; yy < y + h; yy++) {
102 for (let xx = x; xx < x + w; xx++) {
103 if (xx < 0 || yy < 0 || xx >= SPRITE_W || yy >= SPRITE_H) continue
104 const i = yy * SPRITE_W + xx
105 if (rgba) {
106 const color = (Number(rgba[1]) << 16) | (Number(rgba[2]) << 8) | Number(rgba[3])
107 const under = (px[i] ?? -1) < 0 ? BG : (px[i] ?? BG)
108 px[i] = mix(under, color, Number(rgba[4]))
109 } else {
110 px[i] = rgbOf(c)
111 }
112 }
113 }
114 }
115 const draw = COSTUMES[costume] ?? ((g: Fill) => crabBody(g))
116 draw(fill, tint)
117 return px
118}
119
120// A crab drawn for 6×4 pixels: a shrunk sprite loses its eyes and legs, so
121// only the body and hat colors come from the full costume.
122const MINI = ['.HHHH.', 'CICCIC', '.CCCC.']
123const LEGS = ['.C..C.', 'C.CC.C']
124
125function colorsOf(px: Int32Array): { body: number; hat: number } {
126 const tally = (y0: number, y1: number, skip: number[]) => {
127 const counts = new Map<number, number>()
128 for (let i = y0 * SPRITE_W; i < y1 * SPRITE_W; i++) {
129 const c = px[i] ?? -1
130 if (c >= 0 && !skip.includes(c)) counts.set(c, (counts.get(c) ?? 0) + 1)
131 }
132 return [...counts].sort((x, y) => y[1] - x[1])[0]?.[0]
133 }
134 const body = tally(12, SPRITE_H, [INK_RGB]) ?? rgbOf(CLAY)
135 return { body, hat: tally(0, 10, [INK_RGB, body]) ?? body }
136}
137
138function miniPixels(costume: string, tint: string, step: number): Int32Array {
139 const { body, hat } = colorsOf(spritePixels(costume, tint))
140 const color: Record<string, number> = { H: hat, C: body, I: INK_RGB }
141 const rows = [...MINI, LEGS[step % 2] ?? '']
142 const out = new Int32Array(CRAB_COLS * rows.length).fill(-1)
143 rows.forEach((row, y) => [...row].forEach((ch, x) => (out[y * CRAB_COLS + x] = color[ch] ?? -1)))
144 return out
145}
146
147function halfBlocks(px: Int32Array, w: number, h: number, dim: boolean): Grid {
148 const grid = new Grid(w, Math.ceil(h / 2))
149 const tone = (c: number) => (dim ? mix(c, BG, 0.55) : c)
150 for (let r = 0; r < grid.rows; r++) {
151 for (let x = 0; x < w; x++) {
152 const top = px[2 * r * w + x] ?? -1
153 const bottom = px[(2 * r + 1) * w + x] ?? -1
154 if (top >= 0 && bottom >= 0) grid.set(x, r, '▀', tone(top), tone(bottom))
155 else if (top >= 0) grid.set(x, r, '▀', tone(top), DEFAULT)
156 else if (bottom >= 0) grid.set(x, r, '▄', tone(bottom), DEFAULT)
157 }
158 }
159 return grid
160}
161
162// Cards seat the crab in 8 columns: the body in the first 6, a planted flag
163// beside it once the run is done.
164const CRAB_COLS = 8
165const CRAB_ROWS = 2
166// A leg step every half second.
167const WALK_FRAMES = 4
168
169function crabCells(costume: string, tint: string, step: number, dim: boolean): string {
170 const px = miniPixels(costume, tint, step)
171 return halfBlocks(px, CRAB_COLS, CRAB_ROWS * 2, dim).cells()
172}
173
174// The done pose: the body in the done green, the hat swapped for a flag on a
175// pole in the tier's color. While `party` counts frames into the celebration the
176// far claw waves and the pennant cycles three flutter frames; null rests still.
177function doneCells(tint: string, done: number, party: number | null): string {
178 const flag = rgbOf(tint)
179 const fold = mix(flag, WHITE, 0.4)
180 const isUp = party !== null && Math.floor(party / 2) % 2 === 0
181 const flutter: [number, number][] = [[flag, flag], [flag, fold], [fold, flag]]
182 const [top, low] = flutter[party === null ? 0 : party % 3] ?? [flag, flag]
183 const color: Record<string, number> = { C: done, I: INK_RGB, P: POLE, F: top, G: low }
184 const rows = [isUp ? 'C.....PF' : '......PF', isUp ? '.ICCICPG' : 'CICCICPG', '.CCCC.P.', `${LEGS[0]}P.`]
185 const px = new Int32Array(CRAB_COLS * rows.length).fill(-1)
186 rows.forEach((row, y) => [...row].forEach((ch, x) => (px[y * CRAB_COLS + x] = color[ch] ?? -1)))
187 return halfBlocks(px, CRAB_COLS, CRAB_ROWS * 2, false).cells()
188}
189
190// A card's crab: walking while the run runs, the done pose once it is done.
191// `party` is frames into the done celebration (see partyFrame), null after it.
192export function cardCrabCells(costume: string, tint: string, status: string, frame: number, party: number | null, done: string): string {
193 if (status === 'done') return doneCells(tint, rgbOf(done), party)
194 return crabCells(costume, tint, status === 'running' ? Math.floor(frame / WALK_FRAMES) : 0, false)
195}
196
197export type Mood = 'walk' | 'idle' | 'party' | 'rest'
198
199// A six-pixel crab for the one-row band: the legs swap each half second while
200// busy; once the flow closes it turns the done green and waves for a moment.
201export function miniCrabCells(frame: number, mood: Mood, done: number): string {
202 const body = mood === 'party' || mood === 'rest' ? done : rgbOf(CLAY)
203 const legs = mood === 'walk' && Math.floor(frame / WALK_FRAMES) % 2 === 1 ? [0, 1, 0, 0, 1, 0] : [1, 0, 1, 1, 0, 1]
204 const grid = new Grid(6, 1)
205 legs.forEach((b, x) => grid.set(x, 0, b ? '█' : '▀', body, DEFAULT))
206 grid.set(2, 0, '▀', INK_RGB, body)
207 grid.set(3, 0, '▀', INK_RGB, body)
208 if (mood === 'party') grid.set(5, 0, Math.floor(frame / 2) % 2 === 0 ? '▀' : '▄', body, DEFAULT)
209 return grid.cells()
210}
211
212// --- the band's bar: a rounded track, a gradient fill with a sub-cell edge, the
213// running segment breathing ahead of it, the pill.
214
215const EIGHTHS = ['▏', '▎', '▍', '▌', '▋', '▊', '▉']
216const SHEEN_W = 6
217// Frames per breath of the running segment: two seconds.
218const BREATH = 16
219const PARTY_FRAMES = CELEBRATE_MS / FRAME_MS
220
221export type BarMotion = {
222 frame: number
223 // Work is out: the sheen sweeps the fill and the running segment breathes.
224 isWorking: boolean
225 // Frames into the finish's celebration, null outside it.
226 party: number | null
227}
228
229export function barCells(f: Flow, width: number, label: string, ratio: number, accent: number, m: BarMotion): string {
230 const grid = new Grid(width, 1)
231 const inner = width - 2
232 const eighths = Math.round(inner * 8 * Math.min(1, Math.max(0, ratio)))
233 const full = Math.floor(eighths / 8)
234 const part = eighths % 8
235 const edge = full + (part ? 1 : 0)
236 const run = f.total ? Math.round((inner * Math.min(f.total, f.done + f.running)) / f.total) : 0
237 const isMoving = m.isWorking && !f.isFinished
238 const party = f.isFinished ? m.party : null
239
240 const dark = mix(accent, BG, 0.45)
241 const light = mix(accent, WHITE, 0.3)
242 // What lies under cell i past the fill: the track, or the running segment's breath.
243 const under = (i: number): number => {
244 if (i >= run) return TRACK
245 const t = isMoving ? 0.5 - 0.5 * Math.cos((2 * Math.PI * (m.frame - i * 0.5)) / BREATH) : 0.5
246 return mix(TRACK, accent, 0.08 + 0.16 * t)
247 }
248 // White added to fill cell i: the sheen while working, the sparkle while celebrating.
249 const shine = (i: number): number => {
250 if (party !== null) {
251 const d = ((party + 1) / PARTY_FRAMES) * (inner + 6) - 3 - i
252 return d >= 0 && d < 5 ? 0.8 * (1 - d / 5) : 0
253 }
254 if (!isMoving || full === 0) return 0
255 const d = (m.frame % (full + SHEEN_W)) - i
256 return d >= 0 && d < SHEEN_W ? 0.38 * Math.sin((Math.PI * (d + 0.5)) / SHEEN_W) : 0
257 }
258
259 // Each cell's background as painted, so the pill's caps round onto it.
260 const bg: number[] = [DEFAULT]
261 for (let i = 0; i < inner; i++) {
262 const x = i + 1
263 if (i < full) {
264 const c = mix(mix(dark, light, full > 1 ? i / (full - 1) : 1), WHITE, shine(i))
265 grid.set(x, 0, ' ', c, c)
266 bg.push(c)
267 } else if (i === full && part) {
268 // The leading edge: a partial block in the head's color on a soft glow.
269 const glow = mix(under(i), light, 0.16)
270 grid.set(x, 0, EIGHTHS[part - 1] ?? '▌', light, glow)
271 bg.push(glow)
272 } else {
273 const c = i === edge && edge > 0 ? mix(under(i), light, 0.08) : under(i)
274 grid.set(x, 0, ' ', c, c)
275 bg.push(c)
276 }
277 }
278 bg.push(DEFAULT)
279 grid.set(0, 0, '▐', TRACK, DEFAULT)
280 grid.set(width - 1, 0, '▌', TRACK, DEFAULT)
281 for (let t = 1; t < f.total; t++) {
282 const x = 1 + Math.round((inner * t) / f.total)
283 if (x > edge + 2 && x < width - 1) grid.set(x, 0, '╎', FAINT, bg[x] ?? TRACK)
284 }
285
286 // The pill rides just ahead of the edge while it fits there, so the edge
287 // shows; else it sits inside the fill, flush with its end.
288 const text = ` ${label} `
289 const pillW = Math.min(inner, [...text].length)
290 const ahead = edge + 2
291 const pillX = ahead + pillW + 1 <= width - 1 ? ahead : 1 + Math.max(0, Math.min(inner - pillW, edge - pillW))
292 ;[...text].slice(0, pillW).forEach((ch, k) => grid.set(pillX + k, 0, ch, WHITE, accent))
293 grid.set(pillX - 1, 0, '▐', accent, bg[pillX - 1] ?? DEFAULT)
294 if (pillX + pillW < width) grid.set(pillX + pillW, 0, '▌', accent, bg[pillX + pillW] ?? DEFAULT)
295 return grid.cells()
296}
297
298function lineCells(width: number, ratio: number | null, ctx: number, color: number): string {
299 const grid = new Grid(width, 1)
300 const filled = Math.round(width * (ratio ?? ctx / 100))
301 const fg = ratio === null ? 0x6a6a72 : color
302 for (let x = 0; x < width; x++) grid.set(x, 0, '━', x < filled ? fg : 0x38383e, DEFAULT)
303 return grid.cells()
304}
305
306// --- the band above the prompt.
307
308const STATUS: Record<string, { glyph: string; color: string }> = {
309 running: { glyph: '●', color: '#5fbf8f' },
310 done: { glyph: '✓', color: '#3B9C5F' },
311 failed: { glyph: '✗', color: '#D0453F' },
312}
313
314export type BandProps = {
315 f: Flow
316 label: string
317 ratio: number
318 percent: string
319 isWorking: boolean
320 frame: number
321 // Frames into the finish's celebration, null outside it.
322 party: number | null
323 columns: number
324 crewButton: JSX.Element
325 dismiss: JSX.Element
326 look: Look
327 // Agents to list under the bar: the pane is open but too narrow to place.
328 waiting: AgentRun[]
329 at: number
330}
331
332const BAND_AGENTS = 6
333
334// One line per agent, for a terminal too narrow to seat the agents pane.
335function bandAgent(ui: Ui, p: BandProps, a: AgentRun): JSX.Element {
336 const { Box, Text } = ui
337 const { look } = p
338 const tier = look.tierOf(a.type)
339 const tint = look.colorOf(tier === 'other' && look.costumeOf(a.type) === 'explore' ? 'medium' : tier)
340 const status = STATUS[a.status] ?? STATUS.running!
341 const steps = a.stepTotal ? ` ${a.stepDone ?? 0}/${a.stepTotal}` : ''
342 const stats = `${look.ctxOf(a)}% ${look.fmtTime(look.elapsed(a, p.at))}`
343
344 return (
345 <Box key={`band-${a.id}`} flexDirection="row" gap={1}>
346 <Text color={status.color}>{status.glyph}</Text>
347 <Box flexGrow={1} flexShrink={1}>
348 <Text wrap="truncate-end">
349 {a.description || a.type}
350 <Text color={tint}> {tier === 'other' ? a.type : tier}</Text>
351 <Text dimColor>{steps}</Text>
352 </Text>
353 </Box>
354 <Box flexShrink={0}>
355 <Text dimColor>{stats}</Text>
356 </Box>
357 </Box>
358 )
359}
360
361export function terminalBand(ui: Ui, p: BandProps): JSX.Element {
362 const { Box, Text, Raster } = ui
363 const color = p.f.isFinished ? p.look.done : p.look.accent
364 const motion = { frame: p.frame, isWorking: p.isWorking || p.f.running > 0, party: p.party }
365 const mood: Mood = p.f.isFinished ? (p.party !== null ? 'party' : 'rest') : p.isWorking ? 'walk' : 'idle'
366 const titleW = Math.max(8, Math.min(28, p.f.title.length + 1, Math.floor(p.columns / 3)))
367 const barW = Math.max(10, p.columns - titleW - 26)
368
369 const bar = (
370 <Box flexDirection="row" gap={1}>
371 <Text color={color}>●</Text>
372 <Box width={titleW} flexShrink={0}>
373 <Text bold wrap="truncate-end">
374 {p.f.title}
375 </Text>
376 </Box>
377 <Raster key="savvy-bar" columns={barW} rows={1} cells={barCells(p.f, barW, p.label, p.ratio, rgbOf(color), motion)} />
378 <Text dimColor>{p.percent.padStart(4)}</Text>
379 <Raster key="savvy-mini" columns={6} rows={1} cells={miniCrabCells(p.frame, mood, rgbOf(p.look.done))} />
380 {p.crewButton}
381 {p.dismiss}
382 </Box>
383 )
384 if (p.waiting.length === 0) return bar
385
386 const more = p.waiting.length - BAND_AGENTS
387 return (
388 <Box flexDirection="column">
389 {bar}
390 {p.waiting.slice(0, BAND_AGENTS).map(a => bandAgent(ui, p, a))}
391 {more > 0 && <Text dimColor> +{more}</Text>}
392 </Box>
393 )
394}
395
396// --- the agents pane.
397
398export type PaneProps = {
399 title: string
400 running: AgentRun[]
401 finished: AgentRun[]
402 planned: Planned[]
403 totals: { active: number; session: number; tokens: number; time: number }
404 at: number
405 frame: number
406 columns: number
407 isCompact: boolean
408 isDoneCollapsed: boolean
409 toggleCompact: JSX.Element
410 toggleDone: JSX.Element
411 look: Look
412 // Finished runs whose card is open, and what a click on a card's title does.
413 expanded: string[]
414 toggleOpen: (id: string) => void
415}
416
417
418function tile(ui: Ui, key: string, label: string, value: string): JSX.Element {
419 const { Box, Text } = ui
420 return (
421 <Box key={key} flexDirection="column" flexGrow={1} borderStyle="round" borderColor="#3d3d44" paddingX={1}>
422 <Text dimColor>{label}</Text>
423 <Text bold>{value}</Text>
424 </Box>
425 )
426}
427
428function agentCard(ui: Ui, p: PaneProps, a: AgentRun): JSX.Element {
429 const { Box, Text, Raster } = ui
430 const { look } = p
431 const tier = look.tierOf(a.type)
432 const costume = look.costumeOf(a.type)
433 const tint = look.colorOf(tier === 'other' && costume === 'explore' ? 'medium' : tier)
434 const status = STATUS[a.status] ?? STATUS.running!
435 const model = a.effort ? `${look.modelName(a.model)} · ${a.effort}` : look.modelName(a.model)
436 const steps = a.stepTotal ? `${a.stepDone ?? 0}/${a.stepTotal}${a.stepNote ? ' · ' + a.stepNote : ''}` : ''
437 const stats = `ctx ${look.ctxOf(a)}% · ${look.fmtTokens(a.contextTokens)} ≈${look.fmtCost(a.costUsd)} ${look.fmtTime(look.elapsed(a, p.at))}`
438 const lineW = Math.max(10, p.columns - CRAB_COLS - 5)
439 const crab = cardCrabCells(costume, tint, a.status, p.frame, partyFrame(a.endedAt, p.at), look.done)
440 const isOpen = isFinished(a) && p.expanded.includes(a.id)
441
442 return (
443 <Box key={a.id} flexDirection="row" gap={2} marginBottom={1}>
444 <Raster key={`crab-${a.id}`} columns={CRAB_COLS} rows={CRAB_ROWS} cells={crab} />
445 <Box flexDirection="column" flexGrow={1}>
446 <Box flexDirection="row" justifyContent="space-between">
447 {cardTitle(ui, a, isOpen, lineW - 2, () => p.toggleOpen(a.id))}
448 <Text color={status.color}>{status.glyph}</Text>
449 </Box>
450 <Text wrap="truncate-end">
451 <Text color={tint}>{tier === 'other' ? a.type : tier}</Text>
452 <Text dimColor> {model}</Text>
453 </Text>
454 <Box flexDirection="row" justifyContent="space-between">
455 <Text wrap="truncate-end">{steps}</Text>
456 <Text dimColor>{stats}</Text>
457 </Box>
458 <Raster key={`line-${a.id}`} columns={lineW} rows={1} cells={lineCells(lineW, look.progressOf(a), look.ctxOf(a), rgbOf(tint))} />
459 {isOpen && digestBlock(ui, a, lineW, look.s.noReport ?? 'No report yet')}
460 </Box>
461 </Box>
462 )
463}
464
465function plannedCard(ui: Ui, p: PaneProps, pl: Planned): JSX.Element {
466 const { Box, Text, Raster } = ui
467 const { look } = p
468 const tier = pl.tier in look.tierColor ? pl.tier : 'other'
469 const tint = look.colorOf(tier)
470
471 return (
472 <Box key={`plan-${pl.n}`} flexDirection="row" gap={2} marginBottom={1}>
473 <Raster key={`crab-plan-${pl.n}`} columns={CRAB_COLS} rows={CRAB_ROWS} cells={crabCells(tier, tint, 0, true)} />
474 <Box flexDirection="column" flexGrow={1}>
475 <Box flexDirection="row" justifyContent="space-between">
476 <Text bold dimColor wrap="truncate-end">
477 {pl.n}. {pl.title}
478 </Text>
479 <Text dimColor>◷</Text>
480 </Box>
481 <Text wrap="truncate-end">
482 <Text color={tint}>{tier}</Text>
483 <Text dimColor>
484 {' '}
485 {look.tierModel[tier] ?? ''}
486 {pl.after.length ? ` · ${look.s.after} ${pl.after.join(', ')}` : ''}
487 </Text>
488 </Text>
489 </Box>
490 </Box>
491 )
492}
493
494// The rows the inline pane needs to show every card, so the last agent is not
495// cut off by the default third of the screen. `open` is the rows the open
496// finished cards add (digestRows).
497export function paneRows(p: { title: string; running: number; finished: number; planned: number; isCompact: boolean; isDoneCollapsed: boolean; open?: number }): number {
498 const header = (p.title !== '' ? 1 : 0) + 3 + 1
499 if (p.isCompact) return header + 1
500 const cards = (n: number, size: number) => (n > 0 ? 1 + n * size : 0)
501 const finished = p.finished > 0 ? 1 + (p.isDoneCollapsed ? 0 : p.finished * 5 + (p.open ?? 0)) : 0
502 return header + 1 + Math.max(1, cards(p.running, 5) + finished + cards(p.planned, 3))
503}
504
505export function terminalPane(ui: Ui, p: PaneProps): JSX.Element {
506 const { Box, Text } = ui
507 const { look } = p
508 const s = look.s
509 const isEmpty = p.running.length + p.finished.length + p.planned.length === 0
510
511 const header = (
512 <Box flexDirection="column">
513 {p.title !== '' && <Text bold>{p.title}</Text>}
514 <Box flexDirection="row" gap={1}>
515 {tile(ui, 'active', s.active ?? 'Active', `≈${look.fmtCost(p.totals.active)}`)}
516 {tile(ui, 'session', s.session ?? 'Session', look.fmtCost(p.totals.session))}
517 {tile(ui, 'tokens', s.tokens ?? 'Tokens', look.fmtTokens(p.totals.tokens))}
518 {tile(ui, 'time', s.time ?? 'Time', look.fmtTime(p.totals.time))}
519 </Box>
520 {p.toggleCompact}
521 </Box>
522 )
523
524 if (p.isCompact) {
525 return (
526 <Box flexDirection="column">
527 {header}
528 <Text wrap="truncate-end">
529 {[...p.running, ...p.finished].map(a => (
530 <Text key={a.id} color={look.colorOf(look.tierOf(a.type))}>
531 {(STATUS[a.status] ?? STATUS.running!).glyph}{' '}
532 </Text>
533 ))}
534 {p.planned.map(pl => (
535 <Text key={`plan-${pl.n}`} dimColor>
536 ◷{' '}
537 </Text>
538 ))}
539 </Text>
540 </Box>
541 )
542 }
543
544 return (
545 <Box flexDirection="column">
546 {header}
547 <Box flexDirection="column" marginTop={1}>
548 {isEmpty && <Text dimColor>{s.empty}</Text>}
549 {p.running.length > 0 && <Text dimColor>{s.running} · {p.running.length}</Text>}
550 {p.running.map(a => agentCard(ui, p, a))}
551 {p.finished.length > 0 && p.toggleDone}
552 {!p.isDoneCollapsed && p.finished.map(a => agentCard(ui, p, a))}
553 {p.planned.length > 0 && <Text dimColor>{s.planned} · {p.planned.length}</Text>}
554 {p.planned.map(pl => plannedCard(ui, p, pl))}
555 </Box>
556 </Box>
557 )
558}
559hooks/sprites.ts 84 lines1// Pixel crab sprites, shared by the desktop SVG drawing and the terminal raster.
2
3// Pixel Clawd from DockCrab (Clawdy): a 24×18 crab on a 30×28 grid, one costume per tier.
4// The body keeps the brand clay; the tier's color lives in the costume's accent.
5export const CLAY = '#D97757'
6export const INK = '#1F1E1D'
7
8// `cls` puts a pixel in a named group: `bd` (the default) is the body and its
9// costume, `la`/`lb` the leg pairs, anything else a prop with its own motion.
10export type Fill = (x: number, y: number, w: number, h: number, c: string, cls?: string) => void
11
12export const stamp = (f: Fill, x: number, y: number, rows: string[], map: Record<string, string>, cls?: string): void =>
13 rows.forEach((row, dy) => [...row].forEach((ch, dx) => map[ch] && f(x + dx, y + dy, 1, 1, map[ch] ?? '', cls)))
14
15// `armCls` lets a raised claw travel with the prop it holds; `armBack` and
16// `backCls` do the same for the far claw.
17export const crabBody = (f: Fill, armFront = 0, armCls?: string, armBack = 0, backCls?: string): void => {
18 f(7, 10, 16, 12, CLAY)
19 f(3, 14 + armBack, 4, 4, CLAY, backCls)
20 f(23, 14 + armFront, 4, 4, CLAY, armCls)
21 f(9, 12, 2, 2, INK)
22 f(19, 12, 2, 2, INK)
23 f(7, 22, 2, 4, CLAY, 'la')
24 f(17, 22, 2, 4, CLAY, 'la')
25 f(11, 22, 2, 4, CLAY, 'lb')
26 f(21, 22, 2, 4, CLAY, 'lb')
27}
28
29export const COSTUMES: Record<string, (f: Fill, t: string) => void> = {
30 // Fable: astronaut in a glass dome; floats instead of walking, the antenna and the star blink.
31 fable: (f, t) => {
32 crabBody(f)
33 f(6, 7, 18, 1, '#E6E8EE'); f(5, 8, 1, 14, '#E6E8EE'); f(24, 8, 1, 14, '#E6E8EE'); f(6, 22, 18, 1, '#C9CCD2')
34 f(6, 8, 18, 14, 'rgba(169,214,245,.32)'); f(8, 9, 2, 1, '#fff'); f(8, 10, 1, 2, '#fff')
35 f(14, 4, 2, 3, '#C9CCD2'); f(14, 2, 2, 2, t, 'ant'); f(13, 18, 4, 2, t)
36 f(27, 3, 1, 3, '#F5C542', 'star'); f(26, 4, 3, 1, '#F5C542', 'star')
37 },
38 // Heavy: detective with a deerstalker; the magnifier sweeps and glints.
39 heavy: (f, t) => {
40 crabBody(f, -4, 'it')
41 stamp(f, 6, 3, ['......bbbbbb......', '....bbcbbcbbbb....', '...bbbbbbbbbbbb...', '..bcbbcbbcbbcbbb..', '.bbbbbbbbbbbbbbbb.', 'dddddddddddddddddd'], { b: '#7A4A26', c: '#A0703F', d: '#5A3519' })
42 f(6, 9, 18, 1, t)
43 stamp(f, 23, 1, ['.kkk.', 'k...k', 'k...k', 'k...k', '.kkk.'], { k: '#3A3A3C' }, 'it')
44 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')
45 },
46 // Careful: engineer in a hard hat; the wrench turns a bolt.
47 careful: (f, t) => {
48 crabBody(f)
49 stamp(f, 6, 4, ['.....yyyyyyyy.....', '...yyyyyhhyyyyy...', '..yyyyyyhhyyyyyy..', '..yyyyyyhhyyyyyy..', '.yyyyyyyhhyyyyyyy.', 'dddddddddddddddddd'], { y: '#F5C542', h: '#FBE08A', d: '#C99A1E' })
50 f(13, 5, 4, 2, t)
51 stamp(f, 0, 10, ['.s.s', 'sss.', '.s..', '.s..'], { s: '#8E929A' }, 'it')
52 },
53 // Medium: chef, the toque traced from DockCrab's Sprites.chefHat; tosses the omelette.
54 medium: (f, t) => {
55 crabBody(f, -4, 'pan')
56 stamp(f, 6, 0, ['........lll.......', '.......lllll......', '.wwwwgwwwwwwgwwwww', 'wwwwwwwwwwwwwwwwww', 'wwwwwwwwwwwwwwwwww', 'wwwwwgwwwwwggwwwww', '.wwwwgwwwwwggwwwww', '.dddbbbbbbbbbbbbb.', '.dddbbbbbbbbbbbbb.', '.dddbbbbbbbbbbbbb.'], { w: '#F4F3EE', l: '#F7F6F2', g: '#D2D1C8', b: t, d: '#B45F43' })
57 f(22, 8, 7, 2, '#4A4A48', 'pan'); f(26, 10, 1, 1, '#4A4A48', 'pan'); f(24, 7, 3, 1, '#F5B731', 'egg')
58 },
59 // Light: racer in a helmet; runs at double pace, the checkered flag flutters.
60 light: (f, t) => {
61 crabBody(f, -4)
62 stamp(f, 6, 5, ['....rrrrrrrrrr....', '..rrrrrrwwrrrrrr..', '.rrrrrrrwwrrrrrrr.', '.rrrrrrrwwrrrrrrr.', '.rrrrrrrwwrrrrrrr.', '.kkkkkkkkkkkkkkkkr'], { r: t, w: '#F8F6F1', k: INK })
63 f(25, 1, 1, 9, '#8E929A')
64 stamp(f, 26, 1, ['wkwk', 'kwkw', 'wkwk'], { w: '#F8F6F1', k: INK }, 'flag')
65 },
66 // Explore: pirate scouting the code; the cutlass fences.
67 explore: f => {
68 crabBody(f)
69 stamp(f, 5, 3, ['.kk..............kk.', '.kkk....kkkk....kkk.', '..kkkkkkkwwkkkkkkk..', '..kkkkkkkkkkkkkkkk..', '.gggggggggggggggggg.'], { k: '#55514C', w: '#F8F6F1', g: '#F5C542' })
70 f(7, 11, 11, 1, INK); f(18, 11, 4, 3, INK)
71 f(27, 6, 1, 9, '#C9CCD2', 'it'); f(26, 15, 3, 1, '#7A4A26', 'it')
72 },
73 other: f => crabBody(f),
74}
75
76// Done: the work is in. The near claw plants a flag in the tier's color, the far
77// claw is raised to wave (`wv`) and the pennant flutters (`fl`). The drawing
78// swaps the clay for the done green.
79export const doneCrab = (f: Fill, t: string): void => {
80 crabBody(f, 0, undefined, -4, 'wv')
81 f(27, 2, 1, 20, '#C9CCD2')
82 stamp(f, 21, 2, ['....tt', '..tttt', 'tttttt', '..tttt', '....tt'], { t }, 'fl')
83}
84types/index.d.ts 66 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 /** The run's final answer, capped; what its digest is cut from. */
42 report?: string
43 /** Sent with the worker's last `step`; each wins over the report. */
44 summary?: string
45 followUp?: string
46}
47
48export type Panel = {
49 isCompact: boolean
50 isDoneCollapsed: boolean
51 autoOpenedFor: string
52 /** Finished runs whose card is open to show its digest. */
53 expanded: string[]
54}
55
56declare module 'claude-code' {
57 interface PluginState {
58 'savvy-progress': {
59 flow: Flow | null
60 agents: AgentRun[]
61 panel: Panel
62 now: number
63 }
64 }
65}
66