@xiangyixie/dsh-superagent 0.11.0 → 0.12.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.
package/lib/report.js CHANGED
@@ -1,1068 +1,1068 @@
1
- /**
2
- * Static HTML report for dsh-superagent runs.
3
- *
4
- * `report` turns whatever is on disk into one file that can be mailed, attached
5
- * to a README, or opened from a USB stick: inline CSS, inline SVG, no script,
6
- * no font, no image, no network. The output is a pure string, so the layout is
7
- * testable without a browser.
8
- *
9
- * The charts are hand-built SVG rather than a chart library for the same reason
10
- * the watch panel is hand-built ANSI: the package ships zero runtime
11
- * dependencies.
12
- *
13
- * @module dsh-superagent/report
14
- */
15
- import { formatMoney, moneyOfMicros } from './cost.js'
16
- import { ACTIVE_STATUSES } from './store.js'
17
- import { callsOf, formatCount, formatDuration } from './watch.js'
18
-
19
- const STATUS_HEX = {
20
- queued: '#64748b',
21
- planning: '#0284c7',
22
- running: '#0284c7',
23
- aggregating: '#0284c7',
24
- completed: '#15803d',
25
- partial: '#b45309',
26
- failed: '#b91c1c',
27
- cancelled: '#7e22ce',
28
- interrupted: '#c2410c',
29
- }
30
-
31
- const STATUS_ORDER = ['running', 'planning', 'aggregating', 'queued', 'completed', 'partial', 'failed', 'cancelled', 'interrupted']
32
-
33
- /** Phase opacity inside a run bar: plan is fainter, merge is medium. */
34
- const PHASE_OPACITY = { plan: 0.38, work: 1, merge: 0.66 }
35
- const PHASE_LABEL = { plan: 'plan', work: 'work', merge: 'merge' }
36
-
37
- const SVG_FONT = "-apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"
38
- const MONO_FONT = "ui-monospace, SFMono-Regular, 'Cascadia Mono', Consolas, 'Liberation Mono', monospace"
39
-
40
- /**
41
- * Escape text for HTML text nodes and double-quoted attributes.
42
- * @param {unknown} value - raw value.
43
- */
44
- export function escapeHtml(value) {
45
- return String(value ?? '').replace(/[&<>"']/g, char => ({
46
- '&': '&amp;',
47
- '<': '&lt;',
48
- '>': '&gt;',
49
- '"': '&quot;',
50
- "'": '&#39;',
51
- }[char]))
52
- }
53
-
54
- /** Parse an ISO timestamp, or null when absent/unusable. */
55
- function timeOf(value) {
56
- const parsed = Date.parse(String(value ?? ''))
57
- return Number.isFinite(parsed) ? parsed : null
58
- }
59
-
60
- /** `¥0.0225`, `$1.24`, `<¥0.0001`, or `—`. */
61
- function money(value, currency) {
62
- if (typeof value === 'number' && !Number.isFinite(value)) return '—'
63
- if (value === null || value === undefined) return '—'
64
- return formatMoney(value, currency)
65
- }
66
-
67
- /** `2026-11-14 07:52:05` in UTC, matching the axis. */
68
- function stampUtc(ms) {
69
- if (!Number.isFinite(ms)) return '—'
70
- const iso = new Date(ms).toISOString()
71
- return `${iso.slice(0, 10)} ${iso.slice(11, 19)}`
72
- }
73
-
74
- /** Axis label: seconds when the window is short, minute precision when long. */
75
- function axisLabel(ms, span) {
76
- const date = new Date(ms)
77
- const hh = String(date.getUTCHours()).padStart(2, '0')
78
- const mm = String(date.getUTCMinutes()).padStart(2, '0')
79
- const ss = String(date.getUTCSeconds()).padStart(2, '0')
80
- if (span > 24 * 3600_000) {
81
- const mo = String(date.getUTCMonth() + 1).padStart(2, '0')
82
- const dd = String(date.getUTCDate()).padStart(2, '0')
83
- return `${mo}-${dd} ${hh}:${mm}`
84
- }
85
- return `${hh}:${mm}:${ss}`
86
- }
87
-
88
- /** Six-ish evenly spaced ticks that land on round wall-clock values. */
89
- export function axisTicks(start, end) {
90
- const span = Math.max(1, end - start)
91
- const steps = [
92
- 1000, 2000, 5000, 10_000, 15_000, 30_000,
93
- 60_000, 120_000, 300_000, 600_000, 900_000, 1_800_000,
94
- 3_600_000, 7_200_000, 21_600_000, 43_200_000, 86_400_000,
95
- ]
96
- const target = span / 6
97
- const step = steps.find(candidate => candidate >= target) ?? steps[steps.length - 1]
98
- const ticks = []
99
- for (let tick = Math.ceil(start / step) * step; tick <= end; tick += step) ticks.push(tick)
100
- // A window shorter than one step can contain no round boundary at all.
101
- return { ticks: ticks.length > 0 ? ticks : [start, end], step }
102
- }
103
-
104
- /** Truncate to an approximate pixel width at the given font size. */
105
- function clipTo(text, width, fontSize = 11) {
106
- const value = String(text ?? '').replace(/\s+/g, ' ').trim()
107
- const max = Math.max(1, Math.floor(width / (fontSize * 0.58)))
108
- if (value.length <= max) return value
109
- if (max <= 1) return '…'
110
- return `${value.slice(0, max - 1)}…`
111
- }
112
-
113
- /** Short run id for a narrow block: the time stamp alone is ambiguous. */
114
- function shortId(id) {
115
- const value = String(id ?? '')
116
- return value.length <= 12 ? value : `…${value.slice(-9)}`
117
- }
118
-
119
- /**
120
- * Derive the three visible phases from recorded timestamps.
121
- *
122
- * The run file records status, not phase boundaries, so the boundaries come
123
- * from the subtasks: planning ends when the first worker starts, work ends when
124
- * the last worker reports, and merging covers the remainder. The report states
125
- * this derivation in its footnote rather than implying the phases are exact.
126
- *
127
- * @param {object} run - run record.
128
- * @param {number} now - wall clock for a run that has not finished.
129
- */
130
- export function phasesOf(run, now) {
131
- const created = timeOf(run?.createdAt) ?? timeOf(run?.startedAt) ?? now
132
- const started = timeOf(run?.startedAt) ?? created
133
- const finished = timeOf(run?.finishedAt) ?? now
134
- const subtasks = Array.isArray(run?.subtasks) ? run.subtasks : []
135
- const starts = subtasks.map(subtask => timeOf(subtask.startedAt)).filter(value => value !== null)
136
- const ends = subtasks.map(subtask => timeOf(subtask.finishedAt)).filter(value => value !== null)
137
- const firstWork = starts.length > 0 ? Math.min(...starts) : started
138
- const lastWork = ends.length > 0 ? Math.max(...ends) : (starts.length > 0 ? Math.min(...starts) : finished)
139
- const planEnd = Math.min(Math.max(firstWork, started), finished)
140
- const workEnd = Math.min(Math.max(lastWork, planEnd), finished)
141
- return [
142
- { kind: 'plan', start: started, end: planEnd },
143
- { kind: 'work', start: planEnd, end: workEnd },
144
- { kind: 'merge', start: workEnd, end: finished },
145
- ].filter(phase => phase.end > phase.start)
146
- }
147
-
148
- /**
149
- * Greedy interval-graph colouring: a run takes the first lane whose previous
150
- * run has already ended, otherwise it opens a new lane. Two overlapping runs
151
- * therefore never share a lane, and the lane count is the true peak
152
- * concurrency of the selected window.
153
- *
154
- * @param {Array<{ start: number, end: number }>} items - spans, sorted by start.
155
- * @returns {number} number of lanes used.
156
- */
157
- export function assignLanes(items) {
158
- const laneEnds = []
159
- for (const item of items) {
160
- let lane = laneEnds.findIndex(end => end <= item.start)
161
- if (lane === -1) {
162
- lane = laneEnds.length
163
- laneEnds.push(item.end)
164
- } else {
165
- laneEnds[lane] = item.end
166
- }
167
- item.lane = lane
168
- }
169
- return laneEnds.length
170
- }
171
-
172
- /** Worker colours, by subtask order; cycled when a run has more workers. */
173
- const WORKER_COLORS = ['#0f766e', '#0284c7', '#7c3aed', '#b45309', '#be185d', '#15803d', '#475569', '#a16207']
174
-
175
- /** `40%`, or `0.4%` for a sliver rather than a misleading `0%`. */
176
- function percent(share) {
177
- if (!Number.isFinite(share) || share <= 0) return '0%'
178
- const value = share * 100
179
- if (value < 1) return `${value.toFixed(1)}%`
180
- return `${value.toFixed(0)}%`
181
- }
182
-
183
- /**
184
- * Attempts recorded for one worker.
185
- *
186
- * A subtask that never started records zero; a worker that is about to run has
187
- * not spent an attempt yet, so the value is clamped to at least one only when
188
- * the caller is describing work that did happen.
189
- *
190
- * @param {object} subtask - worker record.
191
- */
192
- export function attemptsOf(subtask) {
193
- return Math.max(0, Number(subtask?.attempts) || 0)
194
- }
195
-
196
- /**
197
- * The causal chain for the workers that needed more than one attempt, or that
198
- * ended in failure.
199
- *
200
- * The run file keeps one error per worker, not one per attempt, so a chain can
201
- * say how many attempts were spent and what the last error was, but not what
202
- * each earlier attempt said. The section states that limitation instead of
203
- * inventing per-attempt text. A self-heal round resets the worker's counter, so
204
- * its recorded attempts describe the latest round; the round itself is
205
- * reported from `run.selfHeal`.
206
- *
207
- * @param {object} run - run record.
208
- * @returns {Array<object>} one entry per retried or failed worker.
209
- */
210
- export function retryChainsOf(run) {
211
- const subtasks = Array.isArray(run?.subtasks) ? run.subtasks : []
212
- const cap = Math.max(1, Number(run?.limits?.attempts) || 1)
213
- const chains = []
214
- for (const subtask of subtasks) {
215
- const attempts = attemptsOf(subtask)
216
- const failed = subtask?.status === 'failed'
217
- if (attempts < 2 && !(failed && attempts >= 1)) continue
218
- chains.push({
219
- index: Number(subtask.index) || chains.length + 1,
220
- title: String(subtask.title ?? ''),
221
- attempts: Math.max(1, attempts),
222
- cap,
223
- status: String(subtask.status ?? 'pending'),
224
- error: String(subtask.error ?? ''),
225
- stopReason: String(subtask.stopReason ?? ''),
226
- recovered: subtask?.status === 'completed' && attempts > 1,
227
- startedAt: timeOf(subtask.startedAt),
228
- finishedAt: timeOf(subtask.finishedAt),
229
- })
230
- }
231
- return chains
232
- }
233
-
234
- /**
235
- * Wall-time share of every worker in a run.
236
- *
237
- * `share` is the worker's own span over the run's wall clock, so shares of
238
- * parallel workers can add up to more than 100%; `parallelism` is that sum and
239
- * is the run's effective worker concurrency. A worker still running counts to
240
- * `now`.
241
- *
242
- * @param {{ duration: number, subtasks: object[] }} item - prepared run.
243
- * @param {number} [now] - wall clock.
244
- */
245
- export function workerShares(item, now = Date.now()) {
246
- const wall = Math.max(0, Number(item?.duration) || 0)
247
- const workers = []
248
- for (const subtask of item?.subtasks ?? []) {
249
- const start = timeOf(subtask.startedAt)
250
- if (start === null) continue
251
- const end = timeOf(subtask.finishedAt) ?? (subtask.status === 'running' ? now : null)
252
- const span = end === null ? 0 : Math.max(0, end - start)
253
- workers.push({
254
- index: Number(subtask.index) || workers.length + 1,
255
- title: String(subtask.title ?? ''),
256
- status: String(subtask.status ?? 'pending'),
257
- attempts: attemptsOf(subtask),
258
- span,
259
- share: wall > 0 ? span / wall : 0,
260
- })
261
- }
262
- const busy = workers.reduce((sum, worker) => sum + worker.span, 0)
263
- return { wall, workers, busy, parallelism: wall > 0 ? busy / wall : 0 }
264
- }
265
-
266
- /**
267
- * Normalise run files into what the page needs, in chronological order.
268
- * @param {object[]} runs - run records from the store.
269
- * @param {number} now - wall clock.
270
- */
271
- export function prepare(runs, now) {
272
- const items = []
273
- for (const run of runs ?? []) {
274
- if (!run || !run.id) continue
275
- const start = timeOf(run.startedAt) ?? timeOf(run.createdAt) ?? now
276
- const end = timeOf(run.finishedAt) ?? now
277
- const live = ACTIVE_STATUSES.has(run.status)
278
- const phases = phasesOf(run, now)
279
- const calls = callsOf(run)
280
- const priced = run.cost && run.cost.complete !== false
281
- const cost = priced && Number.isFinite(run.cost?.total) ? run.cost.total : null
282
- const costMicros = priced
283
- ? (Number.isFinite(run.cost?.totalMicros) ? run.cost.totalMicros : Math.round((run.cost.total ?? 0) * 1e6))
284
- : null
285
- items.push({
286
- run,
287
- id: String(run.id),
288
- status: String(run.status ?? 'unknown'),
289
- start,
290
- end: Math.max(end, start),
291
- live,
292
- phases,
293
- calls,
294
- cost,
295
- costMicros,
296
- currency: run.cost?.currency ?? 'USD',
297
- tokens: run.usage?.totalTokens ?? 0,
298
- duration: Math.max(0, end - start),
299
- parent: String(run.parentSessionId ?? ''),
300
- goal: String(run.goal ?? ''),
301
- error: String(run.error ?? ''),
302
- subtasks: Array.isArray(run.subtasks) ? run.subtasks : [],
303
- })
304
- }
305
- items.sort((a, b) => a.start - b.start || a.id.localeCompare(b.id))
306
- return items
307
- }
308
-
309
- /** Totals used by the cards and the one-line summary. */
310
- function summarize(items) {
311
- const byStatus = {}
312
- let calls = 0
313
- let tokens = 0
314
- // Integer micro-units: a long list of runs must not drift the cent total.
315
- let costMicros = 0
316
- let priced = 0
317
- let unpriced = 0
318
- const currencies = new Set()
319
- for (const item of items) {
320
- byStatus[item.status] = (byStatus[item.status] ?? 0) + 1
321
- calls += item.calls
322
- tokens += item.tokens
323
- if (item.costMicros !== null) {
324
- costMicros += item.costMicros
325
- priced += 1
326
- currencies.add(item.currency)
327
- } else if (item.calls > 0) {
328
- unpriced += 1
329
- }
330
- }
331
- const start = items.length > 0 ? Math.min(...items.map(item => item.start)) : 0
332
- const end = items.length > 0 ? Math.max(...items.map(item => item.end)) : 0
333
- const currency = currencies.size === 1 ? [...currencies][0] : (currencies.size === 0 ? 'USD' : null)
334
- return {
335
- byStatus,
336
- calls,
337
- tokens,
338
- cost: costMicros / 1e6,
339
- costMicros,
340
- currency,
341
- mixedCurrency: currencies.size > 1,
342
- priced,
343
- unpriced,
344
- start,
345
- end,
346
- span: Math.max(0, end - start),
347
- }
348
- }
349
-
350
- /**
351
- * Timeline: one row per run, a bar split into plan/work/merge, and an explicit
352
- * marker for the runs that did not complete, because a flat bar alone hides
353
- * whether an early end was success or damage.
354
- */
355
- function timelineSvg(items, options) {
356
- const width = 1240
357
- const left = 292
358
- // The right edge is reserved for the outcome marker, so a run that ends at
359
- // the very last instant still has room for "✕ failed" instead of silently
360
- // losing the annotation.
361
- const right = 176
362
- const top = 54
363
- const rowHeight = 30
364
- const height = top + items.length * rowHeight + 26
365
- const start = options.start
366
- const end = options.end
367
- const span = Math.max(1, end - start)
368
- const track = width - left - right
369
- const x = time => left + ((time - start) / span) * track
370
- const { ticks } = options
371
- const parts = []
372
-
373
- parts.push(`<svg viewBox="0 0 ${width} ${height}" role="img" aria-labelledby="timeline-title timeline-desc">`)
374
- parts.push('<title id="timeline-title">Run timeline</title>')
375
- parts.push(`<desc id="timeline-desc">${escapeHtml(`${items.length} runs from ${stampUtc(start)} to ${stampUtc(end)} UTC, each bar split into planning, work, and merge phases.`)}</desc>`)
376
-
377
- for (const tick of ticks) {
378
- const gx = x(tick).toFixed(1)
379
- parts.push(`<line x1="${gx}" y1="${top - 18}" x2="${gx}" y2="${height - 20}" stroke="#eef1f5" stroke-width="1"/>`)
380
- parts.push(`<text x="${gx}" y="${top - 26}" text-anchor="middle" class="axis" fill="#94a3b8">${escapeHtml(axisLabel(tick, span))}</text>`)
381
- }
382
-
383
- items.forEach((item, index) => {
384
- const y = top + index * rowHeight
385
- const color = STATUS_HEX[item.status] ?? '#64748b'
386
- if (index % 2 === 1) {
387
- parts.push(`<rect x="8" y="${y}" width="${width - 16}" height="${rowHeight - 1}" rx="4" fill="#fbfcfe"/>`)
388
- }
389
- parts.push(`<line x1="16" y1="${y + rowHeight - 0.5}" x2="${width - 16}" y2="${y + rowHeight - 0.5}" stroke="#f1f5f9" stroke-width="1"/>`)
390
- parts.push(`<text x="16" y="${y + 13}" class="id" fill="#0f172a">${escapeHtml(item.id)}</text>`)
391
- parts.push(`<text x="16" y="${y + 25}" class="meta" fill="${color}">${escapeHtml(item.status.toUpperCase())} · ${escapeHtml(formatDuration(item.duration))}</text>`)
392
-
393
- const phases = item.phases.length > 0
394
- ? item.phases
395
- // A run that started and ended in the same millisecond has no positive
396
- // span to draw; keep a tick so the row is not silently blank.
397
- : [{ kind: 'work', start: item.start, end: item.start }]
398
- for (const phase of phases) {
399
- const px = x(phase.start)
400
- // A sub-second run on a multi-hour axis is a hairline. Give it three
401
- // pixels so it stays visible and clickable instead of disappearing.
402
- const pw = Math.max(3, x(phase.end) - px)
403
- const opacity = PHASE_OPACITY[phase.kind] ?? 0.6
404
- parts.push(`<rect x="${px.toFixed(1)}" y="${y + 6}" width="${pw.toFixed(1)}" height="11" rx="3" fill="${color}" opacity="${opacity}"><title>${escapeHtml(`${PHASE_LABEL[phase.kind]} · ${formatDuration(phase.end - phase.start)}`)}</title></rect>`)
405
- }
406
-
407
- // Subtask boundaries inside the work phase: a thin white notch is enough
408
- // to show whether workers overlapped or ran one after another.
409
- const notches = new Set()
410
- for (const subtask of item.subtasks) {
411
- for (const edge of [timeOf(subtask.startedAt), timeOf(subtask.finishedAt)]) {
412
- if (edge !== null) notches.add(edge)
413
- }
414
- }
415
- for (const notch of notches) {
416
- if (notch <= start || notch >= end) continue
417
- const nx = x(notch)
418
- const barStart = x(item.start)
419
- const barEnd = x(item.end)
420
- if (nx <= barStart + 2 || nx >= barEnd - 2) continue
421
- parts.push(`<line x1="${nx.toFixed(1)}" y1="${y + 7}" x2="${nx.toFixed(1)}" y2="${y + 16}" stroke="#ffffff" stroke-width="1" opacity="0.55"/>`)
422
- }
423
-
424
- if (item.live) {
425
- parts.push(`<line x1="${(x(item.end) + 3).toFixed(1)}" y1="${y + 5}" x2="${(x(item.end) + 3).toFixed(1)}" y2="${y + 18}" stroke="${color}" stroke-width="2" stroke-dasharray="2 2"/>`)
426
- }
427
-
428
- const markers = {
429
- failed: '✕ failed',
430
- cancelled: '⊘ cancelled',
431
- interrupted: '! interrupted',
432
- partial: '△ partial',
433
- }
434
- const marker = markers[item.status]
435
- if (marker) {
436
- const available = width - 16 - (x(item.end) + 8)
437
- parts.push(`<text x="${(x(item.end) + 8).toFixed(1)}" y="${y + 15}" class="mark" fill="${color}">${escapeHtml(clipTo(marker, Math.max(40, available), 10))}</text>`)
438
- }
439
- })
440
-
441
- parts.push('</svg>')
442
- return parts.join('')
443
- }
444
-
445
- /**
446
- * Swimlanes: the same runs placed on the minimum number of lanes so that
447
- * overlaps are visible as horizontal neighbours instead of hidden in a
448
- * chronological list.
449
- */
450
- function lanesSvg(items, options) {
451
- const lanes = options.lanes
452
- const laneHeight = 40
453
- const width = 1240
454
- const left = 92
455
- const right = 48
456
- const top = 44
457
- const height = top + Math.max(1, lanes) * laneHeight + 34
458
- const start = options.start
459
- const end = options.end
460
- const span = Math.max(1, end - start)
461
- const track = width - left - right
462
- const x = time => left + ((time - start) / span) * track
463
- const parts = []
464
-
465
- parts.push(`<svg viewBox="0 0 ${width} ${height}" role="img" aria-labelledby="lanes-title lanes-desc">`)
466
- parts.push('<title id="lanes-title">Concurrency swimlanes</title>')
467
- parts.push(`<desc id="lanes-desc">${escapeHtml(`Runs placed on ${lanes} lane${lanes === 1 ? '' : 's'}; overlapping runs never share a lane, so the lane count is the peak concurrency.`)}</desc>`)
468
-
469
- for (let lane = 0; lane < Math.max(1, lanes); lane++) {
470
- const y = top + lane * laneHeight
471
- parts.push(`<rect x="${left}" y="${y + 5}" width="${track}" height="${laneHeight - 10}" rx="6" fill="#f8fafc"/>`)
472
- parts.push(`<text x="${left - 12}" y="${y + laneHeight / 2 + 4}" text-anchor="end" class="axis" fill="#94a3b8">lane ${lane + 1}</text>`)
473
- }
474
-
475
- for (const tick of options.ticks) {
476
- const gx = x(tick).toFixed(1)
477
- parts.push(`<line x1="${gx}" y1="${top}" x2="${gx}" y2="${height - 26}" stroke="#eef1f5" stroke-width="1"/>`)
478
- parts.push(`<text x="${gx}" y="${height - 10}" text-anchor="middle" class="axis" fill="#94a3b8">${escapeHtml(axisLabel(tick, span))}</text>`)
479
- }
480
-
481
- for (const item of items) {
482
- const color = STATUS_HEX[item.status] ?? '#64748b'
483
- const y = top + item.lane * laneHeight + 9
484
- const bx = x(item.start)
485
- const bw = Math.max(4, x(item.end) - bx)
486
- parts.push(`<rect x="${bx.toFixed(1)}" y="${y}" width="${bw.toFixed(1)}" height="${laneHeight - 18}" rx="4" fill="${color}" opacity="${item.live ? 0.55 : 0.88}"><title>${escapeHtml(`${item.id} · ${item.status} · ${formatDuration(item.duration)}`)}</title></rect>`)
487
- if (bw > 74) {
488
- parts.push(`<text x="${(bx + 7).toFixed(1)}" y="${y + 14}" class="lane-label" fill="#ffffff">${escapeHtml(shortId(item.id))}</text>`)
489
- }
490
- }
491
-
492
- parts.push('</svg>')
493
- return parts.join('')
494
- }
495
-
496
- /** Round a value up to a 1/2/5 × 10^n axis maximum. */
497
- function niceMax(value) {
498
- if (!Number.isFinite(value) || value <= 0) return 1
499
- const power = 10 ** Math.floor(Math.log10(value))
500
- const scaled = value / power
501
- const factor = scaled <= 1 ? 1 : scaled <= 2 ? 2 : scaled <= 5 ? 5 : 10
502
- return factor * power
503
- }
504
-
505
- /**
506
- * Cumulative step chart. Events land at each run's end time, so the curve
507
- * answers "how much had this window spent by 09:15?" without pretending to
508
- * know the intra-run shape that the run files do not record.
509
- *
510
- * @param {Array<{ t: number, value: number }>} events - sorted by time.
511
- * @param {{ start: number, end: number, color: string, ticks: number[], formatter?: (value: number) => string, empty?: string, title: string }} options
512
- */
513
- function curveSvg(events, options) {
514
- const width = 620
515
- const height = 220
516
- const left = 58
517
- const right = 16
518
- const top = 20
519
- const bottom = 38
520
- const plotW = width - left - right
521
- const plotH = height - top - bottom
522
- const start = options.start
523
- const end = options.end
524
- const span = Math.max(1, end - start)
525
- const x = time => left + ((time - start) / span) * plotW
526
- const eventsWithValue = events.filter(event => Number.isFinite(event.value))
527
- const total = eventsWithValue.reduce((sum, event) => sum + event.value, 0)
528
- const max = niceMax(total)
529
- const y = value => top + plotH - (value / max) * plotH
530
- const format = options.formatter ?? (value => formatCount(value))
531
- const parts = []
532
-
533
- parts.push(`<svg viewBox="0 0 ${width} ${height}" role="img" aria-label="${escapeHtml(options.title)}">`)
534
- parts.push(`<rect x="${left}" y="${top}" width="${plotW}" height="${plotH}" fill="#f8fafc" rx="6"/>`)
535
-
536
- for (let index = 0; index <= 4; index++) {
537
- const value = (max / 4) * index
538
- const gy = y(value).toFixed(1)
539
- parts.push(`<line x1="${left}" y1="${gy}" x2="${left + plotW}" y2="${gy}" stroke="#e8edf3" stroke-width="1"/>`)
540
- parts.push(`<text x="${left - 10}" y="${Number(gy) + 4}" text-anchor="end" class="axis" fill="#94a3b8">${escapeHtml(format(value))}</text>`)
541
- }
542
-
543
- for (const tick of options.ticks) {
544
- const gx = x(tick).toFixed(1)
545
- parts.push(`<line x1="${gx}" y1="${top}" x2="${gx}" y2="${top + plotH}" stroke="#eef1f5" stroke-width="1"/>`)
546
- parts.push(`<text x="${gx}" y="${height - 12}" text-anchor="middle" class="axis" fill="#94a3b8">${escapeHtml(axisLabel(tick, span))}</text>`)
547
- }
548
-
549
- if (eventsWithValue.length === 0) {
550
- parts.push(`<text x="${(left + plotW / 2).toFixed(1)}" y="${(top + plotH / 2).toFixed(1)}" text-anchor="middle" class="empty">${escapeHtml(options.empty ?? 'no data')}</text>`)
551
- parts.push('</svg>')
552
- return parts.join('')
553
- }
554
-
555
- let cursor = 0
556
- let path = `M ${x(start).toFixed(1)} ${y(0).toFixed(1)}`
557
- for (const event of eventsWithValue) {
558
- cursor += event.value
559
- path += ` H ${x(event.t).toFixed(1)} V ${y(cursor).toFixed(1)}`
560
- }
561
- path += ` H ${x(end).toFixed(1)}`
562
-
563
- parts.push(`<path d="${path} V ${y(0).toFixed(1)} H ${x(start).toFixed(1)} Z" fill="${options.color}" opacity="0.10"/>`)
564
- parts.push(`<path d="${path}" fill="none" stroke="${options.color}" stroke-width="2" stroke-linejoin="round"/>`)
565
-
566
- let running = 0
567
- for (const event of eventsWithValue) {
568
- running += event.value
569
- parts.push(`<circle cx="${x(event.t).toFixed(1)}" cy="${y(running).toFixed(1)}" r="3" fill="#ffffff" stroke="${options.color}" stroke-width="2"><title>${escapeHtml(`${stampUtc(event.t)} · ${format(event.value)} (total ${format(running)})`)}</title></circle>`)
570
- }
571
-
572
- parts.push('</svg>')
573
- return parts.join('')
574
- }
575
-
576
- /** Outcome word and symbol for the last recorded attempt of a worker. */
577
- function outcomeOf(chain) {
578
- if (chain.status === 'completed') return { symbol: '✓', tone: 'ok', text: chain.recovered ? `recovered on attempt ${chain.attempts}` : 'completed' }
579
- if (chain.status === 'failed') return { symbol: '✕', tone: 'bad', text: `failed after ${chain.attempts} attempt${chain.attempts === 1 ? '' : 's'}` }
580
- if (chain.status === 'running') return { symbol: '▶', tone: 'live', text: `running · attempt ${chain.attempts}` }
581
- return { symbol: '…', tone: 'idle', text: `still open · ${chain.attempts} attempt${chain.attempts === 1 ? '' : 's'} spent` }
582
- }
583
-
584
- /**
585
- * Failure and retry chains: which worker failed, how many attempts it burned,
586
- * and what it ended as. Only runs that actually retried or failed are listed,
587
- * so a healthy window says so in one line instead of drawing empty boxes.
588
- */
589
- function retriesSection(items) {
590
- const blocks = []
591
- for (const item of [...items].sort((a, b) => b.end - a.end)) {
592
- const chains = retryChainsOf(item.run)
593
- const heal = item.run?.selfHeal
594
- if (chains.length === 0 && !heal) continue
595
- const attempts = chains.reduce((sum, chain) => sum + chain.attempts, 0)
596
- const color = STATUS_HEX[item.status] ?? '#64748b'
597
- blocks.push([
598
- '<article class="retry">',
599
- '<div class="retry-head">',
600
- `<span class="chip" style="background:${color}">${escapeHtml(item.status.toUpperCase())}</span>`,
601
- `<span class="rid">${escapeHtml(item.id)}</span>`,
602
- `<span class="when">${escapeHtml(stampUtc(item.start))} UTC · ${escapeHtml(formatDuration(item.duration))}</span>`,
603
- `<span class="tally">${chains.length} worker${chains.length === 1 ? '' : 's'} · ${attempts} attempt${attempts === 1 ? '' : 's'}</span>`,
604
- '</div>',
605
- heal
606
- ? `<div class="selfheal">self-heal round ${escapeHtml(String(heal.rounds ?? 1))} · retried ${escapeHtml(String(heal.retried ?? 0))} · recovered ${escapeHtml(String(heal.recovered ?? 0))}${heal.model ? ` · on <code>${escapeHtml(heal.model)}</code>` : ''}</div>`
607
- : '',
608
- item.run?.recovery?.previousStatus
609
- ? `<div class="selfheal">resumed after an earlier <code>${escapeHtml(String(item.run.recovery.previousStatus))}</code> attempt</div>`
610
- : '',
611
- ...chains.map(chain => {
612
- const outcome = outcomeOf(chain)
613
- const steps = []
614
- for (let attempt = 1; attempt <= chain.attempts; attempt++) {
615
- const last = attempt === chain.attempts
616
- const tone = last ? outcome.tone : 'bad'
617
- steps.push(`<span class="step ${tone}">${attempt} ${last ? outcome.symbol : '✕'}</span>`)
618
- }
619
- return [
620
- '<div class="retry-worker">',
621
- `<div class="worker-head"><span class="widx">#${escapeHtml(String(chain.index))}</span> ${escapeHtml(chain.title)}`,
622
- `<span class="outcome ${outcome.tone}">${escapeHtml(outcome.text)}</span></div>`,
623
- `<div class="chain">${steps.join('<span class="arrow">→</span>')}</div>`,
624
- chain.error
625
- ? `<div class="worker-error"><code>${escapeHtml(chain.error)}</code></div>`
626
- : chain.stopReason
627
- ? `<div class="worker-error">child stopped with reason <code>${escapeHtml(chain.stopReason)}</code></div>`
628
- : '',
629
- '</div>',
630
- ].join('')
631
- }),
632
- '</article>',
633
- ].join(''))
634
- if (blocks.length === 12) break
635
- }
636
-
637
- if (blocks.length === 0) {
638
- return '<p class="hint">No retries and no failed workers in this window: every started worker finished on its first attempt.</p>'
639
- }
640
- const note = blocks.length > 0 && items.length > blocks.length
641
- ? `<p class="hint">Showing the ${blocks.length} most recent runs with retries or failures.</p>`
642
- : ''
643
- return `<div class="retries">${blocks.join('')}</div>${note}`
644
- }
645
-
646
- /**
647
- * Worker time share: how the run's wall clock was distributed across its
648
- * workers. Shares are per worker against the run's wall clock, so parallel
649
- * workers add up past 100%; the parallelism factor is that sum.
650
- */
651
- function workersSection(items, now) {
652
- const rows = []
653
- for (const item of [...items].sort((a, b) => b.duration - a.duration)) {
654
- const shares = workerShares(item, now)
655
- if (shares.workers.length === 0) continue
656
- const color = STATUS_HEX[item.status] ?? '#64748b'
657
- const segments = []
658
- let cursor = 0
659
- shares.workers.forEach((worker, index) => {
660
- const wx = shares.busy > 0 ? (worker.span / shares.busy) * 1080 : 0
661
- const fill = WORKER_COLORS[index % WORKER_COLORS.length]
662
- if (wx > 0) {
663
- segments.push(`<rect x="${cursor.toFixed(1)}" y="4" width="${Math.max(1, wx).toFixed(1)}" height="18" rx="3" fill="${fill}"><title>${escapeHtml(`${worker.title} · ${formatDuration(worker.span)} · ${percent(worker.share)} of the run's wall clock`)}</title></rect>`)
664
- }
665
- cursor += wx
666
- })
667
- const listed = shares.workers.slice(0, 6)
668
- const rest = shares.workers.length - listed.length
669
- rows.push([
670
- '<div class="workers-run">',
671
- '<div class="workers-head">',
672
- `<span class="chip" style="background:${color}">${escapeHtml(item.status)}</span>`,
673
- `<span class="rid">${escapeHtml(item.id)}</span>`,
674
- `<span class="when">wall ${escapeHtml(formatDuration(shares.wall))} · workers busy ${escapeHtml(formatDuration(shares.busy))} · ${shares.parallelism.toFixed(2)}× parallel</span>`,
675
- '</div>',
676
- `<svg viewBox="0 0 1080 26" role="img" aria-label="${escapeHtml(`${shares.workers.length} workers of ${item.id} by share of total worker time`)}">`,
677
- '<rect x="0" y="4" width="1080" height="18" rx="6" fill="#f1f5f9"/>',
678
- segments.join(''),
679
- '</svg>',
680
- '<ul class="worker-list">',
681
- ...listed.map((worker, index) => {
682
- const fill = WORKER_COLORS[index % WORKER_COLORS.length]
683
- const outcome = worker.status === 'completed' ? 'done' : worker.status === 'failed' ? 'failed' : worker.status
684
- return [
685
- '<li>',
686
- `<i class="swatch" style="background:${fill}"></i>`,
687
- `<span class="wtitle">#${escapeHtml(String(worker.index))} ${escapeHtml(worker.title)}</span>`,
688
- `<span class="wmeta">${escapeHtml(outcome)}${worker.attempts > 1 ? ` · ${escapeHtml(String(worker.attempts))} attempts` : ''} · ${escapeHtml(formatDuration(worker.span))} · ${escapeHtml(percent(worker.share))}</span>`,
689
- '</li>',
690
- ].join('')
691
- }),
692
- rest > 0 ? `<li class="more">+${rest} more worker${rest === 1 ? '' : 's'} in the bar above</li>` : '',
693
- '</ul>',
694
- '</div>',
695
- ].join(''))
696
- if (rows.length === 10) break
697
- }
698
-
699
- if (rows.length === 0) {
700
- return '<p class="hint">No worker timings recorded: these runs never started a subtask, or their subtasks carry no <code>startedAt</code>.</p>'
701
- }
702
- return `<div class="workers">${rows.join('')}</div>`
703
- }
704
-
705
- /** One stat card. */
706
- function card(label, value, note, accent) {
707
- return [
708
- '<div class="card">',
709
- `<div class="card-label">${escapeHtml(label)}</div>`,
710
- `<div class="card-value"${accent ? ` style="color:${accent}"` : ''}>${escapeHtml(value)}</div>`,
711
- `<div class="card-note">${escapeHtml(note)}</div>`,
712
- '</div>',
713
- ].join('')
714
- }
715
-
716
- const CSS = `
717
- :root {
718
- color-scheme: light;
719
- --ink: #0f172a;
720
- --muted: #64748b;
721
- --line: #e5e9f0;
722
- --card: #ffffff;
723
- --accent: #0f766e;
724
- }
725
- * { box-sizing: border-box; }
726
- html, body { margin: 0; padding: 0; }
727
- body {
728
- background: #f4f6fa;
729
- background-image: radial-gradient(900px 420px at 12% -8%, #e6f2f1 0%, rgba(230,242,241,0) 70%),
730
- radial-gradient(760px 380px at 96% 4%, #eef0fb 0%, rgba(238,240,251,0) 66%);
731
- color: var(--ink);
732
- font: 14px/1.55 ${SVG_FONT};
733
- -webkit-font-smoothing: antialiased;
734
- }
735
- .page { max-width: 1280px; margin: 0 auto; padding: 44px 32px 64px; }
736
- .masthead { margin-bottom: 26px; }
737
- .eyebrow {
738
- font: 600 11px/1 ${MONO_FONT};
739
- letter-spacing: .14em;
740
- text-transform: uppercase;
741
- color: var(--accent);
742
- }
743
- h1 { font-size: 34px; line-height: 1.15; letter-spacing: -.02em; margin: 12px 0 8px; }
744
- .lede { margin: 0; max-width: 760px; color: #475569; font-size: 15px; }
745
- .meta { margin-top: 14px; font: 12px/1.5 ${MONO_FONT}; color: #7c8899; }
746
- .cards { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 12px; margin: 26px 0 22px; }
747
- .card { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px 13px; box-shadow: 0 1px 2px rgba(15,23,42,.04); }
748
- .card-label { font: 600 10px/1 ${MONO_FONT}; letter-spacing: .12em; text-transform: uppercase; color: #8b98a9; }
749
- .card-value { font-size: 26px; font-weight: 650; letter-spacing: -.02em; margin: 9px 0 4px; font-variant-numeric: tabular-nums; }
750
- .card-note { font-size: 11.5px; color: var(--muted); }
751
- .panel { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 20px 22px 16px; margin-bottom: 18px; box-shadow: 0 1px 2px rgba(15,23,42,.04); }
752
- .panel-head { display: flex; align-items: baseline; justify-content: space-between; gap: 18px; margin-bottom: 10px; flex-wrap: wrap; }
753
- .panel h2 { font-size: 15px; letter-spacing: -.01em; margin: 0; }
754
- .panel .hint { font-size: 12px; color: var(--muted); }
755
- .legend { display: flex; gap: 16px; flex-wrap: wrap; font-size: 11.5px; color: #5b6b7f; margin: 4px 0 6px; }
756
- .legend span { display: inline-flex; align-items: center; gap: 6px; }
757
- .swatch { width: 10px; height: 10px; border-radius: 3px; display: inline-block; }
758
- figure { margin: 0; overflow-x: auto; }
759
- svg { display: block; width: 100%; height: auto; min-width: 720px; }
760
- svg text { font-family: ${SVG_FONT}; }
761
- svg .axis { font-family: ${MONO_FONT}; font-size: 10px; }
762
- svg .id { font-family: ${MONO_FONT}; font-size: 11px; font-weight: 600; }
763
- svg .meta { font-family: ${MONO_FONT}; font-size: 9.5px; letter-spacing: .04em; }
764
- svg .mark { font-size: 10px; font-weight: 600; }
765
- svg .lane-label { font-family: ${MONO_FONT}; font-size: 9.5px; }
766
- svg .empty { font-size: 12px; fill: #94a3b8; }
767
- .charts { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
768
- .charts .panel { margin-bottom: 18px; }
769
- .charts svg { min-width: 0; }
770
- .failures { display: grid; gap: 10px; }
771
- .failure { border: 1px solid var(--line); border-left: 3px solid #b91c1c; border-radius: 8px; padding: 10px 13px; background: #fff; }
772
- .failure.cancelled { border-left-color: #7e22ce; }
773
- .failure.interrupted { border-left-color: #c2410c; }
774
- .failure.partial { border-left-color: #b45309; }
775
- .failure-head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font: 600 11.5px/1.4 ${MONO_FONT}; }
776
- .failure-head .chip { font-size: 9.5px; letter-spacing: .06em; padding: 2px 7px; border-radius: 999px; color: #fff; }
777
- .failure-body { margin-top: 6px; font-size: 12.5px; color: #475569; }
778
- .failure-body code { font-family: ${MONO_FONT}; font-size: 11.5px; background: #f4f6fa; padding: 1px 5px; border-radius: 4px; }
779
- .failure .when { color: #8b98a9; font-weight: 400; }
780
- .retries { display: grid; gap: 12px; }
781
- .retry { border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; background: #fff; }
782
- .retry-head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font: 600 11.5px/1.4 ${MONO_FONT}; }
783
- .retry-head .when, .retry-head .tally { color: #8b98a9; font-weight: 400; }
784
- .selfheal { margin-top: 9px; font-size: 12px; color: #475569; border-left: 3px solid #b45309; padding: 2px 0 2px 9px; }
785
- .selfheal code { font-family: ${MONO_FONT}; font-size: 11.5px; background: #f4f6fa; padding: 1px 5px; border-radius: 4px; }
786
- .retry-worker { margin-top: 10px; padding-top: 10px; border-top: 1px dashed #eef1f5; }
787
- .worker-head { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: #1e293b; flex-wrap: wrap; }
788
- .worker-head .widx { font: 600 10.5px ${MONO_FONT}; color: #8b98a9; }
789
- .worker-head .outcome { font: 600 10px ${MONO_FONT}; letter-spacing: .04em; padding: 2px 7px; border-radius: 999px; }
790
- .outcome.ok { color: #15803d; background: #dcfce7; }
791
- .outcome.bad { color: #b91c1c; background: #fee2e2; }
792
- .outcome.live { color: #0284c7; background: #e0f2fe; }
793
- .outcome.idle { color: #b45309; background: #fef3c7; }
794
- .chain { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-top: 9px; }
795
- .step { font: 600 11px ${MONO_FONT}; padding: 3px 9px; border-radius: 6px; border: 1px solid transparent; }
796
- .step.ok { color: #15803d; background: #f0fdf4; border-color: #bbf7d0; }
797
- .step.bad { color: #b91c1c; background: #fef2f2; border-color: #fecaca; }
798
- .step.live { color: #0284c7; background: #f0f9ff; border-color: #bae6fd; }
799
- .step.idle { color: #b45309; background: #fffbeb; border-color: #fde68a; }
800
- .arrow { color: #cbd5e1; font-size: 12px; }
801
- .worker-error { margin-top: 7px; font-size: 12px; color: #475569; }
802
- .worker-error code { font-family: ${MONO_FONT}; font-size: 11.5px; background: #fef2f2; color: #991b1b; padding: 1px 5px; border-radius: 4px; }
803
- .workers { display: grid; gap: 16px; }
804
- .workers-run { border-top: 1px solid #f1f4f8; padding-top: 12px; }
805
- .workers-run:first-child { border-top: 0; padding-top: 0; }
806
- .workers-head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font: 600 11.5px/1.4 ${MONO_FONT}; margin-bottom: 8px; }
807
- .workers-head .when { color: #8b98a9; font-weight: 400; }
808
- .workers svg { min-width: 0; }
809
- .worker-list { list-style: none; margin: 10px 0 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(290px, 1fr)); gap: 5px 20px; }
810
- .worker-list li { display: flex; align-items: center; gap: 7px; font-size: 12px; color: #334155; min-width: 0; }
811
- .worker-list .wtitle { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
812
- .worker-list .wmeta { margin-left: auto; color: #8b98a9; font: 11px ${MONO_FONT}; white-space: nowrap; }
813
- .worker-list .more { color: #8b98a9; font-size: 11.5px; }
814
- .table-wrap { overflow-x: auto; }
815
- table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
816
- th { text-align: left; font: 600 10px/1 ${MONO_FONT}; letter-spacing: .1em; text-transform: uppercase; color: #8b98a9; padding: 0 10px 9px; border-bottom: 1px solid var(--line); }
817
- td { padding: 10px; border-bottom: 1px solid #f1f4f8; vertical-align: top; }
818
- tr:last-child td { border-bottom: 0; }
819
- td.num { text-align: right; font-family: ${MONO_FONT}; font-variant-numeric: tabular-nums; white-space: nowrap; }
820
- td.id { font-family: ${MONO_FONT}; font-size: 11.5px; white-space: nowrap; }
821
- .goal { display: block; max-width: 520px; color: #475569; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
822
- .chip { display: inline-block; padding: 2px 8px; border-radius: 999px; font: 600 10px/1.6 ${MONO_FONT}; letter-spacing: .05em; color: #fff; }
823
- footer { margin-top: 26px; color: #8b98a9; font-size: 11.5px; line-height: 1.7; }
824
- footer code { font-family: ${MONO_FONT}; }
825
- @media (max-width: 1100px) {
826
- .cards { grid-template-columns: repeat(3, minmax(0, 1fr)); }
827
- }
828
- @media (max-width: 680px) {
829
- .cards { grid-template-columns: repeat(2, minmax(0, 1fr)); }
830
- }
831
- @media (max-width: 900px) {
832
- .charts { grid-template-columns: 1fr; }
833
- .page { padding: 28px 16px 44px; }
834
- h1 { font-size: 26px; }
835
- }
836
- @media print {
837
- body { background: #fff; }
838
- .page { max-width: none; padding: 0; }
839
- .panel, .card { box-shadow: none; break-inside: avoid; }
840
- }
841
- `
842
-
843
- /**
844
- * Build the full report.
845
- *
846
- * @param {object[]} runs - run records, any order.
847
- * @param {{ title?: string, generatedAt?: number, now?: number, subtitle?: string }} [options]
848
- * @returns {string} a complete HTML document with no external references.
849
- */
850
- export function buildReport(runs, options = {}) {
851
- const now = options.now ?? Date.now()
852
- const generatedAt = options.generatedAt ?? now
853
- const items = prepare(runs, now)
854
- const summary = summarize(items)
855
- const start = summary.start
856
- const end = summary.end
857
- const span = Math.max(1, summary.span)
858
- const { ticks } = axisTicks(start, end)
859
- const laneCount = assignLanes(items)
860
- const title = options.title ?? 'Superagent run report'
861
- const finished = items.filter(item => !ACTIVE_STATUSES.has(item.status)).length
862
- const windowText = items.length > 0 ? `${stampUtc(start)} → ${stampUtc(end)} UTC` : 'no runs'
863
-
864
- const events = items
865
- .filter(item => item.calls > 0)
866
- .map(item => ({ t: item.end, value: item.calls }))
867
- .sort((a, b) => a.t - b.t)
868
- const costEvents = items
869
- .filter(item => item.cost !== null && item.cost > 0)
870
- .map(item => ({ t: item.end, value: item.cost }))
871
- .sort((a, b) => a.t - b.t)
872
-
873
- const problemRuns = items
874
- .filter(item => ['failed', 'cancelled', 'interrupted', 'partial'].includes(item.status))
875
- .sort((a, b) => b.end - a.end)
876
-
877
- const statusCards = [
878
- card('Runs', String(items.length), `${finished} finished · ${items.length - finished} live`),
879
- card('Completed', String(summary.byStatus.completed ?? 0), `${summary.byStatus.partial ?? 0} partial`, '#15803d'),
880
- card('Failed', String(summary.byStatus.failed ?? 0), `${summary.byStatus.cancelled ?? 0} cancelled · ${summary.byStatus.interrupted ?? 0} interrupted`, '#b91c1c'),
881
- card('Model calls', formatCount(summary.calls), 'measured from child sessions'),
882
- card('Tokens', formatCount(summary.tokens), 'input + cache + output'),
883
- card(
884
- 'Cost',
885
- summary.priced === 0
886
- ? 'unpriced'
887
- : `${moneyOfMicros(summary.costMicros, summary.currency ?? 'USD')}${summary.unpriced > 0 ? '+' : ''}`,
888
- summary.priced === 0
889
- ? 'no configured price — not shown as zero'
890
- : `${summary.priced}/${items.length} runs priced${summary.mixedCurrency ? ' · mixed currencies' : ''}`,
891
- '#0f766e',
892
- ),
893
- ].join('')
894
-
895
- const cards = [
896
- '<section class="cards">',
897
- statusCards,
898
- '</section>',
899
- ].join('')
900
-
901
- const legend = [
902
- '<div class="legend">',
903
- `<span><i class="swatch" style="background:${STATUS_HEX.running}"></i> planning / running / aggregating</span>`,
904
- `<span><i class="swatch" style="background:${STATUS_HEX.completed}"></i> completed</span>`,
905
- `<span><i class="swatch" style="background:${STATUS_HEX.failed}"></i> failed</span>`,
906
- `<span><i class="swatch" style="background:${STATUS_HEX.cancelled}"></i> cancelled</span>`,
907
- `<span><i class="swatch" style="background:${STATUS_HEX.interrupted}"></i> interrupted</span>`,
908
- '<span><i class="swatch" style="background:#94a3b8;opacity:.38"></i> plan</span>',
909
- '<span><i class="swatch" style="background:#94a3b8"></i> work</span>',
910
- '<span><i class="swatch" style="background:#94a3b8;opacity:.66"></i> merge</span>',
911
- '</div>',
912
- ].join('')
913
-
914
- const failures = problemRuns.length === 0
915
- ? '<p class="hint">No failed, cancelled, interrupted, or partial runs in this window.</p>'
916
- : [
917
- '<div class="failures">',
918
- ...problemRuns.map(item => {
919
- const color = STATUS_HEX[item.status] ?? '#64748b'
920
- const detail = item.error
921
- ? escapeHtml(item.error)
922
- : item.status === 'cancelled'
923
- ? `Cancelled after ${escapeHtml(formatDuration(item.duration))}, ${escapeHtml(String(item.calls))} call(s) spent.`
924
- : item.status === 'interrupted'
925
- ? `The host went away after ${escapeHtml(formatDuration(item.duration))}; resume it with <code>superagent_resume</code>.`
926
- : `Ended after ${escapeHtml(formatDuration(item.duration))} without a recorded error.`
927
- return [
928
- `<div class="failure ${escapeHtml(item.status)}">`,
929
- `<div class="failure-head"><span class="chip" style="background:${color}">${escapeHtml(item.status.toUpperCase())}</span>`,
930
- `<span>${escapeHtml(item.id)}</span>`,
931
- `<span class="when">${escapeHtml(stampUtc(item.start))} UTC · ${escapeHtml(formatDuration(item.duration))}</span></div>`,
932
- `<div class="failure-body">${detail}</div>`,
933
- '</div>',
934
- ].join('')
935
- }),
936
- '</div>',
937
- ].join('')
938
-
939
- const rows = [...items].reverse().map(item => {
940
- const color = STATUS_HEX[item.status] ?? '#64748b'
941
- return [
942
- '<tr>',
943
- `<td class="id">${escapeHtml(item.id)}</td>`,
944
- `<td><span class="chip" style="background:${color}">${escapeHtml(item.status)}</span><span class="goal" title="${escapeHtml(item.goal)}">${escapeHtml(item.goal)}</span></td>`,
945
- `<td class="num">${escapeHtml(item.calls ? String(item.calls) : '—')}</td>`,
946
- `<td class="num">${escapeHtml(item.tokens ? formatCount(item.tokens) : '—')}</td>`,
947
- `<td class="num">${escapeHtml(item.costMicros === null ? 'unpriced' : moneyOfMicros(item.costMicros, item.currency))}</td>`,
948
- `<td class="num">${escapeHtml(formatDuration(item.duration))}</td>`,
949
- `<td class="id">${escapeHtml(item.parent.replace(/^session-/, '').slice(0, 8) || '—')}</td>`,
950
- '</tr>',
951
- ].join('')
952
- })
953
-
954
- // Subtask-level spend: only worker children own a subtask, so the planner and
955
- // the merge step appear in the run total but not here. Rows are emitted only
956
- // for subtasks that actually recorded a model call.
957
- const subtaskRows = items.flatMap(item => (item.subtasks ?? [])
958
- .filter(subtask => subtask?.usage?.modelCalls)
959
- .map(subtask => {
960
- const usage = subtask.usage
961
- const tokens = (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.outputTokens ?? 0)
962
- const cost = subtask.cost && Object.keys(subtask.cost.byModel ?? {}).length > 0 ? subtask.cost : null
963
- const costText = cost
964
- ? `${moneyOfMicros(
965
- Number.isFinite(cost.totalMicros) ? cost.totalMicros : Math.round((cost.total ?? 0) * 1e6),
966
- cost.currency ?? item.currency,
967
- )}${cost.complete ? '' : '+'}`
968
- : 'unpriced'
969
- return [
970
- '<tr>',
971
- `<td class="id">${escapeHtml(item.id)}</td>`,
972
- `<td class="num">${escapeHtml(String(subtask.index ?? '—'))}</td>`,
973
- `<td><span class="goal" title="${escapeHtml(subtask.title ?? '')}">${escapeHtml(subtask.title ?? '')}</span></td>`,
974
- `<td class="num">${escapeHtml(String(usage.modelCalls))}</td>`,
975
- `<td class="num">${escapeHtml(formatCount(tokens))}</td>`,
976
- `<td class="num">${escapeHtml(costText)}</td>`,
977
- '</tr>',
978
- ].join('')
979
- }))
980
-
981
- const pricedNote = items.length === 0
982
- ? 'No runs matched this window.'
983
- : summary.unpriced > 0
984
- ? `Cost covers ${summary.priced} of ${items.length} runs; models without a configured price are left out rather than estimated.`
985
- : `Cost covers all ${items.length} runs at the prices configured by the operator.`
986
-
987
- return `<!doctype html>
988
- <html lang="en">
989
- <head>
990
- <meta charset="utf-8">
991
- <meta name="viewport" content="width=device-width, initial-scale=1">
992
- <title>${escapeHtml(title)}</title>
993
- <style>${CSS}</style>
994
- </head>
995
- <body>
996
- <main class="page">
997
- <header class="masthead">
998
- <div class="eyebrow">dsh-superagent · run report</div>
999
- <h1>${escapeHtml(title)}</h1>
1000
- <p class="lede">${escapeHtml(options.subtitle ?? `${items.length} run${items.length === 1 ? '' : 's'} of model-planned parallel subtasks, rendered from the durable run store.`)}</p>
1001
- <div class="meta">${escapeHtml(windowText)} · generated ${escapeHtml(stampUtc(generatedAt))} UTC · peak concurrency ${laneCount} · ${formatCount(summary.calls)} model calls</div>
1002
- </header>
1003
- ${cards}
1004
- <section class="panel" id="timeline">
1005
- <div class="panel-head"><h2>Timeline</h2><span class="hint">one row per run · phases derived from subtask timestamps · ${escapeHtml(formatDuration(summary.span))} window</span></div>
1006
- ${legend}
1007
- <figure>${timelineSvg(items, { start, end, ticks })}</figure>
1008
- </section>
1009
- <section class="panel" id="lanes">
1010
- <div class="panel-head"><h2>Concurrency</h2><span class="hint">${laneCount} lane${laneCount === 1 ? '' : 's'} · overlapping runs never share a lane</span></div>
1011
- <figure>${lanesSvg(items, { start, end, ticks, lanes: laneCount })}</figure>
1012
- </section>
1013
- <section class="panel" id="retries">
1014
- <div class="panel-head"><h2>Failure &amp; retry chains</h2><span class="hint">which worker failed · attempts spent · what it ended as</span></div>
1015
- ${retriesSection(items)}
1016
- <p class="hint">A run file keeps the latest error per worker, so earlier attempts are counted but cannot quote their own message. A self-heal round resets a worker's attempt counter, which is why its steps describe the latest round.</p>
1017
- </section>
1018
- <div class="charts">
1019
- <section class="panel" id="calls">
1020
- <div class="panel-head"><h2>Model calls</h2><span class="hint">cumulative at each run's end</span></div>
1021
- <figure>${curveSvg(events, { start, end, ticks, color: '#0284c7', title: 'Cumulative model calls', empty: 'no model calls recorded' })}</figure>
1022
- <p class="hint">${escapeHtml(`${summary.calls} calls across ${items.length} run(s), measured from child session usage logs.`)}</p>
1023
- </section>
1024
- <section class="panel" id="cost">
1025
- <div class="panel-head"><h2>Cost</h2><span class="hint">cumulative at each run's end</span></div>
1026
- <figure>${curveSvg(costEvents, { start, end, ticks, color: '#0f766e', title: 'Cumulative cost', formatter: value => money(value, summary.currency ?? 'USD'), empty: 'no priced runs' })}</figure>
1027
- <p class="hint">${escapeHtml(pricedNote)}</p>
1028
- </section>
1029
- </div>
1030
- <section class="panel" id="workers">
1031
- <div class="panel-head"><h2>Worker time share</h2><span class="hint">each worker's span against the run's wall clock · bar = share of total worker time</span></div>
1032
- ${workersSection(items, now)}
1033
- </section>
1034
- <section class="panel" id="failures">
1035
- <div class="panel-head"><h2>Failures &amp; cancellations</h2><span class="hint">every run that did not complete normally</span></div>
1036
- ${failures}
1037
- </section>
1038
- <section class="panel" id="runs">
1039
- <div class="panel-head"><h2>Runs</h2><span class="hint">newest first · times in UTC</span></div>
1040
- <div class="table-wrap">
1041
- <table>
1042
- <thead><tr><th>Run</th><th>Status &amp; goal</th><th style="text-align:right">Calls</th><th style="text-align:right">Tokens</th><th style="text-align:right">Cost</th><th style="text-align:right">Duration</th><th>Parent</th></tr></thead>
1043
- <tbody>${rows.join('')}</tbody>
1044
- </table>
1045
- </div>
1046
- </section>
1047
- <section class="panel" id="subtasks">
1048
- <div class="panel-head"><h2>Subtask cost</h2><span class="hint">worker children only · planner and merge calls appear in the run total · a “+” marks an incomplete figure</span></div>
1049
- ${subtaskRows.length === 0
1050
- ? '<p class="hint">No subtask recorded a model call in this window.</p>'
1051
- : `<div class="table-wrap">
1052
- <table>
1053
- <thead><tr><th>Run</th><th style="text-align:right">#</th><th>Subtask</th><th style="text-align:right">Calls</th><th style="text-align:right">Tokens</th><th style="text-align:right">Cost</th></tr></thead>
1054
- <tbody>${subtaskRows.join('')}</tbody>
1055
- </table>
1056
- </div>`}
1057
- </section>
1058
- <footer>
1059
- Self-contained report: inline CSS and inline SVG, no scripts, no external fonts or images, no network access.
1060
- Phases are inferred from <code>startedAt</code>/<code>finishedAt</code> of the run and its subtasks; a run file does not record phase boundaries directly.
1061
- Cost is computed only from operator-configured prices — unpriced models are reported as unpriced, never as zero.
1062
- Generated by <code>dsh-superagent-report</code> from <code>${escapeHtml(items.length)}</code> run file(s).
1063
- </footer>
1064
- </main>
1065
- </body>
1066
- </html>
1067
- `
1068
- }
1
+ /**
2
+ * Static HTML report for dsh-superagent runs.
3
+ *
4
+ * `report` turns whatever is on disk into one file that can be mailed, attached
5
+ * to a README, or opened from a USB stick: inline CSS, inline SVG, no script,
6
+ * no font, no image, no network. The output is a pure string, so the layout is
7
+ * testable without a browser.
8
+ *
9
+ * The charts are hand-built SVG rather than a chart library for the same reason
10
+ * the watch panel is hand-built ANSI: the package ships zero runtime
11
+ * dependencies.
12
+ *
13
+ * @module dsh-superagent/report
14
+ */
15
+ import { formatMoney, moneyOfMicros } from './cost.js'
16
+ import { ACTIVE_STATUSES } from './store.js'
17
+ import { callsOf, formatCount, formatDuration } from './watch.js'
18
+
19
+ const STATUS_HEX = {
20
+ queued: '#64748b',
21
+ planning: '#0284c7',
22
+ running: '#0284c7',
23
+ aggregating: '#0284c7',
24
+ completed: '#15803d',
25
+ partial: '#b45309',
26
+ failed: '#b91c1c',
27
+ cancelled: '#7e22ce',
28
+ interrupted: '#c2410c',
29
+ }
30
+
31
+ const STATUS_ORDER = ['running', 'planning', 'aggregating', 'queued', 'completed', 'partial', 'failed', 'cancelled', 'interrupted']
32
+
33
+ /** Phase opacity inside a run bar: plan is fainter, merge is medium. */
34
+ const PHASE_OPACITY = { plan: 0.38, work: 1, merge: 0.66 }
35
+ const PHASE_LABEL = { plan: 'plan', work: 'work', merge: 'merge' }
36
+
37
+ const SVG_FONT = "-apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"
38
+ const MONO_FONT = "ui-monospace, SFMono-Regular, 'Cascadia Mono', Consolas, 'Liberation Mono', monospace"
39
+
40
+ /**
41
+ * Escape text for HTML text nodes and double-quoted attributes.
42
+ * @param {unknown} value - raw value.
43
+ */
44
+ export function escapeHtml(value) {
45
+ return String(value ?? '').replace(/[&<>"']/g, char => ({
46
+ '&': '&amp;',
47
+ '<': '&lt;',
48
+ '>': '&gt;',
49
+ '"': '&quot;',
50
+ "'": '&#39;',
51
+ }[char]))
52
+ }
53
+
54
+ /** Parse an ISO timestamp, or null when absent/unusable. */
55
+ function timeOf(value) {
56
+ const parsed = Date.parse(String(value ?? ''))
57
+ return Number.isFinite(parsed) ? parsed : null
58
+ }
59
+
60
+ /** `¥0.0225`, `$1.24`, `<¥0.0001`, or `—`. */
61
+ function money(value, currency) {
62
+ if (typeof value === 'number' && !Number.isFinite(value)) return '—'
63
+ if (value === null || value === undefined) return '—'
64
+ return formatMoney(value, currency)
65
+ }
66
+
67
+ /** `2026-11-14 07:52:05` in UTC, matching the axis. */
68
+ function stampUtc(ms) {
69
+ if (!Number.isFinite(ms)) return '—'
70
+ const iso = new Date(ms).toISOString()
71
+ return `${iso.slice(0, 10)} ${iso.slice(11, 19)}`
72
+ }
73
+
74
+ /** Axis label: seconds when the window is short, minute precision when long. */
75
+ function axisLabel(ms, span) {
76
+ const date = new Date(ms)
77
+ const hh = String(date.getUTCHours()).padStart(2, '0')
78
+ const mm = String(date.getUTCMinutes()).padStart(2, '0')
79
+ const ss = String(date.getUTCSeconds()).padStart(2, '0')
80
+ if (span > 24 * 3600_000) {
81
+ const mo = String(date.getUTCMonth() + 1).padStart(2, '0')
82
+ const dd = String(date.getUTCDate()).padStart(2, '0')
83
+ return `${mo}-${dd} ${hh}:${mm}`
84
+ }
85
+ return `${hh}:${mm}:${ss}`
86
+ }
87
+
88
+ /** Six-ish evenly spaced ticks that land on round wall-clock values. */
89
+ export function axisTicks(start, end) {
90
+ const span = Math.max(1, end - start)
91
+ const steps = [
92
+ 1000, 2000, 5000, 10_000, 15_000, 30_000,
93
+ 60_000, 120_000, 300_000, 600_000, 900_000, 1_800_000,
94
+ 3_600_000, 7_200_000, 21_600_000, 43_200_000, 86_400_000,
95
+ ]
96
+ const target = span / 6
97
+ const step = steps.find(candidate => candidate >= target) ?? steps[steps.length - 1]
98
+ const ticks = []
99
+ for (let tick = Math.ceil(start / step) * step; tick <= end; tick += step) ticks.push(tick)
100
+ // A window shorter than one step can contain no round boundary at all.
101
+ return { ticks: ticks.length > 0 ? ticks : [start, end], step }
102
+ }
103
+
104
+ /** Truncate to an approximate pixel width at the given font size. */
105
+ function clipTo(text, width, fontSize = 11) {
106
+ const value = String(text ?? '').replace(/\s+/g, ' ').trim()
107
+ const max = Math.max(1, Math.floor(width / (fontSize * 0.58)))
108
+ if (value.length <= max) return value
109
+ if (max <= 1) return '…'
110
+ return `${value.slice(0, max - 1)}…`
111
+ }
112
+
113
+ /** Short run id for a narrow block: the time stamp alone is ambiguous. */
114
+ function shortId(id) {
115
+ const value = String(id ?? '')
116
+ return value.length <= 12 ? value : `…${value.slice(-9)}`
117
+ }
118
+
119
+ /**
120
+ * Derive the three visible phases from recorded timestamps.
121
+ *
122
+ * The run file records status, not phase boundaries, so the boundaries come
123
+ * from the subtasks: planning ends when the first worker starts, work ends when
124
+ * the last worker reports, and merging covers the remainder. The report states
125
+ * this derivation in its footnote rather than implying the phases are exact.
126
+ *
127
+ * @param {object} run - run record.
128
+ * @param {number} now - wall clock for a run that has not finished.
129
+ */
130
+ export function phasesOf(run, now) {
131
+ const created = timeOf(run?.createdAt) ?? timeOf(run?.startedAt) ?? now
132
+ const started = timeOf(run?.startedAt) ?? created
133
+ const finished = timeOf(run?.finishedAt) ?? now
134
+ const subtasks = Array.isArray(run?.subtasks) ? run.subtasks : []
135
+ const starts = subtasks.map(subtask => timeOf(subtask.startedAt)).filter(value => value !== null)
136
+ const ends = subtasks.map(subtask => timeOf(subtask.finishedAt)).filter(value => value !== null)
137
+ const firstWork = starts.length > 0 ? Math.min(...starts) : started
138
+ const lastWork = ends.length > 0 ? Math.max(...ends) : (starts.length > 0 ? Math.min(...starts) : finished)
139
+ const planEnd = Math.min(Math.max(firstWork, started), finished)
140
+ const workEnd = Math.min(Math.max(lastWork, planEnd), finished)
141
+ return [
142
+ { kind: 'plan', start: started, end: planEnd },
143
+ { kind: 'work', start: planEnd, end: workEnd },
144
+ { kind: 'merge', start: workEnd, end: finished },
145
+ ].filter(phase => phase.end > phase.start)
146
+ }
147
+
148
+ /**
149
+ * Greedy interval-graph colouring: a run takes the first lane whose previous
150
+ * run has already ended, otherwise it opens a new lane. Two overlapping runs
151
+ * therefore never share a lane, and the lane count is the true peak
152
+ * concurrency of the selected window.
153
+ *
154
+ * @param {Array<{ start: number, end: number }>} items - spans, sorted by start.
155
+ * @returns {number} number of lanes used.
156
+ */
157
+ export function assignLanes(items) {
158
+ const laneEnds = []
159
+ for (const item of items) {
160
+ let lane = laneEnds.findIndex(end => end <= item.start)
161
+ if (lane === -1) {
162
+ lane = laneEnds.length
163
+ laneEnds.push(item.end)
164
+ } else {
165
+ laneEnds[lane] = item.end
166
+ }
167
+ item.lane = lane
168
+ }
169
+ return laneEnds.length
170
+ }
171
+
172
+ /** Worker colours, by subtask order; cycled when a run has more workers. */
173
+ const WORKER_COLORS = ['#0f766e', '#0284c7', '#7c3aed', '#b45309', '#be185d', '#15803d', '#475569', '#a16207']
174
+
175
+ /** `40%`, or `0.4%` for a sliver rather than a misleading `0%`. */
176
+ function percent(share) {
177
+ if (!Number.isFinite(share) || share <= 0) return '0%'
178
+ const value = share * 100
179
+ if (value < 1) return `${value.toFixed(1)}%`
180
+ return `${value.toFixed(0)}%`
181
+ }
182
+
183
+ /**
184
+ * Attempts recorded for one worker.
185
+ *
186
+ * A subtask that never started records zero; a worker that is about to run has
187
+ * not spent an attempt yet, so the value is clamped to at least one only when
188
+ * the caller is describing work that did happen.
189
+ *
190
+ * @param {object} subtask - worker record.
191
+ */
192
+ export function attemptsOf(subtask) {
193
+ return Math.max(0, Number(subtask?.attempts) || 0)
194
+ }
195
+
196
+ /**
197
+ * The causal chain for the workers that needed more than one attempt, or that
198
+ * ended in failure.
199
+ *
200
+ * The run file keeps one error per worker, not one per attempt, so a chain can
201
+ * say how many attempts were spent and what the last error was, but not what
202
+ * each earlier attempt said. The section states that limitation instead of
203
+ * inventing per-attempt text. A self-heal round resets the worker's counter, so
204
+ * its recorded attempts describe the latest round; the round itself is
205
+ * reported from `run.selfHeal`.
206
+ *
207
+ * @param {object} run - run record.
208
+ * @returns {Array<object>} one entry per retried or failed worker.
209
+ */
210
+ export function retryChainsOf(run) {
211
+ const subtasks = Array.isArray(run?.subtasks) ? run.subtasks : []
212
+ const cap = Math.max(1, Number(run?.limits?.attempts) || 1)
213
+ const chains = []
214
+ for (const subtask of subtasks) {
215
+ const attempts = attemptsOf(subtask)
216
+ const failed = subtask?.status === 'failed'
217
+ if (attempts < 2 && !(failed && attempts >= 1)) continue
218
+ chains.push({
219
+ index: Number(subtask.index) || chains.length + 1,
220
+ title: String(subtask.title ?? ''),
221
+ attempts: Math.max(1, attempts),
222
+ cap,
223
+ status: String(subtask.status ?? 'pending'),
224
+ error: String(subtask.error ?? ''),
225
+ stopReason: String(subtask.stopReason ?? ''),
226
+ recovered: subtask?.status === 'completed' && attempts > 1,
227
+ startedAt: timeOf(subtask.startedAt),
228
+ finishedAt: timeOf(subtask.finishedAt),
229
+ })
230
+ }
231
+ return chains
232
+ }
233
+
234
+ /**
235
+ * Wall-time share of every worker in a run.
236
+ *
237
+ * `share` is the worker's own span over the run's wall clock, so shares of
238
+ * parallel workers can add up to more than 100%; `parallelism` is that sum and
239
+ * is the run's effective worker concurrency. A worker still running counts to
240
+ * `now`.
241
+ *
242
+ * @param {{ duration: number, subtasks: object[] }} item - prepared run.
243
+ * @param {number} [now] - wall clock.
244
+ */
245
+ export function workerShares(item, now = Date.now()) {
246
+ const wall = Math.max(0, Number(item?.duration) || 0)
247
+ const workers = []
248
+ for (const subtask of item?.subtasks ?? []) {
249
+ const start = timeOf(subtask.startedAt)
250
+ if (start === null) continue
251
+ const end = timeOf(subtask.finishedAt) ?? (subtask.status === 'running' ? now : null)
252
+ const span = end === null ? 0 : Math.max(0, end - start)
253
+ workers.push({
254
+ index: Number(subtask.index) || workers.length + 1,
255
+ title: String(subtask.title ?? ''),
256
+ status: String(subtask.status ?? 'pending'),
257
+ attempts: attemptsOf(subtask),
258
+ span,
259
+ share: wall > 0 ? span / wall : 0,
260
+ })
261
+ }
262
+ const busy = workers.reduce((sum, worker) => sum + worker.span, 0)
263
+ return { wall, workers, busy, parallelism: wall > 0 ? busy / wall : 0 }
264
+ }
265
+
266
+ /**
267
+ * Normalise run files into what the page needs, in chronological order.
268
+ * @param {object[]} runs - run records from the store.
269
+ * @param {number} now - wall clock.
270
+ */
271
+ export function prepare(runs, now) {
272
+ const items = []
273
+ for (const run of runs ?? []) {
274
+ if (!run || !run.id) continue
275
+ const start = timeOf(run.startedAt) ?? timeOf(run.createdAt) ?? now
276
+ const end = timeOf(run.finishedAt) ?? now
277
+ const live = ACTIVE_STATUSES.has(run.status)
278
+ const phases = phasesOf(run, now)
279
+ const calls = callsOf(run)
280
+ const priced = run.cost && run.cost.complete !== false
281
+ const cost = priced && Number.isFinite(run.cost?.total) ? run.cost.total : null
282
+ const costMicros = priced
283
+ ? (Number.isFinite(run.cost?.totalMicros) ? run.cost.totalMicros : Math.round((run.cost.total ?? 0) * 1e6))
284
+ : null
285
+ items.push({
286
+ run,
287
+ id: String(run.id),
288
+ status: String(run.status ?? 'unknown'),
289
+ start,
290
+ end: Math.max(end, start),
291
+ live,
292
+ phases,
293
+ calls,
294
+ cost,
295
+ costMicros,
296
+ currency: run.cost?.currency ?? 'USD',
297
+ tokens: run.usage?.totalTokens ?? 0,
298
+ duration: Math.max(0, end - start),
299
+ parent: String(run.parentSessionId ?? ''),
300
+ goal: String(run.goal ?? ''),
301
+ error: String(run.error ?? ''),
302
+ subtasks: Array.isArray(run.subtasks) ? run.subtasks : [],
303
+ })
304
+ }
305
+ items.sort((a, b) => a.start - b.start || a.id.localeCompare(b.id))
306
+ return items
307
+ }
308
+
309
+ /** Totals used by the cards and the one-line summary. */
310
+ function summarize(items) {
311
+ const byStatus = {}
312
+ let calls = 0
313
+ let tokens = 0
314
+ // Integer micro-units: a long list of runs must not drift the cent total.
315
+ let costMicros = 0
316
+ let priced = 0
317
+ let unpriced = 0
318
+ const currencies = new Set()
319
+ for (const item of items) {
320
+ byStatus[item.status] = (byStatus[item.status] ?? 0) + 1
321
+ calls += item.calls
322
+ tokens += item.tokens
323
+ if (item.costMicros !== null) {
324
+ costMicros += item.costMicros
325
+ priced += 1
326
+ currencies.add(item.currency)
327
+ } else if (item.calls > 0) {
328
+ unpriced += 1
329
+ }
330
+ }
331
+ const start = items.length > 0 ? Math.min(...items.map(item => item.start)) : 0
332
+ const end = items.length > 0 ? Math.max(...items.map(item => item.end)) : 0
333
+ const currency = currencies.size === 1 ? [...currencies][0] : (currencies.size === 0 ? 'USD' : null)
334
+ return {
335
+ byStatus,
336
+ calls,
337
+ tokens,
338
+ cost: costMicros / 1e6,
339
+ costMicros,
340
+ currency,
341
+ mixedCurrency: currencies.size > 1,
342
+ priced,
343
+ unpriced,
344
+ start,
345
+ end,
346
+ span: Math.max(0, end - start),
347
+ }
348
+ }
349
+
350
+ /**
351
+ * Timeline: one row per run, a bar split into plan/work/merge, and an explicit
352
+ * marker for the runs that did not complete, because a flat bar alone hides
353
+ * whether an early end was success or damage.
354
+ */
355
+ function timelineSvg(items, options) {
356
+ const width = 1240
357
+ const left = 292
358
+ // The right edge is reserved for the outcome marker, so a run that ends at
359
+ // the very last instant still has room for "✕ failed" instead of silently
360
+ // losing the annotation.
361
+ const right = 176
362
+ const top = 54
363
+ const rowHeight = 30
364
+ const height = top + items.length * rowHeight + 26
365
+ const start = options.start
366
+ const end = options.end
367
+ const span = Math.max(1, end - start)
368
+ const track = width - left - right
369
+ const x = time => left + ((time - start) / span) * track
370
+ const { ticks } = options
371
+ const parts = []
372
+
373
+ parts.push(`<svg viewBox="0 0 ${width} ${height}" role="img" aria-labelledby="timeline-title timeline-desc">`)
374
+ parts.push('<title id="timeline-title">Run timeline</title>')
375
+ parts.push(`<desc id="timeline-desc">${escapeHtml(`${items.length} runs from ${stampUtc(start)} to ${stampUtc(end)} UTC, each bar split into planning, work, and merge phases.`)}</desc>`)
376
+
377
+ for (const tick of ticks) {
378
+ const gx = x(tick).toFixed(1)
379
+ parts.push(`<line x1="${gx}" y1="${top - 18}" x2="${gx}" y2="${height - 20}" stroke="#eef1f5" stroke-width="1"/>`)
380
+ parts.push(`<text x="${gx}" y="${top - 26}" text-anchor="middle" class="axis" fill="#94a3b8">${escapeHtml(axisLabel(tick, span))}</text>`)
381
+ }
382
+
383
+ items.forEach((item, index) => {
384
+ const y = top + index * rowHeight
385
+ const color = STATUS_HEX[item.status] ?? '#64748b'
386
+ if (index % 2 === 1) {
387
+ parts.push(`<rect x="8" y="${y}" width="${width - 16}" height="${rowHeight - 1}" rx="4" fill="#fbfcfe"/>`)
388
+ }
389
+ parts.push(`<line x1="16" y1="${y + rowHeight - 0.5}" x2="${width - 16}" y2="${y + rowHeight - 0.5}" stroke="#f1f5f9" stroke-width="1"/>`)
390
+ parts.push(`<text x="16" y="${y + 13}" class="id" fill="#0f172a">${escapeHtml(item.id)}</text>`)
391
+ parts.push(`<text x="16" y="${y + 25}" class="meta" fill="${color}">${escapeHtml(item.status.toUpperCase())} · ${escapeHtml(formatDuration(item.duration))}</text>`)
392
+
393
+ const phases = item.phases.length > 0
394
+ ? item.phases
395
+ // A run that started and ended in the same millisecond has no positive
396
+ // span to draw; keep a tick so the row is not silently blank.
397
+ : [{ kind: 'work', start: item.start, end: item.start }]
398
+ for (const phase of phases) {
399
+ const px = x(phase.start)
400
+ // A sub-second run on a multi-hour axis is a hairline. Give it three
401
+ // pixels so it stays visible and clickable instead of disappearing.
402
+ const pw = Math.max(3, x(phase.end) - px)
403
+ const opacity = PHASE_OPACITY[phase.kind] ?? 0.6
404
+ parts.push(`<rect x="${px.toFixed(1)}" y="${y + 6}" width="${pw.toFixed(1)}" height="11" rx="3" fill="${color}" opacity="${opacity}"><title>${escapeHtml(`${PHASE_LABEL[phase.kind]} · ${formatDuration(phase.end - phase.start)}`)}</title></rect>`)
405
+ }
406
+
407
+ // Subtask boundaries inside the work phase: a thin white notch is enough
408
+ // to show whether workers overlapped or ran one after another.
409
+ const notches = new Set()
410
+ for (const subtask of item.subtasks) {
411
+ for (const edge of [timeOf(subtask.startedAt), timeOf(subtask.finishedAt)]) {
412
+ if (edge !== null) notches.add(edge)
413
+ }
414
+ }
415
+ for (const notch of notches) {
416
+ if (notch <= start || notch >= end) continue
417
+ const nx = x(notch)
418
+ const barStart = x(item.start)
419
+ const barEnd = x(item.end)
420
+ if (nx <= barStart + 2 || nx >= barEnd - 2) continue
421
+ parts.push(`<line x1="${nx.toFixed(1)}" y1="${y + 7}" x2="${nx.toFixed(1)}" y2="${y + 16}" stroke="#ffffff" stroke-width="1" opacity="0.55"/>`)
422
+ }
423
+
424
+ if (item.live) {
425
+ parts.push(`<line x1="${(x(item.end) + 3).toFixed(1)}" y1="${y + 5}" x2="${(x(item.end) + 3).toFixed(1)}" y2="${y + 18}" stroke="${color}" stroke-width="2" stroke-dasharray="2 2"/>`)
426
+ }
427
+
428
+ const markers = {
429
+ failed: '✕ failed',
430
+ cancelled: '⊘ cancelled',
431
+ interrupted: '! interrupted',
432
+ partial: '△ partial',
433
+ }
434
+ const marker = markers[item.status]
435
+ if (marker) {
436
+ const available = width - 16 - (x(item.end) + 8)
437
+ parts.push(`<text x="${(x(item.end) + 8).toFixed(1)}" y="${y + 15}" class="mark" fill="${color}">${escapeHtml(clipTo(marker, Math.max(40, available), 10))}</text>`)
438
+ }
439
+ })
440
+
441
+ parts.push('</svg>')
442
+ return parts.join('')
443
+ }
444
+
445
+ /**
446
+ * Swimlanes: the same runs placed on the minimum number of lanes so that
447
+ * overlaps are visible as horizontal neighbours instead of hidden in a
448
+ * chronological list.
449
+ */
450
+ function lanesSvg(items, options) {
451
+ const lanes = options.lanes
452
+ const laneHeight = 40
453
+ const width = 1240
454
+ const left = 92
455
+ const right = 48
456
+ const top = 44
457
+ const height = top + Math.max(1, lanes) * laneHeight + 34
458
+ const start = options.start
459
+ const end = options.end
460
+ const span = Math.max(1, end - start)
461
+ const track = width - left - right
462
+ const x = time => left + ((time - start) / span) * track
463
+ const parts = []
464
+
465
+ parts.push(`<svg viewBox="0 0 ${width} ${height}" role="img" aria-labelledby="lanes-title lanes-desc">`)
466
+ parts.push('<title id="lanes-title">Concurrency swimlanes</title>')
467
+ parts.push(`<desc id="lanes-desc">${escapeHtml(`Runs placed on ${lanes} lane${lanes === 1 ? '' : 's'}; overlapping runs never share a lane, so the lane count is the peak concurrency.`)}</desc>`)
468
+
469
+ for (let lane = 0; lane < Math.max(1, lanes); lane++) {
470
+ const y = top + lane * laneHeight
471
+ parts.push(`<rect x="${left}" y="${y + 5}" width="${track}" height="${laneHeight - 10}" rx="6" fill="#f8fafc"/>`)
472
+ parts.push(`<text x="${left - 12}" y="${y + laneHeight / 2 + 4}" text-anchor="end" class="axis" fill="#94a3b8">lane ${lane + 1}</text>`)
473
+ }
474
+
475
+ for (const tick of options.ticks) {
476
+ const gx = x(tick).toFixed(1)
477
+ parts.push(`<line x1="${gx}" y1="${top}" x2="${gx}" y2="${height - 26}" stroke="#eef1f5" stroke-width="1"/>`)
478
+ parts.push(`<text x="${gx}" y="${height - 10}" text-anchor="middle" class="axis" fill="#94a3b8">${escapeHtml(axisLabel(tick, span))}</text>`)
479
+ }
480
+
481
+ for (const item of items) {
482
+ const color = STATUS_HEX[item.status] ?? '#64748b'
483
+ const y = top + item.lane * laneHeight + 9
484
+ const bx = x(item.start)
485
+ const bw = Math.max(4, x(item.end) - bx)
486
+ parts.push(`<rect x="${bx.toFixed(1)}" y="${y}" width="${bw.toFixed(1)}" height="${laneHeight - 18}" rx="4" fill="${color}" opacity="${item.live ? 0.55 : 0.88}"><title>${escapeHtml(`${item.id} · ${item.status} · ${formatDuration(item.duration)}`)}</title></rect>`)
487
+ if (bw > 74) {
488
+ parts.push(`<text x="${(bx + 7).toFixed(1)}" y="${y + 14}" class="lane-label" fill="#ffffff">${escapeHtml(shortId(item.id))}</text>`)
489
+ }
490
+ }
491
+
492
+ parts.push('</svg>')
493
+ return parts.join('')
494
+ }
495
+
496
+ /** Round a value up to a 1/2/5 × 10^n axis maximum. */
497
+ function niceMax(value) {
498
+ if (!Number.isFinite(value) || value <= 0) return 1
499
+ const power = 10 ** Math.floor(Math.log10(value))
500
+ const scaled = value / power
501
+ const factor = scaled <= 1 ? 1 : scaled <= 2 ? 2 : scaled <= 5 ? 5 : 10
502
+ return factor * power
503
+ }
504
+
505
+ /**
506
+ * Cumulative step chart. Events land at each run's end time, so the curve
507
+ * answers "how much had this window spent by 09:15?" without pretending to
508
+ * know the intra-run shape that the run files do not record.
509
+ *
510
+ * @param {Array<{ t: number, value: number }>} events - sorted by time.
511
+ * @param {{ start: number, end: number, color: string, ticks: number[], formatter?: (value: number) => string, empty?: string, title: string }} options
512
+ */
513
+ function curveSvg(events, options) {
514
+ const width = 620
515
+ const height = 220
516
+ const left = 58
517
+ const right = 16
518
+ const top = 20
519
+ const bottom = 38
520
+ const plotW = width - left - right
521
+ const plotH = height - top - bottom
522
+ const start = options.start
523
+ const end = options.end
524
+ const span = Math.max(1, end - start)
525
+ const x = time => left + ((time - start) / span) * plotW
526
+ const eventsWithValue = events.filter(event => Number.isFinite(event.value))
527
+ const total = eventsWithValue.reduce((sum, event) => sum + event.value, 0)
528
+ const max = niceMax(total)
529
+ const y = value => top + plotH - (value / max) * plotH
530
+ const format = options.formatter ?? (value => formatCount(value))
531
+ const parts = []
532
+
533
+ parts.push(`<svg viewBox="0 0 ${width} ${height}" role="img" aria-label="${escapeHtml(options.title)}">`)
534
+ parts.push(`<rect x="${left}" y="${top}" width="${plotW}" height="${plotH}" fill="#f8fafc" rx="6"/>`)
535
+
536
+ for (let index = 0; index <= 4; index++) {
537
+ const value = (max / 4) * index
538
+ const gy = y(value).toFixed(1)
539
+ parts.push(`<line x1="${left}" y1="${gy}" x2="${left + plotW}" y2="${gy}" stroke="#e8edf3" stroke-width="1"/>`)
540
+ parts.push(`<text x="${left - 10}" y="${Number(gy) + 4}" text-anchor="end" class="axis" fill="#94a3b8">${escapeHtml(format(value))}</text>`)
541
+ }
542
+
543
+ for (const tick of options.ticks) {
544
+ const gx = x(tick).toFixed(1)
545
+ parts.push(`<line x1="${gx}" y1="${top}" x2="${gx}" y2="${top + plotH}" stroke="#eef1f5" stroke-width="1"/>`)
546
+ parts.push(`<text x="${gx}" y="${height - 12}" text-anchor="middle" class="axis" fill="#94a3b8">${escapeHtml(axisLabel(tick, span))}</text>`)
547
+ }
548
+
549
+ if (eventsWithValue.length === 0) {
550
+ parts.push(`<text x="${(left + plotW / 2).toFixed(1)}" y="${(top + plotH / 2).toFixed(1)}" text-anchor="middle" class="empty">${escapeHtml(options.empty ?? 'no data')}</text>`)
551
+ parts.push('</svg>')
552
+ return parts.join('')
553
+ }
554
+
555
+ let cursor = 0
556
+ let path = `M ${x(start).toFixed(1)} ${y(0).toFixed(1)}`
557
+ for (const event of eventsWithValue) {
558
+ cursor += event.value
559
+ path += ` H ${x(event.t).toFixed(1)} V ${y(cursor).toFixed(1)}`
560
+ }
561
+ path += ` H ${x(end).toFixed(1)}`
562
+
563
+ parts.push(`<path d="${path} V ${y(0).toFixed(1)} H ${x(start).toFixed(1)} Z" fill="${options.color}" opacity="0.10"/>`)
564
+ parts.push(`<path d="${path}" fill="none" stroke="${options.color}" stroke-width="2" stroke-linejoin="round"/>`)
565
+
566
+ let running = 0
567
+ for (const event of eventsWithValue) {
568
+ running += event.value
569
+ parts.push(`<circle cx="${x(event.t).toFixed(1)}" cy="${y(running).toFixed(1)}" r="3" fill="#ffffff" stroke="${options.color}" stroke-width="2"><title>${escapeHtml(`${stampUtc(event.t)} · ${format(event.value)} (total ${format(running)})`)}</title></circle>`)
570
+ }
571
+
572
+ parts.push('</svg>')
573
+ return parts.join('')
574
+ }
575
+
576
+ /** Outcome word and symbol for the last recorded attempt of a worker. */
577
+ function outcomeOf(chain) {
578
+ if (chain.status === 'completed') return { symbol: '✓', tone: 'ok', text: chain.recovered ? `recovered on attempt ${chain.attempts}` : 'completed' }
579
+ if (chain.status === 'failed') return { symbol: '✕', tone: 'bad', text: `failed after ${chain.attempts} attempt${chain.attempts === 1 ? '' : 's'}` }
580
+ if (chain.status === 'running') return { symbol: '▶', tone: 'live', text: `running · attempt ${chain.attempts}` }
581
+ return { symbol: '…', tone: 'idle', text: `still open · ${chain.attempts} attempt${chain.attempts === 1 ? '' : 's'} spent` }
582
+ }
583
+
584
+ /**
585
+ * Failure and retry chains: which worker failed, how many attempts it burned,
586
+ * and what it ended as. Only runs that actually retried or failed are listed,
587
+ * so a healthy window says so in one line instead of drawing empty boxes.
588
+ */
589
+ function retriesSection(items) {
590
+ const blocks = []
591
+ for (const item of [...items].sort((a, b) => b.end - a.end)) {
592
+ const chains = retryChainsOf(item.run)
593
+ const heal = item.run?.selfHeal
594
+ if (chains.length === 0 && !heal) continue
595
+ const attempts = chains.reduce((sum, chain) => sum + chain.attempts, 0)
596
+ const color = STATUS_HEX[item.status] ?? '#64748b'
597
+ blocks.push([
598
+ '<article class="retry">',
599
+ '<div class="retry-head">',
600
+ `<span class="chip" style="background:${color}">${escapeHtml(item.status.toUpperCase())}</span>`,
601
+ `<span class="rid">${escapeHtml(item.id)}</span>`,
602
+ `<span class="when">${escapeHtml(stampUtc(item.start))} UTC · ${escapeHtml(formatDuration(item.duration))}</span>`,
603
+ `<span class="tally">${chains.length} worker${chains.length === 1 ? '' : 's'} · ${attempts} attempt${attempts === 1 ? '' : 's'}</span>`,
604
+ '</div>',
605
+ heal
606
+ ? `<div class="selfheal">self-heal round ${escapeHtml(String(heal.rounds ?? 1))} · retried ${escapeHtml(String(heal.retried ?? 0))} · recovered ${escapeHtml(String(heal.recovered ?? 0))}${heal.model ? ` · on <code>${escapeHtml(heal.model)}</code>` : ''}</div>`
607
+ : '',
608
+ item.run?.recovery?.previousStatus
609
+ ? `<div class="selfheal">resumed after an earlier <code>${escapeHtml(String(item.run.recovery.previousStatus))}</code> attempt</div>`
610
+ : '',
611
+ ...chains.map(chain => {
612
+ const outcome = outcomeOf(chain)
613
+ const steps = []
614
+ for (let attempt = 1; attempt <= chain.attempts; attempt++) {
615
+ const last = attempt === chain.attempts
616
+ const tone = last ? outcome.tone : 'bad'
617
+ steps.push(`<span class="step ${tone}">${attempt} ${last ? outcome.symbol : '✕'}</span>`)
618
+ }
619
+ return [
620
+ '<div class="retry-worker">',
621
+ `<div class="worker-head"><span class="widx">#${escapeHtml(String(chain.index))}</span> ${escapeHtml(chain.title)}`,
622
+ `<span class="outcome ${outcome.tone}">${escapeHtml(outcome.text)}</span></div>`,
623
+ `<div class="chain">${steps.join('<span class="arrow">→</span>')}</div>`,
624
+ chain.error
625
+ ? `<div class="worker-error"><code>${escapeHtml(chain.error)}</code></div>`
626
+ : chain.stopReason
627
+ ? `<div class="worker-error">child stopped with reason <code>${escapeHtml(chain.stopReason)}</code></div>`
628
+ : '',
629
+ '</div>',
630
+ ].join('')
631
+ }),
632
+ '</article>',
633
+ ].join(''))
634
+ if (blocks.length === 12) break
635
+ }
636
+
637
+ if (blocks.length === 0) {
638
+ return '<p class="hint">No retries and no failed workers in this window: every started worker finished on its first attempt.</p>'
639
+ }
640
+ const note = blocks.length > 0 && items.length > blocks.length
641
+ ? `<p class="hint">Showing the ${blocks.length} most recent runs with retries or failures.</p>`
642
+ : ''
643
+ return `<div class="retries">${blocks.join('')}</div>${note}`
644
+ }
645
+
646
+ /**
647
+ * Worker time share: how the run's wall clock was distributed across its
648
+ * workers. Shares are per worker against the run's wall clock, so parallel
649
+ * workers add up past 100%; the parallelism factor is that sum.
650
+ */
651
+ function workersSection(items, now) {
652
+ const rows = []
653
+ for (const item of [...items].sort((a, b) => b.duration - a.duration)) {
654
+ const shares = workerShares(item, now)
655
+ if (shares.workers.length === 0) continue
656
+ const color = STATUS_HEX[item.status] ?? '#64748b'
657
+ const segments = []
658
+ let cursor = 0
659
+ shares.workers.forEach((worker, index) => {
660
+ const wx = shares.busy > 0 ? (worker.span / shares.busy) * 1080 : 0
661
+ const fill = WORKER_COLORS[index % WORKER_COLORS.length]
662
+ if (wx > 0) {
663
+ segments.push(`<rect x="${cursor.toFixed(1)}" y="4" width="${Math.max(1, wx).toFixed(1)}" height="18" rx="3" fill="${fill}"><title>${escapeHtml(`${worker.title} · ${formatDuration(worker.span)} · ${percent(worker.share)} of the run's wall clock`)}</title></rect>`)
664
+ }
665
+ cursor += wx
666
+ })
667
+ const listed = shares.workers.slice(0, 6)
668
+ const rest = shares.workers.length - listed.length
669
+ rows.push([
670
+ '<div class="workers-run">',
671
+ '<div class="workers-head">',
672
+ `<span class="chip" style="background:${color}">${escapeHtml(item.status)}</span>`,
673
+ `<span class="rid">${escapeHtml(item.id)}</span>`,
674
+ `<span class="when">wall ${escapeHtml(formatDuration(shares.wall))} · workers busy ${escapeHtml(formatDuration(shares.busy))} · ${shares.parallelism.toFixed(2)}× parallel</span>`,
675
+ '</div>',
676
+ `<svg viewBox="0 0 1080 26" role="img" aria-label="${escapeHtml(`${shares.workers.length} workers of ${item.id} by share of total worker time`)}">`,
677
+ '<rect x="0" y="4" width="1080" height="18" rx="6" fill="#f1f5f9"/>',
678
+ segments.join(''),
679
+ '</svg>',
680
+ '<ul class="worker-list">',
681
+ ...listed.map((worker, index) => {
682
+ const fill = WORKER_COLORS[index % WORKER_COLORS.length]
683
+ const outcome = worker.status === 'completed' ? 'done' : worker.status === 'failed' ? 'failed' : worker.status
684
+ return [
685
+ '<li>',
686
+ `<i class="swatch" style="background:${fill}"></i>`,
687
+ `<span class="wtitle">#${escapeHtml(String(worker.index))} ${escapeHtml(worker.title)}</span>`,
688
+ `<span class="wmeta">${escapeHtml(outcome)}${worker.attempts > 1 ? ` · ${escapeHtml(String(worker.attempts))} attempts` : ''} · ${escapeHtml(formatDuration(worker.span))} · ${escapeHtml(percent(worker.share))}</span>`,
689
+ '</li>',
690
+ ].join('')
691
+ }),
692
+ rest > 0 ? `<li class="more">+${rest} more worker${rest === 1 ? '' : 's'} in the bar above</li>` : '',
693
+ '</ul>',
694
+ '</div>',
695
+ ].join(''))
696
+ if (rows.length === 10) break
697
+ }
698
+
699
+ if (rows.length === 0) {
700
+ return '<p class="hint">No worker timings recorded: these runs never started a subtask, or their subtasks carry no <code>startedAt</code>.</p>'
701
+ }
702
+ return `<div class="workers">${rows.join('')}</div>`
703
+ }
704
+
705
+ /** One stat card. */
706
+ function card(label, value, note, accent) {
707
+ return [
708
+ '<div class="card">',
709
+ `<div class="card-label">${escapeHtml(label)}</div>`,
710
+ `<div class="card-value"${accent ? ` style="color:${accent}"` : ''}>${escapeHtml(value)}</div>`,
711
+ `<div class="card-note">${escapeHtml(note)}</div>`,
712
+ '</div>',
713
+ ].join('')
714
+ }
715
+
716
+ const CSS = `
717
+ :root {
718
+ color-scheme: light;
719
+ --ink: #0f172a;
720
+ --muted: #64748b;
721
+ --line: #e5e9f0;
722
+ --card: #ffffff;
723
+ --accent: #0f766e;
724
+ }
725
+ * { box-sizing: border-box; }
726
+ html, body { margin: 0; padding: 0; }
727
+ body {
728
+ background: #f4f6fa;
729
+ background-image: radial-gradient(900px 420px at 12% -8%, #e6f2f1 0%, rgba(230,242,241,0) 70%),
730
+ radial-gradient(760px 380px at 96% 4%, #eef0fb 0%, rgba(238,240,251,0) 66%);
731
+ color: var(--ink);
732
+ font: 14px/1.55 ${SVG_FONT};
733
+ -webkit-font-smoothing: antialiased;
734
+ }
735
+ .page { max-width: 1280px; margin: 0 auto; padding: 44px 32px 64px; }
736
+ .masthead { margin-bottom: 26px; }
737
+ .eyebrow {
738
+ font: 600 11px/1 ${MONO_FONT};
739
+ letter-spacing: .14em;
740
+ text-transform: uppercase;
741
+ color: var(--accent);
742
+ }
743
+ h1 { font-size: 34px; line-height: 1.15; letter-spacing: -.02em; margin: 12px 0 8px; }
744
+ .lede { margin: 0; max-width: 760px; color: #475569; font-size: 15px; }
745
+ .meta { margin-top: 14px; font: 12px/1.5 ${MONO_FONT}; color: #7c8899; }
746
+ .cards { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 12px; margin: 26px 0 22px; }
747
+ .card { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px 13px; box-shadow: 0 1px 2px rgba(15,23,42,.04); }
748
+ .card-label { font: 600 10px/1 ${MONO_FONT}; letter-spacing: .12em; text-transform: uppercase; color: #8b98a9; }
749
+ .card-value { font-size: 26px; font-weight: 650; letter-spacing: -.02em; margin: 9px 0 4px; font-variant-numeric: tabular-nums; }
750
+ .card-note { font-size: 11.5px; color: var(--muted); }
751
+ .panel { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 20px 22px 16px; margin-bottom: 18px; box-shadow: 0 1px 2px rgba(15,23,42,.04); }
752
+ .panel-head { display: flex; align-items: baseline; justify-content: space-between; gap: 18px; margin-bottom: 10px; flex-wrap: wrap; }
753
+ .panel h2 { font-size: 15px; letter-spacing: -.01em; margin: 0; }
754
+ .panel .hint { font-size: 12px; color: var(--muted); }
755
+ .legend { display: flex; gap: 16px; flex-wrap: wrap; font-size: 11.5px; color: #5b6b7f; margin: 4px 0 6px; }
756
+ .legend span { display: inline-flex; align-items: center; gap: 6px; }
757
+ .swatch { width: 10px; height: 10px; border-radius: 3px; display: inline-block; }
758
+ figure { margin: 0; overflow-x: auto; }
759
+ svg { display: block; width: 100%; height: auto; min-width: 720px; }
760
+ svg text { font-family: ${SVG_FONT}; }
761
+ svg .axis { font-family: ${MONO_FONT}; font-size: 10px; }
762
+ svg .id { font-family: ${MONO_FONT}; font-size: 11px; font-weight: 600; }
763
+ svg .meta { font-family: ${MONO_FONT}; font-size: 9.5px; letter-spacing: .04em; }
764
+ svg .mark { font-size: 10px; font-weight: 600; }
765
+ svg .lane-label { font-family: ${MONO_FONT}; font-size: 9.5px; }
766
+ svg .empty { font-size: 12px; fill: #94a3b8; }
767
+ .charts { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
768
+ .charts .panel { margin-bottom: 18px; }
769
+ .charts svg { min-width: 0; }
770
+ .failures { display: grid; gap: 10px; }
771
+ .failure { border: 1px solid var(--line); border-left: 3px solid #b91c1c; border-radius: 8px; padding: 10px 13px; background: #fff; }
772
+ .failure.cancelled { border-left-color: #7e22ce; }
773
+ .failure.interrupted { border-left-color: #c2410c; }
774
+ .failure.partial { border-left-color: #b45309; }
775
+ .failure-head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font: 600 11.5px/1.4 ${MONO_FONT}; }
776
+ .failure-head .chip { font-size: 9.5px; letter-spacing: .06em; padding: 2px 7px; border-radius: 999px; color: #fff; }
777
+ .failure-body { margin-top: 6px; font-size: 12.5px; color: #475569; }
778
+ .failure-body code { font-family: ${MONO_FONT}; font-size: 11.5px; background: #f4f6fa; padding: 1px 5px; border-radius: 4px; }
779
+ .failure .when { color: #8b98a9; font-weight: 400; }
780
+ .retries { display: grid; gap: 12px; }
781
+ .retry { border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; background: #fff; }
782
+ .retry-head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font: 600 11.5px/1.4 ${MONO_FONT}; }
783
+ .retry-head .when, .retry-head .tally { color: #8b98a9; font-weight: 400; }
784
+ .selfheal { margin-top: 9px; font-size: 12px; color: #475569; border-left: 3px solid #b45309; padding: 2px 0 2px 9px; }
785
+ .selfheal code { font-family: ${MONO_FONT}; font-size: 11.5px; background: #f4f6fa; padding: 1px 5px; border-radius: 4px; }
786
+ .retry-worker { margin-top: 10px; padding-top: 10px; border-top: 1px dashed #eef1f5; }
787
+ .worker-head { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: #1e293b; flex-wrap: wrap; }
788
+ .worker-head .widx { font: 600 10.5px ${MONO_FONT}; color: #8b98a9; }
789
+ .worker-head .outcome { font: 600 10px ${MONO_FONT}; letter-spacing: .04em; padding: 2px 7px; border-radius: 999px; }
790
+ .outcome.ok { color: #15803d; background: #dcfce7; }
791
+ .outcome.bad { color: #b91c1c; background: #fee2e2; }
792
+ .outcome.live { color: #0284c7; background: #e0f2fe; }
793
+ .outcome.idle { color: #b45309; background: #fef3c7; }
794
+ .chain { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-top: 9px; }
795
+ .step { font: 600 11px ${MONO_FONT}; padding: 3px 9px; border-radius: 6px; border: 1px solid transparent; }
796
+ .step.ok { color: #15803d; background: #f0fdf4; border-color: #bbf7d0; }
797
+ .step.bad { color: #b91c1c; background: #fef2f2; border-color: #fecaca; }
798
+ .step.live { color: #0284c7; background: #f0f9ff; border-color: #bae6fd; }
799
+ .step.idle { color: #b45309; background: #fffbeb; border-color: #fde68a; }
800
+ .arrow { color: #cbd5e1; font-size: 12px; }
801
+ .worker-error { margin-top: 7px; font-size: 12px; color: #475569; }
802
+ .worker-error code { font-family: ${MONO_FONT}; font-size: 11.5px; background: #fef2f2; color: #991b1b; padding: 1px 5px; border-radius: 4px; }
803
+ .workers { display: grid; gap: 16px; }
804
+ .workers-run { border-top: 1px solid #f1f4f8; padding-top: 12px; }
805
+ .workers-run:first-child { border-top: 0; padding-top: 0; }
806
+ .workers-head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font: 600 11.5px/1.4 ${MONO_FONT}; margin-bottom: 8px; }
807
+ .workers-head .when { color: #8b98a9; font-weight: 400; }
808
+ .workers svg { min-width: 0; }
809
+ .worker-list { list-style: none; margin: 10px 0 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(290px, 1fr)); gap: 5px 20px; }
810
+ .worker-list li { display: flex; align-items: center; gap: 7px; font-size: 12px; color: #334155; min-width: 0; }
811
+ .worker-list .wtitle { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
812
+ .worker-list .wmeta { margin-left: auto; color: #8b98a9; font: 11px ${MONO_FONT}; white-space: nowrap; }
813
+ .worker-list .more { color: #8b98a9; font-size: 11.5px; }
814
+ .table-wrap { overflow-x: auto; }
815
+ table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
816
+ th { text-align: left; font: 600 10px/1 ${MONO_FONT}; letter-spacing: .1em; text-transform: uppercase; color: #8b98a9; padding: 0 10px 9px; border-bottom: 1px solid var(--line); }
817
+ td { padding: 10px; border-bottom: 1px solid #f1f4f8; vertical-align: top; }
818
+ tr:last-child td { border-bottom: 0; }
819
+ td.num { text-align: right; font-family: ${MONO_FONT}; font-variant-numeric: tabular-nums; white-space: nowrap; }
820
+ td.id { font-family: ${MONO_FONT}; font-size: 11.5px; white-space: nowrap; }
821
+ .goal { display: block; max-width: 520px; color: #475569; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
822
+ .chip { display: inline-block; padding: 2px 8px; border-radius: 999px; font: 600 10px/1.6 ${MONO_FONT}; letter-spacing: .05em; color: #fff; }
823
+ footer { margin-top: 26px; color: #8b98a9; font-size: 11.5px; line-height: 1.7; }
824
+ footer code { font-family: ${MONO_FONT}; }
825
+ @media (max-width: 1100px) {
826
+ .cards { grid-template-columns: repeat(3, minmax(0, 1fr)); }
827
+ }
828
+ @media (max-width: 680px) {
829
+ .cards { grid-template-columns: repeat(2, minmax(0, 1fr)); }
830
+ }
831
+ @media (max-width: 900px) {
832
+ .charts { grid-template-columns: 1fr; }
833
+ .page { padding: 28px 16px 44px; }
834
+ h1 { font-size: 26px; }
835
+ }
836
+ @media print {
837
+ body { background: #fff; }
838
+ .page { max-width: none; padding: 0; }
839
+ .panel, .card { box-shadow: none; break-inside: avoid; }
840
+ }
841
+ `
842
+
843
+ /**
844
+ * Build the full report.
845
+ *
846
+ * @param {object[]} runs - run records, any order.
847
+ * @param {{ title?: string, generatedAt?: number, now?: number, subtitle?: string }} [options]
848
+ * @returns {string} a complete HTML document with no external references.
849
+ */
850
+ export function buildReport(runs, options = {}) {
851
+ const now = options.now ?? Date.now()
852
+ const generatedAt = options.generatedAt ?? now
853
+ const items = prepare(runs, now)
854
+ const summary = summarize(items)
855
+ const start = summary.start
856
+ const end = summary.end
857
+ const span = Math.max(1, summary.span)
858
+ const { ticks } = axisTicks(start, end)
859
+ const laneCount = assignLanes(items)
860
+ const title = options.title ?? 'Superagent run report'
861
+ const finished = items.filter(item => !ACTIVE_STATUSES.has(item.status)).length
862
+ const windowText = items.length > 0 ? `${stampUtc(start)} → ${stampUtc(end)} UTC` : 'no runs'
863
+
864
+ const events = items
865
+ .filter(item => item.calls > 0)
866
+ .map(item => ({ t: item.end, value: item.calls }))
867
+ .sort((a, b) => a.t - b.t)
868
+ const costEvents = items
869
+ .filter(item => item.cost !== null && item.cost > 0)
870
+ .map(item => ({ t: item.end, value: item.cost }))
871
+ .sort((a, b) => a.t - b.t)
872
+
873
+ const problemRuns = items
874
+ .filter(item => ['failed', 'cancelled', 'interrupted', 'partial'].includes(item.status))
875
+ .sort((a, b) => b.end - a.end)
876
+
877
+ const statusCards = [
878
+ card('Runs', String(items.length), `${finished} finished · ${items.length - finished} live`),
879
+ card('Completed', String(summary.byStatus.completed ?? 0), `${summary.byStatus.partial ?? 0} partial`, '#15803d'),
880
+ card('Failed', String(summary.byStatus.failed ?? 0), `${summary.byStatus.cancelled ?? 0} cancelled · ${summary.byStatus.interrupted ?? 0} interrupted`, '#b91c1c'),
881
+ card('Model calls', formatCount(summary.calls), 'measured from child sessions'),
882
+ card('Tokens', formatCount(summary.tokens), 'input + cache + output'),
883
+ card(
884
+ 'Cost',
885
+ summary.priced === 0
886
+ ? 'unpriced'
887
+ : `${moneyOfMicros(summary.costMicros, summary.currency ?? 'USD')}${summary.unpriced > 0 ? '+' : ''}`,
888
+ summary.priced === 0
889
+ ? 'no configured price — not shown as zero'
890
+ : `${summary.priced}/${items.length} runs priced${summary.mixedCurrency ? ' · mixed currencies' : ''}`,
891
+ '#0f766e',
892
+ ),
893
+ ].join('')
894
+
895
+ const cards = [
896
+ '<section class="cards">',
897
+ statusCards,
898
+ '</section>',
899
+ ].join('')
900
+
901
+ const legend = [
902
+ '<div class="legend">',
903
+ `<span><i class="swatch" style="background:${STATUS_HEX.running}"></i> planning / running / aggregating</span>`,
904
+ `<span><i class="swatch" style="background:${STATUS_HEX.completed}"></i> completed</span>`,
905
+ `<span><i class="swatch" style="background:${STATUS_HEX.failed}"></i> failed</span>`,
906
+ `<span><i class="swatch" style="background:${STATUS_HEX.cancelled}"></i> cancelled</span>`,
907
+ `<span><i class="swatch" style="background:${STATUS_HEX.interrupted}"></i> interrupted</span>`,
908
+ '<span><i class="swatch" style="background:#94a3b8;opacity:.38"></i> plan</span>',
909
+ '<span><i class="swatch" style="background:#94a3b8"></i> work</span>',
910
+ '<span><i class="swatch" style="background:#94a3b8;opacity:.66"></i> merge</span>',
911
+ '</div>',
912
+ ].join('')
913
+
914
+ const failures = problemRuns.length === 0
915
+ ? '<p class="hint">No failed, cancelled, interrupted, or partial runs in this window.</p>'
916
+ : [
917
+ '<div class="failures">',
918
+ ...problemRuns.map(item => {
919
+ const color = STATUS_HEX[item.status] ?? '#64748b'
920
+ const detail = item.error
921
+ ? escapeHtml(item.error)
922
+ : item.status === 'cancelled'
923
+ ? `Cancelled after ${escapeHtml(formatDuration(item.duration))}, ${escapeHtml(String(item.calls))} call(s) spent.`
924
+ : item.status === 'interrupted'
925
+ ? `The host went away after ${escapeHtml(formatDuration(item.duration))}; resume it with <code>superagent_resume</code>.`
926
+ : `Ended after ${escapeHtml(formatDuration(item.duration))} without a recorded error.`
927
+ return [
928
+ `<div class="failure ${escapeHtml(item.status)}">`,
929
+ `<div class="failure-head"><span class="chip" style="background:${color}">${escapeHtml(item.status.toUpperCase())}</span>`,
930
+ `<span>${escapeHtml(item.id)}</span>`,
931
+ `<span class="when">${escapeHtml(stampUtc(item.start))} UTC · ${escapeHtml(formatDuration(item.duration))}</span></div>`,
932
+ `<div class="failure-body">${detail}</div>`,
933
+ '</div>',
934
+ ].join('')
935
+ }),
936
+ '</div>',
937
+ ].join('')
938
+
939
+ const rows = [...items].reverse().map(item => {
940
+ const color = STATUS_HEX[item.status] ?? '#64748b'
941
+ return [
942
+ '<tr>',
943
+ `<td class="id">${escapeHtml(item.id)}</td>`,
944
+ `<td><span class="chip" style="background:${color}">${escapeHtml(item.status)}</span><span class="goal" title="${escapeHtml(item.goal)}">${escapeHtml(item.goal)}</span></td>`,
945
+ `<td class="num">${escapeHtml(item.calls ? String(item.calls) : '—')}</td>`,
946
+ `<td class="num">${escapeHtml(item.tokens ? formatCount(item.tokens) : '—')}</td>`,
947
+ `<td class="num">${escapeHtml(item.costMicros === null ? 'unpriced' : moneyOfMicros(item.costMicros, item.currency))}</td>`,
948
+ `<td class="num">${escapeHtml(formatDuration(item.duration))}</td>`,
949
+ `<td class="id">${escapeHtml(item.parent.replace(/^session-/, '').slice(0, 8) || '—')}</td>`,
950
+ '</tr>',
951
+ ].join('')
952
+ })
953
+
954
+ // Subtask-level spend: only worker children own a subtask, so the planner and
955
+ // the merge step appear in the run total but not here. Rows are emitted only
956
+ // for subtasks that actually recorded a model call.
957
+ const subtaskRows = items.flatMap(item => (item.subtasks ?? [])
958
+ .filter(subtask => subtask?.usage?.modelCalls)
959
+ .map(subtask => {
960
+ const usage = subtask.usage
961
+ const tokens = (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.outputTokens ?? 0)
962
+ const cost = subtask.cost && Object.keys(subtask.cost.byModel ?? {}).length > 0 ? subtask.cost : null
963
+ const costText = cost
964
+ ? `${moneyOfMicros(
965
+ Number.isFinite(cost.totalMicros) ? cost.totalMicros : Math.round((cost.total ?? 0) * 1e6),
966
+ cost.currency ?? item.currency,
967
+ )}${cost.complete ? '' : '+'}`
968
+ : 'unpriced'
969
+ return [
970
+ '<tr>',
971
+ `<td class="id">${escapeHtml(item.id)}</td>`,
972
+ `<td class="num">${escapeHtml(String(subtask.index ?? '—'))}</td>`,
973
+ `<td><span class="goal" title="${escapeHtml(subtask.title ?? '')}">${escapeHtml(subtask.title ?? '')}</span></td>`,
974
+ `<td class="num">${escapeHtml(String(usage.modelCalls))}</td>`,
975
+ `<td class="num">${escapeHtml(formatCount(tokens))}</td>`,
976
+ `<td class="num">${escapeHtml(costText)}</td>`,
977
+ '</tr>',
978
+ ].join('')
979
+ }))
980
+
981
+ const pricedNote = items.length === 0
982
+ ? 'No runs matched this window.'
983
+ : summary.unpriced > 0
984
+ ? `Cost covers ${summary.priced} of ${items.length} runs; models without a configured price are left out rather than estimated.`
985
+ : `Cost covers all ${items.length} runs at the prices configured by the operator.`
986
+
987
+ return `<!doctype html>
988
+ <html lang="en">
989
+ <head>
990
+ <meta charset="utf-8">
991
+ <meta name="viewport" content="width=device-width, initial-scale=1">
992
+ <title>${escapeHtml(title)}</title>
993
+ <style>${CSS}</style>
994
+ </head>
995
+ <body>
996
+ <main class="page">
997
+ <header class="masthead">
998
+ <div class="eyebrow">dsh-superagent · run report</div>
999
+ <h1>${escapeHtml(title)}</h1>
1000
+ <p class="lede">${escapeHtml(options.subtitle ?? `${items.length} run${items.length === 1 ? '' : 's'} of model-planned parallel subtasks, rendered from the durable run store.`)}</p>
1001
+ <div class="meta">${escapeHtml(windowText)} · generated ${escapeHtml(stampUtc(generatedAt))} UTC · peak concurrency ${laneCount} · ${formatCount(summary.calls)} model calls</div>
1002
+ </header>
1003
+ ${cards}
1004
+ <section class="panel" id="timeline">
1005
+ <div class="panel-head"><h2>Timeline</h2><span class="hint">one row per run · phases derived from subtask timestamps · ${escapeHtml(formatDuration(summary.span))} window</span></div>
1006
+ ${legend}
1007
+ <figure>${timelineSvg(items, { start, end, ticks })}</figure>
1008
+ </section>
1009
+ <section class="panel" id="lanes">
1010
+ <div class="panel-head"><h2>Concurrency</h2><span class="hint">${laneCount} lane${laneCount === 1 ? '' : 's'} · overlapping runs never share a lane</span></div>
1011
+ <figure>${lanesSvg(items, { start, end, ticks, lanes: laneCount })}</figure>
1012
+ </section>
1013
+ <section class="panel" id="retries">
1014
+ <div class="panel-head"><h2>Failure &amp; retry chains</h2><span class="hint">which worker failed · attempts spent · what it ended as</span></div>
1015
+ ${retriesSection(items)}
1016
+ <p class="hint">A run file keeps the latest error per worker, so earlier attempts are counted but cannot quote their own message. A self-heal round resets a worker's attempt counter, which is why its steps describe the latest round.</p>
1017
+ </section>
1018
+ <div class="charts">
1019
+ <section class="panel" id="calls">
1020
+ <div class="panel-head"><h2>Model calls</h2><span class="hint">cumulative at each run's end</span></div>
1021
+ <figure>${curveSvg(events, { start, end, ticks, color: '#0284c7', title: 'Cumulative model calls', empty: 'no model calls recorded' })}</figure>
1022
+ <p class="hint">${escapeHtml(`${summary.calls} calls across ${items.length} run(s), measured from child session usage logs.`)}</p>
1023
+ </section>
1024
+ <section class="panel" id="cost">
1025
+ <div class="panel-head"><h2>Cost</h2><span class="hint">cumulative at each run's end</span></div>
1026
+ <figure>${curveSvg(costEvents, { start, end, ticks, color: '#0f766e', title: 'Cumulative cost', formatter: value => money(value, summary.currency ?? 'USD'), empty: 'no priced runs' })}</figure>
1027
+ <p class="hint">${escapeHtml(pricedNote)}</p>
1028
+ </section>
1029
+ </div>
1030
+ <section class="panel" id="workers">
1031
+ <div class="panel-head"><h2>Worker time share</h2><span class="hint">each worker's span against the run's wall clock · bar = share of total worker time</span></div>
1032
+ ${workersSection(items, now)}
1033
+ </section>
1034
+ <section class="panel" id="failures">
1035
+ <div class="panel-head"><h2>Failures &amp; cancellations</h2><span class="hint">every run that did not complete normally</span></div>
1036
+ ${failures}
1037
+ </section>
1038
+ <section class="panel" id="runs">
1039
+ <div class="panel-head"><h2>Runs</h2><span class="hint">newest first · times in UTC</span></div>
1040
+ <div class="table-wrap">
1041
+ <table>
1042
+ <thead><tr><th>Run</th><th>Status &amp; goal</th><th style="text-align:right">Calls</th><th style="text-align:right">Tokens</th><th style="text-align:right">Cost</th><th style="text-align:right">Duration</th><th>Parent</th></tr></thead>
1043
+ <tbody>${rows.join('')}</tbody>
1044
+ </table>
1045
+ </div>
1046
+ </section>
1047
+ <section class="panel" id="subtasks">
1048
+ <div class="panel-head"><h2>Subtask cost</h2><span class="hint">worker children only · planner and merge calls appear in the run total · a “+” marks an incomplete figure</span></div>
1049
+ ${subtaskRows.length === 0
1050
+ ? '<p class="hint">No subtask recorded a model call in this window.</p>'
1051
+ : `<div class="table-wrap">
1052
+ <table>
1053
+ <thead><tr><th>Run</th><th style="text-align:right">#</th><th>Subtask</th><th style="text-align:right">Calls</th><th style="text-align:right">Tokens</th><th style="text-align:right">Cost</th></tr></thead>
1054
+ <tbody>${subtaskRows.join('')}</tbody>
1055
+ </table>
1056
+ </div>`}
1057
+ </section>
1058
+ <footer>
1059
+ Self-contained report: inline CSS and inline SVG, no scripts, no external fonts or images, no network access.
1060
+ Phases are inferred from <code>startedAt</code>/<code>finishedAt</code> of the run and its subtasks; a run file does not record phase boundaries directly.
1061
+ Cost is computed only from operator-configured prices — unpriced models are reported as unpriced, never as zero.
1062
+ Generated by <code>dsh-superagent-report</code> from <code>${escapeHtml(items.length)}</code> run file(s).
1063
+ </footer>
1064
+ </main>
1065
+ </body>
1066
+ </html>
1067
+ `
1068
+ }