project-brain 0.43.0 → 0.45.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +97 -11
  2. package/package.json +6 -6
  3. package/templates/claude-tui/activity-pane/.claude-plugin/plugin.json +7 -0
  4. package/templates/claude-tui/activity-pane/hooks/feat-agents.tsx +179 -0
  5. package/templates/claude-tui/activity-pane/hooks/feat-blocked.tsx +232 -0
  6. package/templates/claude-tui/activity-pane/hooks/feat-ci.tsx +400 -0
  7. package/templates/claude-tui/activity-pane/hooks/feat-context.tsx +283 -0
  8. package/templates/claude-tui/activity-pane/hooks/feat-notify.tsx +145 -0
  9. package/templates/claude-tui/activity-pane/hooks/feat-progress.tsx +413 -0
  10. package/templates/claude-tui/activity-pane/hooks/feat-running.tsx +528 -0
  11. package/templates/claude-tui/activity-pane/hooks/feat-savings.tsx +533 -0
  12. package/templates/claude-tui/activity-pane/hooks/hooks.json +1 -0
  13. package/templates/claude-tui/activity-pane/hooks/register.tsx +2141 -0
  14. package/templates/claude-tui/activity-pane/types/index.d.ts +201 -0
  15. package/templates/claude-tui/context-gate/.claude-plugin/plugin.json +7 -0
  16. package/templates/claude-tui/context-gate/hooks/hooks.json +1 -0
  17. package/templates/claude-tui/context-gate/hooks/register.tsx +355 -0
  18. package/templates/claude-tui/context-gate/types/index.d.ts +28 -0
  19. package/templates/claude-tui/skill-listing/.claude-plugin/plugin.json +7 -0
  20. package/templates/claude-tui/skill-listing/hooks/hooks.json +1 -0
  21. package/templates/claude-tui/skill-listing/hooks/register.tsx +300 -0
  22. package/templates/claude-tui/skill-listing/types/index.d.ts +22 -0
  23. package/templates/model-routing.md +10 -0
  24. package/templates/skills/brain-design-review/SKILL.md +65 -0
  25. package/templates/skills/brain-design-review/references/audit.md +56 -0
  26. package/templates/skills/brain-design-review/references/fix-loop.md +36 -0
  27. package/templates/skills/brain-design-review/references/probes.md +80 -0
  28. package/templates/skills/brain-qa-only/SKILL.md +59 -0
  29. package/templates/skills/brain-qa-only/references/report.md +63 -0
  30. package/templates/skills/brain-worktree/SKILL.md +18 -0
@@ -0,0 +1,528 @@
1
+ import type { Hook } from 'claude-code'
2
+ import { atom, read, update } from 'claude-code'
3
+ import type { Register } from 'claude-code'
4
+
5
+ import type { Api, Row, Span, Tone } from './register'
6
+ import { ICONS, clean, fit, shortName, span } from './register'
7
+ import { notify } from './feat-notify'
8
+
9
+ export type RunningKind = 'bash' | 'monitor' | 'agent' | 'workflow'
10
+ export type RunningStatus = 'running' | 'completed' | 'failed' | 'killed'
11
+
12
+ /** One piece of background work: a backgrounded shell, a Monitor watch, a background agent or a workflow. */
13
+ export type RunningTask = {
14
+ id: string
15
+ kind: RunningKind
16
+ label: string
17
+ status: RunningStatus
18
+ startedAt: number
19
+ endedAt?: number
20
+ /** The loop that started it; absent for the main conversation. */
21
+ agentId?: string
22
+ agentLabel?: string
23
+ toolUseId?: string
24
+ /** Only ever a path the engine reported for this task. */
25
+ outputFile?: string
26
+ lastLine?: string
27
+ exitCode?: number
28
+ /** A Monitor's kill deadline, when it has one. */
29
+ deadline?: number
30
+ /** Ended without a notification: the session's in-flight list no longer named it. */
31
+ isInferred?: boolean
32
+ }
33
+
34
+ export type RunningPart = { tasks: RunningTask[]; now: number }
35
+
36
+ /** What a background-launching tool call reported. */
37
+ export type Launch = Pick<RunningTask, 'id' | 'kind' | 'label'> & Partial<Pick<RunningTask, 'outputFile' | 'deadline'>>
38
+
39
+ /** One `<task-notification>` block, its fields unescaped; `status` absent on a Monitor's mid-stream event. */
40
+ export type Notice = { id: string; toolUseId?: string; status?: string; summary?: string; event?: string; outputFile?: string; exitCode?: number }
41
+
42
+ type On = Parameters<Register>[0]
43
+
44
+ const KEEP = 50
45
+ const LINGER_MS = 10 * 60_000
46
+ const TICK_MS = 3000
47
+ const TAIL_BYTES = 64 * 1024
48
+ const TAILS_PER_TICK = 8
49
+ const LINE_MAX = 300
50
+ const LABEL_MAX = 200
51
+ const MONITOR_GRACE_MS = 15_000
52
+ const STOP_GRACE_MS = 5000
53
+ const SECTION_KEY = 'running-section'
54
+ const TASK_ID = /^[A-Za-z0-9_-]{4,64}$/
55
+ const OUTPUT_PATH = /^\/(?:[^\0/]+\/)+tasks\/[A-Za-z0-9_-]{4,64}\.output$/
56
+ const NOTICE_DOORS = new Set(['prompt', 'delivery', 'attachment', 'queue', 'hook-context', 'notice'])
57
+
58
+ const tasksAtom = atom({ plugin: 'project-brain-activity', key: 'runningTasks' } as const, [] as RunningTask[], { shape: 'running-tasks-1' })
59
+ const tickAtom = atom({ plugin: 'project-brain-activity', key: 'runningTick' } as const, 0, { shape: 'running-tick-1' })
60
+
61
+ // A reload drops these; session.start restarts the timer when work is still running.
62
+ let ticker: { cancel: () => void } | undefined
63
+ let ticking = false
64
+ const tailMtime = new Map<string, number>()
65
+
66
+ // ---------------------------------------------------------------- parsing
67
+
68
+ const str = (value: unknown): string | undefined => (typeof value === 'string' && value.trim() !== '' ? value : undefined)
69
+
70
+ const oneLine = (raw: string, max: number): string => fit(clean(raw).replace(/\s+/g, ' ').trim(), max)
71
+
72
+ const unescape = (value: string): string =>
73
+ value.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, '&')
74
+
75
+ const safeId = (value: unknown): string | undefined => {
76
+ const id = str(value)?.trim()
77
+ return id !== undefined && TASK_ID.test(id) ? id : undefined
78
+ }
79
+
80
+ /** A task output path as the engine wrote it; anything else is refused. */
81
+ export const safeOutputPath = (value: unknown): string | undefined => {
82
+ const path = str(value)?.trim()
83
+ return path !== undefined && OUTPUT_PATH.test(path) && !path.split('/').includes('..') ? path : undefined
84
+ }
85
+
86
+ /** The exit code a notification's summary or event names: `(exit code 0)`, `failed with exit code 1`, `[exited with code 1]`. */
87
+ export const exitCodeIn = (text: string): number | undefined => {
88
+ const match = /exit(?:ed)? (?:with )?code (\d{1,3})/i.exec(text)
89
+ return match ? Number(match[1]) : undefined
90
+ }
91
+
92
+ /** Reads what a tool call that may have started background work reported. */
93
+ export const launchOf = (tool: string, input: Record<string, unknown>, result: unknown, text: string | undefined, startedAt: number): Launch | undefined => {
94
+ const record = (result ?? {}) as Record<string, unknown>
95
+ if (tool === 'Bash') {
96
+ const id = safeId(record.backgroundTaskId)
97
+ if (id === undefined) return undefined
98
+ const written = /Output is being written to: (\S+?\.output)\b/.exec(text ?? '')?.[1]
99
+ const outputFile = safeOutputPath(record.backgroundOutputPath) ?? safeOutputPath(written)
100
+ const label = oneLine(str(input.description) ?? str(input.command) ?? 'comando', LABEL_MAX)
101
+ return { id, kind: 'bash', label, ...(outputFile === undefined ? {} : { outputFile }) }
102
+ }
103
+ if (tool === 'Monitor') {
104
+ const id = safeId(record.taskId)
105
+ if (id === undefined) return undefined
106
+ const timeoutMs = typeof record.timeoutMs === 'number' && record.timeoutMs > 0 && record.persistent !== true ? record.timeoutMs : undefined
107
+ const label = oneLine(str(input.description) ?? str(input.command) ?? 'monitor', LABEL_MAX)
108
+ return { id, kind: 'monitor', label, ...(timeoutMs === undefined ? {} : { deadline: startedAt + timeoutMs }) }
109
+ }
110
+ if (tool === 'Agent') {
111
+ const status = record.status
112
+ const id = status === 'async_launched' ? safeId(record.agentId) : status === 'remote_launched' ? safeId(record.taskId) : undefined
113
+ if (id === undefined) return undefined
114
+ return { id, kind: 'agent', label: oneLine(str(record.description) ?? str(input.description) ?? 'agente', LABEL_MAX) }
115
+ }
116
+ if (tool === 'Workflow') {
117
+ const id = safeId(record.taskId)
118
+ if (id === undefined || (record.status !== 'async_launched' && record.status !== 'remote_launched')) return undefined
119
+ return { id, kind: 'workflow', label: oneLine(str(record.workflowName) ?? str(record.summary) ?? 'workflow', LABEL_MAX) }
120
+ }
121
+ return undefined
122
+ }
123
+
124
+ const tag = (block: string, name: string): string | undefined => {
125
+ const match = new RegExp(`<${name}>([\\s\\S]*?)</${name}>`).exec(block)
126
+ return match ? unescape(match[1] ?? '').trim() : undefined
127
+ }
128
+
129
+ /** Every `<task-notification>` block in a row's text. */
130
+ export const parseNotices = (text: string): Notice[] => {
131
+ if (!text.includes('<task-notification>')) return []
132
+ const found: Notice[] = []
133
+ for (const match of text.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)) {
134
+ const block = match[1] ?? ''
135
+ const id = safeId(tag(block, 'task-id'))
136
+ if (id === undefined) continue
137
+ const notice: Notice = { id }
138
+ const toolUseId = tag(block, 'tool-use-id')
139
+ const status = tag(block, 'status')
140
+ const summary = tag(block, 'summary')
141
+ const event = tag(block, 'event')
142
+ const outputFile = safeOutputPath(tag(block, 'output-file'))
143
+ if (toolUseId) notice.toolUseId = toolUseId
144
+ if (status) notice.status = status.toLowerCase()
145
+ if (summary) notice.summary = summary
146
+ if (event) notice.event = event
147
+ if (outputFile) notice.outputFile = outputFile
148
+ const exitCode = exitCodeIn(`${summary ?? ''} ${event ?? ''}`)
149
+ if (exitCode !== undefined) notice.exitCode = exitCode
150
+ found.push(notice)
151
+ }
152
+ return found
153
+ }
154
+
155
+ /** A notification's word as one of ours: `stopped` reads as killed; an unknown word as completed. */
156
+ export const statusOf = (word: string | undefined, exitCode: number | undefined): RunningStatus | undefined => {
157
+ if (word === undefined) return undefined
158
+ if (word === 'failed' || word === 'error') return 'failed'
159
+ if (word === 'killed' || word === 'stopped' || word === 'cancelled') return 'killed'
160
+ return exitCode !== undefined && exitCode !== 0 ? 'failed' : 'completed'
161
+ }
162
+
163
+ /** The last non-empty line of an output tail, bounded and stripped of escapes. */
164
+ export const lastLineOf = (tail: string): string | undefined => {
165
+ const lines = tail.replace(/\r/g, '\n').split('\n')
166
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
167
+ const line = oneLine(lines[index] ?? '', LINE_MAX)
168
+ if (line !== '') return line
169
+ }
170
+ return undefined
171
+ }
172
+
173
+ // ---------------------------------------------------------------- list model
174
+
175
+ const end = (task: RunningTask, status: RunningStatus, now: number, extra: Partial<RunningTask> = {}): RunningTask => ({ ...task, ...extra, status, endedAt: now })
176
+
177
+ /** Adds or replaces a task by id, then prunes. */
178
+ export const addTask = (list: RunningTask[], task: RunningTask, now: number): RunningTask[] => prune([...list.filter(one => one.id !== task.id), task], now)
179
+
180
+ /** Applies one notification; `ended` lists the tasks it finished, for the toast. Unknown ids are ignored. */
181
+ export const applyNotice = (list: RunningTask[], notice: Notice, now: number): { list: RunningTask[]; ended: RunningTask[] } => {
182
+ const ended: RunningTask[] = []
183
+ const next = list.map(task => {
184
+ if (task.id !== notice.id && (notice.toolUseId === undefined || task.toolUseId !== notice.toolUseId)) return task
185
+ if (task.status !== 'running') return task
186
+ const lastLine = notice.event !== undefined ? lastLineOf(notice.event) : undefined
187
+ const extra: Partial<RunningTask> = {
188
+ ...(lastLine === undefined ? {} : { lastLine }),
189
+ ...(task.outputFile === undefined && notice.outputFile !== undefined && task.kind === 'bash' ? { outputFile: notice.outputFile } : {}),
190
+ }
191
+ const status = statusOf(notice.status, notice.exitCode)
192
+ if (status === undefined) return { ...task, ...extra }
193
+ const done = end(task, status, now, { ...extra, ...(notice.exitCode === undefined ? {} : { exitCode: notice.exitCode }) })
194
+ ended.push(done)
195
+ return done
196
+ })
197
+ return { list: next, ended }
198
+ }
199
+
200
+ /** Ends the main loop's shells and monitors the session no longer lists as in flight. */
201
+ export const reconcileInFlight = (list: RunningTask[], inFlight: string[], now: number): { list: RunningTask[]; ended: RunningTask[] } => {
202
+ const live = new Set(inFlight)
203
+ const ended: RunningTask[] = []
204
+ const next = list.map(task => {
205
+ const isCandidate = task.status === 'running' && task.agentId === undefined && (task.kind === 'bash' || task.kind === 'monitor')
206
+ if (!isCandidate || live.has(task.id) || now - task.startedAt < STOP_GRACE_MS) return task
207
+ const done = end(task, 'completed', now, { isInferred: true })
208
+ ended.push(done)
209
+ return done
210
+ })
211
+ return { list: next, ended }
212
+ }
213
+
214
+ /** Ends Monitors past their deadline, and background agents the session lists as ended. */
215
+ export const expireTasks = (list: RunningTask[], agentStatus: Record<string, string>, now: number): { list: RunningTask[]; ended: RunningTask[] } => {
216
+ const ended: RunningTask[] = []
217
+ const next = list.map(task => {
218
+ if (task.status !== 'running') return task
219
+ if (task.kind === 'monitor' && task.deadline !== undefined && now > task.deadline + MONITOR_GRACE_MS) {
220
+ const done = end(task, 'completed', now, { isInferred: true })
221
+ ended.push(done)
222
+ return done
223
+ }
224
+ const word = task.kind === 'agent' ? agentStatus[task.id] : undefined
225
+ if (word === 'completed' || word === 'failed' || word === 'killed') {
226
+ const done = end(task, word, now)
227
+ ended.push(done)
228
+ return done
229
+ }
230
+ return task
231
+ })
232
+ return { list: next, ended }
233
+ }
234
+
235
+ /** Drops finished tasks older than ten minutes, then keeps the newest fifty, running ones first. */
236
+ export const prune = (list: RunningTask[], now: number): RunningTask[] => {
237
+ const kept = list.filter(task => task.status === 'running' || now - (task.endedAt ?? now) <= LINGER_MS)
238
+ if (kept.length <= KEEP) return kept
239
+ const running = kept.filter(task => task.status === 'running').slice(-KEEP)
240
+ const finished = kept.filter(task => task.status !== 'running').slice(-(KEEP - running.length))
241
+ const keep = new Set([...running, ...finished])
242
+ return kept.filter(task => keep.has(task))
243
+ }
244
+
245
+ export const isRunning = (task: RunningTask): boolean => task.status === 'running'
246
+
247
+ // ---------------------------------------------------------------- drawing
248
+
249
+ /** `12 s`, `2m 05s`, `1h 03m`. */
250
+ export const elapsed = (ms: number): string => {
251
+ const total = Math.max(0, Math.floor(ms / 1000))
252
+ if (total < 60) return `${total} s`
253
+ const minutes = Math.floor(total / 60)
254
+ if (minutes < 60) return `${minutes}m ${String(total % 60).padStart(2, '0')}s`
255
+ return `${Math.floor(minutes / 60)}h ${String(minutes % 60).padStart(2, '0')}m`
256
+ }
257
+
258
+ const kindIcon = (kind: RunningKind): string =>
259
+ kind === 'bash' ? ICONS.command : kind === 'monitor' ? ICONS.gauge : kind === 'agent' ? ICONS.agent : ICONS.branch
260
+
261
+ const DONE_LOOK: Record<Exclude<RunningStatus, 'running'>, { icon: string; color: Tone }> = {
262
+ completed: { icon: '✓', color: 'success' },
263
+ failed: { icon: '✗', color: 'error' },
264
+ killed: { icon: '◼', color: 'subtle' },
265
+ }
266
+
267
+ /** PASS/FAIL once a task ended with a verdict to give; a killed or inferred end gives none. */
268
+ export const verdictOfTask = (task: RunningTask): 'PASS' | 'FAIL' | undefined => {
269
+ if (task.status === 'failed') return 'FAIL'
270
+ if (task.status === 'completed' && !task.isInferred) return task.exitCode === undefined || task.exitCode === 0 ? 'PASS' : 'FAIL'
271
+ return undefined
272
+ }
273
+
274
+ const visible = (part: RunningPart): RunningTask[] => {
275
+ const shown = part.tasks.filter(task => task.status === 'running' || part.now - (task.endedAt ?? part.now) <= LINGER_MS)
276
+ return [...shown.filter(isRunning), ...shown.filter(task => !isRunning(task)).reverse()].slice(0, KEEP)
277
+ }
278
+
279
+ export const rowsRunning = (part: RunningPart, ctx: { width: number; accent: string; isOpen: (key: string, byDefault: boolean) => boolean }): Row[] => {
280
+ const shown = visible(part)
281
+ if (shown.length === 0) return []
282
+ const width = Math.max(10, ctx.width)
283
+ const live = shown.filter(isRunning).length
284
+ const open = ctx.isOpen(SECTION_KEY, true)
285
+ const title = `${open ? '▼' : '▶'} ◷ En curso · ${live}`
286
+ const rows: Row[] = [{
287
+ key: SECTION_KEY,
288
+ cells: [{ spans: [span(fit(title, width), { bold: true, color: live > 0 ? ctx.accent : undefined })], action: { kind: 'toggle', key: SECTION_KEY }, label: 'En curso', key: `btn-${SECTION_KEY}` }],
289
+ }]
290
+ if (!open) return rows
291
+ for (const task of shown) {
292
+ const who = task.agentLabel !== undefined ? `${clean(task.agentLabel)} · ` : ''
293
+ const label = clean(task.label)
294
+ if (task.status === 'running') {
295
+ const right = elapsed(part.now - task.startedAt)
296
+ rows.push({
297
+ key: `running-${task.id}`,
298
+ cells: [{ spans: [span(` ${ICONS.running} `, { color: 'warning' }), span(`${kindIcon(task.kind)} ${fit(label, width - right.length - 8)}`)] }],
299
+ right: [span(right, { color: 'warning' })],
300
+ })
301
+ const detail = `${who}${clean(task.lastLine ?? '')}`
302
+ if (detail !== '') rows.push({ key: `running-${task.id}-line`, cells: [{ spans: [span(fit(` └ ${detail}`, width), { dim: true })] }] })
303
+ continue
304
+ }
305
+ const look = DONE_LOOK[task.status]
306
+ const verdict = verdictOfTask(task)
307
+ const took = elapsed((task.endedAt ?? part.now) - task.startedAt)
308
+ const rightText = verdict ? `${verdict} ${took}` : took
309
+ rows.push({
310
+ key: `running-${task.id}`,
311
+ cells: [{ spans: [span(` ${look.icon} `, { color: look.color }), span(`${kindIcon(task.kind)} ${fit(`${who}${label}`, width - rightText.length - 8)}`, { dim: true })] }],
312
+ right: verdict ? [span(verdict, { color: verdict === 'PASS' ? 'success' : 'error' }), span(` ${took}`, { dim: true })] : [span(took, { dim: true })],
313
+ })
314
+ }
315
+ return rows
316
+ }
317
+
318
+ /** `◷ 2 en curso` for the pane's title row; nothing when no work is running. */
319
+ export const headerRunning = (part: RunningPart): Span[] => {
320
+ const live = part.tasks.filter(isRunning).length
321
+ return live === 0 ? [] : [span(`◷ ${live} en curso`, { color: 'warning' })]
322
+ }
323
+
324
+ /** The toast a finished task raises. */
325
+ export const toastOf = (task: RunningTask): string => {
326
+ const took = elapsed((task.endedAt ?? task.startedAt) - task.startedAt)
327
+ const label = fit(clean(task.label), 60)
328
+ if (task.status === 'failed') return `✗ Falló: ${label}${task.exitCode !== undefined ? ` (código ${task.exitCode})` : ''} · ${took}`
329
+ if (task.status === 'killed') return `◼ Detenida: ${label} · ${took}`
330
+ return `✓ Terminó: ${label} · ${took}`
331
+ }
332
+
333
+ const KIND_NAME: Record<RunningKind, string> = { bash: 'Comando', monitor: 'Monitor', agent: 'Agente', workflow: 'Workflow' }
334
+
335
+ /** The one-line OS notification a finished task raises: what it was, how it ended, its verdict. */
336
+ export const notifyLineOf = (task: RunningTask): string => {
337
+ const took = elapsed((task.endedAt ?? task.startedAt) - task.startedAt)
338
+ const what = `${KIND_NAME[task.kind]} '${fit(clean(task.label), 60)}'`
339
+ if (task.status === 'killed') return `◼ ${what} se detuvo · ${took}`
340
+ const verdict = verdictOfTask(task)
341
+ const code = task.status === 'failed' && task.exitCode !== undefined ? ` (código ${task.exitCode})` : ''
342
+ const ok = verdict !== 'FAIL'
343
+ return `${ok ? '✓' : '✗'} ${what} ${ok ? 'terminó' : 'falló'}${code}${verdict ? ` · ${verdict}` : ''} · ${took}`
344
+ }
345
+
346
+ // ---------------------------------------------------------------- engine
347
+
348
+ export async function readRunning($: Api): Promise<RunningPart> {
349
+ const [tasks, now] = await Promise.all([read($, tasksAtom), $.clock.now(), read($, tickAtom)])
350
+ return { tasks, now }
351
+ }
352
+
353
+ function announce($: Api, ended: RunningTask[]): void {
354
+ for (const task of ended) {
355
+ if (task.isInferred) continue
356
+ try {
357
+ $.ui.toast(toastOf(task), { timeoutMs: 6000 })
358
+ } catch {
359
+ // A refused toast loses only the toast.
360
+ }
361
+ void notify($, { key: `task:${task.id}`, text: notifyLineOf(task) }).catch(() => undefined)
362
+ }
363
+ }
364
+
365
+ /** Reads the last output line of a running shell from its engine-reported file, at most 64 KB of its tail. */
366
+ async function tailLine($: Api, path: string): Promise<string | undefined> {
367
+ const stat = await $.fs.stat(path)
368
+ if (stat.kind !== 'file') return undefined
369
+ if (tailMtime.get(path) === stat.mtimeMs) return undefined
370
+ tailMtime.set(path, stat.mtimeMs)
371
+ if (stat.size === 0) return undefined
372
+ if (stat.size <= TAIL_BYTES) return lastLineOf(await $.fs.read(path))
373
+ const out = await $.process.run(['/usr/bin/tail', '-c', String(TAIL_BYTES), path], { timeoutMs: 2000 })
374
+ return out.exitCode === 0 ? lastLineOf(out.stdout.slice(-TAIL_BYTES)) : undefined
375
+ }
376
+
377
+ async function tick($: Api): Promise<void> {
378
+ if (ticking) return
379
+ ticking = true
380
+ try {
381
+ const before = await read($, tasksAtom)
382
+ const running = before.filter(isRunning)
383
+ if (running.length === 0) {
384
+ ticker?.cancel()
385
+ ticker = undefined
386
+ return
387
+ }
388
+ const lines: Record<string, string> = {}
389
+ for (const task of running.filter(one => one.kind === 'bash' && one.outputFile !== undefined).slice(0, TAILS_PER_TICK)) {
390
+ const line = await tailLine($, task.outputFile as string).catch(() => undefined)
391
+ if (line !== undefined) lines[task.id] = line
392
+ }
393
+ const agentStatus: Record<string, string> = {}
394
+ if (running.some(one => one.kind === 'agent')) for (const info of await $.agent.list().catch(() => [])) agentStatus[info.id] = info.status
395
+ const now = await $.clock.now()
396
+ let ended: RunningTask[] = []
397
+ await update($, tasksAtom, list => {
398
+ const withLines = list.map(task => (task.status === 'running' && lines[task.id] !== undefined ? { ...task, lastLine: lines[task.id] } : task))
399
+ const expired = expireTasks(withLines, agentStatus, now)
400
+ ended = expired.ended
401
+ return prune(expired.list, now)
402
+ })
403
+ await update($, tickAtom, () => now)
404
+ announce($, ended)
405
+ } finally {
406
+ ticking = false
407
+ }
408
+ }
409
+
410
+ function ensureTicker($: Api): void {
411
+ if (ticker !== undefined) return
412
+ ticker = $.clock.every(TICK_MS, () => {
413
+ void tick($).catch(() => undefined)
414
+ })
415
+ }
416
+
417
+ async function agentLabelOf($: Api, agentId: string | undefined): Promise<string | undefined> {
418
+ if (agentId === undefined) return undefined
419
+ const info = (await $.agent.list().catch(() => [])).find(one => one.id === agentId)
420
+ return info ? oneLine(shortName({ description: info.description, ...(info.name ? { name: info.name } : {}) }), 16) : 'agente'
421
+ }
422
+
423
+ const textOfBlocks = (content: unknown): string => {
424
+ if (typeof content === 'string') return content
425
+ if (!Array.isArray(content)) return ''
426
+ return content.map(block => (block && typeof block === 'object' && typeof (block as { text?: unknown }).text === 'string' ? (block as { text: string }).text : '')).join('\n')
427
+ }
428
+
429
+ async function onNotices($: Api, notices: Notice[]): Promise<void> {
430
+ const now = await $.clock.now()
431
+ let ended: RunningTask[] = []
432
+ await update($, tasksAtom, list => {
433
+ let next = list
434
+ for (const notice of notices) {
435
+ const applied = applyNotice(next, notice, now)
436
+ next = applied.list
437
+ ended = [...ended, ...applied.ended]
438
+ }
439
+ return ended.length === 0 && next === list ? list : prune(next, now)
440
+ })
441
+ announce($, ended)
442
+ }
443
+
444
+ export const registerRunning = (on: On): void => {
445
+
446
+
447
+ on('session.append', async ($, e, next) => {
448
+ try {
449
+ if (NOTICE_DOORS.has(e.door) && e.message.type !== 'assistant') {
450
+ const notices = parseNotices(textOfBlocks(e.message.content))
451
+ if (notices.length > 0) await onNotices($ as Api, notices)
452
+ }
453
+ } catch {
454
+ // A notice the pane missed leaves the row running until the next reconcile.
455
+ }
456
+ return next(e)
457
+ })
458
+
459
+ on('classic.Stop', async ($, e, next) => {
460
+ try {
461
+ const inFlight = e.background_tasks
462
+ if (Array.isArray(inFlight)) {
463
+ const now = await $.clock.now()
464
+ let ended: RunningTask[] = []
465
+ await update($, tasksAtom, list => {
466
+ const reconciled = reconcileInFlight(list, inFlight.map(one => one.id), now)
467
+ ended = reconciled.ended
468
+ return reconciled.ended.length === 0 ? list : prune(reconciled.list, now)
469
+ })
470
+ announce($ as Api, ended)
471
+ }
472
+ } catch {
473
+ // The notification or the next Stop settles it.
474
+ }
475
+ return next(e)
476
+ })
477
+ }
478
+
479
+ export async function runningSessionStart($: Api, e: Parameters<Hook<'session.start'>>[1], next: Parameters<Hook<'session.start'>>[2]): Promise<Awaited<ReturnType<Hook<'session.start'>>>> {
480
+ try {
481
+ if ((await read($, tasksAtom)).some(isRunning)) ensureTicker($ as Api)
482
+ } catch {
483
+ // The timer starts again with the next launch.
484
+ }
485
+ return next(e)
486
+ }
487
+
488
+ export async function runningToolCall($: Api, e: Parameters<Hook<'tool.call'>>[1], next: Parameters<Hook<'tool.call'>>[2]): Promise<Awaited<ReturnType<Hook<'tool.call'>>>> {
489
+ const ran = await next(e)
490
+ try {
491
+ if (e.tool === 'TaskStop' && ran.deny === undefined && ran.isError !== true) {
492
+ const stopped = safeId((ran.result as { task_id?: unknown } | undefined)?.task_id)
493
+ if (stopped !== undefined) {
494
+ const now = await $.clock.now()
495
+ let ended: RunningTask[] = []
496
+ await update($, tasksAtom, list =>
497
+ list.map(task => {
498
+ if (task.id !== stopped || task.status !== 'running') return task
499
+ const done = end(task, 'killed', now)
500
+ ended = [done]
501
+ return done
502
+ }),
503
+ )
504
+ announce($ as Api, ended)
505
+ }
506
+ return ran
507
+ }
508
+ if (ran.deny !== undefined || ran.isError === true) return ran
509
+ if (e.tool !== 'Bash' && e.tool !== 'Monitor' && e.tool !== 'Agent' && e.tool !== 'Workflow') return ran
510
+ const startedAt = await $.clock.now()
511
+ const launch = launchOf(e.tool, e as unknown as Record<string, unknown>, ran.result, ran.text, startedAt)
512
+ if (launch === undefined) return ran
513
+ const agentLabel = await agentLabelOf($ as Api, e.agentId)
514
+ const task: RunningTask = {
515
+ ...launch,
516
+ status: 'running',
517
+ startedAt,
518
+ toolUseId: e.tool_use_id,
519
+ ...(e.agentId === undefined ? {} : { agentId: e.agentId }),
520
+ ...(agentLabel === undefined ? {} : { agentLabel }),
521
+ }
522
+ await update($, tasksAtom, list => addTask(list, task, startedAt))
523
+ ensureTicker($ as Api)
524
+ } catch {
525
+ // Tracking is best effort; the call's result stands.
526
+ }
527
+ return ran
528
+ }