Bullswarm as a Claude Mod: live subscription meters for every installed coding-agent CLI above the prompt, quota-aware routing of Claude's own subagents to…

A Claude Mod is a Claude Code plugin whose behaviour is TypeScript running inside Claude Code's engine ("function hooks", early access, enabled with CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1). This folder is that plugin.
The terminal dashboard is Bullswarm's main screen. This Mod is its read-only counterpart: the strip is the run list, and the pane shows the dashboard's Run, Step, and Usage/Pools view in the same meter colours. It does not show the dashboard's Home, Runs, Budget, Stats, History, Fleet, or Help pages, and deliberately exposes no [edit] or [install] action. The pane's bottom row is back (on a step), the workflow and standalone-task buttons, usage, and close. Navigation matches the dashboard's mouse rules: click any button, tab, run, or step, and use the wheel to scroll.
Workflow buttons keep their digit hotkeys. A standalone dispatch has its own task <8-character-tail> button without taking a workflow digit; selecting it opens that task, and back returns to the selected workflow. A task is promoted automatically only when no workflow is in flight.
The pane's usage button is available even when no workflow is running, so it always opens the read-only pools and rungs page. When the workflow list is empty but a live bullswarm run assignment is present, the empty pane opens with Single task in flight and shows that task's lane, pool and model, the tail of its task-file path (falling back to its project or working directory) and its elapsed time; the same in-flight refresh cadence keeps that elapsed value current. Workflow assignments remain part of the run views, while the empty pane only promotes the standalone source: "run" record.
What it adds beyond the packaged skill and the MCP server:
| Hook | What happens | |
|---|---|---|
engine.create | $.bullswarm (pools, refresh, run) for any other plugin | |
session.start | registers /bullswarm, reads the meters, runs and in-flight ledger; re-reads every 2 min, every 20 s while work is in flight | |
prompt.context | a context block naming every pool's surplus and every ongoing workflow run, re-sent only when a pool changes by a bucket or a run starts, ends or changes status; a run waiting at a gate or a loop out of rounds reads waiting at gate approve with the bullswarm workflow continue command that moves it | |
tool.call on Agent | a general-purpose, Explore or Plan subagent runs on the pool with the most surplus via bullswarm run --lane analyze --no-retry: read-only, one attempt, since a build run must change a file and the mod's process budget holds one attempt; the tool result carries the verified output plus a routing note | |
tool.call on Bash | a bullswarm run / bullswarm workflow goal result gets the verdict appended in the doctrine's words, with a run's checked answer (--answer-schema) or its failed answer check; a launched workflow is pointed at bullswarm workflow watch <id> --until trouble; a goal that parked at a gate names the gate and its continue command. A bullswarm workflow watch or workflow wait result gets a note when it shows a v3 run waiting at a gate or a loop out of rounds (with the command), a loop's round, or checked answers | |
command.run /bullswarm | pools, runs, pane, open <step> [run], on, off, refresh, routed | |
ui.render AbovePrompt | the strip: one header line (run count, dispatches in flight, route off when routing is off) with [w], which opens or closes the runs pane; then one row per ongoing workflow run (progress, the step each pool is running with elapsed/expected minutes, the goal) and one per standalone dispatch; a digit in front of a run row opens that run. Routing and refresh are /bullswarm on, off and refresh. The strip option picks runs (default), full (pool meter rows too) or off. Nothing is pinned under the prompt | |
ui.render Pane + ui.scroll | the runs pane, docked beside the transcript. Fixed at the top: the run's header (with first–last/total while scrolled) and [Top] [End]. Fixed at the bottom: the pool rows, the page's hint line, then a button per workflow and standalone task, usage, close. Under 20 body rows (a phone terminal, a short inline pane) the pane draws a compact layout: one header row, one nav row with [Top] [End] and no close (the frame's ✕ closes it), nothing else pinned; ctrl+x up grows an inline pane while it has focus. Between them the whole overview as bullswarm workflow tui draws it (Preflight with the accepted goal and the goal and plan files, every phase, Live workers with their latest activity, Next) from bullswarm workflow tui <id> --overview, with the pool meters last (each bar carries a white mark where the window's elapsed time falls, in the status line's colours). Pools ▸ opens a pools page: every meter window of every pool as a full-width bar with reset time and pace, the credit meter where there is one, and the rungs (model, reasoning and record per pool × tier) grouped by lane or by provider with two tabs; read-only, back returns even when no workflow is running. The mod owns that window: the wheel over the pane, and arrows, PgUp/PgDn, Home/End once the pane has focus (click it), move the middle only. Every workflow step row opens the dashboard's finished Step v2 grammar from compact step.schemaVersion: 2 JSON in bullswarm workflow action show <run> <step> --json; a task button reads the same schema from bullswarm workflow task show <taskId> --json. The mod resolves the selected attempt and its canonical activity while rendering the same rows. Both show one verdict header with the visible overview · detail toggle; the latest 10 turns (5 below 100 columns) and its click for detail fold line; the full turn-and-tool transcript in detail; structured result, task facts, and the dashboard cost rows. Phone order is result → activity → task → cost. The newest overview turn is selected and expanded until the reader chooses another; a running command shows its name and a one-second elapsed clock from the CLI projection. The mod maps good/running/failure, dim, bold and pool-series roles onto its meter palette. v toggles the view, clicking either top tab selects it, and clicking expands overview turns. If the task JSON read fails, the honest unavailable fallback remains. Other in-flight pages refresh every 20 s; an open running Step refreshes every four seconds. | |
tool.call mcp__bullswarm__route | a tool the mod registers so the model can switch auto-routing on or off when the person asks ("stop routing my subagents"); the same switch as `/bullswarm on | off` |
ui.close | keeps the strip's [w] label in step when the person closes the pane |
Pool names in the session context, strip, pane and usage page are display names: an account pool such as claude-code:acme shows as claude-code:a (first letter of the account slug, unless two accounts would collide). A core label set with bullswarm pools label <pool> <label> is used when present. The plugin option poolAliases (/config, or pluginConfigs in settings) overrides any name: claude-code:acme=cc:a,claude-code:initech=cc:i. The durable pool ids remain unchanged because bullswarm derives them from the account's config directory (~/.claude-acme) and the keychain entry is keyed by it.
Observing a run: press the digit shown in front of a run row in the strip (1 for the first run) from an empty prompt, click the row, or press [w], or type /bullswarm pane. Letter hotkeys (b, r, w) fire while the band has focus (click it, or ctrl+x tab); digits fire from an empty composer. Inside the pane, q closes it, r re-reads, and a digit switches runs.
Run it from source for one session:
CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude --plugin-dir mods/bullswarm
Load it in every session with plain claude. The CLI does both halves, linking the folder into the skills directory (a plugin there auto-loads as bullswarm@skills-dir) and setting the early-access flag under env in ~/.claude/settings.json; integrate status reports both and integrate remove undoes them:
bullswarm integrate install --agents claude --yes
Or install it from the repository's plugin marketplace, which copies the mod into Claude's plugin cache (refresh it with claude plugin update) and still needs the flag set:
claude plugin marketplace add Bulls-Work/bullswarm claude plugin install bullswarm@bullswarm
By hand, the two halves are:
ln -sfn "$(npm root -g)/bullswarm/mods/bullswarm" ~/.claude/skills/bullswarm-mod
{ "env": { "CLAUDE_CODE_ENABLE_FUNCTION_HOOKS": "1" } }
Use one route: an installed marketplace copy takes precedence over a skills-dir link with the same name, and Claude says so at startup.
Typecheck against this build's own declarations: inside a session with the mod loaded, /plugin-types mods/types writes claude-code.d.ts (the engine API plus every built-in tool's input and result schema) next to this folder, where tsconfig.json includes it; mods/types/ is generated, not committed.
CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude --plugin-dir mods/bullswarm -p "/plugin-types mods/types" npx -p typescript tsc -p mods/bullswarm/tsconfig.json
Known limits: bullswarm's content gate wants real substance (80+ characters after any "I'll read…" narration), so a delegate that answers in one short line is rejected and the call falls back to an in-session subagent; a delegate run is capped at 9 minutes by $.process.run; /bullswarm is owned by the packaged skill, so the mod answers only its own subcommands on it and hands anything else to the skill.
hooks/register.ts 1088 lines1import type { On, PluginOptions } from 'claude-code'
2
3import type {
4 Bullswarm,
5 BullswarmAssignment,
6 BullswarmPool,
7 BullswarmRun,
8 BullswarmRunArgs,
9 BullswarmRung,
10 BullswarmRunDetail,
11 BullswarmStep,
12 BullswarmVerdict,
13} from '../types'
14import type { Host } from './host'
15import {
16 contextSignature,
17 contextText,
18 cacheFileOf,
19 cacheMaxAgeSec,
20 freshDoc,
21 type CacheName,
22 parsePools,
23 parseRungs,
24 poolLine,
25} from './pools'
26import { argvOf, decide, type AgentArgs } from './route'
27import { aliasesOf, displayNames, withDisplayNames } from './names'
28import { parseOverview, type OverviewLine } from './overview'
29import { type PaneScroll, paneView } from './pane'
30import {
31 parseAssignmentRecord,
32 parseAssignments,
33 parseDetail,
34 parseRuns,
35 parseStep,
36 paneChoice,
37 runLine,
38 standaloneTasks,
39 type BullswarmAssignmentRecord,
40} from './runs'
41import { strip } from './strip'
42import type { StepMode } from './step'
43import { parseVerdict, routedContext, verdictContext, watchContext } from './verdict'
44
45const COMMAND = 'bullswarm'
46const PANE_ID = 'bullswarm'
47/** Body rows the pane asks for while inline above the prompt. */
48const PANE_ROWS = 40
49const PANE_TITLE = 'bullswarm runs'
50const STORE_AUTO_ROUTE = 'bullswarm.autoRoute'
51/** The words the mod answers on `/bullswarm`; anything else is the skill's. */
52const SUBCOMMANDS = new Set(['pools', 'status', 'on', 'off', 'refresh', 'routed', 'runs', 'pane'])
53/** Refresh period while nothing is in flight, and while something is. */
54const IDLE_REFRESH_MS = 120_000
55const BUSY_REFRESH_MS = 20_000
56const STEP_REFRESH_MS = 4_000
57const STEP_TICK_MS = 1_000
58const POOLS_TIMEOUT_MS = 30_000
59/**
60 * Every session reads one shared pools, runs and assignments result (the
61 * file while it is young, else `--json --max-age`, where one caller rebuilds
62 * and the rest answer with the last good set) at most cacheMaxAgeSec old.
63 * Each CLI process is ~300 MB, and 11 sessions refreshing at once on
64 * 2026-10-20 took about 3 GB.
65 */
66const POOLS_MAX_AGE_SEC = 60
67/**
68 * `bullswarm run --timeout`, seconds: under the 10-minute cap on `$.process.run`.
69 * The process budget holds one attempt, which is why the run gets `--no-retry`
70 * (route.ts argvOf).
71 */
72const RUN_TIMEOUT_SEC = 540
73const RUN_PROCESS_MS = 585_000
74/** Rows asked of the overview frame, so the timeline is never windowed. */
75const FULL_FRAME_ROWS = 400
76/** How much of a step's output file the pane shows. */
77const OUTPUT_TAIL_CHARS = 1_800
78/** Lines of the task file the step view shows, as the TUI's agent panel does. */
79const PROMPT_PREVIEW_LINES = 7
80
81type Routed = {
82 at: number
83 description: string
84 lane: string
85 pool: string | null
86 model: string | null
87 outFile: string | null
88 ok: boolean
89 why: string | null
90}
91
92const messageOf = (error: unknown): string =>
93 error instanceof Error ? error.message : String(error)
94
95type RuntimeGlobal = typeof globalThis & {
96 process?: { env?: Record<string, string | undefined> }
97}
98
99/** The same home override the Bullswarm CLI uses for its ledger. */
100function assignmentPath(id: string): string | null {
101 if (!id || /[\\/]/.test(id)) return null
102 const env = (globalThis as RuntimeGlobal).process?.env ?? {}
103 const home = env.BULLSWARM_HOME?.trim() || (env.HOME ? `${env.HOME}/.bullswarm` : '')
104 return home ? `${home.replace(/\/+$/, '')}/assignments/${id}.json` : null
105}
106
107/**
108 * The CLI view contains the timing projection used by the strip. For a
109 * standalone `bullswarm run`, read its ledger file too so the empty pane can
110 * show optional project/task metadata without assuming an old record schema.
111 */
112async function readRunAssignmentFiles(h: Host, values: readonly BullswarmAssignmentRecord[]): Promise<BullswarmAssignmentRecord[]> {
113 const candidates = values.filter(a => a.source === 'run' && !!a.id)
114 if (!candidates.length) return [...values]
115 const direct = await Promise.all(
116 candidates.map(async a => {
117 const path = assignmentPath(a.id!)
118 if (!path) return a
119 try {
120 const raw = JSON.parse(await h.read(path)) as unknown
121 return parseAssignmentRecord(raw, a) ?? a
122 } catch {
123 return a
124 }
125 }),
126 )
127 const byId = new Map(direct.flatMap(a => (a.id ? [[a.id, a] as const] : [])))
128 return values.map(a => (a.id ? byId.get(a.id) ?? a : a))
129}
130
131/**
132 * Registers the mod: `$.bullswarm` in the engine.create fold, `/bullswarm`
133 * and the meter refresh at session.start, the pools in the prompt context,
134 * Agent calls routed through `bullswarm run`, the verdict on Bash calls
135 * that ran bullswarm, and the meter strip above the prompt.
136 *
137 * @param on the engine's registrar
138 */
139export function register(on: On, options: PluginOptions = {}) {
140 const aliases = aliasesOf(options.poolAliases)
141 const stripLevel: 'runs' | 'full' | 'off' =
142 options.strip === 'full' || options.strip === 'off' ? options.strip : 'runs'
143 let names = new Map<string, string>()
144 let host: Host | null = null
145 let cwd = ''
146 let depth: string | undefined
147 let pools: BullswarmPool[] = []
148 /** Where the CLI keeps the shared caches, as a `--max-age` reply's cache file named it. */
149 let cacheDir: string | null = null
150 let runs: BullswarmRun[] = []
151 let assignments: BullswarmAssignment[] = []
152 let nowMs = Date.now()
153 let timerGeneration = 0
154 let stepTickGeneration = 0
155 let paneOpen = false
156 let selectedShortId: string | null = null
157 let selectedTaskId: string | null = null
158 let detail: BullswarmRunDetail | null = null
159 let detailError: string | null = null
160 let overview: OverviewLine[] | null = null
161 let overviewReadAt: number | null = null
162 let selectedActionId: string | null = null
163 let outputTail: string | null = null
164 let paneColumns = 100
165 let paneRows = 30
166 /** The body rows the pane really has, learned from the engine's report (see the render hook). */
167 let paneWant: number | null = null
168 /** The overview's own window: the first scrollable row shown, and its extent. */
169 let paneOffset = 0
170 /** The open step as `action show` reports it, and the head of its task file. */
171 let step: BullswarmStep | null = null
172 let stepMode: StepMode = 'overview'
173 let expandedStepTurn: number | null = null
174 /** The pool × tier rungs, read while the pane is open; the pane's pools section expands to show them. */
175 let rungs: BullswarmRung[] = []
176 /** The pane shows the pools page instead of the run while this is set. */
177 let poolsPage = false
178 /** How the usage page groups the rungs: by effort tier (lane) or by pool. */
179 let rungsBy: 'tier' | 'pool' = 'tier'
180 let promptPreview: string[] = []
181 let paneScroll: PaneScroll | null = null
182 let autoRoute = true
183 let inflight = 0
184 let lastError: string | null = null
185 let ready: Promise<unknown> = Promise.resolve()
186 let signature = ''
187 let own: { kind: string; percentUsed: number }[] = []
188 const routed: Routed[] = []
189
190 function stepActivity(): Record<string, unknown> | null {
191 const page = (step as unknown as { page?: Record<string, unknown> | null } | null)?.page
192 const presentation = page?.presentation
193 if (!presentation || typeof presentation !== 'object' || Array.isArray(presentation)) return null
194 const activity = (presentation as Record<string, unknown>).activity
195 return activity && typeof activity === 'object' && !Array.isArray(activity)
196 ? activity as Record<string, unknown>
197 : null
198 }
199
200 function runningStepOpen(): boolean {
201 const choice = paneChoice(runs, assignments, selectedShortId, selectedTaskId)
202 return paneOpen && Boolean(selectedActionId || choice?.kind === 'task') && stepActivity()?.running === true
203 }
204
205 /** Tick elapsed command time from the engine clock; never refetch for a tick. */
206 function syncStepTick(h: Host) {
207 const generation = ++stepTickGeneration
208 const activity = stepActivity()
209 if (!runningStepOpen() || !activity?.runningCommand) return
210 const tick = () => h.after(STEP_TICK_MS, async () => {
211 if (generation !== stepTickGeneration || !runningStepOpen() || !stepActivity()?.runningCommand) return
212 nowMs = await h.now()
213 h.invalidate('ui.render')
214 tick()
215 })
216 tick()
217 }
218
219 /**
220 * One shared read: the cache file when it is young enough (no process),
221 * else the CLI's `--json --max-age` form, whose reply names the file.
222 */
223 async function readCached<T>(h: Host, name: CacheName, argv: readonly string[], parse: (s: string) => T): Promise<T> {
224 // Meters move slowly and a pools build reads every one: a minute always.
225 const maxAgeSec = name === 'pools'
226 ? POOLS_MAX_AGE_SEC
227 : cacheMaxAgeSec({ stepOpen: runningStepOpen(), busy: assignments.length > 0 || runs.length > 0 })
228 if (cacheDir) {
229 try {
230 const text = await h.read(`${cacheDir}/${name}.json`)
231 const doc = freshDoc(text, name, await h.now(), maxAgeSec * 1000)
232 if (doc) return parse(name === 'assignments' ? JSON.stringify(doc.assignments ?? []) : text)
233 } catch {
234 // No file yet, or it went away: the CLI below answers and rewrites it.
235 }
236 }
237 const r = await h.run([...argv, '--json', '--max-age', String(maxAgeSec)], { timeoutMs: POOLS_TIMEOUT_MS })
238 if (r.exitCode !== 0)
239 throw new Error(r.stderr.trim().split('\n')[0] || `${argv[1]} exited ${r.exitCode}`)
240 const file = cacheFileOf(r.stdout)
241 if (file) cacheDir = file.slice(0, file.lastIndexOf('/'))
242 return parse(r.stdout)
243 }
244
245 function readPools(h: Host): Promise<BullswarmPool[]> {
246 return readCached(h, 'pools', ['bullswarm', 'pools'], parsePools)
247 }
248
249 async function readJson<T>(h: Host, argv: readonly string[], parse: (s: string) => T): Promise<T> {
250 const r = await h.run(argv, { timeoutMs: POOLS_TIMEOUT_MS })
251 if (r.exitCode !== 0)
252 throw new Error(r.stderr.trim().split('\n')[0] || `${argv[1]} exited ${r.exitCode}`)
253 return parse(r.stdout)
254 }
255
256 /**
257 * `action show` can exceed Claude's process-output limit because the Step
258 * record intentionally carries the complete transcript. Keep that exact
259 * model, but let the child split it into sub-limit files inside a validated
260 * temporary directory instead of parsing truncated stdout.
261 */
262 async function readLargeJson<T>(h: Host, argv: readonly string[], parse: (s: string) => T): Promise<T> {
263 const made = await h.run(['mktemp', '-d', '-t', 'bullswarm-step'], { timeoutMs: POOLS_TIMEOUT_MS })
264 const dir = made.stdout.trim()
265 if (made.exitCode !== 0 || !/^\/(?:private\/)?(?:tmp|var\/folders)\/(?:.+\/)?bullswarm-step\.[A-Za-z0-9]+$/.test(dir)) {
266 throw new Error(made.stderr.trim().split('\n')[0] || 'could not create a safe Step transport directory')
267 }
268 try {
269 const shown = await h.run(
270 ['/bin/sh', '-c', 'bullswarm "$@" > "$BULLSWARM_STEP_DIR/step.json" && /usr/bin/split -b 3000000 "$BULLSWARM_STEP_DIR/step.json" "$BULLSWARM_STEP_DIR/part-"', 'bullswarm-step', ...argv.slice(1)],
271 { timeoutMs: POOLS_TIMEOUT_MS, env: { BULLSWARM_STEP_DIR: dir } },
272 )
273 if (shown.exitCode !== 0) throw new Error(shown.stderr.trim().split('\n')[0] || `${argv[1]} exited ${shown.exitCode}`)
274 let text = ''
275 for (const first of 'abcdefghijklmnopqrstuvwxyz') {
276 for (const second of 'abcdefghijklmnopqrstuvwxyz') {
277 try { text += await h.read(`${dir}/part-${first}${second}`) }
278 catch { return parse(text) }
279 }
280 }
281 return parse(text)
282 } finally {
283 await h.run(['/bin/rm', '-rf', '--', dir], { timeoutMs: POOLS_TIMEOUT_MS }).catch(() => undefined)
284 }
285 }
286
287 async function refresh(h: Host): Promise<BullswarmPool[]> {
288 const [p, r, a, g] = await Promise.allSettled([
289 readPools(h),
290 readCached(h, 'runs', ['bullswarm', 'workflow', 'runs'], parseRuns),
291 readCached(h, 'assignments', ['bullswarm', 'assignments'], parseAssignments),
292 paneOpen ? readJson(h, ['bullswarm', 'strategy', 'rungs', '--json'], parseRungs) : Promise.resolve(rungs),
293 ])
294 if (g.status === 'fulfilled') rungs = g.value
295 if (p.status === 'fulfilled') {
296 pools = p.value
297 }
298 if (r.status === 'fulfilled') runs = r.value
299 if (a.status === 'fulfilled') assignments = await readRunAssignmentFiles(h, a.value)
300 const identities = [...new Set([
301 ...pools.map(x => x.name),
302 ...assignments.map(x => x.pool),
303 ...rungs.map(x => x.pool),
304 ])]
305 const coreLabels = new Map<string, string>([
306 ...pools.flatMap(x => x.poolLabel && x.poolLabel !== x.name ? [[x.name, x.poolLabel] as const] : []),
307 ...assignments.flatMap(x => x.poolLabel && x.poolLabel !== x.pool ? [[x.pool, x.poolLabel] as const] : []),
308 ...rungs.flatMap(x => x.poolLabel && x.poolLabel !== x.pool ? [[x.pool, x.poolLabel] as const] : []),
309 ])
310 names = displayNames(identities, aliases, coreLabels)
311 const failed = [p, r, a].find((x): x is PromiseRejectedResult => x.status === 'rejected')
312 lastError = failed ? messageOf(failed.reason) : null
313 nowMs = await h.now()
314 if (selectedTaskId && !standaloneTasks(assignments).some(task => task.id === selectedTaskId)) {
315 selectedTaskId = null
316 step = null
317 detailError = null
318 paneOffset = 0
319 }
320 if (selectedShortId && !runs.some(r => r.shortId === selectedShortId)) {
321 // The selected run finished and left the ongoing list: keep its last
322 // detail on screen, fall to the newest run when one exists. The open
323 // step belonged to the old run, so it goes too — otherwise the pane
324 // asks the new run for a step it never had (`run "w89k6s" has no
325 // action "accept"`, seen 2026-09-17 when tc6cpi finished with its
326 // accept step open).
327 const next = runs[0]?.shortId ?? selectedShortId
328 if (next !== selectedShortId) {
329 selectedActionId = null
330 step = null
331 stepMode = 'overview'
332 expandedStepTurn = null
333 outputTail = null
334 promptPreview = []
335 paneOffset = 0
336 }
337 selectedShortId = next
338 }
339 if (paneOpen) await readDetail(h)
340 try {
341 const usage = await h.usage()
342 own = usage.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed }))
343 } catch {
344 own = []
345 }
346 settle(h)
347 return pools
348 }
349
350 async function readDetail(h: Host): Promise<BullswarmRunDetail | null> {
351 const choice = paneChoice(runs, assignments, selectedShortId, selectedTaskId)
352 if (!choice) {
353 detail = null
354 overview = null
355 step = null
356 syncStepTick(h)
357 return null
358 }
359 if (choice.kind === 'task') {
360 detailError = null
361 selectedActionId = null
362 step = null
363 promptPreview = []
364 outputTail = null
365 try {
366 step = await readLargeJson(h, ['bullswarm', 'workflow', 'task', 'show', choice.taskId, '--json'], text =>
367 parseStep(text, Date.now()),
368 )
369 } catch (error) {
370 detailError = messageOf(error)
371 }
372 syncStepTick(h)
373 schedule(h)
374 return detail
375 }
376 const id = choice.shortId
377 // A frame tall enough to hold the whole timeline: the pane scrolls it,
378 // so no level is hidden behind an "earlier rows" marker. The TUI keeps
379 // two columns for its own borders, which the parser strips, so asking
380 // for two more than the pane makes the text span the whole body.
381 const width = Math.max(40, paneColumns + 2)
382 const height = FULL_FRAME_ROWS
383 const [frame, shown] = await Promise.allSettled([
384 readJson(
385 h,
386 ['bullswarm', 'workflow', 'tui', id, '--overview', `--width=${String(width)}`, `--height=${String(height)}`],
387 text => parseOverview(text).map(l => ({ ...l, text: withDisplayNames(l.text, names) })),
388 ),
389 readJson(h, ['bullswarm', 'workflow', 'runs', 'show', id, '--json'], text =>
390 parseDetail(text, Date.now()),
391 ),
392 ])
393 if (frame.status === 'fulfilled') {
394 overview = frame.value
395 overviewReadAt = Date.now()
396 }
397 if (shown.status === 'fulfilled') detail = shown.value
398 const failed = [frame, shown].find((x): x is PromiseRejectedResult => x.status === 'rejected')
399 detailError = failed ? messageOf(failed.reason) : null
400
401 // The open step: its record and latest attempt as the TUI's agent panel
402 // shows them, the head of its task file, and the tail of its output.
403 step = null
404 promptPreview = []
405 outputTail = null
406 if (selectedActionId) {
407 try {
408 step = await readLargeJson(h, ['bullswarm', 'workflow', 'action', 'show', id, selectedActionId, '--json'], text =>
409 parseStep(text, Date.now()),
410 )
411 } catch (error) {
412 detailError = messageOf(error)
413 }
414 const taskFile = step?.attempt?.taskFile ?? null
415 if (taskFile) {
416 try {
417 const all = (await h.read(taskFile)).split(/\r?\n/).filter(l => l.trim())
418 promptPreview = all.slice(0, PROMPT_PREVIEW_LINES)
419 if (all.length > PROMPT_PREVIEW_LINES) promptPreview.push(`… ${String(all.length - PROMPT_PREVIEW_LINES)} more lines`)
420 } catch {
421 promptPreview = []
422 }
423 }
424 const outputFile = step?.outputFile ?? step?.attempt?.outputFile ?? null
425 if (outputFile) {
426 try {
427 const text = await h.read(outputFile)
428 outputTail = text.length > OUTPUT_TAIL_CHARS ? `…${text.slice(-OUTPUT_TAIL_CHARS)}` : text
429 } catch {
430 outputTail = null
431 }
432 }
433 }
434 syncStepTick(h)
435 schedule(h)
436 return detail
437 }
438
439 async function openPane(h: Host, shortId: string | null) {
440 if (shortId && shortId !== selectedShortId) selectedActionId = null
441 if (shortId) selectedTaskId = null
442 selectedShortId = shortId ?? selectedShortId ?? runs[0]?.shortId ?? null
443 // Seated inline (a phone terminal, a narrow window) the pane asks for
444 // most of the screen: the engine grants what the layout spares, and the
445 // dock beside a wide transcript ignores the request.
446 await h.openPane({ id: PANE_ID, title: PANE_TITLE, holdToasts: true, rows: PANE_ROWS })
447 paneOpen = true
448 settle(h)
449 await readDetail(h)
450 settle(h)
451 }
452
453 async function closePane(h: Host) {
454 await h.closePane({ id: PANE_ID }).catch(() => undefined)
455 paneOpen = false
456 expandedStepTurn = null
457 stepTickGeneration += 1
458 schedule(h)
459 settle(h)
460 }
461
462 /** Redraws what changed: the strip always, the prompt block only on a real change. */
463 function settle(h: Host) {
464 h.invalidate('ui.render')
465 const next = contextSignature(
466 pools,
467 autoRoute,
468 // A run that parks at a gate re-sends the block, so the model sees it wait.
469 runs.map(r => `${r.shortId}:${r.status}`),
470 )
471 if (next !== signature) {
472 signature = next
473 h.invalidate('prompt.context')
474 }
475 }
476
477 async function run(h: Host, args: BullswarmRunArgs): Promise<BullswarmVerdict> {
478 const argv = argvOf({
479 lane: args.lane,
480 cwd: args.cwd,
481 task: args.task,
482 timeoutSec: args.timeoutSec ?? RUN_TIMEOUT_SEC,
483 })
484 const r = await h.run(argv, { timeoutMs: RUN_PROCESS_MS, cwd: args.cwd })
485 return parseVerdict(r.stdout || r.stderr, r.exitCode)
486 }
487
488 /** Re-reads on a cadence that tightens while work is in flight. */
489 function schedule(h: Host) {
490 const generation = ++timerGeneration
491 const period = runningStepOpen()
492 ? STEP_REFRESH_MS
493 : assignments.length || runs.length ? BUSY_REFRESH_MS : IDLE_REFRESH_MS
494 h.after(period, () => {
495 if (generation !== timerGeneration) return
496 void refresh(h).finally(() => {
497 if (generation === timerGeneration) schedule(h)
498 })
499 })
500 }
501
502 async function setAutoRoute(h: Host, value: boolean) {
503 autoRoute = value
504 await h.storeSet(STORE_AUTO_ROUTE, value).catch(() => undefined)
505 settle(h)
506 }
507
508 on('engine.create', async ($, e, next) => {
509 const beneath = await next(e)
510
511 const built: Host = {
512 run: (argv, init) => beneath.process.run(argv, init),
513 usage: () => beneath.session.usage(),
514 read: path => beneath.fs.read(path),
515 storeSet: (key, value) => beneath.store.set(key, value),
516 after: (ms, fn) => beneath.clock.after(ms, fn),
517 now: () => beneath.clock.now(),
518 invalidate: event => beneath.ui.invalidate(event),
519 log: text => beneath.ui.log(text),
520 toast: text => beneath.ui.toast(text, { timeoutMs: 6_000 }),
521 openPane: pane => beneath.ui.open(pane),
522 closePane: pane => beneath.ui.close(pane),
523 }
524
525 const bullswarm: Bullswarm = {
526 pools: async () => (pools.length ? pools : refresh(host ?? built)),
527 refresh: () => refresh(host ?? built),
528 runs: async () => runs,
529 assignments: async () => assignments,
530 detail: async shortId => {
531 const h = host ?? built
532 const d = await readJson(h, ['bullswarm', 'workflow', 'runs', 'show', shortId, '--json'], text =>
533 parseDetail(text, Date.now()),
534 )
535 return d
536 },
537 run: args => run(host ?? built, args),
538 rungs: async () => readJson(host ?? built, ['bullswarm', 'strategy', 'rungs', '--json'], parseRungs),
539 step: async (shortId, actionId) => {
540 const h = host ?? built
541 return readLargeJson(h, ['bullswarm', 'workflow', 'action', 'show', shortId, actionId, '--json'], text =>
542 parseStep(text, Date.now()),
543 )
544 },
545 }
546
547 return { ...beneath, bullswarm }
548 })
549
550 on('session.start', async ($, e, next) => {
551 cwd = e.cwd
552 host = {
553 run: (argv, init) => $.process.run(argv, init),
554 usage: () => $.session.usage(),
555 read: path => $.fs.read(path),
556 storeSet: (key, value) => $.store.set(key, value),
557 after: (ms, fn) => $.clock.after(ms, fn),
558 now: () => $.clock.now(),
559 invalidate: event => $.ui.invalidate(event),
560 log: text => $.ui.log(text),
561 toast: text => $.ui.toast(text, { timeoutMs: 6_000 }),
562 openPane: pane => $.ui.open(pane),
563 closePane: pane => $.ui.close(pane),
564 }
565 const h = host
566 // Nothing pinned under the prompt: the strip and the pane carry the state.
567 $.ui.status(undefined)
568
569 depth = await $.env.get('BULLSWARM_DEPTH').catch(() => undefined)
570
571 const stored = await $.store.get(STORE_AUTO_ROUTE).catch(() => undefined)
572 if (typeof stored === 'boolean') autoRoute = stored
573
574 // Where the packaged skill already owns `/bullswarm`, the engine refuses
575 // the registration and the command.run hook below still answers the
576 // mod's subcommands on the skill's command.
577 try {
578 await $.command.register({
579 name: COMMAND,
580 description: 'Bullswarm meters and routing: pools · on · off · refresh · routed',
581 argumentHint: '[pools|on|off|refresh|routed]',
582 })
583 } catch (error) {
584 const reason = messageOf(error)
585 if (!/is the user's/.test(reason)) $.ui.log(`/${COMMAND} not registered: ${reason}`)
586 }
587
588 ready = refresh(h).finally(() => schedule(h))
589
590 // The person may ask Claude to stop or resume routing: a tool the model
591 // can call, the same switch as `/bullswarm on|off`.
592 await $.tool
593 .register({
594 name: 'route',
595 description:
596 'Switch bullswarm auto-routing of subagents on or off for this session, when the person asks. Off keeps every subagent in-session; on sends general-purpose subagents to the pool with spare quota. Report the resulting state.',
597 inputSchema: {
598 type: 'object',
599 properties: { on: { type: 'boolean', description: 'true to route, false to keep subagents in-session' } },
600 required: ['on'],
601 },
602 })
603 .catch(() => undefined)
604
605 return next(e)
606 })
607
608 on('prompt.context', async ($, e, next) => {
609 const result = await next(e)
610 if (depth) return result
611 await ready
612 if (pools.length === 0) return result
613 return {
614 blocks: [
615 ...result.blocks,
616 {
617 name: 'bullswarm',
618 text: withDisplayNames(contextText(
619 pools,
620 autoRoute,
621 routed.length,
622 runs.map(r => runLine(r, assignments, nowMs)),
623 ), names),
624 },
625 ],
626 }
627 })
628
629 on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
630 const h = host
631 if (!autoRoute || depth || !h) return next(e)
632 await ready
633
634 const args = e as unknown as AgentArgs
635 const decision = decide(args, pools)
636 if (!decision.route) {
637 $.ui.log(`agent stays in-session: ${decision.reason}`)
638 return next(e)
639 }
640
641 const description =
642 typeof args.description === 'string' ? args.description : decision.task.slice(0, 60)
643
644 inflight += 1
645 settle(h)
646 $.ui.notice(
647 e.tool_use_id,
648 `bullswarm: routing this ${decision.lane} subagent to the pool with the most surplus…`,
649 )
650
651 let verdict: BullswarmVerdict
652 try {
653 verdict = await run(h, { lane: decision.lane, task: decision.task, cwd })
654 } catch (error) {
655 inflight -= 1
656 settle(h)
657 $.ui.notice(e.tool_use_id, `bullswarm: ${messageOf(error)} → running in-session`)
658 return next(e)
659 }
660 inflight -= 1
661
662 routed.push({
663 at: Date.now(),
664 description,
665 lane: decision.lane,
666 pool: verdict.pool,
667 model: verdict.model,
668 outFile: verdict.outFile,
669 ok: verdict.ok,
670 why: verdict.why,
671 })
672 void refresh(h)
673
674 if (!verdict.ok || !verdict.outFile) {
675 $.ui.notice(e.tool_use_id, `bullswarm: ${verdict.why ?? 'no verdict'} → running in-session`)
676 return next(e)
677 }
678
679 let output: string
680 try {
681 output = await $.fs.read(verdict.outFile)
682 } catch (error) {
683 $.ui.notice(
684 e.tool_use_id,
685 `bullswarm: output unreadable (${messageOf(error)}) → running in-session`,
686 )
687 return next(e)
688 }
689
690 $.ui.notice(
691 e.tool_use_id,
692 `bullswarm → ${verdict.pool ?? '?'} (${verdict.model ?? '?'}) · ${verdict.why ?? 'verified'}${verdict.notDone ? ` · worker left ${verdict.notDone.count} not done` : ''} · ${verdict.outFile}`,
693 )
694 $.ui.toast(`bullswarm routed "${description}" to ${verdict.pool ?? '?'}`, {
695 timeoutMs: 6_000,
696 })
697
698 const startedAt = routed[routed.length - 1]!.at
699 const elapsedMs = Math.max(0, Date.now() - startedAt)
700 const inputTokens = verdict.inputTokens ?? 0
701 const outputTokens = verdict.outputTokens ?? 0
702
703 // The Agent tool's own completed record, so the model's result channel
704 // validates: the delegate's output as the one text block, bullswarm's
705 // measured usage where it reports one.
706 return {
707 result: {
708 agentId: `bullswarm-${verdict.pool ?? 'pool'}-${startedAt.toString(36)}`,
709 agentType: `bullswarm:${verdict.pool ?? 'pool'}`,
710 content: [{ type: 'text', text: output }],
711 ...(verdict.model ? { resolvedModel: verdict.model, modelsUsed: [verdict.model] } : {}),
712 totalToolUseCount: 0,
713 totalDurationMs: verdict.wallSec !== null ? Math.round(verdict.wallSec * 1000) : elapsedMs,
714 totalTokens: inputTokens + outputTokens,
715 usage: {
716 input_tokens: inputTokens,
717 output_tokens: outputTokens,
718 cache_creation_input_tokens: null,
719 cache_read_input_tokens: null,
720 server_tool_use: null,
721 service_tier: null,
722 cache_creation: null,
723 },
724 status: 'completed',
725 prompt: decision.task,
726 },
727 context: [
728 routedContext(verdict, decision.lane),
729 ],
730 }
731 })
732
733 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
734 const command =
735 typeof (e as { command?: unknown }).command === 'string'
736 ? (e as { command: string }).command
737 : ''
738 const match =
739 /^(?:\s*[A-Z_][A-Z0-9_]*=\S*\s+)*(?:rtk\s+\S+\s+)?(?:\S*\/)?bullswarm\s+(run|workflow\s+goal|workflow\s+(?:watch|wait))\b/m.exec(
740 command,
741 )
742 if (!match) return next(e)
743
744 const result = await next(e)
745 const answered = result as {
746 deny?: string
747 isError?: true
748 result?: unknown
749 context?: readonly string[]
750 }
751 if (answered.deny !== undefined || answered.isError) return result
752
753 const watching = /^workflow\s+(?:watch|wait)/.test(match[1]!)
754 const verb = match[1]!.startsWith('run') ? 'run' : 'workflow goal'
755 // Bash's record: the verdict document is its stdout.
756 const record = answered.result as { stdout?: unknown; stderr?: unknown } | string | undefined
757 const text =
758 typeof record === 'string'
759 ? record
760 : typeof record?.stdout === 'string' && record.stdout.trim()
761 ? record.stdout
762 : typeof record?.stderr === 'string'
763 ? record.stderr
764 : ''
765 // A watch or wait prints lines, not a verdict: its note names where a
766 // v3 run waits, its loop's round and the answers it shows.
767 if (watching) {
768 const note = watchContext(text)
769 return note ? ({ ...result, context: [...(answered.context ?? []), note] } as typeof result) : result
770 }
771 const verdict = parseVerdict(text, 0)
772 const note = verdictContext(verb, verdict)
773
774 if (verb === 'run' && verdict.pool) {
775 routed.push({
776 at: Date.now(),
777 description: 'bullswarm run (Bash)',
778 lane: 'explicit',
779 pool: verdict.pool,
780 model: verdict.model,
781 outFile: verdict.outFile,
782 ok: verdict.ok,
783 why: verdict.why,
784 })
785 }
786 if (host) void refresh(host)
787
788 if (!note) return result
789 return { ...result, context: [...(answered.context ?? []), note] } as typeof result
790 })
791
792 on('command.run', { command: COMMAND }, async ($, e, next) => {
793 const arg = e.args.trim()
794 const h = host
795
796 // The packaged bullswarm skill owns bare `/bullswarm <task>`; the mod
797 // answers only its own words and hands everything else on.
798 const open = /^open\s+(\S+)(?:\s+(\S+))?$/.exec(arg)
799 if (open && h) {
800 // `/bullswarm open <step> [run]`: the pane on that step of the run.
801 const [, stepId, runId] = open
802 await openPane(h, runId ?? null)
803 const known = detail?.actions.map(a => a.id) ?? []
804 if (!known.includes(stepId!)) {
805 return {
806 text: known.length
807 ? `no step "${stepId!}" in ${selectedShortId ?? 'the run'}; steps: ${known.join(', ')}`
808 : `no action list yet for ${selectedShortId ?? 'the run'}`,
809 }
810 }
811 selectedActionId = stepId!
812 await readDetail(h)
813 settle(h)
814 return { text: `pane on ${selectedShortId ?? ''} · ${stepId!}` }
815 }
816 if (!SUBCOMMANDS.has(arg)) return next(e)
817
818 if (h && (arg === 'on' || arg === 'off')) {
819 await setAutoRoute(h, arg === 'on')
820 return { text: `bullswarm auto-route ${arg}` }
821 }
822 if (h && arg === 'refresh') await refresh(h)
823 if (h && arg === 'pane') {
824 await (paneOpen ? closePane(h) : openPane(h, null))
825 return { text: paneOpen ? `runs pane opened on ${selectedShortId ?? 'no run'}` : 'runs pane closed' }
826 }
827 if (arg === 'runs') {
828 const lines = runs.map(r => ` ${runLine(r, assignments, nowMs)}`)
829 const loose = assignments.filter(a => !a.runId || !runs.some(r => r.runId === a.runId))
830 for (const a of loose)
831 lines.push(` standalone ${a.lane} on ${a.pool}${a.model ? ` (${a.model})` : ''} ${a.elapsedMinutes ?? '?'}m elapsed`)
832 return {
833 text: withDisplayNames(lines.length
834 ? [`${runs.length} ongoing run(s), ${assignments.length} step(s) in flight:`, ...lines,
835 'bullswarm workflow watch <shortId> --until trouble wakes you when a run needs you; bullswarm workflow runs result <shortId> --json --summary reads its result'].join('\n')
836 : 'no ongoing workflow runs and nothing in flight', names),
837 }
838 }
839 if (arg === 'routed') {
840 return {
841 text: withDisplayNames(routed.length
842 ? routed
843 .map(
844 r =>
845 `${new Date(r.at).toISOString().slice(11, 19)} ${r.ok ? 'ok ' : 'no '} ${r.lane.padEnd(8)} ${r.pool ?? '-'} (${r.model ?? '-'}) ${r.description}${r.outFile ? ` → ${r.outFile}` : ''}${r.ok ? '' : ` · ${r.why ?? ''}`}`,
846 )
847 .join('\n')
848 : 'nothing routed this session', names),
849 }
850 }
851
852 const lines = [
853 `bullswarm mod · auto-route ${autoRoute ? 'on' : 'off'} · ${routed.length} routed this session${inflight ? ` · ${inflight} in flight` : ''}`,
854 ...(lastError ? [`meter read failed: ${lastError}`] : []),
855 ...pools.map(p => ` ${poolLine(p)}`),
856 ...runs.map(r => ` run ${runLine(r, assignments, nowMs)}`),
857 ...(own.length
858 ? [
859 ` this session: ${own
860 .map(l => `${l.kind} ${Math.round(l.percentUsed)}%`)
861 .join(', ')}`,
862 ]
863 : []),
864 '/bullswarm on|off toggles routing · /bullswarm refresh re-reads · /bullswarm runs shows ongoing workflows · /bullswarm pane opens the pane · /bullswarm open <step> [run] opens a step · /bullswarm routed lists routed calls · bare /bullswarm <task> is the skill',
865 ]
866 return { text: withDisplayNames(lines.join('\n'), names) }
867 })
868
869 on('tool.call', { tool: /^mcp__bullswarm__route$/ }, async ($, e) => {
870 const wanted = (e as { on?: unknown }).on === true
871 if (host) await setAutoRoute(host, wanted)
872 else autoRoute = wanted
873 return {
874 result: `bullswarm auto-route is now ${wanted ? 'on: general-purpose subagents route to the pool with spare quota' : 'off: subagents run in-session'} (the person can also type /bullswarm ${wanted ? 'off' : 'on'}).`,
875 }
876 })
877
878 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
879 if (stripLevel === 'off' || e.surface === 'mobile' || e.props.hasSurvey || pools.length === 0)
880 return next(e)
881
882 const { Box, Text, Button } = await $.ui.resolve(e)
883 const h = host
884
885 return strip(
886 { ui: { Box, Text, Button }, columns: e.props.bodyColumns, maxRows: e.props.maxRows },
887 {
888 pools,
889 runs,
890 assignments,
891 autoRoute,
892 routedCount: routed.length,
893 lastError,
894 paneOpen,
895 selectedShortId,
896 names,
897 level: stripLevel,
898 },
899 {
900 pane: () => {
901 if (!h) return
902 void (paneOpen ? closePane(h) : openPane(h, null))
903 },
904 open: shortId => {
905 if (!h) return
906 void (paneOpen && selectedShortId === shortId ? closePane(h) : openPane(h, shortId))
907 },
908 },
909 )
910 })
911
912 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
913 if (e.requestId !== PANE_ID || e.surface === 'mobile') return next(e)
914 const { Box, Text, Button } = await $.ui.resolve(e)
915 const h = host
916 const choice = paneChoice(runs, assignments, selectedShortId, selectedTaskId)
917 const selected = choice?.kind === 'workflow'
918 ? (runs.find(r => r.shortId === choice.shortId) ?? null)
919 : null
920 const selectedTask = choice?.kind === 'task'
921 ? (standaloneTasks(assignments).find(task => task.id === choice.taskId) ?? null)
922 : null
923
924 // The frame is sized to the pane; a resize re-reads at the new size.
925 // The engine reports the body as the lesser of the rows it granted and
926 // the rows the tree drew, so a tree sized to the report would only ever
927 // shrink. The tree carries blank probe rows past its footer; the report
928 // is then the grant itself, and the frame is laid out to that.
929 const reported = e.props.scroll.bodyRows
930 const grew = reported > 0 && reported !== paneWant
931 if (grew) paneWant = reported
932 const resized = paneColumns !== e.props.bodyColumns || paneRows !== reported
933 paneColumns = e.props.bodyColumns
934 paneRows = reported
935 const bodyRows = paneWant ?? Math.max(reported, 5)
936
937 // The engine still shows the pane across a module reload: adopt it, and
938 // read the frame the fresh environment does not have yet.
939 if ((!paneOpen || resized) && h) {
940 paneOpen = true
941 void readDetail(h).then(() => settle(h))
942 } else if (grew && h) {
943 settle(h)
944 }
945
946 const action = selectedActionId ? (detail?.actions.find(a => a.id === selectedActionId) ?? null) : null
947
948 const view = paneView(
949 { ui: { Box, Text, Button }, columns: e.props.bodyColumns },
950 {
951 runs,
952 selected,
953 selectedTask,
954 overview,
955 detail,
956 action,
957 step,
958 stepMode,
959 expandedStepTurn,
960 promptPreview,
961 outputTail,
962 pools,
963 assignments,
964 rungs,
965 poolsPage,
966 rungsBy,
967 readAt: overviewReadAt,
968 nowMs,
969 error: detailError,
970 names,
971 offset: paneOffset,
972 bodyRows,
973 },
974 {
975 select: shortId => {
976 paneOffset = 0
977 poolsPage = false
978 stepMode = 'overview'
979 expandedStepTurn = null
980 if (h) void openPane(h, shortId)
981 },
982 selectTask: taskId => {
983 selectedTaskId = taskId
984 selectedActionId = null
985 poolsPage = false
986 stepMode = 'overview'
987 expandedStepTurn = null
988 paneOffset = 0
989 if (h) {
990 settle(h)
991 void readDetail(h).then(() => settle(h))
992 }
993 },
994 openAction: actionId => {
995 selectedActionId = actionId
996 stepMode = 'overview'
997 expandedStepTurn = null
998 paneOffset = 0
999 if (h) {
1000 settle(h)
1001 void readDetail(h).then(() => settle(h))
1002 }
1003 },
1004 back: () => {
1005 const wasPoolsPage = poolsPage
1006 poolsPage = false
1007 if (!wasPoolsPage) {
1008 selectedActionId = null
1009 selectedTaskId = null
1010 }
1011 outputTail = null
1012 step = null
1013 stepMode = 'overview'
1014 expandedStepTurn = null
1015 paneOffset = 0
1016 if (h) {
1017 syncStepTick(h)
1018 schedule(h)
1019 settle(h)
1020 }
1021 },
1022 toggleStep: () => {
1023 stepMode = stepMode === 'overview' ? 'detail' : 'overview'
1024 expandedStepTurn = null
1025 paneOffset = 0
1026 if (h) h.invalidate('ui.render')
1027 },
1028 setStepMode: mode => {
1029 stepMode = mode
1030 expandedStepTurn = null
1031 paneOffset = 0
1032 if (h) h.invalidate('ui.render')
1033 },
1034 expandStepTurn: turnIndex => {
1035 expandedStepTurn = expandedStepTurn === turnIndex ? null : turnIndex
1036 if (h) h.invalidate('ui.render')
1037 },
1038 setRungsBy: by => {
1039 rungsBy = by
1040 if (h) h.invalidate('ui.render')
1041 },
1042 openPools: () => {
1043 poolsPage = true
1044 paneOffset = 0
1045 if (!h) return
1046 h.invalidate('ui.render')
1047 if (!rungs.length) void refresh(h)
1048 },
1049 scrollTo: where => {
1050 paneOffset = where === 'start' ? 0 : Number.MAX_SAFE_INTEGER
1051 if (h) h.invalidate('ui.render')
1052 },
1053 close: () => {
1054 if (h) void closePane(h)
1055 },
1056 },
1057 )
1058 paneScroll = view.scroll
1059 if (view.scroll) paneOffset = view.scroll.offset
1060 return view.tree
1061 })
1062
1063 // The overview draws its own window under a fixed header and footer, so
1064 // the person's wheel and scroll keys move that window rather than the
1065 // engine's; the step view is left to the engine.
1066 on('ui.scroll', { requestId: PANE_ID }, async ($, e, next) => {
1067 if (!paneScroll) return next(e)
1068 const max = Math.max(0, paneScroll.contentRows - paneScroll.windowRows)
1069 paneOffset = Math.max(0, Math.min(max, paneOffset + e.by))
1070 $.ui.invalidate('ui.render')
1071 return {}
1072 })
1073
1074 on('ui.close', { id: PANE_ID }, async ($, e, next) => {
1075 const result = await next(e)
1076 if (result.deny === undefined) {
1077 paneOpen = false
1078 expandedStepTurn = null
1079 stepTickGeneration += 1
1080 if (host) {
1081 schedule(host)
1082 settle(host)
1083 }
1084 }
1085 return result
1086 })
1087}
1088hooks/host.ts 27 lines1import type {
2 PaneCloseArgs,
3 PaneOpenArgs,
4 ProcessRunInit,
5 ProcessRunResult,
6 SessionUsage,
7} from 'claude-code'
8
9/**
10 * The calls on `$` the mod's helpers make, each a closure written where
11 * `$` is in scope: the engine tracks side effects at the call site, so `$`
12 * itself is never passed around.
13 */
14export type Host = {
15 run: (argv: readonly string[], init?: ProcessRunInit) => Promise<ProcessRunResult>
16 usage: () => Promise<SessionUsage>
17 read: (path: string) => Promise<string>
18 storeSet: (key: string, value: unknown) => Promise<void>
19 after: (ms: number, fn: () => void) => unknown
20 now: () => number | Promise<number>
21 invalidate: (event: 'ui.render' | 'prompt.context') => void
22 log: (text: string) => void
23 toast: (text: string) => void
24 openPane: (pane: PaneOpenArgs) => Promise<void>
25 closePane: (pane: PaneCloseArgs) => Promise<void>
26}
27hooks/pools.ts 279 lines1import type { BullswarmPool, BullswarmRung, BullswarmWindow } from '../types'
2
3type Raw = Record<string, unknown>
4
5const num = (v: unknown): number | null =>
6 typeof v === 'number' && Number.isFinite(v) ? v : null
7
8const str = (v: unknown): string | null => (typeof v === 'string' ? v : null)
9
10/**
11 * Reads `bullswarm pools --json` into the pool model, test fixtures left out.
12 *
13 * @param stdout the command's stdout
14 * @returns the pools, in bullswarm's order
15 */
16export function parsePools(stdout: string): BullswarmPool[] {
17 const doc = JSON.parse(stdout) as { pools?: Raw[] }
18 const raw = Array.isArray(doc.pools) ? doc.pools : []
19
20 return raw
21 .filter(p => p.testFixture !== true && typeof p.name === 'string')
22 .map(p => {
23 const q = p.quarantine as Raw | null | undefined
24
25 return {
26 name: p.name as string,
27 poolLabel: str(p.poolLabel),
28 enabled: p.enabled === true,
29 ...windowsOf(p, num(p.elapsedPct), str(p.pacingWindow)),
30 usedPct: num(p.usedPct),
31 elapsedPct: num(p.elapsedPct),
32 pace: num(p.pace),
33 pacingWindow: str(p.pacingWindow),
34 fiveHourUsedPct: num(p.fiveHourUsedPct),
35 costRank: num(p.costRank),
36 meterSource: str(p.meterSource),
37 meterError: str(p.meterError),
38 meterHoldUntil: num(p.meterHoldUntil),
39 quarantine:
40 q && typeof q === 'object'
41 ? {
42 until: num(q.until) ?? 0,
43 reason: str(q.reason) ?? '',
44 kind: str(q.kind) ?? 'unknown',
45 }
46 : null,
47 }
48 })
49}
50
51/** How far the reader's clock may run behind the writer's and still count the file as fresh. */
52const CLOCK_SLACK_MS = 10_000
53
54/** The shared caches the CLI writes under `<home>/cache/<name>.json`. */
55export type CacheName = 'pools' | 'runs' | 'assignments'
56
57/**
58 * A shared cache file's doc, when it is at most `maxAgeMs` old; null when it
59 * is older, unreadable or another cache's schema, and the mod then asks the
60 * CLI's `--json --max-age` form (which rebuilds it once for every session).
61 *
62 * @param text the cache file's contents
63 * @param name which cache the file should be
64 * @param nowMs the reader's clock
65 * @param maxAgeMs the oldest result to take
66 */
67export function freshDoc(text: string, name: CacheName, nowMs: number, maxAgeMs: number): Raw | null {
68 let doc: Raw
69 try {
70 doc = JSON.parse(text) as Raw
71 } catch {
72 return null
73 }
74 const savedAt = num(doc?.savedAt)
75 if (doc?.schema !== `bullswarm.${name}-cache.v1` || savedAt === null) return null
76 const age = nowMs - savedAt
77 if (age > maxAgeMs || age < -CLOCK_SLACK_MS) return null
78 return doc
79}
80
81/** The pools from the shared cache file while it is young enough, else null. */
82export function freshPools(text: string, nowMs: number, maxAgeMs: number): BullswarmPool[] | null {
83 return freshDoc(text, 'pools', nowMs, maxAgeMs) ? parsePools(text) : null
84}
85
86/**
87 * How old a shared answer the mod takes, in seconds: a minute while nothing
88 * is in flight, and younger while work is, so progress does not lag behind
89 * the refresh cadence (20 s busy, 4 s on an open running step).
90 */
91export function cacheMaxAgeSec(state: { stepOpen: boolean; busy: boolean }): number {
92 return state.stepOpen ? 3 : state.busy ? 15 : 60
93}
94
95/** The cache file a `--json --max-age` reply names, or null. */
96export function cacheFileOf(stdout: string): string | null {
97 try {
98 const doc = JSON.parse(stdout) as { cache?: { file?: unknown } }
99 return str(doc?.cache?.file)
100 } catch {
101 return null
102 }
103}
104
105const WINDOW_MS: Record<string, number> = { '5h': 5 * 3600_000, '7d': 7 * 86_400_000 }
106
107/** The meter windows of one pool record, with elapsed% from each reset time. */
108function windowsOf(
109 p: Raw,
110 pacingElapsed: number | null,
111 pacingWindow: string | null,
112): Pick<BullswarmPool, 'windows' | 'capturedAt' | 'planType' | 'credits'> {
113 const snap = (p.meterSnapshot ?? null) as Raw | null
114 if (!snap) return { windows: [], capturedAt: null, planType: null, credits: null }
115 const capturedAt = str(snap.captured_at)
116 const nowMs = capturedAt ? Date.parse(capturedAt) : Date.now()
117 const windows: BullswarmWindow[] = []
118 const pacingKey = pacingWindow === 'monthly' ? 'mo' : pacingWindow === 'weekly' ? '7d' : pacingWindow === 'fiveHour' ? '5h' : null
119 for (const [key, field] of [['5h', 'five_hour'], ['7d', 'seven_day'], ['mo', 'monthly']] as const) {
120 const w = snap[field] as Raw | null | undefined
121 const used = w ? num(w.utilization) : null
122 if (used === null) continue
123 const resetsAt = w ? str(w.resets_at) : null
124 let elapsedPct: number | null = null
125 if (key === pacingKey && pacingElapsed !== null) elapsedPct = pacingElapsed
126 else if (resetsAt && WINDOW_MS[key]) {
127 const left = Date.parse(resetsAt) - nowMs
128 if (Number.isFinite(left)) elapsedPct = Math.max(0, Math.min(100, 100 - (left / WINDOW_MS[key]!) * 100))
129 }
130 windows.push({ key, usedPct: used, resetsAt, elapsedPct })
131 }
132 const quota = (snap.monthly_quota ?? null) as Raw | null
133 const credits =
134 quota && num(quota.used) !== null && num(quota.limit) !== null
135 ? { used: num(quota.used)!, limit: num(quota.limit)!, unit: str(quota.unit) ?? 'credits' }
136 : null
137 return { windows, capturedAt, planType: str(snap.plan_type), credits }
138}
139
140/** Reads `bullswarm strategy rungs --json`. */
141export function parseRungs(stdout: string): BullswarmRung[] {
142 const doc = JSON.parse(stdout) as { rungs?: Raw[] }
143 const raw = Array.isArray(doc.rungs) ? doc.rungs : []
144 return raw
145 .filter(r => typeof r.pool === 'string' && typeof r.tier === 'string')
146 .map(r => {
147 const reasoning = (r.reasoning ?? null) as Raw | null
148 const record = (r.record ?? null) as Raw | null
149 return {
150 pool: r.pool as string,
151 poolLabel: str(r.poolLabel),
152 tier: r.tier as string,
153 model: str(r.model),
154 reasoning: reasoning ? (str(reasoning.applied) ?? str(reasoning.requested)) : null,
155 dispatches: record ? (num(record.dispatches) ?? 0) : 0,
156 okShare: record ? num(record.okShare) : null,
157 medianMinutes: record ? num(record.medianMinutes) : null,
158 }
159 })
160}
161
162/** `+11.6` / `−4.5` / `n/a`. */
163export function paceText(p: BullswarmPool): string {
164 if (p.pace === null) return 'no meter'
165 const sign = p.pace >= 0 ? '+' : '−'
166 return `${sign}${Math.abs(p.pace).toFixed(1)}`
167}
168
169/** One word for the pool's state, and the color it draws in. */
170export function stateOf(p: BullswarmPool): { word: string; color: string } {
171 if (!p.enabled) return { word: 'disabled', color: 'gray' }
172 if (p.quarantine) return { word: 'quarantined', color: 'red' }
173 if (p.pace === null) return { word: 'unmetered', color: 'gray' }
174 if (p.pace >= 10) return { word: 'surplus', color: 'green' }
175 if (p.pace >= 0) return { word: 'on pace', color: 'cyan' }
176 return { word: 'over pace', color: 'yellow' }
177}
178
179/** A `[████░░░░░░]` bar of `width` cells for a percent. */
180export function barOf(pct: number | null, width: number): string {
181 if (pct === null) return '·'.repeat(width)
182 const filled = Math.max(0, Math.min(width, Math.round((pct / 100) * width)))
183 return '█'.repeat(filled) + '░'.repeat(width - filled)
184}
185
186const hhmm = (ms: number): string => {
187 const d = new Date(ms)
188 const p = (n: number) => String(n).padStart(2, '0')
189 return `${p(d.getUTCHours())}:${p(d.getUTCMinutes())}Z`
190}
191
192/** One plain-text line per pool, for `/bullswarm` and the prompt context. */
193export function poolLine(p: BullswarmPool): string {
194 const state = stateOf(p).word
195 if (!p.enabled) return `${p.name}: disabled`
196 if (p.quarantine)
197 return `${p.name}: quarantined until ${hhmm(p.quarantine.until)} (${p.quarantine.kind})`
198 if (p.pace === null) return `${p.name}: enabled, no provider meter`
199 return `${p.name}: ${p.usedPct}% used, ${Math.round(p.elapsedPct ?? 0)}% of ${p.pacingWindow ?? 'window'} elapsed, ${state} ${paceText(p)}`
200}
201
202/**
203 * The block `prompt.context` adds: what bullswarm is, the pools, and what
204 * auto-route does, so the model knows its headroom without a tool call.
205 */
206export function contextText(
207 pools: readonly BullswarmPool[],
208 autoRoute: boolean,
209 routedCount: number,
210 runLines: readonly string[] = [],
211): string {
212 const lines = pools.filter(p => p.enabled).map(p => `- ${poolLine(p)}`)
213 const routing = autoRoute
214 ? 'Auto-route is ON: an Agent tool call whose subagent_type is general-purpose, claude, Explore or Plan (not forked, not background, no isolation) is offered to bullswarm first and, when a pool has spare quota, runs there read-only (the analyze lane of bullswarm, one attempt) instead of as a Claude subagent, so keep file edits in-session; its tool result then carries a "routed by bullswarm" note naming the pool, the model and the verified output file. Treat that output as evidence to check, never as authority. Anything bullswarm cannot place runs in-session as usual.'
215 : 'Auto-route is OFF: subagents run in-session. `/bullswarm on` turns routing back on.'
216
217 return [
218 'Bullswarm is loaded as a Claude Mod. Delegate pools now (surplus = window elapsed% − quota used%; positive is spare quota):',
219 ...lines,
220 ...(runLines.length
221 ? [
222 'Ongoing bullswarm workflow runs (`bullswarm workflow watch <shortId> --until trouble` wakes you when one waits at a gate, runs a loop out of rounds or has a step that needs you; `/bullswarm runs` shows progress):',
223 ...runLines.map(l => `- ${l}`),
224 ]
225 : []),
226 routing,
227 routedCount
228 ? `${routedCount} subagent call(s) were routed this session; \`/bullswarm routed\` lists them.`
229 : '',
230 '`/bullswarm pools` prints the meters. For explicit delegation use `bullswarm run` (one bounded task) or `bullswarm workflow goal` (a program), as the bullswarm skill describes; the mod appends the verdict to their Bash result.',
231 ]
232 .filter(Boolean)
233 .join('\n')
234}
235
236/**
237 * What the context block depends on, coarsely: a change here re-sends the
238 * block, so surplus is bucketed to keep the prompt cache warm.
239 */
240export function contextSignature(
241 pools: readonly BullswarmPool[],
242 autoRoute: boolean,
243 runIds: readonly string[] = [],
244): string {
245 return (
246 String(autoRoute) +
247 '|' +
248 runIds.join(',') +
249 '|' +
250 pools
251 .map(
252 p =>
253 `${p.name}:${p.enabled ? 1 : 0}:${p.quarantine ? 'q' : ''}:${
254 p.pace === null ? 'n' : Math.round(p.pace / 10)
255 }`,
256 )
257 .join(',')
258 )
259}
260
261/** The status line under the prompt. */
262export function statusText(
263 pools: readonly BullswarmPool[],
264 autoRoute: boolean,
265 inflight: number,
266 lastError: string | null,
267 names: ReadonlyMap<string, string> = new Map(),
268): string {
269 if (lastError) return `bullswarm: ${lastError}`
270 const best = pools
271 .filter(p => p.enabled && !p.quarantine && p.pace !== null)
272 .sort((a, b) => (b.pace ?? 0) - (a.pace ?? 0))[0]
273 const head = best
274 ? `most surplus: ${names.get(best.name) ?? best.name} ${paceText(best)}`
275 : 'no metered pool available'
276 const flight = inflight ? ` · ${inflight} routed run(s) in flight` : ''
277 return `bullswarm ${autoRoute ? 'auto-route on' : 'auto-route off'} · ${head}${flight}`
278}
279hooks/route.ts 83 lines1import type { BullswarmLane, BullswarmPool } from '../types'
2
3/** The Agent tool's arguments as the tool.call event carries them. */
4export type AgentArgs = {
5 prompt?: unknown
6 description?: unknown
7 subagent_type?: unknown
8 isolation?: unknown
9 run_in_background?: unknown
10 fork?: unknown
11 model?: unknown
12}
13
14/**
15 * Which bullswarm lane a subagent type maps to; a missing entry keeps it
16 * in-session. General subagents go to analyze: a build run must change a
17 * file (run-step.js), so a subagent that only answers would fail
18 * `not-produced` there, and a routed subagent's value is its answer.
19 */
20const LANE_OF: Record<string, BullswarmLane> = {
21 '': 'analyze',
22 'general-purpose': 'analyze',
23 claude: 'analyze',
24 Explore: 'analyze',
25 Plan: 'analyze',
26}
27
28export type RouteDecision =
29 | { route: true; lane: BullswarmLane; task: string }
30 | { route: false; reason: string }
31
32/**
33 * Decides whether an Agent call may leave the session: only plain subagent
34 * types, with a text prompt, not forked, not background, not isolated.
35 */
36export function decide(args: AgentArgs, pools: readonly BullswarmPool[]): RouteDecision {
37 const type = typeof args.subagent_type === 'string' ? args.subagent_type : ''
38 const lane = LANE_OF[type]
39 if (!lane) return { route: false, reason: `subagent_type ${type} stays in-session` }
40 if (typeof args.prompt !== 'string' || !args.prompt.trim())
41 return { route: false, reason: 'no prompt text' }
42 if (args.fork === true) return { route: false, reason: 'forked agents need this conversation' }
43 if (args.run_in_background === true)
44 return { route: false, reason: 'background agents report back later' }
45 if (typeof args.isolation === 'string' && args.isolation)
46 return { route: false, reason: `isolation ${args.isolation} is a session feature` }
47
48 const candidates = pools.filter(
49 p => p.enabled && !p.quarantine && p.name !== 'claude-code',
50 )
51 if (candidates.length === 0)
52 return { route: false, reason: 'no enabled, unquarantined delegate pool' }
53
54 return { route: true, lane, task: args.prompt }
55}
56
57/**
58 * The argv `$.process.run` spawns; no shell, the task inline. `--no-retry`:
59 * the mod's process budget holds one attempt, and a failed run already
60 * falls back to running the subagent in-session.
61 */
62export function argvOf(input: {
63 lane: BullswarmLane
64 cwd: string
65 task: string
66 timeoutSec: number
67}): string[] {
68 return [
69 'bullswarm',
70 'run',
71 '--lane',
72 input.lane,
73 '--add-dir',
74 input.cwd,
75 '--json',
76 '--no-retry',
77 '--timeout',
78 String(input.timeoutSec),
79 '--prompt',
80 input.task,
81 ]
82}
83hooks/names.ts 67 lines1/**
2 * Display names for pools: a `prefix:slug` account pool shows as
3 * `prefix:<first letter of slug>` unless two accounts would collide, and
4 * the plugin's `poolAliases` option (`from=to,from=to`) overrides any name.
5 */
6export function aliasesOf(option: unknown): Map<string, string> {
7 const map = new Map<string, string>()
8 if (typeof option !== 'string') return map
9 for (const pair of option.split(',')) {
10 const [from, to] = pair.split('=').map(s => s.trim())
11 if (from && to) map.set(from, to)
12 }
13 return map
14}
15
16export function displayNames(
17 pools: readonly string[],
18 aliases: ReadonlyMap<string, string>,
19 coreLabels: ReadonlyMap<string, string> = new Map(),
20): Map<string, string> {
21 const out = new Map<string, string>()
22 const taken = new Map<string, string>()
23 for (const name of pools) {
24 const alias = aliases.get(name)
25 if (alias) {
26 out.set(name, alias)
27 taken.set(alias, name)
28 }
29 }
30 for (const name of pools) {
31 if (out.has(name)) continue
32 const core = coreLabels.get(name)
33 if (core && !taken.has(core)) {
34 out.set(name, core)
35 taken.set(core, name)
36 continue
37 }
38 const at = name.indexOf(':')
39 const slug = at >= 0 ? name.slice(at + 1) : ''
40 let short = name
41 if (slug.length > 1) {
42 const prefix = name.slice(0, at)
43 const letter = `${prefix}:${slug[0]}`
44 const clash = pools.some(
45 other =>
46 other !== name &&
47 !aliases.has(other) &&
48 other.startsWith(`${prefix}:`) &&
49 other.slice(at + 1)[0] === slug[0],
50 )
51 short = clash || taken.has(letter) ? name : letter
52 }
53 out.set(name, short)
54 taken.set(short, name)
55 }
56 return out
57}
58
59/** Rewrites every full pool name in a text line to its display name. */
60export function withDisplayNames(text: string, names: ReadonlyMap<string, string>): string {
61 let out = text
62 for (const [full, short] of [...names.entries()].sort((a, b) => b[0].length - a[0].length)) {
63 if (full !== short) out = out.split(full).join(short)
64 }
65 return out
66}
67hooks/overview.ts 52 lines1/**
2 * One line of the run overview as bullswarm draws it, classified for the
3 * pane: a section header, a timestamped milestone, a detail line, or plain.
4 */
5export type OverviewLine = {
6 text: string
7 kind: 'header' | 'section' | 'milestone' | 'detail' | 'plain' | 'blank'
8 /** The right-aligned value bullswarm put at the end, when the row has one. */
9 tone: 'ok' | 'fail' | 'running' | 'none'
10}
11
12/**
13 * Reads the frame `bullswarm workflow tui <id> --overview` prints: the box
14 * border comes off (the pane draws its own), section titles become headers.
15 */
16export function parseOverview(stdout: string): OverviewLine[] {
17 const lines: OverviewLine[] = []
18 for (const raw of stdout.split('\n')) {
19 const line = raw.replace(/\s+$/, '')
20 if (!line) continue
21 if (/^[┌├]/.test(line)) {
22 const title = line.replace(/^[┌├]\s?/, '').replace(/[─┐┤]+$/, '').trim()
23 if (title) lines.push({ text: title, kind: 'header', tone: 'none' })
24 continue
25 }
26 if (/^└/.test(line)) continue
27 const inner = line.replace(/^│/, '').replace(/│$/, '').replace(/\s+$/, '')
28 if (!inner.trim()) {
29 if (lines.length && lines[lines.length - 1]!.kind !== 'blank')
30 lines.push({ text: '', kind: 'blank', tone: 'none' })
31 continue
32 }
33 const tone: OverviewLine['tone'] = /✓|✔/.test(inner)
34 ? 'ok'
35 : /✗|×|failed|blocked/.test(inner)
36 ? 'fail'
37 : /running|∴|◐|◑|◒|◓|⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏/.test(inner)
38 ? 'running'
39 : 'none'
40 const kind: OverviewLine['kind'] = /^── /.test(inner)
41 ? 'section'
42 : /^\d{2}:\d{2}\s/.test(inner)
43 ? 'milestone'
44 : /^\s{3,}/.test(inner) || /^\s*[↳↓↑]/.test(inner)
45 ? 'detail'
46 : 'plain'
47 lines.push({ text: inner, kind, tone })
48 }
49 while (lines.length && lines[lines.length - 1]!.kind === 'blank') lines.pop()
50 return lines
51}
52hooks/pane.tsx 693 lines1/* @jsxRuntime classic */
2/* @jsx h */
3/* @jsxFrag Fragment */
4import type { ElementTable, RenderElement } from 'claude-code'
5
6import type {
7 BullswarmAction,
8 BullswarmAssignment,
9 BullswarmPool,
10 BullswarmRun,
11 BullswarmRunDetail,
12 BullswarmRung,
13 BullswarmStep,
14} from '../types'
15import type { OverviewLine } from './overview'
16import { METER_AMBER, METER_GREEN, METER_RED, meterBar, poolRows, severityColor } from './pool-rows'
17import { ageOf, standaloneTasks } from './runs'
18import { shapeStep, taskStepPane, type StepMode, type StepPaneRow } from './step'
19
20export type PaneUi = Pick<ElementTable<'terminal' | 'desktop'>, 'Box' | 'Text' | 'Button'>
21
22export type PaneModel = {
23 runs: readonly BullswarmRun[]
24 selected: BullswarmRun | null
25 /** The standalone task explicitly selected, or promoted because no workflow exists. */
26 selectedTask: BullswarmAssignment | null
27 overview: readonly OverviewLine[] | null
28 detail: BullswarmRunDetail | null
29 /** The action the person opened, when one is open. */
30 action: BullswarmAction | null
31 /** That step as `action show` reports it, when read. */
32 step: BullswarmStep | null
33 /** Pane-local mode/turn state; the host may persist and update these. */
34 stepMode?: StepMode
35 expandedStepTurn?: number | null
36 /** The head of the step's task file, one entry per line. */
37 promptPreview: readonly string[]
38 /** The tail of that action's output file, when read. */
39 outputTail: string | null
40 pools: readonly BullswarmPool[]
41 assignments: readonly BullswarmAssignment[]
42 /** Every pool × tier rung, for the expanded pools section. */
43 rungs: readonly BullswarmRung[]
44 /** The pools page is open instead of the run. */
45 poolsPage: boolean
46 /** How that page groups the rungs. */
47 rungsBy: 'tier' | 'pool'
48 readAt: number | null
49 nowMs: number
50 error: string | null
51 names: ReadonlyMap<string, string>
52 /** The first scrollable row the overview shows; 0 at the top. */
53 offset: number
54 /** The rows the pane body has, as the engine drew it. */
55 bodyRows: number
56}
57
58/** How the overview's own window sits over its scrollable rows. */
59export type PaneScroll = {
60 offset: number
61 contentRows: number
62 windowRows: number
63}
64
65export type PaneActions = {
66 select: (shortId: string) => void
67 selectTask: (taskId: string) => void
68 openAction: (actionId: string) => void
69 /** Optional until the host wires the pane's v/Enter controls to state. */
70 toggleStep?: () => void
71 setStepMode?: (mode: StepMode) => void
72 expandStepTurn?: (turnIndex: number) => void
73 /** Moves the overview's window to its top or bottom. */
74 scrollTo: (where: 'start' | 'end') => void
75 /** Opens the pools page: every meter window and the model per tier. */
76 openPools: () => void
77 /** Groups the rung table by effort tier (lane) or by pool. */
78 setRungsBy: (by: 'tier' | 'pool') => void
79 back: () => void
80 close: () => void
81}
82
83/** The single-row Usage header, including the oldest failed meter reason. */
84export function poolsHeaderText(
85 pools: readonly BullswarmPool[],
86 nowMs: number,
87 nameOf: (pool: string | null) => string = pool => pool ?? '',
88): string {
89 const sampled = pools
90 .filter(p => !!p.capturedAt)
91 .sort((a, b) => Date.parse(a.capturedAt!) - Date.parse(b.capturedAt!))
92 const oldest = sampled[0] ?? null
93 const oldestError = sampled.find(p => !!p.meterError) ?? null
94 const shown = oldestError ?? oldest
95 if (!shown) return 'Pools · no meter snapshot yet'
96 const age = ageOf(shown.capturedAt, nowMs) || '0m'
97 return oldestError
98 ? `Pools · ${nameOf(shown.name)} sampled ${age} ago · ${oldestError.meterError}`
99 : `Pools · sampled ${age} ago`
100}
101
102/** Below this many body rows the pane draws its compact layout (a phone terminal, a short inline pane). */
103export const COMPACT_ROWS = 20
104/** Blank rows drawn past the footer so the engine reports the pane's true height. */
105const PROBE_ROWS = 8
106
107const toneColor = (tone: OverviewLine['tone']): string | undefined =>
108 tone === 'ok' ? 'green' : tone === 'fail' ? 'red' : tone === 'running' ? 'cyan' : undefined
109
110type AssignmentRecord = BullswarmAssignment & {
111 id?: string
112 startedAt?: string
113 project?: string
114 projectName?: string
115 cwd?: string
116 taskFile?: string
117 task?: string
118 description?: string
119}
120
121const pathTail = (value: string): string => value.split(/[\\/]/).filter(Boolean).pop() ?? value
122
123/** Best available project/task label from a live assignment record. */
124const assignmentWork = (a: BullswarmAssignment): string => {
125 const record = a as AssignmentRecord
126 const value = [record.taskFile, record.projectName, record.project, record.cwd, record.description, record.task]
127 .find(candidate => typeof candidate === 'string' && candidate.trim())
128 return value ? pathTail(value) : 'task unavailable'
129}
130
131/** Greedy word wrap to `width` cells, one string per row; long words are cut. */
132export function wrapText(text: string, width: number): string[] {
133 const w = Math.max(8, width)
134 const out: string[] = []
135 for (const raw of text.split(/\r?\n/)) {
136 let line = raw
137 if (!line.trim()) {
138 out.push('')
139 continue
140 }
141 while (line.length > w) {
142 let cut = line.lastIndexOf(' ', w)
143 if (cut < w * 0.5) cut = w
144 out.push(line.slice(0, cut))
145 line = line.slice(cut).replace(/^\s+/, '')
146 }
147 out.push(line)
148 }
149 return out
150}
151
152/** The action id a frame line names, when it is one of the run's actions. */
153function actionOf(text: string, actions: readonly BullswarmAction[]): BullswarmAction | null {
154 let best: BullswarmAction | null = null
155 for (const a of actions) {
156 const re = new RegExp(`(^|[\\s│├└─✓✗×·])${a.id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?=$|[\\s·])`)
157 if (re.test(text) && (!best || a.id.length > best.id.length)) best = a
158 }
159 return best
160}
161
162/**
163 * The docked pane. Overview mode: the run's header and `[Top] [End]` stay
164 * put, the frame `bullswarm workflow tui --overview` draws scrolls under
165 * them (every step row a button that opens the step, the pools at the
166 * bottom), and the run switcher stays put beneath. The mod owns that
167 * window (`ui.scroll`), so the tree is never taller than the body. Step
168 * mode: that action's attempt, files and the tail of its output, which
169 * the engine scrolls.
170 */
171export function paneView(
172 kit: { ui: PaneUi; columns: number },
173 model: PaneModel,
174 actions: PaneActions,
175): { tree: RenderElement; scroll: PaneScroll | null } {
176 const { Box, Text, Button } = kit.ui
177 const run = model.selected
178 const rule = '─'.repeat(Math.max(1, Math.min(kit.columns, 120)))
179 const nameOf = (pool: string | null) => (pool ? (model.names.get(pool) ?? pool) : '')
180 const looseTask = model.selectedTask
181
182 // Compact: a phone terminal or a short inline pane. One header row, one
183 // nav row with [Top] [End] beside it and no [close] (the frame's ✕ does
184 // that), and nothing else pinned, so the window keeps most of the body.
185 // Pools stay one press away: [usage].
186 const compact = model.bodyRows < COMPACT_ROWS
187 const runButtons = model.runs.map((r, i) => (
188 <Button
189 key={`run-${r.shortId}`}
190 hotkey={i < 9 ? String(i + 1) : undefined}
191 label={run && r.shortId === run.shortId && !model.poolsPage ? `● ${r.shortId}` : r.shortId}
192 onPress={() => actions.select(r.shortId)}
193 />
194 ))
195 const taskButtons = standaloneTasks(model.assignments).map(task => {
196 const id = task.id!
197 const tail = id.length > 8 ? id.slice(-8) : id
198 const active = looseTask && (looseTask as AssignmentRecord).id === id && !model.poolsPage
199 return <Button key={`task-${id}`} label={`${active ? '● ' : ''}task ${tail}`} onPress={() => actions.selectTask(id)} />
200 })
201 const backButton = model.action || model.poolsPage || looseTask
202 ? <Button key="back" hotkey="b" label="back" onPress={actions.back} />
203 : null
204 const usageButton = (
205 <Button key="usage" hotkey="u" label={model.poolsPage ? '● usage' : 'usage'} onPress={actions.openPools} />
206 )
207 const closeButton = <Button key="close" hotkey="q" label="close" onPress={actions.close} />
208 const switcher = compact ? (
209 <Box key="switcher" flexDirection="row" gap={1} flexWrap="nowrap" overflow="hidden">
210 {backButton}
211 {runButtons}
212 {taskButtons}
213 {usageButton}
214 <Button key="top" plain label="[Top]" onPress={() => actions.scrollTo('start')} />
215 <Button key="end" plain label="[End]" onPress={() => actions.scrollTo('end')} />
216 </Box>
217 ) : (
218 <Box key="switcher" flexDirection="row" gap={1} flexWrap="nowrap" overflow="hidden">
219 {backButton}
220 {runButtons}
221 {taskButtons}
222 {usageButton}
223 {closeButton}
224 </Box>
225 )
226
227 const poolsSection = model.pools.length ? (
228 <Box key="pools" flexDirection="column">
229 <Text wrap="truncate-end">
230 <Text bold>Pools</Text>
231 <Text dimColor> · used/elapsed · pace {'─'.repeat(Math.max(0, Math.min(kit.columns, 120) - 30))}</Text>
232 </Text>
233 {poolRows({ Box, Text }, model.pools, model.assignments, model.names)}
234 </Box>
235 ) : null
236
237 // Both modes share one frame: fixed header rows, a window over `rows`
238 // the mod scrolls itself, fixed footer rows. One element per row keeps
239 // the window's arithmetic exact, so long text is wrapped here.
240 const width = Math.max(20, Math.min(kit.columns, 120))
241 const frame = (
242 header: RenderElement[],
243 rows: RenderElement[],
244 footer: RenderElement[],
245 ): { tree: RenderElement; scroll: PaneScroll } => {
246 const fixedRows = header.length + footer.length
247 const windowRows = Math.max(1, model.bodyRows - fixedRows)
248 const contentRows = rows.length
249 const offset = Math.max(0, Math.min(model.offset, Math.max(0, contentRows - windowRows)))
250 const shown = rows.slice(offset, offset + windowRows)
251 // Pad a short body so the footer always sits on the pane's last rows.
252 while (shown.length < windowRows) shown.push(<Text key={`pad${String(shown.length)}`}> </Text>)
253 // Blank rows past the footer, hidden below the body: they let the engine
254 // report the rows it granted rather than the rows the frame drew.
255 const probe = Array.from({ length: PROBE_ROWS }, (_, k) => <Text key={`probe${String(k)}`}> </Text>)
256 const scrolled = offset > 0 || contentRows > offset + windowRows
257 const position = scrolled ? ` · ${String(offset + 1)}–${String(offset + shown.length)}/${String(contentRows)}` : ''
258 return {
259 tree: (
260 <Box flexDirection="column">
261 {header.map((el, k) => (k === 0 ? <Box key="hdr" flexDirection="row">{el}<Text dimColor>{position}</Text></Box> : el))}
262 {shown}
263 {footer}
264 {probe}
265 </Box>
266 ),
267 scroll: { offset, contentRows, windowRows },
268 }
269 }
270 const nav = (
271 <Box key="nav" flexDirection="row" gap={1} flexWrap="nowrap">
272 <Button key="top" plain label="[Top]" onPress={() => actions.scrollTo('start')} />
273 <Button key="end" plain label="[End]" onPress={() => actions.scrollTo('end')} />
274 <Text dimColor wrap="truncate-end">
275 {' '}
276 wheel · arrows · PgUp/PgDn when the pane has focus
277 </Text>
278 </Box>
279 )
280 const dim = (key: string, text: string) => (
281 <Text key={key} dimColor wrap="truncate-end">
282 {text}
283 </Text>
284 )
285 const plain = (key: string, text: string, color?: string) => (
286 <Text key={key} wrap="truncate-end" color={color}>
287 {text}
288 </Text>
289 )
290 const blank = (key: string) => <Text key={key}> </Text>
291
292 if (model.poolsPage) {
293 const header: RenderElement[] = [
294 <Text key="h0" wrap="truncate-end">
295 <Text bold color="cyan">
296 Pools
297 </Text>
298 <Text dimColor>{poolsHeaderText(model.pools, model.nowMs, nameOf).slice('Pools'.length)}</Text>
299 </Text>,
300 ]
301 if (!compact) header.push(nav)
302 if (model.error) header.push(plain('err', model.error, 'red'))
303 // The note sits whole, wrapped, right above the nav, where it is read;
304 // compact panes carry it as the page's first rows instead.
305 const note = wrapText('read-only · adjust pools and rungs with `bullswarm setup` (or `bullswarm strategy`)', width)
306 const noteRows = note.map((l, k) => dim(`note${String(k)}`, l))
307 const pageRows = poolsPageRows({ Box, Text, Button }, model, width, nameOf, actions)
308 const footer: RenderElement[] = compact ? [switcher] : [...noteRows, switcher]
309 return frame(header, compact ? [...noteRows, ...pageRows] : pageRows, footer)
310 }
311
312 if (!run && !model.step && !looseTask) {
313 return {
314 tree: (
315 <Box flexDirection="column">
316 <Text key="empty" dimColor>No ongoing workflow run. `bullswarm workflow goal` launches one.</Text>
317 {model.error ? <Text key="idle-error" color={METER_RED}>{model.error}</Text> : null}
318 {poolsSection}
319 {switcher}
320 </Box>
321 ),
322 scroll: null,
323 }
324 }
325
326 if (model.action || model.step || looseTask) {
327 // The Step model is shaped without UI concerns. This branch only maps
328 // rows to the Claude engine's Text/Button elements.
329 const page = model.step
330 const assignment = looseTask as AssignmentRecord | null
331 const a = model.action ?? {
332 id: page?.id ?? assignment?.id ?? assignmentWork(assignment!),
333 status: page?.status ?? (assignment ? 'running' : 'unknown'),
334 attempts: page?.attempt ? 1 : 0,
335 startedAt: page?.attempt?.startedAt ?? null,
336 finishedAt: page?.attempt?.finishedAt ?? null,
337 outputFile: page?.outputFile ?? null,
338 lastFailure: page?.lastFailure ?? null,
339 latest: null,
340 }
341 const st = model.step
342 const stepOptions = {
343 mode: model.stepMode,
344 expandedTurn: model.expandedStepTurn,
345 promptPreview: model.promptPreview.length ? model.promptPreview : assignment?.description ? [assignment.description] : [],
346 outputTail: model.outputTail,
347 width,
348 nowMs: model.nowMs,
349 }
350 const shaped = st ?? page ? shapeStep(st ?? page, stepOptions) : taskStepPane(assignment, stepOptions)
351 const poolColor = (pool: string): string => {
352 const colors = ['#a99cf0', '#70b7c7', '#d596c7', '#86b98a', '#d39b72']
353 let hash = 0
354 for (const char of pool) hash = ((hash * 31) + char.charCodeAt(0)) >>> 0
355 return colors[hash % colors.length]!
356 }
357 const toneProps = (tone: StepPaneRow['tone'], pool?: string): { color?: string; bold?: boolean; dimColor?: boolean } => {
358 if (tone === 'good') return { color: METER_GREEN }
359 if (tone === 'bad') return { color: METER_RED }
360 if (tone === 'running') return { color: METER_AMBER }
361 if (tone === 'strong') return { bold: true }
362 if (tone === 'pool') return { color: poolColor(pool ?? '') }
363 if (tone === 'dim') return { dimColor: true }
364 return {}
365 }
366 const rowText = (entry: StepPaneRow): RenderElement[] => {
367 if (entry.toggle) {
368 // Rule 14: the toggle sits in the activity heading, straight after the
369 // heading word; the current view is marked, each word switches to its view.
370 const { lead, trail } = entry.toggle
371 return [
372 <Box key={entry.key} flexDirection="row">
373 <Text dimColor>──</Text>
374 <Text {...toneProps(entry.tone)}>{lead.slice(2)}</Text>
375 <Button key="overview" plain label={shaped.mode === 'overview' ? '● overview' : 'overview'} onPress={() => actions.setStepMode?.('overview')} />
376 <Text dimColor> · </Text>
377 <Button key="detail" plain label={shaped.mode === 'detail' ? '● detail' : 'detail'} onPress={() => actions.setStepMode?.('detail')} />
378 <Text {...toneProps(entry.tone)}>{trail.slice(0, -2)}</Text>
379 <Text dimColor>──</Text>
380 </Box>,
381 ]
382 }
383 const lines = wrapText(entry.text, width)
384 if (entry.segments && lines.length === 1) return [
385 <Text key={entry.key} wrap="truncate-end">
386 {entry.segments.map((part, index) => <Text key={`${entry.key}-part-${String(index)}`} {...toneProps(part.tone, part.pool)}>{part.text}</Text>)}
387 </Text>,
388 ]
389 if (entry.kind === 'section') return lines.map((line, index) => {
390 const leading = line.startsWith('──')
391 const trailing = line.endsWith('──')
392 const body = line.slice(leading ? 2 : 0, trailing ? -2 : undefined)
393 return <Text key={`${entry.key}-${String(index)}`} {...toneProps(entry.tone)}><Text dimColor>{leading ? '──' : ''}</Text>{body}<Text dimColor>{trailing ? '──' : ''}</Text></Text>
394 })
395 if (entry.kind === 'fold' && entry.opensDetail) return [
396 <Button key={entry.key} plain label={entry.text} onPress={() => actions.setStepMode?.('detail')} />,
397 ]
398 if (entry.kind === 'response' && entry.expandable) {
399 const [first, ...rest] = lines
400 if (entry.selected) return [
401 <Box key={entry.key} flexDirection="row">
402 <Button
403 key={`${entry.key}-close`}
404 plain
405 label="▶"
406 onPress={() => entry.turnIndex === undefined ? undefined : actions.expandStepTurn?.(entry.turnIndex)}
407 />
408 <Text inverse wrap="truncate-end">{(first ?? entry.text).replace(/^▶/, '')}</Text>
409 </Box>,
410 ...rest.map((line, index) => <Text key={`${entry.key}-continuation-${String(index)}`} inverse>{line}</Text>),
411 ]
412 return [
413 <Button
414 key={entry.key}
415 plain
416 label={first ?? entry.text}
417 onPress={() => entry.turnIndex === undefined ? undefined : actions.expandStepTurn?.(entry.turnIndex)}
418 />,
419 ...rest.map((line, index) => <Text key={`${entry.key}-continuation-${String(index)}`} dimColor>{line}</Text>),
420 ]
421 }
422 return lines.map((line, index) => <Text key={`${entry.key}-${String(index)}`} {...toneProps(entry.tone)}>{line}</Text>)
423 }
424 const rows: RenderElement[] = shaped.rows.flatMap(rowText)
425
426 const header: RenderElement[] = [
427 <Box key="h0" flexDirection="row">
428 <Text bold>Step </Text>
429 </Box>,
430 ]
431 if (!compact) header.push(nav)
432 if (model.error) header.push(plain('err', model.error, 'red'))
433 // The hint sits whole above the nav, as the usage page's note does.
434 const hintText = looseTask
435 ? `bullswarm workflow task show ${(looseTask as AssignmentRecord).id ?? a.id} · read-only Step view`
436 : shaped.runId
437 ? `bullswarm workflow action show ${shaped.runId} ${a.id}`
438 : 'bullswarm run task · read-only Step view'
439 const hint = wrapText(hintText, width)
440 const stepModeButton = (
441 <Button
442 key="step-mode"
443 hotkey="v"
444 label="v"
445 onPress={() => actions.toggleStep?.()}
446 />
447 )
448 const stepModeFooter = <Box key="step-mode-footer" flexDirection="row" gap={1}>{stepModeButton}<Text dimColor>{shaped.toggleHint.replace(/^v\s+/, '')}</Text></Box>
449 const footer: RenderElement[] = compact
450 ? [stepModeFooter, switcher]
451 : [...hint.map((l, k) => dim(`f${String(k)}`, l)), stepModeFooter, switcher]
452 return frame(header, rows, footer)
453 }
454
455 // The only path below is the ordinary run overview. The explicit guard
456 // keeps the standalone-task branch above type-safe when the host has no run.
457 if (!run) return { tree: <Text dimColor>No run selected.</Text>, scroll: null }
458
459 const age = ageOf(run.startedAt, model.nowMs)
460 const read = model.readAt ? ageOf(new Date(model.readAt).toISOString(), model.nowMs) : ''
461 const known = model.detail?.actions ?? []
462 const lines = model.overview ?? []
463
464 // One element per row, so the window's arithmetic holds: the frame lines
465 // are already wrapped to the pane's width by `--width`.
466 const rows: RenderElement[] = lines.map((line, i) => {
467 if (line.kind === 'blank') return <Text key={`b${String(i)}`}> </Text>
468 if (line.kind === 'header')
469 return (
470 <Text key={`h${String(i)}`} wrap="truncate-end">
471 <Text bold>{line.text}</Text>
472 <Text dimColor> {'─'.repeat(Math.max(0, Math.min(kit.columns, 120) - line.text.length - 1))}</Text>
473 </Text>
474 )
475 if (line.kind === 'section')
476 return (
477 <Text key={`s${String(i)}`} wrap="truncate-end" bold color={toneColor(line.tone)}>
478 {line.text}
479 </Text>
480 )
481 const step = line.kind === 'detail' ? null : actionOf(line.text, known)
482 if (step)
483 return (
484 <Box key={`a${String(i)}`} flexDirection="row">
485 <Button
486 key={`step-${step.id}-${String(i)}`}
487 plain
488 label={line.text}
489 onPress={() => actions.openAction(step.id)}
490 />
491 </Box>
492 )
493 return (
494 <Text
495 key={`l${String(i)}`}
496 wrap="truncate-end"
497 dimColor={line.kind === 'detail'}
498 color={line.kind === 'detail' ? undefined : toneColor(line.tone)}
499 >
500 {line.text}
501 </Text>
502 )
503 })
504 const poolsFooter: RenderElement[] = model.pools.length
505 ? [
506 <Text key="pools-rule" dimColor>
507 {rule}
508 </Text>,
509 <Box key="pools" flexDirection="row">
510 <Button key="pools-open" plain label="Pools ▸" onPress={actions.openPools} />
511 <Text dimColor wrap="truncate-end">
512 {' '}· used/elapsed · pace · ▏ marks elapsed · click for every window and the model per tier
513 </Text>
514 </Box>,
515 ...poolRows({ Box, Text }, model.pools, model.assignments, model.names),
516 ]
517 : []
518
519 const header: RenderElement[] = [
520 <Text key="h0" wrap="truncate-end">
521 <Text bold color="cyan">
522 {run.shortId}
523 </Text>
524 <Text>
525 {' '}
526 {run.status}
527 {age ? ` · ${age}` : ''} ·{' '}
528 </Text>
529 <Text color="green">
530 {run.actionsSucceeded}/{run.actionsTotal}
531 </Text>
532 <Text dimColor>{model.overview ? ` · ${read || '0m'} old` : ' · reading…'}</Text>
533 </Text>,
534 ]
535 if (!compact) header.push(nav)
536 if (model.error) header.push(plain('err', model.error, 'red'))
537 // The hint sits whole above the nav, as the usage page's note does.
538 const hint = wrapText(`click a step to open it · bullswarm workflow watch ${run.shortId} --next`, width)
539 const footer: RenderElement[] = compact
540 ? [switcher]
541 : [...poolsFooter, ...hint.map((l, k) => dim(`f${String(k)}`, l)), switcher]
542 return frame(header, rows, footer)
543}
544
545/** `1h41m`, `2d9h` until an ISO time, or ''. */
546const untilText = (iso: string | null, nowMs: number): string => {
547 if (!iso) return ''
548 const mins = Math.round((Date.parse(iso) - nowMs) / 60_000)
549 if (!Number.isFinite(mins) || mins < 0) return 'now'
550 if (mins < 60) return `${String(mins)}m`
551 const h = Math.floor(mins / 60)
552 if (h < 24) return `${String(h)}h${String(mins % 60).padStart(2, '0')}m`
553 return `${String(Math.floor(h / 24))}d${String(h % 24)}h`
554}
555
556/** `on track −5pp`, `slow +36pp` (quota to spare) or `hot −20pp` (ahead of the window), with a color. */
557const paceWord = (usedPct: number, elapsedPct: number | null): { text: string; color: string } => {
558 if (elapsedPct === null) return { text: '', color: 'gray' }
559 const pp = Math.round(elapsedPct - usedPct)
560 const signed = `${pp >= 0 ? '+' : '−'}${String(Math.abs(pp))}pp`
561 if (pp >= 15) return { text: `slow ${signed}`, color: METER_AMBER }
562 if (pp <= -15) return { text: `hot ${signed}`, color: METER_RED }
563 return { text: `on track ${signed}`, color: METER_GREEN }
564}
565
566/**
567 * The pools page: every meter window of every pool as a full width bar
568 * with the elapsed mark, its reset time and pace word, the credit meter
569 * when there is one; then every pool × tier rung with its model and
570 * reasoning. Read-only: the footer names the command that changes it.
571 */
572function poolsPageRows(
573 ui: PaneUi,
574 model: PaneModel,
575 width: number,
576 nameOf: (pool: string | null) => string,
577 actions: Pick<PaneActions, 'setRungsBy'>,
578): RenderElement[] {
579 const { Box, Text, Button } = ui
580 const rows: RenderElement[] = []
581 const barWidth = Math.max(10, width - 4 - 8)
582 for (const p of model.pools.filter(p => p.enabled)) {
583 rows.push(
584 <Text key={`x-${p.name}`} bold wrap="truncate-end">
585 {nameOf(p.name)}
586 {p.planType ? <Text dimColor> · {p.planType}</Text> : null}
587 </Text>,
588 )
589 if (!p.windows.length) rows.push(<Text key={`x-${p.name}-none`} dimColor> no meter reported</Text>)
590 for (const w of p.windows) {
591 const pace = paceWord(w.usedPct, w.elapsedPct)
592 rows.push(
593 <Box key={`x-${p.name}-${w.key}`} flexDirection="row">
594 <Text dimColor>{w.key.padEnd(3)} </Text>
595 {meterBar(Text, w.usedPct, w.elapsedPct, barWidth)}
596 <Text color={severityColor(w.usedPct)}> {`${w.usedPct.toFixed(1)}%`.padStart(6)}</Text>
597 </Box>,
598 <Text key={`x-${p.name}-${w.key}-r`} wrap="truncate-end">
599 <Text dimColor> {w.resetsAt ? `resets ${untilText(w.resetsAt, model.nowMs)}` : 'no reset time'}</Text>
600 {pace.text ? (
601 <Text color={pace.color}>
602 {' '}· {pace.text}
603 </Text>
604 ) : null}
605 </Text>,
606 )
607 }
608 if (p.credits)
609 rows.push(
610 <Text key={`x-${p.name}-credits`} dimColor wrap="truncate-end">
611 {' '}
612 {String(p.credits.used)} / {String(p.credits.limit)} {p.credits.unit}
613 </Text>,
614 )
615 rows.push(<Text key={`x-${p.name}-b`}> </Text>)
616 }
617
618 // The rungs: the model and reasoning each pool dispatches with per effort
619 // tier, and what the local record says about it, grouped by tier (the
620 // lane a task lands in) or by pool.
621 const tiers = ['high', 'medium', 'low']
622 const enabled = model.pools.filter(p => p.enabled)
623 const short = (m: string | null) => (m ? (m.split('/').pop() ?? m) : '—')
624 const recordOf = (r: BullswarmRung) =>
625 r.dispatches
626 ? `${String(r.dispatches)} run${r.dispatches === 1 ? '' : 's'}${r.okShare !== null ? ` · ${String(Math.round(r.okShare * 100))}% ok` : ''}${r.medianMinutes !== null ? ` · p50 ${String(Math.round(r.medianMinutes))}m` : ''}`
627 : 'no runs yet'
628 const rungRow = (key: string, _head: string, sub: string, r: BullswarmRung) => [
629 <Text key={key} wrap="truncate-end">
630 <Text>{' '}</Text>
631 <Text dimColor>{sub.padEnd(16).slice(0, 16)}</Text>
632 <Text color="cyan">{short(r.model)}</Text>
633 <Text>{r.reasoning ? ` · ${r.reasoning}` : ''}</Text>
634 </Text>,
635 <Text key={`${key}-r`} dimColor wrap="truncate-end">
636 {' '.repeat(18)}
637 {recordOf(r)}
638 </Text>,
639 ]
640 // What each lane carries, from the program kinds table: the effort a
641 // kind resolves to decides the tier a step dispatches on.
642 const laneBlurb: Record<string, string> = {
643 high: 'integration · architecture · adversarial-acceptance',
644 medium: 'implement · check (the ordinary writers)',
645 low: 'mechanical · io-read · digest',
646 }
647 const poolBlurb = (p: BullswarmPool) => {
648 const meter = p.usedPct !== null && p.elapsedPct !== null ? `${String(Math.round(p.usedPct))}% used of ${String(Math.round(p.elapsedPct))}% elapsed` : 'no meter'
649 const window = p.pacingWindow === 'monthly' ? 'monthly' : p.pacingWindow === 'weekly' ? 'weekly' : p.pacingWindow ?? ''
650 return [window ? `${window} window` : '', meter, p.quarantine ? 'quarantined' : '']
651 .filter(Boolean)
652 .join(' · ')
653 }
654 rows.push(
655 <Text key="x-rungs" wrap="truncate-end">
656 <Text bold>Rungs</Text>
657 <Text dimColor> · model · reasoning · record, per lane and pool</Text>
658 </Text>,
659 <Box key="x-rungs-tabs" flexDirection="row" gap={1} flexWrap="nowrap">
660 <Button key="rungs-tier" plain label={model.rungsBy === 'tier' ? '[● by lane]' : '[by lane]'} onPress={() => actions.setRungsBy('tier')} />
661 <Button key="rungs-pool" plain label={model.rungsBy === 'pool' ? '[● by provider]' : '[by provider]'} onPress={() => actions.setRungsBy('pool')} />
662 </Box>,
663 )
664 const group = (key: string, title: string, blurb: string) => [
665 <Text key={`${key}-gap`}> </Text>,
666 <Text key={`${key}-title`} wrap="truncate-end">
667 <Text bold>{title}</Text>
668 <Text dimColor> · {blurb}</Text>
669 </Text>,
670 ]
671 if (model.rungsBy === 'tier') {
672 for (const t of tiers) {
673 const mine = enabled
674 .map(p => ({ p, r: model.rungs.find(x => x.pool === p.name && x.tier === t) }))
675 .filter((x): x is { p: BullswarmPool; r: BullswarmRung } => !!x.r?.model)
676 if (!mine.length) continue
677 rows.push(...group(`x-lane-${t}`, t, laneBlurb[t] ?? ''))
678 for (const { p, r } of mine) rows.push(...rungRow(`x-rung-${t}-${p.name}`, '', nameOf(p.name), r))
679 }
680 } else {
681 for (const p of enabled) {
682 const mine = tiers
683 .map(t => ({ t, r: model.rungs.find(x => x.pool === p.name && x.tier === t) }))
684 .filter((x): x is { t: string; r: BullswarmRung } => !!x.r?.model)
685 if (!mine.length) continue
686 rows.push(...group(`x-pool-${p.name}`, nameOf(p.name), poolBlurb(p)))
687 for (const { t, r } of mine) rows.push(...rungRow(`x-rung-${p.name}-${t}`, '', t, r))
688 }
689 }
690 if (!model.rungs.length) rows.push(<Text key="x-rungs-none" dimColor> reading rungs…</Text>)
691 return rows
692}
693hooks/runs.ts 352 lines1import type {
2 BullswarmAction,
3 BullswarmAssignment,
4 BullswarmAttempt,
5 BullswarmRun,
6 BullswarmRunDetail,
7 BullswarmStep,
8 BullswarmStepAttempt,
9} from '../types'
10
11type Raw = Record<string, unknown>
12
13/** The rich, serializable Step model appended by `action show --json`. */
14export type ParsedBullswarmStep = BullswarmStep & {
15 /** The JSON `step` object; kept separate from the legacy compact projection. */
16 page: Raw | null
17 /** Action-scoped durable events, retained for callers that need raw context. */
18 events: readonly Raw[]
19}
20
21export type BullswarmAssignmentRecord = BullswarmAssignment & {
22 id?: string
23 startedAt?: string
24 project?: string
25 projectName?: string
26 cwd?: string
27 taskFile?: string
28 task?: string
29 description?: string
30}
31
32const num = (v: unknown): number | null =>
33 typeof v === 'number' && Number.isFinite(v) ? v : null
34const str = (v: unknown): string | null => (typeof v === 'string' ? v : null)
35
36const optionalStrings = (
37 raw: Raw,
38 fallback: BullswarmAssignmentRecord | null,
39 keys: readonly ('id' | 'startedAt' | 'project' | 'projectName' | 'cwd' | 'taskFile' | 'task' | 'description')[],
40): Partial<BullswarmAssignmentRecord> => {
41 const fields: Partial<BullswarmAssignmentRecord> = {}
42 for (const key of keys) {
43 const value = str(raw[key]) ?? str(fallback?.[key])
44 if (value !== null) fields[key] = value
45 }
46 return fields
47}
48
49/** Reads one raw ledger record, preserving optional fields newer records may carry. */
50export function parseAssignmentRecord(
51 value: unknown,
52 fallback: BullswarmAssignmentRecord | null = null,
53): BullswarmAssignmentRecord | null {
54 if (!value || typeof value !== 'object') return fallback
55 const raw = value as Raw
56 const pool = str(raw.pool) ?? fallback?.pool ?? null
57 if (!pool) return fallback
58 return {
59 pool,
60 poolLabel: str(raw.poolLabel) ?? fallback?.poolLabel ?? null,
61 model: str(raw.model) ?? fallback?.model ?? null,
62 lane: str(raw.lane) ?? fallback?.lane ?? '',
63 source: str(raw.source) ?? fallback?.source ?? '',
64 runId: str(raw.runId) ?? fallback?.runId ?? null,
65 actionId: str(raw.actionId) ?? fallback?.actionId ?? null,
66 elapsedMinutes: num(raw.elapsedMinutes) ?? fallback?.elapsedMinutes ?? null,
67 expectedMinutes: num(raw.expectedMinutes) ?? fallback?.expectedMinutes ?? null,
68 ...optionalStrings(raw, fallback, ['id', 'startedAt', 'project', 'projectName', 'cwd', 'taskFile', 'task', 'description']),
69 }
70}
71
72/** Reads `bullswarm workflow runs --json` (ongoing runs) into the run model. */
73export function parseRuns(stdout: string): BullswarmRun[] {
74 const doc = JSON.parse(stdout) as { runs?: Raw[] }
75 const raw = Array.isArray(doc.runs) ? doc.runs : []
76 return raw
77 .filter(r => typeof r.runId === 'string' && r.legacy !== true)
78 .map(r => ({
79 runId: r.runId as string,
80 shortId: str(r.shortId) ?? (r.runId as string).slice(-6),
81 goal: str(r.goal) ?? '',
82 status: str(r.status) ?? 'unknown',
83 startedAt: str(r.startedAt),
84 actionsSucceeded: num(r.actionsSucceeded) ?? 0,
85 actionsTotal: num(r.actionsTotal) ?? 0,
86 waitingFor: Array.isArray(r.waitingFor)
87 ? (r.waitingFor as Raw[])
88 .filter(n => typeof n?.id === 'string')
89 .map(n => ({ id: n.id as string, type: str(n.type) ?? 'gate', note: str(n.note) }))
90 : [],
91 }))
92}
93
94/** `waiting at gate approve`, or the run's own status word. */
95export function runStatusText(run: BullswarmRun): string {
96 if (!run.waitingFor?.length) return run.status
97 return `waiting at ${run.waitingFor.map(n => `${n.type} ${n.id}`).join(', ')}`
98}
99
100/** The commands that move a parked run's gates and loops. */
101export function continueCommands(run: BullswarmRun): string[] {
102 return (run.waitingFor ?? []).map(n =>
103 `bullswarm workflow continue ${run.shortId} ${n.id}${n.type === 'loop' ? ' --rounds <n>' : ''}`)
104}
105
106/** Reads `bullswarm assignments --json` (the in-flight ledger). */
107export function parseAssignments(stdout: string): BullswarmAssignmentRecord[] {
108 const doc = JSON.parse(stdout) as unknown
109 const raw = Array.isArray(doc) ? (doc as Raw[]) : []
110 return raw
111 .map(a => parseAssignmentRecord(a))
112 .filter((a): a is BullswarmAssignmentRecord => a !== null)
113}
114
115/** `3m/9m`, `3m`, or ''. */
116export function timingOf(a: BullswarmAssignment): string {
117 if (a.elapsedMinutes === null) return ''
118 const e = `${Math.round(a.elapsedMinutes)}m`
119 return a.expectedMinutes !== null ? `${e}/${Math.round(a.expectedMinutes)}m` : e
120}
121
122/** Minutes since an ISO timestamp, as `42m` or `2h05m`. */
123export function ageOf(iso: string | null, nowMs: number): string {
124 if (!iso) return ''
125 const mins = Math.max(0, Math.round((nowMs - Date.parse(iso)) / 60_000))
126 if (!Number.isFinite(mins)) return ''
127 return mins < 60 ? `${mins}m` : `${Math.floor(mins / 60)}h${String(mins % 60).padStart(2, '0')}m`
128}
129
130/** The steps of one run in flight right now. */
131export function stepsOf(run: BullswarmRun, assignments: readonly BullswarmAssignment[]) {
132 return assignments.filter(a => a.runId === run.runId)
133}
134
135/** Standalone `bullswarm run` dispatches, not part of any listed run. */
136export function looseOf(
137 runs: readonly BullswarmRun[],
138 assignments: readonly BullswarmAssignment[],
139): BullswarmAssignment[] {
140 const known = new Set(runs.map(r => r.runId))
141 return assignments.filter(a => !a.runId || !known.has(a.runId))
142}
143
144/** Standalone task assignments in nav order; workflow digits never depend on these. */
145export function standaloneTasks(assignments: readonly BullswarmAssignment[]): BullswarmAssignmentRecord[] {
146 return assignments.filter((a): a is BullswarmAssignmentRecord => a.source === 'run' && typeof (a as BullswarmAssignmentRecord).id === 'string')
147}
148
149export type PaneChoice =
150 | { kind: 'workflow'; shortId: string }
151 | { kind: 'task'; taskId: string }
152 | null
153
154/**
155 * Resolve the pane without letting an unrelated live task override a workflow.
156 * An explicit task wins, then an explicit workflow, then the first workflow;
157 * a task is promoted only when there is no workflow to show.
158 */
159export function paneChoice(
160 runs: readonly BullswarmRun[],
161 assignments: readonly BullswarmAssignment[],
162 selectedShortId: string | null,
163 selectedTaskId: string | null,
164): PaneChoice {
165 const tasks = standaloneTasks(assignments)
166 const task = selectedTaskId ? tasks.find(a => a.id === selectedTaskId) : null
167 if (task?.id) return { kind: 'task', taskId: task.id }
168 const run = (selectedShortId ? runs.find(r => r.shortId === selectedShortId) : null) ?? runs[0] ?? null
169 if (run) return { kind: 'workflow', shortId: run.shortId }
170 return tasks[0]?.id ? { kind: 'task', taskId: tasks[0].id } : null
171}
172
173/** One plain-text line per run, for `/bullswarm runs` and the context block. */
174export function runLine(
175 run: BullswarmRun,
176 assignments: readonly BullswarmAssignment[],
177 nowMs: number,
178): string {
179 const steps = stepsOf(run, assignments)
180 .map(a => `${a.actionId ?? '?'} on ${a.pool}${timingOf(a) ? ` ${timingOf(a)}` : ''}`)
181 .join(', ')
182 const progress = `${run.actionsSucceeded}/${run.actionsTotal} done`
183 const age = ageOf(run.startedAt, nowMs)
184 const next = continueCommands(run)
185 return `${run.shortId} (${runStatusText(run)}${age ? `, ${age}` : ''}): ${progress}${steps ? `; running ${steps}` : ''}${next.length ? `; continue: ${next.join(' or ')}` : ''} — ${run.goal.slice(0, 80)}${run.goal.length > 80 ? '…' : ''}`
186}
187
188const activityOf = (v: unknown): string | null => {
189 if (typeof v === 'string') return v
190 if (v && typeof v === 'object') {
191 const o = v as Raw
192 return str(o.summary) ?? str(o.kind) ?? str(o.status) ?? null
193 }
194 return null
195}
196
197/** Reads `bullswarm workflow runs show <id> --json` into the action list. */
198export function parseDetail(stdout: string, readAt: number): BullswarmRunDetail {
199 const doc = JSON.parse(stdout) as Raw
200 const state = (doc.state ?? {}) as Raw
201 const rawAttempts = Array.isArray(state.attempts) ? (state.attempts as Raw[]) : []
202 const attempts: BullswarmAttempt[] = rawAttempts
203 .filter(a => typeof a.actionId === 'string')
204 .map(a => ({
205 actionId: a.actionId as string,
206 ordinal: num(a.ordinal) ?? 0,
207 status: str(a.status) ?? 'unknown',
208 pool: str(a.pool),
209 model: str(a.model),
210 startedAt: str(a.startedAt),
211 finishedAt: str(a.finishedAt),
212 why: str(a.why),
213 wallSec: num(a.wallSec),
214 lastActivity: activityOf(a.lastAgentEvent),
215 }))
216 const rawActions = Array.isArray(state.actions) ? (state.actions as Raw[]) : []
217 const actions: BullswarmAction[] = rawActions
218 .filter(a => typeof a.id === 'string')
219 .map(a => {
220 const mine = attempts.filter(t => t.actionId === a.id)
221 const latest = mine.sort((x, y) => y.ordinal - x.ordinal)[0] ?? null
222 const failure = a.lastFailure
223 return {
224 id: a.id as string,
225 status: str(a.status) ?? 'unknown',
226 attempts: num(a.attempts) ?? mine.length,
227 startedAt: str(a.startedAt),
228 finishedAt: str(a.finishedAt),
229 outputFile: str(a.outputFile),
230 lastFailure:
231 typeof failure === 'string'
232 ? failure
233 : failure && typeof failure === 'object'
234 ? (str((failure as Raw).why) ?? str((failure as Raw).kind))
235 : null,
236 latest,
237 }
238 })
239 return {
240 runId: str(doc.runId) ?? '',
241 shortId: str(doc.shortId) ?? '',
242 ongoing: doc.ongoing === true,
243 actions,
244 readAt,
245 }
246}
247
248/** `6m12s` for a finished attempt, `3m` so far for a running one, or ''. */
249export function durationOf(a: BullswarmAction, nowMs: number): string {
250 const wall = a.latest?.wallSec
251 if (wall !== null && wall !== undefined) {
252 const m = Math.floor(wall / 60)
253 const sec = Math.round(wall % 60)
254 return m ? `${m}m${String(sec).padStart(2, '0')}s` : `${sec}s`
255 }
256 if (a.startedAt && !a.finishedAt) return `${ageOf(a.startedAt, nowMs)} so far`
257 return ''
258}
259
260/** A glyph and color per action status. */
261export function glyphOf(status: string): { glyph: string; color: string } {
262 switch (status) {
263 case 'succeeded':
264 return { glyph: '✓', color: 'green' }
265 case 'running':
266 return { glyph: '▶', color: 'cyan' }
267 case 'failed':
268 return { glyph: '✗', color: 'red' }
269 case 'cancelled':
270 case 'skipped':
271 return { glyph: '–', color: 'yellow' }
272 default:
273 return { glyph: '·', color: 'gray' }
274 }
275}
276
277/** `tokens read=… output=… · cost≈$…`, as the TUI's compact usage line. */
278function usageText(v: unknown): string | null {
279 if (!v || typeof v !== 'object') return null
280 const u = v as Raw
281 const t = (u.tokens ?? {}) as Raw
282 const cost = (u.cost ?? {}) as Raw
283 const parts = [
284 `tokens read=${String(num(t.standardRead) ?? '?')} output=${String(num(t.output) ?? '?')}`,
285 num(cost.estimatedUsd) !== null ? `cost≈$${String(num(cost.estimatedUsd))}` : '',
286 ]
287 return parts.filter(Boolean).join(' · ')
288}
289
290const eventText = (v: unknown): string | null => {
291 if (!v || typeof v !== 'object') return null
292 const e = v as Raw
293 const bits = [str(e.kind) ?? str(e.providerType), str(e.summary), str(e.status)].filter(
294 (x): x is string => !!x,
295 )
296 return bits.length ? bits.join(' · ') : null
297}
298
299/** Reads `bullswarm workflow action show <run> <step> --json` into one step. */
300export function parseStep(stdout: string, readAt: number): ParsedBullswarmStep {
301 const doc = JSON.parse(stdout) as Raw
302 const rec = (doc.actionRecord ?? {}) as Raw
303 const rawAttempts = Array.isArray(doc.attempts) ? (doc.attempts as Raw[]) : []
304 const last = [...rawAttempts].sort((x, y) => (num(y.ordinal) ?? 0) - (num(x.ordinal) ?? 0))[0]
305 const attempt: BullswarmStepAttempt | null = last
306 ? {
307 ordinal: num(last.ordinal) ?? 1,
308 status: str(last.status) ?? 'unknown',
309 pool: str(last.pool),
310 model: str(last.model),
311 reasoning: str(((last.reasoning ?? {}) as Raw).applied),
312 routeReason: str(((last.routing ?? {}) as Raw).reason),
313 startedAt: str(last.startedAt),
314 finishedAt: str(last.finishedAt),
315 lastActivityAt: str(last.lastActivityAt),
316 outputBytes: num(last.outputBytesObserved),
317 taskFile: str(last.taskFile),
318 outputFile: str(last.outputFile),
319 why: str(last.why),
320 wallSec: num(last.wallSec),
321 usage: usageText(last.usage),
322 lastEvent: eventText(last.lastAgentEvent),
323 }
324 : null
325 const failure = rec.lastFailure
326 const page = doc.step && typeof doc.step === 'object' && !Array.isArray(doc.step)
327 ? (doc.step as Raw)
328 : null
329 const events = Array.isArray(doc.events)
330 ? (doc.events as unknown[]).filter((event): event is Raw => Boolean(event && typeof event === 'object' && !Array.isArray(event)))
331 : []
332 return {
333 id: str(rec.id) ?? '',
334 purpose: str(rec.purpose) ?? '',
335 kind: str(rec.kind),
336 lane: str(rec.lane),
337 effort: str(rec.effort),
338 status: str(rec.status) ?? 'unknown',
339 outputFile: str(rec.outputFile) ?? attempt?.outputFile ?? null,
340 lastFailure:
341 typeof failure === 'string'
342 ? failure
343 : failure && typeof failure === 'object'
344 ? (str((failure as Raw).why) ?? str((failure as Raw).kind))
345 : null,
346 attempt,
347 readAt,
348 page,
349 events,
350 }
351}
352hooks/strip.tsx 149 lines1/* @jsxRuntime classic */
2/* @jsx h */
3/* @jsxFrag Fragment */
4import type { ElementTable, RenderElement } from 'claude-code'
5
6import type { BullswarmAssignment, BullswarmPool, BullswarmRun } from '../types'
7import { poolRows } from './pool-rows'
8import { looseOf, runStatusText, stepsOf, timingOf } from './runs'
9
10export type StripUi = Pick<
11 ElementTable<'terminal' | 'desktop'>,
12 'Box' | 'Text' | 'Button'
13>
14
15export type StripModel = {
16 pools: readonly BullswarmPool[]
17 runs: readonly BullswarmRun[]
18 assignments: readonly BullswarmAssignment[]
19 autoRoute: boolean
20 routedCount: number
21 lastError: string | null
22 paneOpen: boolean
23 selectedShortId: string | null
24 /** Pool name → what the strip shows for it. */
25 names: ReadonlyMap<string, string>
26 /** `full` draws the pool rows too; `runs` only the run rows. */
27 level: 'runs' | 'full'
28}
29
30export type StripActions = {
31 /** Opens (or closes) the run pane on the selected run. */
32 pane: () => void
33 /** Selects one run and opens the pane on it. */
34 open: (shortId: string) => void
35}
36
37/**
38 * The strip in the AbovePrompt band, kept to one idea per row: a header
39 * line with the pane button, one row per pool (bar, used/elapsed, pace,
40 * what is running there), one row per ongoing run (progress, the step in
41 * flight, the goal), one per standalone dispatch.
42 */
43export function strip(
44 kit: { ui: StripUi; columns: number; maxRows: number },
45 model: StripModel,
46 actions: StripActions,
47): RenderElement {
48 const { Box, Text, Button } = kit.ui
49 const budget = Math.max(1, kit.maxRows - 1)
50 const pools = model.level === 'full' ? model.pools.filter(p => p.enabled).slice(0, budget) : []
51 const loose = looseOf(model.runs, model.assignments)
52 const runRows = Math.max(0, budget - pools.length)
53 const runs = model.runs.slice(0, runRows)
54 const looseShown = loose.slice(0, Math.max(0, runRows - runs.length))
55 const nameOf = (pool: string) => model.names.get(pool) ?? pool
56
57 const summary = [
58 model.runs.length ? `${model.runs.length} run${model.runs.length === 1 ? '' : 's'}` : 'no runs',
59 model.assignments.length ? `${model.assignments.length} in flight` : '',
60 model.routedCount ? `${model.routedCount} routed` : '',
61 model.autoRoute ? '' : 'route off',
62 ]
63 .filter(Boolean)
64 .join(' · ')
65
66 return (
67 <Box flexDirection="column">
68 <Box flexDirection="row" flexWrap="nowrap" gap={1} marginRight={4}>
69 <Box flexShrink={1} overflow="hidden">
70 <Text wrap="truncate-end">
71 <Text bold color="magenta">
72 bullswarm
73 </Text>
74 <Text dimColor> {summary}{model.level === 'full' ? ' · used/elapsed · pace' : ''}</Text>
75 </Text>
76 </Box>
77 <Box flexShrink={0} flexDirection="row" gap={1}>
78 <Button
79 key="pane"
80 hotkey="w"
81 label={model.paneOpen ? '[w] close' : '[w] runs'}
82 onPress={actions.pane}
83 />
84 </Box>
85 </Box>
86 {model.lastError ? (
87 <Text color="red" wrap="truncate-end">
88 {model.lastError}
89 </Text>
90 ) : null}
91 {poolRows({ Box, Text }, pools, model.assignments, model.names)}
92 {runs.map((run, i) => {
93 const steps = stepsOf(run, model.assignments)
94 const done = `${run.actionsSucceeded}/${run.actionsTotal}`
95 // One step in flight is named; the rest are counted, so the goal
96 // that says which run this is always stays on the row.
97 const named = steps
98 .slice(0, 1)
99 .map(a => `${a.actionId ?? '?'}@${nameOf(a.pool)}${timingOf(a) ? ` ${timingOf(a)}` : ''}`)
100 .join(', ')
101 const running = steps.length > 1 ? `${named}, and ${String(steps.length - 1)} more` : named
102 const finished = run.status !== 'running'
103 // A parked v3 run waits for the caller at a gate or loop.
104 const waiting = (run.waitingFor ?? []).length > 0
105 const selected = model.selectedShortId === run.shortId && model.paneOpen
106
107 return (
108 <Box key={run.runId} flexDirection="row">
109 <Button
110 key={`open-${run.shortId}`}
111 plain
112 hotkey={i < 9 ? String(i + 1) : undefined}
113 label={`${waiting ? '⧖' : finished ? '◼' : '▶'} ${run.shortId}`}
114 onPress={() => actions.open(run.shortId)}
115 />
116 <Text wrap="truncate-end">
117 <Text color="magenta">{selected ? ' ●' : ''}</Text>
118 <Text color="green">
119 {' '}
120 {done}
121 </Text>
122 {finished ? <Text color="yellow"> {runStatusText(run)}</Text> : null}
123 <Text color="cyan">{running ? ` ${running}` : ''}</Text>
124 <Text dimColor> {run.goal}</Text>
125 </Text>
126 </Box>
127 )
128 })}
129 {looseShown.map((a, i) => (
130 <Box key={`loose-${String(i)}`} flexDirection="row">
131 <Text wrap="truncate-end">
132 <Text color="cyan" bold>
133 ▶ run
134 </Text>
135 <Text>
136 {' '}
137 {a.lane}@{nameOf(a.pool)}
138 </Text>
139 <Text dimColor>
140 {timingOf(a) ? ` ${timingOf(a)}` : ''}
141 {a.source ? ` ${a.source}` : ''}
142 </Text>
143 </Text>
144 </Box>
145 ))}
146 </Box>
147 )
148}
149hooks/step.ts 442 lines1import type { BullswarmStep } from '../types'
2
3type Raw = Record<string, unknown>
4
5export type StepMode = 'overview' | 'detail'
6export type StepTone = 'normal' | 'dim' | 'good' | 'bad' | 'running' | 'strong' | 'pool'
7
8export type StepPaneSegment = { text: string; tone: StepTone; pool?: string }
9
10/** One width-aware row for the Claude pane. JSX belongs in pane.tsx. */
11export type StepPaneRow = {
12 key: string
13 kind: 'section' | 'text' | 'response' | 'summary' | 'atomic' | 'artifact' | 'fold'
14 text: string
15 tone: StepTone
16 segments?: readonly StepPaneSegment[]
17 turnIndex?: number
18 selected?: boolean
19 expandable?: boolean
20 opensDetail?: boolean
21 /** A heading that carries the `overview · detail` toggle: `text` is `${lead}overview · detail${trail}`. */
22 toggle?: { lead: string; trail: string }
23}
24
25export type StepPaneBlock = {
26 key: 'header' | 'task' | 'activity' | 'result' | 'cost'
27 title: string
28 rows: readonly StepPaneRow[]
29}
30
31export type StepPaneModel = {
32 mode: StepMode
33 actionId: string
34 runId: string | null
35 blocks: readonly StepPaneBlock[]
36 rows: readonly StepPaneRow[]
37 toggleLabel: 'detail' | 'overview'
38 toggleHint: string
39}
40
41export type StepPaneOptions = {
42 mode?: StepMode
43 expandedTurn?: number | null
44 promptPreview?: readonly string[]
45 outputTail?: string | null
46 width?: number
47 nowMs?: number
48}
49
50const record = (value: unknown): Raw | null =>
51 value && typeof value === 'object' && !Array.isArray(value) ? value as Raw : null
52const list = (value: unknown): readonly unknown[] => Array.isArray(value) ? value : []
53const valueText = (value: unknown, fallback = '—'): string => {
54 if (value === null || value === undefined) return fallback
55 if (typeof value === 'object') {
56 try { return JSON.stringify(value) }
57 catch { return String(value) }
58 }
59 const result = String(value).trim()
60 return result || fallback
61}
62const oneLine = (value: unknown, fallback = '—'): string => valueText(value, fallback).replace(/\s+/g, ' ')
63const nullable = (value: unknown): string | null => {
64 const result = oneLine(value, '')
65 return result || null
66}
67const numberOf = (value: unknown): number | null => {
68 if (value === null || value === undefined || value === '') return null
69 const parsed = Number(value)
70 return Number.isFinite(parsed) ? parsed : null
71}
72const row = (
73 key: string,
74 kind: StepPaneRow['kind'],
75 text: string,
76 tone: StepTone = 'normal',
77 extra: Partial<Omit<StepPaneRow, 'key' | 'kind' | 'text' | 'tone'>> = {},
78): StepPaneRow => ({ key, kind, text, tone, ...extra })
79const segment = (text: string, tone: StepTone = 'normal', pool?: string): StepPaneSegment => ({ text, tone, ...(pool ? { pool } : {}) })
80const clip = (value: string, cells: number): string => value.length > cells ? `${value.slice(0, Math.max(0, cells - 1)).trimEnd()}…` : value
81
82/** The rich model attached by `workflow action show --json`. */
83export function stepPageOf(value: unknown): Raw {
84 const root = record(value)
85 return record(root?.page) ?? record(root?.step) ?? root ?? {}
86}
87
88const presentationOf = (page: Raw): Raw => record(page.presentation) ?? {}
89
90/** Resolve the selected attempt in compact Step JSON schema v2. */
91function selectedAttemptOf(page: Raw): Raw {
92 const direct = record(page.selectedAttempt)
93 if (direct && !nullable(direct.sameAs)) return direct
94 const attempts = list(page.attempts).map(record).filter((attempt): attempt is Raw => attempt !== null)
95 const ordinal = numberOf(page.selectedAttemptOrdinal)
96 return attempts.find(attempt => numberOf(attempt.ordinal) === ordinal) ?? attempts.at(-1) ?? {}
97}
98
99function activityOf(page: Raw): Raw {
100 return record(page.activity) ?? record(selectedAttemptOf(page).activity) ?? {}
101}
102const statusTone = (status: unknown): StepTone => {
103 const value = String(status ?? '').toLowerCase()
104 if (['succeeded', 'success', 'completed', 'complete', 'verified'].includes(value)) return 'good'
105 if (['failed', 'failure', 'error', 'cancelled', 'canceled', 'interrupted', 'blocked'].includes(value)) return 'bad'
106 if (['running', 'started', 'in_progress', 'in-progress', 'queued'].includes(value)) return 'running'
107 return 'dim'
108}
109const statusGlyph = (state: unknown): string => state === 'ok' ? '✓' : state === 'fail' ? '✗' : '▶'
110
111function headerRows(page: Raw, fallback: BullswarmStep | null, options: StepPaneOptions): StepPaneRow[] {
112 const header = record(presentationOf(page).header) ?? {}
113 const identity = record(page.identity) ?? {}
114 const attempt = selectedAttemptOf(page)
115 const fallbackAttempt = record(fallback?.attempt) ?? {}
116 const actionId = oneLine(header.actionId ?? identity.actionId ?? fallback?.id, 'step')
117 const shortId = nullable(header.shortId ?? identity.shortId)
118 const status = oneLine(header.status ?? identity.status ?? attempt.status ?? fallbackAttempt.status ?? fallback?.status, 'unknown').toLowerCase()
119 const tone = statusTone(status)
120 const phone = (options.width ?? 120) < 100
121 const fullVerdict = nullable(header.verdictText)
122 const verdict = phone && fullVerdict?.startsWith('verified by the workflow') ? 'verified'
123 : phone && fullVerdict?.startsWith('not verified') ? 'not verified'
124 : fullVerdict
125 const attemptText = phone ? null : nullable(header.attemptText)
126 const state = header.state ?? (tone === 'good' ? 'ok' : tone === 'bad' ? 'fail' : 'running')
127 const identityParts: StepPaneSegment[] = [
128 segment(`${statusGlyph(state)} `, tone), segment(actionId, 'strong'),
129 ...(shortId ? [segment(' · '), segment(shortId, 'strong')] : []),
130 segment(' · '), segment(status, tone),
131 ...(verdict ? [segment(' · '), segment(verdict, verdict.startsWith('not ') ? 'bad' : 'good')] : []),
132 ...(attemptText ? [segment(' · '), segment(attemptText, 'dim')] : []),
133 ]
134 const pool = nullable(header.pool ?? attempt.pool ?? fallbackAttempt.pool)
135 const model = nullable(header.model ?? attempt.model ?? fallbackAttempt.model)
136 const effort = nullable(header.effort ?? fallback?.effort)
137 const reasoning = nullable(header.reasoning)
138 const clock = nullable(header.clockText)
139 const clockRange = header.startedClock && header.finishedClock
140 ? `${String(header.startedClock)} → ${String(header.finishedClock)} HKT`
141 : nullable(header.startedClock) ? `since ${String(header.startedClock)} HKT` : null
142 const metaParts: StepPaneSegment[] = [
143 ...(pool ? [segment(pool, 'pool', pool)] : []),
144 ...(model ? [segment(`${pool ? ' · ' : ''}${model}`)] : []),
145 ...(effort ? [segment(` · ${effort}${phone ? '' : ' effort'}`)] : []),
146 ...(!phone && reasoning ? [segment(` · reasoning ${reasoning}`)] : []),
147 ...((clock || clockRange) ? [segment(` · ${[clock, clockRange?.replace(' → ', '→')].filter(Boolean).join(' · ')}`, 'dim')] : []),
148 ]
149 return [
150 row('identity', 'text', identityParts.map(part => part.text).join(''), tone, { segments: identityParts }),
151 ...(nullable(header.purpose ?? identity.purpose ?? fallback?.purpose)
152 ? [row('purpose', 'text', oneLine(header.purpose ?? identity.purpose ?? fallback?.purpose))]
153 : []),
154 row('meta', 'text', metaParts.map(part => part.text).join('') || '—', 'normal', { segments: metaParts }),
155 ...(nullable(header.route) ? [row('route', 'text', `route ${oneLine(header.route)}`, 'dim')] : []),
156 ]
157}
158
159function taskRows(page: Raw, fallback: BullswarmStep | null, options: StepPaneOptions): StepPaneRow[] {
160 const task = record(presentationOf(page).task) ?? record(page.taskBlock) ?? {}
161 const promptLines = list(task.promptLines).length ? list(task.promptLines) : options.promptPreview ?? []
162 const promptWidth = Math.max(20, options.width ?? 120)
163 const rows = promptLines.slice(0, 3).map((line, index) => row(`prompt-${index}`, 'text', clip(oneLine(line, ''), promptWidth)))
164 const facts: Array<[string, unknown]> = [['owns', task.owns], ['after', task.after], ['affects', task.affects]]
165 for (const [label, value] of facts) {
166 const values = list(value).map(entry => oneLine(entry, '')).filter(Boolean)
167 if (values.length) rows.push(row(label, 'text', `${label} ${values.join(' · ')}`, 'dim'))
168 }
169 const bytes = record(task.bytes)
170 if (bytes) {
171 const kb = (value: unknown) => numberOf(value) === null ? '—' : `${(numberOf(value)! / 1000).toFixed(1)} KB`
172 rows.push(row('task-open', 'text', `Enter on task: full text ${kb(bytes.authorPrompt)} · kernel wrapper ${kb(bytes.kernel)}`, 'dim'))
173 }
174 if (!rows.length) rows.push(row('task-unavailable', 'text', fallback?.purpose ?? 'task unavailable', 'dim'))
175 return rows
176}
177
178type ToolRow = { clock: string | null; text: string; command: boolean; duration: string | null; error: boolean; inFlight: boolean }
179
180function clockOf(value: unknown, seconds = false): string | null {
181 const date = new Date(String(value ?? ''))
182 if (!Number.isFinite(date.getTime())) return null
183 return new Intl.DateTimeFormat('en-GB', {
184 hour: '2-digit', minute: '2-digit', ...(seconds ? { second: '2-digit' } : {}), hour12: false,
185 }).format(date)
186}
187
188function rawToolRows(turn: Raw): ToolRow[] {
189 const events = list(turn.atomicEvents).map(record).filter((event): event is Raw => event !== null)
190 const paired = new Set<number>()
191 const rows: ToolRow[] = []
192 for (let index = 0; index < events.length; index += 1) {
193 if (paired.has(index)) continue
194 const event = events[index]!
195 const kind = String(event.kind ?? '').toLowerCase()
196 if (kind === 'response' || kind === 'usage' || kind === 'envelope' || kind === 'agent_result') continue
197 const next = events[index + 1]
198 const samePair = next
199 && String(next.kind ?? '') === String(event.kind ?? '')
200 && oneLine(next.summary, '') === oneLine(event.summary, '')
201 && String(event.status ?? '') === 'running'
202 && ['completed', 'failed', 'error'].includes(String(next.status ?? ''))
203 if (samePair) paired.add(index + 1)
204 const command = /command|shell|bash/.test(kind)
205 const durationMs = numberOf(next?.durationMs ?? event.durationMs)
206 rows.push({
207 clock: clockOf(event.at, true), text: oneLine(event.summary ?? event.tool ?? event.kind, 'tool'), command,
208 duration: durationMs !== null && durationMs >= 1000 ? `${Math.round(durationMs / 1000)}s` : null,
209 error: ['failed', 'error'].includes(String(next?.status ?? event.status ?? '')),
210 inFlight: String(event.status ?? '') === 'running' && !samePair,
211 })
212 }
213 return rows
214}
215
216function toolsFor(page: Raw, shownTurn: Raw): readonly ToolRow[] {
217 const projected = list(shownTurn.toolRows).map(record).filter((entry): entry is Raw => entry !== null)
218 if (projected.length) return projected.map(entry => ({
219 clock: nullable(entry.clock), text: oneLine(entry.text, 'tool'), command: entry.command === true,
220 duration: nullable(entry.durationText), error: entry.error === true,
221 inFlight: entry.inFlight === true,
222 }))
223 const rawActivity = activityOf(page)
224 const rawTurn = list(rawActivity.turns).map(record).find(turn => numberOf(turn?.index) === numberOf(shownTurn.index))
225 if (!rawTurn) return []
226 const atomic = list(rawTurn.atomicEvents)
227 if (atomic.length) return rawToolRows(rawTurn)
228 const events = list(rawActivity.events)
229 const indices = list(rawTurn.eventIndices).map(numberOf).filter((index): index is number => index !== null)
230 return rawToolRows({ ...rawTurn, atomicEvents: indices.map(index => events[index]).filter(Boolean) })
231}
232
233function totalsOf(turns: readonly Raw[]): string {
234 const totals = { commands: 0, filesRead: 0, searches: 0, edits: 0, otherTools: 0, errors: 0 }
235 for (const turn of turns) {
236 const summary = record(turn.summary) ?? {}
237 for (const key of Object.keys(totals) as Array<keyof typeof totals>) totals[key] += numberOf(summary[key]) ?? 0
238 }
239 return [
240 totals.commands ? `${totals.commands} command${totals.commands === 1 ? '' : 's'}` : null,
241 totals.filesRead ? `${totals.filesRead} file${totals.filesRead === 1 ? '' : 's'} read` : null,
242 totals.searches ? `${totals.searches} search${totals.searches === 1 ? '' : 'es'}` : null,
243 totals.edits ? `${totals.edits} edit${totals.edits === 1 ? '' : 's'}` : null,
244 totals.otherTools ? `${totals.otherTools} other tool${totals.otherTools === 1 ? '' : 's'}` : null,
245 totals.errors ? `${totals.errors} error${totals.errors === 1 ? '' : 's'}` : null,
246 ].filter(Boolean).join(' · ')
247}
248
249function elapsedText(startedAt: unknown, nowMs: unknown): string | null {
250 const started = Date.parse(String(startedAt ?? ''))
251 const now = numberOf(nowMs)
252 if (!Number.isFinite(started) || now === null) return null
253 const seconds = Math.max(0, Math.floor((now - started) / 1000))
254 if (seconds < 60) return `${seconds}s`
255 const minutes = Math.floor(seconds / 60)
256 return `${minutes}m${String(seconds % 60).padStart(2, '0')}s`
257}
258
259function activityRows(page: Raw, options: StepPaneOptions): StepPaneRow[] {
260 const activity = record(presentationOf(page).activity) ?? {}
261 const turns = list(activity.turns).map(record).filter((turn): turn is Raw => turn !== null)
262 const mode = options.mode ?? 'overview'
263 const rows: StepPaneRow[] = []
264 if (!activity.available || !turns.length) return [row('activity-empty', 'text', oneLine(activity.reason, 'event stream unavailable'), 'dim')]
265 const visibleCount = (options.width ?? 120) < 100 ? 5 : 10
266 const first = mode === 'overview' ? Math.max(0, turns.length - visibleCount) : 0
267 const followedTurn = turns.at(-1)
268 const selectedIndex = options.expandedTurn ?? numberOf(followedTurn?.index)
269 const runningCommand = record(activity.runningCommand)
270 const runningElapsed = runningCommand ? elapsedText(runningCommand.startedAt, options.nowMs) : null
271 if (mode === 'overview' && first > 0) {
272 const hidden = turns.slice(0, first)
273 const range = hidden.length === 1 ? 'turn 1' : `turns 1–${hidden.length}`
274 const counts = totalsOf(hidden)
275 rows.push(row('fold', 'fold', `${range}${counts ? ` · ${counts}` : ''} · click for detail`, 'dim', { opensDetail: true }))
276 }
277 turns.slice(first).forEach((turn, offset) => {
278 const index = numberOf(turn.index) ?? first + offset
279 const number = numberOf(turn.number) ?? index + 1
280 const selected = mode === 'overview' && selectedIndex === index
281 const prefix = `${selected ? '▶' : ' '}${String(number).padStart(2)} ${oneLine(turn.clock, '--:--')} `
282 const response = mode === 'overview'
283 ? clip(oneLine(turn.text, 'response summary unavailable'), Math.max(20, ((options.width ?? 120) - prefix.length) * 2))
284 : valueText(turn.text, 'response summary unavailable')
285 const head = `${prefix}${response}`
286 rows.push(row(`turn-${index}`, 'response', head, selected ? 'strong' : 'normal', { turnIndex: index, expandable: mode === 'overview', selected }))
287 if (mode === 'overview') {
288 const baseCounts = oneLine(turn.countsText, 'no tools').replace(/ · running:.*$/, '')
289 const counts = runningCommand && turn === followedTurn
290 ? `${baseCounts} · running: ${oneLine(runningCommand.text, 'command')}${runningElapsed ? ` ${runningElapsed}` : ''}`
291 : baseCounts
292 rows.push(row(`counts-${index}`, 'summary', turn.resultMarked === true ? '→ the report, shown under result' : counts, 'dim', { turnIndex: index, selected }))
293 if (selected) {
294 toolsFor(page, turn).filter(tool => !tool.inFlight).forEach((tool, toolIndex) => rows.push(row(`tool-${index}-${toolIndex}`, 'atomic', `${tool.clock ?? '--:--:--'} ${tool.command ? '$ ' : ''}${tool.text}${tool.duration ? ` ${tool.duration}` : ''}`, tool.error ? 'bad' : 'dim', { turnIndex: index })))
295 if (runningCommand && turn === followedTurn) {
296 const live = `⋮ running${runningElapsed ? ` ${runningElapsed}` : ''} ${oneLine(runningCommand.text, 'command')}`
297 rows.push(row(`running-${index}`, 'atomic', clip(live, Math.max(20, options.width ?? 120)), 'running', { turnIndex: index, selected: true }))
298 }
299 }
300 return
301 }
302 rows.push(row(`counts-${index}`, 'summary', oneLine(turn.countsText, 'no tools'), 'dim', { turnIndex: index }))
303 toolsFor(page, turn).forEach((tool, toolIndex) => rows.push(row(`tool-${index}-${toolIndex}`, 'atomic', `${tool.clock ?? '--:--:--'} ${tool.command ? '$ ' : ''}${tool.text}${tool.duration ? ` ${tool.duration}` : ''}`, tool.error ? 'bad' : 'dim', { turnIndex: index })))
304 })
305 return rows
306}
307
308function resultRows(page: Raw, fallback: BullswarmStep | null, options: StepPaneOptions): StepPaneRow[] {
309 const result = record(presentationOf(page).result) ?? {}
310 if (!Object.keys(result).length) return options.outputTail
311 ? options.outputTail.split(/\r?\n/).slice(0, 3).map((line, index) => row(`output-${index}`, 'text', line))
312 : [row('result-empty', 'text', fallback?.lastFailure ?? 'no report was written', 'dim')]
313 const rows: StepPaneRow[] = []
314 // A v3 step's checked answer leads its result, as on the dashboard.
315 const answer = record(result.answer)
316 if (answer && nullable(answer.text))
317 rows.push(row('answer', 'text', clip(oneLine(answer.text), Math.max(20, options.width ?? 120)), answer.ok === false ? 'bad' : 'normal'))
318 if (result.running === true) {
319 rows.push(row('not-yet', 'text', 'not yet', 'dim'))
320 const last = record(result.lastResponse)
321 if (last) rows.push(row('last-response', 'text', `${oneLine(last.clock)} ${valueText(last.text, '')}`))
322 } else list(result.reportLines).forEach((line, index) => rows.push(row(`report-${index}`, 'text', clip(oneLine(line, ''), Math.max(20, options.width ?? 120)))))
323 if (nullable(result.failure)) rows.push(row('failure', 'text', oneLine(result.failure), 'bad'))
324 list(result.changed).forEach((path, index) => rows.push(row(`changed-${index}`, 'artifact', `changed ${String(path)}`, 'dim')))
325 list(result.asks).forEach((ask, index) => rows.push(row(`asks-${index}`, 'text', `asks ${String(ask)}`, 'dim')))
326 const artifacts = record(result.artifacts) ?? {}
327 const fileBits = [result.runDirShort ? `run ${String(result.runDirShort)}` : null]
328 for (const name of ['task', 'output', 'stream', 'diff'] as const) {
329 const value = nullable(artifacts[name])
330 if (value) fileBits.push(name === 'stream' ? `${name} (${String(result.streamEvents ?? 0)} events)` : name)
331 }
332 if (fileBits.length) rows.push(row('files', 'artifact', `files ${fileBits.filter(Boolean).join(' · ')}`, 'dim'))
333 if (nullable(result.reportBytesText)) rows.push(row('result-open', 'text', `Enter on result: the full report, ${String(result.reportBytesText)}`, 'dim'))
334 return rows
335}
336
337function costRows(page: Raw): StepPaneRow[] {
338 const cost = record(presentationOf(page).cost) ?? {}
339 const rows: StepPaneRow[] = []
340 for (const value of list(cost.rows)) {
341 const entry = record(value) ?? {}
342 const label = oneLine(entry.label, 'cost')
343 const amount = oneLine(entry.amount)
344 const headline = oneLine(entry.headline, '')
345 const segments = [segment(label, label.endsWith(' plan') ? 'pool' : 'dim', label.replace(/ plan$/, '')), segment(' '), segment(amount, 'strong'), ...(headline ? [segment(` ${headline}`, 'dim')] : [])]
346 rows.push(row(`cost-${label}`, 'text', segments.map(part => part.text).join(''), 'normal', { segments }))
347 list(entry.details).forEach((detail, index) => rows.push(row(`cost-${label}-${index}`, 'text', ` ${String(detail)}`, 'dim')))
348 }
349 if (nullable(cost.basisLine)) rows.push(row('cost-basis', 'text', String(cost.basisLine), 'dim'))
350 return rows.length ? rows : [row('cost-empty', 'text', '—', 'dim')]
351}
352
353const TOGGLE_TEXT = 'overview · detail'
354
355/**
356 * The activity block's heading (rule 14): the heading word, the toggle straight
357 * after it, then the counts. A narrow pane drops count segments from the end,
358 * the filter control first; the word and the toggle are never cut. The current
359 * view is marked with two cells (`● ` in the pane, brackets in the frames).
360 */
361function headingWithToggle(label: string, segments: readonly string[], width: number): { lead: string; trail: string; title: string } {
362 const lead = `── ${label} · `
363 let keep = segments.length
364 const trailOf = (count: number): string => `${count ? ` · ${segments.slice(0, count).join(' · ')}` : ''} ──`
365 while (keep > 0 && lead.length + TOGGLE_TEXT.length + trailOf(keep).length + 2 > width) keep -= 1
366 const trail = trailOf(keep)
367 return { lead, trail, title: `${lead.slice(3)}${TOGGLE_TEXT}${trail.slice(0, -3)}` }
368}
369
370/** Shape the action-show record into the finished Step v2 pane. */
371export function shapeStep(value: unknown, options: StepPaneOptions = {}): StepPaneModel {
372 const page = stepPageOf(value)
373 const fallback = record(value) as BullswarmStep | null
374 const mode: StepMode = options.mode ?? (page.view === 'detail' ? 'detail' : 'overview')
375 const presentation = presentationOf(page)
376 const header = record(presentation.header) ?? {}
377 const result = record(presentation.result) ?? {}
378 const task = record(presentation.task) ?? {}
379 const activity = record(presentation.activity) ?? {}
380 const status = oneLine(header.status ?? fallback?.status, 'unknown')
381 const resultVerdict = nullable(result.verdictText)
382 const activityTotals = record(activity.totals) ?? {}
383 const turnCount = list(activity.turns).length
384 const commandCount = numberOf(activityTotals.commands) ?? 0
385 const editCount = numberOf(activityTotals.edits) ?? 0
386 const errorCount = numberOf(activityTotals.errors) ?? 0
387 const running = activity.running === true
388 const countSegments = [
389 `${turnCount} turn${turnCount === 1 ? '' : 's'}${running ? ' so far' : ''}`,
390 `${commandCount} cmds`, `${editCount} edits`, `${errorCount} err`,
391 ]
392 const activityHeading = headingWithToggle(mode === 'detail' ? 'transcript' : 'activity', mode === 'detail'
393 ? [...countSegments, 'showing all']
394 : [...countSegments, 'showing turns'], options.width ?? 120)
395 const activityTitle = activityHeading.title
396 const resultTitle = result.running === true ? 'now · not yet' : `result · ${status}${resultVerdict ? ` · ${resultVerdict}` : ''}`
397 const taskTitle = `task${task.lane ? ` · ${String(task.lane)}` : ''}${task.kind ? ` · ${String(task.kind)}` : ''}`
398 const cost = record(presentation.cost) ?? {}
399 const attemptCount = numberOf(cost.attemptCount) ?? 1
400 const blocksByKey: Record<StepPaneBlock['key'], StepPaneBlock> = {
401 header: { key: 'header', title: '', rows: headerRows(page, fallback, options) },
402 activity: { key: 'activity', title: activityTitle, rows: activityRows(page, { ...options, mode }) },
403 result: { key: 'result', title: resultTitle, rows: resultRows(page, fallback, options) },
404 task: { key: 'task', title: taskTitle, rows: taskRows(page, fallback, options) },
405 cost: { key: 'cost', title: attemptCount > 1 ? `cost · ${attemptCount} attempts` : 'cost', rows: costRows(page) },
406 }
407 const order: StepPaneBlock['key'][] = (options.width ?? 120) < 100
408 ? ['header', 'result', 'activity', 'task', 'cost']
409 : ['header', 'activity', 'result', 'task', 'cost']
410 const blocks = order.map(key => blocksByKey[key])
411 const sectionRow = (block: StepPaneBlock): StepPaneRow => block.key === 'activity'
412 ? row('activity-section', 'section', `${activityHeading.lead}${TOGGLE_TEXT}${activityHeading.trail}`, 'normal', { toggle: { lead: activityHeading.lead, trail: activityHeading.trail } })
413 : row(`${block.key}-section`, 'section', `── ${block.title} ──`)
414 const rows = blocks.flatMap(block => block.key === 'header' ? block.rows : [sectionRow(block), ...block.rows])
415 return {
416 mode,
417 actionId: oneLine(header.actionId ?? fallback?.id, 'step'),
418 runId: nullable(header.shortId),
419 blocks,
420 rows,
421 toggleLabel: mode === 'overview' ? 'detail' : 'overview',
422 toggleHint: mode === 'overview' ? 'v detail (every turn in full)' : 'v overview (latest turns)',
423 }
424}
425
426export const stepPaneModel = shapeStep
427
428/** Standalone tasks use a supplied Step model, or the same five-block grammar with honest absences. */
429export function taskStepPane(task: unknown, options: StepPaneOptions = {}): StepPaneModel {
430 const value = record(task) ?? {}
431 if (record(value.step) || record(value.page) || record(value.presentation)) return shapeStep(value, options)
432 const id = nullable(value.id) ?? nullable(value.taskFile)?.split(/[\\/]/).pop() ?? 'task'
433 const status = value.ok === true ? 'succeeded' : value.ok === false ? 'failed' : 'running'
434 return shapeStep({ presentation: {
435 header: { state: status === 'succeeded' ? 'ok' : status === 'failed' ? 'fail' : 'running', actionId: id, status, pool: value.pool, model: value.model, purpose: value.description ?? value.task },
436 activity: { available: false, reason: 'event stream unavailable', turns: [], totals: {} },
437 result: { running: status === 'running', reportLines: [], failure: value.reason, artifacts: { task: value.taskFile, output: value.outFile } },
438 task: { promptLines: options.promptPreview ?? [], owns: [], after: [], affects: [] },
439 cost: { attemptCount: 1, rows: [{ label: 'API rate', amount: '—', headline: 'no recorded rate', details: [] }, { label: `${String(value.pool ?? 'pool')} plan`, amount: '—', headline: 'no meter reading for this attempt', details: [] }] },
440 } }, options)
441}
442hooks/verdict.ts 223 lines1import type { BullswarmVerdict } from '../types'
2
3type Raw = Record<string, unknown>
4
5/**
6 * Finds the JSON document in a command's output: the whole text, or the
7 * last object that starts at a line start and parses to the end.
8 */
9export function jsonIn(text: string): Raw | null {
10 const trimmed = text.trim()
11 try {
12 const whole = JSON.parse(trimmed) as unknown
13 if (whole && typeof whole === 'object') return whole as Raw
14 } catch {
15 // fall through to a scan
16 }
17
18 const end = trimmed.lastIndexOf('}')
19 if (end < 0) return null
20 const starts: number[] = []
21 const re = /^\{/gm
22 let m: RegExpExecArray | null
23 while ((m = re.exec(trimmed))) starts.push(m.index)
24 for (const start of starts.reverse()) {
25 try {
26 const doc = JSON.parse(trimmed.slice(start, end + 1)) as unknown
27 if (doc && typeof doc === 'object') return doc as Raw
28 } catch {
29 // try the next start
30 }
31 }
32 return null
33}
34
35const str = (v: unknown): string | null => (typeof v === 'string' ? v : null)
36const num = (v: unknown): number | null =>
37 typeof v === 'number' && Number.isFinite(v) ? v : null
38
39/** A gate or loop a parked run waits at, as the waiting document lists it. */
40function waitingNodes(v: unknown): BullswarmVerdict['waitingFor'] {
41 if (!Array.isArray(v)) return []
42 return (v as Raw[])
43 .filter(n => typeof n?.id === 'string')
44 .map(n => ({ id: n.id as string, type: str(n.type) ?? 'gate', note: str(n.note) }))
45}
46
47const ANSWER_CHARS = 300
48
49function answerText(value: unknown): string {
50 const text = JSON.stringify(value) ?? 'null'
51 return text.length > ANSWER_CHARS ? `${text.slice(0, ANSWER_CHARS - 1)}…` : text
52}
53
54/** A run verdict's `notDone` (0.37), or null when absent or malformed. */
55function notDoneOf(v: unknown): BullswarmVerdict['notDone'] {
56 const raw = (v ?? null) as Raw | null
57 const count = num(raw?.count)
58 if (count === null || count <= 0) return null
59 const items = Array.isArray(raw?.items) ? (raw.items as unknown[]).filter((i): i is string => typeof i === 'string') : []
60 return { count, items }
61}
62
63/**
64 * Reads a `bullswarm run --json` or `bullswarm workflow goal --json`
65 * document into one verdict shape.
66 */
67export function parseVerdict(text: string, exitCode: number): BullswarmVerdict {
68 const doc = jsonIn(text)
69 const pick = (doc?.pick ?? null) as Raw | null
70 const meta = (doc?.meta ?? null) as Raw | null
71 // 0.37: a run's verdict carries a short `usage` summary; earlier ones kept
72 // the attempt's full usage under meta.usage.
73 const usage = (doc?.usage ?? meta?.usage ?? null) as Raw | null
74 const tokens = (usage?.tokens ?? null) as Raw | null
75 const check = (doc?.answerCheck ?? null) as Raw | null
76 const errors = Array.isArray(check?.errors) ? (check.errors as unknown[]) : []
77
78 return {
79 found: doc !== null && (typeof doc.ok === 'boolean' || doc.action === 'workflow-waiting'),
80 ok: doc?.ok === true,
81 why: str(doc?.why),
82 outFile: str(doc?.outFile),
83 pool: str(pick?.pool) ?? str(doc?.picked) ?? str(doc?.pool),
84 model: str(pick?.model) ?? str(doc?.model),
85 shortId: str(doc?.shortId),
86 wallSec: num(meta?.wallSec),
87 inputTokens: num(tokens?.standardRead),
88 outputTokens: num(tokens?.output),
89 answer: doc && 'answer' in doc ? (doc.answer ?? null) : null,
90 answerOk: typeof check?.ok === 'boolean' ? check.ok : null,
91 answerErrors: errors.map(e => (typeof e === 'string' ? e : str((e as Raw)?.message) ?? JSON.stringify(e))),
92 notDone: notDoneOf(doc?.notDone),
93 waitingFor: waitingNodes(doc?.waitingFor),
94 next: Array.isArray(doc?.next) ? (doc.next as unknown[]).filter((c): c is string => typeof c === 'string') : [],
95 exitCode,
96 raw: text,
97 }
98}
99
100/**
101 * The note appended to a Bash result that ran bullswarm: the verdict in the
102 * doctrine's words, so the model reads the output file instead of trusting
103 * the exit code.
104 */
105export function verdictContext(
106 verb: 'run' | 'workflow goal',
107 v: BullswarmVerdict,
108): string | null {
109 if (!v.found) return null
110 if (verb === 'workflow goal') {
111 if (v.waitingFor.length && v.shortId) return `bullswarm mod: ${waitingSentence(v.shortId, v.waitingFor, v.next)}`
112 return v.shortId
113 ? `bullswarm mod: workflow ${v.shortId} launched and detached. It stops for you only at a gate, a loop out of rounds or a step that needs you: run \`bullswarm workflow watch ${v.shortId} --until trouble\` (in the background when your harness wakes you when it exits, else in the foreground with \`--timeout\` below your tool's time limit; never end your turn while it runs), act on what wakes you, and relaunch it with the \`next:\` line it prints; \`/bullswarm\` shows the meters.`
114 : null
115 }
116 // A run given --answer-schema reports its answer, checked against the schema.
117 const answer = v.answerOk === true
118 ? ` Its answer ${answerText(v.answer)} (checked against its schema).`
119 : v.answerOk === false
120 ? ` Its answer check failed: ${v.answerErrors[0] ?? 'the answer does not match its schema'}.`
121 : ''
122 // What the worker's report says it left: a fact beside ok, not a failure.
123 const more = v.notDone ? v.notDone.count - v.notDone.items.length : 0
124 const notDone = v.notDone
125 ? ` The worker left ${v.notDone.count} item${v.notDone.count === 1 ? '' : 's'} not done${v.notDone.items.length ? `: ${v.notDone.items.join('; ')}${more > 0 ? ` (and ${more} more)` : ''}` : ''}.`
126 : ''
127 if (v.ok && v.outFile)
128 return `bullswarm mod: verdict ok from pool ${v.pool ?? '?'} (${v.model ?? '?'}); ${v.why ?? 'verified by content'}.${answer}${notDone} Read ${v.outFile} and check its content before using it — a clean exit code is not proof.`
129 if (!v.ok)
130 return `bullswarm mod: verdict ok=false — ${v.why ?? 'unknown failure'}.${answer} Inspect and report; do not retry blindly.`
131 return null
132}
133
134/** `2fne62 is waiting for you at gate approve (note). Nothing moves until …` */
135function waitingSentence(
136 token: string,
137 nodes: BullswarmVerdict['waitingFor'],
138 next: readonly string[],
139): string {
140 const named = nodes
141 .map(n => `${n.type} ${n.id}${n.note ? ` (${n.note})` : ''}`)
142 .join(', ')
143 const commands = next.length
144 ? next
145 : nodes.map(n => `bullswarm workflow continue ${token} ${n.id}${n.type === 'loop' ? ' --rounds <n>' : ''}`)
146 return `workflow ${token} is waiting for you at ${named}. Nothing behind it moves until you decide: ${commands.map(c => `\`${c}\``).join(' or ')}.`
147}
148
149/**
150 * The note appended to a `bullswarm workflow watch` or `workflow wait` result
151 * that shows a v3 run's gates, loops or answers, or null when it shows none:
152 * where the run waits and the command that moves it, the loop's round, and
153 * how many checked answers the output holds.
154 */
155export function watchContext(text: string): string | null {
156 const lines = text.split(/\r?\n/)
157 const parts: string[] = []
158 // Where the run waits: watch's `waiting: gate approve · note`, a stopped
159 // wait's ` waiting gate approve · note`, or wait's own fact line
160 // `⧖ gate approve waiting · note` / `⧖ loop fix waiting · round 3 of 3 · …`.
161 const waiting = lines
162 .map(l => {
163 const listed = /^waiting(?::\s*|\s+)(gate|loop) (\S+)(?: · (.*))?$/.exec(l.trim())
164 if (listed) return listed
165 const fact = /^\S+ (gate|loop) (\S+) waiting(?: · (.*?))?(?: · continue: .*)?$/.exec(l.trim())
166 if (!fact) return null
167 const rounds = fact[1] === 'loop' ? /round (\d+) of (\d+)/.exec(fact[3] ?? '') : null
168 if (rounds) fact[3] = `out of rounds (${rounds[1]!} of ${rounds[2]!})`
169 return fact
170 })
171 .filter((m): m is RegExpExecArray => m !== null)
172 .filter((m, i, all) => all.findIndex(o => o[1] === m[1] && o[2] === m[2]) === i)
173 const token = /bullswarm workflow continue (\S+) /.exec(text)?.[1] ?? null
174 const next = [
175 ...new Set(
176 lines
177 .map(l => /^(?:next:| or:|\s*continue)\s+(bullswarm workflow continue .*?)(?:\s{2,}\(.*)?$/.exec(l)?.[1] ?? null)
178 .filter((c): c is string => c !== null),
179 ),
180 ]
181 if (waiting.length && token) {
182 parts.push(
183 waitingSentence(
184 token,
185 waiting.map(m => ({ id: m[2]!, type: m[1]!, note: m[1] === 'gate' ? (m[3] ?? null) : null })),
186 next,
187 ),
188 )
189 for (const m of waiting.filter(w => w[1] === 'loop'))
190 parts.push(`The loop ${m[2]!} is ${(m[3] ?? 'out of rounds').replace(/;.*$/, '')}: --rounds gives it more; without --rounds it ends continued with its condition not met, which is no pass.`)
191 }
192 const loop = [...lines]
193 .reverse()
194 .map(l => {
195 const m = /loop (\S+) (passed (?:in|after) round \d+ of \d+|round \d+ of \d+|blocked in round \d+|continued by the caller after \d+ of \d+ rounds \(condition not met\))/.exec(l)
196 if (m) return m
197 // wait's fact line: `✓ loop fix passed · round 2 of 3`.
198 const fact = /loop (\S+) (passed|blocked) · round (\d+ of \d+)/.exec(l)
199 if (fact) fact[2] = `${fact[2]!} in round ${fact[3]!}`
200 return fact
201 })
202 .find((m): m is RegExpExecArray => m !== null)
203 if (loop && !waiting.some(w => w[1] === 'loop' && w[2] === loop[1]))
204 parts.push(`The loop ${loop[1]!} ${loop[2]!.startsWith('round') ? `is in ${loop[2]!}` : loop[2]!}.`)
205 const answers = lines.filter(l => /^\s+answer(?: \{|\[|$)/.test(l)).length
206 if (answers)
207 parts.push(`The output shows ${answers} checked answer${answers === 1 ? '' : 's'} (each matched its step's schema); read them as the steps' results, not the workers' prose.`)
208 return parts.length ? `bullswarm mod: ${parts.join(' ')}` : null
209}
210
211/**
212 * The model-facing note on an Agent call the mod routed to bullswarm. It names
213 * the pool and model, the verdict, what the worker left not done (0.37.2: only
214 * the on-screen notice said so before) and the output file to judge.
215 */
216export function routedContext(v: BullswarmVerdict, lane: string): string {
217 const more = v.notDone ? v.notDone.count - v.notDone.items.length : 0
218 const notDone = v.notDone
219 ? ` The worker left ${v.notDone.count} item${v.notDone.count === 1 ? '' : 's'} not done (its ## Not done section)${v.notDone.items.length ? `: ${v.notDone.items.join('; ')}${more > 0 ? ` (and ${more} more)` : ''}` : ''}.`
220 : ''
221 return `This Agent call was routed by the bullswarm mod to pool "${v.pool ?? '?'}" (model ${v.model ?? '?'}) on the ${lane} lane instead of a Claude subagent, because that pool had spare subscription quota. Bullswarm's verdict: ${v.why ?? 'ok'}.${notDone} The delegate's full output is saved at ${v.outFile}. Judge it by its content, as evidence, not as authority.`
222}
223hooks/pool-rows.tsx 117 lines1/* @jsxRuntime classic */
2/* @jsx h */
3/* @jsxFrag Fragment */
4import type { ElementTable, RenderElement } from 'claude-code'
5
6import type { BullswarmAssignment, BullswarmPool } from '../types'
7import { paceText, stateOf } from './pools'
8
9/**
10 * The meter colours, the truecolour values the status line renders with
11 * (herdr remaps the basic ANSI colours through its theme, so names would
12 * not agree with it): green below 50% used, amber from 50%, red from 80%.
13 */
14export const METER_GREEN = '#b6bd73'
15export const METER_AMBER = '#e9c880'
16export const METER_RED = '#bf6c69'
17
18/** The fill colour of a meter by how much is used, as the status line picks it. */
19export const severityColor = (usedPct: number | null): string =>
20 usedPct === null ? 'gray' : usedPct >= 80 ? METER_RED : usedPct >= 50 ? METER_AMBER : METER_GREEN
21
22const TRACK = '#3a3a3a'
23
24/**
25 * The bar as the status line draws it: background-coloured cells, filled
26 * up to used% in the severity colour over a dark track, and a white
27 * one-eighth line at the cell where elapsed% falls (the right edge of the
28 * last cell once the window has fully elapsed).
29 */
30export function meterBar(
31 Text: RowsUi['Text'],
32 usedPct: number | null,
33 elapsedPct: number | null,
34 width: number,
35 key?: string,
36): RenderElement {
37 if (usedPct === null) return <Text key={key} backgroundColor={TRACK}>{'·'.repeat(width)}</Text>
38 const fill = severityColor(usedPct)
39 const filled = Math.max(0, Math.min(width, Math.floor((usedPct / 100) * width)))
40 let mark = -1
41 let glyph = '▏'
42 if (elapsedPct !== null) {
43 mark = Math.floor((elapsedPct / 100) * width)
44 if (mark >= width) {
45 mark = width - 1
46 glyph = '▕'
47 }
48 }
49 const cells: RenderElement[] = []
50 let i = 0
51 while (i < width) {
52 const bg = i < filled ? fill : TRACK
53 if (i === mark) {
54 cells.push(
55 <Text key={`m${String(i)}`} color="white" backgroundColor={bg}>
56 {glyph}
57 </Text>,
58 )
59 i += 1
60 continue
61 }
62 let j = i
63 while (j < width && j !== mark && (j < filled) === (i < filled)) j += 1
64 cells.push(
65 <Text key={`c${String(i)}`} backgroundColor={bg}>
66 {' '.repeat(j - i)}
67 </Text>,
68 )
69 i = j
70 }
71 return <Text key={key}>{cells}</Text>
72}
73
74export type RowsUi = Pick<ElementTable<'terminal' | 'desktop'>, 'Box' | 'Text'>
75
76const NAME_WIDTH = 16
77const BAR_WIDTH = 10
78
79/**
80 * One row per enabled pool: display name, used-quota bar, used/elapsed,
81 * signed pace in the state's color, the actions running there. Shared by
82 * the strip and the pane.
83 */
84export function poolRows(
85 ui: RowsUi,
86 pools: readonly BullswarmPool[],
87 assignments: readonly BullswarmAssignment[],
88 names: ReadonlyMap<string, string>,
89): RenderElement[] {
90 const { Box, Text } = ui
91 return pools
92 .filter(p => p.enabled)
93 .map(p => {
94 const state = stateOf(p)
95 const name = (names.get(p.name) ?? p.name).padEnd(NAME_WIDTH).slice(0, NAME_WIDTH)
96 const used = p.usedPct === null ? ' —' : `${String(Math.round(p.usedPct)).padStart(3)}%`
97 const elapsed = p.elapsedPct === null ? '' : `/${String(Math.round(p.elapsedPct)).padStart(2)}%`
98 const busy = assignments.filter(a => a.pool === p.name)
99 const running = busy.length ? ` ${busy.map(a => a.actionId ?? a.lane).join(', ')}` : ''
100 return (
101 <Box key={p.name} flexDirection="row">
102 <Text wrap="truncate-end">
103 <Text>{name}</Text>
104 {meterBar(Text, p.usedPct, p.elapsedPct, BAR_WIDTH)}
105 <Text> {used}</Text>
106 <Text dimColor>{elapsed}</Text>
107 <Text color={state.color} bold>
108 {' '}
109 {p.quarantine ? 'quarantined' : paceText(p)}
110 </Text>
111 {running ? <Text color="cyan">{running}</Text> : null}
112 </Text>
113 </Box>
114 )
115 })
116}
117