@xiangyixie/dsh-superagent 0.10.0 → 0.12.0

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.
package/lib/watch.js CHANGED
@@ -1,458 +1,810 @@
1
- /**
2
- * Live terminal panel for dsh-superagent.
3
- *
4
- * The panel is a pure renderer plus a poll loop: it reads the same durable run
5
- * files the host writes and draws one line per run, so it works from another
6
- * process, survives a host restart, and never needs IPC.
7
- *
8
- * There is no dependency here on purpose — the package is a zero-dependency
9
- * plugin, and a monitoring aid is not a reason to pull in an ANSI toolkit. The
10
- * escape sequences used are the small, stable subset: alternate screen, hide
11
- * cursor, cursor home, erase line, and SGR colours.
12
- *
13
- * @module dsh-superagent/watch
14
- */
15
- import { ACTIVE_STATUSES, createStore, resolveStateRoot } from './store.js'
16
-
17
- /** Refresh cadence. A run file is small, so one read per second is cheap. */
18
- export const DEFAULT_INTERVAL_MS = 1000
19
-
20
- const COLUMNS = {
21
- id: 20,
22
- status: 12,
23
- calls: 8,
24
- elapsed: 7,
25
- parent: 9,
26
- }
27
-
28
- const STATUS_COLOR = {
29
- queued: 2,
30
- planning: 6,
31
- running: 6,
32
- aggregating: 6,
33
- completed: 2,
34
- partial: 3,
35
- failed: 1,
36
- cancelled: 5,
37
- interrupted: 3,
38
- }
39
-
40
- const STATUS_LABEL = {
41
- queued: 'queued',
42
- planning: 'planning',
43
- running: 'running',
44
- aggregating: 'aggregating',
45
- completed: 'completed',
46
- partial: 'partial',
47
- failed: 'failed',
48
- cancelled: 'cancelled',
49
- interrupted: 'interrupted',
50
- }
51
-
52
- const ANSI = {
53
- reset: '\u001b[0m',
54
- dim: '\u001b[2m',
55
- bold: '\u001b[1m',
56
- hide: '\u001b[?25l',
57
- show: '\u001b[?25h',
58
- altOn: '\u001b[?1049h',
59
- altOff: '\u001b[?1049l',
60
- home: '\u001b[H',
61
- clearLine: '\u001b[K',
62
- clearScreen: '\u001b[2J',
63
- }
64
-
65
- /**
66
- * Paint text only when colour is on, so a piped frame stays parseable.
67
- * @param {string | number} code - SGR code.
68
- * @param {string} text - content.
69
- * @param {boolean} color - whether ANSI is allowed.
70
- */
71
- function paint(code, text, color) {
72
- return color ? `\u001b[${code}m${text}\u001b[0m` : text
73
- }
74
-
75
- /**
76
- * Shorten to `width` cells, appending an ellipsis when it does not fit.
77
- * @param {string} text - input.
78
- * @param {number} width - maximum cells.
79
- */
80
- export function clip(text, width) {
81
- const value = String(text ?? '').replace(/\s+/g, ' ').trim()
82
- if (width <= 0) return ''
83
- if (value.length <= width) return value
84
- if (width === 1) return '…'
85
- return `${value.slice(0, width - 1)}…`
86
- }
87
-
88
- /**
89
- * Pad to a fixed cell count, clipping first so a long value cannot push the
90
- * following columns out of alignment.
91
- * @param {string} text - value.
92
- * @param {number} width - target cells.
93
- */
94
- export function pad(text, width) {
95
- const value = clip(text, width)
96
- return value + ' '.repeat(Math.max(0, width - value.length))
97
- }
98
-
99
- /** `950ms`, `12s`, `3m04s`, `1h02m`. */
100
- export function formatDuration(ms) {
101
- const value = Number(ms)
102
- if (!Number.isFinite(value) || value < 0) return '-'
103
- if (value < 1000) return `${Math.round(value)}ms`
104
- const seconds = Math.round(value / 1000)
105
- if (seconds < 60) return `${seconds}s`
106
- const minutes = Math.floor(seconds / 60)
107
- const rest = seconds % 60
108
- if (minutes < 60) return `${minutes}m${String(rest).padStart(2, '0')}s`
109
- return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}m`
110
- }
111
-
112
- /** `5.4k`, `1.2M`, `840`. */
113
- export function formatCount(value) {
114
- const number = Number(value) || 0
115
- if (number < 1000) return String(number)
116
- if (number < 1_000_000) return `${(number / 1000).toFixed(1).replace(/\.0$/, '')}k`
117
- return `${(number / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
118
- }
119
-
120
- /** First non-empty line of an error, for a one-row outcome. */
121
- function firstLine(text) {
122
- const value = String(text ?? '').trim()
123
- if (!value) return ''
124
- return value.split(/\r?\n/, 1)[0]
125
- }
126
-
127
- /** Parent session label: the uuid tail is what the user recognises. */
128
- export function parentLabel(run) {
129
- const id = String(run?.parentSessionId ?? '').trim()
130
- if (!id) return '-'
131
- const tail = id.replace(/^session-/, '')
132
- return tail.slice(0, 8)
133
- }
134
-
135
- /** Calls spent, matching the orchestrator's `spentCalls` (measured beats counted). */
136
- export function callsOf(run) {
137
- return Math.max(run?.usage?.modelCalls ?? 0, run?.counters?.spawns ?? 0)
138
- }
139
-
140
- /** Elapsed wall-clock; a live run counts to `now`, a finished one stops at `finishedAt`. */
141
- export function elapsedOf(run, now) {
142
- const start = Date.parse(run?.startedAt ?? run?.createdAt ?? '')
143
- if (!Number.isFinite(start)) return null
144
- const end = ACTIVE_STATUSES.has(run?.status)
145
- ? now
146
- : Date.parse(run?.finishedAt ?? '') || now
147
- return Math.max(0, end - start)
148
- }
149
-
150
- /**
151
- * What the run is doing right now, or how it ended. One short phrase, because
152
- * the panel's job is to answer "is it stuck?" at a glance.
153
- * @param {object} run - run record.
154
- */
155
- export function activityOf(run) {
156
- const subtasks = Array.isArray(run?.subtasks) ? run.subtasks : []
157
- const completed = subtasks.filter(subtask => subtask.status === 'completed').length
158
- const running = subtasks.filter(subtask => subtask.status === 'running')
159
- switch (run?.status) {
160
- case 'queued':
161
- return 'waiting for an active-run slot'
162
- case 'planning':
163
- return 'planner is decomposing the goal'
164
- case 'running':
165
- if (running.length > 0) {
166
- return `${running.length} running · ${running[0].title ?? 'subtask'}`
167
- }
168
- if (subtasks.length > 0) return `${completed}/${subtasks.length} subtasks done`
169
- return 'starting the first subtask'
170
- case 'aggregating':
171
- return `merging ${completed || subtasks.length} report(s)`
172
- case 'completed':
173
- return `report ready · ${completed}/${subtasks.length} subtasks`
174
- case 'partial':
175
- return `partial report · ${completed}/${subtasks.length} subtasks`
176
- case 'failed':
177
- return firstLine(run.error) || 'failed without a recorded error'
178
- case 'cancelled':
179
- return 'cancelled by request'
180
- case 'interrupted':
181
- return 'host went away · resume to continue'
182
- default:
183
- return STATUS_LABEL[run?.status] ?? String(run?.status ?? 'unknown')
184
- }
185
- }
186
-
187
- /**
188
- * Order for display: live work first (oldest first, so rows do not reorder
189
- * while you watch them), then finished runs newest-first.
190
- * @param {object[]} runs - run records.
191
- */
192
- export function orderRuns(runs) {
193
- const list = [...(runs ?? [])]
194
- const active = list.filter(run => ACTIVE_STATUSES.has(run.status))
195
- const done = list.filter(run => !ACTIVE_STATUSES.has(run.status))
196
- active.sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)))
197
- done.sort((a, b) => String(b.finishedAt ?? b.createdAt).localeCompare(String(a.finishedAt ?? a.createdAt)))
198
- return [...active, ...done]
199
- }
200
-
201
- /** Totals for the footer: calls, tokens, priced cost, and whether any price is missing. */
202
- export function totalsOf(runs) {
203
- let calls = 0
204
- let tokens = 0
205
- let cost = 0
206
- let unpriced = false
207
- let active = 0
208
- let failed = 0
209
- for (const run of runs ?? []) {
210
- calls += callsOf(run)
211
- tokens += run?.usage?.totalTokens ?? 0
212
- if (run?.cost) {
213
- cost += run.cost.total ?? 0
214
- if (run.cost.complete === false) unpriced = true
215
- } else if ((run?.usage?.modelCalls ?? 0) > 0) {
216
- unpriced = true
217
- }
218
- if (ACTIVE_STATUSES.has(run?.status)) active += 1
219
- if (run?.status === 'failed') failed += 1
220
- }
221
- return { calls, tokens, cost, unpriced, active, failed, total: (runs ?? []).length }
222
- }
223
-
224
- /** Header + column names, reused by every frame so the layout never shifts. */
225
- function headerRow(color) {
226
- const cells = [
227
- pad('RUN ID', COLUMNS.id),
228
- pad('STATUS', COLUMNS.status),
229
- pad('CALLS', COLUMNS.calls),
230
- pad('ELAPSED', COLUMNS.elapsed),
231
- pad('ACTIVITY', 32),
232
- 'PARENT',
233
- ]
234
- return paint('2', ` ${cells.join(' ')}`, color)
235
- }
236
-
237
- function rule(width, color) {
238
- return paint('2', ` ${'─'.repeat(Math.max(0, width - 2))}`, color)
239
- }
240
-
241
- /**
242
- * Render one complete frame, with no trailing newline.
243
- *
244
- * Kept pure so the layout can be asserted in tests without a terminal.
245
- *
246
- * @param {object[]} runs - run records.
247
- * @param {{ now?: number, width?: number, color?: boolean, stateRoot?: string, intervalMs?: number, columns?: number }} [options]
248
- * @returns {string} frame text, ANSI-painted only when `color` is true.
249
- */
250
- export function renderFrame(runs, options = {}) {
251
- const now = options.now ?? Date.now()
252
- const width = Math.max(60, options.width ?? 100)
253
- const color = options.color === true
254
- const interval = options.intervalMs ?? DEFAULT_INTERVAL_MS
255
- const list = orderRuns(runs)
256
- const totals = totalsOf(list)
257
- const activityWidth = Math.max(
258
- 20,
259
- width - (COLUMNS.id + COLUMNS.status + COLUMNS.calls + COLUMNS.elapsed + COLUMNS.parent + 6),
260
- )
261
-
262
- const clock = new Date(now).toISOString().slice(11, 19)
263
- const headline = [
264
- paint('1', 'dsh-superagent', color),
265
- paint('2', '·', color),
266
- `${totals.total} run${totals.total === 1 ? '' : 's'}`,
267
- totals.active > 0 ? paint('6', `${totals.active} active`, color) : paint('2', 'idle', color),
268
- paint('2', `· ${clock}Z`, color),
269
- ].join(' ')
270
-
271
- const lines = [headline, rule(width, color)]
272
- if (list.length === 0) {
273
- lines.push('')
274
- lines.push(paint('2', ' no runs recorded yet', color))
275
- lines.push(paint('2', ` state: ${options.stateRoot ?? '-'}`, color))
276
- lines.push('')
277
- lines.push(paint('2', ' start one with the superagent_start tool; this panel updates itself.', color))
278
- } else {
279
- lines.push(headerRow(color))
280
- for (const run of list) {
281
- const elapsed = elapsedOf(run, now)
282
- const calls = callsOf(run)
283
- const cap = run?.limits?.maxModelCalls ?? 0
284
- const callsText = cap > 0 ? `${calls}/${cap}` : String(calls)
285
- const status = STATUS_LABEL[run.status] ?? String(run.status ?? '?')
286
- const activity = activityOf(run)
287
- const row = [
288
- ` ${paint('1', pad(run.id, COLUMNS.id), color)}`,
289
- ` ${paint(String(STATUS_COLOR[run.status] ?? 0), pad(status, COLUMNS.status), color)}`,
290
- ` ${pad(callsText, COLUMNS.calls)}`,
291
- ` ${pad(elapsed === null ? '-' : formatDuration(elapsed), COLUMNS.elapsed)}`,
292
- ` ${pad(activity, activityWidth)}`,
293
- ` ${paint('2', pad(parentLabel(run), COLUMNS.parent), color)}`,
294
- ].join('')
295
- lines.push(row.replace(/\s+$/, ''))
296
- }
297
- }
298
-
299
- const money = totals.unpriced ? `$${totals.cost.toFixed(4)}+` : `$${totals.cost.toFixed(4)}`
300
- const summary = [
301
- paint('2', 'calls', color),
302
- `${totals.calls}`,
303
- paint('2', 'tokens', color),
304
- formatCount(totals.tokens),
305
- paint('2', 'cost', color),
306
- money,
307
- totals.failed > 0 ? paint('1', `${totals.failed} failed`, color) : null,
308
- ].filter(Boolean).join(' ')
309
-
310
- const footer = [
311
- paint('2', `${summary} · refreshing every ${interval >= 1000 ? `${interval / 1000}s` : `${interval}ms`} · Ctrl-C to quit`, color),
312
- ].join('')
313
-
314
- lines.push(rule(width, color))
315
- lines.push(footer)
316
- return lines.join('\n')
317
- }
318
-
319
- /** Status + progress fingerprint; a change here is worth an immediate repaint. */
320
- export function signatureOf(runs) {
321
- return orderRuns(runs)
322
- .map(run => [
323
- run.id,
324
- run.status,
325
- callsOf(run),
326
- (run.subtasks ?? []).filter(subtask => subtask.status === 'running').length,
327
- (run.subtasks ?? []).filter(subtask => subtask.status === 'completed').length,
328
- ].join(':'))
329
- .join('|')
330
- }
331
-
332
- /**
333
- * Run the panel until interrupted.
334
- *
335
- * When stdout is a terminal the frame is drawn in the alternate screen and the
336
- * cursor is hidden; both are restored on every exit path, including SIGINT,
337
- * SIGTERM, an uncaught exception, and `EPIPE` from a closed pipe. `once`
338
- * deliberately skips the alternate screen so its frame stays readable after
339
- * the process exits. When output is a pipe, each change is appended as a plain
340
- * frame instead, which keeps `watch --once | ...` and log capture useful.
341
- *
342
- * @param {{ stateDir?: string, intervalMs?: number, once?: boolean, out?: NodeJS.WriteStream | { write: Function, isTTY?: boolean, columns?: number }, now?: () => number }} [options]
343
- * @returns {Promise<void>} resolves after cleanup.
344
- */
345
- export async function watch(options = {}) {
346
- const out = options.out ?? process.stdout
347
- const intervalMs = Math.max(200, Number(options.intervalMs) || DEFAULT_INTERVAL_MS)
348
- const once = options.once === true
349
- const tty = out.isTTY === true
350
- // `--once` prints one frame for a pipe or a log. Entering the alternate
351
- // screen for that would draw it and then erase it on exit, so a person who
352
- // runs it in a terminal would see nothing at all.
353
- const altScreen = tty && !once
354
- const color = options.color ?? tty
355
- const now = options.now ?? Date.now
356
- const store = createStore(resolveStateRoot(options.stateDir))
357
- await store.init()
358
-
359
- let stopped = false
360
- let cleaned = false
361
- let timer = null
362
- let wake = null
363
- let lastFrame = ''
364
- let lastSignature = null
365
-
366
- const draw = runs => {
367
- const frame = renderFrame(runs, {
368
- now: now(),
369
- width: out.columns || 100,
370
- color,
371
- stateRoot: store.root,
372
- intervalMs,
373
- })
374
- if (altScreen) {
375
- // Home + per-line erase avoids a full-screen flash and keeps the panel
376
- // from leaving ghost rows when a run disappears.
377
- out.write(`${ANSI.home}${frame.split('\n').map(line => `${line}${ANSI.clearLine}`).join('\n')}\n${ANSI.clearLine}`)
378
- } else if (frame !== lastFrame) {
379
- out.write(`${frame}\n`)
380
- lastFrame = frame
381
- }
382
- }
383
-
384
- const cleanup = () => {
385
- if (cleaned) return
386
- cleaned = true
387
- stopped = true
388
- if (timer) clearTimeout(timer)
389
- timer = null
390
- wake = null
391
- process.removeListener('SIGINT', onSignal)
392
- process.removeListener('SIGTERM', onSignal)
393
- if (altScreen) out.write(`${ANSI.show}${ANSI.altOff}`)
394
- }
395
-
396
- /**
397
- * Ctrl-C ends the panel. The loop is woken rather than the process killed so
398
- * the `finally` below restores the terminal *before* Node exits; calling
399
- * `process.exit` here could drop the pending un-hide/un-alt-screen write.
400
- */
401
- const onSignal = () => {
402
- if (stopped) return
403
- stopped = true
404
- if (timer) clearTimeout(timer)
405
- timer = null
406
- if (wake) wake()
407
- }
408
-
409
- process.on('SIGINT', onSignal)
410
- process.on('SIGTERM', onSignal)
411
- if (out.on) out.on('error', error => {
412
- if (error?.code === 'EPIPE') {
413
- cleanup()
414
- process.exit(0)
415
- }
416
- throw error
417
- })
418
-
419
- if (altScreen) out.write(`${ANSI.altOn}${ANSI.hide}`)
420
-
421
- try {
422
- while (!stopped) {
423
- let runs
424
- try {
425
- runs = await store.list()
426
- } catch (error) {
427
- const problem = [
428
- 'dsh-superagent watch',
429
- '',
430
- `cannot read ${store.root}`,
431
- error?.message ?? String(error),
432
- ].join('\n')
433
- if (altScreen) out.write(`${ANSI.home}${problem.split('\n').map(line => `${line}${ANSI.clearLine}`).join('\n')}`)
434
- else out.write(`${problem}\n`)
435
- if (once) return
436
- await new Promise(resolve => {
437
- wake = resolve
438
- timer = setTimeout(resolve, intervalMs)
439
- })
440
- continue
441
- }
442
- draw(runs)
443
- if (once) return
444
- // A status transition (planning -> running -> aggregating) can happen
445
- // inside one interval. Re-read at once when the fingerprint moved, then
446
- // settle back to the normal cadence so an idle panel costs one read/s.
447
- const signature = signatureOf(runs)
448
- const moved = signature !== lastSignature
449
- lastSignature = signature
450
- await new Promise(resolve => {
451
- wake = resolve
452
- timer = setTimeout(resolve, moved ? Math.min(200, intervalMs) : intervalMs)
453
- })
454
- }
455
- } finally {
456
- cleanup()
457
- }
458
- }
1
+ /**
2
+ * Live terminal panel for dsh-superagent.
3
+ *
4
+ * The panel is a pure renderer plus a poll loop: it reads the same durable run
5
+ * files the host writes and draws one line per run, so it works from another
6
+ * process, survives a host restart, and never needs IPC.
7
+ *
8
+ * Two questions matter more than the raw numbers: who is running beside whom,
9
+ * and who is waiting on what. Overlapping runs therefore share a coloured
10
+ * gutter label, and a waiting row leads with its cause (a full slot, a full
11
+ * worker pool, or a retry backoff) before the ordinary activity phrase.
12
+ *
13
+ * There is no dependency here on purpose — the package is a zero-dependency
14
+ * plugin, and a monitoring aid is not a reason to pull in an ANSI toolkit. The
15
+ * escape sequences used are the small, stable subset: alternate screen, hide
16
+ * cursor, cursor home, erase line, and SGR colours.
17
+ *
18
+ * @module dsh-superagent/watch
19
+ */
20
+ import { formatMoney } from './cost.js'
21
+ import { ACTIVE_STATUSES, createStore, resolveStateRoot } from './store.js'
22
+
23
+ /** Refresh cadence. A run file is small, so one read per second is cheap. */
24
+ export const DEFAULT_INTERVAL_MS = 1000
25
+
26
+ /** Width of the concurrency gutter, including its trailing space. */
27
+ const GUTTER = 3
28
+
29
+ /** Gutter colours, one per overlapping group, cycled when there are many. */
30
+ const GROUP_COLORS = [6, 3, 5, 2, 4]
31
+
32
+ const STATUS_COLOR = {
33
+ queued: 2,
34
+ planning: 6,
35
+ running: 6,
36
+ aggregating: 6,
37
+ completed: 2,
38
+ partial: 3,
39
+ failed: 1,
40
+ cancelled: 5,
41
+ interrupted: 3,
42
+ }
43
+
44
+ const STATUS_LABEL = {
45
+ queued: 'queued',
46
+ planning: 'planning',
47
+ running: 'running',
48
+ aggregating: 'aggregating',
49
+ completed: 'completed',
50
+ partial: 'partial',
51
+ failed: 'failed',
52
+ cancelled: 'cancelled',
53
+ interrupted: 'interrupted',
54
+ }
55
+
56
+ /** Medium-width labels, all within ten cells. */
57
+ const STATUS_MEDIUM = {
58
+ queued: 'queued',
59
+ planning: 'plan',
60
+ running: 'running',
61
+ aggregating: 'aggreg.',
62
+ completed: 'done',
63
+ partial: 'partial',
64
+ failed: 'failed',
65
+ cancelled: 'cancel',
66
+ interrupted: 'interrupt',
67
+ }
68
+
69
+ /** Compact and narrow labels: the word is kept, vowels are not. */
70
+ const STATUS_SHORT = {
71
+ queued: 'que',
72
+ planning: 'plan',
73
+ running: 'run',
74
+ aggregating: 'agg',
75
+ completed: 'done',
76
+ partial: 'part',
77
+ failed: 'FAIL',
78
+ cancelled: 'cncl',
79
+ interrupted: 'intr',
80
+ }
81
+
82
+ const ANSI = {
83
+ reset: '\u001b[0m',
84
+ dim: '\u001b[2m',
85
+ bold: '\u001b[1m',
86
+ hide: '\u001b[?25l',
87
+ show: '\u001b[?25h',
88
+ altOn: '\u001b[?1049h',
89
+ altOff: '\u001b[?1049l',
90
+ home: '\u001b[H',
91
+ clearLine: '\u001b[K',
92
+ clearScreen: '\u001b[2J',
93
+ }
94
+
95
+ /**
96
+ * Paint text only when colour is on, so a piped frame stays parseable.
97
+ * @param {string | number} code - SGR code.
98
+ * @param {string} text - content.
99
+ * @param {boolean} color - whether ANSI is allowed.
100
+ */
101
+ function paint(code, text, color) {
102
+ return color ? `\u001b[${code}m${text}\u001b[0m` : text
103
+ }
104
+
105
+ /** Cell count of a string that may already carry SGR escapes. */
106
+ function visibleLength(text) {
107
+ return String(text ?? '').replace(/\u001b\[[0-9;?]*[a-zA-Z]/g, '').length
108
+ }
109
+
110
+ /**
111
+ * Shorten to `width` cells, appending an ellipsis when it does not fit.
112
+ * @param {string} text - input.
113
+ * @param {number} width - maximum cells.
114
+ */
115
+ export function clip(text, width) {
116
+ const value = String(text ?? '').replace(/\s+/g, ' ').trim()
117
+ if (width <= 0) return ''
118
+ if (value.length <= width) return value
119
+ if (width === 1) return '…'
120
+ return `${value.slice(0, width - 1)}…`
121
+ }
122
+
123
+ /**
124
+ * Pad to a fixed cell count, clipping first so a long value cannot push the
125
+ * following columns out of alignment.
126
+ * @param {string} text - value.
127
+ * @param {number} width - target cells.
128
+ */
129
+ export function pad(text, width) {
130
+ const value = clip(text, width)
131
+ return value + ' '.repeat(Math.max(0, width - value.length))
132
+ }
133
+
134
+ /** `950ms`, `12s`, `3m04s`, `1h02m`. */
135
+ export function formatDuration(ms) {
136
+ const value = Number(ms)
137
+ if (!Number.isFinite(value) || value < 0) return '-'
138
+ if (value < 1000) return `${Math.round(value)}ms`
139
+ const seconds = Math.round(value / 1000)
140
+ if (seconds < 60) return `${seconds}s`
141
+ const minutes = Math.floor(seconds / 60)
142
+ const rest = seconds % 60
143
+ if (minutes < 60) return `${minutes}m${String(rest).padStart(2, '0')}s`
144
+ return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}m`
145
+ }
146
+
147
+ /** `5.4k`, `1.2M`, `840`. */
148
+ export function formatCount(value) {
149
+ const number = Number(value) || 0
150
+ if (number < 1000) return String(number)
151
+ if (number < 1_000_000) return `${(number / 1000).toFixed(1).replace(/\.0$/, '')}k`
152
+ return `${(number / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
153
+ }
154
+
155
+ /** First non-empty line of an error, for a one-row outcome. */
156
+ function firstLine(text) {
157
+ const value = String(text ?? '').trim()
158
+ if (!value) return ''
159
+ return value.split(/\r?\n/, 1)[0]
160
+ }
161
+
162
+ /** Last dash-separated segment of a run id: the part that fits a narrow cell. */
163
+ function runTail(run) {
164
+ const parts = String(run?.id ?? '').split('-')
165
+ return parts[parts.length - 1] || String(run?.id ?? '')
166
+ }
167
+
168
+ /** Parent session label: the uuid tail is what the user recognises. */
169
+ export function parentLabel(run) {
170
+ const id = String(run?.parentSessionId ?? '').trim()
171
+ if (!id) return '-'
172
+ const tail = id.replace(/^session-/, '')
173
+ return tail.slice(0, 8)
174
+ }
175
+
176
+ /** Calls spent, matching the orchestrator's `spentCalls` (measured beats counted). */
177
+ export function callsOf(run) {
178
+ return Math.max(run?.usage?.modelCalls ?? 0, run?.counters?.spawns ?? 0)
179
+ }
180
+
181
+ /** Elapsed wall-clock; a live run counts to `now`, a finished one stops at `finishedAt`. */
182
+ export function elapsedOf(run, now) {
183
+ const start = Date.parse(run?.startedAt ?? run?.createdAt ?? '')
184
+ if (!Number.isFinite(start)) return null
185
+ const end = ACTIVE_STATUSES.has(run?.status)
186
+ ? now
187
+ : Date.parse(run?.finishedAt ?? '') || now
188
+ return Math.max(0, end - start)
189
+ }
190
+
191
+ /** Half-open lifetime of a run, used for overlap detection. */
192
+ function spanOf(run, now) {
193
+ const start = Date.parse(run?.createdAt ?? run?.startedAt ?? '')
194
+ if (!Number.isFinite(start)) return null
195
+ const end = ACTIVE_STATUSES.has(run?.status)
196
+ ? now
197
+ : Date.parse(run?.finishedAt ?? '') || now
198
+ return { start, end: Math.max(start, end) }
199
+ }
200
+
201
+ /**
202
+ * Cluster runs into connected groups of overlapping lifetimes.
203
+ *
204
+ * Two runs that were alive at the same moment end up in the same group, and
205
+ * overlap is transitive: if A overlaps B and B overlaps C, one group covers
206
+ * all three. A run that never overlapped anything is its own group and is left
207
+ * out of the gutter, so the panel only spends visual noise on real parallelism.
208
+ *
209
+ * @param {object[]} runs - run records.
210
+ * @param {number} [now] - wall clock for live runs.
211
+ * @returns {object[][]} groups, each sorted by start time.
212
+ */
213
+ export function overlapGroups(runs, now = Date.now()) {
214
+ const entries = []
215
+ for (const run of runs ?? []) {
216
+ const span = spanOf(run, now)
217
+ if (span) entries.push({ run, span })
218
+ }
219
+ entries.sort((a, b) => a.span.start - b.span.start || String(a.run.id).localeCompare(String(b.run.id)))
220
+ const groups = []
221
+ let open = null
222
+ for (const entry of entries) {
223
+ if (open && entry.span.start < open.end) {
224
+ open.items.push(entry.run)
225
+ open.end = Math.max(open.end, entry.span.end)
226
+ } else {
227
+ open = { end: entry.span.end, items: [entry.run] }
228
+ groups.push(open)
229
+ }
230
+ }
231
+ return groups.map(group => group.items)
232
+ }
233
+
234
+ /**
235
+ * Gutter label per run for the groups that actually contain more than one run.
236
+ * @param {object[]} runs - run records.
237
+ * @param {number} [now] - wall clock.
238
+ * @returns {Map<string, { label: string, color: number, size: number }>}
239
+ */
240
+ export function groupingOf(runs, now = Date.now()) {
241
+ const map = new Map()
242
+ const groups = overlapGroups(runs, now).filter(group => group.length > 1)
243
+ groups.forEach((group, index) => {
244
+ const label = index < 9
245
+ ? String(index + 1)
246
+ : index < 35
247
+ ? String.fromCharCode(65 + index - 9)
248
+ : '#'
249
+ const meta = { label, color: GROUP_COLORS[index % GROUP_COLORS.length], size: group.length }
250
+ for (const run of group) map.set(run.id, meta)
251
+ })
252
+ return map
253
+ }
254
+
255
+ /**
256
+ * Why a run is not making progress, in the run store's own terms.
257
+ *
258
+ * Only observable facts are used, so the panel never guesses a cause it cannot
259
+ * see: a queued run is waiting for an active-run slot (the other active runs are
260
+ * its candidates), a pending worker behind a full `maxParallel` pool is waiting
261
+ * for a slot inside its own run, and a pending worker that already burned an
262
+ * attempt is in retry backoff.
263
+ *
264
+ * @param {object} run - run record.
265
+ * @param {{ runs?: object[], now?: number }} [options] - sibling runs and clock.
266
+ * @returns {{ kind: 'slot' | 'parallel' | 'retry', text: string } | null}
267
+ */
268
+ export function waitingOf(run, options = {}) {
269
+ if (!run) return null
270
+ const runs = options.runs ?? []
271
+ const subtasks = Array.isArray(run.subtasks) ? run.subtasks : []
272
+
273
+ if (run.status === 'queued') {
274
+ // Only a run that is actually working holds a slot; other queued runs are
275
+ // waiting beside this one, not blocking it.
276
+ const active = runs
277
+ .filter(other => other.id !== run.id && ACTIVE_STATUSES.has(other.status) && other.status !== 'queued')
278
+ .sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)))
279
+ const queued = runs
280
+ .filter(other => other.status === 'queued')
281
+ .sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)))
282
+ const position = queued.findIndex(other => other.id === run.id) + 1
283
+ // Blockers first: a narrow terminal clips the tail of a cell, and the run
284
+ // holding the slot is the one fact the reader can act on.
285
+ const parts = []
286
+ if (active.length > 0) {
287
+ parts.push(`slot ← ${active.slice(0, 2).map(runTail).join(',')}`)
288
+ parts.push(`${active.length} active`)
289
+ } else {
290
+ parts.push('waiting on a slot')
291
+ }
292
+ if (position > 1) parts.push(`#${position}`)
293
+ return { kind: 'slot', text: parts.join(' · ') }
294
+ }
295
+
296
+ if (!ACTIVE_STATUSES.has(run.status)) return null
297
+
298
+ const running = subtasks.filter(subtask => subtask.status === 'running')
299
+ const pending = subtasks.filter(subtask => subtask.status === 'pending')
300
+ const retrying = pending.filter(subtask => Number(subtask.attempts) > 0)
301
+ if (retrying.length > 0) {
302
+ const cap = Number(run.limits?.attempts) || 0
303
+ const used = Math.max(...retrying.map(subtask => Number(subtask.attempts) || 0))
304
+ return { kind: 'retry', text: `retry ${used}${cap > 0 ? `/${cap}` : ''} backoff` }
305
+ }
306
+
307
+ const parallel = Number(run.limits?.maxParallel)
308
+ if (pending.length > 0 && Number.isFinite(parallel) && parallel > 0 && running.length >= parallel) {
309
+ return { kind: 'parallel', text: `worker pool full ${running.length}/${parallel} · ${pending.length} waiting` }
310
+ }
311
+ return null
312
+ }
313
+
314
+ /**
315
+ * What the run is doing right now, or how it ended. One short phrase, because
316
+ * the panel's job is to answer "is it stuck?" at a glance.
317
+ * @param {object} run - run record.
318
+ */
319
+ export function activityOf(run) {
320
+ const subtasks = Array.isArray(run?.subtasks) ? run.subtasks : []
321
+ const completed = subtasks.filter(subtask => subtask.status === 'completed').length
322
+ const running = subtasks.filter(subtask => subtask.status === 'running')
323
+ const failed = subtasks.filter(subtask => subtask.status === 'failed').length
324
+ switch (run?.status) {
325
+ case 'queued':
326
+ return 'waiting for an active-run slot'
327
+ case 'planning':
328
+ return 'planner is decomposing the goal'
329
+ case 'running':
330
+ if (running.length > 0) {
331
+ const waiting = subtasks.filter(subtask => subtask.status === 'waiting').length
332
+ const held = waiting > 0 ? ` · ${waiting} waiting on dependencies` : ''
333
+ return `${running.length} running${held} · ${running[0].title ?? 'subtask'}`
334
+ }
335
+ if (subtasks.length > 0) return `${completed}/${subtasks.length} subtasks done`
336
+ return 'starting the first subtask'
337
+ case 'aggregating':
338
+ return `merging ${completed || subtasks.length} report(s)`
339
+ case 'completed':
340
+ return `report ready · ${completed}/${subtasks.length} subtasks`
341
+ case 'partial':
342
+ return `partial report · ${completed}/${subtasks.length} subtasks${failed > 0 ? ` · ${failed} failed` : ''}`
343
+ case 'failed':
344
+ return firstLine(run.error) || 'failed without a recorded error'
345
+ case 'cancelled':
346
+ return 'cancelled by request'
347
+ case 'interrupted':
348
+ return 'host went away · resume to continue'
349
+ default:
350
+ return STATUS_LABEL[run?.status] ?? String(run?.status ?? 'unknown')
351
+ }
352
+ }
353
+
354
+ /**
355
+ * Order for display: live work first (oldest first, so rows do not reorder
356
+ * while you watch them), then finished runs newest-first.
357
+ * @param {object[]} runs - run records.
358
+ */
359
+ export function orderRuns(runs) {
360
+ const list = [...(runs ?? [])]
361
+ const active = list.filter(run => ACTIVE_STATUSES.has(run.status))
362
+ const done = list.filter(run => !ACTIVE_STATUSES.has(run.status))
363
+ active.sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)))
364
+ done.sort((a, b) => String(b.finishedAt ?? b.createdAt).localeCompare(String(a.finishedAt ?? a.createdAt)))
365
+ return [...active, ...done]
366
+ }
367
+
368
+ /** Totals for the footer: calls, tokens, priced cost, and whether any price is missing. */
369
+ export function totalsOf(runs) {
370
+ let calls = 0
371
+ let tokens = 0
372
+ // Integer micro-units keep a long-running panel's total exactly additive.
373
+ let costMicros = 0
374
+ let currency = null
375
+ const currencies = new Set()
376
+ let unpriced = false
377
+ let active = 0
378
+ let failed = 0
379
+ for (const run of runs ?? []) {
380
+ calls += callsOf(run)
381
+ tokens += run?.usage?.totalTokens ?? 0
382
+ if (run?.cost) {
383
+ costMicros += Number.isFinite(run.cost.totalMicros)
384
+ ? run.cost.totalMicros
385
+ : Math.round((run.cost.total ?? 0) * 1e6)
386
+ const code = run.cost.currency ?? 'USD'
387
+ currencies.add(code)
388
+ currency = currency ?? code
389
+ if (run.cost.complete === false) unpriced = true
390
+ } else if ((run?.usage?.modelCalls ?? 0) > 0) {
391
+ unpriced = true
392
+ }
393
+ if (ACTIVE_STATUSES.has(run?.status)) active += 1
394
+ if (run?.status === 'failed') failed += 1
395
+ }
396
+ return {
397
+ calls,
398
+ tokens,
399
+ cost: costMicros / 1e6,
400
+ costMicros,
401
+ currency: currencies.size === 1 ? currency : null,
402
+ mixedCurrency: currencies.size > 1,
403
+ unpriced,
404
+ active,
405
+ failed,
406
+ total: (runs ?? []).length,
407
+ }
408
+ }
409
+
410
+ /**
411
+ * Column sets, widest first. The first one whose fixed columns plus a readable
412
+ * activity column fit the terminal wins; the narrowest fallback stacks id and
413
+ * activity onto two lines instead of squeezing them together.
414
+ */
415
+ const TIERS = [
416
+ {
417
+ name: 'wide',
418
+ min: 22,
419
+ cells: [['gutter', GUTTER], ['id', 20], ['status', 12], ['calls', 8], ['elapsed', 7], ['workers', 9], ['activity', 0], ['parent', 8]],
420
+ },
421
+ {
422
+ name: 'standard',
423
+ min: 16,
424
+ cells: [['gutter', GUTTER], ['id', 16], ['status', 10], ['calls', 7], ['elapsed', 6], ['workers', 7], ['activity', 0]],
425
+ },
426
+ {
427
+ name: 'compact',
428
+ min: 10,
429
+ cells: [['gutter', GUTTER], ['id', 12], ['status', 8], ['elapsed', 6], ['workers', 6], ['activity', 0]],
430
+ },
431
+ {
432
+ name: 'narrow',
433
+ min: 10,
434
+ cells: [['gutter', GUTTER], ['id', 9], ['status', 5], ['elapsed', 5], ['activity', 0]],
435
+ },
436
+ ]
437
+
438
+ /**
439
+ * Pick the widest column set that still leaves a usable activity column.
440
+ * @param {number} width - terminal columns.
441
+ */
442
+ function layoutFor(width) {
443
+ for (const tier of TIERS) {
444
+ const fixed = tier.cells.reduce((sum, [, cells]) => sum + cells, 0)
445
+ const separators = tier.cells.length - 1
446
+ const activity = width - fixed - separators
447
+ if (activity >= tier.min) return { ...tier, activity }
448
+ }
449
+ // Below this, a single-line row cannot hold an id and a reason at once.
450
+ return { name: 'tiny', cells: [['gutter', GUTTER], ['id', 0], ['status', 6], ['elapsed', 6]], min: 6, activity: 0 }
451
+ }
452
+
453
+ /** Status text for the chosen width. */
454
+ function statusText(status, tier) {
455
+ if (tier === 'wide') return STATUS_LABEL[status] ?? String(status ?? '?')
456
+ if (tier === 'standard') return STATUS_MEDIUM[status] ?? String(status ?? '?')
457
+ return STATUS_SHORT[status] ?? String(status ?? '?')
458
+ }
459
+
460
+ /**
461
+ * Run id for a narrow cell: the head and the tail survive, the middle does not.
462
+ * Run ids share their date prefix, so a left truncation would leave every row
463
+ * looking identical exactly when the panel is too narrow to compare columns.
464
+ */
465
+ function shortId(id, width) {
466
+ const value = String(id ?? '')
467
+ if (value.length <= width) return value
468
+ if (width <= 1) return '…'
469
+ const tail = Math.max(2, Math.floor((width - 1) / 2))
470
+ const head = width - 1 - tail
471
+ return `${value.slice(0, head)}…${value.slice(-tail)}`
472
+ }
473
+
474
+ /**
475
+ * Worker column: what the pool is doing now, or what it ended with.
476
+ *
477
+ * A live run shows running and pending counts because that is the pool's
478
+ * pressure; a finished run shows completed and failed counts because that is
479
+ * its outcome. `0▶` or `0✓` on a row with no workers would answer a question
480
+ * nobody asked, so an empty pool is left blank.
481
+ */
482
+ function workersOf(run) {
483
+ const subtasks = Array.isArray(run?.subtasks) ? run.subtasks : []
484
+ const running = subtasks.filter(subtask => subtask.status === 'running').length
485
+ const pending = subtasks.filter(subtask => subtask.status === 'pending').length
486
+ const completed = subtasks.filter(subtask => subtask.status === 'completed').length
487
+ const failed = subtasks.filter(subtask => subtask.status === 'failed').length
488
+ const parts = []
489
+ if (ACTIVE_STATUSES.has(run?.status)) {
490
+ if (running > 0) parts.push(`${running}▶`)
491
+ if (pending > 0) parts.push(`${pending}·`)
492
+ } else if (completed > 0) {
493
+ parts.push(`${completed}✓`)
494
+ }
495
+ if (failed > 0) parts.push(`${failed}✕`)
496
+ return parts.join(' ')
497
+ }
498
+
499
+ /** Column names, with a shorter spelling when the column itself is narrow. */
500
+ function headerFor(layout, color) {
501
+ const labels = {
502
+ gutter: ['', ''],
503
+ id: ['RUN ID', 'ID'],
504
+ status: ['STATUS', 'ST'],
505
+ calls: ['CALLS', 'CALLS'],
506
+ elapsed: ['ELAPSED', 'TIME'],
507
+ workers: ['WORKERS', 'WKRS'],
508
+ activity: ['ACTIVITY / WAITING ON', 'ACTIVITY'],
509
+ parent: ['PARENT', 'PARENT'],
510
+ }
511
+ const cells = layout.cells.map(([key, width]) => {
512
+ const cellWidth = key === 'activity' ? layout.activity : width
513
+ const [long, short] = labels[key] ?? [key, key]
514
+ return pad(long.length <= cellWidth ? long : short, cellWidth)
515
+ })
516
+ return paint('2', cells.join(' '), color)
517
+ }
518
+
519
+ function rule(width, color) {
520
+ return paint('2', ` ${'─'.repeat(Math.max(0, width - 2))}`, color)
521
+ }
522
+
523
+ /** Gutter cell: a shared label and colour for runs alive at the same time. */
524
+ function gutterOf(group, color) {
525
+ if (!group) return ' '.repeat(GUTTER)
526
+ const text = `▐${group.label}`
527
+ return paint(group.color, `${text}${' '.repeat(Math.max(0, GUTTER - text.length))}`, color)
528
+ }
529
+
530
+ /**
531
+ * Render one complete frame, with no trailing newline.
532
+ *
533
+ * Kept pure so the layout can be asserted in tests without a terminal, and so
534
+ * every tier can be checked for the promise that no line exceeds the terminal
535
+ * width.
536
+ *
537
+ * @param {object[]} runs - run records.
538
+ * @param {{ now?: number, width?: number, rows?: number, color?: boolean, stateRoot?: string, intervalMs?: number }} [options]
539
+ * @returns {string} frame text, ANSI-painted only when `color` is true.
540
+ */
541
+ export function renderFrame(runs, options = {}) {
542
+ const now = options.now ?? Date.now()
543
+ const width = Math.max(24, Math.floor(options.width ?? 100))
544
+ const color = options.color === true
545
+ const interval = options.intervalMs ?? DEFAULT_INTERVAL_MS
546
+ const list = orderRuns(runs)
547
+ const totals = totalsOf(list)
548
+ const groups = groupingOf(list, now)
549
+ const layout = layoutFor(width)
550
+
551
+ const clock = new Date(now).toISOString().slice(11, 19)
552
+ const headline = [
553
+ paint('1', 'dsh-superagent', color),
554
+ paint('2', '·', color),
555
+ `${totals.total} run${totals.total === 1 ? '' : 's'}`,
556
+ totals.active > 0 ? paint('6', `${totals.active} active`, color) : paint('2', 'idle', color),
557
+ paint('2', `· ${clock}Z`, color),
558
+ ].join(' ')
559
+ const headlineText = visibleLength(headline) <= width
560
+ ? headline
561
+ : paint('2', clip(`dsh-superagent · ${totals.total} run${totals.total === 1 ? '' : 's'} · ${totals.active} active · ${clock}Z`, width), color)
562
+
563
+ const lines = [headlineText, rule(width, color)]
564
+ if (list.length === 0) {
565
+ lines.push('')
566
+ lines.push(paint('2', ` ${clip('no runs recorded yet', width - 2)}`, color))
567
+ lines.push(paint('2', ` ${clip(`state: ${options.stateRoot ?? '-'}`, width - 2)}`, color))
568
+ lines.push('')
569
+ lines.push(paint('2', ` ${clip('start one with the superagent_start tool; this panel updates itself.', width - 2)}`, color))
570
+ } else {
571
+ // A live panel is bounded by the terminal height; a one-shot frame is not,
572
+ // so `--once` and log capture keep every row.
573
+ const budget = Number.isFinite(options.rows) ? Math.max(1, Math.floor(options.rows) - 6) : Infinity
574
+ const visible = list.slice(0, budget)
575
+ const hidden = list.length - visible.length
576
+
577
+ if (layout.name !== 'tiny') lines.push(headerFor(layout, color))
578
+ for (const run of visible) {
579
+ const why = waitingOf(run, { runs: list, now })
580
+ const activity = activityOf(run)
581
+ // A queued run's only fact is its wait, so repeating "waiting for an
582
+ // active-run slot" after the concrete reason would just spend cells.
583
+ const activityText = why
584
+ ? (run.status === 'queued' ? why.text : `${why.text} · ${activity}`)
585
+ : activity
586
+ const elapsed = elapsedOf(run, now)
587
+ const calls = callsOf(run)
588
+ const cap = run?.limits?.maxModelCalls ?? 0
589
+ const callsText = cap > 0 ? `${calls}/${cap}` : String(calls)
590
+ const group = groups.get(run.id)
591
+ const status = statusText(run.status, layout.name)
592
+ const statusColor = STATUS_COLOR[run.status] ?? 0
593
+ const elapsedText = elapsed === null ? '-' : formatDuration(elapsed)
594
+
595
+ if (layout.name === 'tiny') {
596
+ // gutter + sep + id + sep + status + sep + elapsed = width
597
+ const idWidth = Math.max(4, width - GUTTER - 3 - 6 - 6)
598
+ const top = [
599
+ gutterOf(group, color),
600
+ ` ${paint('1', pad(shortId(run.id, idWidth), idWidth), color)}`,
601
+ ` ${paint(String(statusColor), pad(status, 6), color)}`,
602
+ ` ${pad(elapsedText, 6)}`,
603
+ ].join('')
604
+ lines.push(top.replace(/\s+$/, ''))
605
+ lines.push(` ${paint('2', '└', color)} ${clip(activityText, Math.max(1, width - 4))}`)
606
+ continue
607
+ }
608
+
609
+ const cells = layout.cells.map(([key, cellWidth]) => {
610
+ switch (key) {
611
+ case 'gutter':
612
+ return gutterOf(group, color)
613
+ case 'id':
614
+ return paint('1', pad(shortId(run.id, cellWidth), cellWidth), color)
615
+ case 'status':
616
+ return paint(String(statusColor), pad(status, cellWidth), color)
617
+ case 'calls':
618
+ return pad(callsText, cellWidth)
619
+ case 'elapsed':
620
+ return pad(elapsedText, cellWidth)
621
+ case 'workers':
622
+ return pad(workersOf(run), cellWidth)
623
+ case 'activity':
624
+ return pad(activityText, layout.activity)
625
+ case 'parent':
626
+ return paint('2', pad(parentLabel(run), cellWidth), color)
627
+ default:
628
+ return pad('', cellWidth)
629
+ }
630
+ })
631
+ lines.push(cells.join(' ').replace(/\s+$/, ''))
632
+ }
633
+
634
+ if (hidden > 0) {
635
+ lines.push(paint('2', ` ${clip(`… ${hidden} more run(s) · enlarge the terminal to see them`, width - 2)}`, color))
636
+ }
637
+ }
638
+
639
+ // An unpriced panel says so. Printing 0.0000 there would look like "this run
640
+ // was free", when the truth is "no price is configured for its model".
641
+ const shown = formatMoney({ totalMicros: totals.costMicros, currency: totals.currency ?? 'USD' })
642
+ const money = totals.unpriced
643
+ ? (totals.costMicros > 0 ? `${shown}+` : 'unpriced')
644
+ : shown
645
+ const summary = [
646
+ `calls ${totals.calls}`,
647
+ `${formatCount(totals.tokens)} tok`,
648
+ `cost ${money}`,
649
+ totals.failed > 0 ? paint('1', `${totals.failed} failed`, color) : null,
650
+ ].filter(Boolean).join(' · ')
651
+ const legend = list.length > 0 && groups.size > 0
652
+ ? ' · ▐n overlapping · ▶ running · · pending'
653
+ : ''
654
+ const footer = paint('2', clip(`${summary} · ${interval >= 1000 ? `${interval / 1000}s` : `${interval}ms`} refresh · Ctrl-C quit${legend}`, width), color)
655
+
656
+ lines.push(rule(width, color))
657
+ lines.push(footer)
658
+ return lines.join('\n')
659
+ }
660
+
661
+ /** Status + progress + blocking fingerprint; a change here is worth an immediate repaint. */
662
+ export function signatureOf(runs, now = Date.now()) {
663
+ const groups = groupingOf(runs, now)
664
+ return orderRuns(runs)
665
+ .map(run => {
666
+ const subtasks = Array.isArray(run.subtasks) ? run.subtasks : []
667
+ const attempts = subtasks.reduce((sum, subtask) => sum + (Number(subtask.attempts) || 0), 0)
668
+ return [
669
+ run.id,
670
+ run.status,
671
+ callsOf(run),
672
+ subtasks.filter(subtask => subtask.status === 'running').length,
673
+ subtasks.filter(subtask => subtask.status === 'completed').length,
674
+ attempts,
675
+ groups.get(run.id)?.label ?? '-',
676
+ ].join(':')
677
+ })
678
+ .join('|')
679
+ }
680
+
681
+ /**
682
+ * Run the panel until interrupted.
683
+ *
684
+ * When stdout is a terminal the frame is drawn in the alternate screen and the
685
+ * cursor is hidden; both are restored on every exit path, including SIGINT,
686
+ * SIGTERM, an uncaught exception, and `EPIPE` from a closed pipe. `once`
687
+ * deliberately skips the alternate screen so its frame stays readable after
688
+ * the process exits. When output is a pipe, each change is appended as a plain
689
+ * frame instead, which keeps `watch --once | ...` and log capture useful.
690
+ *
691
+ * @param {{ stateDir?: string, intervalMs?: number, once?: boolean, out?: NodeJS.WriteStream | { write: Function, isTTY?: boolean, columns?: number, rows?: number }, now?: () => number }} [options]
692
+ * @returns {Promise<void>} resolves after cleanup.
693
+ */
694
+ export async function watch(options = {}) {
695
+ const out = options.out ?? process.stdout
696
+ const intervalMs = Math.max(200, Number(options.intervalMs) || DEFAULT_INTERVAL_MS)
697
+ const once = options.once === true
698
+ const tty = out.isTTY === true
699
+ // `--once` prints one frame for a pipe or a log. Entering the alternate
700
+ // screen for that would draw it and then erase it on exit, so a person who
701
+ // runs it in a terminal would see nothing at all.
702
+ const altScreen = tty && !once
703
+ const color = options.color ?? tty
704
+ const now = options.now ?? Date.now
705
+ const store = createStore(resolveStateRoot(options.stateDir))
706
+ await store.init()
707
+
708
+ let stopped = false
709
+ let cleaned = false
710
+ let timer = null
711
+ let wake = null
712
+ let lastFrame = ''
713
+ let lastSignature = null
714
+
715
+ const draw = runs => {
716
+ const frame = renderFrame(runs, {
717
+ now: now(),
718
+ width: out.columns || 100,
719
+ // A one-shot frame goes to a log or a pipe, where nothing scrolls: only a
720
+ // live alternate-screen panel is bounded by the terminal height.
721
+ rows: altScreen ? out.rows : undefined,
722
+ color,
723
+ stateRoot: store.root,
724
+ intervalMs,
725
+ })
726
+ if (altScreen) {
727
+ // Home + per-line erase avoids a full-screen flash and keeps the panel
728
+ // from leaving ghost rows when a run disappears.
729
+ out.write(`${ANSI.home}${frame.split('\n').map(line => `${line}${ANSI.clearLine}`).join('\n')}\n${ANSI.clearLine}`)
730
+ } else if (frame !== lastFrame) {
731
+ out.write(`${frame}\n`)
732
+ lastFrame = frame
733
+ }
734
+ }
735
+
736
+ const cleanup = () => {
737
+ if (cleaned) return
738
+ cleaned = true
739
+ stopped = true
740
+ if (timer) clearTimeout(timer)
741
+ timer = null
742
+ wake = null
743
+ process.removeListener('SIGINT', onSignal)
744
+ process.removeListener('SIGTERM', onSignal)
745
+ if (altScreen) out.write(`${ANSI.show}${ANSI.altOff}`)
746
+ }
747
+
748
+ /**
749
+ * Ctrl-C ends the panel. The loop is woken rather than the process killed so
750
+ * the `finally` below restores the terminal *before* Node exits; calling
751
+ * `process.exit` here could drop the pending un-hide/un-alt-screen write.
752
+ */
753
+ const onSignal = () => {
754
+ if (stopped) return
755
+ stopped = true
756
+ if (timer) clearTimeout(timer)
757
+ timer = null
758
+ if (wake) wake()
759
+ }
760
+
761
+ process.on('SIGINT', onSignal)
762
+ process.on('SIGTERM', onSignal)
763
+ if (out.on) out.on('error', error => {
764
+ if (error?.code === 'EPIPE') {
765
+ cleanup()
766
+ process.exit(0)
767
+ }
768
+ throw error
769
+ })
770
+
771
+ if (altScreen) out.write(`${ANSI.altOn}${ANSI.hide}`)
772
+
773
+ try {
774
+ while (!stopped) {
775
+ let runs
776
+ try {
777
+ runs = await store.list()
778
+ } catch (error) {
779
+ const problem = [
780
+ 'dsh-superagent watch',
781
+ '',
782
+ `cannot read ${store.root}`,
783
+ error?.message ?? String(error),
784
+ ].join('\n')
785
+ if (altScreen) out.write(`${ANSI.home}${problem.split('\n').map(line => `${line}${ANSI.clearLine}`).join('\n')}`)
786
+ else out.write(`${problem}\n`)
787
+ if (once) return
788
+ await new Promise(resolve => {
789
+ wake = resolve
790
+ timer = setTimeout(resolve, intervalMs)
791
+ })
792
+ continue
793
+ }
794
+ draw(runs)
795
+ if (once) return
796
+ // A status transition (planning -> running -> aggregating) can happen
797
+ // inside one interval. Re-read at once when the fingerprint moved, then
798
+ // settle back to the normal cadence so an idle panel costs one read/s.
799
+ const signature = signatureOf(runs, now())
800
+ const moved = signature !== lastSignature
801
+ lastSignature = signature
802
+ await new Promise(resolve => {
803
+ wake = resolve
804
+ timer = setTimeout(resolve, moved ? Math.min(200, intervalMs) : intervalMs)
805
+ })
806
+ }
807
+ } finally {
808
+ cleanup()
809
+ }
810
+ }