Holds risky tool calls (production domains, live Stripe keys, protected-branch pushes, deploys, destructive commands) for your OK, replays each turn's edits…

A Claude Code mod that keeps an eye on what Claude does for you. One plugin, five features:
vercel --prod, terraform apply, cdk deploy, kubectl apply, docker push).rm -r/-f, git reset --hard, git checkout -- ., git restore ., git clean, force pushes, database migrations) and shows what they would delete or change before you decide.Read · src/api/routes.ts, step and tool counts). The panel opens by itself when a second subagent starts in a turn, has a compact one-line-per-subagent view, and can warn you when subagents pass a cost budget. Details › on any subagent shows everything about it: its full task, model and effort, what it is doing now, tokens and cost by kind, context size, a timeline of its tool calls (✓ ok, ✗ error, ⏸ held), tools used, files changed and read, commands run, its latest message or final report (with Copy buttons), and how it runs (background, fork, parent, folder, permissions)./code-buddy control. A paused feature shows in the band with a Resume button, and timed pauses end by themselves.It draws in the terminal and in the Claude desktop app's Code tab, in light and dark mode.
<img alt="Code Buddy's hold pane, replay stepper, agents panel and status band" src="docs/preview-light.png" width="720">
In a Claude Code terminal session:
/plugin install code-buddy --marketplace RuahTechSolutions/code-buddy
Answer y to add the marketplace, pick a scope (user scope loads it everywhere, including the desktop app's Code tab), and fill in the settings screen. You can change any setting later with /code-buddy config.
| Setting | What it does | Default |
|---|---|---|
| Production domains | Comma-separated hosts. *.example.com matches every subdomain. Shell commands, web requests and browser calls that target one are held. | empty (rule off) |
| Staging domains | Hosts that are let through. Production wins on overlap: only an exact host listed here (no wildcard) is let through. | empty |
| Protected branch | Pushes to it and merges into it are held. Comma-separated; * matches within a name. | main |
| Staging guard | Feature 1 on or off in every session. | on |
| Blast radius | Feature 2 on or off in every session. | on |
| Replay | Feature 3 on or off in every session. | on |
| Agents panel | Feature 4 on or off in every session. | on |
| Holds (master switch) | Off turns off both hold features at once (the older guard setting). | on |
| Subagent budget | Estimated subagent spend per session, in USD. Past it you get one toast, and the agents bar, the panel's budget tile and the idle band turn coral. 0 or off turns it off. | off |
| Auto-open agents panel | Opens the agents panel by itself when a second subagent starts in a turn, once per turn, so closing it sticks. | on |
/code-buddy config production example.com, *.example.com
/code-buddy config staging staging.example.com
/code-buddy config branch main, release/*
/code-buddy config guard off
/code-buddy config budget 2.50
/code-buddy config autoopen off
/code-buddy config blast off
Every setting can also be changed in the control panel (/code-buddy control): edit a field and press Enter.
| Command | What it does |
|---|---|
/code-buddy | Status, settings, and this session's held calls with their outcomes. |
/code-buddy:code-buddy | The same command, from the plugin's command file. The desktop app's / menu lists this one before a session has started; it answers exactly like /code-buddy. |
/code-buddy replay | Opens the replay of the last turn's edits. |
/code-buddy agents | Opens or closes the agents panel (also the band's Agents button, hotkey a). Inside it, Compact / Expand (hotkey x) switches between full rows and one line per subagent. |
/code-buddy config | Shows the settings, or changes one. |
/code-buddy control | Opens the control panel (also /code-buddy settings, and /code-buddy pause with nothing after it). |
/code-buddy pause <feature> [time] | Pauses guard, blast, replay, agents or all for this session: 30m, 2h, 90s, or until resumed. |
/code-buddy resume [feature] | Resumes one feature, or everything paused. |
claude -p).One band, shared by all four features, shows the most important thing first: a waiting hold, then the agents progress bar, then the replay hint, then Code Buddy · guard on · N held.
git status, git log, git clean -n and du. Migrations are listed from files on disk, never by connecting to the database.secret=/token= values show only their first 8 characters, on screen and in anything stored.git clone https://github.com/RuahTechSolutions/code-buddy
claude --plugin-dir ./code-buddy
claude plugin test ./code-buddy runs the tests (125 across 9 files).claude plugin validate ./code-buddy checks the manifest, the marketplace file and the hooks module.The plugin is a Claude Code function-hooks module: hooks/register.tsx is the only file that calls the engine. guard.ts, blast.ts, diff.ts and mask.ts are pure logic. features.ts handles pauses. hold.tsx, replay.tsx, agents.tsx, detail.tsx, control.tsx and theme.ts draw.
Apache License 2.0; see LICENSE. Code Buddy adapts code and ideas from blast-radius and replay-theater (Apache-2.0, Anthropic PBC) and savvy-progress (MIT). See NOTICE for what was adapted and where.
Made by Ruah Tech Solutions. Powered by www.Ruah.ai.
hooks/register.tsx 957 lines1// Code Buddy: one plugin, four features.
2// 1. Staging guard (guard.ts) holds calls that reach production
3// 2. Blast radius (blast.ts) holds destructive shell commands
4// 3. Replay (replay.tsx, diff.ts) steps through a turn's edits
5// 4. Agents panel (agents.tsx) tracks every subagent
6// Features 1 and 2 share the hold pane (hold.tsx); all four share the band.
7// Only this file calls the engine (`$`); the others are pure logic and drawing.
8// No network requests, no model calls, no environment variables.
9
10import type { EngineInterface, Register } from 'claude-code'
11
12import type { AgentDetail, AgentRun, AgentsUi, HeldRecord, Pauses, HoldOutcome, HoldView, Replay, ReplayStep } from '../types'
13import {
14 AGENTS_PANE,
15 activityOf,
16 agentsConfigOf,
17 agentsPaneArgs,
18 agentsRows,
19 barRuns,
20 budgetOf,
21 costOf,
22 costParts,
23 drawAgents,
24 drawAgentsBand,
25 fmtUsd,
26 parseBudget,
27 tokensOf,
28} from './agents'
29import type { AgentsConfig, Usage } from './agents'
30import { inspectBlast, looksDestructive, merge } from './blast'
31import { drawAgentDetail, newDetail, onFinish, onStep, onToolEnd, onToolStart } from './detail'
32import { applyEdits, buildStep, relPath } from './diff'
33import { CONTROL_PANE, controlRows, drawControl } from './control'
34import type { SettingField } from './control'
35import { FEATURES, durText, enabledOf, expire, featureOf, isPaused, leftText, nameOf, parseDuration } from './features'
36import type { Feature } from './features'
37import { configOf, inspectGuard, looksRisky, parseList } from './guard'
38import type { Finding, GuardConfig, Io } from './guard'
39import { HOLD_LIMIT_MS, HOLD_PANE, OUTCOME_LABEL, POLL_SECONDS, drawHold, drawHoldBand, drawIdleBand, paneRows, pending, refusal } from './hold'
40import type { Pending } from './hold'
41import { mask } from './mask'
42import { REPLAY_PANE, drawReplay, drawReplayBand, replayRows } from './replay'
43
44const COMMAND = 'code-buddy'
45const QUEUE = { plugin: 'code-buddy', key: 'queue' } as const
46const LOG = { plugin: 'code-buddy', key: 'log' } as const
47const RECORDING = { plugin: 'code-buddy', key: 'recording' } as const
48const REPLAY = { plugin: 'code-buddy', key: 'replay' } as const
49const AGENTS = { plugin: 'code-buddy', key: 'agents' } as const
50const BATCH = { plugin: 'code-buddy', key: 'batch' } as const
51const AGENTS_UI = { plugin: 'code-buddy', key: 'agentsUi' } as const
52const DETAILS = { plugin: 'code-buddy', key: 'details' } as const
53const SEEN = { plugin: 'code-buddy', key: 'seenSurface' } as const
54const PAUSES = { plugin: 'code-buddy', key: 'pauses' } as const
55const UI_DEFAULT: AgentsUi = { isCompact: false, autoOpenedBatch: -1, budgetAlertedAt: 0 }
56
57const EDIT_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
58const MAX_STEPS = 100
59
60const CONFIG_FIELDS: Record<string, { key: string; label: string }> = {
61 production: { key: 'productionDomains', label: 'Production domains' },
62 staging: { key: 'stagingDomains', label: 'Staging domains' },
63 branch: { key: 'protectedBranch', label: 'Protected branch' },
64 guard: { key: 'guard', label: 'Guard' },
65 budget: { key: 'agentBudgetUsd', label: 'Subagent budget' },
66 autoopen: { key: 'autoOpenAgents', label: 'Auto-open agents panel' },
67 stagingguard: { key: 'stagingGuard', label: 'Staging guard' },
68 blast: { key: 'blastRadius', label: 'Blast radius' },
69 replay: { key: 'replay', label: 'Replay' },
70 agents: { key: 'agentsPanel', label: 'Agents panel' },
71}
72
73const ago = (ms: number): string => {
74 const s = Math.max(0, Math.round(ms / 1000))
75 if (s < 60) return `${s}s ago`
76 if (s < 3600) return `${Math.round(s / 60)} min ago`
77 return `${Math.round(s / 3600)} h ago`
78}
79
80let serial = 0
81// Whether anyone could ever answer a hold: a REPL session, or one some surface has
82// drawn Code Buddy on (the desktop app attaches its window after the session starts).
83let isInteractive = false
84let hasDrawn = false
85// Whether `seenSurface` is already written, so the tick doesn't read it every second.
86let isSeenSaved = false
87
88/**
89 * Remembers in session state, which outlives a reload of this module, that a
90 * window has been attached: a hold then waits for an answer instead of refusing.
91 */
92async function markSeen($: EngineInterface): Promise<void> {
93 if (isSeenSaved) return
94 if ((await $.state.get(SEEN)).value !== true) await $.state.set(SEEN, true)
95 isSeenSaved = true
96}
97
98// ---- Engine access (every `$` call lives in this file) ----------------------
99
100/** What guard.ts may read: the session folder, local commands, folder listings. */
101function ioOf($: EngineInterface): Io {
102 return {
103 cwd: () => $.session.cwd(),
104 run: async (argv, cwd, timeoutMs) => {
105 try {
106 const r = await $.process.run(argv, { cwd, timeoutMs })
107 return { exitCode: r.exitCode, stdout: r.stdout }
108 } catch {
109 return null
110 }
111 },
112 list: async dir => {
113 try {
114 return (await $.fs.list(dir)).map(f => f.name)
115 } catch {
116 return []
117 }
118 },
119 }
120}
121
122async function readLog($: EngineInterface): Promise<HeldRecord[]> {
123 return (await $.state.get(LOG)).value ?? []
124}
125
126/** Writes the log with read-modify-write, again on a lost race. */
127async function writeLog($: EngineInterface, change: (list: HeldRecord[]) => HeldRecord[]): Promise<void> {
128 for (let tries = 0; tries < 5; tries += 1) {
129 const now = await $.state.get(LOG)
130 const done = await $.state.set(LOG, change(now.value ?? []), { ifVersion: now.version })
131 if (done.isSet) return
132 }
133}
134
135async function record($: EngineInterface, view: HoldView, outcome: HoldOutcome, at: number): Promise<void> {
136 await writeLog($, list => {
137 const row: HeldRecord = { id: view.id, at, tool: view.tool, rules: view.rules, command: view.command, outcome }
138 return list.some(r => r.id === view.id) ? list.map(r => (r.id === view.id ? row : r)) : [...list, row].slice(-200)
139 })
140}
141
142async function publish($: EngineInterface): Promise<void> {
143 await $.state.set(QUEUE, pending.map(p => p.view))
144}
145
146async function pause($: EngineInterface): Promise<void> {
147 await $.process.run(['sleep', POLL_SECONDS], { timeoutMs: 5000 })
148}
149
150/**
151 * Holds the call until the person answers, one hold shown at a time. Resolves
152 * the outcome: `proceeded` runs the call, anything else refuses it.
153 */
154async function hold($: EngineInterface, signal: AbortSignal, tool: string, found: Finding, isSubagent: boolean): Promise<HoldOutcome> {
155 serial += 1
156 const heldAt = await $.clock.now()
157 const view: HoldView = { id: `h${heldAt}-${serial}`, tool, rules: found.rules, command: found.command, affects: found.affects, isSubagent }
158
159 // Nobody could ever answer (a -p run, an SDK session no surface ever drew): refuse at
160 // once. A desktop window that is only detached for now gets the usual 10 minutes.
161 const surfaces = await $.session.surfaces()
162 if (surfaces.length > 0 || hasDrawn) await markSeen($)
163 else if (!isInteractive && (await $.state.get(SEEN)).value !== true) {
164 await record($, view, 'no-one', heldAt)
165 return 'no-one'
166 }
167
168 const mine: Pending = { view, decision: null }
169 pending.push(mine)
170 let outcome: HoldOutcome = 'error'
171 try {
172 await record($, view, 'waiting', heldAt)
173 await publish($)
174
175 while (pending[0] !== mine) {
176 if (signal.aborted) {
177 outcome = 'interrupted'
178 return outcome
179 }
180 await pause($)
181 }
182
183 await $.ui.open({ id: HOLD_PANE, title: 'Code Buddy · held', focus: true, rows: paneRows(view) })
184 $.ui.invalidate('ui.render')
185 const shownAt = await $.clock.now()
186 for (;;) {
187 if (mine.decision !== null) {
188 outcome = mine.decision === 'proceed' ? 'proceeded' : 'cancelled'
189 break
190 }
191 if (signal.aborted) {
192 outcome = 'interrupted'
193 break
194 }
195 if ((await $.clock.now()) - shownAt >= HOLD_LIMIT_MS) {
196 outcome = 'timeout'
197 break
198 }
199 await pause($)
200 }
201 return outcome
202 } catch {
203 outcome = 'error' // anything unexpected refuses the call
204 return outcome
205 } finally {
206 const i = pending.indexOf(mine)
207 if (i >= 0) pending.splice(i, 1)
208 try {
209 if (pending.length === 0) await $.ui.close({ id: HOLD_PANE })
210 await publish($)
211 await record($, view, outcome, heldAt)
212 } catch {
213 // the pane is already gone
214 }
215 $.ui.invalidate('ui.render')
216 }
217}
218
219// ---- Replay (feature 3) -------------------------------------------------------
220
221/** The step an edit makes: the file's text before, the edit applied. Null when not an edit. */
222async function stepFor($: EngineInterface, e: Record<string, unknown>): Promise<ReplayStep | null> {
223 const tool = String(e.tool)
224 const path = String(e.file_path ?? e.notebook_path ?? '')
225 if (!EDIT_TOOLS.has(tool) || !path) return null
226 let before = ''
227 let isNew = true
228 try {
229 if (await $.fs.exists(path)) {
230 before = await $.fs.read(path)
231 isNew = false
232 }
233 } catch {
234 // unreadable: shown as a new file
235 }
236 const file = relPath(await $.session.cwd(), path)
237 if (tool === 'Write') return buildStep(file, tool, isNew ? '' : 'rewrite', before, String(e.content ?? ''), isNew)
238 if (tool === 'NotebookEdit') return buildStep(file, tool, `cell ${String(e.edit_mode ?? 'replace')}`, '', String(e.new_source ?? ''), false)
239 const edits = tool === 'MultiEdit' && Array.isArray(e.edits) ? (e.edits as Record<string, unknown>[]) : [e]
240 const after = applyEdits(before, edits)
241 if (after === null) return null
242 const note = tool === 'MultiEdit' ? `${edits.length} edits` : e.replace_all === true ? 'replace all' : ''
243 return buildStep(file, tool, note, before, after, isNew)
244}
245
246async function recordStep($: EngineInterface, step: ReplayStep): Promise<void> {
247 for (let tries = 0; tries < 5; tries += 1) {
248 const now = await $.state.get(RECORDING)
249 const done = await $.state.set(RECORDING, [...(now.value ?? []), step].slice(-MAX_STEPS), { ifVersion: now.version })
250 if (done.isSet) return
251 }
252}
253
254/** Opens the replay pane on step 1; false when there is nothing to replay. */
255async function openReplay($: EngineInterface): Promise<boolean> {
256 const r = (await $.state.get(REPLAY)).value
257 if (!r || r.steps.length === 0) return false
258 await $.state.set(REPLAY, { ...r, index: 0, isSeen: true })
259 await $.ui.open({ id: REPLAY_PANE, title: 'Code Buddy · replay', focus: true, closeOnEscape: true, rows: replayRows(r) })
260 return true
261}
262
263async function goToStep($: EngineInterface, index: number): Promise<void> {
264 const r = (await $.state.get(REPLAY)).value
265 if (!r) return
266 await $.state.set(REPLAY, { ...r, index: Math.max(0, Math.min(index, r.steps.length - 1)) })
267}
268
269// ---- Agents (feature 4) ---------------------------------------------------------
270
271/** Changes the list of runs with read-modify-write, again on a lost race. */
272async function writeAgents($: EngineInterface, change: (list: AgentRun[]) => AgentRun[]): Promise<void> {
273 for (let tries = 0; tries < 5; tries += 1) {
274 const now = await $.state.get(AGENTS)
275 const done = await $.state.set(AGENTS, change(now.value ?? []), { ifVersion: now.version })
276 if (done.isSet) return
277 }
278}
279
280/** Opens the agents panel, or closes it when it is up; true when it ends up open. */
281async function toggleAgents($: EngineInterface): Promise<boolean> {
282 if ((await $.ui.panes()).some(p => p.id === AGENTS_PANE)) {
283 await $.ui.close({ id: AGENTS_PANE })
284 return false
285 }
286 const n = ((await $.state.get(AGENTS)).value ?? []).length
287 await $.ui.open(agentsPaneArgs(agentsRows(n, (await readUi($)).isCompact)))
288 return true
289}
290
291async function readUi($: EngineInterface): Promise<AgentsUi> {
292 return { ...UI_DEFAULT, ...((await $.state.get(AGENTS_UI)).value ?? {}) }
293}
294
295/** Full rows or one line each; the open pane is resized to match. */
296async function toggleCompact($: EngineInterface): Promise<void> {
297 const ui = await readUi($)
298 await $.state.set(AGENTS_UI, { ...ui, isCompact: !ui.isCompact })
299 if ((await $.ui.panes()).some(p => p.id === AGENTS_PANE)) {
300 const n = ((await $.state.get(AGENTS)).value ?? []).length
301 await $.ui.open(agentsPaneArgs(agentsRows(n, !ui.isCompact)))
302 }
303}
304
305/** Opens the panel by itself once a turn has two subagents; once per turn, so a close sticks. */
306async function maybeAutoOpen($: EngineInterface, batch: number): Promise<void> {
307 const list = (await $.state.get(AGENTS)).value ?? []
308 if (list.filter(a => a.batch === batch).length < 2) return
309 const ui = await readUi($)
310 if (ui.autoOpenedBatch === batch) return
311 await $.state.set(AGENTS_UI, { ...ui, autoOpenedBatch: batch })
312 if ((await $.ui.panes()).some(p => p.id === AGENTS_PANE)) return
313 await $.ui.open(agentsPaneArgs(agentsRows(list.length, ui.isCompact)))
314}
315
316/** A subagent's tool call: what it is doing now, and one more tool. */
317async function noteActivity($: EngineInterface, agentId: string, activity: string): Promise<void> {
318 await writeAgents($, list => list.map(a => (a.agentId === agentId && a.status === 'running' ? { ...a, activity, tools: (a.tools ?? 0) + 1 } : a)))
319}
320
321/** Changes one subagent's detail record, again on a lost race; nothing when it has none. */
322async function writeDetail($: EngineInterface, id: string, change: (d: AgentDetail) => AgentDetail): Promise<void> {
323 for (let tries = 0; tries < 5; tries += 1) {
324 const cur = await $.state.get({ ...DETAILS, id })
325 if (!cur.value) return
326 const done = await $.state.set({ ...DETAILS, id }, change(cur.value), { ifVersion: cur.version })
327 if (done.isSet) return
328 }
329}
330
331let entrySerial = 0
332
333/** A subagent's tool call starts: its timeline entry. Returns the entry's id ('' when not recorded). */
334async function startDetailEntry($: EngineInterface, agentId: string, input: Record<string, unknown>): Promise<string> {
335 try {
336 const at = await $.clock.now()
337 entrySerial += 1
338 const id = `${at}-${entrySerial}`
339 const cwd = await $.session.cwd()
340 await writeDetail($, agentId, d => onToolStart(d, input, cwd, id, at))
341 return id
342 } catch {
343 return ''
344 }
345}
346
347/** It ended: ok, an error, or held by Code Buddy. */
348async function endDetailEntry($: EngineInterface, agentId: string, input: Record<string, unknown>, entryId: string, ran: { deny?: string; isError?: boolean }): Promise<void> {
349 try {
350 const status = ran.deny !== undefined ? (ran.deny.startsWith('Code Buddy') ? 'held' : 'error') : ran.isError === true ? 'error' : 'ok'
351 const at = await $.clock.now()
352 const cwd = await $.session.cwd()
353 await writeDetail($, agentId, d => onToolEnd(d, input, cwd, entryId, status, at))
354 } catch {
355 // details must never fail a call
356 }
357}
358
359/** Shows one subagent's details in the panel, or the list again (undefined). */
360async function selectAgent($: EngineInterface, id: string | undefined): Promise<void> {
361 const ui = await readUi($)
362 await $.state.set(AGENTS_UI, { ...ui, selected: id })
363 if (id !== undefined && (await $.ui.panes()).some(p => p.id === AGENTS_PANE)) await $.ui.open(agentsPaneArgs(34))
364}
365
366async function copyText($: EngineInterface, text: string, surface: 'terminal' | 'desktop' | 'mobile' | 'vscode'): Promise<void> {
367 const done = await $.ui.copy({ text, surface })
368 $.ui.toast(done.isCopied ? 'Code Buddy: copied' : 'Code Buddy: could not copy here')
369}
370
371/** One toast when the session's subagents pass the budget (again only if the budget changes). */
372async function checkBudget($: EngineInterface, budget: number): Promise<void> {
373 if (budget <= 0) return
374 const b = budgetOf((await $.state.get(AGENTS)).value ?? [], budget)
375 if (!b?.isOver) return
376 const ui = await readUi($)
377 if (ui.budgetAlertedAt === budget) return
378 await $.state.set(AGENTS_UI, { ...ui, budgetAlertedAt: budget })
379 $.ui.toast(`Code Buddy: subagents have used ${b.used} this session, over your ${b.limit} budget.`, { timeoutMs: 8000 })
380}
381
382/** One model request of a subagent: its tokens and estimated cost. */
383async function addUsage($: EngineInterface, agentId: string, model: string, usage: Usage): Promise<void> {
384 await writeAgents($, list =>
385 list.map(a =>
386 a.agentId !== agentId
387 ? a
388 : { ...a, model: model || a.model, tokens: a.tokens + tokensOf(usage), costUsd: a.costUsd + costOf(model || a.model, usage), steps: a.steps + 1 },
389 ),
390 )
391}
392
393/** A subagent's turn ended: done, failed or stopped, with the turn's usage when no step was seen. */
394async function finishAgent($: EngineInterface, agentId: string, reason: string, usage: (Usage & { model?: string }) | undefined): Promise<void> {
395 const at = await $.clock.now()
396 const status: AgentRun['status'] = reason === 'answer' ? 'done' : reason === 'aborted' ? 'stopped' : 'failed'
397 await writeAgents($, list =>
398 list.map(a => {
399 if (a.agentId !== agentId || a.status !== 'running') return a
400 const model = usage?.model || a.model
401 const fallback = a.steps === 0 && usage ? { model, tokens: tokensOf(usage), costUsd: costOf(model, usage) } : {}
402 return { ...a, ...fallback, status, endedAt: at, activity: undefined }
403 }),
404 )
405}
406
407// ---- Feature 5: pausing features and the control panel ---------------------------
408
409let version = ''
410
411async function readVersion($: EngineInterface): Promise<string> {
412 try {
413 const text = await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)
414 return String((JSON.parse(text) as { version?: unknown }).version ?? '')
415 } catch {
416 return ''
417 }
418}
419
420async function pausesOf($: EngineInterface): Promise<Pauses> {
421 return (await $.state.get(PAUSES)).value ?? {}
422}
423
424/** On in the settings and not paused right now. */
425async function isActive($: EngineInterface, enabled: Record<Feature, boolean>, f: Feature): Promise<boolean> {
426 if (!enabled[f]) return false
427 const p = await pausesOf($)
428 return p[f] === undefined || !isPaused(p, f, await $.clock.now())
429}
430
431async function writePauses($: EngineInterface, change: (p: Pauses) => Pauses): Promise<void> {
432 for (let tries = 0; tries < 5; tries += 1) {
433 const cur = await $.state.get(PAUSES)
434 const done = await $.state.set(PAUSES, change(cur.value ?? {}), { ifVersion: cur.version })
435 if (done.isSet) return
436 }
437}
438
439/** Pauses one feature, or every one that is on, for `ms` (0: until resumed). */
440async function pauseFeature($: EngineInterface, f: Feature | 'all', ms: number, enabled: Record<Feature, boolean>): Promise<string> {
441 const ids = f === 'all' ? FEATURES.map(x => x.id).filter(id => enabled[id]) : [f]
442 const until = ms > 0 ? (await $.clock.now()) + ms : 0
443 await writePauses($, p => {
444 const next: Pauses = { ...p }
445 for (const id of ids) next[id] = until
446 return next
447 })
448 $.ui.invalidate('ui.render')
449 const what = f === 'all' ? 'All features' : nameOf(f)
450 const text = `Code Buddy: ${what} paused ${ms > 0 ? `for ${durText(ms)}` : 'until you resume'}. /code-buddy resume${f === 'all' ? '' : ` ${f}`} brings ${f === 'all' ? 'them' : 'it'} back.`
451 $.ui.toast(text)
452 return text
453}
454
455async function resumeFeature($: EngineInterface, f: Feature | 'all'): Promise<string> {
456 const before = await pausesOf($)
457 const ids = f === 'all' ? (Object.keys(before) as Feature[]) : [f]
458 await writePauses($, p => {
459 const next: Pauses = { ...p }
460 for (const id of ids) delete next[id]
461 return next
462 })
463 $.ui.invalidate('ui.render')
464 const was = ids.filter(id => before[id] !== undefined)
465 const text = was.length ? `Code Buddy: ${was.map(nameOf).join(', ')} resumed.` : `Code Buddy: ${f === 'all' ? 'nothing was' : `${nameOf(f)} wasn't`} paused.`
466 $.ui.toast(text)
467 return text
468}
469
470/** Turns a feature on or off in the settings, for every session. */
471async function setFeatureOn($: EngineInterface, f: Feature, on: boolean, options: Record<string, unknown>): Promise<string> {
472 const key = FEATURES.find(x => x.id === f)?.key
473 if (!key) return ''
474 if (on && (f === 'guard' || f === 'blast') && options.guard === false) await $.config.set({ key: 'code-buddy.guard', value: true })
475 const done = await $.config.set({ key: `code-buddy.${key}`, value: on })
476 const text = 'deny' in done && done.deny !== undefined ? `Couldn't change ${nameOf(f)}: ${done.deny}` : `Code Buddy: ${nameOf(f)} turned ${on ? 'on' : 'off'} for every session.`
477 $.ui.toast(text)
478 return text
479}
480
481const SETTING_KEYS: Record<SettingField, { key: string; label: string }> = {
482 production: { key: 'productionDomains', label: 'Production domains' },
483 staging: { key: 'stagingDomains', label: 'Staging domains' },
484 branch: { key: 'protectedBranch', label: 'Protected branch' },
485 budget: { key: 'agentBudgetUsd', label: 'Subagent budget' },
486}
487
488/** Saves one field of the control panel's settings. */
489async function saveSetting($: EngineInterface, field: SettingField, text: string): Promise<void> {
490 let value: string | number
491 let shown: string
492 if (field === 'budget') {
493 const budget = parseBudget(text.trim() || 'off')
494 if (budget === null) {
495 $.ui.toast('Code Buddy: the budget takes an amount in dollars, like 2 or 2.50, or off.')
496 return
497 }
498 value = budget
499 shown = budget > 0 ? fmtUsd(budget) : 'off'
500 } else {
501 value = parseList(text).join(', ')
502 shown = value || '(none)'
503 if (field === 'branch' && !value) {
504 $.ui.toast("Code Buddy: the protected branch can't be empty.")
505 return
506 }
507 }
508 const { key, label } = SETTING_KEYS[field]
509 const done = await $.config.set({ key: `code-buddy.${key}`, value })
510 $.ui.toast('deny' in done && done.deny !== undefined ? `Code Buddy: couldn't save ${label}: ${done.deny}` : `Code Buddy: ${label} set to ${shown}.`)
511}
512
513async function openControl($: EngineInterface): Promise<void> {
514 await $.ui.open({ id: CONTROL_PANE, title: 'Code Buddy', focus: true, rows: controlRows(), columns: 72 })
515}
516
517/** Everything the guard and blast radius hold this call for; null lets it through. */
518async function inspect($: EngineInterface, e: Record<string, unknown>, cfg: GuardConfig, enabled: Record<Feature, boolean>): Promise<Finding | null> {
519 const guardOn = await isActive($, enabled, 'guard')
520 const blastOn = await isActive($, enabled, 'blast')
521 if (!guardOn && !blastOn) return null
522 const io = ioOf($)
523 return merge(guardOn ? await inspectGuard(io, e, cfg) : null, blastOn ? await inspectBlast(io, e) : null)
524}
525
526/** "Staging guard on · Blast radius paused (28m left) · Replay on · Agents panel off" */
527async function featuresLine($: EngineInterface, enabled: Record<Feature, boolean>): Promise<string> {
528 const p = await pausesOf($)
529 const now = await $.clock.now()
530 return FEATURES.map(f => `${f.name} ${!enabled[f.id] ? 'off' : isPaused(p, f.id, now) ? `paused (${leftText(p, f.id, now)})` : 'on'}`).join(' · ')
531}
532
533// ---- /code-buddy -------------------------------------------------------------
534
535async function statusText($: EngineInterface, cfg: GuardConfig, acfg: AgentsConfig, enabled: Record<Feature, boolean>): Promise<string> {
536 const log = await readLog($)
537 const now = await $.clock.now()
538 const lines = [
539 `Code Buddy · ${log.length} held this session`,
540 ` Features: ${await featuresLine($, enabled)}`,
541 ` Production: ${cfg.production.join(', ') || '(none)'}`,
542 ` Staging: ${cfg.staging.join(', ') || '(none)'} (production wins on overlap)`,
543 ` Protected: ${cfg.branches.join(', ')}`,
544 ` Subagents: budget ${acfg.budget > 0 ? fmtUsd(acfg.budget) : 'off'} · auto-open ${acfg.autoOpen ? 'on' : 'off'}`,
545 '',
546 ]
547 if (log.length === 0) {
548 lines.push('No calls held this session.')
549 } else {
550 lines.push('Held calls, newest first:')
551 for (const r of [...log].reverse()) {
552 lines.push(` ${ago(now - r.at).padEnd(10)} ${r.tool.padEnd(8)} ${OUTCOME_LABEL[r.outcome]}`)
553 lines.push(` ${r.rules.join('; ')}`)
554 lines.push(` ${r.command.length > 160 ? `${r.command.slice(0, 159)}…` : r.command}`)
555 }
556 }
557 lines.push('', 'More: /code-buddy control · pause · resume · replay · agents · config')
558 return mask(lines.join('\n'))
559}
560
561function configText(cfg: GuardConfig, acfg: AgentsConfig, enabled: Record<Feature, boolean>): string {
562 return [
563 'Code Buddy settings',
564 ` production ${cfg.production.join(', ') || '(none)'}`,
565 ` staging ${cfg.staging.join(', ') || '(none)'}`,
566 ` branch ${cfg.branches.join(', ')}`,
567 ` guard ${cfg.isOn ? 'on' : 'off'} (master switch for both hold features)`,
568 ` stagingguard ${enabled.guard ? 'on' : 'off'}`,
569 ` blast ${enabled.blast ? 'on' : 'off'}`,
570 ` replay ${enabled.replay ? 'on' : 'off'}`,
571 ` agents ${enabled.agents ? 'on' : 'off'}`,
572 ` budget ${acfg.budget > 0 ? fmtUsd(acfg.budget) : 'off'} (estimated subagent spend per session)`,
573 ` autoopen ${acfg.autoOpen ? 'on' : 'off'} (agents panel opens when a 2nd subagent starts)`,
574 '',
575 'Production wins on overlap: a host is let through only when staging lists it exactly (no wildcard).',
576 '',
577 'Change one with /code-buddy config <setting> <value>, for example:',
578 ' /code-buddy config production example.com, *.example.com',
579 ' /code-buddy config staging staging.example.com',
580 ' /code-buddy config branch main',
581 ' /code-buddy config guard off',
582 ' /code-buddy config budget 2.50',
583 ' /code-buddy config autoopen off',
584 ' /code-buddy config blast off (off in every session; /code-buddy pause blast 30m pauses it for now)',
585 '',
586 'Or open the control panel: /code-buddy control',
587 ].join('\n')
588}
589
590async function setConfig($: EngineInterface, args: string, cfg: GuardConfig, acfg: AgentsConfig, enabled: Record<Feature, boolean>): Promise<string> {
591 const [name = '', ...rest] = args.trim().split(/\s+/)
592 if (!name) return configText(cfg, acfg, enabled)
593 const field = CONFIG_FIELDS[name.toLowerCase()]
594 if (!field) return `Unknown setting "${name}". Settings: ${Object.keys(CONFIG_FIELDS).join(', ')}.`
595 const text = rest.join(' ').trim()
596 if (!text) return `Give a value: /code-buddy config ${name} <value>`
597 const isSwitch = ['guard', 'autoOpenAgents', 'stagingGuard', 'blastRadius', 'replay', 'agentsPanel'].includes(field.key)
598 if (isSwitch && text !== 'on' && text !== 'off') return `${field.label} takes on or off.`
599 const budget = field.key === 'agentBudgetUsd' ? parseBudget(text) : 0
600 if (budget === null) return 'Budget takes an amount in dollars, like 2 or 2.50, or off.'
601 const value = isSwitch ? text === 'on' : field.key === 'agentBudgetUsd' ? budget : text
602 const result = await $.config.set({ key: `${COMMAND}.${field.key}`, value })
603 if ('deny' in result && result.deny !== undefined) return `Couldn't change ${field.label}: ${result.deny}`
604 return `${field.label} set to ${text}. Code Buddy reloads with it now.`
605}
606
607/** What /code-buddy answers, for every subcommand. */
608async function answerBuddy(
609 $: EngineInterface,
610 args: string,
611 cfg: GuardConfig,
612 acfg: AgentsConfig,
613 enabled: Record<Feature, boolean>,
614): Promise<{ text: string }> {
615 const [sub = '', ...rest] = args.trim().split(/\s+/)
616 switch (sub.toLowerCase()) {
617 case '':
618 case 'status':
619 return { text: await statusText($, cfg, acfg, enabled) }
620 case 'config':
621 return { text: await setConfig($, rest.join(' '), cfg, acfg, enabled) }
622 case 'replay': {
623 const r = (await $.state.get(REPLAY)).value
624 if (!(await openReplay($)) || !r) return { text: 'Code Buddy · replay: no edits recorded yet. It fills after a turn that edits files.' }
625 return { text: `Code Buddy · replay: ${r.steps.length} ${r.steps.length === 1 ? 'edit' : 'edits'} from the last turn. Prev, Next and Close step through them.` }
626 }
627 case 'agents': {
628 const isOpen = await toggleAgents($)
629 const n = ((await $.state.get(AGENTS)).value ?? []).length
630 return { text: isOpen ? `Code Buddy · agents panel opened (${n} ${n === 1 ? 'subagent' : 'subagents'} this session).` : 'Code Buddy · agents panel closed.' }
631 }
632 case 'control':
633 case 'settings':
634 case 'features':
635 await openControl($)
636 return { text: 'Code Buddy · control panel opened.' }
637 case 'pause': {
638 if (!rest[0]) {
639 await openControl($)
640 return { text: 'Code Buddy · control panel opened. Or pause from here: /code-buddy pause <guard | blast | replay | agents | all> [30m].' }
641 }
642 const f = featureOf(rest[0])
643 if (f === null) return { text: `Unknown feature "${rest[0]}". Features: guard, blast, replay, agents, all.` }
644 const ms = parseDuration(rest.slice(1).join(' '))
645 if (ms === null) return { text: 'Give a duration like 30m, 2h or 90s, or nothing to pause until you resume.' }
646 if (f !== 'all' && !enabled[f]) return { text: `${nameOf(f)} is already off in the settings. Turn it on with /code-buddy config ${FEATURES.find(x => x.id === f)?.key === 'stagingGuard' ? 'stagingguard' : f} on.` }
647 return { text: await pauseFeature($, f, ms, enabled) }
648 }
649 case 'resume': {
650 const f = rest[0] ? featureOf(rest[0]) : 'all'
651 if (f === null) return { text: `Unknown feature "${rest[0]}". Features: guard, blast, replay, agents, all.` }
652 return { text: await resumeFeature($, f) }
653 }
654 default:
655 return { text: `Unknown option "${sub}". Try /code-buddy, /code-buddy control, /code-buddy pause, /code-buddy replay, /code-buddy agents or /code-buddy config.` }
656 }
657}
658
659// ---- Hooks -------------------------------------------------------------------
660
661export const register: Register = (on, options) => {
662 const cfg = configOf(options as Record<string, unknown>)
663 const acfg = agentsConfigOf(options as Record<string, unknown>)
664 const enabled = enabledOf(options as Record<string, unknown>)
665
666 on('session.start', async ($, e, next) => {
667 const started = await next(e)
668 isInteractive = e.isInteractive
669 if (e.isInteractive || e.surface !== null) await markSeen($)
670 version = await readVersion($)
671 await $.command.register({
672 name: 'code-buddy',
673 description: 'Code Buddy: status and held calls; replay, agents or config',
674 argumentHint: '[control | pause <feature> [30m] | resume | replay | agents | config]',
675 })
676 // Running subagents' clocks tick once a second; quiet when none runs.
677 $.clock.every(1000, () => {
678 void (async () => {
679 if (hasDrawn && !isSeenSaved) await markSeen($)
680 // Timed pauses end by themselves; the band counts them down.
681 const paused = (await $.state.get(PAUSES)).value ?? {}
682 if (Object.keys(paused).length > 0) {
683 const { pauses, ended } = expire(paused, await $.clock.now())
684 if (ended.length > 0) {
685 await $.state.set(PAUSES, pauses)
686 $.ui.toast(`Code Buddy: ${ended.map(nameOf).join(', ')} resumed (the pause ended).`)
687 }
688 if (Object.values(paused).some(until => until !== 0)) $.ui.invalidate('ui.render')
689 }
690 const list = (await $.state.get(AGENTS)).value ?? []
691 if (list.some(a => a.status === 'running')) $.ui.invalidate('ui.render')
692 })()
693 })
694 return started
695 })
696
697 on('command.run', { command: 'code-buddy' }, async ($, e) => answerBuddy($, e.args, cfg, acfg, enabled))
698
699 // The same command from the plugin's commands/code-buddy.md. That file is
700 // there so the desktop's / menu lists Code Buddy before a session starts (it
701 // builds that menu with hooks off, when /code-buddy above is never registered);
702 // with hooks on, it answers exactly as /code-buddy does and stays out of the menu.
703 on('command.run', { command: 'code-buddy:code-buddy' }, async ($, e) => answerBuddy($, e.args, cfg, acfg, enabled))
704 on('command.describe', { command: 'code-buddy:code-buddy' }, ($, e, next) => next({ ...e, isHidden: true }))
705
706 // Features 1 and 2: hold a risky call until the person answers.
707 // Feature 3: record each file edit that runs, never changing it.
708 on('tool.call', async ($, e, next) => {
709 const input = e as unknown as Record<string, unknown>
710 if (e.agentId !== undefined) {
711 try {
712 await noteActivity($, e.agentId, activityOf(input, await $.session.cwd()))
713 } catch {
714 // showing activity must never stop a call
715 }
716 }
717 const agentId = e.agentId
718 const entryId = agentId !== undefined ? await startDetailEntry($, agentId, input) : ''
719 const result = await (async () => {
720 const found = await inspect($, input, cfg, enabled)
721 if (found !== null) {
722 const outcome = await hold($, next.signal, String(e.tool), found, e.agentId !== undefined)
723 if (outcome !== 'proceeded') {
724 $.ui.toast(`Code Buddy: refused (${OUTCOME_LABEL[outcome]})`)
725 return { deny: refusal(outcome, found) }
726 }
727 $.ui.toast('Code Buddy: running it')
728 }
729 if (!EDIT_TOOLS.has(String(e.tool)) || !(await isActive($, enabled, 'replay'))) return next(e)
730 let step: ReplayStep | null = null
731 try {
732 step = await stepFor($, input)
733 } catch {
734 // recording must never stop the edit
735 }
736 const ran = await next(e)
737 if (step !== null && ran.deny === undefined && ran.isError !== true) {
738 try {
739 await recordStep($, step)
740 } catch {
741 // nor fail it
742 }
743 }
744 return ran
745 })()
746 if (agentId !== undefined && entryId) await endDetailEntry($, agentId, input, entryId, result)
747 return result
748 }).catch(($, e, next) =>
749 next.called
750 ? next(e)
751 : (enabled.guard && looksRisky(e as unknown as Record<string, unknown>, cfg)) || (enabled.blast && e.tool === 'Bash' && looksDestructive(String(e.command)))
752 ? { deny: 'Code Buddy could not finish checking this call, and it looks risky, so it was refused. Do not retry it unless the user asks you to.' }
753 : next(e),
754 )
755
756 // A window joined the session: holds can be answered from now on, reloads included.
757 on('session.attach', async ($, e, next) => {
758 const attached = await next(e)
759 try {
760 await markSeen($)
761 } catch {
762 // the hold falls back to its own checks
763 }
764 return attached
765 })
766
767 // Feature 4: every subagent, as it starts. Any Agent tool call, no companion skill.
768 on('agent.spawn', async ($, e, next) => {
769 const started = await next(e)
770 if (started.deny !== undefined) return started
771 if (!(await isActive($, enabled, 'agents'))) return started
772 try {
773 const at = await $.clock.now()
774 const batch = (await $.state.get(BATCH)).value ?? 0
775 const run: AgentRun = {
776 id: started.agentId ?? e.tool_use_id,
777 agentId: started.agentId,
778 type: e.subagentType || 'general-purpose',
779 description: mask(e.description || e.name || ''),
780 model: started.model,
781 status: 'running',
782 startedAt: at,
783 tokens: 0,
784 costUsd: 0,
785 steps: 0,
786 batch,
787 }
788 await writeAgents($, list => [...list.filter(a => a.id !== run.id), run].slice(-200))
789 await $.state.set(
790 { ...DETAILS, id: run.id },
791 newDetail(
792 {
793 id: run.id,
794 prompt: e.prompt,
795 name: e.name,
796 cwd: e.cwd,
797 permissionMode: e.permissionMode,
798 background: e.background,
799 fork: e.fork,
800 model: e.model,
801 parentModel: e.parentModel,
802 parentAgentId: e.parentAgentId,
803 teammateId: started.teammateId,
804 },
805 at,
806 ),
807 )
808 if (acfg.autoOpen) await maybeAutoOpen($, batch)
809 } catch {
810 // tracking must never stop a subagent
811 }
812 return started
813 }).catch(($, e, next) => next(e)) // a failed hook still lets the subagent start
814
815 // Each model request of a subagent: its tokens and cost.
816 on('turn.step', async function* ($, e, next) {
817 const result = yield* next(e)
818 if (e.agentId !== undefined && result.usage) {
819 try {
820 const model = result.usage.model || e.model
821 await addUsage($, e.agentId, model, result.usage)
822 const usage = result.usage
823 const at = await $.clock.now()
824 await writeDetail($, e.agentId, d => onStep(d, usage, costParts(model, usage), typeof e.effort === 'string' ? e.effort : undefined, result.answer, at))
825 await checkBudget($, acfg.budget)
826 } catch {
827 // nor slow one down
828 }
829 }
830 return result
831 })
832
833 // A new prompt starts a new recording and a new batch of subagents; the replay hint is put away.
834 on('turn.start', async ($, e, next) => {
835 await $.state.set(BATCH, ((await $.state.get(BATCH)).value ?? 0) + 1)
836 await $.state.set(RECORDING, [])
837 const r = (await $.state.get(REPLAY)).value
838 if (r && !r.isSeen) await $.state.set(REPLAY, { ...r, isSeen: true })
839 return next(e)
840 })
841
842 // The main turn's end: its edits become the replay (subagents' turns end too, carrying agentId).
843 on('turn.complete', async ($, e, next) => {
844 const done = await next(e)
845 if (e.agentId !== undefined) {
846 await finishAgent($, e.agentId, e.reason, e.usage)
847 const at = await $.clock.now()
848 const agentId = e.agentId
849 await writeDetail($, agentId, d => onFinish(d, e.answer, e.reason, at))
850 await checkBudget($, acfg.budget)
851 return done
852 }
853 const steps = (await $.state.get(RECORDING)).value ?? []
854 if (steps.length > 0) {
855 const replay: Replay = { steps, index: 0, isSeen: false }
856 await $.state.set(REPLAY, replay)
857 await $.state.set(RECORDING, [])
858 }
859 return done
860 })
861
862 on('ui.render', { component: 'Pane', requestId: 'code-buddy-replay' }, async ($, e) => {
863 const ui = $.ui.resolve(e)
864 const r = (await $.state.get(REPLAY)).value
865 if (!r || r.steps.length === 0) return <ui.Text dimColor>No edits to replay yet.</ui.Text>
866 return drawReplay(ui, e.surface, r, e.props.bodyColumns, {
867 go: index => void goToStep($, index),
868 close: () => void $.ui.close({ id: REPLAY_PANE }),
869 })
870 })
871
872 on('ui.render', { component: 'Pane', requestId: 'code-buddy-agents' }, async ($, e) => {
873 const ui = $.ui.resolve(e)
874 const list = (await $.state.get(AGENTS)).value ?? []
875 const agentsUi = await readUi($)
876 const chosen = agentsUi.selected === undefined ? undefined : list.find(a => a.id === agentsUi.selected)
877 if (chosen !== undefined) {
878 const detail = (await $.state.get({ ...DETAILS, id: chosen.id })).value
879 return drawAgentDetail(ui, e.surface, chosen, detail ?? undefined, await $.clock.now(), e.props.bodyColumns, {
880 back: () => void selectAgent($, undefined),
881 copy: text => void copyText($, text, e.surface),
882 })
883 }
884 const view = { isCompact: agentsUi.isCompact, budget: acfg.budget }
885 return drawAgents(ui, e.surface, list, await $.clock.now(), e.props.bodyColumns, view, {
886 toggleCompact: () => void toggleCompact($),
887 select: id => void selectAgent($, id),
888 })
889 })
890
891 on('ui.render', { component: 'Pane', requestId: 'code-buddy-control' }, async ($, e) => {
892 const ui = $.ui.resolve(e)
893 const p = await pausesOf($)
894 const now = await $.clock.now()
895 const log = (await $.state.get(LOG)).value ?? []
896 const view = {
897 version,
898 held: log.length,
899 features: FEATURES.map(f => ({
900 id: f.id,
901 state: !enabled[f.id] ? ('off' as const) : isPaused(p, f.id, now) ? ('paused' as const) : ('on' as const),
902 left: leftText(p, f.id, now),
903 })),
904 settings: {
905 production: cfg.production.join(', '),
906 staging: cfg.staging.join(', '),
907 branch: cfg.branches.join(', '),
908 budget: acfg.budget > 0 ? String(acfg.budget) : 'off',
909 autoOpen: acfg.autoOpen,
910 },
911 }
912 return drawControl(ui, e.surface, view, e.props.bodyColumns, {
913 pause: (f, ms) => void pauseFeature($, f, ms, enabled),
914 resume: f => void resumeFeature($, f),
915 setOn: (f, turnOn) => void setFeatureOn($, f, turnOn, options as Record<string, unknown>),
916 set: (field, value) => void saveSetting($, field, value),
917 setAutoOpen: turnOn => void $.config.set({ key: 'code-buddy.autoOpenAgents', value: turnOn }),
918 })
919 })
920
921 on('ui.render', { component: 'Pane', requestId: 'code-buddy-hold' }, async ($, e) => {
922 const ui = $.ui.resolve(e)
923 const queue = (await $.state.get(QUEUE)).value ?? []
924 const head = queue[0]
925 if (head === undefined) return <ui.Text dimColor>Nothing is held.</ui.Text>
926 return drawHold(ui, e.surface, head, queue.length - 1, e.props.bodyColumns)
927 })
928
929 // The one band above the prompt. Priority: a waiting hold, then the agents
930 // progress bar, then the replay hint, then the idle status.
931 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
932 hasDrawn = true
933 if (e.props.hasSurvey) return next(e)
934 const ui = $.ui.resolve(e)
935 const queue = (await $.state.get(QUEUE)).value ?? []
936 const head = queue[0]
937 if (head !== undefined) return drawHoldBand(ui, e.surface, head, queue.length - 1, e.props.bodyColumns)
938 const all = (await $.state.get(AGENTS)).value ?? []
939 const spend = budgetOf(all, acfg.budget)
940 const runs = barRuns(all, (await $.state.get(BATCH)).value ?? 0)
941 const agentsOn = await isActive($, enabled, 'agents')
942 if (agentsOn && (runs.some(a => a.status === 'running') || (e.props.isWorking && runs.length > 0))) {
943 return drawAgentsBand(ui, e.surface, runs, e.props.bodyColumns, spend?.isOver ?? false, () => void toggleAgents($))
944 }
945 const replay = (await $.state.get(REPLAY)).value
946 if (replay && !replay.isSeen && replay.steps.length > 0 && !e.props.isWorking && (await isActive($, enabled, 'replay'))) {
947 return drawReplayBand(ui, e.surface, replay, e.props.bodyColumns, () => void openReplay($))
948 }
949 const log = (await $.state.get(LOG)).value ?? []
950 const p = await pausesOf($)
951 const now = await $.clock.now()
952 const paused = FEATURES.filter(f => enabled[f.id] && isPaused(p, f.id, now)).map(f => `${f.name} · ${leftText(p, f.id, now)}`)
953 const holdsOn = (enabled.guard && !isPaused(p, 'guard', now)) || (enabled.blast && !isPaused(p, 'blast', now))
954 return drawIdleBand(ui, e.surface, holdsOn, log.length, e.props.bodyColumns, spend?.isOver ? `over budget · ${spend.used}` : '', paused, () => void resumeFeature($, 'all'))
955 })
956}
957hooks/agents.tsx 363 lines1// Feature 4, Agents panel: every subagent of the session with its model,
2// status, elapsed time, tokens, estimated cost and what it is doing now; a
3// progress bar of finished out of total in the band; a cost budget. Pure
4// helpers and drawing: register.tsx records the runs from agent.spawn,
5// tool.call, turn.step and turn.complete.
6//
7// The tracking approach and the token-cost estimate follow savvy-progress
8// (claude-kit, MIT). Modified for Code Buddy: no companion skill or tool, no
9// environment reads, current list prices, Ruah Tech theme. See NOTICE.
10
11import type { EngineInterface } from 'claude-code'
12
13import type { AgentRun } from '../types'
14import { mask } from './mask'
15import {
16 AGENTS_HEADER_H,
17 BAND_ROW_H,
18 BRAND,
19 COMPACT_ROW_H,
20 GREEN,
21 agentRowHeight,
22 agentRowSvg,
23 agentsBandSvg,
24 agentsHeaderSvg,
25 compactAgentRowSvg,
26 labelSvg,
27 pxOf,
28} from './theme'
29import type { AgentRowView, BudgetView } from './theme'
30
31export const AGENTS_PANE = 'code-buddy-agents'
32
33type Ui = ReturnType<EngineInterface['ui']['resolve']>
34type Surface = 'terminal' | 'desktop' | 'mobile' | 'vscode'
35export type Usage = { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
36
37// ---- Settings ----------------------------------------------------------------
38
39export type AgentsConfig = {
40 /** USD; 0 means no budget. */
41 budget: number
42 autoOpen: boolean
43}
44
45export function agentsConfigOf(options: Record<string, unknown>): AgentsConfig {
46 const budget = Number(String(options.agentBudgetUsd ?? '').replace(/[$\s]/g, ''))
47 return { budget: Number.isFinite(budget) && budget > 0 ? budget : 0, autoOpen: options.autoOpenAgents !== false }
48}
49
50/** "2", "$2.50", "off" → dollars, 0 for off; null when it is not a number. */
51export function parseBudget(text: string): number | null {
52 if (/^(off|none|0)$/i.test(text.trim())) return 0
53 const n = Number(text.replace(/[$\s]/g, ''))
54 return Number.isFinite(n) && n > 0 ? Math.round(n * 100) / 100 : null
55}
56
57/** The pane's open arguments: a wider dock, and as tall as its rows want. */
58export function agentsPaneArgs(rows: number) {
59 return { id: AGENTS_PANE, title: 'Agents', columns: 76, rows: Math.max(12, Math.min(34, rows)) }
60}
61
62/** Rows the panel wants for this many subagents, full or compact. */
63export const agentsRows = (n: number, isCompact: boolean): number => 8 + (isCompact ? n : n * 3)
64
65// ---- Pricing -----------------------------------------------------------------
66
67// USD per million tokens: input, output, cache read, cache write (5-minute TTL,
68// 1.25 × input). List prices as of 2026-10; the engine reports tokens, not money.
69const PRICES: [RegExp, [number, number, number, number]][] = [
70 [/(fable|mythos)-5-1/, [10, 50, 0.25, 12.5]],
71 [/fable|mythos/, [10, 50, 1, 12.5]],
72 [/opus-5-5/, [4, 20, 0.2, 5]],
73 [/opus/, [5, 25, 0.5, 6.25]],
74 [/sonnet-4/, [3, 15, 0.3, 3.75]],
75 [/sonnet/, [2, 10, 0.2, 2.5]],
76 [/haiku-5/, [0.1, 0.5, 0.01, 0.125]],
77 [/haiku/, [1, 5, 0.1, 1.25]],
78]
79const DEFAULT_PRICE: [number, number, number, number] = [4, 20, 0.2, 5]
80
81export const priceOf = (model: string): [number, number, number, number] =>
82 PRICES.find(([re]) => re.test(model.toLowerCase()))?.[1] ?? DEFAULT_PRICE
83
84export function costOf(model: string, u: Usage): number {
85 const [i, o, r, w] = priceOf(model)
86 return ((u.input_tokens || 0) * i + (u.output_tokens || 0) * o + (u.cache_read_input_tokens || 0) * r + (u.cache_creation_input_tokens || 0) * w) / 1e6
87}
88
89/** The cost of one request by kind of token. */
90export function costParts(model: string, u: Usage): { input: number; output: number; cacheRead: number; cacheWrite: number } {
91 const [i, o, r, w] = priceOf(model)
92 return {
93 input: ((u.input_tokens || 0) * i) / 1e6,
94 output: ((u.output_tokens || 0) * o) / 1e6,
95 cacheRead: ((u.cache_read_input_tokens || 0) * r) / 1e6,
96 cacheWrite: ((u.cache_creation_input_tokens || 0) * w) / 1e6,
97 }
98}
99
100export const tokensOf = (u: Usage): number =>
101 (u.input_tokens || 0) + (u.output_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0)
102
103// ---- Formatting --------------------------------------------------------------
104
105/** `claude-opus-5-5` → `Opus 5.5`. */
106export function modelName(id: string): string {
107 const m = /(fable|mythos|opus|sonnet|haiku)-(\d+)(?:-(\d{1,2})(?!\d))?/i.exec(id)
108 const [, family = '', major = '', minor] = m ?? []
109 if (!family) return id.replace(/^claude-/, '').replace(/\[.*\]$/, '') || '—'
110 return `${family.charAt(0).toUpperCase()}${family.slice(1).toLowerCase()} ${major}${minor ? `.${minor}` : ''}`
111}
112
113export const fmtTokens = (n: number): string => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : `${Math.round(n)}`)
114export const fmtCost = (usd: number): string =>
115 usd > 0 && usd < 0.005 ? '<$0.01' : `≈$${usd < 10 ? usd.toFixed(2) : usd.toFixed(1)}`
116export const fmtUsd = (usd: number): string => `$${usd.toFixed(2)}`
117export function fmtTime(ms: number): string {
118 const s = Math.max(0, Math.round(ms / 1000))
119 const h = Math.floor(s / 3600)
120 const m = Math.floor((s % 3600) / 60)
121 const ss = String(s % 60).padStart(2, '0')
122 return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`
123}
124
125// ---- Activity ----------------------------------------------------------------
126
127const short = (s: string, n: number): string => (s.length > n ? `${s.slice(0, n - 1)}…` : s)
128const rel = (cwd: string, path: string): string => (cwd && path.startsWith(`${cwd}/`) ? path.slice(cwd.length + 1) : path)
129
130/** What a subagent's tool call is doing, in a few words, masked: "Read · src/api/routes.ts". */
131export function activityOf(e: Record<string, unknown>, cwd: string): string {
132 const tool = String(e.tool)
133 const s = (k: string) => (typeof e[k] === 'string' ? (e[k] as string) : '')
134 const name = tool.startsWith('mcp__') ? tool.split('__').slice(-1)[0] ?? tool : tool
135 let what = ''
136 if (s('command')) what = s('command').split('\n')[0] ?? ''
137 else if (s('file_path') || s('notebook_path')) what = rel(cwd, s('file_path') || s('notebook_path'))
138 else if (s('pattern')) what = `${s('pattern')}${s('path') ? ` in ${rel(cwd, s('path'))}` : ''}`
139 else if (s('url')) what = s('url').replace(/^https?:\/\//, '')
140 else if (s('query')) what = s('query')
141 else if (s('description')) what = s('description')
142 else if (s('prompt')) what = s('prompt')
143 return mask(what ? `${name} · ${short(what, 80)}` : name)
144}
145
146// ---- Totals ------------------------------------------------------------------
147
148export const elapsed = (a: AgentRun, now: number): number => (a.endedAt ?? Math.max(now, a.startedAt)) - a.startedAt
149
150export function totals(list: AgentRun[], now: number) {
151 const done = list.filter(a => a.status !== 'running').length
152 const running = list.length - done
153 const cost = list.reduce((s, a) => s + a.costUsd, 0)
154 const tokens = list.reduce((s, a) => s + a.tokens, 0)
155 const start = list.length ? Math.min(...list.map(a => a.startedAt)) : now
156 const end = list.length ? Math.max(...list.map(a => a.endedAt ?? Math.max(now, a.startedAt))) : now
157 return { done, running, total: list.length, cost, tokens, time: end - start }
158}
159
160/** The session's spend against the budget, or undefined with no budget set. */
161export function budgetOf(list: AgentRun[], budget: number): BudgetView | undefined {
162 if (budget <= 0) return undefined
163 const used = list.reduce((s, a) => s + a.costUsd, 0)
164 return { limit: fmtUsd(budget), used: fmtCost(used), ratio: Math.min(1, used / budget), isOver: used >= budget }
165}
166
167/** The runs the band's bar counts: this prompt's, plus any still running from before. */
168export const barRuns = (list: AgentRun[], batch: number): AgentRun[] => list.filter(a => a.batch === batch || a.status === 'running')
169
170// ---- Drawing -----------------------------------------------------------------
171
172const STATUS_WORD = { running: 'running', done: 'finished', failed: 'failed', stopped: 'stopped' } as const
173const STATUS_GLYPH = { running: '●', done: '✓', failed: '✗', stopped: '■' } as const
174const STATUS_COLOR = { running: BRAND.sky, done: GREEN, failed: BRAND.coral, stopped: BRAND.muted } as const
175
176const rowOf = (a: AgentRun, now: number): AgentRowView => ({
177 status: a.status,
178 title: a.description || a.type,
179 type: a.type,
180 model: modelName(a.model),
181 elapsed: fmtTime(elapsed(a, now)),
182 tokens: `${fmtTokens(a.tokens)} tokens`,
183 cost: fmtCost(a.costUsd),
184 activity: a.status === 'running' ? a.activity || 'starting…' : undefined,
185 progress: `step ${a.steps} · ${a.tools ?? 0} ${(a.tools ?? 0) === 1 ? 'tool' : 'tools'}`,
186})
187
188export type AgentsView = { isCompact: boolean; budget: number }
189export type AgentsActions = { toggleCompact: () => void; select: (id: string) => void }
190
191/** The side panel: summary, then running and finished subagents, full or compact. */
192export function drawAgents(ui: Ui, surface: Surface, list: AgentRun[], now: number, columns: number, view: AgentsView, act: AgentsActions) {
193 const { Box, Text, Button } = ui
194 const running = list.filter(a => a.status === 'running').reverse()
195 const finished = list.filter(a => a.status !== 'running').reverse()
196 const t = totals(list, now)
197 const budget = budgetOf(list, view.budget)
198 const stats: [string, string][] = [
199 ['Cost', fmtCost(t.cost)],
200 ['Tokens', fmtTokens(t.tokens)],
201 ['Time', fmtTime(t.time)],
202 ]
203 const toggle = (
204 <Button key="compact" label={view.isCompact ? 'Expand' : 'Compact'} hotkey="x" onPress={() => act.toggleCompact()} />
205 )
206 const note = (
207 <Text key="note" dimColor italic wrap="wrap">
208 {`Costs are estimates from list prices per model; the engine reports tokens, not money.${budget ? ` Budget ${budget.limit} this session${budget.isOver ? `, passed at ${budget.used}` : ''}.` : ''}`}
209 </Text>
210 )
211 const empty = (
212 <Text key="empty" dimColor wrap="wrap">
213 No subagents yet this session. Each one shows here as soon as it starts.
214 </Text>
215 )
216
217 if (surface === 'desktop' && 'Svg' in ui) {
218 const { Svg } = ui
219 const W = pxOf(columns, 16, 260)
220 const rows = (items: AgentRun[]) =>
221 items.map(a => {
222 const r = rowOf(a, now)
223 const alt = `${r.title}: ${STATUS_WORD[a.status]}, ${r.type}, ${r.model}, ${r.elapsed}, ${r.tokens}, ${r.cost}${r.activity ? `, now ${r.activity}` : ''}`
224 const details = <Button key={`d-${a.id}`} label={`Details ›`} plain onPress={() => act.select(a.id)} />
225 return (
226 <Box key={`r-${a.id}`} flexDirection="column">
227 {view.isCompact ? (
228 <Svg key={a.id} source={compactAgentRowSvg(W, r)} alt={alt} width={W} height={COMPACT_ROW_H} />
229 ) : (
230 <Svg key={a.id} source={agentRowSvg(W, r)} alt={alt} width={W} height={agentRowHeight(r, W)} />
231 )}
232 {details}
233 </Box>
234 )
235 })
236 return (
237 <Box flexDirection="column" gap={1}>
238 <Svg
239 key="head"
240 source={agentsHeaderSvg(W, t.done, t.running, t.total, stats, budget)}
241 alt={`Subagents: ${t.done} of ${t.total} finished. ${stats.map(s => s.join(' ')).join(', ')}${budget ? `, budget ${budget.limit}${budget.isOver ? ' passed' : ''}` : ''}`}
242 width={W}
243 height={AGENTS_HEADER_H}
244 />
245 {toggle}
246 {list.length === 0 && empty}
247 {running.length > 0 && <Svg key="l-run" source={labelSvg(W, `Running · ${running.length}`)} alt={`Running: ${running.length}`} width={W} height={18} />}
248 {rows(running)}
249 {finished.length > 0 && <Svg key="l-done" source={labelSvg(W, `Finished · ${finished.length}`)} alt={`Finished: ${finished.length}`} width={W} height={18} />}
250 {rows(finished)}
251 {list.length > 0 && note}
252 </Box>
253 )
254 }
255
256 const barW = Math.max(8, Math.min(24, columns - 40))
257 const row = (a: AgentRun) => {
258 const r = rowOf(a, now)
259 const details = <Button key={`d-${a.id}`} label="Details ›" plain onPress={() => act.select(a.id)} />
260 if (view.isCompact) {
261 return (
262 <Box key={a.id} flexDirection="row" gap={1}>
263 <Text wrap="truncate-end">
264 <Text color={STATUS_COLOR[a.status]} bold>{`${STATUS_GLYPH[a.status]} `}</Text>
265 <Text bold>{r.title}</Text>
266 <Text dimColor>{` ${r.model} · ${r.elapsed} · ${r.cost}`}</Text>
267 {r.activity ? <Text color={BRAND.sky}>{` ▸ ${r.activity}`}</Text> : null}
268 </Text>
269 {details}
270 </Box>
271 )
272 }
273 return (
274 <Box key={a.id} flexDirection="column" marginBottom={1}>
275 <Text wrap="truncate-end">
276 <Text color={STATUS_COLOR[a.status]} bold>{`${STATUS_GLYPH[a.status]} `}</Text>
277 <Text bold>{r.title}</Text>
278 </Text>
279 <Text dimColor wrap="truncate-end">{` ${r.type} · ${r.model} · ${r.elapsed} · ${r.tokens} · ${r.cost}`}</Text>
280 {r.activity ? (
281 <Text wrap="truncate-end">
282 <Text color={BRAND.sky}>{` ▸ ${r.activity}`}</Text>
283 <Text dimColor>{` ${r.progress}`}</Text>
284 </Text>
285 ) : null}
286 {details}
287 </Box>
288 )
289 }
290 return (
291 <Box flexDirection="column" paddingX={1}>
292 <Box key="head" flexDirection="row" justifyContent="space-between">
293 <Text wrap="truncate-end">
294 <Text backgroundColor={BRAND.royal} color={BRAND.white} bold>
295 {' ≋ AGENTS '}
296 </Text>
297 <Text bold color={BRAND.sky}>{` ${t.done} of ${t.total} finished`}</Text>
298 </Text>
299 {toggle}
300 </Box>
301 <Text key="bar" wrap="truncate-end">
302 <Text color={budget?.isOver ? BRAND.coral : BRAND.blue}>{bar(t.done, t.total, barW)}</Text>
303 <Text dimColor>{` ${stats.map(([k, v]) => `${k.toLowerCase()} ${v}`).join(' · ')}`}</Text>
304 </Text>
305 {budget && (
306 <Text key="budget" wrap="truncate-end">
307 <Text dimColor>{'budget '}</Text>
308 {budget.isOver ? (
309 <Text backgroundColor={BRAND.coral} color={BRAND.white} bold>{` over ${budget.limit} `}</Text>
310 ) : (
311 <Text color={BRAND.sky}>{`${Math.round(budget.ratio * 100)}% of ${budget.limit}`}</Text>
312 )}
313 </Text>
314 )}
315 <Box key="list" flexDirection="column" marginTop={1}>
316 {list.length === 0 && empty}
317 {running.length > 0 && <Text color={BRAND.sky} bold>{`RUNNING · ${running.length}`}</Text>}
318 {running.map(row)}
319 {finished.length > 0 && <Text color={BRAND.sky} bold>{`FINISHED · ${finished.length}`}</Text>}
320 {finished.map(row)}
321 </Box>
322 {list.length > 0 && note}
323 </Box>
324 )
325}
326
327const bar = (done: number, total: number, width: number): string => {
328 const filled = total ? Math.round((width * done) / total) : 0
329 return '█'.repeat(filled) + '░'.repeat(Math.max(0, width - filled))
330}
331
332/** The band: finished out of total, and a button that toggles the panel. Coral past the budget. */
333export function drawAgentsBand(ui: Ui, surface: Surface, list: AgentRun[], columns: number, isOver: boolean, toggle: () => void) {
334 const { Box, Text, Button } = ui
335 const t = totals(list, 0)
336 const button = <Button key="toggle-agents" label="Agents" hotkey="a" onPress={toggle} />
337 if (surface === 'desktop' && 'Svg' in ui) {
338 const { Svg } = ui
339 const W = Math.min(pxOf(columns, 110, 220), 760)
340 return (
341 <Box flexDirection="row" alignItems="center" gap={1}>
342 <Svg key="agents" source={agentsBandSvg(W, t.done, t.running, t.total, fmtCost(t.cost), isOver)} alt={`Agents: ${t.done} of ${t.total} finished, ${fmtCost(t.cost)}${isOver ? ', over budget' : ''}`} width={W} height={BAND_ROW_H} />
343 {button}
344 </Box>
345 )
346 }
347 const barW = Math.max(6, Math.min(24, columns - 60))
348 return (
349 <Box flexDirection="row" gap={1}>
350 <Text wrap="truncate-end">
351 <Text backgroundColor={BRAND.royal} color={BRAND.white} bold>
352 {' ≋ Code Buddy '}
353 </Text>
354 <Text bold>{' Agents '}</Text>
355 <Text color={isOver ? BRAND.coral : BRAND.blue}>{bar(t.done, t.total, barW)}</Text>
356 <Text dimColor>{` ${t.done}/${t.total} finished · ${fmtCost(t.cost)}`}</Text>
357 {isOver ? <Text color={BRAND.coral} bold>{' · over budget'}</Text> : null}
358 </Text>
359 {button}
360 </Box>
361 )
362}
363hooks/blast.ts 325 lines1// Feature 2, Blast radius: holds destructive shell commands and works out what
2// they would delete or change.
3//
4// Adapted from blast-radius (claude-code-playground), Copyright 2026 Anthropic
5// PBC, licensed under the Apache License 2.0. Modified for Code Buddy: ported
6// to TypeScript; reads through register.tsx's Io instead of `$`; `~` expands
7// from the account record (HOME unset) so no environment variable is read;
8// migrations are listed from files on disk instead of the migration tools'
9// status commands, which would connect to the database. See NOTICE.
10
11import type { Finding, Io } from './guard'
12import { mask } from './mask'
13import { gitParts, segments } from './shell'
14import type { Segment } from './shell'
15
16const LIST_MAX = 10
17
18type GitRisk = { kind: 'git-reset' | 'git-clean' | 'git-push-force' | 'git-checkout'; label: string; args: string[]; dir: string | null }
19
20type Risk =
21 | { kind: 'rm'; label: string; targets: string[]; dir: string | null }
22 | GitRisk
23 | { kind: 'migrate'; tool: string; label: string; dir: string | null }
24
25type Measured = { summary: string; lines: string[]; more: number; note: string }
26
27// Commands that only read, so a bare word "migrate" in them isn't a migration.
28const READ_ONLY = new Set(['ls', 'cat', 'echo', 'printf', 'grep', 'rg', 'find', 'less', 'head', 'tail', 'git', 'man', 'which', 'type'])
29
30/** Every destructive command on the line, in order. */
31export function classify(command: string): Risk[] {
32 return segments(command)
33 .map(classifySegment)
34 .filter((r): r is Risk => r !== null)
35}
36
37function classifySegment(seg: Segment): Risk | null {
38 const { cmd, args, dir } = seg
39 if (cmd === 'rm') {
40 const flags = args.filter(a => a.startsWith('-') && a !== '-' && a !== '--')
41 const recursive = flags.some(f => f === '--recursive' || (/^-[^-]/.test(f) && /[rR]/.test(f)))
42 const force = flags.some(f => f === '--force' || (/^-[^-]/.test(f) && f.includes('f')))
43 if (recursive || force) {
44 const dash = args.indexOf('--')
45 const targets = dash >= 0 ? args.slice(dash + 1) : args.filter(a => !a.startsWith('-') || a === '-')
46 return { kind: 'rm', label: `rm ${flags.join(' ')}`.trim(), targets, dir }
47 }
48 }
49 if (cmd === 'git') {
50 const { dir: gitDir, sub, rest } = gitParts(seg)
51 if (sub === 'reset' && rest.includes('--hard')) return { kind: 'git-reset', label: 'git reset --hard', args: rest, dir: gitDir }
52 if (sub === 'clean' && !rest.some(a => a === '-n' || a === '--dry-run' || (/^-[a-zA-Z]+$/.test(a) && a.includes('n')))) {
53 return { kind: 'git-clean', label: 'git clean', args: rest, dir: gitDir }
54 }
55 if (sub === 'push' && rest.some(a => a === '--force' || a === '-f' || a.startsWith('--force-with-lease') || a === '--force-if-includes' || /^\+/.test(a) || (/^-[a-zA-Z]+$/.test(a) && a.includes('f')))) {
56 return { kind: 'git-push-force', label: 'git push --force', args: rest, dir: gitDir }
57 }
58 const stagedOnly = sub === 'restore' && rest.includes('--staged') && !rest.includes('--worktree') && !rest.includes('-W')
59 if ((sub === 'checkout' || sub === 'restore') && (rest.includes('.') || rest.includes(':/')) && !stagedOnly) {
60 return { kind: 'git-checkout', label: `git ${sub} -- .`, args: rest, dir: gitDir }
61 }
62 }
63 const joined = [cmd, ...args].join(' ')
64 const migration: [RegExp, string, string][] = [
65 [/\balembic\s+(upgrade|downgrade)\b/, 'alembic', 'alembic upgrade'],
66 [/\bdb:(migrate|rollback|reset|drop|schema:load)(?!:status\b)/, 'rails', 'rails db:migrate'],
67 [/\bprisma\s+(migrate\s+(deploy|dev|reset)|db\s+push)\b/, 'prisma', 'prisma migrate'],
68 [/\bmanage\.py\s+(migrate|flush)\b/, 'django', 'manage.py migrate'],
69 [/\b(knex|sequelize)\b.*\b(migrate|db:migrate)/, 'knex', 'knex/sequelize migrate'],
70 [/\bdrizzle-kit\s+(migrate|push)\b/, 'drizzle', 'drizzle-kit migrate'],
71 [/\bflyway\b.*\bmigrate\b/, 'flyway', 'flyway migrate'],
72 ]
73 for (const [re, tool, label] of migration) if (re.test(joined)) return { kind: 'migrate', tool, label, dir }
74 if (!READ_ONLY.has(cmd) && args.includes('migrate')) return { kind: 'migrate', tool: 'unknown', label: `${cmd} migrate`, dir }
75 return null
76}
77
78// ---- Measuring -------------------------------------------------------------
79
80// With HOME unset, bash expands ~ from the account record: no variable is read.
81const NO_HOME = ['env', '-u', 'HOME', 'bash', '-c']
82
83// Resolves a folder to an absolute one, or prints nothing when it doesn't exist.
84// The folder is an argument, never source.
85const CD_SCRIPT = [
86 'unset CDPATH; h=~; d="$1"',
87 'case "$d" in "~") d="$h";; "~/"*) d="$h/${d#\\~/}";; esac',
88 'cd -- "$d" 2>/dev/null && pwd -P',
89].join('\n')
90
91// Counts what rm would remove. Paths are arguments, never source; compgen -G
92// expands a glob without command substitution.
93const RM_SCRIPT = [
94 'shopt -s nullglob dotglob',
95 'h=~',
96 'paths=()',
97 'for p in "$@"; do',
98 ' case "$p" in "~") p="$h";; "~/"*) p="$h/${p#\\~/}";; esac',
99 ' if [[ "$p" == *[*?[]* ]]; then',
100 ' while IFS= read -r m; do paths+=("$m"); done < <(compgen -G "$p")',
101 ' elif [[ -e "$p" || -L "$p" ]]; then',
102 ' paths+=("$p")',
103 ' fi',
104 'done',
105 'if (( ${#paths[@]} == 0 )); then echo "0 0 0"; exit 0; fi',
106 // A relative path gets ./ in front, so find never reads a name like -delete as an action.
107 'for i in "${!paths[@]}"; do case "${paths[$i]}" in /*) ;; *) paths[$i]="./${paths[$i]}";; esac; done',
108 'files=$(find "${paths[@]}" \\( -type f -o -type l \\) 2>/dev/null | wc -l | tr -d " ")',
109 'kb=$(du -skc "${paths[@]}" 2>/dev/null | tail -n1 | cut -f1)',
110 'echo "$files $(( ${kb:-0} * 1024 )) ${#paths[@]}"',
111 `find "\${paths[@]}" \\( -type f -o -type l \\) 2>/dev/null | head -n ${LIST_MAX}`,
112].join('\n')
113
114async function resolveDir(io: Io, cwd: string, dir: string | null): Promise<string | null> {
115 if (dir === null) return cwd
116 if (dir === '-') return null // `cd -` depends on the shell's history
117 const run = await io.run([...NO_HOME, CD_SCRIPT, 'code-buddy', dir], cwd, 5000)
118 const out = run?.stdout.trim() ?? ''
119 return run?.exitCode === 0 && out !== '' ? out : null
120}
121
122function size(bytes: number): string {
123 if (!Number.isFinite(bytes) || bytes < 1024) return `${bytes || 0} B`
124 const units = ['KB', 'MB', 'GB', 'TB']
125 let n = bytes
126 let i = -1
127 while (n >= 1024 && i < units.length - 1) {
128 n /= 1024
129 i += 1
130 }
131 return `${n.toFixed(n < 10 ? 1 : 0)} ${units[i]}`
132}
133
134const plural = (n: number, one: string, many = `${one}s`): string => `${n} ${n === 1 ? one : many}`
135
136async function measureRm(io: Io, risk: Extract<Risk, { kind: 'rm' }>, cwd: string): Promise<Measured> {
137 if (risk.targets.length === 0) return { summary: 'rm with no paths', lines: [], more: 0, note: 'No paths to expand.' }
138 const run = await io.run([...NO_HOME, RM_SCRIPT, 'code-buddy', ...risk.targets], cwd, 15000)
139 const [head, ...rest] = (run?.stdout ?? '').split('\n').filter(l => l !== '')
140 const [files = 0, bytes = 0, found = 0] = (head ?? '0 0 0').split(' ').map(Number)
141 if (!found) return { summary: `delete nothing: no file matches ${risk.targets.join(' ')}`, lines: [], more: 0, note: "The paths don't exist, so rm has nothing to remove." }
142 if (!files) return { summary: `delete ${plural(found, 'path')} with no files in ${found === 1 ? 'it' : 'them'}`, lines: [], more: 0, note: `Paths: ${risk.targets.join(' ')}` }
143 return {
144 summary: `delete ${plural(files, 'file')} (about ${size(bytes)})`,
145 lines: rest.map(l => l.replace(/^\.\//, '')),
146 more: Math.max(0, files - rest.length),
147 note: `Paths: ${risk.targets.join(' ')}. Deleted files don't go to the Trash.`,
148 }
149}
150
151async function measureClean(io: Io, args: string[], where: string): Promise<Measured> {
152 const flags: string[] = []
153 const paths: string[] = []
154 for (let i = 0; i < args.length; i += 1) {
155 const a = args[i] ?? ''
156 if (a === '--') {
157 paths.push(...args.slice(i + 1))
158 break
159 }
160 if (a === '-e' || a === '--exclude') {
161 flags.push(a, args[i + 1] ?? '')
162 i += 1
163 } else if (a.startsWith('--exclude=') || /^-e./.test(a)) {
164 flags.push(a)
165 } else if (/^-[a-zA-Z]+$/.test(a)) {
166 const kept = a.replace(/[finq]/g, '') // -n is added below; -f, -i and -q would change the dry run
167 if (kept !== '-') flags.push(kept)
168 } else if (!a.startsWith('-')) {
169 paths.push(a)
170 }
171 }
172 const run = await io.run(['git', 'clean', '-n', ...flags, '--', ...paths], where, 15000)
173 if (run?.exitCode !== 0) return { summary: 'git clean (could not dry-run it)', lines: [], more: 0, note: '' }
174 const gone = run.stdout.split('\n').filter(l => l.startsWith('Would remove ')).map(l => l.slice(13))
175 return {
176 summary: gone.length === 0 ? 'remove nothing: no untracked files match' : `remove ${plural(gone.length, 'untracked path')}`,
177 lines: gone.slice(0, LIST_MAX),
178 more: Math.max(0, gone.length - LIST_MAX),
179 note: "From git clean -n. Untracked files aren't in git, so they can't be recovered.",
180 }
181}
182
183async function measureDiscard(io: Io, risk: GitRisk, where: string): Promise<Measured> {
184 const status = await io.run(['git', 'status', '--porcelain'], where, 15000)
185 if (status?.exitCode !== 0) return { summary: `${risk.label} (not a git repo here?)`, lines: [], more: 0, note: '' }
186 const rows = status.stdout.split('\n').filter(l => l.length > 3 && !l.startsWith('??'))
187 // reset --hard drops staged and unstaged changes; checkout -- . drops unstaged ones.
188 const lost = risk.kind === 'git-reset' ? rows : rows.filter(l => l[1] !== ' ')
189 const stat = await io.run(['git', 'diff', '--shortstat', risk.kind === 'git-reset' ? 'HEAD' : '--'], where, 15000)
190 const target = risk.kind === 'git-reset' ? risk.args.find(a => !a.startsWith('-')) : undefined
191 const shortstat = stat?.stdout.trim() ?? ''
192 return {
193 summary: lost.length === 0 ? `discard nothing: no uncommitted changes${target ? ` (then move to ${target})` : ''}` : `discard uncommitted changes in ${plural(lost.length, 'file')}${target ? ` and move to ${target}` : ''}`,
194 lines: lost.slice(0, LIST_MAX).map(l => `${l.slice(0, 2)} ${l.slice(3)}`),
195 more: Math.max(0, lost.length - LIST_MAX),
196 note: shortstat !== '' ? `${shortstat}. Uncommitted changes can't be recovered.` : 'From git status --porcelain.',
197 }
198}
199
200async function measurePush(io: Io, args: string[], where: string): Promise<Measured> {
201 const positional = args.filter(a => !a.startsWith('-'))
202 const remote = positional[0] ?? 'origin'
203 const spec = (positional[1] ?? '').replace(/^\+/, '')
204 let [source = '', branch = ''] = spec.includes(':') ? spec.split(':') : [spec, spec]
205 branch = branch.replace(/^refs\/heads\//, '')
206 if (!branch || branch === 'HEAD') {
207 const head = await io.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], where, 10000)
208 branch = head?.stdout.trim() ?? ''
209 source = 'HEAD'
210 }
211 source = source || 'HEAD'
212 const ref = `${remote}/${branch}`
213 const known = await io.run(['git', 'rev-parse', '--verify', '--quiet', ref], where, 10000)
214 if (known?.exitCode !== 0) return { summary: `force-push to ${ref}`, lines: [], more: 0, note: `No local copy of ${ref}, so the commits it would drop can't be listed (no fetch is made).` }
215 const log = await io.run(['git', 'log', '--oneline', '--no-decorate', `${source}..${ref}`], where, 15000)
216 const dropped = (log?.stdout ?? '').split('\n').filter(l => l !== '')
217 return {
218 summary: dropped.length === 0 ? `force-push to ${ref}: drops no commits` : `force-push to ${ref}: drops ${plural(dropped.length, 'commit')}`,
219 lines: dropped.slice(0, LIST_MAX),
220 more: Math.max(0, dropped.length - LIST_MAX),
221 note: `Commits on ${ref} that ${source} doesn't have, as of the last fetch.`,
222 }
223}
224
225// Where each tool keeps its migration files. Listing files needs no database.
226const MIGRATION_DIRS: Record<string, string[]> = {
227 prisma: ['prisma/migrations'],
228 django: ['migrations'],
229 alembic: ['alembic/versions', 'migrations/versions'],
230 rails: ['db/migrate'],
231 knex: ['migrations', 'db/migrations'],
232 drizzle: ['drizzle', 'migrations'],
233 flyway: ['sql', 'db/migration', 'src/main/resources/db/migration'],
234 unknown: ['migrations', 'db/migrations', 'db/migrate'],
235}
236
237async function measureMigrations(io: Io, risk: Extract<Risk, { kind: 'migrate' }>, where: string): Promise<Measured> {
238 for (const rel of MIGRATION_DIRS[risk.tool] ?? []) {
239 const names = (await io.list(`${where}/${rel}`)).filter(n => !n.startsWith('.') && !n.startsWith('__') && n !== 'migration_lock.toml').sort()
240 if (names.length === 0) continue
241 const newest = names.slice(-LIST_MAX).reverse()
242 return {
243 summary: `run ${risk.label} against the configured database (${plural(names.length, 'migration')} in ${rel})`,
244 lines: newest,
245 more: Math.max(0, names.length - newest.length),
246 note: "Newest first. Which ones are pending can't be checked without connecting to the database, so none is assumed applied.",
247 }
248 }
249 return { summary: `run ${risk.label} against the configured database`, lines: [], more: 0, note: "Couldn't find the migration files to list them." }
250}
251
252async function measure(io: Io, risk: Risk, cwd: string): Promise<Measured> {
253 const where = await resolveDir(io, cwd, risk.dir)
254 if (where === null) return { summary: `${risk.label} in ${risk.dir}`, lines: [], more: 0, note: `Couldn't find the folder ${risk.dir}, so I couldn't measure what this would change.` }
255 switch (risk.kind) {
256 case 'rm':
257 return measureRm(io, risk, where)
258 case 'git-clean':
259 return measureClean(io, risk.args, where)
260 case 'git-push-force':
261 return measurePush(io, risk.args, where)
262 case 'migrate':
263 return measureMigrations(io, risk, where)
264 default:
265 return measureDiscard(io, risk, where)
266 }
267}
268
269/** Whether blast radius holds this call, and what it would change. */
270export async function inspectBlast(io: Io, e: Record<string, unknown>): Promise<Finding | null> {
271 if (String(e.tool) !== 'Bash') return null
272 const command = String(e.command ?? '')
273 const risks = classify(command)
274 if (risks.length === 0) return null
275 const cwd = await io.cwd()
276 const rules: string[] = []
277 const summaries: string[] = []
278 const lines: string[] = []
279 const notes: string[] = []
280 let more = 0
281 for (const risk of risks) {
282 let m: Measured
283 try {
284 m = await measure(io, risk, cwd)
285 } catch {
286 m = { summary: `${risk.label} (could not measure it)`, lines: [], more: 0, note: '' }
287 }
288 rules.push(`destructive: ${risk.label}`)
289 summaries.push(m.summary)
290 lines.push(...m.lines)
291 more += m.more
292 if (m.note) notes.push(m.note)
293 }
294 return {
295 rules: rules.map(mask),
296 command: mask(command),
297 affects: {
298 summary: mask(summaries.join('; ')),
299 lines: lines.slice(0, LIST_MAX).map(mask),
300 more: more + Math.max(0, lines.length - LIST_MAX),
301 note: mask(notes.join(' ')),
302 },
303 }
304}
305
306/** Merges the guard's and blast radius's findings for one call into one hold. */
307export function merge(a: Finding | null, b: Finding | null): Finding | null {
308 if (a === null) return b
309 if (b === null) return a
310 const lines = [...a.affects.lines, ...b.affects.lines]
311 return {
312 rules: [...a.rules, ...b.rules],
313 command: a.command,
314 affects: {
315 summary: `${a.affects.summary}; ${b.affects.summary}`,
316 lines: lines.slice(0, LIST_MAX),
317 more: a.affects.more + b.affects.more + Math.max(0, lines.length - LIST_MAX),
318 note: [a.affects.note, b.affects.note].filter(Boolean).join(' '),
319 },
320 }
321}
322
323/** For when the check itself failed: does this look destructive? */
324export const looksDestructive = (command: string): boolean => classify(command).length > 0
325hooks/detail.tsx 307 lines1// Feature 4, agent details: everything Code Buddy sees about one subagent,
2// gathered from agent.spawn, its tool calls, its model requests and its end,
3// and the view that shows it when you click Details on a row. Pure helpers
4// and drawing: register.tsx calls the engine and stores the record.
5
6import type { EngineInterface } from 'claude-code'
7
8import type { AgentDetail, AgentRun, TimelineEntry } from '../types'
9import { activityOf, fmtCost, fmtTime, fmtTokens, modelName } from './agents'
10import type { Usage } from './agents'
11import { mask } from './mask'
12import { BRAND, GREEN, detailHeaderSvg, labelSvg, pxOf, statsGridSvg, tokenBreakdownSvg } from './theme'
13
14type Ui = ReturnType<EngineInterface['ui']['resolve']>
15type Surface = 'terminal' | 'desktop' | 'mobile' | 'vscode'
16
17const PROMPT_MAX = 6000
18const REPORT_MAX = 8000
19const MESSAGE_MAX = 2000
20const TIMELINE_MAX = 60
21const LIST_MAX = 200
22const COMMANDS_MAX = 30
23
24const cap = (text: string, n: number): string => (text.length > n ? `${text.slice(0, n)}\n\n… ${text.length - n} more characters not shown` : text)
25const rel = (cwd: string, path: string): string => (cwd && path.startsWith(`${cwd}/`) ? path.slice(cwd.length + 1) : path)
26const addUnique = (list: string[], item: string): string[] => (item && !list.includes(item) ? [...list, item].slice(-LIST_MAX) : list)
27
28const READS = new Set(['Read', 'NotebookRead'])
29const EDITS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
30
31// ---- Building the record --------------------------------------------------------
32
33export type SpawnFacts = {
34 id: string
35 prompt: string
36 name?: string
37 cwd?: string
38 permissionMode?: string
39 background: boolean
40 fork: boolean
41 model?: string
42 parentModel: string
43 parentAgentId?: string
44 teammateId?: string
45}
46
47export function newDetail(f: SpawnFacts, at: number): AgentDetail {
48 return {
49 id: f.id,
50 prompt: mask(cap(f.prompt, PROMPT_MAX)),
51 name: f.name ? mask(f.name) : undefined,
52 cwd: f.cwd,
53 permissionMode: f.permissionMode,
54 isBackground: f.background,
55 isFork: f.fork,
56 requestedModel: f.model,
57 parentModel: f.parentModel,
58 parentAgentId: f.parentAgentId,
59 teammateId: f.teammateId,
60 usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
61 cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
62 lastContext: 0,
63 timeline: [],
64 toolCounts: {},
65 errors: 0,
66 holds: 0,
67 filesRead: [],
68 filesChanged: [],
69 commands: [],
70 lastMessage: '',
71 finalReport: '',
72 lastActivityAt: at,
73 }
74}
75
76/** What a tool call acted on, without the tool's name. */
77const targetOf = (e: Record<string, unknown>, cwd: string): string => activityOf(e, cwd).replace(/^[^·]*·\s?/, '')
78
79/** A tool call starts: a timeline entry, a count, a file read or a command. */
80export function onToolStart(d: AgentDetail, e: Record<string, unknown>, cwd: string, entryId: string, at: number): AgentDetail {
81 const tool = String(e.tool)
82 const name = tool.startsWith('mcp__') ? tool.split('__').slice(-1)[0] ?? tool : tool
83 const entry: TimelineEntry = { id: entryId, at, tool: name, target: targetOf(e, cwd), status: 'running' }
84 const path = typeof e.file_path === 'string' ? mask(rel(cwd, e.file_path)) : ''
85 const command = tool === 'Bash' && typeof e.command === 'string' ? mask(e.command.split('\n')[0] ?? '').slice(0, 200) : ''
86 return {
87 ...d,
88 timeline: [...d.timeline, entry].slice(-TIMELINE_MAX),
89 toolCounts: { ...d.toolCounts, [name]: (d.toolCounts[name] ?? 0) + 1 },
90 filesRead: READS.has(tool) ? addUnique(d.filesRead, path) : d.filesRead,
91 commands: command ? [...d.commands, command].slice(-COMMANDS_MAX) : d.commands,
92 lastActivityAt: at,
93 }
94}
95
96/** A tool call ends: ok, an error, or held by Code Buddy; a successful edit adds its file. */
97export function onToolEnd(d: AgentDetail, e: Record<string, unknown>, cwd: string, entryId: string, status: 'ok' | 'error' | 'held', at: number): AgentDetail {
98 const path = typeof e.file_path === 'string' ? mask(rel(cwd, e.file_path)) : ''
99 return {
100 ...d,
101 timeline: d.timeline.map(t => (t.id === entryId ? { ...t, status } : t)),
102 errors: d.errors + (status === 'error' ? 1 : 0),
103 holds: d.holds + (status === 'held' ? 1 : 0),
104 filesChanged: status === 'ok' && EDITS.has(String(e.tool)) ? addUnique(d.filesChanged, path) : d.filesChanged,
105 lastActivityAt: at,
106 }
107}
108
109/** One model request: tokens and cost by kind, the context it held, its effort and its text. */
110export function onStep(d: AgentDetail, u: Usage, cost: { input: number; output: number; cacheRead: number; cacheWrite: number }, effort: string | undefined, answer: string, at: number): AgentDetail {
111 return {
112 ...d,
113 usage: {
114 input: d.usage.input + (u.input_tokens || 0),
115 output: d.usage.output + (u.output_tokens || 0),
116 cacheRead: d.usage.cacheRead + (u.cache_read_input_tokens || 0),
117 cacheWrite: d.usage.cacheWrite + (u.cache_creation_input_tokens || 0),
118 },
119 cost: {
120 input: d.cost.input + cost.input,
121 output: d.cost.output + cost.output,
122 cacheRead: d.cost.cacheRead + cost.cacheRead,
123 cacheWrite: d.cost.cacheWrite + cost.cacheWrite,
124 },
125 lastContext: (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0),
126 effort: effort ?? d.effort,
127 lastMessage: answer.trim() ? mask(cap(answer.trim(), MESSAGE_MAX)) : d.lastMessage,
128 lastActivityAt: at,
129 }
130}
131
132/** It ended: its answer is the final report. */
133export function onFinish(d: AgentDetail, answer: string, reason: string, at: number): AgentDetail {
134 return {
135 ...d,
136 finalReport: answer.trim() ? mask(cap(answer.trim(), REPORT_MAX)) : d.finalReport,
137 endReason: reason,
138 timeline: d.timeline.map(t => (t.status === 'running' ? { ...t, status: 'error' } : t)),
139 lastActivityAt: at,
140 }
141}
142
143// ---- Drawing -------------------------------------------------------------------
144
145export type DetailActions = { back: () => void; copy: (text: string) => void }
146
147const STATUS_GLYPH = { running: '●', ok: '✓', error: '✗', held: '⏸' } as const
148const STATUS_COLOR = { running: BRAND.sky, ok: GREEN, error: BRAND.coral, held: BRAND.coral } as const
149const END_WORD: Record<string, string> = { answer: 'finished with an answer', aborted: 'stopped (interrupted)', error: 'ended with an error', refusal: 'ended with a refusal' }
150
151const windowOf = (model: string): number => (/haiku-4/i.test(model) ? 200_000 : 1_000_000)
152const sinceText = (ms: number): string => (ms < 60_000 ? `${Math.max(0, Math.round(ms / 1000))}s ago` : `${fmtTime(ms)} ago`)
153const pct = (n: number, of: number): string => (of > 0 ? `${Math.round((n / of) * 100)}%` : '0%')
154
155/** The detail view of one subagent. */
156export function drawAgentDetail(ui: Ui, surface: Surface, a: AgentRun, d: AgentDetail | undefined, now: number, columns: number, act: DetailActions) {
157 const { Box, Text, Button, Markdown, Code } = ui
158 const back = <Button key="back" label="◀ All agents" hotkey="b" onPress={() => act.back()} />
159 if (d === undefined) {
160 return (
161 <Box flexDirection="column" gap={1}>
162 {back}
163 <Text dimColor wrap="wrap">
164 No details were recorded for this subagent (it started before Code Buddy loaded).
165 </Text>
166 </Box>
167 )
168 }
169
170 const elapsedMs = (a.endedAt ?? Math.max(now, a.startedAt)) - a.startedAt
171 const title = a.description || d.name || a.type
172 const effort = d.effort ? ` · ${d.effort} effort` : ''
173 const meta = `${a.type} · ${modelName(a.model)}${effort}${d.isBackground ? ' · background' : ''}${d.isFork ? ' · fork' : ''}`
174 const row = { status: a.status, title, type: a.type, model: modelName(a.model), elapsed: fmtTime(elapsedMs), tokens: '', cost: '' }
175 const tools = Object.entries(d.toolCounts).sort((x, y) => y[1] - x[1])
176 const toolTotal = tools.reduce((s, [, n]) => s + n, 0)
177 const window = windowOf(a.model)
178 const stats: [string, string, string?][] = [
179 ['Tokens', fmtTokens(a.tokens)],
180 ['Cost', fmtCost(a.costUsd)],
181 ['Requests', String(a.steps)],
182 ['Tool calls', String(toolTotal)],
183 ['Errors', String(d.errors), d.holds ? `${d.holds} held` : undefined],
184 ['Context', fmtTokens(d.lastContext), pct(d.lastContext, window)],
185 ]
186 const parts: [string, string, string, number][] = [
187 ['Input', fmtTokens(d.usage.input), fmtCost(d.cost.input), d.usage.input],
188 ['Output', fmtTokens(d.usage.output), fmtCost(d.cost.output), d.usage.output],
189 ['Cache reads', fmtTokens(d.usage.cacheRead), fmtCost(d.cost.cacheRead), d.usage.cacheRead],
190 ['Cache writes', fmtTokens(d.usage.cacheWrite), fmtCost(d.cost.cacheWrite), d.usage.cacheWrite],
191 ]
192 const recent = [...d.timeline].reverse().slice(0, 15)
193 const facts: [string, string][] = [
194 ['Agent ID', a.agentId ?? a.id],
195 ['Status', a.status === 'running' ? `running for ${fmtTime(elapsedMs)}` : `${END_WORD[d.endReason ?? ''] ?? a.status} after ${fmtTime(elapsedMs)}`],
196 ['Model', `${a.model}${d.requestedModel && d.requestedModel !== a.model ? ` (asked for ${d.requestedModel})` : ''}`],
197 ['Parent model', d.parentModel],
198 ...(d.effort ? ([['Effort', d.effort]] as [string, string][]) : []),
199 ['Runs', `${d.isBackground ? 'in the background' : 'in the foreground'}${d.isFork ? ', as a fork' : ''}`],
200 ...(d.teammateId ? ([['Teammate', d.teammateId]] as [string, string][]) : []),
201 ...(d.parentAgentId ? ([['Started by', `agent ${d.parentAgentId}`]] as [string, string][]) : []),
202 ...(d.permissionMode ? ([['Permissions', d.permissionMode]] as [string, string][]) : []),
203 ...(d.cwd ? ([['Folder', d.cwd]] as [string, string][]) : []),
204 ['Code Buddy holds', String(d.holds)],
205 ]
206
207 const isDesktop = surface === 'desktop' && 'Svg' in ui
208 const W = pxOf(columns, 16, 240)
209 const label = (key: string, text: string) =>
210 isDesktop && 'Svg' in ui ? (
211 <ui.Svg key={key} source={labelSvg(W, text)} alt={text} width={W} height={18} />
212 ) : (
213 <Text key={key} bold color={BRAND.sky}>{`\n${text.toUpperCase()}`}</Text>
214 )
215
216 const header =
217 isDesktop && 'Svg' in ui ? (
218 (() => {
219 const card = detailHeaderSvg(W, row, meta)
220 return <ui.Svg key="head" source={card.source} alt={`${title}. ${row.elapsed}. ${meta}`} width={W} height={card.height} />
221 })()
222 ) : (
223 <Box key="head" flexDirection="column">
224 <Text wrap="wrap">
225 <Text backgroundColor={BRAND.royal} color={BRAND.white} bold>{` ${a.status.toUpperCase()} `}</Text>
226 <Text bold>{` ${title}`}</Text>
227 </Text>
228 <Text dimColor wrap="wrap">{`${meta} · ${row.elapsed}`}</Text>
229 </Box>
230 )
231 const numbers =
232 isDesktop && 'Svg' in ui ? (
233 (() => {
234 const g = statsGridSvg(W, stats)
235 const t = tokenBreakdownSvg(W, parts)
236 return (
237 <Box key="numbers" flexDirection="column" gap={1}>
238 <ui.Svg key="stats" source={g.source} alt={stats.map(([k, v, s]) => `${k} ${v}${s ? ` (${s})` : ''}`).join(', ')} width={W} height={g.height} />
239 <ui.Svg key="tokens" source={t.source} alt={parts.map(([k, n, c]) => `${k} ${n} ${c}`).join(', ')} width={W} height={t.height} />
240 </Box>
241 )
242 })()
243 ) : (
244 <Box key="numbers" flexDirection="column">
245 <Text wrap="wrap">{stats.map(([k, v, s]) => `${k} ${v}${s ? ` (${s})` : ''}`).join(' · ')}</Text>
246 <Text dimColor wrap="wrap">{parts.map(([k, n, c]) => `${k.toLowerCase()} ${n} ${c}`).join(' · ')}</Text>
247 </Box>
248 )
249
250 return (
251 <Box flexDirection="column" gap={isDesktop ? 1 : 0} paddingX={isDesktop ? 0 : 1}>
252 {back}
253 {header}
254 {a.status === 'running' && (
255 <Box key="now" flexDirection="column">
256 <Text wrap="wrap">
257 <Text color={BRAND.sky} bold>{'▸ Now '}</Text>
258 <Text color={BRAND.sky}>{a.activity || 'thinking…'}</Text>
259 </Text>
260 <Text dimColor>{`step ${a.steps} · last activity ${sinceText(now - d.lastActivityAt)}`}</Text>
261 </Box>
262 )}
263 {numbers}
264
265 {label('l-task', 'Task')}
266 <Markdown key="task" text={d.prompt || '_No brief recorded._'} />
267 <Button key="copy-task" label="Copy task" plain onPress={() => act.copy(d.prompt)} />
268
269 {(d.finalReport || d.lastMessage) && label('l-report', d.finalReport ? 'Final report' : 'Latest message')}
270 {(d.finalReport || d.lastMessage) && <Markdown key="report" text={d.finalReport || d.lastMessage} />}
271 {d.finalReport && <Button key="copy-report" label="Copy report" plain onPress={() => act.copy(d.finalReport)} />}
272
273 {label('l-timeline', `Timeline · last ${recent.length} of ${d.timeline.length}`)}
274 {recent.length === 0 && <Text key="t-none" dimColor>No tool calls yet.</Text>}
275 {recent.map(t => (
276 <Text key={`t-${t.id}`} wrap="truncate-end">
277 <Text dimColor>{`+${fmtTime(t.at - a.startedAt).padStart(5)} `}</Text>
278 <Text color={STATUS_COLOR[t.status]} bold>{`${STATUS_GLYPH[t.status]} `}</Text>
279 <Text bold>{`${t.tool} `}</Text>
280 <Text dimColor>{t.target}</Text>
281 </Text>
282 ))}
283
284 {tools.length > 0 && label('l-tools', `Tools used · ${toolTotal}`)}
285 {tools.length > 0 && <Text key="tools" wrap="wrap">{tools.map(([n, c]) => `${n} ${c}`).join(' · ')}</Text>}
286
287 {d.filesChanged.length > 0 && label('l-changed', `Files changed · ${d.filesChanged.length}`)}
288 {d.filesChanged.length > 0 && <Code key="changed" source={d.filesChanged.slice(-20).join('\n')} language="text" wrap="truncate-end" />}
289
290 {d.filesRead.length > 0 && label('l-read', `Files read · ${d.filesRead.length}`)}
291 {d.filesRead.length > 0 && <Code key="read" source={`${d.filesRead.slice(-12).join('\n')}${d.filesRead.length > 12 ? `\n… and ${d.filesRead.length - 12} more` : ''}`} language="text" wrap="truncate-end" />}
292
293 {d.commands.length > 0 && label('l-commands', `Commands run · ${d.commands.length}`)}
294 {d.commands.length > 0 && <Code key="commands" source={d.commands.slice(-8).join('\n')} language="bash" wrap="truncate-end" />}
295
296 {label('l-facts', 'Details')}
297 {facts.map(([k, v]) => (
298 <Text key={`f-${k}`} wrap="wrap">
299 <Text dimColor>{`${k.padEnd(16)} `}</Text>
300 <Text>{v}</Text>
301 </Text>
302 ))}
303 <Button key="back-end" label="◀ All agents" onPress={() => act.back()} />
304 </Box>
305 )
306}
307hooks/diff.ts 151 lines1// Feature 3, Replay: turns one file edit into a step with a unified diff.
2//
3// The line diff is adapted from replay-theater (claude-code-playground),
4// Copyright 2026 Anthropic PBC, licensed under the Apache License 2.0.
5// Modified for Code Buddy: ported to TypeScript; the edit is applied to the
6// file's text so the diff has real line numbers; common lines at the ends are
7// trimmed before the LCS; the result is unified-diff hunks, masked. See NOTICE.
8
9import type { ReplayStep } from '../types'
10import { mask } from './mask'
11
12type Op = { op: ' ' | '-' | '+'; t: string }
13
14const MAX_LCS_LINES = 400
15const CONTEXT = 3
16/** Diff lines kept per step; whole hunks first, the last one cut to fit. */
17export const MAX_DIFF_LINES = 160
18
19function splitLines(text: string): string[] {
20 if (text === '') return []
21 const lines = text.split('\n')
22 if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop()
23 return lines
24}
25
26/** Line operations from a to b: common ends trimmed, then an LCS on the middle. */
27export function lineOps(a: string[], b: string[]): { ops: Op[]; skipped: number } {
28 let start = 0
29 while (start < a.length && start < b.length && a[start] === b[start]) start += 1
30 let endA = a.length
31 let endB = b.length
32 while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
33 endA -= 1
34 endB -= 1
35 }
36 const ctxStart = Math.max(0, start - CONTEXT)
37 const head: Op[] = a.slice(ctxStart, start).map(t => ({ op: ' ', t }))
38 const tail: Op[] = a.slice(endA, Math.min(a.length, endA + CONTEXT)).map(t => ({ op: ' ', t }))
39 const midA = a.slice(start, endA)
40 const midB = b.slice(start, endB)
41 let mid: Op[]
42 if (midA.length > MAX_LCS_LINES || midB.length > MAX_LCS_LINES) {
43 mid = [...midA.map(t => ({ op: '-' as const, t })), ...midB.map(t => ({ op: '+' as const, t }))]
44 } else {
45 const n = midA.length
46 const m = midB.length
47 const dp = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0))
48 for (let i = n - 1; i >= 0; i -= 1) {
49 for (let j = m - 1; j >= 0; j -= 1) {
50 dp[i]![j] = midA[i] === midB[j] ? dp[i + 1]![j + 1]! + 1 : Math.max(dp[i + 1]![j]!, dp[i]![j + 1]!)
51 }
52 }
53 mid = []
54 let i = 0
55 let j = 0
56 while (i < n && j < m) {
57 if (midA[i] === midB[j]) {
58 mid.push({ op: ' ', t: midA[i]! })
59 i += 1
60 j += 1
61 } else if (dp[i + 1]![j]! >= dp[i]![j + 1]!) {
62 mid.push({ op: '-', t: midA[i]! })
63 i += 1
64 } else {
65 mid.push({ op: '+', t: midB[j]! })
66 j += 1
67 }
68 }
69 while (i < n) mid.push({ op: '-', t: midA[i++]! })
70 while (j < m) mid.push({ op: '+', t: midB[j++]! })
71 }
72 return { ops: [...head, ...mid, ...tail], skipped: ctxStart }
73}
74
75/** Unified-diff hunks over the ops; `skipped` lines precede the first op in both files. */
76function hunks(ops: Op[], skipped: number): string[][] {
77 const changed = ops.map((o, i) => (o.op === ' ' ? -1 : i)).filter(i => i >= 0)
78 if (changed.length === 0) return []
79 // Group changes whose gap is small enough to share context.
80 const groups: [number, number][] = []
81 for (const i of changed) {
82 const last = groups[groups.length - 1]
83 if (last && i - last[1] <= CONTEXT * 2 + 1) last[1] = i
84 else groups.push([i, i])
85 }
86 const out: string[][] = []
87 for (const [first, lastChange] of groups) {
88 const from = Math.max(0, first - CONTEXT)
89 const to = Math.min(ops.length, lastChange + CONTEXT + 1)
90 const before = ops.slice(0, from)
91 const oldBefore = skipped + before.filter(o => o.op !== '+').length
92 const newBefore = skipped + before.filter(o => o.op !== '-').length
93 out.push([`@@${oldBefore}@@${newBefore}`, ...ops.slice(from, to).map(o => `${o.op}${o.t}`)])
94 }
95 return out
96}
97
98/** The header of a hunk from its lines, counts recomputed so a cut hunk still parses. */
99function header(oldBefore: number, newBefore: number, lines: string[]): string {
100 const oldCount = lines.filter(l => !l.startsWith('+')).length
101 const newCount = lines.filter(l => !l.startsWith('-')).length
102 const oldStart = oldCount === 0 ? oldBefore : oldBefore + 1
103 const newStart = newCount === 0 ? newBefore : newBefore + 1
104 return `@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`
105}
106
107/** One replay step: the file's text before and after the edit, as a masked unified diff. */
108export function buildStep(file: string, tool: string, note: string, before: string, after: string, isNew: boolean): ReplayStep {
109 const { ops, skipped } = lineOps(splitLines(before), splitLines(after))
110 const adds = ops.filter(o => o.op === '+').length
111 const dels = ops.filter(o => o.op === '-').length
112 const body: string[] = []
113 let cut = 0
114 for (const h of hunks(ops, skipped)) {
115 const [mark = '', ...lines] = h
116 const [, ob = '0', nb = '0'] = mark.split('@@')
117 const room = MAX_DIFF_LINES - body.length - 1
118 if (room < 2) {
119 cut += lines.length
120 continue
121 }
122 const kept = lines.slice(0, room)
123 cut += lines.length - kept.length
124 body.push(header(Number(ob), Number(nb), kept), ...kept.map(mask))
125 }
126 const path = mask(file)
127 const diff = body.length === 0 ? '' : [`--- ${isNew ? '/dev/null' : `a/${path}`}`, `+++ b/${path}`, ...body].join('\n')
128 return { file: path, tool, note: cut > 0 ? `${note}${note ? ' · ' : ''}${cut} more lines not shown` : note, diff, adds, dels, isNew }
129}
130
131/** The file's text after an Edit or MultiEdit, the edits applied as the tool would. */
132export function applyEdits(before: string, edits: { old_string?: unknown; new_string?: unknown; replace_all?: unknown }[]): string | null {
133 let text = before
134 for (const ed of edits) {
135 const from = String(ed.old_string ?? '')
136 const to = String(ed.new_string ?? '')
137 if (from === '') {
138 text = to + text
139 continue
140 }
141 const at = text.indexOf(from)
142 if (at < 0) return null // the tool would fail; nothing to record
143 text = ed.replace_all === true ? text.split(from).join(to) : text.slice(0, at) + to + text.slice(at + from.length)
144 }
145 return text
146}
147
148/** Relative to the session folder when inside it. */
149export const relPath = (cwd: string, path: string): string =>
150 !path ? '(unknown file)' : cwd && path.startsWith(`${cwd}/`) ? path.slice(cwd.length + 1) : path
151hooks/control.tsx 162 lines1// Feature 5, the control panel: pause, resume, or switch off each feature, and
2// change the settings, from one pane. Drawing only: register.tsx owns the
3// pauses and writes the settings.
4
5import type { EngineInterface } from 'claude-code'
6
7import { FEATURES } from './features'
8import type { Feature } from './features'
9import { BRAND, CONTROL_HEADER_H, GREEN, controlHeaderSvg, featureRowSvg, labelSvg, pxOf } from './theme'
10import type { FeatureState } from './theme'
11
12export const CONTROL_PANE = 'code-buddy-control'
13
14type Ui = ReturnType<EngineInterface['ui']['resolve']>
15type Surface = 'terminal' | 'desktop' | 'mobile' | 'vscode'
16
17export const PAUSE_SHORT_MS = 30 * 60 * 1000
18
19export type ControlView = {
20 version: string
21 held: number
22 features: { id: Feature; state: FeatureState; left: string }[]
23 settings: { production: string; staging: string; branch: string; budget: string; autoOpen: boolean }
24}
25
26export type SettingField = 'production' | 'staging' | 'branch' | 'budget'
27
28export type ControlActions = {
29 pause: (f: Feature | 'all', ms: number) => void
30 resume: (f: Feature | 'all') => void
31 setOn: (f: Feature, on: boolean) => void
32 set: (field: SettingField, value: string) => void
33 setAutoOpen: (on: boolean) => void
34}
35
36export const controlRows = (): number => 40
37
38const SETTING_FIELDS: { field: SettingField; label: string; placeholder: string; hint: string }[] = [
39 { field: 'production', label: 'Production domains', placeholder: 'example.com, *.example.com', hint: 'Calls that target one are held. *.example.com matches every subdomain.' },
40 { field: 'staging', label: 'Staging domains', placeholder: 'staging.example.com', hint: 'Production wins on overlap: only an exact host listed here goes through.' },
41 { field: 'branch', label: 'Protected branch', placeholder: 'main', hint: 'Pushes to it and merges into it are held. Comma-separated; * matches within a name.' },
42 { field: 'budget', label: 'Subagent budget (USD)', placeholder: 'off', hint: 'Estimated subagent spend per session; past it the agents bar turns coral. 0 or off turns it off.' },
43]
44
45export function summaryOf(v: ControlView): string {
46 const on = v.features.filter(f => f.state === 'on').length
47 const paused = v.features.filter(f => f.state === 'paused').length
48 return `${on} of ${v.features.length} features on${paused ? ` · ${paused} paused` : ''} · ${v.held} held this session`
49}
50
51/** The control panel: features with Pause / Resume / Turn off, then the settings. */
52export function drawControl(ui: Ui, surface: Surface, v: ControlView, columns: number, act: ControlActions) {
53 const { Box, Text, Button } = ui
54 const isDesktop = surface === 'desktop' && 'Svg' in ui
55 const W = pxOf(columns, 16, 260)
56 const label = (key: string, text: string) =>
57 isDesktop && 'Svg' in ui ? (
58 <ui.Svg key={key} source={labelSvg(W, text)} alt={text} width={W} height={18} />
59 ) : (
60 <Text key={key} bold color={BRAND.sky}>{`\n${text.toUpperCase()}`}</Text>
61 )
62 const anyPaused = v.features.some(f => f.state === 'paused')
63
64 const featureRows = v.features.map(f => {
65 const meta = FEATURES.find(x => x.id === f.id)
66 const name = meta?.name ?? f.id
67 const what = meta?.what ?? ''
68 const buttons =
69 f.state === 'on' ? (
70 <Box key={`b-${f.id}`} flexDirection="row" gap={1}>
71 <Button key={`pause30-${f.id}`} label="Pause 30m" onPress={() => act.pause(f.id, PAUSE_SHORT_MS)} />
72 <Button key={`pause-${f.id}`} label="Pause" onPress={() => act.pause(f.id, 0)} />
73 <Button key={`off-${f.id}`} label="Turn off" plain onPress={() => act.setOn(f.id, false)} />
74 </Box>
75 ) : f.state === 'paused' ? (
76 <Box key={`b-${f.id}`} flexDirection="row" gap={1}>
77 <Button key={`resume-${f.id}`} label="Resume" variant="primary" onPress={() => act.resume(f.id)} />
78 </Box>
79 ) : (
80 <Box key={`b-${f.id}`} flexDirection="row" gap={1}>
81 <Button key={`on-${f.id}`} label="Turn on" variant="primary" onPress={() => act.setOn(f.id, true)} />
82 </Box>
83 )
84 if (isDesktop && 'Svg' in ui) {
85 const row = featureRowSvg(W, name, what, f.state, f.left)
86 const alt = `${name}: ${f.state === 'paused' ? `paused, ${f.left}` : f.state}. ${what}`
87 return (
88 <Box key={`f-${f.id}`} flexDirection="column" gap={1}>
89 <ui.Svg key={`s-${f.id}`} source={row.source} alt={alt} width={W} height={row.height} />
90 {buttons}
91 </Box>
92 )
93 }
94 const color = f.state === 'on' ? GREEN : f.state === 'off' ? undefined : BRAND.coral
95 const chip = f.state === 'on' ? 'on' : f.state === 'off' ? 'off' : `paused · ${f.left}`
96 return (
97 <Box key={`f-${f.id}`} flexDirection="column" marginBottom={1}>
98 <Text wrap="truncate-end">
99 <Text bold>{name}</Text>
100 <Text color={color} dimColor={f.state === 'off'} bold>{` ● ${chip}`}</Text>
101 </Text>
102 <Text dimColor wrap="wrap">{what}</Text>
103 {buttons}
104 </Box>
105 )
106 })
107
108 const hasInput = 'Input' in ui
109 const settingRows = SETTING_FIELDS.map(s => {
110 const value = v.settings[s.field]
111 if (hasInput && 'Input' in ui) {
112 return (
113 <Box key={`set-${s.field}`} flexDirection="column">
114 <ui.Input key={`in-${s.field}`} label={s.label} placeholder={s.placeholder} value={value} submitLabel="save" onSubmit={text => act.set(s.field, text)} />
115 <Text dimColor wrap="wrap">{s.hint}</Text>
116 </Box>
117 )
118 }
119 return (
120 <Text key={`set-${s.field}`} wrap="wrap">
121 <Text bold>{`${s.label}: `}</Text>
122 <Text>{value || '(none)'}</Text>
123 </Text>
124 )
125 })
126
127 return (
128 <Box flexDirection="column" gap={isDesktop ? 1 : 0} paddingX={isDesktop ? 0 : 1}>
129 {isDesktop && 'Svg' in ui ? (
130 <ui.Svg key="head" source={controlHeaderSvg(W, v.version, summaryOf(v))} alt={`Code Buddy ${v.version}: ${summaryOf(v)}`} width={W} height={CONTROL_HEADER_H} />
131 ) : (
132 <Text key="head" wrap="wrap">
133 <Text backgroundColor={BRAND.royal} color={BRAND.white} bold>{' ≋ CODE BUDDY '}</Text>
134 <Text dimColor>{` ${v.version ? `v${v.version} · ` : ''}${summaryOf(v)}`}</Text>
135 </Text>
136 )}
137 <Box key="all" flexDirection="row" gap={1}>
138 <Button key="pause30-all" label="Pause all 30m" onPress={() => act.pause('all', PAUSE_SHORT_MS)} />
139 {anyPaused && <Button key="resume-all" label="Resume all" variant="primary" onPress={() => act.resume('all')} />}
140 </Box>
141
142 {label('l-features', 'Features')}
143 {featureRows}
144 <Text key="pause-note" dimColor italic wrap="wrap">
145 Pauses last for this session only. Turn off keeps a feature off in every session until you turn it on again.
146 </Text>
147
148 {label('l-settings', 'Settings')}
149 {settingRows}
150 <Box key="autoopen" flexDirection="row" gap={1}>
151 <Text>{`Auto-open agents panel: ${v.settings.autoOpen ? 'on' : 'off'}`}</Text>
152 <Button key="autoopen-toggle" label={v.settings.autoOpen ? 'Turn off' : 'Turn on'} plain onPress={() => act.setAutoOpen(!v.settings.autoOpen)} />
153 </Box>
154 <Text key="settings-note" dimColor italic wrap="wrap">
155 {hasInput
156 ? 'Edit a field and press Enter to save. Settings apply to every session; Code Buddy reloads with them.'
157 : 'Change settings with /code-buddy config <setting> <value>.'}
158 </Text>
159 </Box>
160 )
161}
162hooks/features.ts 89 lines1// Pausing and switching off features. Each of the four can be paused for this
2// session (for a while, or until resumed) or turned off in the settings.
3// Pure helpers: register.tsx stores the pauses in session state.
4
5export type Feature = 'guard' | 'blast' | 'replay' | 'agents'
6
7export const FEATURES: { id: Feature; name: string; key: string; words: string[]; what: string }[] = [
8 { id: 'guard', name: 'Staging guard', key: 'stagingGuard', words: ['guard', 'staging', 'stagingguard'], what: 'holds calls to production, live keys, protected-branch pushes and deploys' },
9 { id: 'blast', name: 'Blast radius', key: 'blastRadius', words: ['blast', 'blastradius', 'destructive'], what: 'holds destructive shell commands' },
10 { id: 'replay', name: 'Replay', key: 'replay', words: ['replay', 'edits'], what: "records each turn's edits for /code-buddy replay" },
11 { id: 'agents', name: 'Agents panel', key: 'agentsPanel', words: ['agents', 'agentspanel', 'panel', 'subagents'], what: 'tracks subagents in the band and the panel' },
12]
13
14export const nameOf = (f: Feature): string => FEATURES.find(x => x.id === f)?.name ?? f
15
16/** A word the person typed → one feature, all of them, or null. */
17export function featureOf(word: string): Feature | 'all' | null {
18 const w = word.toLowerCase().replace(/[^a-z]/g, '')
19 if (w === 'all' || w === 'everything') return 'all'
20 return FEATURES.find(f => f.words.includes(w))?.id ?? null
21}
22
23/** "30m", "2h", "90s", "45" (minutes) → milliseconds; "" → 0, until resumed; null when not a duration. */
24export function parseDuration(text: string): number | null {
25 const t = text.trim().toLowerCase()
26 if (!t || t === 'session' || t === 'forever') return 0
27 const m = /^(\d+(?:\.\d+)?)\s*(s|sec|secs|seconds?|m|min|mins|minutes?|h|hr|hrs|hours?)?$/.exec(t)
28 if (!m) return null
29 const n = Number(m[1])
30 const unit = (m[2] ?? 'm')[0]
31 const ms = unit === 's' ? n * 1000 : unit === 'h' ? n * 3_600_000 : n * 60_000
32 return ms > 0 ? Math.round(ms) : null
33}
34
35/** Paused features: when each pause ends (ms since the epoch), 0 for until resumed. */
36export type Pauses = Partial<Record<Feature, number>>
37
38export const isPaused = (p: Pauses, f: Feature, now: number): boolean => {
39 const until = p[f]
40 return until !== undefined && (until === 0 || until > now)
41}
42
43/** "28m left", "1h 5m left", "40s left" or "until resumed". */
44export function leftText(p: Pauses, f: Feature, now: number): string {
45 const until = p[f]
46 if (until === undefined) return ''
47 if (until === 0) return 'until resumed'
48 const s = Math.max(0, Math.ceil((until - now) / 1000))
49 if (s < 60) return `${s}s left`
50 const m = Math.ceil(s / 60)
51 return m < 60 ? `${m}m left` : `${Math.floor(m / 60)}h ${m % 60}m left`
52}
53
54/** The pauses with ended ones dropped, and which ended. */
55export function expire(p: Pauses, now: number): { pauses: Pauses; ended: Feature[] } {
56 const pauses: Pauses = {}
57 const ended: Feature[] = []
58 for (const f of Object.keys(p) as Feature[]) {
59 const until = p[f]
60 if (until === undefined) continue
61 if (until !== 0 && until <= now) ended.push(f)
62 else pauses[f] = until
63 }
64 return { pauses, ended }
65}
66
67/**
68 * Which features the settings leave on. `guard: false` (the older master switch)
69 * also turns both hold features off.
70 */
71export function enabledOf(options: Record<string, unknown>): Record<Feature, boolean> {
72 const master = options.guard !== false && options.guard !== 'off'
73 return {
74 guard: master && options.stagingGuard !== false,
75 blast: master && options.blastRadius !== false,
76 replay: options.replay !== false,
77 agents: options.agentsPanel !== false,
78 }
79}
80
81/** 30 min, 2 h, 1 h 30 min, 45 s. */
82export function durText(ms: number): string {
83 const s = Math.round(ms / 1000)
84 if (s < 60) return `${s} s`
85 const m = Math.round(s / 60)
86 if (m < 60) return `${m} min`
87 return m % 60 ? `${Math.floor(m / 60)} h ${m % 60} min` : `${m / 60} h`
88}
89hooks/guard.ts 375 lines1// Feature 1, Staging guard: decides whether a tool call should be held, and
2// works out what it would affect. Reads the working copy with local git only:
3// no network requests, no model calls, no environment variables.
4
5import type { Affects } from '../types'
6import { liveStripeKeys, mask } from './mask'
7import { gitParts, segments } from './shell'
8import type { Segment } from './shell'
9
10/** What the guard may read, handed in by register.tsx (only it calls the engine). */
11export type Io = {
12 cwd: () => Promise<string>
13 /** Runs a local command; null when it could not start. */
14 run: (argv: string[], cwd: string, timeoutMs: number) => Promise<{ exitCode: number; stdout: string } | null>
15 /** The names in a folder; empty when unreadable. */
16 list: (dir: string) => Promise<string[]>
17}
18
19export type GuardConfig = {
20 production: string[]
21 staging: string[]
22 branches: string[]
23 isOn: boolean
24}
25
26/** What a held call is held for. Every text in it is masked. */
27export type Finding = {
28 rules: string[]
29 command: string
30 affects: Affects
31}
32
33const LIST_MAX = 10
34
35export const parseList = (text: unknown): string[] =>
36 String(text ?? '')
37 .split(/[,\s]+/)
38 .map(s => s.trim().toLowerCase().replace(/\.$/, ''))
39 .filter(Boolean)
40
41export function configOf(options: Record<string, unknown>): GuardConfig {
42 return {
43 production: parseList(options.productionDomains),
44 staging: parseList(options.stagingDomains),
45 branches: parseList(options.protectedBranch).length ? parseList(options.protectedBranch) : ['main'],
46 isOn: options.guard !== false && options.guard !== 'off',
47 }
48}
49
50// ---- Domains ---------------------------------------------------------------
51
52const HOST = /(?<![A-Za-z0-9_%+.-])((?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63})\.?(?![A-Za-z0-9_-])/g
53// A URL's host, or a whole value that is a bare host (a browser's address bar).
54const URL_HOST = /[A-Za-z][A-Za-z0-9+.-]*:\/\/(?:[^\s/@]*@)?([A-Za-z0-9.-]+)/g
55
56/** Every host named in shell text. */
57export function hostsIn(text: string): string[] {
58 const out = new Set<string>()
59 for (const m of text.matchAll(HOST)) out.add((m[1] ?? '').toLowerCase())
60 return [...out]
61}
62
63/** Hosts in a browser or fetch tool's values: URLs, or a value that is just a host. */
64export function urlHostsIn(text: string): string[] {
65 const out = new Set<string>()
66 for (const m of text.matchAll(URL_HOST)) out.add((m[1] ?? '').toLowerCase().replace(/\.$/, ''))
67 const bare = text.trim().toLowerCase().replace(/[/?#].*$/, '')
68 if (/^(?:[a-z0-9-]+\.)+[a-z]{2,63}$/.test(bare)) out.add(bare)
69 return [...out]
70}
71
72export const matchesHost = (host: string, pattern: string): boolean =>
73 pattern.startsWith('*.') ? host.endsWith(pattern.slice(1)) : host === pattern
74
75/**
76 * Production wins on overlap: a host is let through only when an exact
77 * (non-wildcard) staging entry names it. Returns null when it isn't held.
78 */
79export function productionMatch(host: string, cfg: GuardConfig): { pattern: string; alsoStaging: string | undefined } | null {
80 const pattern = cfg.production.find(p => matchesHost(host, p))
81 if (pattern === undefined) return null
82 if (cfg.staging.some(p => !p.startsWith('*.') && p === host)) return null
83 return { pattern, alsoStaging: cfg.staging.find(p => matchesHost(host, p)) }
84}
85
86function domainFindings(hosts: string[], cfg: GuardConfig, verb: string): { rules: string[]; lines: string[]; notes: string[] } {
87 const rules: string[] = []
88 const lines: string[] = []
89 const notes: string[] = []
90 for (const host of hosts) {
91 const hit = productionMatch(host, cfg)
92 if (!hit) continue
93 rules.push(`production domain: ${host}`)
94 lines.push(`${verb} ${host} (matches ${hit.pattern})`)
95 if (hit.alsoStaging) notes.push(`${host} also matches staging ${hit.alsoStaging}; production wins.`)
96 }
97 return { rules, lines, notes }
98}
99
100// ---- Branches --------------------------------------------------------------
101
102const globRe = (glob: string): RegExp =>
103 new RegExp(`^${glob.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*')}$`)
104
105export const isProtected = (branch: string | undefined, cfg: GuardConfig): boolean =>
106 branch !== undefined && cfg.branches.some(b => globRe(b).test(branch.replace(/^refs\/heads\//, '')))
107
108const absDir = (cwd: string, dir: string | null): string | null => {
109 if (dir === null) return cwd
110 if (dir === '-' || dir.startsWith('~')) return null // depends on the shell's state
111 return dir.startsWith('/') ? dir : `${cwd}/${dir}`
112}
113
114async function currentBranch(io: Io, dir: string | null): Promise<string | undefined> {
115 if (dir === null) return undefined
116 const run = await io.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], dir, 10000)
117 const out = run?.stdout.trim()
118 return run?.exitCode === 0 && out && out !== 'HEAD' ? out : undefined
119}
120
121async function gitLines(io: Io, dir: string | null, argv: string[]): Promise<string[] | null> {
122 if (dir === null) return null
123 const run = await io.run(['git', ...argv], dir, 15000)
124 return run?.exitCode === 0 ? run.stdout.split('\n').filter(l => l !== '') : null
125}
126
127// Options of git push that take a value, so the value isn't read as the remote.
128const PUSH_VALUE_OPTIONS = new Set(['-o', '--push-option', '--repo', '--receive-pack', '--exec'])
129
130function positional(args: string[], valued: Set<string>): string[] {
131 const out: string[] = []
132 for (let i = 0; i < args.length; i += 1) {
133 const a = args[i] ?? ''
134 if (a === '--') {
135 out.push(...args.slice(i + 1))
136 break
137 }
138 if (valued.has(a)) i += 1
139 else if (!a.startsWith('-')) out.push(a)
140 }
141 return out
142}
143
144type Hit = { rule: string; summary: string; lines: string[]; note?: string }
145
146async function gitFindings(io: Io, seg: Segment, cwd: string, cfg: GuardConfig, switched: { branch?: string }): Promise<Hit[]> {
147 const { dir, sub, rest } = gitParts(seg)
148 const where = absDir(cwd, dir)
149 const hits: Hit[] = []
150 const branchNow = async () => switched.branch ?? (await currentBranch(io, where))
151
152 if (sub === 'checkout' || sub === 'switch') {
153 const pos = positional(rest, new Set(['-b', '-B', '-c', '-C', '--orphan']))
154 const created = rest.findIndex(a => ['-b', '-B', '-c', '-C', '--orphan'].includes(a))
155 const target = created >= 0 ? rest[created + 1] : pos.length === 1 ? pos[0] : undefined
156 if (target && target !== '.' && target !== '--') switched.branch = target
157 return hits
158 }
159
160 if (sub === 'push') {
161 const flags = rest.filter(a => a.startsWith('-'))
162 const pos = positional(rest, PUSH_VALUE_OPTIONS)
163 const remote = pos[0] ?? 'origin'
164 const specs = pos.slice(1)
165 if (flags.some(f => f === '--all' || f === '--mirror' || f === '--branches')) {
166 hits.push({ rule: `push to protected branch: ${flags.find(f => ['--all', '--mirror', '--branches'].includes(f))} includes ${cfg.branches.join(', ')}`, summary: `push every local branch to ${remote}, ${cfg.branches.join(', ')} included`, lines: [] })
167 return hits
168 }
169 const deleting = flags.includes('-d') || flags.includes('--delete')
170 const targets: { src: string; dst: string }[] = []
171 if (specs.length === 0) {
172 if (flags.includes('--tags')) return hits
173 const b = await branchNow()
174 if (b === undefined) {
175 hits.push({ rule: 'push to protected branch: could not tell the current branch', summary: `push the current branch to ${remote}`, lines: [], note: "Couldn't read the current branch, so this is held to be safe." })
176 return hits
177 }
178 targets.push({ src: 'HEAD', dst: b })
179 }
180 for (const spec of specs) {
181 const s = spec.replace(/^\+/, '')
182 const [src = '', dst = ''] = s.includes(':') ? s.split(':') : [s, s]
183 const name = dst.replace(/^refs\/heads\//, '')
184 targets.push({ src: src || '(delete)', dst: name === 'HEAD' ? ((await branchNow()) ?? 'HEAD') : name })
185 }
186 for (const t of targets) {
187 if (!isProtected(t.dst, cfg)) continue
188 if (deleting || t.src === '(delete)') {
189 hits.push({ rule: `push to protected branch: deletes ${remote}/${t.dst}`, summary: `delete ${t.dst} on ${remote}`, lines: [] })
190 continue
191 }
192 const commits = await gitLines(io, where, ['log', '--oneline', '--no-decorate', `${remote}/${t.dst}..${t.src}`])
193 hits.push({
194 rule: `push to protected branch: ${remote}/${t.dst}`,
195 summary: commits === null ? `push ${t.src} to ${remote}/${t.dst}` : `push ${commits.length} ${commits.length === 1 ? 'commit' : 'commits'} to ${remote}/${t.dst}`,
196 lines: (commits ?? []).slice(0, LIST_MAX),
197 note: commits === null ? `No local copy of ${remote}/${t.dst}, so the commits can't be listed (no fetch is made).` : `Commits ${t.src} has that ${remote}/${t.dst} doesn't, as of the last fetch.`,
198 })
199 }
200 return hits
201 }
202
203 if (sub === 'merge' || sub === 'pull') {
204 if (rest.some(a => ['--abort', '--continue', '--quit', '--skip'].includes(a))) return hits
205 const b = await branchNow()
206 if (!isProtected(b, cfg)) return hits
207 const pos = positional(rest, new Set(['-m', '-s', '-X', '--strategy', '--strategy-option', '-F', '--file']))
208 const from = sub === 'merge' ? pos : pos.slice(1)
209 if (sub === 'pull' && (from.length === 0 || from.every(f => isProtected(f.replace(/^.*:/, ''), cfg)))) return hits // updating main from its own upstream
210 const source = from.join(' ') || '(upstream)'
211 const commits = sub === 'merge' && from.length === 1 ? await gitLines(io, where, ['log', '--oneline', '--no-decorate', `HEAD..${from[0]}`]) : null
212 hits.push({
213 rule: `merge into protected branch: ${b}`,
214 summary: commits === null ? `merge ${source} into ${b}` : `merge ${commits.length} ${commits.length === 1 ? 'commit' : 'commits'} from ${source} into ${b}`,
215 lines: (commits ?? []).slice(0, LIST_MAX),
216 note: '',
217 })
218 }
219 return hits
220}
221
222// ---- Deploys ---------------------------------------------------------------
223
224async function deployFindings(io: Io, seg: Segment, cwd: string): Promise<Hit[]> {
225 const { cmd, args } = seg
226 const where = absDir(cwd, seg.dir)
227 const place = seg.dir ?? 'the session folder'
228 const valueOf = (names: string[]): string | undefined => {
229 for (let i = 0; i < args.length; i += 1) {
230 const a = args[i] ?? ''
231 for (const n of names) {
232 if (a === n) return args[i + 1]
233 if (a.startsWith(`${n}=`)) return a.slice(n.length + 1)
234 }
235 }
236 return undefined
237 }
238
239 if ((cmd === 'vercel' || cmd === 'vc') && (args.includes('--prod') || args.includes('--production') || valueOf(['--target']) === 'production')) {
240 return [{ rule: 'deploy: vercel --prod', summary: `deploy ${place} to Vercel production`, lines: [], note: 'Production traffic is served from this build once it finishes.' }]
241 }
242 if ((cmd === 'terraform' || cmd === 'tofu') && args.includes('apply')) {
243 const tf = where ? (await io.list(where)).filter(n => n.endsWith('.tf')) : []
244 const plan = args.find(a => a.endsWith('.tfplan') || a.endsWith('.plan'))
245 return [{
246 rule: `deploy: ${cmd} apply`,
247 summary: plan ? `apply the saved plan ${plan}` : `apply Terraform changes in ${place}`,
248 lines: tf.slice(0, LIST_MAX),
249 note: args.some(a => a.startsWith('-auto-approve') || a.startsWith('--auto-approve')) ? "-auto-approve skips Terraform's own confirmation." : '',
250 }]
251 }
252 if (cmd === 'cdk' && args.includes('deploy')) {
253 const stacks = positional(args.slice(args.indexOf('deploy') + 1), new Set(['--profile', '-c', '--context', '--app', '-a', '--role-arn', '-r', '--parameters', '--outputs-file', '-O']))
254 return [{ rule: 'deploy: cdk deploy', summary: args.includes('--all') || stacks.length === 0 ? 'deploy every stack in the CDK app' : `deploy ${stacks.length} CDK ${stacks.length === 1 ? 'stack' : 'stacks'}`, lines: stacks.slice(0, LIST_MAX), note: args.includes('--require-approval') ? '' : '' }]
255 }
256 if (cmd === 'kubectl' && args.includes('apply')) {
257 const files: string[] = []
258 for (let i = 0; i < args.length; i += 1) {
259 const a = args[i] ?? ''
260 if (a === '-f' || a === '--filename' || a === '-k' || a === '--kustomize') files.push(args[i + 1] ?? '')
261 else if (a.startsWith('--filename=') || a.startsWith('-f=')) files.push(a.replace(/^[^=]*=/, ''))
262 }
263 let context = valueOf(['--context'])
264 if (!context) {
265 const run = await io.run(['kubectl', 'config', 'current-context'], where ?? cwd, 5000)
266 if (run?.exitCode === 0) context = run.stdout.trim()
267 }
268 const ns = valueOf(['-n', '--namespace'])
269 return [{ rule: 'deploy: kubectl apply', summary: `apply ${files.length ? files.join(', ') : 'manifests'} to ${context ? `context ${context}` : 'the current kubectl context'}${ns ? `, namespace ${ns}` : ''}`, lines: [], note: args.some(a => a.startsWith('--dry-run')) ? 'This has --dry-run, but is held anyway.' : '' }]
270 }
271 if ((cmd === 'docker' || cmd === 'podman') && args.includes('push')) {
272 const image = positional(args.slice(args.indexOf('push') + 1), new Set())[0] ?? '(image)'
273 return [{ rule: `deploy: ${cmd} push`, summary: `push image ${image} to its registry`, lines: [], note: '' }]
274 }
275 if (cmd === 'gh' && args[0] === 'pr' && args[1] === 'merge') {
276 return [{ rule: 'merge into protected branch: gh pr merge', summary: `merge pull request ${args[2] && !args[2].startsWith('-') ? args[2] : '(current branch)'} into its base branch`, lines: [], note: "The base branch isn't checked (that needs the network); it is usually main." }]
277 }
278 return []
279}
280
281// ---- Tools -----------------------------------------------------------------
282
283const EDIT_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
284const WEBBY = /fetch|http|request|curl|browser|chrome|playwright|puppeteer|navigate|preview_start|web/i
285
286const strings = (value: unknown, out: string[] = []): string[] => {
287 if (typeof value === 'string') out.push(value)
288 else if (Array.isArray(value)) value.forEach(v => strings(v, out))
289 else if (value && typeof value === 'object') Object.values(value).forEach(v => strings(v, out))
290 return out
291}
292
293const finding = (rules: string[], command: string, summary: string, lines: string[], notes: string[]): Finding => ({
294 rules: rules.map(mask),
295 command: mask(command),
296 affects: {
297 summary: mask(summary),
298 lines: lines.slice(0, LIST_MAX).map(mask),
299 more: Math.max(0, lines.length - LIST_MAX),
300 note: mask(notes.filter(Boolean).join(' ')),
301 },
302})
303
304/** Whether the guard holds this call, and why. Null when it goes through. */
305export async function inspectGuard(io: Io, e: Record<string, unknown>, cfg: GuardConfig): Promise<Finding | null> {
306 const tool = String(e.tool)
307
308 if (tool === 'Bash') {
309 const command = String(e.command ?? '')
310 const rules: string[] = []
311 const lines: string[] = []
312 const notes: string[] = []
313 let summary = ''
314 const domains = domainFindings(hostsIn(command), cfg, 'reaches')
315 rules.push(...domains.rules)
316 lines.push(...domains.lines)
317 notes.push(...domains.notes)
318 if (domains.rules.length) summary = `reach production: ${domains.rules.map(r => r.replace(/^production domain: /, '')).join(', ')}`
319 const keys = liveStripeKeys(command)
320 if (keys.length) {
321 rules.push(`live Stripe key in the command: ${keys.join(', ')}`)
322 summary ||= 'use a live Stripe key: real charges and real customer data'
323 }
324 const cwd = await io.cwd()
325 const switched: { branch?: string } = {}
326 for (const seg of segments(command)) {
327 const hits = [...(seg.cmd === 'git' ? await gitFindings(io, seg, cwd, cfg, switched) : []), ...(await deployFindings(io, seg, cwd))]
328 for (const h of hits) {
329 rules.push(h.rule)
330 summary = summary ? `${summary}; ${h.summary}` : h.summary
331 lines.push(...h.lines)
332 if (h.note) notes.push(h.note)
333 }
334 }
335 return rules.length ? finding(rules, command, summary, lines, notes) : null
336 }
337
338 if (EDIT_TOOLS.has(tool)) {
339 const file = String(e.file_path ?? e.notebook_path ?? '')
340 const text = [e.content, e.new_string, e.new_source, ...(Array.isArray(e.edits) ? e.edits.map(x => (x as { new_string?: unknown }).new_string) : [])]
341 .filter(v => typeof v === 'string')
342 .join('\n')
343 const keys = liveStripeKeys(text)
344 if (!keys.length) return null
345 return finding([`live Stripe key in file content: ${keys.join(', ')}`], `${tool} ${file}`, `write a live Stripe key into ${file}`, [], ['Anything that reads this file gets live access to Stripe. Use a test key (sk_test_) or an environment variable.'])
346 }
347
348 if (tool === 'WebFetch' || (tool.startsWith('mcp__') && WEBBY.test(tool))) {
349 const values = strings(e)
350 const hosts = [...new Set(values.flatMap(urlHostsIn))]
351 const domains = domainFindings(hosts, cfg, tool === 'WebFetch' ? 'fetches' : 'opens')
352 if (!domains.rules.length) return null
353 const shown = typeof e.url === 'string' ? e.url : values.find(v => urlHostsIn(v).some(h => productionMatch(h, cfg))) ?? ''
354 return finding(domains.rules, `${tool} ${shown}`, `send a request to production: ${domains.rules.map(r => r.replace(/^production domain: /, '')).join(', ')}`, domains.lines, domains.notes)
355 }
356
357 return null
358}
359
360/**
361 * A synchronous judgment for when the guard itself failed: true when the call
362 * looks risky enough to refuse without the full check.
363 */
364export function looksRisky(e: Record<string, unknown>, cfg: GuardConfig): boolean {
365 const text = strings(e).join('\n')
366 if (liveStripeKeys(text).length) return true
367 if (String(e.tool) === 'Bash' || String(e.tool) === 'WebFetch' || WEBBY.test(String(e.tool))) {
368 if ([...hostsIn(text), ...urlHostsIn(text)].some(h => productionMatch(h, cfg))) return true
369 }
370 if (String(e.tool) === 'Bash') {
371 return /\bgit\b[^;&|\n]*\b(push|merge)\b|\b(vercel|vc)\b[^;&|\n]*--prod|\b(terraform|tofu)\b[^;&|\n]*\bapply\b|\bcdk\b[^;&|\n]*\bdeploy\b|\bkubectl\b[^;&|\n]*\bapply\b|\b(docker|podman)\b[^;&|\n]*\bpush\b/.test(text)
372 }
373 return false
374}
375hooks/hold.tsx 242 lines1// The one hold pane for the staging guard and blast radius. Holds are queued so
2// only one shows at a time. Each waits for Proceed or Cancel, and is refused
3// after 10 minutes, when the turn is interrupted, or when nobody can answer.
4//
5// The waiting approach follows blast-radius (claude-code-playground, Copyright
6// 2026 Anthropic PBC, Apache-2.0): a hook has 10 s of its own time, but time
7// inside a `$` call is free, so the loop waits on a short `sleep` process.
8
9import type { EngineInterface } from 'claude-code'
10
11import type { HoldOutcome, HoldView } from '../types'
12import type { Finding } from './guard'
13import { BRAND, HEADER_H, chipsSvg, holdBandSvg, holdHeaderSvg, idleBandSvg, idleBandWidth, labelSvg, pxOf } from './theme'
14
15export const HOLD_PANE = 'code-buddy-hold'
16export const HOLD_LIMIT_MS = 10 * 60 * 1000
17export const POLL_SECONDS = '0.25'
18
19export type Decision = 'proceed' | 'cancel'
20export type Pending = { view: HoldView; decision: Decision | null }
21
22// The calls being held, in order; the first is the one shown. Module state:
23// a reload drops the module and with it every hook that waits here.
24export const pending: Pending[] = []
25
26/** A press on Proceed or Cancel, for the hold drawn with this id. */
27export function decide(id: string, decision: Decision): void {
28 const p = pending.find(x => x.view.id === id)
29 if (p && p.decision === null) p.decision = decision
30}
31
32export const paneRows = (view: HoldView): number =>
33 Math.min(28, 14 + view.rules.length + view.affects.lines.length + (view.affects.more ? 1 : 0) + Math.ceil(view.command.length / 70))
34
35const WHY: Record<HoldOutcome, string> = {
36 waiting: 'it is still waiting',
37 proceeded: 'it was allowed',
38 cancelled: 'the user pressed Cancel',
39 timeout: 'nobody answered within 10 minutes',
40 interrupted: 'the turn was interrupted',
41 'no-one': 'this is a non-interactive run, so nobody could approve it',
42 error: 'Code Buddy hit an error while holding it',
43}
44
45export function refusal(outcome: HoldOutcome, found: Finding): string {
46 return `Code Buddy held this call and did not run it: ${WHY[outcome]}. Rule: ${found.rules.join('; ')}. It would: ${found.affects.summary}. Do not retry it unless the user asks you to.`
47}
48
49export const OUTCOME_LABEL: Record<HoldOutcome, string> = {
50 waiting: 'waiting',
51 proceeded: 'proceeded',
52 cancelled: 'cancelled',
53 timeout: 'refused: no answer in 10 min',
54 interrupted: 'refused: turn interrupted',
55 'no-one': 'refused: non-interactive',
56 error: 'refused: error',
57}
58
59// ---- Drawing ---------------------------------------------------------------
60// The desktop gets brand SVG rows (theme.ts) with real Buttons beside them; a
61// terminal gets the same hierarchy in coloured text.
62
63type Ui = ReturnType<EngineInterface['ui']['resolve']>
64type Surface = 'terminal' | 'desktop' | 'mobile' | 'vscode'
65
66const subtitleOf = (view: HoldView): string => {
67 const blast = view.rules.some(r => r.startsWith('destructive'))
68 const guard = view.rules.some(r => !r.startsWith('destructive'))
69 return `Code Buddy · ${[guard ? 'staging guard' : '', blast ? 'blast radius' : ''].filter(Boolean).join(' + ')} · needs your OK`
70}
71
72const titleOf = (view: HoldView): string => `Holding a ${view.tool} call${view.isSubagent ? ' from a subagent' : ''}`
73
74/** The hold pane: header, rules, command, what it would affect, Proceed and Cancel. */
75export function drawHold(ui: Ui, surface: Surface, view: HoldView, behind: number, columns: number) {
76 const { Box, Text, Button, Code } = ui
77 const a = view.affects
78 const buttons = (
79 <Box key="buttons" flexDirection="row" gap={2} marginTop={1}>
80 <Button key="proceed" label="Proceed" hotkey="1" onPress={() => decide(view.id, 'proceed')} />
81 <Button key="cancel" label="Cancel" hotkey="2" variant="primary" autoFocus onPress={() => decide(view.id, 'cancel')} />
82 </Box>
83 )
84 const footer = (
85 <Text key="footer" dimColor>
86 Refused automatically after 10 minutes without an answer.
87 </Text>
88 )
89 const lines = a.lines.length > 0 ? `${a.lines.join('\n')}${a.more > 0 ? `\n+ ${a.more} more` : ''}` : ''
90
91 if (surface === 'desktop' && 'Svg' in ui) {
92 const { Svg } = ui
93 const W = pxOf(columns, 16, 260)
94 const chips = chipsSvg(W, view.rules)
95 return (
96 <Box flexDirection="column" gap={1}>
97 <Svg key="head" source={holdHeaderSvg(W, titleOf(view), subtitleOf(view), behind)} alt={`${titleOf(view)}. ${subtitleOf(view)}`} width={W} height={HEADER_H} />
98 <Svg key="rules" source={chips.source} alt={`Rule: ${view.rules.join('; ')}`} width={W} height={chips.height} />
99 <Svg key="l-cmd" source={labelSvg(W, 'Command')} alt="Command" width={W} height={18} />
100 <Code key="cmd" source={view.command} language={view.tool === 'Bash' ? 'bash' : 'text'} wrap="wrap" />
101 <Svg key="l-would" source={labelSvg(W, 'Would')} alt="Would" width={W} height={18} />
102 <Text key="sum" bold color={BRAND.coral} wrap="wrap">
103 {a.summary}
104 </Text>
105 {lines !== '' && <Code key="lines" source={lines} language="text" wrap="truncate-end" />}
106 {a.note !== '' && (
107 <Text key="note" dimColor italic wrap="wrap">
108 {a.note}
109 </Text>
110 )}
111 {buttons}
112 {footer}
113 </Box>
114 )
115 }
116
117 return (
118 <Box flexDirection="column" paddingX={1}>
119 <Text key="head" wrap="truncate-end">
120 <Text backgroundColor={BRAND.royal} color={BRAND.white} bold>
121 {' ⏸ CODE BUDDY '}
122 </Text>
123 <Text bold color={BRAND.sky}>
124 {` ${titleOf(view)}`}
125 </Text>
126 <Text dimColor>{behind > 0 ? ` · ${behind} more waiting` : ''}</Text>
127 </Text>
128 <Text key="sub" dimColor wrap="truncate-end">
129 {subtitleOf(view).replace('Code Buddy · ', '')}
130 </Text>
131 <Box key="rules" flexDirection="column" marginTop={1}>
132 {view.rules.map((r, i) => (
133 <Text key={`rule${i}`} wrap="wrap">
134 <Text color={BRAND.coral}>{'● '}</Text>
135 <Text bold>{r}</Text>
136 </Text>
137 ))}
138 </Box>
139 <Text key="l-cmd" bold color={BRAND.sky}>
140 {'\nCOMMAND'}
141 </Text>
142 <Code key="cmd" source={view.command} language={view.tool === 'Bash' ? 'bash' : 'text'} wrap="wrap" />
143 <Text key="l-would" bold color={BRAND.sky}>
144 {'\nWOULD'}
145 </Text>
146 <Text key="sum" bold color={BRAND.coral} wrap="wrap">
147 {a.summary}
148 </Text>
149 {a.lines.map((l, i) => (
150 <Text key={`l${i}`} wrap="truncate-end">
151 <Text color={BRAND.blue}>{' │ '}</Text>
152 {l}
153 </Text>
154 ))}
155 {a.more > 0 && <Text key="more" dimColor>{` │ + ${a.more} more`}</Text>}
156 {a.note !== '' && (
157 <Text key="note" dimColor italic wrap="wrap">
158 {a.note}
159 </Text>
160 )}
161 {buttons}
162 {footer}
163 </Box>
164 )
165}
166
167/** The band while a call waits: alert badge, the rule, the command, the buttons. */
168export function drawHoldBand(ui: Ui, surface: Surface, view: HoldView, behind: number, columns: number) {
169 const { Box, Text, Button } = ui
170 const rule = view.rules[0] ?? 'held'
171 const proceed = <Button key="band-proceed" label="Proceed" hotkey="1" onPress={() => decide(view.id, 'proceed')} />
172 const cancel = <Button key="band-cancel" label="Cancel" hotkey="2" variant="primary" autoFocus onPress={() => decide(view.id, 'cancel')} />
173 if (surface === 'desktop' && 'Svg' in ui) {
174 const { Svg } = ui
175 const W = pxOf(columns, 210, 200)
176 return (
177 <Box flexDirection="row" alignItems="center" gap={1}>
178 <Svg key="held" source={holdBandSvg(W, rule, view.command, behind)} alt={`Held${behind > 0 ? ` +${behind}` : ''}: ${rule}. ${view.command}`} width={W} height={24} />
179 {proceed}
180 {cancel}
181 </Box>
182 )
183 }
184 const room = Math.max(10, columns - rule.length - 40)
185 return (
186 <Box flexDirection="row" gap={1}>
187 <Text backgroundColor={BRAND.coral} color={BRAND.white} bold>
188 {` ⏸ HELD${behind > 0 ? ` +${behind}` : ''} `}
189 </Text>
190 <Text bold wrap="truncate-end">
191 {rule}
192 </Text>
193 <Text dimColor wrap="truncate-end">
194 {view.command.length > room ? `${view.command.slice(0, room - 1)}…` : view.command}
195 </Text>
196 {proceed}
197 {cancel}
198 </Box>
199 )
200}
201
202/** The idle band: the brand badge, guard state, how many calls were held. */
203export function drawIdleBand(ui: Ui, surface: Surface, isOn: boolean, held: number, columns: number, overBudget = '', paused: string[] = [], resume: () => void = () => {}) {
204 const { Text } = ui
205 const words = `Code Buddy · guard ${isOn ? 'on' : 'off'} · ${held} held`
206 if (surface === 'desktop' && 'Svg' in ui) {
207 const { Svg } = ui
208 const W = Math.min(pxOf(columns, paused.length ? 100 : 0, 200), idleBandWidth(held, overBudget, paused))
209 const alt = [words, overBudget, ...paused.map(p => `paused: ${p}`)].filter(Boolean).join(' · ')
210 const drawing = <Svg key="idle" source={idleBandSvg(W, isOn, held, overBudget, paused)} alt={alt} width={W} height={24} />
211 if (paused.length === 0) return drawing
212 return (
213 <ui.Box flexDirection="row" alignItems="center" gap={1}>
214 {drawing}
215 <ui.Button key="resume-all" label="Resume" hotkey="r" variant="primary" onPress={resume} />
216 </ui.Box>
217 )
218 }
219 const line = (
220 <Text key="idle" wrap="truncate-end">
221 <Text backgroundColor={BRAND.royal} color={BRAND.white} bold>
222 {' ≋ Code Buddy '}
223 </Text>
224 <Text color={isOn ? BRAND.sky : undefined} dimColor={!isOn}>
225 {isOn ? ' ● guard on' : ' ○ guard off'}
226 </Text>
227 <Text dimColor>{` · ${held} held`}</Text>
228 {overBudget ? <Text color={BRAND.coral} bold>{` · ${overBudget}`}</Text> : null}
229 {paused.map(p => (
230 <Text key={`p-${p}`} color={BRAND.coral} bold>{` · ⏸ ${p}`}</Text>
231 ))}
232 </Text>
233 )
234 if (paused.length === 0) return line
235 return (
236 <ui.Box flexDirection="row" gap={1}>
237 {line}
238 <ui.Button key="resume-all" label="Resume" hotkey="r" variant="primary" onPress={resume} />
239 </ui.Box>
240 )
241}
242hooks/mask.ts 56 lines1// Masks secrets so only their first 8 characters show. Everything Code Buddy
2// draws, stores or hands back to the model goes through `mask` first.
3
4const KEEP = 8
5const HIDDEN = '••••••'
6
7// Whole-token secrets: the match itself is the key.
8const TOKENS: RegExp[] = [
9 /\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{6,}/g, // Stripe
10 /\bwhsec_[A-Za-z0-9]{10,}/g, // Stripe webhook secret
11 /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, // AWS access key id
12 /\bgh[pousr]_[A-Za-z0-9]{20,}/g, // GitHub
13 /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
14 /\bglpat-[A-Za-z0-9_-]{16,}/g, // GitLab
15 /\bxox[abposr]-[A-Za-z0-9-]{10,}/g, // Slack
16 /\bsk-[A-Za-z0-9_-]{20,}/g, // Anthropic, OpenAI and similar
17 /\bAIza[0-9A-Za-z_-]{30,}/g, // Google API key
18 /\bnpm_[A-Za-z0-9]{30,}/g,
19 /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, // JWT
20 /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
21]
22
23// key = value: the value is the secret.
24const ASSIGNED =
25 /\b([A-Za-z0-9_.-]*(?:api[_-]?key|secret|token|passwd|password|private[_-]?key|access[_-]?key)[A-Za-z0-9_.-]*)(\s*[:=]\s*|\s+(?=["']))(["']?)([^\s"'`]{9,})/gi
26// --token xyz, --password=xyz
27const FLAG = /(--?(?:api[_-]?key|token|secret|password|passwd)(?:=|\s+))(["']?)([^\s"'`]{6,})/gi
28
29// Authorization: Bearer xyz, and user:password@ in URLs.
30const BEARER = /\b(Bearer|Basic|Token)\s+([A-Za-z0-9._~+/=-]{9,})/g
31const URL_PASSWORD = /(:\/\/[^\s:/@]+:)([^\s@/]{1,})@/g
32
33const cut = (secret: string): string => secret.slice(0, KEEP) + HIDDEN
34
35export function mask(text: string): string {
36 if (!text) return text
37 let out = text
38 for (const re of TOKENS) out = out.replace(re, m => cut(m))
39 out = out.replace(ASSIGNED, (_m, name: string, sep: string, quote: string, value: string) =>
40 value.endsWith(HIDDEN) ? `${name}${sep}${quote}${value}` : `${name}${sep}${quote}${cut(value)}`,
41 )
42 out = out.replace(FLAG, (_m, flag: string, quote: string, value: string) =>
43 value.endsWith(HIDDEN) ? `${flag}${quote}${value}` : `${flag}${quote}${cut(value)}`,
44 )
45 out = out.replace(BEARER, (_m, kind: string, value: string) => `${kind} ${cut(value)}`)
46 out = out.replace(URL_PASSWORD, (_m, head: string, pass: string) => `${head}${cut(pass)}@`)
47 return out
48}
49
50/** Live Stripe keys, for the guard: sk_live_, rk_live_, pk_live_. */
51export const LIVE_STRIPE = /\b(?:sk|rk|pk)_live_[A-Za-z0-9]{6,}/g
52
53export function liveStripeKeys(text: string): string[] {
54 return [...new Set(text.match(LIVE_STRIPE) ?? [])]
55}
56hooks/replay.tsx 124 lines1// Feature 3, Replay: the pane that steps through the last turn's edits with
2// Prev, Next and Close, and the band's hint. Drawing only: register.tsx owns
3// the state and hands in what the buttons do.
4//
5// The stepper follows replay-theater (claude-code-playground, Copyright 2026
6// Anthropic PBC, Apache-2.0): a strip of steps, one diff at a time, Prev /
7// Next / Close with hotkeys p, n and c. See NOTICE.
8
9import type { EngineInterface } from 'claude-code'
10
11import type { Replay } from '../types'
12import { BAND_ROW_H, BRAND, GREEN, REPLAY_HEADER_H, fileRowSvg, pxOf, replayBandSvg, replayHeaderSvg } from './theme'
13
14export const REPLAY_PANE = 'code-buddy-replay'
15
16type Ui = ReturnType<EngineInterface['ui']['resolve']>
17type Surface = 'terminal' | 'desktop' | 'mobile' | 'vscode'
18
19export type ReplayActions = { go: (index: number) => void; close: () => void }
20
21export const filesOf = (r: Replay): number => new Set(r.steps.map(s => s.file)).size
22
23export const replayRows = (r: Replay): number =>
24 Math.min(32, 9 + Math.max(...r.steps.map(s => s.diff.split('\n').length), 1))
25
26const countText = (r: Replay): string => {
27 const n = r.steps.length
28 const f = filesOf(r)
29 return `${n} ${n === 1 ? 'edit' : 'edits'} in ${f} ${f === 1 ? 'file' : 'files'}`
30}
31
32/** The replay pane: one step at a time. */
33export function drawReplay(ui: Ui, surface: Surface, r: Replay, columns: number, act: ReplayActions) {
34 const { Box, Text, Button, Code } = ui
35 const total = r.steps.length
36 const k = Math.max(0, Math.min(r.index, total - 1))
37 const step = r.steps[k]
38 if (step === undefined) return <Text dimColor>No edits to replay.</Text>
39 const meta = `${step.tool}${step.isNew ? ' · new file' : ''}${step.note ? ` · ${step.note}` : ''}`
40 const diff =
41 step.diff === '' ? (
42 <Text key="diff" dimColor>
43 (no line changes)
44 </Text>
45 ) : (
46 <Code key="diff" source={step.diff} format="diff" path={step.file} wrap="truncate-end" />
47 )
48 const buttons = (
49 <Box key="buttons" flexDirection="row" gap={2} marginTop={1}>
50 <Button key="prev" label="◀ Prev" hotkey="p" onPress={() => act.go(k - 1)} />
51 <Button key="next" label="Next ▶" hotkey="n" variant="primary" autoFocus onPress={() => act.go(k + 1)} />
52 <Button key="close" label="Close" hotkey="c" onPress={() => act.close()} />
53 </Box>
54 )
55
56 if (surface === 'desktop' && 'Svg' in ui) {
57 const { Svg } = ui
58 const W = pxOf(columns, 16, 260)
59 return (
60 <Box flexDirection="column" gap={1}>
61 <Svg key="head" source={replayHeaderSvg(W, k, total, filesOf(r))} alt={`Replay, step ${k + 1} of ${total}. ${countText(r)}.`} width={W} height={REPLAY_HEADER_H} />
62 <Svg key="file" source={fileRowSvg(W, step.file, meta, step.adds, step.dels)} alt={`${step.file}: ${meta}, ${step.adds} added, ${step.dels} removed`} width={W} height={34} />
63 {diff}
64 {buttons}
65 </Box>
66 )
67 }
68
69 const strip = r.steps.map((_, i) => (i === k ? '●' : i < k ? '•' : '·')).join(' ')
70 return (
71 <Box flexDirection="column" paddingX={1}>
72 <Text key="head" wrap="truncate-end">
73 <Text backgroundColor={BRAND.royal} color={BRAND.white} bold>
74 {' ▶ REPLAY '}
75 </Text>
76 <Text bold color={BRAND.sky}>{` step ${k + 1} of ${total}`}</Text>
77 <Text dimColor>{` · ${countText(r)}`}</Text>
78 </Text>
79 <Text key="strip" color={BRAND.sky} wrap="truncate-end">
80 {strip}
81 </Text>
82 <Text key="file" bold wrap="truncate-start">
83 {`\n${step.file}`}
84 </Text>
85 <Text key="meta" wrap="truncate-end">
86 <Text dimColor>{`${meta} `}</Text>
87 <Text color={GREEN} bold>{`+${step.adds}`}</Text>
88 <Text>{' '}</Text>
89 <Text color={BRAND.coral} bold>{`−${step.dels}`}</Text>
90 </Text>
91 {diff}
92 {buttons}
93 </Box>
94 )
95}
96
97/** The band's hint after a turn with edits. */
98export function drawReplayBand(ui: Ui, surface: Surface, r: Replay, columns: number, open: () => void) {
99 const { Box, Text, Button } = ui
100 const button = <Button key="open-replay" label="Replay" hotkey="r" variant="primary" onPress={open} />
101 if (surface === 'desktop' && 'Svg' in ui) {
102 const { Svg } = ui
103 const W = Math.min(pxOf(columns, 110, 200), 460)
104 return (
105 <Box flexDirection="row" alignItems="center" gap={1}>
106 <Svg key="hint" source={replayBandSvg(W, r.steps.length, filesOf(r))} alt={`Replay ready: ${countText(r)}`} width={W} height={BAND_ROW_H} />
107 {button}
108 </Box>
109 )
110 }
111 return (
112 <Box flexDirection="row" gap={1}>
113 <Text wrap="truncate-end">
114 <Text backgroundColor={BRAND.royal} color={BRAND.white} bold>
115 {' ≋ Code Buddy '}
116 </Text>
117 <Text bold color={BRAND.sky}>{' ▶ Replay ready'}</Text>
118 <Text dimColor>{` · ${countText(r)}`}</Text>
119 </Text>
120 {button}
121 </Box>
122 )
123}
124hooks/theme.ts 602 lines1// Code Buddy's look: the Ruah Tech logo's blues (sampled from the official logo
2// at ruahtech.com.au), drawn as SVG on the desktop Code tab and as coloured
3// text in a terminal. The coral alert comes from the website's highlight.
4//
5// One SVG per row on the desktop, with Buttons beside it, follows savvy-progress
6// (claude-kit, MIT; see NOTICE): the desktop wraps sibling elements onto new
7// lines, so a row's text and shapes live in one drawing.
8
9export const BRAND = {
10 deep: '#012D96', // the logo's darkest royal blue
11 royal: '#0745A4',
12 blue: '#037AC1', // the logo's median blue
13 sky: '#1E99D5', // the logo's lightest blue
14 ink: '#0B1B3F',
15 tint: '#E5F2FB',
16 muted: '#6B7A90',
17 coral: '#F55C6D', // ruahtech.com.au highlight, for holds
18 white: '#FFFFFF',
19} as const
20
21export const FONT = "'IBM Plex Sans',-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',sans-serif"
22export const MONO = "'IBM Plex Mono',ui-monospace,'SF Mono',Menlo,Consolas,monospace"
23
24/** About 8 CSS px per reported column on the desktop. */
25export const pxOf = (columns: number, reserve = 0, min = 220): number =>
26 Math.max(min, Math.min(1600, Math.round((columns || 100) * 8 - reserve)))
27
28export const xml = (s: string): string =>
29 s.replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c] ?? c)
30
31// Rough advance of UI text, in em: enough to size a slot and cut with an ellipsis.
32const charEm = (ch: string, mono: boolean): number =>
33 mono ? 0.61 : /[\s.,:;'|!il1()[\]]/.test(ch) ? 0.3 : /[A-ZmwW@%]/.test(ch) ? 0.72 : 0.56
34
35export const textWidth = (s: string, size: number, mono = false): number =>
36 [...s].reduce((w, ch) => w + charEm(ch, mono) * size, 0)
37
38export function fit(s: string, size: number, maxW: number, mono = false): string {
39 if (textWidth(s, size, mono) <= maxW) return s
40 let out = ''
41 for (const ch of s) {
42 if (textWidth(`${out}${ch}…`, size, mono) > maxW) break
43 out += ch
44 }
45 return `${out}…`
46}
47
48// Light and dark: the classes every drawing shares.
49const CSS = `<style>
50.t{fill:${BRAND.ink}}.m{fill:${BRAND.muted}}.chip{fill:${BRAND.tint}}.chipt{fill:${BRAND.royal}}.ln{stroke:#D9E8F4}.acc{fill:${BRAND.blue}}
51@media (prefers-color-scheme: dark){.t{fill:#EAF2FB}.m{fill:#93A3B8}.chip{fill:#0D2A4F}.chipt{fill:#7CC4EC}.ln{stroke:#1E3352}.acc{fill:${BRAND.sky}}}
52.pulse{animation:p 1.6s ease-in-out infinite}@keyframes p{50%{opacity:.35}}
53@media (prefers-reduced-motion: reduce){.pulse{animation:none}}
54</style>`
55
56const DEFS = `<defs>
57<linearGradient id="cb-brand" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="${BRAND.deep}"/><stop offset=".55" stop-color="${BRAND.blue}"/><stop offset="1" stop-color="${BRAND.sky}"/></linearGradient>
58<linearGradient id="cb-glow" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="${BRAND.sky}"/><stop offset="1" stop-color="${BRAND.white}" stop-opacity=".6"/></linearGradient>
59<linearGradient id="cb-alert" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="${BRAND.coral}"/><stop offset="1" stop-color="#E2475A"/></linearGradient>
60</defs>`
61
62const svg = (W: number, H: number, body: string): string =>
63 `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">${CSS}${DEFS}${body}</svg>`
64
65// The Ruah wave: a dot over four widening swooshes, 14 × 13, top-left at (x, y).
66const wave = (x: number, y: number, stroke: string): string =>
67 `<g transform="translate(${x},${y})" fill="none" stroke="${stroke}" stroke-width="1.5" stroke-linecap="round">` +
68 `<circle cx="8.2" cy="1" r=".9" fill="${stroke}" stroke="none"/>` +
69 '<path d="M5.6 3.4Q7.6 4.1 9.6 3.2"/><path d="M4 6Q7.2 7 10.8 5.7"/>' +
70 '<path d="M2.4 8.6Q6.9 10 12.2 8.3"/><path d="M.8 11.2Q6.7 13 13.6 10.9"/></g>'
71
72// Two pause bars, 10 × 12.
73const pauseMark = (x: number, y: number, fill: string): string =>
74 `<rect x="${x}" y="${y}" width="3.4" height="12" rx="1.2" fill="${fill}"/><rect x="${x + 6.2}" y="${y}" width="3.4" height="12" rx="1.2" fill="${fill}"/>`
75
76/** The "Code Buddy" badge; returns its markup and width. */
77function badge(x: number, y: number, h: number, label: string, alert: boolean): { body: string; w: number } {
78 const w = Math.round(30 + textWidth(label, 11.5) + 12)
79 const icon = alert ? pauseMark(x + 11, y + (h - 12) / 2, BRAND.white) : wave(x + 9, y + (h - 13) / 2, BRAND.white)
80 return {
81 w,
82 body: `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${h / 2}" fill="url(#${alert ? 'cb-alert' : 'cb-brand'})"/>${icon}
83<text x="${x + 29}" y="${y + h / 2 + 4}" font-family="${FONT}" font-size="11.5" font-weight="600" letter-spacing=".2" fill="${BRAND.white}">${xml(label)}</text>`,
84 }
85}
86
87const BAND_H = 24
88
89/** Idle band: badge, guard state, how many calls were held. */
90export function idleBandSvg(W: number, isOn: boolean, held: number, overBudget = '', paused: string[] = []): string {
91 const b = badge(0, 2, 20, 'Code Buddy', false)
92 let x = b.w + 12
93 const dot = isOn
94 ? `<circle class="pulse" cx="${x + 4}" cy="${BAND_H / 2}" r="3.6" fill="${BRAND.sky}"/>`
95 : `<circle cx="${x + 4}" cy="${BAND_H / 2}" r="3.6" fill="none" stroke="${BRAND.muted}" stroke-width="1.4"/>`
96 x += 13
97 const guard = `<text class="${isOn ? 't' : 'm'}" x="${x}" y="${BAND_H / 2 + 4.5}" font-family="${FONT}" font-size="12.5" font-weight="500">Guard ${isOn ? 'on' : 'off'}</text>`
98 x += textWidth(`Guard ${isOn ? 'on' : 'off'}`, 12.5) + 14
99 const label = `${held} held`
100 const cw = Math.round(textWidth(label, 11.5) + 18)
101 const chip = `<rect class="chip" x="${x}" y="4" width="${cw}" height="16" rx="8"/><text class="chipt" x="${x + cw / 2}" y="${BAND_H / 2 + 4}" text-anchor="middle" font-family="${FONT}" font-size="11.5" font-weight="600">${xml(label)}</text>`
102 x += cw + 8
103 const ow = Math.round(textWidth(overBudget, 11.5) + 18)
104 const over = overBudget
105 ? `<rect x="${x}" y="4" width="${ow}" height="16" rx="8" fill="${BRAND.coral}" fill-opacity=".16"/><text x="${x + ow / 2}" y="${BAND_H / 2 + 4}" text-anchor="middle" font-family="${FONT}" font-size="11.5" font-weight="700" fill="${BRAND.coral}">${xml(overBudget)}</text>`
106 : ''
107 x += overBudget ? ow + 8 : 0
108 const pausedSvg = paused
109 .map(label => {
110 const text = `⏸ ${label}`
111 const pw = Math.round(textWidth(text, 11.5) + 18)
112 const out = `<rect x="${x}" y="4" width="${pw}" height="16" rx="8" fill="${BRAND.coral}" fill-opacity=".14"/><text x="${x + pw / 2}" y="${BAND_H / 2 + 4}" text-anchor="middle" font-family="${FONT}" font-size="11.5" font-weight="700" fill="${BRAND.coral}">${xml(text)}</text>`
113 x += pw + 6
114 return out
115 })
116 .join('')
117 return svg(W, BAND_H, `${b.body}${dot}${guard}${chip}${over}${pausedSvg}`)
118}
119
120/** How wide the idle band's drawing needs to be for its chips. */
121export const idleBandWidth = (held: number, overBudget: string, paused: string[]): number =>
122 Math.round(260 + (overBudget ? textWidth(overBudget, 11.5) + 26 : 0) + paused.reduce((s, l) => s + textWidth(`⏸ ${l}`, 11.5) + 24, 0))
123
124/** Band while a call waits: coral badge, the rule, the command. */
125export function holdBandSvg(W: number, rule: string, command: string, behind: number): string {
126 const b = badge(0, 2, 20, behind > 0 ? `Held +${behind}` : 'Held', true)
127 const x = b.w + 12
128 const ruleW = Math.min(W * 0.45, textWidth(rule, 12.5) + 4)
129 const ruleText = fit(rule, 12.5, ruleW)
130 const cx = x + textWidth(ruleText, 12.5) + 14
131 const cmd = fit(command, 12, Math.max(0, W - cx - 4), true)
132 return svg(
133 W,
134 BAND_H,
135 `${b.body}<text class="t" x="${x}" y="${BAND_H / 2 + 4.5}" font-family="${FONT}" font-size="12.5" font-weight="600">${xml(ruleText)}</text>
136<text class="m" x="${cx}" y="${BAND_H / 2 + 4.5}" font-family="${MONO}" font-size="12">${xml(cmd)}</text>`,
137 )
138}
139
140export const HEADER_H = 62
141
142/** The hold pane's header card. */
143export function holdHeaderSvg(W: number, title: string, subtitle: string, behind: number): string {
144 const pill = behind > 0 ? `+${behind} waiting` : ''
145 const pw = pill ? Math.round(textWidth(pill, 11.5) + 20) : 0
146 const textW = W - 64 - (pw ? pw + 16 : 12)
147 return svg(
148 W,
149 HEADER_H,
150 `<clipPath id="cb-card"><rect x="0" y="0" width="${W}" height="${HEADER_H}" rx="12"/></clipPath>
151<g clip-path="url(#cb-card)"><rect x="0" y="0" width="${W}" height="${HEADER_H}" fill="url(#cb-brand)"/>
152<rect x="0" y="${HEADER_H - 3}" width="${W}" height="3" fill="url(#cb-glow)" opacity=".9"/></g>
153<circle cx="31" cy="${HEADER_H / 2}" r="17" fill="${BRAND.white}" fill-opacity=".14"/>
154${pauseMark(26.2, HEADER_H / 2 - 6, BRAND.white)}
155${pill ? '' : wave(0, 0, BRAND.white).replace('<g transform="translate(0,0)"', `<g opacity=".22" transform="translate(${W - 58},${HEADER_H / 2 - 16}) scale(2.4)"`)}
156<text x="60" y="27" font-family="${FONT}" font-size="15" font-weight="600" fill="${BRAND.white}">${xml(fit(title, 15, textW))}</text>
157<text x="60" y="45" font-family="${FONT}" font-size="11.5" fill="${BRAND.white}" fill-opacity=".78">${xml(fit(subtitle, 11.5, textW))}</text>
158${pill ? `<rect x="${W - pw - 14}" y="${HEADER_H / 2 - 11}" width="${pw}" height="22" rx="11" fill="${BRAND.white}" fill-opacity=".16"/><text x="${W - 14 - pw / 2}" y="${HEADER_H / 2 + 4}" text-anchor="middle" font-family="${FONT}" font-size="11.5" font-weight="600" fill="${BRAND.white}">${xml(pill)}</text>` : ''}`,
159 )
160}
161
162/** Rule chips, wrapped onto as many rows as they need; returns markup and height. */
163export function chipsSvg(W: number, chips: string[]): { source: string; height: number } {
164 const ROW = 26
165 let x = 0
166 let row = 0
167 const parts: string[] = []
168 for (const chip of chips) {
169 const label = fit(chip, 12, W - 34)
170 const w = Math.round(textWidth(label, 12) + 30)
171 if (x > 0 && x + w > W) {
172 x = 0
173 row += 1
174 }
175 const y = row * ROW + 2
176 parts.push(`<rect class="chip" x="${x}" y="${y}" width="${w}" height="21" rx="10.5"/>
177<circle cx="${x + 11}" cy="${y + 10.5}" r="3" fill="${BRAND.coral}"/>
178<text class="chipt" x="${x + 20}" y="${y + 14.5}" font-family="${FONT}" font-size="12" font-weight="600">${xml(label)}</text>`)
179 x += w + 6
180 }
181 const height = (row + 1) * ROW
182 return { source: svg(W, height, parts.join('')), height }
183}
184
185/** A section label: small caps in the accent blue, with a hairline. */
186export function labelSvg(W: number, label: string): string {
187 const tw = textWidth(label.toUpperCase(), 10.5) + 8
188 return svg(
189 W,
190 18,
191 `<text class="acc" x="0" y="13" font-family="${FONT}" font-size="10.5" font-weight="700" letter-spacing=".9">${xml(label.toUpperCase())}</text>
192<line class="ln" x1="${tw + 4}" y1="9.5" x2="${W}" y2="9.5"/>`,
193 )
194}
195
196// ---- Replay ----------------------------------------------------------------
197
198export const GREEN = '#1FA971'
199
200/** Cuts the start of `s` (a path) to fit, with a leading ellipsis. */
201export function fitStart(s: string, size: number, maxW: number, mono = false): string {
202 if (textWidth(s, size, mono) <= maxW) return s
203 let out = ''
204 for (const ch of [...s].reverse()) {
205 if (textWidth(`…${ch}${out}`, size, mono) > maxW) break
206 out = ch + out
207 }
208 return `…${out}`
209}
210
211// A play triangle, about 10 × 12.
212const playMark = (x: number, y: number, fill: string): string =>
213 `<path transform="translate(${x},${y})" d="M1.2 0.6Q0 0 0 1.4V10.6Q0 12 1.2 11.4L9.6 6.8Q10.8 6 9.6 5.2Z" fill="${fill}"/>`
214
215export const REPLAY_HEADER_H = 54
216
217/** The replay pane's header card: step k of n, the edits, a dot per step. */
218export function replayHeaderSvg(W: number, k: number, total: number, files: number): string {
219 const H = REPLAY_HEADER_H
220 const title = `Replay · step ${k + 1} of ${total}`
221 const sub = `${total} ${total === 1 ? 'edit' : 'edits'} in ${files} ${files === 1 ? 'file' : 'files'} · last turn`
222 const DOT = 14
223 const dotsW = total * DOT
224 const showDots = dotsW <= W * 0.4
225 const right = showDots ? dotsW + 16 : 0
226 const dots = showDots
227 ? Array.from({ length: total }, (_, i) => {
228 const cx = W - 16 - dotsW + i * DOT + DOT / 2
229 return i === k
230 ? `<rect x="${cx - 6}" y="${H / 2 - 3.5}" width="12" height="7" rx="3.5" fill="${BRAND.white}"/>`
231 : `<circle cx="${cx}" cy="${H / 2}" r="3" fill="${BRAND.white}" fill-opacity="${i < k ? 0.6 : 0.3}"/>`
232 }).join('')
233 : ''
234 const textW = W - 58 - right - 8
235 return svg(
236 W,
237 H,
238 `<clipPath id="cb-rcard"><rect x="0" y="0" width="${W}" height="${H}" rx="12"/></clipPath>
239<g clip-path="url(#cb-rcard)"><rect x="0" y="0" width="${W}" height="${H}" fill="url(#cb-brand)"/>
240<rect x="0" y="${H - 3}" width="${Math.round((W * (k + 1)) / Math.max(1, total))}" height="3" fill="url(#cb-glow)"/></g>
241<circle cx="27" cy="${H / 2}" r="15" fill="${BRAND.white}" fill-opacity=".14"/>
242${playMark(23.5, H / 2 - 6, BRAND.white)}
243<text x="52" y="23" font-family="${FONT}" font-size="14.5" font-weight="600" fill="${BRAND.white}">${xml(fit(title, 14.5, textW))}</text>
244<text x="52" y="40" font-family="${FONT}" font-size="11.5" fill="${BRAND.white}" fill-opacity=".78">${xml(fit(sub, 11.5, textW))}</text>
245${dots}`,
246 )
247}
248
249/** One step's file row: the path, the tool, and +adds −dels pills. */
250export function fileRowSvg(W: number, file: string, meta: string, adds: number, dels: number): string {
251 const H = 34
252 const plus = `+${adds}`
253 const minus = `−${dels}`
254 const pw = Math.round(textWidth(plus, 11.5) + 16)
255 const mw = Math.round(textWidth(minus, 11.5) + 16)
256 const pills = `<rect x="${W - pw - mw - 6}" y="${H / 2 - 9}" width="${pw}" height="18" rx="9" fill="${GREEN}" fill-opacity=".14"/>
257<text x="${W - mw - 6 - pw / 2}" y="${H / 2 + 4}" text-anchor="middle" font-family="${FONT}" font-size="11.5" font-weight="700" fill="${GREEN}">${plus}</text>
258<rect x="${W - mw}" y="${H / 2 - 9}" width="${mw}" height="18" rx="9" fill="${BRAND.coral}" fill-opacity=".14"/>
259<text x="${W - mw / 2}" y="${H / 2 + 4}" text-anchor="middle" font-family="${FONT}" font-size="11.5" font-weight="700" fill="${BRAND.coral}">${minus}</text>`
260 const textW = W - 24 - pw - mw - 18
261 const doc = `<path class="acc" d="M3 2.5Q3 1 4.5 1H10l4 4v10.5Q14 17 12.5 17h-8Q3 17 3 15.5Z" fill-opacity=".16"/><path d="M10 1v4h4" fill="none" stroke="${BRAND.blue}" stroke-width="1.2"/><path d="M3 2.5Q3 1 4.5 1H10l4 4v10.5Q14 17 12.5 17h-8Q3 17 3 15.5Z" fill="none" stroke="${BRAND.blue}" stroke-width="1.2"/>`
262 return svg(
263 W,
264 H,
265 `<g transform="translate(0,${H / 2 - 9})">${doc}</g>
266<text class="t" x="24" y="15" font-family="${MONO}" font-size="12.5" font-weight="600">${xml(fitStart(file, 12.5, textW, true))}</text>
267<text class="m" x="24" y="30" font-family="${FONT}" font-size="11">${xml(fit(meta, 11, textW))}</text>
268${pills}`,
269 )
270}
271
272/** The band's replay hint: badge, "Replay ready", how many edits. */
273export function replayBandSvg(W: number, edits: number, files: number): string {
274 const b = badge(0, 2, 20, 'Code Buddy', false)
275 const x = b.w + 12
276 const label = 'Replay ready'
277 const lx = x + 16
278 const count = `${edits} ${edits === 1 ? 'edit' : 'edits'} in ${files} ${files === 1 ? 'file' : 'files'}`
279 return svg(
280 W,
281 BAND_H,
282 `${b.body}${playMark(x, BAND_H / 2 - 6, BRAND.blue).replace('fill="#037AC1"', 'class="acc"')}
283<text class="t" x="${lx}" y="${BAND_H / 2 + 4.5}" font-family="${FONT}" font-size="12.5" font-weight="600">${label}</text>
284<text class="m" x="${lx + textWidth(label, 12.5) + 12}" y="${BAND_H / 2 + 4.5}" font-family="${FONT}" font-size="12.5">${xml(count)}</text>`,
285 )
286}
287export const BAND_ROW_H = BAND_H
288
289// ---- Agents ----------------------------------------------------------------
290
291export type AgentRowView = {
292 status: 'running' | 'done' | 'failed' | 'stopped'
293 title: string
294 type: string
295 model: string
296 elapsed: string
297 tokens: string
298 cost: string
299 /** What a running subagent is doing now, e.g. "Read · src/api/routes.ts". */
300 activity?: string
301 /** "step 4 · 9 tools" */
302 progress?: string
303}
304
305/** Spend against the budget, for the panel's header and the band. */
306export type BudgetView = { limit: string; used: string; ratio: number; isOver: boolean }
307
308const STATUS_COLOR = { running: BRAND.sky, done: GREEN, failed: BRAND.coral, stopped: BRAND.muted } as const
309
310function statusMark(cx: number, cy: number, status: AgentRowView['status'], r = 9): string {
311 const c = STATUS_COLOR[status]
312 const s = r / 9
313 if (status === 'running') {
314 return `<circle class="pulse" cx="${cx}" cy="${cy}" r="${r}" fill="${c}" fill-opacity=".18"/><circle cx="${cx}" cy="${cy}" r="${4.5 * s}" fill="${c}"/>`
315 }
316 const ring = `<circle cx="${cx}" cy="${cy}" r="${r}" fill="${c}" fill-opacity=".14"/>`
317 if (status === 'done') return `${ring}<path d="M${cx - 4 * s} ${cy}l${2.8 * s} ${2.8 * s} ${5.2 * s}-${5.6 * s}" fill="none" stroke="${c}" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/>`
318 if (status === 'failed') return `${ring}<path d="M${cx - 3.4 * s} ${cy - 3.4 * s}l${6.8 * s} ${6.8 * s}M${cx + 3.4 * s} ${cy - 3.4 * s}l-${6.8 * s} ${6.8 * s}" stroke="${c}" stroke-width="1.9" stroke-linecap="round"/>`
319 return `${ring}<rect x="${cx - 3.2 * s}" y="${cy - 3.2 * s}" width="${6.4 * s}" height="${6.4 * s}" rx="1.2" fill="${c}"/>`
320}
321
322/** A progress bar: finished in the brand gradient (coral when over budget), running as a lighter, moving stripe. */
323function progressBar(x: number, y: number, w: number, h: number, done: number, running: number, total: number, onCard: boolean, isOver = false): string {
324 const fw = total ? Math.round((w * done) / total) : 0
325 const rw = total ? Math.round((w * Math.min(total - done, running)) / total) : 0
326 const track = onCard ? `fill="${BRAND.white}" fill-opacity=".22"` : 'class="chip"'
327 const fill = isOver ? 'fill="url(#cb-alert)"' : onCard ? `fill="${BRAND.white}"` : 'fill="url(#cb-brand)"'
328 const id = `cb-bar-${x}-${y}`
329 return `<clipPath id="${id}"><rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${h / 2}"/></clipPath>
330<g clip-path="url(#${id})"><rect x="${x}" y="${y}" width="${w}" height="${h}" ${track}/>
331<rect x="${x}" y="${y}" width="${fw}" height="${h}" ${fill}/>
332${rw > 0 ? `<rect class="pulse" x="${x + fw}" y="${y}" width="${rw}" height="${h}" fill="${isOver ? BRAND.coral : onCard ? BRAND.white : BRAND.sky}" fill-opacity=".45"/>` : ''}</g>`
333}
334
335/** Band: badge, "Agents", the bar, finished of total and the cost so far (coral past the budget). */
336export function agentsBandSvg(W: number, done: number, running: number, total: number, cost: string, isOver = false): string {
337 const b = badge(0, 2, 20, 'Code Buddy', false)
338 let x = b.w + 12
339 const label = 'Agents'
340 const head = `<text class="t" x="${x}" y="${BAND_H / 2 + 4.5}" font-family="${FONT}" font-size="12.5" font-weight="600">${label}</text>`
341 x += textWidth(label, 12.5) + 12
342 const tail = `${done} / ${total} finished · ${cost}`
343 const over = isOver ? ' · over budget' : ''
344 const tw = textWidth(tail + over, 12.5) + 6
345 const barW = Math.max(60, Math.min(320, W - x - tw - 12))
346 const bar = progressBar(x, BAND_H / 2 - 4, barW, 8, done, running, total, false, isOver)
347 const tx = x + barW + 12
348 return svg(
349 W,
350 BAND_H,
351 `${b.body}${head}${bar}<text class="m" x="${tx}" y="${BAND_H / 2 + 4.5}" font-family="${FONT}" font-size="12.5" font-variant-numeric="tabular-nums">${xml(tail)}${isOver ? `<tspan fill="${BRAND.coral}" font-weight="700">${over}</tspan>` : ''}</text>`,
352 )
353}
354
355export const AGENTS_HEADER_H = 96
356
357/** The agents pane's summary card: finished of total, a bar, cost, tokens, time and the budget. */
358export function agentsHeaderSvg(W: number, done: number, running: number, total: number, stats: [string, string][], budget?: BudgetView): string {
359 const H = AGENTS_HEADER_H
360 const right = `${done} of ${total} finished`
361 const tiles: [string, string, boolean][] = stats.map(([k, v]) => [k, v, false])
362 if (budget) tiles.push(['Budget', budget.isOver ? `Over ${budget.limit}` : `${Math.round(budget.ratio * 100)}% of ${budget.limit}`, budget.isOver])
363 const tw = (W - 32) / tiles.length
364 const tileSvg = tiles
365 .map(([k, v, alert], i) => {
366 const x = 16 + i * tw
367 const vw = textWidth(v, 15) + 14
368 return `<text x="${x}" y="${H - 30}" font-family="${FONT}" font-size="10.5" font-weight="600" letter-spacing=".8" fill="${BRAND.white}" fill-opacity=".7">${xml(k.toUpperCase())}</text>
369${alert ? `<rect x="${x - 7}" y="${H - 28}" width="${vw}" height="22" rx="11" fill="${BRAND.coral}"/>` : ''}
370<text x="${x}" y="${H - 12}" font-family="${FONT}" font-size="15" font-weight="600" font-variant-numeric="tabular-nums" fill="${BRAND.white}">${xml(fit(v, 15, tw - 12))}</text>`
371 })
372 .join('')
373 return svg(
374 W,
375 H,
376 `<clipPath id="cb-acard"><rect x="0" y="0" width="${W}" height="${H}" rx="12"/></clipPath>
377<g clip-path="url(#cb-acard)"><rect x="0" y="0" width="${W}" height="${H}" fill="url(#cb-brand)"/></g>
378${wave(0, 0, BRAND.white).replace('<g transform="translate(0,0)"', `<g transform="translate(16,10) scale(1.15)"`)}
379<text x="40" y="23" font-family="${FONT}" font-size="14.5" font-weight="600" fill="${BRAND.white}">Subagents</text>
380<text x="${W - 16}" y="23" text-anchor="end" font-family="${FONT}" font-size="12" font-weight="600" fill="${BRAND.white}" fill-opacity=".85">${xml(right)}</text>
381${progressBar(16, 34, W - 32, 7, done, running, total, true, budget?.isOver ?? false)}
382${tileSvg}`,
383 )
384}
385
386/** Below this width a row stacks its stats under the model instead of beside it. */
387const NARROW = 520
388
389/** A row's height: 54 px (72 narrow), plus a line for a running subagent's activity. */
390export const agentRowHeight = (a: AgentRowView, W = 640): number => {
391 const live = a.status === 'running' && !!a.activity
392 return W < NARROW ? (live ? 90 : 72) : live ? 72 : 54
393}
394
395/** One subagent: status, description, type and model, elapsed, tokens, cost, and what it is doing now. */
396export function agentRowSvg(W: number, a: AgentRowView): string {
397 const H = agentRowHeight(a, W)
398 const narrow = W < NARROW
399 const stats = `${a.tokens} · ${a.cost}`
400 const statsW = textWidth(stats, 11.5, true) + 4
401 const elapsedW = textWidth(a.elapsed, 11.5, true) + 12
402 const chip = fit(a.type, 10.5, Math.min(140, W * 0.4))
403 const cw = Math.round(textWidth(chip, 10.5) + 14)
404 const modelW = Math.max(40, W - 40 - cw - 8 - (narrow ? 0 : statsW + 12))
405 const live = a.status === 'running' && a.activity
406 const activity = live
407 ? `<path d="M40 ${H - 22}l5 3.5-5 3.5z" fill="${BRAND.sky}"/>
408<text x="51" y="${H - 14.5}" font-family="${MONO}" font-size="11.5" fill="${BRAND.sky}">${xml(fit(a.activity ?? '', 11.5, W - 51 - (narrow ? 0 : textWidth(a.progress ?? '', 11) + 16), true))}</text>
409${narrow ? '' : `<text class="m" x="${W}" y="${H - 14.5}" text-anchor="end" font-family="${FONT}" font-size="11">${xml(a.progress ?? '')}</text>`}`
410 : ''
411 const statsSvg = narrow
412 ? `<text class="m" x="40" y="60" font-family="${MONO}" font-size="11.5">${xml(fit(`${stats}${live && a.progress ? ` · ${a.progress}` : ''}`, 11.5, W - 40, true))}</text>`
413 : `<text class="m" x="${W}" y="41" text-anchor="end" font-family="${MONO}" font-size="11.5">${xml(stats)}</text>`
414 const shimmer =
415 a.status === 'running'
416 ? `<rect class="pulse" x="40" y="${H - 4}" width="${W - 40}" height="2" rx="1" fill="${BRAND.sky}" fill-opacity=".6"/>`
417 : `<line class="ln" x1="40" y1="${H - 0.5}" x2="${W}" y2="${H - 0.5}"/>`
418 return svg(
419 W,
420 H,
421 `${statusMark(16, 20, a.status)}
422<text class="t" x="40" y="20" font-family="${FONT}" font-size="13" font-weight="600">${xml(fit(a.title, 13, W - 40 - elapsedW))}</text>
423<rect class="chip" x="40" y="29" width="${cw}" height="16" rx="8"/>
424<text class="chipt" x="${40 + cw / 2}" y="40.5" text-anchor="middle" font-family="${FONT}" font-size="10.5" font-weight="600">${xml(chip)}</text>
425<text class="m" x="${40 + cw + 8}" y="41" font-family="${FONT}" font-size="11.5">${xml(fit(a.model, 11.5, modelW))}</text>
426<text class="t" x="${W}" y="20" text-anchor="end" font-family="${MONO}" font-size="11.5">${xml(a.elapsed)}</text>
427${statsSvg}
428${activity}
429${shimmer}`,
430 )
431}
432
433export const COMPACT_ROW_H = 26
434
435/** The compact row: one line per subagent. */
436export function compactAgentRowSvg(W: number, a: AgentRowView): string {
437 const H = COMPACT_ROW_H
438 const right = `${a.model} · ${a.elapsed} · ${a.cost}`
439 const rw = textWidth(right, 11.5, true) + 8
440 const middle = a.status === 'running' && a.activity ? a.activity : ''
441 const titleW = Math.max(60, (W - 24 - rw) * (middle ? 0.55 : 1))
442 const title = fit(a.title, 12.5, titleW)
443 const mx = 24 + textWidth(title, 12.5) + 12
444 return svg(
445 W,
446 H,
447 `${statusMark(9, H / 2, a.status, 7)}
448<text class="t" x="24" y="${H / 2 + 4.5}" font-family="${FONT}" font-size="12.5" font-weight="600">${xml(title)}</text>
449${middle ? `<text x="${mx}" y="${H / 2 + 4.5}" font-family="${MONO}" font-size="11" fill="${BRAND.sky}">${xml(fit(middle, 11, Math.max(0, W - rw - mx - 8), true))}</text>` : ''}
450<text class="m" x="${W}" y="${H / 2 + 4.5}" text-anchor="end" font-family="${MONO}" font-size="11.5">${xml(right)}</text>
451<line class="ln" x1="24" y1="${H - 0.5}" x2="${W}" y2="${H - 0.5}"/>`,
452 )
453}
454
455// ---- Agent details -------------------------------------------------------------
456
457/** Splits text into lines that fit `maxW`, at most `max` of them, the last cut with an ellipsis. */
458export function wrapLines(text: string, size: number, maxW: number, max: number): string[] {
459 const words = text.split(/\s+/).filter(Boolean)
460 const lines: string[] = []
461 let line = ''
462 for (const word of words) {
463 const next = line ? `${line} ${word}` : word
464 if (textWidth(next, size) <= maxW) {
465 line = next
466 continue
467 }
468 if (line) lines.push(line)
469 line = textWidth(word, size) <= maxW ? word : fit(word, size, maxW)
470 if (lines.length === max) break
471 }
472 if (line && lines.length < max) lines.push(line)
473 if (lines.length === max && words.join(' ').length > lines.join(' ').length) {
474 lines[max - 1] = fit(`${lines[max - 1]} …`, size, maxW)
475 }
476 return lines
477}
478
479const STATUS_LABEL = { running: 'Running', done: 'Finished', failed: 'Failed', stopped: 'Stopped' } as const
480
481/** The detail view's card: status, elapsed, the full name over up to three lines, type · model · effort. */
482export function detailHeaderSvg(W: number, a: AgentRowView, meta: string): { source: string; height: number } {
483 const lines = wrapLines(a.title, 15, W - 32, 3)
484 const H = 70 + lines.length * 20
485 const label = STATUS_LABEL[a.status]
486 const pw = Math.round(textWidth(label, 11) + 26)
487 const pill = `<rect x="16" y="14" width="${pw}" height="20" rx="10" fill="${BRAND.white}" fill-opacity=".18"/>
488<circle ${a.status === 'running' ? 'class="pulse" ' : ''}cx="27" cy="24" r="3.5" fill="${a.status === 'running' ? BRAND.white : STATUS_COLOR[a.status]}"/>
489<text x="35" y="28" font-family="${FONT}" font-size="11" font-weight="700" fill="${BRAND.white}">${label}</text>`
490 const title = lines
491 .map((l, i) => `<text x="16" y="${58 + i * 20}" font-family="${FONT}" font-size="15" font-weight="600" fill="${BRAND.white}">${xml(l)}</text>`)
492 .join('')
493 return {
494 height: H,
495 source: svg(
496 W,
497 H,
498 `<clipPath id="cb-dcard"><rect x="0" y="0" width="${W}" height="${H}" rx="12"/></clipPath>
499<g clip-path="url(#cb-dcard)"><rect x="0" y="0" width="${W}" height="${H}" fill="url(#cb-brand)"/>
500${a.status === 'running' ? `<rect class="pulse" x="0" y="${H - 3}" width="${W}" height="3" fill="${BRAND.white}" fill-opacity=".5"/>` : ''}</g>
501${pill}
502<text x="${W - 16}" y="29" text-anchor="end" font-family="${MONO}" font-size="15" font-weight="600" fill="${BRAND.white}">${xml(a.elapsed)}</text>
503${title}
504<text x="16" y="${H - 14}" font-family="${FONT}" font-size="11.5" fill="${BRAND.white}" fill-opacity=".8">${xml(fit(meta, 11.5, W - 32))}</text>`,
505 ),
506 }
507}
508
509/** A grid of labelled numbers, two or three across. */
510export function statsGridSvg(W: number, stats: [string, string, string?][]): { source: string; height: number } {
511 const cols = W < 420 ? 2 : 3
512 const gap = 8
513 const tw = (W - gap * (cols - 1)) / cols
514 const TH = 52
515 const rows = Math.ceil(stats.length / cols)
516 const H = rows * TH + (rows - 1) * gap
517 const tiles = stats
518 .map(([k, v, sub], i) => {
519 const x = (i % cols) * (tw + gap)
520 const y = Math.floor(i / cols) * (TH + gap)
521 return `<rect class="chip" x="${x}" y="${y}" width="${tw}" height="${TH}" rx="10"/>
522<text class="chipt" x="${x + 10}" y="${y + 17}" font-family="${FONT}" font-size="10" font-weight="700" letter-spacing=".7">${xml(k.toUpperCase())}</text>
523<text class="t" x="${x + 10}" y="${y + 38}" font-family="${FONT}" font-size="15" font-weight="600" font-variant-numeric="tabular-nums">${xml(fit(v, 15, tw - 20 - (sub ? textWidth(sub, 10.5) + 6 : 0)))}</text>
524${sub ? `<text class="m" x="${x + tw - 10}" y="${y + 38}" text-anchor="end" font-family="${FONT}" font-size="10.5">${xml(sub)}</text>` : ''}`
525 })
526 .join('')
527 return { height: H, source: svg(W, H, tiles) }
528}
529
530const PART_COLORS = [BRAND.deep, BRAND.blue, BRAND.sky, BRAND.coral]
531
532/** Tokens by kind as one stacked bar, with a legend: tokens and cost of each. */
533export function tokenBreakdownSvg(W: number, parts: [string, string, string, number][]): { source: string; height: number } {
534 const total = parts.reduce((s, p) => s + p[3], 0) || 1
535 let x = 0
536 const bar = parts
537 .map(([, , , n], i) => {
538 const w = Math.round((W * n) / total)
539 const r = `<rect x="${x}" y="0" width="${Math.max(0, w)}" height="10" fill="${PART_COLORS[i % PART_COLORS.length]}"/>`
540 x += w
541 return r
542 })
543 .join('')
544 const legend = parts
545 .map(([label, tokens, cost], i) => {
546 const y = 30 + i * 20
547 return `<rect x="0" y="${y - 9}" width="10" height="10" rx="3" fill="${PART_COLORS[i % PART_COLORS.length]}"/>
548<text class="t" x="18" y="${y}" font-family="${FONT}" font-size="12">${xml(label)}</text>
549<text class="m" x="${W - 70}" y="${y}" text-anchor="end" font-family="${MONO}" font-size="11.5">${xml(tokens)}</text>
550<text class="t" x="${W}" y="${y}" text-anchor="end" font-family="${MONO}" font-size="11.5">${xml(cost)}</text>`
551 })
552 .join('')
553 const H = 30 + parts.length * 20 - 6
554 return {
555 height: H,
556 source: svg(W, H, `<clipPath id="cb-tbar"><rect x="0" y="0" width="${W}" height="10" rx="5"/></clipPath><g clip-path="url(#cb-tbar)"><rect class="chip" x="0" y="0" width="${W}" height="10"/>${bar}</g>${legend}`),
557 }
558}
559
560// ---- Control panel -------------------------------------------------------------
561
562export const CONTROL_HEADER_H = 74
563
564/** The control panel's card: name, version and a one-line summary. */
565export function controlHeaderSvg(W: number, version: string, summary: string): string {
566 const H = CONTROL_HEADER_H
567 return svg(
568 W,
569 H,
570 `<clipPath id="cb-ccard"><rect x="0" y="0" width="${W}" height="${H}" rx="12"/></clipPath>
571<g clip-path="url(#cb-ccard)"><rect x="0" y="0" width="${W}" height="${H}" fill="url(#cb-brand)"/>
572<rect x="0" y="${H - 3}" width="${W}" height="3" fill="url(#cb-glow)" opacity=".9"/></g>
573<circle cx="31" cy="${H / 2}" r="17" fill="${BRAND.white}" fill-opacity=".14"/>
574${wave(0, 0, BRAND.white).replace('<g transform="translate(0,0)"', `<g transform="translate(22.5,${H / 2 - 8}) scale(1.25)"`)}
575<text x="60" y="30" font-family="${FONT}" font-size="15" font-weight="600" fill="${BRAND.white}">Code Buddy${version ? ` <tspan font-size="11.5" font-weight="500" fill-opacity=".75">v${xml(version)}</tspan>` : ''}</text>
576<text x="60" y="49" font-family="${FONT}" font-size="11.5" fill="${BRAND.white}" fill-opacity=".8">${xml(fit(summary, 11.5, W - 76))}</text>`,
577 )
578}
579
580export type FeatureState = 'on' | 'paused' | 'off'
581
582/** One feature: its name and what it does, and a chip with its state. */
583export function featureRowSvg(W: number, name: string, what: string, state: FeatureState, left: string): { source: string; height: number } {
584 const chip = state === 'on' ? 'On' : state === 'off' ? 'Off' : `Paused · ${left}`
585 const cw = Math.round(textWidth(chip, 11) + 22)
586 const color = state === 'on' ? GREEN : state === 'off' ? BRAND.muted : BRAND.coral
587 const lines = wrapLines(what, 11.5, W - 4, 2)
588 const H = 30 + lines.length * 16
589 return {
590 height: H,
591 source: svg(
592 W,
593 H,
594 `<text class="t" x="0" y="17" font-family="${FONT}" font-size="13.5" font-weight="600">${xml(fit(name, 13.5, W - cw - 12))}</text>
595<rect x="${W - cw}" y="4" width="${cw}" height="19" rx="9.5" fill="${color}" fill-opacity=".14"/>
596<circle cx="${W - cw + 10}" cy="13.5" r="3" fill="${color}"/>
597<text x="${W - cw + 17}" y="17.5" font-family="${FONT}" font-size="11" font-weight="700" fill="${color}">${xml(chip)}</text>
598${lines.map((l, i) => `<text class="m" x="0" y="${36 + i * 16}" font-family="${FONT}" font-size="11.5">${xml(l)}</text>`).join('')}`,
599 ),
600 }
601}
602