@xiangyixie/dsh-superagent 0.9.1 → 0.9.2
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/CHANGELOG.md +259 -244
- package/LICENSE +21 -21
- package/README.md +589 -556
- package/bin/report.js +79 -79
- package/bin/watch.js +57 -57
- package/cordis.patch.yml +9 -9
- package/lib/control.js +494 -494
- package/lib/errors.js +199 -199
- package/lib/index.js +822 -822
- package/lib/orchestrator.js +1464 -1464
- package/lib/report.js +733 -733
- package/lib/store.js +385 -385
- package/lib/usage.js +152 -152
- package/lib/watch.js +458 -458
- package/package.json +67 -67
package/lib/watch.js
CHANGED
|
@@ -1,458 +1,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
|
-
* 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
|
+
* 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
|
+
}
|