@xiangyixie/dsh-superagent 0.9.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/report.js CHANGED
@@ -1,733 +1,733 @@
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 { ACTIVE_STATUSES } from './store.js'
16
- import { callsOf, formatCount, formatDuration } from './watch.js'
17
-
18
- const STATUS_HEX = {
19
- queued: '#64748b',
20
- planning: '#0284c7',
21
- running: '#0284c7',
22
- aggregating: '#0284c7',
23
- completed: '#15803d',
24
- partial: '#b45309',
25
- failed: '#b91c1c',
26
- cancelled: '#7e22ce',
27
- interrupted: '#c2410c',
28
- }
29
-
30
- const STATUS_ORDER = ['running', 'planning', 'aggregating', 'queued', 'completed', 'partial', 'failed', 'cancelled', 'interrupted']
31
-
32
- /** Phase opacity inside a run bar: plan is fainter, merge is medium. */
33
- const PHASE_OPACITY = { plan: 0.38, work: 1, merge: 0.66 }
34
- const PHASE_LABEL = { plan: 'plan', work: 'work', merge: 'merge' }
35
-
36
- const SVG_FONT = "-apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"
37
- const MONO_FONT = "ui-monospace, SFMono-Regular, 'Cascadia Mono', Consolas, 'Liberation Mono', monospace"
38
-
39
- /**
40
- * Escape text for HTML text nodes and double-quoted attributes.
41
- * @param {unknown} value - raw value.
42
- */
43
- export function escapeHtml(value) {
44
- return String(value ?? '').replace(/[&<>"']/g, char => ({
45
- '&': '&amp;',
46
- '<': '&lt;',
47
- '>': '&gt;',
48
- '"': '&quot;',
49
- "'": '&#39;',
50
- }[char]))
51
- }
52
-
53
- /** Parse an ISO timestamp, or null when absent/unusable. */
54
- function timeOf(value) {
55
- const parsed = Date.parse(String(value ?? ''))
56
- return Number.isFinite(parsed) ? parsed : null
57
- }
58
-
59
- /** `$0.0225`, `$1.24`, `<$0.0001`, or `—`. */
60
- function money(value) {
61
- if (value === null || value === undefined || !Number.isFinite(value)) return '—'
62
- if (value === 0) return '$0'
63
- if (value < 0.0001) return '<$0.0001'
64
- if (value < 1) return `$${value.toFixed(4)}`
65
- return `$${value.toFixed(2)}`
66
- }
67
-
68
- /** `2026-11-14 07:52:05` in UTC, matching the axis. */
69
- function stampUtc(ms) {
70
- if (!Number.isFinite(ms)) return '—'
71
- const iso = new Date(ms).toISOString()
72
- return `${iso.slice(0, 10)} ${iso.slice(11, 19)}`
73
- }
74
-
75
- /** Axis label: seconds when the window is short, minute precision when long. */
76
- function axisLabel(ms, span) {
77
- const date = new Date(ms)
78
- const hh = String(date.getUTCHours()).padStart(2, '0')
79
- const mm = String(date.getUTCMinutes()).padStart(2, '0')
80
- const ss = String(date.getUTCSeconds()).padStart(2, '0')
81
- if (span > 24 * 3600_000) {
82
- const mo = String(date.getUTCMonth() + 1).padStart(2, '0')
83
- const dd = String(date.getUTCDate()).padStart(2, '0')
84
- return `${mo}-${dd} ${hh}:${mm}`
85
- }
86
- return `${hh}:${mm}:${ss}`
87
- }
88
-
89
- /** Six-ish evenly spaced ticks that land on round wall-clock values. */
90
- export function axisTicks(start, end) {
91
- const span = Math.max(1, end - start)
92
- const steps = [
93
- 1000, 2000, 5000, 10_000, 15_000, 30_000,
94
- 60_000, 120_000, 300_000, 600_000, 900_000, 1_800_000,
95
- 3_600_000, 7_200_000, 21_600_000, 43_200_000, 86_400_000,
96
- ]
97
- const target = span / 6
98
- const step = steps.find(candidate => candidate >= target) ?? steps[steps.length - 1]
99
- const ticks = []
100
- for (let tick = Math.ceil(start / step) * step; tick <= end; tick += step) ticks.push(tick)
101
- // A window shorter than one step can contain no round boundary at all.
102
- return { ticks: ticks.length > 0 ? ticks : [start, end], step }
103
- }
104
-
105
- /** Truncate to an approximate pixel width at the given font size. */
106
- function clipTo(text, width, fontSize = 11) {
107
- const value = String(text ?? '').replace(/\s+/g, ' ').trim()
108
- const max = Math.max(1, Math.floor(width / (fontSize * 0.58)))
109
- if (value.length <= max) return value
110
- if (max <= 1) return '…'
111
- return `${value.slice(0, max - 1)}…`
112
- }
113
-
114
- /** Short run id for a narrow block: the time stamp alone is ambiguous. */
115
- function shortId(id) {
116
- const value = String(id ?? '')
117
- return value.length <= 12 ? value : `…${value.slice(-9)}`
118
- }
119
-
120
- /**
121
- * Derive the three visible phases from recorded timestamps.
122
- *
123
- * The run file records status, not phase boundaries, so the boundaries come
124
- * from the subtasks: planning ends when the first worker starts, work ends when
125
- * the last worker reports, and merging covers the remainder. The report states
126
- * this derivation in its footnote rather than implying the phases are exact.
127
- *
128
- * @param {object} run - run record.
129
- * @param {number} now - wall clock for a run that has not finished.
130
- */
131
- export function phasesOf(run, now) {
132
- const created = timeOf(run?.createdAt) ?? timeOf(run?.startedAt) ?? now
133
- const started = timeOf(run?.startedAt) ?? created
134
- const finished = timeOf(run?.finishedAt) ?? now
135
- const subtasks = Array.isArray(run?.subtasks) ? run.subtasks : []
136
- const starts = subtasks.map(subtask => timeOf(subtask.startedAt)).filter(value => value !== null)
137
- const ends = subtasks.map(subtask => timeOf(subtask.finishedAt)).filter(value => value !== null)
138
- const firstWork = starts.length > 0 ? Math.min(...starts) : started
139
- const lastWork = ends.length > 0 ? Math.max(...ends) : (starts.length > 0 ? Math.min(...starts) : finished)
140
- const planEnd = Math.min(Math.max(firstWork, started), finished)
141
- const workEnd = Math.min(Math.max(lastWork, planEnd), finished)
142
- return [
143
- { kind: 'plan', start: started, end: planEnd },
144
- { kind: 'work', start: planEnd, end: workEnd },
145
- { kind: 'merge', start: workEnd, end: finished },
146
- ].filter(phase => phase.end > phase.start)
147
- }
148
-
149
- /**
150
- * Greedy interval-graph colouring: a run takes the first lane whose previous
151
- * run has already ended, otherwise it opens a new lane. Two overlapping runs
152
- * therefore never share a lane, and the lane count is the true peak
153
- * concurrency of the selected window.
154
- *
155
- * @param {Array<{ start: number, end: number }>} items - spans, sorted by start.
156
- * @returns {number} number of lanes used.
157
- */
158
- export function assignLanes(items) {
159
- const laneEnds = []
160
- for (const item of items) {
161
- let lane = laneEnds.findIndex(end => end <= item.start)
162
- if (lane === -1) {
163
- lane = laneEnds.length
164
- laneEnds.push(item.end)
165
- } else {
166
- laneEnds[lane] = item.end
167
- }
168
- item.lane = lane
169
- }
170
- return laneEnds.length
171
- }
172
-
173
- /**
174
- * Normalise run files into what the page needs, in chronological order.
175
- * @param {object[]} runs - run records from the store.
176
- * @param {number} now - wall clock.
177
- */
178
- export function prepare(runs, now) {
179
- const items = []
180
- for (const run of runs ?? []) {
181
- if (!run || !run.id) continue
182
- const start = timeOf(run.startedAt) ?? timeOf(run.createdAt) ?? now
183
- const end = timeOf(run.finishedAt) ?? now
184
- const live = ACTIVE_STATUSES.has(run.status)
185
- const phases = phasesOf(run, now)
186
- const calls = callsOf(run)
187
- const cost = Number.isFinite(run.cost?.total) && run.cost?.complete !== false ? run.cost.total : null
188
- items.push({
189
- run,
190
- id: String(run.id),
191
- status: String(run.status ?? 'unknown'),
192
- start,
193
- end: Math.max(end, start),
194
- live,
195
- phases,
196
- calls,
197
- cost,
198
- tokens: run.usage?.totalTokens ?? 0,
199
- duration: Math.max(0, end - start),
200
- parent: String(run.parentSessionId ?? ''),
201
- goal: String(run.goal ?? ''),
202
- error: String(run.error ?? ''),
203
- subtasks: Array.isArray(run.subtasks) ? run.subtasks : [],
204
- })
205
- }
206
- items.sort((a, b) => a.start - b.start || a.id.localeCompare(b.id))
207
- return items
208
- }
209
-
210
- /** Totals used by the cards and the one-line summary. */
211
- function summarize(items) {
212
- const byStatus = {}
213
- let calls = 0
214
- let tokens = 0
215
- let cost = 0
216
- let priced = 0
217
- let unpriced = 0
218
- for (const item of items) {
219
- byStatus[item.status] = (byStatus[item.status] ?? 0) + 1
220
- calls += item.calls
221
- tokens += item.tokens
222
- if (item.cost !== null) {
223
- cost += item.cost
224
- priced += 1
225
- } else if (item.calls > 0) {
226
- unpriced += 1
227
- }
228
- }
229
- const start = items.length > 0 ? Math.min(...items.map(item => item.start)) : 0
230
- const end = items.length > 0 ? Math.max(...items.map(item => item.end)) : 0
231
- return { byStatus, calls, tokens, cost, priced, unpriced, start, end, span: Math.max(0, end - start) }
232
- }
233
-
234
- /**
235
- * Timeline: one row per run, a bar split into plan/work/merge, and an explicit
236
- * marker for the runs that did not complete, because a flat bar alone hides
237
- * whether an early end was success or damage.
238
- */
239
- function timelineSvg(items, options) {
240
- const width = 1240
241
- const left = 292
242
- // The right edge is reserved for the outcome marker, so a run that ends at
243
- // the very last instant still has room for "✕ failed" instead of silently
244
- // losing the annotation.
245
- const right = 176
246
- const top = 54
247
- const rowHeight = 30
248
- const height = top + items.length * rowHeight + 26
249
- const start = options.start
250
- const end = options.end
251
- const span = Math.max(1, end - start)
252
- const track = width - left - right
253
- const x = time => left + ((time - start) / span) * track
254
- const { ticks } = options
255
- const parts = []
256
-
257
- parts.push(`<svg viewBox="0 0 ${width} ${height}" role="img" aria-labelledby="timeline-title timeline-desc">`)
258
- parts.push('<title id="timeline-title">Run timeline</title>')
259
- 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>`)
260
-
261
- for (const tick of ticks) {
262
- const gx = x(tick).toFixed(1)
263
- parts.push(`<line x1="${gx}" y1="${top - 18}" x2="${gx}" y2="${height - 20}" stroke="#eef1f5" stroke-width="1"/>`)
264
- parts.push(`<text x="${gx}" y="${top - 26}" text-anchor="middle" class="axis" fill="#94a3b8">${escapeHtml(axisLabel(tick, span))}</text>`)
265
- }
266
-
267
- items.forEach((item, index) => {
268
- const y = top + index * rowHeight
269
- const color = STATUS_HEX[item.status] ?? '#64748b'
270
- if (index % 2 === 1) {
271
- parts.push(`<rect x="8" y="${y}" width="${width - 16}" height="${rowHeight - 1}" rx="4" fill="#fbfcfe"/>`)
272
- }
273
- parts.push(`<line x1="16" y1="${y + rowHeight - 0.5}" x2="${width - 16}" y2="${y + rowHeight - 0.5}" stroke="#f1f5f9" stroke-width="1"/>`)
274
- parts.push(`<text x="16" y="${y + 13}" class="id" fill="#0f172a">${escapeHtml(item.id)}</text>`)
275
- parts.push(`<text x="16" y="${y + 25}" class="meta" fill="${color}">${escapeHtml(item.status.toUpperCase())} · ${escapeHtml(formatDuration(item.duration))}</text>`)
276
-
277
- const phases = item.phases.length > 0
278
- ? item.phases
279
- // A run that started and ended in the same millisecond has no positive
280
- // span to draw; keep a tick so the row is not silently blank.
281
- : [{ kind: 'work', start: item.start, end: item.start }]
282
- for (const phase of phases) {
283
- const px = x(phase.start)
284
- // A sub-second run on a multi-hour axis is a hairline. Give it three
285
- // pixels so it stays visible and clickable instead of disappearing.
286
- const pw = Math.max(3, x(phase.end) - px)
287
- const opacity = PHASE_OPACITY[phase.kind] ?? 0.6
288
- 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>`)
289
- }
290
-
291
- // Subtask boundaries inside the work phase: a thin white notch is enough
292
- // to show whether workers overlapped or ran one after another.
293
- const notches = new Set()
294
- for (const subtask of item.subtasks) {
295
- for (const edge of [timeOf(subtask.startedAt), timeOf(subtask.finishedAt)]) {
296
- if (edge !== null) notches.add(edge)
297
- }
298
- }
299
- for (const notch of notches) {
300
- if (notch <= start || notch >= end) continue
301
- const nx = x(notch)
302
- const barStart = x(item.start)
303
- const barEnd = x(item.end)
304
- if (nx <= barStart + 2 || nx >= barEnd - 2) continue
305
- 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"/>`)
306
- }
307
-
308
- if (item.live) {
309
- 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"/>`)
310
- }
311
-
312
- const markers = {
313
- failed: '✕ failed',
314
- cancelled: '⊘ cancelled',
315
- interrupted: '! interrupted',
316
- partial: '△ partial',
317
- }
318
- const marker = markers[item.status]
319
- if (marker) {
320
- const available = width - 16 - (x(item.end) + 8)
321
- 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>`)
322
- }
323
- })
324
-
325
- parts.push('</svg>')
326
- return parts.join('')
327
- }
328
-
329
- /**
330
- * Swimlanes: the same runs placed on the minimum number of lanes so that
331
- * overlaps are visible as horizontal neighbours instead of hidden in a
332
- * chronological list.
333
- */
334
- function lanesSvg(items, options) {
335
- const lanes = options.lanes
336
- const laneHeight = 40
337
- const width = 1240
338
- const left = 92
339
- const right = 48
340
- const top = 44
341
- const height = top + Math.max(1, lanes) * laneHeight + 34
342
- const start = options.start
343
- const end = options.end
344
- const span = Math.max(1, end - start)
345
- const track = width - left - right
346
- const x = time => left + ((time - start) / span) * track
347
- const parts = []
348
-
349
- parts.push(`<svg viewBox="0 0 ${width} ${height}" role="img" aria-labelledby="lanes-title lanes-desc">`)
350
- parts.push('<title id="lanes-title">Concurrency swimlanes</title>')
351
- 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>`)
352
-
353
- for (let lane = 0; lane < Math.max(1, lanes); lane++) {
354
- const y = top + lane * laneHeight
355
- parts.push(`<rect x="${left}" y="${y + 5}" width="${track}" height="${laneHeight - 10}" rx="6" fill="#f8fafc"/>`)
356
- parts.push(`<text x="${left - 12}" y="${y + laneHeight / 2 + 4}" text-anchor="end" class="axis" fill="#94a3b8">lane ${lane + 1}</text>`)
357
- }
358
-
359
- for (const tick of options.ticks) {
360
- const gx = x(tick).toFixed(1)
361
- parts.push(`<line x1="${gx}" y1="${top}" x2="${gx}" y2="${height - 26}" stroke="#eef1f5" stroke-width="1"/>`)
362
- parts.push(`<text x="${gx}" y="${height - 10}" text-anchor="middle" class="axis" fill="#94a3b8">${escapeHtml(axisLabel(tick, span))}</text>`)
363
- }
364
-
365
- for (const item of items) {
366
- const color = STATUS_HEX[item.status] ?? '#64748b'
367
- const y = top + item.lane * laneHeight + 9
368
- const bx = x(item.start)
369
- const bw = Math.max(4, x(item.end) - bx)
370
- 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>`)
371
- if (bw > 74) {
372
- parts.push(`<text x="${(bx + 7).toFixed(1)}" y="${y + 14}" class="lane-label" fill="#ffffff">${escapeHtml(shortId(item.id))}</text>`)
373
- }
374
- }
375
-
376
- parts.push('</svg>')
377
- return parts.join('')
378
- }
379
-
380
- /** Round a value up to a 1/2/5 × 10^n axis maximum. */
381
- function niceMax(value) {
382
- if (!Number.isFinite(value) || value <= 0) return 1
383
- const power = 10 ** Math.floor(Math.log10(value))
384
- const scaled = value / power
385
- const factor = scaled <= 1 ? 1 : scaled <= 2 ? 2 : scaled <= 5 ? 5 : 10
386
- return factor * power
387
- }
388
-
389
- /**
390
- * Cumulative step chart. Events land at each run's end time, so the curve
391
- * answers "how much had this window spent by 09:15?" without pretending to
392
- * know the intra-run shape that the run files do not record.
393
- *
394
- * @param {Array<{ t: number, value: number }>} events - sorted by time.
395
- * @param {{ start: number, end: number, color: string, ticks: number[], formatter?: (value: number) => string, empty?: string, title: string }} options
396
- */
397
- function curveSvg(events, options) {
398
- const width = 620
399
- const height = 220
400
- const left = 58
401
- const right = 16
402
- const top = 20
403
- const bottom = 38
404
- const plotW = width - left - right
405
- const plotH = height - top - bottom
406
- const start = options.start
407
- const end = options.end
408
- const span = Math.max(1, end - start)
409
- const x = time => left + ((time - start) / span) * plotW
410
- const eventsWithValue = events.filter(event => Number.isFinite(event.value))
411
- const total = eventsWithValue.reduce((sum, event) => sum + event.value, 0)
412
- const max = niceMax(total)
413
- const y = value => top + plotH - (value / max) * plotH
414
- const format = options.formatter ?? (value => formatCount(value))
415
- const parts = []
416
-
417
- parts.push(`<svg viewBox="0 0 ${width} ${height}" role="img" aria-label="${escapeHtml(options.title)}">`)
418
- parts.push(`<rect x="${left}" y="${top}" width="${plotW}" height="${plotH}" fill="#f8fafc" rx="6"/>`)
419
-
420
- for (let index = 0; index <= 4; index++) {
421
- const value = (max / 4) * index
422
- const gy = y(value).toFixed(1)
423
- parts.push(`<line x1="${left}" y1="${gy}" x2="${left + plotW}" y2="${gy}" stroke="#e8edf3" stroke-width="1"/>`)
424
- parts.push(`<text x="${left - 10}" y="${Number(gy) + 4}" text-anchor="end" class="axis" fill="#94a3b8">${escapeHtml(format(value))}</text>`)
425
- }
426
-
427
- for (const tick of options.ticks) {
428
- const gx = x(tick).toFixed(1)
429
- parts.push(`<line x1="${gx}" y1="${top}" x2="${gx}" y2="${top + plotH}" stroke="#eef1f5" stroke-width="1"/>`)
430
- parts.push(`<text x="${gx}" y="${height - 12}" text-anchor="middle" class="axis" fill="#94a3b8">${escapeHtml(axisLabel(tick, span))}</text>`)
431
- }
432
-
433
- if (eventsWithValue.length === 0) {
434
- 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>`)
435
- parts.push('</svg>')
436
- return parts.join('')
437
- }
438
-
439
- let cursor = 0
440
- let path = `M ${x(start).toFixed(1)} ${y(0).toFixed(1)}`
441
- for (const event of eventsWithValue) {
442
- cursor += event.value
443
- path += ` H ${x(event.t).toFixed(1)} V ${y(cursor).toFixed(1)}`
444
- }
445
- path += ` H ${x(end).toFixed(1)}`
446
-
447
- parts.push(`<path d="${path} V ${y(0).toFixed(1)} H ${x(start).toFixed(1)} Z" fill="${options.color}" opacity="0.10"/>`)
448
- parts.push(`<path d="${path}" fill="none" stroke="${options.color}" stroke-width="2" stroke-linejoin="round"/>`)
449
-
450
- let running = 0
451
- for (const event of eventsWithValue) {
452
- running += event.value
453
- 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>`)
454
- }
455
-
456
- parts.push('</svg>')
457
- return parts.join('')
458
- }
459
-
460
- /** One stat card. */
461
- function card(label, value, note, accent) {
462
- return [
463
- '<div class="card">',
464
- `<div class="card-label">${escapeHtml(label)}</div>`,
465
- `<div class="card-value"${accent ? ` style="color:${accent}"` : ''}>${escapeHtml(value)}</div>`,
466
- `<div class="card-note">${escapeHtml(note)}</div>`,
467
- '</div>',
468
- ].join('')
469
- }
470
-
471
- const CSS = `
472
- :root {
473
- color-scheme: light;
474
- --ink: #0f172a;
475
- --muted: #64748b;
476
- --line: #e5e9f0;
477
- --card: #ffffff;
478
- --accent: #0f766e;
479
- }
480
- * { box-sizing: border-box; }
481
- html, body { margin: 0; padding: 0; }
482
- body {
483
- background: #f4f6fa;
484
- background-image: radial-gradient(900px 420px at 12% -8%, #e6f2f1 0%, rgba(230,242,241,0) 70%),
485
- radial-gradient(760px 380px at 96% 4%, #eef0fb 0%, rgba(238,240,251,0) 66%);
486
- color: var(--ink);
487
- font: 14px/1.55 ${SVG_FONT};
488
- -webkit-font-smoothing: antialiased;
489
- }
490
- .page { max-width: 1280px; margin: 0 auto; padding: 44px 32px 64px; }
491
- .masthead { margin-bottom: 26px; }
492
- .eyebrow {
493
- font: 600 11px/1 ${MONO_FONT};
494
- letter-spacing: .14em;
495
- text-transform: uppercase;
496
- color: var(--accent);
497
- }
498
- h1 { font-size: 34px; line-height: 1.15; letter-spacing: -.02em; margin: 12px 0 8px; }
499
- .lede { margin: 0; max-width: 760px; color: #475569; font-size: 15px; }
500
- .meta { margin-top: 14px; font: 12px/1.5 ${MONO_FONT}; color: #7c8899; }
501
- .cards { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 12px; margin: 26px 0 22px; }
502
- .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); }
503
- .card-label { font: 600 10px/1 ${MONO_FONT}; letter-spacing: .12em; text-transform: uppercase; color: #8b98a9; }
504
- .card-value { font-size: 26px; font-weight: 650; letter-spacing: -.02em; margin: 9px 0 4px; font-variant-numeric: tabular-nums; }
505
- .card-note { font-size: 11.5px; color: var(--muted); }
506
- .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); }
507
- .panel-head { display: flex; align-items: baseline; justify-content: space-between; gap: 18px; margin-bottom: 10px; flex-wrap: wrap; }
508
- .panel h2 { font-size: 15px; letter-spacing: -.01em; margin: 0; }
509
- .panel .hint { font-size: 12px; color: var(--muted); }
510
- .legend { display: flex; gap: 16px; flex-wrap: wrap; font-size: 11.5px; color: #5b6b7f; margin: 4px 0 6px; }
511
- .legend span { display: inline-flex; align-items: center; gap: 6px; }
512
- .swatch { width: 10px; height: 10px; border-radius: 3px; display: inline-block; }
513
- figure { margin: 0; overflow-x: auto; }
514
- svg { display: block; width: 100%; height: auto; min-width: 720px; }
515
- svg text { font-family: ${SVG_FONT}; }
516
- svg .axis { font-family: ${MONO_FONT}; font-size: 10px; }
517
- svg .id { font-family: ${MONO_FONT}; font-size: 11px; font-weight: 600; }
518
- svg .meta { font-family: ${MONO_FONT}; font-size: 9.5px; letter-spacing: .04em; }
519
- svg .mark { font-size: 10px; font-weight: 600; }
520
- svg .lane-label { font-family: ${MONO_FONT}; font-size: 9.5px; }
521
- svg .empty { font-size: 12px; fill: #94a3b8; }
522
- .charts { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
523
- .charts .panel { margin-bottom: 18px; }
524
- .charts svg { min-width: 0; }
525
- .failures { display: grid; gap: 10px; }
526
- .failure { border: 1px solid var(--line); border-left: 3px solid #b91c1c; border-radius: 8px; padding: 10px 13px; background: #fff; }
527
- .failure.cancelled { border-left-color: #7e22ce; }
528
- .failure.interrupted { border-left-color: #c2410c; }
529
- .failure.partial { border-left-color: #b45309; }
530
- .failure-head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font: 600 11.5px/1.4 ${MONO_FONT}; }
531
- .failure-head .chip { font-size: 9.5px; letter-spacing: .06em; padding: 2px 7px; border-radius: 999px; color: #fff; }
532
- .failure-body { margin-top: 6px; font-size: 12.5px; color: #475569; }
533
- .failure-body code { font-family: ${MONO_FONT}; font-size: 11.5px; background: #f4f6fa; padding: 1px 5px; border-radius: 4px; }
534
- .failure .when { color: #8b98a9; font-weight: 400; }
535
- .table-wrap { overflow-x: auto; }
536
- table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
537
- 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); }
538
- td { padding: 10px; border-bottom: 1px solid #f1f4f8; vertical-align: top; }
539
- tr:last-child td { border-bottom: 0; }
540
- td.num { text-align: right; font-family: ${MONO_FONT}; font-variant-numeric: tabular-nums; white-space: nowrap; }
541
- td.id { font-family: ${MONO_FONT}; font-size: 11.5px; white-space: nowrap; }
542
- .goal { display: block; max-width: 520px; color: #475569; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
543
- .chip { display: inline-block; padding: 2px 8px; border-radius: 999px; font: 600 10px/1.6 ${MONO_FONT}; letter-spacing: .05em; color: #fff; }
544
- footer { margin-top: 26px; color: #8b98a9; font-size: 11.5px; line-height: 1.7; }
545
- footer code { font-family: ${MONO_FONT}; }
546
- @media (max-width: 1100px) {
547
- .cards { grid-template-columns: repeat(3, minmax(0, 1fr)); }
548
- }
549
- @media (max-width: 680px) {
550
- .cards { grid-template-columns: repeat(2, minmax(0, 1fr)); }
551
- }
552
- @media (max-width: 900px) {
553
- .charts { grid-template-columns: 1fr; }
554
- .page { padding: 28px 16px 44px; }
555
- h1 { font-size: 26px; }
556
- }
557
- @media print {
558
- body { background: #fff; }
559
- .page { max-width: none; padding: 0; }
560
- .panel, .card { box-shadow: none; break-inside: avoid; }
561
- }
562
- `
563
-
564
- /**
565
- * Build the full report.
566
- *
567
- * @param {object[]} runs - run records, any order.
568
- * @param {{ title?: string, generatedAt?: number, now?: number, subtitle?: string }} [options]
569
- * @returns {string} a complete HTML document with no external references.
570
- */
571
- export function buildReport(runs, options = {}) {
572
- const now = options.now ?? Date.now()
573
- const generatedAt = options.generatedAt ?? now
574
- const items = prepare(runs, now)
575
- const summary = summarize(items)
576
- const start = summary.start
577
- const end = summary.end
578
- const span = Math.max(1, summary.span)
579
- const { ticks } = axisTicks(start, end)
580
- const laneCount = assignLanes(items)
581
- const title = options.title ?? 'Superagent run report'
582
- const finished = items.filter(item => !ACTIVE_STATUSES.has(item.status)).length
583
- const windowText = items.length > 0 ? `${stampUtc(start)} → ${stampUtc(end)} UTC` : 'no runs'
584
-
585
- const events = items
586
- .filter(item => item.calls > 0)
587
- .map(item => ({ t: item.end, value: item.calls }))
588
- .sort((a, b) => a.t - b.t)
589
- const costEvents = items
590
- .filter(item => item.cost !== null && item.cost > 0)
591
- .map(item => ({ t: item.end, value: item.cost }))
592
- .sort((a, b) => a.t - b.t)
593
-
594
- const problemRuns = items
595
- .filter(item => ['failed', 'cancelled', 'interrupted', 'partial'].includes(item.status))
596
- .sort((a, b) => b.end - a.end)
597
-
598
- const statusCards = [
599
- card('Runs', String(items.length), `${finished} finished · ${items.length - finished} live`),
600
- card('Completed', String(summary.byStatus.completed ?? 0), `${summary.byStatus.partial ?? 0} partial`, '#15803d'),
601
- card('Failed', String(summary.byStatus.failed ?? 0), `${summary.byStatus.cancelled ?? 0} cancelled · ${summary.byStatus.interrupted ?? 0} interrupted`, '#b91c1c'),
602
- card('Model calls', formatCount(summary.calls), 'measured from child sessions'),
603
- card('Tokens', formatCount(summary.tokens), 'input + cache + output'),
604
- card('Cost', summary.priced === 0 ? 'unpriced' : money(summary.cost), summary.priced === 0 ? 'no configured price for these models' : `${summary.priced}/${items.length} runs priced`, '#0f766e'),
605
- ].join('')
606
-
607
- const cards = [
608
- '<section class="cards">',
609
- statusCards,
610
- '</section>',
611
- ].join('')
612
-
613
- const legend = [
614
- '<div class="legend">',
615
- `<span><i class="swatch" style="background:${STATUS_HEX.running}"></i> planning / running / aggregating</span>`,
616
- `<span><i class="swatch" style="background:${STATUS_HEX.completed}"></i> completed</span>`,
617
- `<span><i class="swatch" style="background:${STATUS_HEX.failed}"></i> failed</span>`,
618
- `<span><i class="swatch" style="background:${STATUS_HEX.cancelled}"></i> cancelled</span>`,
619
- `<span><i class="swatch" style="background:${STATUS_HEX.interrupted}"></i> interrupted</span>`,
620
- '<span><i class="swatch" style="background:#94a3b8;opacity:.38"></i> plan</span>',
621
- '<span><i class="swatch" style="background:#94a3b8"></i> work</span>',
622
- '<span><i class="swatch" style="background:#94a3b8;opacity:.66"></i> merge</span>',
623
- '</div>',
624
- ].join('')
625
-
626
- const failures = problemRuns.length === 0
627
- ? '<p class="hint">No failed, cancelled, interrupted, or partial runs in this window.</p>'
628
- : [
629
- '<div class="failures">',
630
- ...problemRuns.map(item => {
631
- const color = STATUS_HEX[item.status] ?? '#64748b'
632
- const detail = item.error
633
- ? escapeHtml(item.error)
634
- : item.status === 'cancelled'
635
- ? `Cancelled after ${escapeHtml(formatDuration(item.duration))}, ${escapeHtml(String(item.calls))} call(s) spent.`
636
- : item.status === 'interrupted'
637
- ? `The host went away after ${escapeHtml(formatDuration(item.duration))}; resume it with <code>superagent_resume</code>.`
638
- : `Ended after ${escapeHtml(formatDuration(item.duration))} without a recorded error.`
639
- return [
640
- `<div class="failure ${escapeHtml(item.status)}">`,
641
- `<div class="failure-head"><span class="chip" style="background:${color}">${escapeHtml(item.status.toUpperCase())}</span>`,
642
- `<span>${escapeHtml(item.id)}</span>`,
643
- `<span class="when">${escapeHtml(stampUtc(item.start))} UTC · ${escapeHtml(formatDuration(item.duration))}</span></div>`,
644
- `<div class="failure-body">${detail}</div>`,
645
- '</div>',
646
- ].join('')
647
- }),
648
- '</div>',
649
- ].join('')
650
-
651
- const rows = [...items].reverse().map(item => {
652
- const color = STATUS_HEX[item.status] ?? '#64748b'
653
- return [
654
- '<tr>',
655
- `<td class="id">${escapeHtml(item.id)}</td>`,
656
- `<td><span class="chip" style="background:${color}">${escapeHtml(item.status)}</span><span class="goal" title="${escapeHtml(item.goal)}">${escapeHtml(item.goal)}</span></td>`,
657
- `<td class="num">${escapeHtml(item.calls ? String(item.calls) : '—')}</td>`,
658
- `<td class="num">${escapeHtml(item.tokens ? formatCount(item.tokens) : '—')}</td>`,
659
- `<td class="num">${escapeHtml(money(item.cost))}</td>`,
660
- `<td class="num">${escapeHtml(formatDuration(item.duration))}</td>`,
661
- `<td class="id">${escapeHtml(item.parent.replace(/^session-/, '').slice(0, 8) || '—')}</td>`,
662
- '</tr>',
663
- ].join('')
664
- })
665
-
666
- const pricedNote = items.length === 0
667
- ? 'No runs matched this window.'
668
- : summary.unpriced > 0
669
- ? `Cost covers ${summary.priced} of ${items.length} runs; models without a configured price are left out rather than estimated.`
670
- : `Cost covers all ${items.length} runs at the prices configured by the operator.`
671
-
672
- return `<!doctype html>
673
- <html lang="en">
674
- <head>
675
- <meta charset="utf-8">
676
- <meta name="viewport" content="width=device-width, initial-scale=1">
677
- <title>${escapeHtml(title)}</title>
678
- <style>${CSS}</style>
679
- </head>
680
- <body>
681
- <main class="page">
682
- <header class="masthead">
683
- <div class="eyebrow">dsh-superagent · run report</div>
684
- <h1>${escapeHtml(title)}</h1>
685
- <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>
686
- <div class="meta">${escapeHtml(windowText)} · generated ${escapeHtml(stampUtc(generatedAt))} UTC · peak concurrency ${laneCount} · ${formatCount(summary.calls)} model calls</div>
687
- </header>
688
- ${cards}
689
- <section class="panel" id="timeline">
690
- <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>
691
- ${legend}
692
- <figure>${timelineSvg(items, { start, end, ticks })}</figure>
693
- </section>
694
- <section class="panel" id="lanes">
695
- <div class="panel-head"><h2>Concurrency</h2><span class="hint">${laneCount} lane${laneCount === 1 ? '' : 's'} · overlapping runs never share a lane</span></div>
696
- <figure>${lanesSvg(items, { start, end, ticks, lanes: laneCount })}</figure>
697
- </section>
698
- <div class="charts">
699
- <section class="panel" id="calls">
700
- <div class="panel-head"><h2>Model calls</h2><span class="hint">cumulative at each run's end</span></div>
701
- <figure>${curveSvg(events, { start, end, ticks, color: '#0284c7', title: 'Cumulative model calls', empty: 'no model calls recorded' })}</figure>
702
- <p class="hint">${escapeHtml(`${summary.calls} calls across ${items.length} run(s), measured from child session usage logs.`)}</p>
703
- </section>
704
- <section class="panel" id="cost">
705
- <div class="panel-head"><h2>Cost</h2><span class="hint">cumulative at each run's end</span></div>
706
- <figure>${curveSvg(costEvents, { start, end, ticks, color: '#0f766e', title: 'Cumulative cost', formatter: value => money(value), empty: 'no priced runs' })}</figure>
707
- <p class="hint">${escapeHtml(pricedNote)}</p>
708
- </section>
709
- </div>
710
- <section class="panel" id="failures">
711
- <div class="panel-head"><h2>Failures &amp; cancellations</h2><span class="hint">every run that did not complete normally</span></div>
712
- ${failures}
713
- </section>
714
- <section class="panel" id="runs">
715
- <div class="panel-head"><h2>Runs</h2><span class="hint">newest first · times in UTC</span></div>
716
- <div class="table-wrap">
717
- <table>
718
- <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>
719
- <tbody>${rows.join('')}</tbody>
720
- </table>
721
- </div>
722
- </section>
723
- <footer>
724
- Self-contained report: inline CSS and inline SVG, no scripts, no external fonts or images, no network access.
725
- 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.
726
- Cost is computed only from operator-configured prices — unpriced models are reported as unpriced, never as zero.
727
- Generated by <code>dsh-superagent-report</code> from <code>${escapeHtml(items.length)}</code> run file(s).
728
- </footer>
729
- </main>
730
- </body>
731
- </html>
732
- `
733
- }
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 { ACTIVE_STATUSES } from './store.js'
16
+ import { callsOf, formatCount, formatDuration } from './watch.js'
17
+
18
+ const STATUS_HEX = {
19
+ queued: '#64748b',
20
+ planning: '#0284c7',
21
+ running: '#0284c7',
22
+ aggregating: '#0284c7',
23
+ completed: '#15803d',
24
+ partial: '#b45309',
25
+ failed: '#b91c1c',
26
+ cancelled: '#7e22ce',
27
+ interrupted: '#c2410c',
28
+ }
29
+
30
+ const STATUS_ORDER = ['running', 'planning', 'aggregating', 'queued', 'completed', 'partial', 'failed', 'cancelled', 'interrupted']
31
+
32
+ /** Phase opacity inside a run bar: plan is fainter, merge is medium. */
33
+ const PHASE_OPACITY = { plan: 0.38, work: 1, merge: 0.66 }
34
+ const PHASE_LABEL = { plan: 'plan', work: 'work', merge: 'merge' }
35
+
36
+ const SVG_FONT = "-apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"
37
+ const MONO_FONT = "ui-monospace, SFMono-Regular, 'Cascadia Mono', Consolas, 'Liberation Mono', monospace"
38
+
39
+ /**
40
+ * Escape text for HTML text nodes and double-quoted attributes.
41
+ * @param {unknown} value - raw value.
42
+ */
43
+ export function escapeHtml(value) {
44
+ return String(value ?? '').replace(/[&<>"']/g, char => ({
45
+ '&': '&amp;',
46
+ '<': '&lt;',
47
+ '>': '&gt;',
48
+ '"': '&quot;',
49
+ "'": '&#39;',
50
+ }[char]))
51
+ }
52
+
53
+ /** Parse an ISO timestamp, or null when absent/unusable. */
54
+ function timeOf(value) {
55
+ const parsed = Date.parse(String(value ?? ''))
56
+ return Number.isFinite(parsed) ? parsed : null
57
+ }
58
+
59
+ /** `$0.0225`, `$1.24`, `<$0.0001`, or `—`. */
60
+ function money(value) {
61
+ if (value === null || value === undefined || !Number.isFinite(value)) return '—'
62
+ if (value === 0) return '$0'
63
+ if (value < 0.0001) return '<$0.0001'
64
+ if (value < 1) return `$${value.toFixed(4)}`
65
+ return `$${value.toFixed(2)}`
66
+ }
67
+
68
+ /** `2026-11-14 07:52:05` in UTC, matching the axis. */
69
+ function stampUtc(ms) {
70
+ if (!Number.isFinite(ms)) return '—'
71
+ const iso = new Date(ms).toISOString()
72
+ return `${iso.slice(0, 10)} ${iso.slice(11, 19)}`
73
+ }
74
+
75
+ /** Axis label: seconds when the window is short, minute precision when long. */
76
+ function axisLabel(ms, span) {
77
+ const date = new Date(ms)
78
+ const hh = String(date.getUTCHours()).padStart(2, '0')
79
+ const mm = String(date.getUTCMinutes()).padStart(2, '0')
80
+ const ss = String(date.getUTCSeconds()).padStart(2, '0')
81
+ if (span > 24 * 3600_000) {
82
+ const mo = String(date.getUTCMonth() + 1).padStart(2, '0')
83
+ const dd = String(date.getUTCDate()).padStart(2, '0')
84
+ return `${mo}-${dd} ${hh}:${mm}`
85
+ }
86
+ return `${hh}:${mm}:${ss}`
87
+ }
88
+
89
+ /** Six-ish evenly spaced ticks that land on round wall-clock values. */
90
+ export function axisTicks(start, end) {
91
+ const span = Math.max(1, end - start)
92
+ const steps = [
93
+ 1000, 2000, 5000, 10_000, 15_000, 30_000,
94
+ 60_000, 120_000, 300_000, 600_000, 900_000, 1_800_000,
95
+ 3_600_000, 7_200_000, 21_600_000, 43_200_000, 86_400_000,
96
+ ]
97
+ const target = span / 6
98
+ const step = steps.find(candidate => candidate >= target) ?? steps[steps.length - 1]
99
+ const ticks = []
100
+ for (let tick = Math.ceil(start / step) * step; tick <= end; tick += step) ticks.push(tick)
101
+ // A window shorter than one step can contain no round boundary at all.
102
+ return { ticks: ticks.length > 0 ? ticks : [start, end], step }
103
+ }
104
+
105
+ /** Truncate to an approximate pixel width at the given font size. */
106
+ function clipTo(text, width, fontSize = 11) {
107
+ const value = String(text ?? '').replace(/\s+/g, ' ').trim()
108
+ const max = Math.max(1, Math.floor(width / (fontSize * 0.58)))
109
+ if (value.length <= max) return value
110
+ if (max <= 1) return '…'
111
+ return `${value.slice(0, max - 1)}…`
112
+ }
113
+
114
+ /** Short run id for a narrow block: the time stamp alone is ambiguous. */
115
+ function shortId(id) {
116
+ const value = String(id ?? '')
117
+ return value.length <= 12 ? value : `…${value.slice(-9)}`
118
+ }
119
+
120
+ /**
121
+ * Derive the three visible phases from recorded timestamps.
122
+ *
123
+ * The run file records status, not phase boundaries, so the boundaries come
124
+ * from the subtasks: planning ends when the first worker starts, work ends when
125
+ * the last worker reports, and merging covers the remainder. The report states
126
+ * this derivation in its footnote rather than implying the phases are exact.
127
+ *
128
+ * @param {object} run - run record.
129
+ * @param {number} now - wall clock for a run that has not finished.
130
+ */
131
+ export function phasesOf(run, now) {
132
+ const created = timeOf(run?.createdAt) ?? timeOf(run?.startedAt) ?? now
133
+ const started = timeOf(run?.startedAt) ?? created
134
+ const finished = timeOf(run?.finishedAt) ?? now
135
+ const subtasks = Array.isArray(run?.subtasks) ? run.subtasks : []
136
+ const starts = subtasks.map(subtask => timeOf(subtask.startedAt)).filter(value => value !== null)
137
+ const ends = subtasks.map(subtask => timeOf(subtask.finishedAt)).filter(value => value !== null)
138
+ const firstWork = starts.length > 0 ? Math.min(...starts) : started
139
+ const lastWork = ends.length > 0 ? Math.max(...ends) : (starts.length > 0 ? Math.min(...starts) : finished)
140
+ const planEnd = Math.min(Math.max(firstWork, started), finished)
141
+ const workEnd = Math.min(Math.max(lastWork, planEnd), finished)
142
+ return [
143
+ { kind: 'plan', start: started, end: planEnd },
144
+ { kind: 'work', start: planEnd, end: workEnd },
145
+ { kind: 'merge', start: workEnd, end: finished },
146
+ ].filter(phase => phase.end > phase.start)
147
+ }
148
+
149
+ /**
150
+ * Greedy interval-graph colouring: a run takes the first lane whose previous
151
+ * run has already ended, otherwise it opens a new lane. Two overlapping runs
152
+ * therefore never share a lane, and the lane count is the true peak
153
+ * concurrency of the selected window.
154
+ *
155
+ * @param {Array<{ start: number, end: number }>} items - spans, sorted by start.
156
+ * @returns {number} number of lanes used.
157
+ */
158
+ export function assignLanes(items) {
159
+ const laneEnds = []
160
+ for (const item of items) {
161
+ let lane = laneEnds.findIndex(end => end <= item.start)
162
+ if (lane === -1) {
163
+ lane = laneEnds.length
164
+ laneEnds.push(item.end)
165
+ } else {
166
+ laneEnds[lane] = item.end
167
+ }
168
+ item.lane = lane
169
+ }
170
+ return laneEnds.length
171
+ }
172
+
173
+ /**
174
+ * Normalise run files into what the page needs, in chronological order.
175
+ * @param {object[]} runs - run records from the store.
176
+ * @param {number} now - wall clock.
177
+ */
178
+ export function prepare(runs, now) {
179
+ const items = []
180
+ for (const run of runs ?? []) {
181
+ if (!run || !run.id) continue
182
+ const start = timeOf(run.startedAt) ?? timeOf(run.createdAt) ?? now
183
+ const end = timeOf(run.finishedAt) ?? now
184
+ const live = ACTIVE_STATUSES.has(run.status)
185
+ const phases = phasesOf(run, now)
186
+ const calls = callsOf(run)
187
+ const cost = Number.isFinite(run.cost?.total) && run.cost?.complete !== false ? run.cost.total : null
188
+ items.push({
189
+ run,
190
+ id: String(run.id),
191
+ status: String(run.status ?? 'unknown'),
192
+ start,
193
+ end: Math.max(end, start),
194
+ live,
195
+ phases,
196
+ calls,
197
+ cost,
198
+ tokens: run.usage?.totalTokens ?? 0,
199
+ duration: Math.max(0, end - start),
200
+ parent: String(run.parentSessionId ?? ''),
201
+ goal: String(run.goal ?? ''),
202
+ error: String(run.error ?? ''),
203
+ subtasks: Array.isArray(run.subtasks) ? run.subtasks : [],
204
+ })
205
+ }
206
+ items.sort((a, b) => a.start - b.start || a.id.localeCompare(b.id))
207
+ return items
208
+ }
209
+
210
+ /** Totals used by the cards and the one-line summary. */
211
+ function summarize(items) {
212
+ const byStatus = {}
213
+ let calls = 0
214
+ let tokens = 0
215
+ let cost = 0
216
+ let priced = 0
217
+ let unpriced = 0
218
+ for (const item of items) {
219
+ byStatus[item.status] = (byStatus[item.status] ?? 0) + 1
220
+ calls += item.calls
221
+ tokens += item.tokens
222
+ if (item.cost !== null) {
223
+ cost += item.cost
224
+ priced += 1
225
+ } else if (item.calls > 0) {
226
+ unpriced += 1
227
+ }
228
+ }
229
+ const start = items.length > 0 ? Math.min(...items.map(item => item.start)) : 0
230
+ const end = items.length > 0 ? Math.max(...items.map(item => item.end)) : 0
231
+ return { byStatus, calls, tokens, cost, priced, unpriced, start, end, span: Math.max(0, end - start) }
232
+ }
233
+
234
+ /**
235
+ * Timeline: one row per run, a bar split into plan/work/merge, and an explicit
236
+ * marker for the runs that did not complete, because a flat bar alone hides
237
+ * whether an early end was success or damage.
238
+ */
239
+ function timelineSvg(items, options) {
240
+ const width = 1240
241
+ const left = 292
242
+ // The right edge is reserved for the outcome marker, so a run that ends at
243
+ // the very last instant still has room for "✕ failed" instead of silently
244
+ // losing the annotation.
245
+ const right = 176
246
+ const top = 54
247
+ const rowHeight = 30
248
+ const height = top + items.length * rowHeight + 26
249
+ const start = options.start
250
+ const end = options.end
251
+ const span = Math.max(1, end - start)
252
+ const track = width - left - right
253
+ const x = time => left + ((time - start) / span) * track
254
+ const { ticks } = options
255
+ const parts = []
256
+
257
+ parts.push(`<svg viewBox="0 0 ${width} ${height}" role="img" aria-labelledby="timeline-title timeline-desc">`)
258
+ parts.push('<title id="timeline-title">Run timeline</title>')
259
+ 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>`)
260
+
261
+ for (const tick of ticks) {
262
+ const gx = x(tick).toFixed(1)
263
+ parts.push(`<line x1="${gx}" y1="${top - 18}" x2="${gx}" y2="${height - 20}" stroke="#eef1f5" stroke-width="1"/>`)
264
+ parts.push(`<text x="${gx}" y="${top - 26}" text-anchor="middle" class="axis" fill="#94a3b8">${escapeHtml(axisLabel(tick, span))}</text>`)
265
+ }
266
+
267
+ items.forEach((item, index) => {
268
+ const y = top + index * rowHeight
269
+ const color = STATUS_HEX[item.status] ?? '#64748b'
270
+ if (index % 2 === 1) {
271
+ parts.push(`<rect x="8" y="${y}" width="${width - 16}" height="${rowHeight - 1}" rx="4" fill="#fbfcfe"/>`)
272
+ }
273
+ parts.push(`<line x1="16" y1="${y + rowHeight - 0.5}" x2="${width - 16}" y2="${y + rowHeight - 0.5}" stroke="#f1f5f9" stroke-width="1"/>`)
274
+ parts.push(`<text x="16" y="${y + 13}" class="id" fill="#0f172a">${escapeHtml(item.id)}</text>`)
275
+ parts.push(`<text x="16" y="${y + 25}" class="meta" fill="${color}">${escapeHtml(item.status.toUpperCase())} · ${escapeHtml(formatDuration(item.duration))}</text>`)
276
+
277
+ const phases = item.phases.length > 0
278
+ ? item.phases
279
+ // A run that started and ended in the same millisecond has no positive
280
+ // span to draw; keep a tick so the row is not silently blank.
281
+ : [{ kind: 'work', start: item.start, end: item.start }]
282
+ for (const phase of phases) {
283
+ const px = x(phase.start)
284
+ // A sub-second run on a multi-hour axis is a hairline. Give it three
285
+ // pixels so it stays visible and clickable instead of disappearing.
286
+ const pw = Math.max(3, x(phase.end) - px)
287
+ const opacity = PHASE_OPACITY[phase.kind] ?? 0.6
288
+ 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>`)
289
+ }
290
+
291
+ // Subtask boundaries inside the work phase: a thin white notch is enough
292
+ // to show whether workers overlapped or ran one after another.
293
+ const notches = new Set()
294
+ for (const subtask of item.subtasks) {
295
+ for (const edge of [timeOf(subtask.startedAt), timeOf(subtask.finishedAt)]) {
296
+ if (edge !== null) notches.add(edge)
297
+ }
298
+ }
299
+ for (const notch of notches) {
300
+ if (notch <= start || notch >= end) continue
301
+ const nx = x(notch)
302
+ const barStart = x(item.start)
303
+ const barEnd = x(item.end)
304
+ if (nx <= barStart + 2 || nx >= barEnd - 2) continue
305
+ 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"/>`)
306
+ }
307
+
308
+ if (item.live) {
309
+ 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"/>`)
310
+ }
311
+
312
+ const markers = {
313
+ failed: '✕ failed',
314
+ cancelled: '⊘ cancelled',
315
+ interrupted: '! interrupted',
316
+ partial: '△ partial',
317
+ }
318
+ const marker = markers[item.status]
319
+ if (marker) {
320
+ const available = width - 16 - (x(item.end) + 8)
321
+ 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>`)
322
+ }
323
+ })
324
+
325
+ parts.push('</svg>')
326
+ return parts.join('')
327
+ }
328
+
329
+ /**
330
+ * Swimlanes: the same runs placed on the minimum number of lanes so that
331
+ * overlaps are visible as horizontal neighbours instead of hidden in a
332
+ * chronological list.
333
+ */
334
+ function lanesSvg(items, options) {
335
+ const lanes = options.lanes
336
+ const laneHeight = 40
337
+ const width = 1240
338
+ const left = 92
339
+ const right = 48
340
+ const top = 44
341
+ const height = top + Math.max(1, lanes) * laneHeight + 34
342
+ const start = options.start
343
+ const end = options.end
344
+ const span = Math.max(1, end - start)
345
+ const track = width - left - right
346
+ const x = time => left + ((time - start) / span) * track
347
+ const parts = []
348
+
349
+ parts.push(`<svg viewBox="0 0 ${width} ${height}" role="img" aria-labelledby="lanes-title lanes-desc">`)
350
+ parts.push('<title id="lanes-title">Concurrency swimlanes</title>')
351
+ 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>`)
352
+
353
+ for (let lane = 0; lane < Math.max(1, lanes); lane++) {
354
+ const y = top + lane * laneHeight
355
+ parts.push(`<rect x="${left}" y="${y + 5}" width="${track}" height="${laneHeight - 10}" rx="6" fill="#f8fafc"/>`)
356
+ parts.push(`<text x="${left - 12}" y="${y + laneHeight / 2 + 4}" text-anchor="end" class="axis" fill="#94a3b8">lane ${lane + 1}</text>`)
357
+ }
358
+
359
+ for (const tick of options.ticks) {
360
+ const gx = x(tick).toFixed(1)
361
+ parts.push(`<line x1="${gx}" y1="${top}" x2="${gx}" y2="${height - 26}" stroke="#eef1f5" stroke-width="1"/>`)
362
+ parts.push(`<text x="${gx}" y="${height - 10}" text-anchor="middle" class="axis" fill="#94a3b8">${escapeHtml(axisLabel(tick, span))}</text>`)
363
+ }
364
+
365
+ for (const item of items) {
366
+ const color = STATUS_HEX[item.status] ?? '#64748b'
367
+ const y = top + item.lane * laneHeight + 9
368
+ const bx = x(item.start)
369
+ const bw = Math.max(4, x(item.end) - bx)
370
+ 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>`)
371
+ if (bw > 74) {
372
+ parts.push(`<text x="${(bx + 7).toFixed(1)}" y="${y + 14}" class="lane-label" fill="#ffffff">${escapeHtml(shortId(item.id))}</text>`)
373
+ }
374
+ }
375
+
376
+ parts.push('</svg>')
377
+ return parts.join('')
378
+ }
379
+
380
+ /** Round a value up to a 1/2/5 × 10^n axis maximum. */
381
+ function niceMax(value) {
382
+ if (!Number.isFinite(value) || value <= 0) return 1
383
+ const power = 10 ** Math.floor(Math.log10(value))
384
+ const scaled = value / power
385
+ const factor = scaled <= 1 ? 1 : scaled <= 2 ? 2 : scaled <= 5 ? 5 : 10
386
+ return factor * power
387
+ }
388
+
389
+ /**
390
+ * Cumulative step chart. Events land at each run's end time, so the curve
391
+ * answers "how much had this window spent by 09:15?" without pretending to
392
+ * know the intra-run shape that the run files do not record.
393
+ *
394
+ * @param {Array<{ t: number, value: number }>} events - sorted by time.
395
+ * @param {{ start: number, end: number, color: string, ticks: number[], formatter?: (value: number) => string, empty?: string, title: string }} options
396
+ */
397
+ function curveSvg(events, options) {
398
+ const width = 620
399
+ const height = 220
400
+ const left = 58
401
+ const right = 16
402
+ const top = 20
403
+ const bottom = 38
404
+ const plotW = width - left - right
405
+ const plotH = height - top - bottom
406
+ const start = options.start
407
+ const end = options.end
408
+ const span = Math.max(1, end - start)
409
+ const x = time => left + ((time - start) / span) * plotW
410
+ const eventsWithValue = events.filter(event => Number.isFinite(event.value))
411
+ const total = eventsWithValue.reduce((sum, event) => sum + event.value, 0)
412
+ const max = niceMax(total)
413
+ const y = value => top + plotH - (value / max) * plotH
414
+ const format = options.formatter ?? (value => formatCount(value))
415
+ const parts = []
416
+
417
+ parts.push(`<svg viewBox="0 0 ${width} ${height}" role="img" aria-label="${escapeHtml(options.title)}">`)
418
+ parts.push(`<rect x="${left}" y="${top}" width="${plotW}" height="${plotH}" fill="#f8fafc" rx="6"/>`)
419
+
420
+ for (let index = 0; index <= 4; index++) {
421
+ const value = (max / 4) * index
422
+ const gy = y(value).toFixed(1)
423
+ parts.push(`<line x1="${left}" y1="${gy}" x2="${left + plotW}" y2="${gy}" stroke="#e8edf3" stroke-width="1"/>`)
424
+ parts.push(`<text x="${left - 10}" y="${Number(gy) + 4}" text-anchor="end" class="axis" fill="#94a3b8">${escapeHtml(format(value))}</text>`)
425
+ }
426
+
427
+ for (const tick of options.ticks) {
428
+ const gx = x(tick).toFixed(1)
429
+ parts.push(`<line x1="${gx}" y1="${top}" x2="${gx}" y2="${top + plotH}" stroke="#eef1f5" stroke-width="1"/>`)
430
+ parts.push(`<text x="${gx}" y="${height - 12}" text-anchor="middle" class="axis" fill="#94a3b8">${escapeHtml(axisLabel(tick, span))}</text>`)
431
+ }
432
+
433
+ if (eventsWithValue.length === 0) {
434
+ 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>`)
435
+ parts.push('</svg>')
436
+ return parts.join('')
437
+ }
438
+
439
+ let cursor = 0
440
+ let path = `M ${x(start).toFixed(1)} ${y(0).toFixed(1)}`
441
+ for (const event of eventsWithValue) {
442
+ cursor += event.value
443
+ path += ` H ${x(event.t).toFixed(1)} V ${y(cursor).toFixed(1)}`
444
+ }
445
+ path += ` H ${x(end).toFixed(1)}`
446
+
447
+ parts.push(`<path d="${path} V ${y(0).toFixed(1)} H ${x(start).toFixed(1)} Z" fill="${options.color}" opacity="0.10"/>`)
448
+ parts.push(`<path d="${path}" fill="none" stroke="${options.color}" stroke-width="2" stroke-linejoin="round"/>`)
449
+
450
+ let running = 0
451
+ for (const event of eventsWithValue) {
452
+ running += event.value
453
+ 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>`)
454
+ }
455
+
456
+ parts.push('</svg>')
457
+ return parts.join('')
458
+ }
459
+
460
+ /** One stat card. */
461
+ function card(label, value, note, accent) {
462
+ return [
463
+ '<div class="card">',
464
+ `<div class="card-label">${escapeHtml(label)}</div>`,
465
+ `<div class="card-value"${accent ? ` style="color:${accent}"` : ''}>${escapeHtml(value)}</div>`,
466
+ `<div class="card-note">${escapeHtml(note)}</div>`,
467
+ '</div>',
468
+ ].join('')
469
+ }
470
+
471
+ const CSS = `
472
+ :root {
473
+ color-scheme: light;
474
+ --ink: #0f172a;
475
+ --muted: #64748b;
476
+ --line: #e5e9f0;
477
+ --card: #ffffff;
478
+ --accent: #0f766e;
479
+ }
480
+ * { box-sizing: border-box; }
481
+ html, body { margin: 0; padding: 0; }
482
+ body {
483
+ background: #f4f6fa;
484
+ background-image: radial-gradient(900px 420px at 12% -8%, #e6f2f1 0%, rgba(230,242,241,0) 70%),
485
+ radial-gradient(760px 380px at 96% 4%, #eef0fb 0%, rgba(238,240,251,0) 66%);
486
+ color: var(--ink);
487
+ font: 14px/1.55 ${SVG_FONT};
488
+ -webkit-font-smoothing: antialiased;
489
+ }
490
+ .page { max-width: 1280px; margin: 0 auto; padding: 44px 32px 64px; }
491
+ .masthead { margin-bottom: 26px; }
492
+ .eyebrow {
493
+ font: 600 11px/1 ${MONO_FONT};
494
+ letter-spacing: .14em;
495
+ text-transform: uppercase;
496
+ color: var(--accent);
497
+ }
498
+ h1 { font-size: 34px; line-height: 1.15; letter-spacing: -.02em; margin: 12px 0 8px; }
499
+ .lede { margin: 0; max-width: 760px; color: #475569; font-size: 15px; }
500
+ .meta { margin-top: 14px; font: 12px/1.5 ${MONO_FONT}; color: #7c8899; }
501
+ .cards { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 12px; margin: 26px 0 22px; }
502
+ .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); }
503
+ .card-label { font: 600 10px/1 ${MONO_FONT}; letter-spacing: .12em; text-transform: uppercase; color: #8b98a9; }
504
+ .card-value { font-size: 26px; font-weight: 650; letter-spacing: -.02em; margin: 9px 0 4px; font-variant-numeric: tabular-nums; }
505
+ .card-note { font-size: 11.5px; color: var(--muted); }
506
+ .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); }
507
+ .panel-head { display: flex; align-items: baseline; justify-content: space-between; gap: 18px; margin-bottom: 10px; flex-wrap: wrap; }
508
+ .panel h2 { font-size: 15px; letter-spacing: -.01em; margin: 0; }
509
+ .panel .hint { font-size: 12px; color: var(--muted); }
510
+ .legend { display: flex; gap: 16px; flex-wrap: wrap; font-size: 11.5px; color: #5b6b7f; margin: 4px 0 6px; }
511
+ .legend span { display: inline-flex; align-items: center; gap: 6px; }
512
+ .swatch { width: 10px; height: 10px; border-radius: 3px; display: inline-block; }
513
+ figure { margin: 0; overflow-x: auto; }
514
+ svg { display: block; width: 100%; height: auto; min-width: 720px; }
515
+ svg text { font-family: ${SVG_FONT}; }
516
+ svg .axis { font-family: ${MONO_FONT}; font-size: 10px; }
517
+ svg .id { font-family: ${MONO_FONT}; font-size: 11px; font-weight: 600; }
518
+ svg .meta { font-family: ${MONO_FONT}; font-size: 9.5px; letter-spacing: .04em; }
519
+ svg .mark { font-size: 10px; font-weight: 600; }
520
+ svg .lane-label { font-family: ${MONO_FONT}; font-size: 9.5px; }
521
+ svg .empty { font-size: 12px; fill: #94a3b8; }
522
+ .charts { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
523
+ .charts .panel { margin-bottom: 18px; }
524
+ .charts svg { min-width: 0; }
525
+ .failures { display: grid; gap: 10px; }
526
+ .failure { border: 1px solid var(--line); border-left: 3px solid #b91c1c; border-radius: 8px; padding: 10px 13px; background: #fff; }
527
+ .failure.cancelled { border-left-color: #7e22ce; }
528
+ .failure.interrupted { border-left-color: #c2410c; }
529
+ .failure.partial { border-left-color: #b45309; }
530
+ .failure-head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font: 600 11.5px/1.4 ${MONO_FONT}; }
531
+ .failure-head .chip { font-size: 9.5px; letter-spacing: .06em; padding: 2px 7px; border-radius: 999px; color: #fff; }
532
+ .failure-body { margin-top: 6px; font-size: 12.5px; color: #475569; }
533
+ .failure-body code { font-family: ${MONO_FONT}; font-size: 11.5px; background: #f4f6fa; padding: 1px 5px; border-radius: 4px; }
534
+ .failure .when { color: #8b98a9; font-weight: 400; }
535
+ .table-wrap { overflow-x: auto; }
536
+ table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
537
+ 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); }
538
+ td { padding: 10px; border-bottom: 1px solid #f1f4f8; vertical-align: top; }
539
+ tr:last-child td { border-bottom: 0; }
540
+ td.num { text-align: right; font-family: ${MONO_FONT}; font-variant-numeric: tabular-nums; white-space: nowrap; }
541
+ td.id { font-family: ${MONO_FONT}; font-size: 11.5px; white-space: nowrap; }
542
+ .goal { display: block; max-width: 520px; color: #475569; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
543
+ .chip { display: inline-block; padding: 2px 8px; border-radius: 999px; font: 600 10px/1.6 ${MONO_FONT}; letter-spacing: .05em; color: #fff; }
544
+ footer { margin-top: 26px; color: #8b98a9; font-size: 11.5px; line-height: 1.7; }
545
+ footer code { font-family: ${MONO_FONT}; }
546
+ @media (max-width: 1100px) {
547
+ .cards { grid-template-columns: repeat(3, minmax(0, 1fr)); }
548
+ }
549
+ @media (max-width: 680px) {
550
+ .cards { grid-template-columns: repeat(2, minmax(0, 1fr)); }
551
+ }
552
+ @media (max-width: 900px) {
553
+ .charts { grid-template-columns: 1fr; }
554
+ .page { padding: 28px 16px 44px; }
555
+ h1 { font-size: 26px; }
556
+ }
557
+ @media print {
558
+ body { background: #fff; }
559
+ .page { max-width: none; padding: 0; }
560
+ .panel, .card { box-shadow: none; break-inside: avoid; }
561
+ }
562
+ `
563
+
564
+ /**
565
+ * Build the full report.
566
+ *
567
+ * @param {object[]} runs - run records, any order.
568
+ * @param {{ title?: string, generatedAt?: number, now?: number, subtitle?: string }} [options]
569
+ * @returns {string} a complete HTML document with no external references.
570
+ */
571
+ export function buildReport(runs, options = {}) {
572
+ const now = options.now ?? Date.now()
573
+ const generatedAt = options.generatedAt ?? now
574
+ const items = prepare(runs, now)
575
+ const summary = summarize(items)
576
+ const start = summary.start
577
+ const end = summary.end
578
+ const span = Math.max(1, summary.span)
579
+ const { ticks } = axisTicks(start, end)
580
+ const laneCount = assignLanes(items)
581
+ const title = options.title ?? 'Superagent run report'
582
+ const finished = items.filter(item => !ACTIVE_STATUSES.has(item.status)).length
583
+ const windowText = items.length > 0 ? `${stampUtc(start)} → ${stampUtc(end)} UTC` : 'no runs'
584
+
585
+ const events = items
586
+ .filter(item => item.calls > 0)
587
+ .map(item => ({ t: item.end, value: item.calls }))
588
+ .sort((a, b) => a.t - b.t)
589
+ const costEvents = items
590
+ .filter(item => item.cost !== null && item.cost > 0)
591
+ .map(item => ({ t: item.end, value: item.cost }))
592
+ .sort((a, b) => a.t - b.t)
593
+
594
+ const problemRuns = items
595
+ .filter(item => ['failed', 'cancelled', 'interrupted', 'partial'].includes(item.status))
596
+ .sort((a, b) => b.end - a.end)
597
+
598
+ const statusCards = [
599
+ card('Runs', String(items.length), `${finished} finished · ${items.length - finished} live`),
600
+ card('Completed', String(summary.byStatus.completed ?? 0), `${summary.byStatus.partial ?? 0} partial`, '#15803d'),
601
+ card('Failed', String(summary.byStatus.failed ?? 0), `${summary.byStatus.cancelled ?? 0} cancelled · ${summary.byStatus.interrupted ?? 0} interrupted`, '#b91c1c'),
602
+ card('Model calls', formatCount(summary.calls), 'measured from child sessions'),
603
+ card('Tokens', formatCount(summary.tokens), 'input + cache + output'),
604
+ card('Cost', summary.priced === 0 ? 'unpriced' : money(summary.cost), summary.priced === 0 ? 'no configured price for these models' : `${summary.priced}/${items.length} runs priced`, '#0f766e'),
605
+ ].join('')
606
+
607
+ const cards = [
608
+ '<section class="cards">',
609
+ statusCards,
610
+ '</section>',
611
+ ].join('')
612
+
613
+ const legend = [
614
+ '<div class="legend">',
615
+ `<span><i class="swatch" style="background:${STATUS_HEX.running}"></i> planning / running / aggregating</span>`,
616
+ `<span><i class="swatch" style="background:${STATUS_HEX.completed}"></i> completed</span>`,
617
+ `<span><i class="swatch" style="background:${STATUS_HEX.failed}"></i> failed</span>`,
618
+ `<span><i class="swatch" style="background:${STATUS_HEX.cancelled}"></i> cancelled</span>`,
619
+ `<span><i class="swatch" style="background:${STATUS_HEX.interrupted}"></i> interrupted</span>`,
620
+ '<span><i class="swatch" style="background:#94a3b8;opacity:.38"></i> plan</span>',
621
+ '<span><i class="swatch" style="background:#94a3b8"></i> work</span>',
622
+ '<span><i class="swatch" style="background:#94a3b8;opacity:.66"></i> merge</span>',
623
+ '</div>',
624
+ ].join('')
625
+
626
+ const failures = problemRuns.length === 0
627
+ ? '<p class="hint">No failed, cancelled, interrupted, or partial runs in this window.</p>'
628
+ : [
629
+ '<div class="failures">',
630
+ ...problemRuns.map(item => {
631
+ const color = STATUS_HEX[item.status] ?? '#64748b'
632
+ const detail = item.error
633
+ ? escapeHtml(item.error)
634
+ : item.status === 'cancelled'
635
+ ? `Cancelled after ${escapeHtml(formatDuration(item.duration))}, ${escapeHtml(String(item.calls))} call(s) spent.`
636
+ : item.status === 'interrupted'
637
+ ? `The host went away after ${escapeHtml(formatDuration(item.duration))}; resume it with <code>superagent_resume</code>.`
638
+ : `Ended after ${escapeHtml(formatDuration(item.duration))} without a recorded error.`
639
+ return [
640
+ `<div class="failure ${escapeHtml(item.status)}">`,
641
+ `<div class="failure-head"><span class="chip" style="background:${color}">${escapeHtml(item.status.toUpperCase())}</span>`,
642
+ `<span>${escapeHtml(item.id)}</span>`,
643
+ `<span class="when">${escapeHtml(stampUtc(item.start))} UTC · ${escapeHtml(formatDuration(item.duration))}</span></div>`,
644
+ `<div class="failure-body">${detail}</div>`,
645
+ '</div>',
646
+ ].join('')
647
+ }),
648
+ '</div>',
649
+ ].join('')
650
+
651
+ const rows = [...items].reverse().map(item => {
652
+ const color = STATUS_HEX[item.status] ?? '#64748b'
653
+ return [
654
+ '<tr>',
655
+ `<td class="id">${escapeHtml(item.id)}</td>`,
656
+ `<td><span class="chip" style="background:${color}">${escapeHtml(item.status)}</span><span class="goal" title="${escapeHtml(item.goal)}">${escapeHtml(item.goal)}</span></td>`,
657
+ `<td class="num">${escapeHtml(item.calls ? String(item.calls) : '—')}</td>`,
658
+ `<td class="num">${escapeHtml(item.tokens ? formatCount(item.tokens) : '—')}</td>`,
659
+ `<td class="num">${escapeHtml(money(item.cost))}</td>`,
660
+ `<td class="num">${escapeHtml(formatDuration(item.duration))}</td>`,
661
+ `<td class="id">${escapeHtml(item.parent.replace(/^session-/, '').slice(0, 8) || '—')}</td>`,
662
+ '</tr>',
663
+ ].join('')
664
+ })
665
+
666
+ const pricedNote = items.length === 0
667
+ ? 'No runs matched this window.'
668
+ : summary.unpriced > 0
669
+ ? `Cost covers ${summary.priced} of ${items.length} runs; models without a configured price are left out rather than estimated.`
670
+ : `Cost covers all ${items.length} runs at the prices configured by the operator.`
671
+
672
+ return `<!doctype html>
673
+ <html lang="en">
674
+ <head>
675
+ <meta charset="utf-8">
676
+ <meta name="viewport" content="width=device-width, initial-scale=1">
677
+ <title>${escapeHtml(title)}</title>
678
+ <style>${CSS}</style>
679
+ </head>
680
+ <body>
681
+ <main class="page">
682
+ <header class="masthead">
683
+ <div class="eyebrow">dsh-superagent · run report</div>
684
+ <h1>${escapeHtml(title)}</h1>
685
+ <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>
686
+ <div class="meta">${escapeHtml(windowText)} · generated ${escapeHtml(stampUtc(generatedAt))} UTC · peak concurrency ${laneCount} · ${formatCount(summary.calls)} model calls</div>
687
+ </header>
688
+ ${cards}
689
+ <section class="panel" id="timeline">
690
+ <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>
691
+ ${legend}
692
+ <figure>${timelineSvg(items, { start, end, ticks })}</figure>
693
+ </section>
694
+ <section class="panel" id="lanes">
695
+ <div class="panel-head"><h2>Concurrency</h2><span class="hint">${laneCount} lane${laneCount === 1 ? '' : 's'} · overlapping runs never share a lane</span></div>
696
+ <figure>${lanesSvg(items, { start, end, ticks, lanes: laneCount })}</figure>
697
+ </section>
698
+ <div class="charts">
699
+ <section class="panel" id="calls">
700
+ <div class="panel-head"><h2>Model calls</h2><span class="hint">cumulative at each run's end</span></div>
701
+ <figure>${curveSvg(events, { start, end, ticks, color: '#0284c7', title: 'Cumulative model calls', empty: 'no model calls recorded' })}</figure>
702
+ <p class="hint">${escapeHtml(`${summary.calls} calls across ${items.length} run(s), measured from child session usage logs.`)}</p>
703
+ </section>
704
+ <section class="panel" id="cost">
705
+ <div class="panel-head"><h2>Cost</h2><span class="hint">cumulative at each run's end</span></div>
706
+ <figure>${curveSvg(costEvents, { start, end, ticks, color: '#0f766e', title: 'Cumulative cost', formatter: value => money(value), empty: 'no priced runs' })}</figure>
707
+ <p class="hint">${escapeHtml(pricedNote)}</p>
708
+ </section>
709
+ </div>
710
+ <section class="panel" id="failures">
711
+ <div class="panel-head"><h2>Failures &amp; cancellations</h2><span class="hint">every run that did not complete normally</span></div>
712
+ ${failures}
713
+ </section>
714
+ <section class="panel" id="runs">
715
+ <div class="panel-head"><h2>Runs</h2><span class="hint">newest first · times in UTC</span></div>
716
+ <div class="table-wrap">
717
+ <table>
718
+ <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>
719
+ <tbody>${rows.join('')}</tbody>
720
+ </table>
721
+ </div>
722
+ </section>
723
+ <footer>
724
+ Self-contained report: inline CSS and inline SVG, no scripts, no external fonts or images, no network access.
725
+ 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.
726
+ Cost is computed only from operator-configured prices — unpriced models are reported as unpriced, never as zero.
727
+ Generated by <code>dsh-superagent-report</code> from <code>${escapeHtml(items.length)}</code> run file(s).
728
+ </footer>
729
+ </main>
730
+ </body>
731
+ </html>
732
+ `
733
+ }