@agentguard-run/burn 0.3.24 → 0.3.26

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.
@@ -24,6 +24,7 @@ exports.calendarReport = calendarReport;
24
24
  const node_crypto_1 = require("node:crypto");
25
25
  const node_fs_1 = require("node:fs");
26
26
  const node_path_1 = require("node:path");
27
+ const subagent_signals_1 = require("../history/subagent-signals");
27
28
  const history_1 = require("./history");
28
29
  const pricing_1 = require("./pricing");
29
30
  const render_1 = require("./render");
@@ -39,7 +40,8 @@ exports.CALENDAR_MAX_WEEKS = 53;
39
40
  exports.CALENDAR_GRID_PREFIX = Math.max(...Object.values(i18n_1.CALENDAR_TEXT).flatMap(text => text.weekdays.map(label => label.length))) + 1;
40
41
  /** Transcripts larger than this are parsed in pieces (see InsightReadOptions), which bounds memory on a machine of 400 MB sessions. */
41
42
  const CHUNK_BYTES = 16 * 1024 * 1024;
42
- const CACHE_SCHEMA = 3, ROLLUP_SCHEMA = 1;
43
+ /** 4: each transcript's cached counts carry the sub-agent outcomes it records. */
44
+ const CACHE_SCHEMA = 4, ROLLUP_SCHEMA = 1;
43
45
  const sha256 = (text) => (0, node_crypto_1.createHash)('sha256').update(text).digest('hex');
44
46
  const pad = (n) => String(n).padStart(2, '0');
45
47
  /** The local calendar day of an instant, YYYY-MM-DD, in this process's time zone. */
@@ -76,6 +78,8 @@ function transcriptUnits(locations) {
76
78
  }
77
79
  return units.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
78
80
  }
81
+ /** A stored sub-agent's key, `<session>/agent-<id>`: its session and its sub-agent id. */
82
+ const SUBAGENT_KEY = /^([^/]+)\/agent-([A-Za-z0-9][A-Za-z0-9_-]{0,63})$/;
79
83
  /** Parser ids are SHA-256 digests; 64 bits of one tell a machine's responses apart. */
80
84
  const turnKey = (id) => /^[0-9a-f]{64}$/.test(id) ? id.slice(0, 16) : sha256(id).slice(0, 16);
81
85
  const rowTokens = (row) => row[5] + row[6] + row[7] + row[8];
@@ -98,7 +102,9 @@ function readUnit(unit, rates) {
98
102
  turn.inputTokens, turn.cacheWriteTokens, turn.cacheReadTokens, turn.outputTokens,
99
103
  split ? turn.cacheWrite5mTokens : null, split ? turn.cacheWrite1hTokens : null, turn.cacheTtlSeconds ?? null, turn.subagent ? 1 : 0];
100
104
  });
101
- return { host: unit.host, key: unit.key, models, rows, forkUnknown: false };
105
+ const signals = transcript.state.subagentSignals;
106
+ return { host: unit.host, key: unit.key, models, rows, forkUnknown: false,
107
+ ...(signals ? { agents: [Object.keys(signals.completed ?? {}), Object.keys(signals.ended ?? {}), Object.keys(signals.resumed ?? {})] } : {}) };
102
108
  }
103
109
  /**
104
110
  * A cached response as a turn again, for the rare response recorded in more
@@ -142,8 +148,13 @@ const DAY = /^\d{4}-\d{2}-\d{2}$/;
142
148
  function figuresOf(value) {
143
149
  const raw = record(value), usd = record(raw.usd);
144
150
  const models = Array.isArray(raw.unpricedModels) ? raw.unpricedModels.filter((model) => model === null || typeof model === 'string') : [];
151
+ const unfinishedUsd = record(raw.unfinishedUsd);
145
152
  return { tokens: count(raw.tokens), subagentTokens: count(raw.subagentTokens), usd: { min: count(usd.min), max: count(usd.max) },
146
- unpricedTokens: count(raw.unpricedTokens), unpricedModels: models };
153
+ unpricedTokens: count(raw.unpricedTokens), unpricedModels: models,
154
+ // Kept only where a sub-agent's first day carries them; a day an older Burn counted has none.
155
+ ...(raw.subagents !== undefined ? { subagents: count(raw.subagents) } : {}),
156
+ ...(raw.unfinishedSubagents !== undefined ? { unfinishedSubagents: count(raw.unfinishedSubagents), unfinishedTokens: count(raw.unfinishedTokens),
157
+ unfinishedUsd: { min: count(unfinishedUsd.min), max: count(unfinishedUsd.max) }, unfinishedUnpricedTokens: count(raw.unfinishedUnpricedTokens) } : {}) };
147
158
  }
148
159
  /** The daily count on disk. An unreadable file is moved aside, never overwritten, so it can still be recovered. */
149
160
  function readRollup(home) {
@@ -203,7 +214,9 @@ function cacheSignature(rates) {
203
214
  function cachedUnit(value, file) {
204
215
  const unit = record(value);
205
216
  const same = Array.isArray(unit.file) && unit.file.length === 3 && unit.file.every((part, i) => part === file[i]);
206
- return same && typeof unit.key === 'string' && Array.isArray(unit.models) && Array.isArray(unit.rows)
217
+ const agents = unit.agents === undefined || (Array.isArray(unit.agents) && unit.agents.length === 3
218
+ && unit.agents.every(ids => Array.isArray(ids) && ids.every(id => typeof id === 'string')));
219
+ return same && agents && typeof unit.key === 'string' && Array.isArray(unit.models) && Array.isArray(unit.rows)
207
220
  && (unit.host === 'claude' || unit.host === 'codex') && typeof unit.forkUnknown === 'boolean' ? unit : undefined;
208
221
  }
209
222
  /* ----------------------------------------------------------------- ledger */
@@ -317,6 +330,40 @@ function collectCalendar(options) {
317
330
  shared[id] = merged.sessionId;
318
331
  add(merged.sessionId, merged.at ?? null, merged.inputTokens + merged.cacheWriteTokens + merged.cacheReadTokens + merged.outputTokens, merged.subagent === true, (0, pricing_1.priceTurn)(merged, rates).usd, merged.model ?? null);
319
332
  }
333
+ // Each stored sub-agent counts once, on its first day with tokens. Whether it
334
+ // ended without finishing is what its session's transcripts record: the
335
+ // parent's, and those of sub-agents that launched others. One that may still
336
+ // be running, or whose end no transcript records, is never counted as ended.
337
+ const outcomes = new Map();
338
+ for (const entry of loaded) {
339
+ if (!entry.agents)
340
+ continue;
341
+ const session = entry.key.split('/', 1)[0];
342
+ const sets = outcomes.get(session) ?? { completed: new Set(), ended: new Set(), resumed: new Set() };
343
+ const [completed, ended, resumed] = entry.agents;
344
+ for (const id of completed)
345
+ sets.completed.add(id);
346
+ for (const id of ended)
347
+ sets.ended.add(id);
348
+ for (const id of resumed)
349
+ sets.resumed.add(id);
350
+ outcomes.set(session, sets);
351
+ }
352
+ for (const [key, own] of fresh) {
353
+ const match = SUBAGENT_KEY.exec(key), firstDay = Object.keys(own).sort()[0];
354
+ if (!match || firstDay === undefined)
355
+ continue;
356
+ const target = own[firstDay];
357
+ target.subagents = 1;
358
+ const sets = outcomes.get(match[1]);
359
+ if (!sets || !(0, subagent_signals_1.endedWithoutFinishing)(match[2], sets))
360
+ continue;
361
+ const used = Object.values(own);
362
+ target.unfinishedSubagents = 1;
363
+ target.unfinishedTokens = used.reduce((sum, figures) => sum + figures.tokens, 0);
364
+ target.unfinishedUsd = used.reduce((sum, figures) => ({ min: sum.min + figures.usd.min, max: sum.max + figures.usd.max }), { min: 0, max: 0 });
365
+ target.unfinishedUnpricedTokens = used.reduce((sum, figures) => sum + figures.unpricedTokens, 0);
366
+ }
320
367
  // Files on disk replace their own days; files that are gone keep theirs.
321
368
  const files = {};
322
369
  let rollupFiles = 0;
@@ -368,6 +415,14 @@ function collectCalendar(options) {
368
415
  total.claudeTokens += figures.tokens;
369
416
  else
370
417
  total.codexTokens += figures.tokens;
418
+ if (figures.subagents)
419
+ total.subagents = (total.subagents ?? 0) + figures.subagents;
420
+ if (figures.unfinishedSubagents) {
421
+ total.unfinishedSubagents = (total.unfinishedSubagents ?? 0) + figures.unfinishedSubagents;
422
+ total.unfinishedTokens = (total.unfinishedTokens ?? 0) + (figures.unfinishedTokens ?? 0);
423
+ total.unfinishedUsd = { min: (total.unfinishedUsd?.min ?? 0) + (figures.unfinishedUsd?.min ?? 0), max: (total.unfinishedUsd?.max ?? 0) + (figures.unfinishedUsd?.max ?? 0) };
424
+ total.unfinishedUnpricedTokens = (total.unfinishedUnpricedTokens ?? 0) + (figures.unfinishedUnpricedTokens ?? 0);
425
+ }
371
426
  days.set(day, total);
372
427
  }
373
428
  }
@@ -420,10 +475,24 @@ function calendarReport(data, options = {}) {
420
475
  .sort((a, b) => a === b ? 0 : a === null ? 1 : b === null ? -1 : a < b ? -1 : 1);
421
476
  const usd = tokens > 0 && unpricedTokens === tokens ? null : days.reduce((total, day) => ({ min: total.min + day.usd.min, max: total.max + day.usd.max }), { min: 0, max: 0 });
422
477
  const busiest = days.reduce((best, day) => day.tokens > (best?.tokens ?? 0) ? day : best, null);
478
+ // A sub-agent is in the span when its first day is: its count and all of its tokens together.
479
+ const stored = { subagents: 0, unfinishedSubagents: 0, unfinishedTokens: 0, unfinishedUnpricedTokens: 0, unfinishedUsd: { min: 0, max: 0 } };
480
+ for (const day of days) {
481
+ const figures = data.days.get(day.date);
482
+ if (!figures)
483
+ continue;
484
+ stored.subagents += figures.subagents ?? 0;
485
+ stored.unfinishedSubagents += figures.unfinishedSubagents ?? 0;
486
+ stored.unfinishedTokens += figures.unfinishedTokens ?? 0;
487
+ stored.unfinishedUnpricedTokens += figures.unfinishedUnpricedTokens ?? 0;
488
+ stored.unfinishedUsd = { min: stored.unfinishedUsd.min + (figures.unfinishedUsd?.min ?? 0), max: stored.unfinishedUsd.max + (figures.unfinishedUsd?.max ?? 0) };
489
+ }
423
490
  return {
424
491
  from, to: today, weeks, firstRecordedDay: oldest, days,
425
492
  totals: { tokens, subagentTokens, subagentShare: tokens ? subagentTokens / tokens : null, usd, unpricedTokens, unpricedModels,
426
- heldLaunches: sum('heldLaunches'), claudeTokens: sum('claudeTokens'), codexTokens: sum('codexTokens') },
493
+ heldLaunches: sum('heldLaunches'), claudeTokens: sum('claudeTokens'), codexTokens: sum('codexTokens'),
494
+ subagents: stored.subagents, unfinishedSubagents: stored.unfinishedSubagents, unfinishedTokens: stored.unfinishedTokens,
495
+ unfinishedUsd: stored.unfinishedUnpricedTokens > 0 ? null : stored.unfinishedUsd },
427
496
  busiest: busiest ? { date: busiest.date, tokens: busiest.tokens } : null,
428
497
  historyShort: data.claudeSeen && oldest !== null && history < span,
429
498
  sources: data.sources, subagentsIncluded: true, basis: 'estimated_api_list_price',
@@ -0,0 +1,34 @@
1
+ import type { CalendarReport } from './calendar';
2
+ import type { DollarRange } from './pricing';
3
+ export declare const CARD_WIDTH = 1200;
4
+ export declare const CARD_HEIGHT = 675;
5
+ export declare const CARD_SITE = "agentguard.run/burn";
6
+ export interface CardTile {
7
+ value: string;
8
+ label: string;
9
+ tone: 'teal' | 'ink' | 'amber';
10
+ }
11
+ export interface CardBar {
12
+ date: string;
13
+ tokens: number;
14
+ held: boolean;
15
+ busiest: boolean;
16
+ }
17
+ export interface CardModel {
18
+ heading: string;
19
+ range: string;
20
+ hero: string;
21
+ heroLabel: string;
22
+ /** Claude and Codex tokens side by side; null when one host carries every token. */
23
+ split: string | null;
24
+ tiles: CardTile[];
25
+ bars: CardBar[];
26
+ footnote: string;
27
+ site: string;
28
+ }
29
+ /** Three significant digits and a unit: 28.8B, 4.39B, 738M, 12.3K, 999. */
30
+ export declare function compact(value: number): string;
31
+ /** A dollar range for the card: one figure when both ends round alike, null when nothing is priced. */
32
+ export declare function compactDollars(range: DollarRange | null): string | null;
33
+ export declare function cardModel(report: CalendarReport): CardModel;
34
+ export declare function renderCard(model: CardModel): Promise<Buffer>;
@@ -0,0 +1,225 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CARD_SITE = exports.CARD_HEIGHT = exports.CARD_WIDTH = void 0;
4
+ exports.compact = compact;
5
+ exports.compactDollars = compactDollars;
6
+ exports.cardModel = cardModel;
7
+ exports.renderCard = renderCard;
8
+ /**
9
+ * `agentguard-burn card`: the calendar's totals as one image made to be shared, 1200x675 (the
10
+ * X/Twitter large-card ratio). Everything on it comes from `calendarReport`, the same figures the
11
+ * calendar prints; dollars carry the calendar's basis (API list price, not a bill); nothing
12
+ * about a project, prompt or file is drawn, and the image is written locally, never uploaded.
13
+ */
14
+ const promises_1 = require("node:fs/promises");
15
+ const node_path_1 = require("node:path");
16
+ const canvas_1 = require("@napi-rs/canvas");
17
+ exports.CARD_WIDTH = 1200;
18
+ exports.CARD_HEIGHT = 675;
19
+ exports.CARD_SITE = 'agentguard.run/burn';
20
+ const UNITS = [[1e12, 'T'], [1e9, 'B'], [1e6, 'M'], [1e3, 'K']];
21
+ /** Three significant digits and a unit: 28.8B, 4.39B, 738M, 12.3K, 999. */
22
+ function compact(value) {
23
+ for (const [size, unit] of UNITS) {
24
+ if (Math.abs(value) >= size)
25
+ return `${Number((value / size).toPrecision(3))}${unit}`;
26
+ }
27
+ return String(Math.round(value));
28
+ }
29
+ /** A dollar range for the card: one figure when both ends round alike, null when nothing is priced. */
30
+ function compactDollars(range) {
31
+ if (!range || !(Math.max(range.min, range.max) > 0))
32
+ return null;
33
+ const low = dollarFigure(range.min), high = dollarFigure(range.max);
34
+ return low === high ? low : `${low} to ${high}`;
35
+ }
36
+ function dollarFigure(value) {
37
+ return value >= 1000 ? `$${compact(value)}` : `$${Math.round(value)}`;
38
+ }
39
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
40
+ const monthDay = (day) => `${MONTHS[Number(day.slice(5, 7)) - 1]} ${Number(day.slice(8, 10))}`;
41
+ function spanText(from, to) {
42
+ const fromYear = from.slice(0, 4), toYear = to.slice(0, 4);
43
+ return fromYear === toYear
44
+ ? `${monthDay(from)} to ${monthDay(to)}, ${toYear}`
45
+ : `${monthDay(from)}, ${fromYear} to ${monthDay(to)}, ${toYear}`;
46
+ }
47
+ /** The span starts on a Sunday; the days after today stay as empty slots so the week reads as a week. */
48
+ function wholeWeeks(bars) {
49
+ const padded = [...bars];
50
+ while (padded.length % 7 !== 0)
51
+ padded.push({ date: '', tokens: 0, held: false, busiest: false });
52
+ return padded;
53
+ }
54
+ function cardModel(report) {
55
+ const { totals } = report;
56
+ const both = totals.claudeTokens > 0 && totals.codexTokens > 0;
57
+ const host = both ? 'Claude Code and Codex' : totals.codexTokens > 0 ? 'Codex' : 'Claude Code';
58
+ const tiles = [];
59
+ const dollars = compactDollars(totals.usd);
60
+ if (dollars)
61
+ tiles.push({ value: dollars, label: 'at API prices, not a bill', tone: 'teal' });
62
+ if (totals.subagentShare !== null) {
63
+ tiles.push({ value: `${Math.round(totals.subagentShare * 100)}%`, label: 'by sub-agents', tone: 'ink' });
64
+ }
65
+ if (report.busiest) {
66
+ tiles.push({ value: compact(report.busiest.tokens), label: `busiest day, ${monthDay(report.busiest.date)}`, tone: 'ink' });
67
+ }
68
+ tiles.push(totals.heldLaunches > 0
69
+ ? { value: totals.heldLaunches.toLocaleString('en-US'), label: 'sub-agent launches AgentGuard held', tone: 'amber' }
70
+ : { value: report.sources.transcripts.toLocaleString('en-US'), label: 'transcripts read on this machine', tone: 'ink' });
71
+ return {
72
+ heading: report.weeks === 1 ? 'My week of AI coding' : `My last ${report.weeks} weeks of AI coding`,
73
+ range: spanText(report.from, report.to),
74
+ hero: compact(totals.tokens),
75
+ heroLabel: `tokens through ${host}`,
76
+ split: both ? `Claude ${compact(totals.claudeTokens)} · Codex ${compact(totals.codexTokens)}` : null,
77
+ tiles,
78
+ bars: wholeWeeks(report.days.map(day => ({
79
+ date: day.date, tokens: day.tokens, held: day.heldLaunches > 0,
80
+ busiest: report.busiest?.date === day.date,
81
+ }))),
82
+ footnote: 'Counted from this machine’s transcripts. Dollars are API list prices, not a bill. Nothing was uploaded.',
83
+ site: exports.CARD_SITE,
84
+ };
85
+ }
86
+ /* ---------------------------------------------------------------- drawing */
87
+ const FONT_DIR = (0, node_path_1.join)(__dirname, '../../../fonts');
88
+ const TEXT = 'AgentGuardCardText', MONO = 'AgentGuardCardMono';
89
+ const FONT_FILES = [
90
+ ['Inter-Regular.ttf', TEXT], ['Inter-SemiBold.ttf', TEXT],
91
+ ['JetBrainsMono-Regular.ttf', MONO], ['JetBrainsMono-Bold.ttf', MONO],
92
+ ];
93
+ const INK = {
94
+ paper: '#0B1117', ink: '#FFFFFF', secondary: '#B4BECF', faint: '#6B7686', teal: '#2ABCB4',
95
+ tealSoft: 'rgba(42,188,180,0.38)', amber: '#F59E0B', panel: 'rgba(255,255,255,0.04)', line: 'rgba(255,255,255,0.10)',
96
+ };
97
+ const TONE = { teal: INK.teal, ink: INK.ink, amber: INK.amber };
98
+ let fontsReady = false;
99
+ async function registerFonts() {
100
+ if (fontsReady)
101
+ return;
102
+ for (const [file, alias] of FONT_FILES) {
103
+ const path = (0, node_path_1.join)(FONT_DIR, file);
104
+ await (0, promises_1.access)(path, promises_1.constants.R_OK);
105
+ canvas_1.GlobalFonts.registerFromPath(path, alias);
106
+ }
107
+ if (!canvas_1.GlobalFonts.has(TEXT) || !canvas_1.GlobalFonts.has(MONO))
108
+ throw new Error('Card fonts did not register from the package fonts directory.');
109
+ fontsReady = true;
110
+ }
111
+ function wrapLines(ctx, text, width) {
112
+ const lines = [];
113
+ let line = '';
114
+ for (const word of text.split(' ')) {
115
+ const next = line ? `${line} ${word}` : word;
116
+ if (line && ctx.measureText(next).width > width) {
117
+ lines.push(line);
118
+ line = word;
119
+ }
120
+ else
121
+ line = next;
122
+ }
123
+ if (line)
124
+ lines.push(line);
125
+ return lines;
126
+ }
127
+ function roundedRect(ctx, x, y, w, h, r) {
128
+ ctx.beginPath();
129
+ ctx.moveTo(x + r, y);
130
+ ctx.arcTo(x + w, y, x + w, y + h, r);
131
+ ctx.arcTo(x + w, y + h, x, y + h, r);
132
+ ctx.arcTo(x, y + h, x, y, r);
133
+ ctx.arcTo(x, y, x + w, y, r);
134
+ ctx.closePath();
135
+ }
136
+ async function renderCard(model) {
137
+ await registerFonts();
138
+ const canvas = (0, canvas_1.createCanvas)(exports.CARD_WIDTH, exports.CARD_HEIGHT);
139
+ const ctx = canvas.getContext('2d');
140
+ const pad = 64;
141
+ ctx.fillStyle = INK.paper;
142
+ ctx.fillRect(0, 0, exports.CARD_WIDTH, exports.CARD_HEIGHT);
143
+ ctx.textBaseline = 'alphabetic';
144
+ // Header: wordmark left, date span right.
145
+ ctx.font = `600 26px ${TEXT}`;
146
+ ctx.fillStyle = INK.ink;
147
+ // No registration symbol: the card is a social image, and the registration's services do not list Burn.
148
+ ctx.fillText('AgentGuard', pad, 88);
149
+ const markWidth = ctx.measureText('AgentGuard ').width;
150
+ ctx.fillStyle = INK.teal;
151
+ ctx.fillText('Burn', pad + markWidth, 88);
152
+ ctx.font = `22px ${TEXT}`;
153
+ ctx.fillStyle = INK.secondary;
154
+ ctx.textAlign = 'right';
155
+ ctx.fillText(model.range, exports.CARD_WIDTH - pad, 88);
156
+ ctx.textAlign = 'left';
157
+ // Hero: the token total.
158
+ ctx.font = `30px ${TEXT}`;
159
+ ctx.fillStyle = INK.secondary;
160
+ ctx.fillText(model.heading, pad, 158);
161
+ ctx.font = `600 150px ${TEXT}`;
162
+ ctx.fillStyle = INK.ink;
163
+ ctx.fillText(model.hero, pad - 6, 292);
164
+ ctx.font = `26px ${TEXT}`;
165
+ ctx.fillStyle = INK.secondary;
166
+ ctx.fillText(model.heroLabel, pad, 336);
167
+ if (model.split) {
168
+ ctx.font = `22px ${TEXT}`;
169
+ ctx.fillStyle = INK.faint;
170
+ ctx.fillText(model.split, pad, 372);
171
+ }
172
+ // Tiles: a 2x2 grid on the right.
173
+ const gridX = 668, gridY = 126, tileW = 226, tileH = 118, gap = 16;
174
+ model.tiles.slice(0, 4).forEach((tile, index) => {
175
+ const x = gridX + (index % 2) * (tileW + gap), y = gridY + Math.floor(index / 2) * (tileH + gap);
176
+ roundedRect(ctx, x, y, tileW, tileH, 14);
177
+ ctx.fillStyle = INK.panel;
178
+ ctx.fill();
179
+ ctx.strokeStyle = INK.line;
180
+ ctx.lineWidth = 1;
181
+ ctx.stroke();
182
+ ctx.font = `600 40px ${TEXT}`;
183
+ ctx.fillStyle = TONE[tile.tone];
184
+ ctx.fillText(tile.value, x + 20, y + 56);
185
+ ctx.font = `17px ${TEXT}`;
186
+ ctx.fillStyle = INK.secondary;
187
+ wrapLines(ctx, tile.label, tileW - 40).slice(0, 2).forEach((line, row) => ctx.fillText(line, x + 20, y + 84 + row * 21));
188
+ });
189
+ // Daily bars: one per day of the span, the busiest in full teal, a dot where AgentGuard held a launch.
190
+ const barsTop = 420, barsBottom = 566, barsLeft = pad, barsRight = exports.CARD_WIDTH - pad;
191
+ const count = Math.max(model.bars.length, 1);
192
+ const slot = (barsRight - barsLeft) / count;
193
+ const barWidth = Math.max(2, Math.min(28, slot * 0.72));
194
+ const peak = Math.max(...model.bars.map(bar => bar.tokens), 1);
195
+ ctx.strokeStyle = INK.line;
196
+ ctx.beginPath();
197
+ ctx.moveTo(barsLeft, barsBottom + 0.5);
198
+ ctx.lineTo(barsRight, barsBottom + 0.5);
199
+ ctx.stroke();
200
+ model.bars.forEach((bar, index) => {
201
+ const x = barsLeft + index * slot + (slot - barWidth) / 2;
202
+ const height = bar.tokens > 0 ? Math.max(3, (bar.tokens / peak) * (barsBottom - barsTop - 18)) : 0;
203
+ if (height > 0) {
204
+ roundedRect(ctx, x, barsBottom - height, barWidth, height, Math.min(4, barWidth / 2));
205
+ ctx.fillStyle = bar.busiest ? INK.teal : INK.tealSoft;
206
+ ctx.fill();
207
+ }
208
+ if (bar.held) {
209
+ ctx.beginPath();
210
+ ctx.arc(x + barWidth / 2, barsBottom - height - 9, 3.5, 0, Math.PI * 2);
211
+ ctx.fillStyle = INK.amber;
212
+ ctx.fill();
213
+ }
214
+ });
215
+ // Footer: the basis, then the site.
216
+ ctx.font = `16px ${TEXT}`;
217
+ ctx.fillStyle = INK.faint;
218
+ ctx.fillText(model.footnote, pad, 616);
219
+ ctx.font = `600 20px ${TEXT}`;
220
+ ctx.fillStyle = INK.teal;
221
+ ctx.textAlign = 'right';
222
+ ctx.fillText(model.site, exports.CARD_WIDTH - pad, 616);
223
+ ctx.textAlign = 'left';
224
+ return canvas.encode('png');
225
+ }
@@ -51,6 +51,14 @@ export interface WhyText {
51
51
  shares: string;
52
52
  increments: (shared: number, rebaselines: number, priorOutput: string) => string;
53
53
  observed: (calls: InsightObservations) => string;
54
+ /**
55
+ * Sub-agents that ended without finishing (recorded as failed, killed or
56
+ * stopped, never as completed or resumed), out of every sub-agent with a
57
+ * transcript; their tokens, those tokens' share of the session's, and their
58
+ * API list equivalent, null when a model is unpriced. Printed only from 1.
59
+ * Burn knows whether a sub-agent finished, never whether its work was right.
60
+ */
61
+ unfinished: (count: number, total: number, tokens: string, share: string, usd: string | null) => string;
54
62
  methodTitle: string;
55
63
  explicit: string;
56
64
  unpricedModels: (models: string) => string;
@@ -96,12 +104,17 @@ export declare const WHY_TEXT: Readonly<Record<WhyLang, WhyText>>;
96
104
  * The cost of one more sub-agent, for the STOP prompt and box: what this
97
105
  * session's finished sub-agents averaged, a measurement of what already ran and
98
106
  * never a forecast. `count` is at least three; `usd` is null when any of them ran
99
- * on an unpriced model. Every other line of the STOP text is English on every
100
- * host, so the hook asks for English; the Spanish and Portuguese lines are here
101
- * for when the STOP text is translated.
107
+ * on an unpriced model. `unfinished`, when the transcripts record sub-agents
108
+ * that ended without finishing, adds how many and the tokens they used in all;
109
+ * Burn knows they did not finish, never whether any work was right. Every other
110
+ * line of the STOP text is English on every host, so the hook asks for English;
111
+ * the Spanish and Portuguese lines are here for when the STOP text is translated.
102
112
  */
103
113
  export interface DecisionText {
104
- finished: (count: number, tokens: string, usd: string | null) => string;
114
+ finished: (count: number, tokens: string, usd: string | null, unfinished?: {
115
+ count: number;
116
+ tokens: string;
117
+ } | null) => string;
105
118
  }
106
119
  export declare const DECISION_TEXT: Readonly<Record<WhyLang, DecisionText>>;
107
120
  /**
@@ -165,6 +178,12 @@ export interface CalendarText {
165
178
  dollars: (usd: string | null) => string;
166
179
  busiest: (date: string, count: string) => string;
167
180
  subagents: (share: string) => string;
181
+ /**
182
+ * Sub-agents that ended without finishing, out of every sub-agent counted:
183
+ * their tokens, those tokens' share of all tokens, and dollars at API prices,
184
+ * null when a model is unpriced. Printed only from 1.
185
+ */
186
+ unfinished: (count: number, total: number, tokens: string, share: string, usd: string | null) => string;
168
187
  /** Sub-agent launches AgentGuard held (refused, or held for the person's yes); printed only above zero. */
169
188
  held: (launches: number) => string;
170
189
  less: string;
@@ -60,6 +60,7 @@ const en = {
60
60
  shares: 'Token shares partition recorded usage; byte sizes only split measured token increments and are never converted into tokens.',
61
61
  increments: (shared, rebaselines, priorOutput) => `Shared event increments: ${shared}. Prefix rebaselines: ${rebaselines}. Prior output retained in unattributed input: ${priorOutput} tokens.`,
62
62
  observed: calls => `Observed calls: ${calls.readCalls} reads of ${calls.uniqueReadFiles} paths, ${calls.repeatedReadCalls} repeated reads, ${calls.spawnCalls} spawns, ${calls.toolResultRecords} tool results.`,
63
+ unfinished: (count, total, tokens, share, usd) => `Sub-agents that ended without finishing: ${count} of ${total}, ${tokens} tokens (${share} of session tokens${usd === null ? '' : `, ${usd} API list equivalent`}).`,
63
64
  methodTitle: 'Method',
64
65
  explicit: 'Explicit host token attribution takes precedence over the delta method for responses that provide it.',
65
66
  unpricedModels: models => `Tokens only for unpriced models: ${models}. No verified exact model rate is available for at least one token category.`,
@@ -110,6 +111,7 @@ const es = {
110
111
  shares: 'Los porcentajes de tokens reparten el uso registrado; los tamaños en bytes solo dividen incrementos medidos de tokens y nunca se convierten en tokens.',
111
112
  increments: (shared, rebaselines, priorOutput) => `Incrementos compartidos entre eventos: ${shared}. Nuevas líneas base del prefijo: ${rebaselines}. Tokens de salida previa retenidos en la entrada sin atribuir: ${priorOutput}.`,
112
113
  observed: calls => `Llamadas observadas: ${plural(calls.readCalls, 'lectura', 'lecturas')} de ${plural(calls.uniqueReadFiles, 'ruta', 'rutas')}, ${plural(calls.repeatedReadCalls, 'lectura repetida', 'lecturas repetidas')}, ${plural(calls.spawnCalls, 'subagente lanzado', 'subagentes lanzados')}, ${plural(calls.toolResultRecords, 'resultado de herramienta', 'resultados de herramientas')}.`,
114
+ unfinished: (count, total, tokens, share, usd) => `Subagentes que quedaron sin terminar: ${count} de ${total}, ${tokens} tokens (el ${share} de los tokens de la sesión${usd === null ? '' : `, ${usd} equivalente a precio de lista de la API`}).`,
113
115
  methodTitle: 'Método',
114
116
  explicit: 'La atribución explícita de tokens que informa el host tiene prioridad sobre el método de deltas en las respuestas que la incluyen.',
115
117
  unpricedModels: models => `Modelos sin precio (solo tokens): ${models}. No hay una tarifa exacta verificada para al menos una categoría de tokens.`,
@@ -160,6 +162,7 @@ const pt = {
160
162
  shares: 'As porcentagens de tokens repartem o uso registrado; os tamanhos em bytes apenas dividem incrementos medidos de tokens e nunca são convertidos em tokens.',
161
163
  increments: (shared, rebaselines, priorOutput) => `Incrementos compartilhados entre eventos: ${shared}. Novas linhas de base do prefixo: ${rebaselines}. Tokens de saída anterior retidos na entrada não atribuída: ${priorOutput}.`,
162
164
  observed: calls => `Chamadas observadas: ${plural(calls.readCalls, 'leitura', 'leituras')} de ${plural(calls.uniqueReadFiles, 'caminho', 'caminhos')}, ${plural(calls.repeatedReadCalls, 'leitura repetida', 'leituras repetidas')}, ${plural(calls.spawnCalls, 'subagente iniciado', 'subagentes iniciados')}, ${plural(calls.toolResultRecords, 'resultado de ferramenta', 'resultados de ferramentas')}.`,
165
+ unfinished: (count, total, tokens, share, usd) => `Subagentes que pararam sem terminar: ${count} de ${total}, ${tokens} tokens (${share} dos tokens da sessão${usd === null ? '' : `, ${usd} equivalente ao preço de tabela da API`}).`,
163
166
  methodTitle: 'Método',
164
167
  explicit: 'A atribuição explícita de tokens informada pelo host tem prioridade sobre o método de deltas nas respostas que a incluem.',
165
168
  unpricedModels: models => `Modelos sem preço (apenas tokens): ${models}. Não há tarifa exata verificada para pelo menos uma categoria de tokens.`,
@@ -184,9 +187,9 @@ const pt = {
184
187
  };
185
188
  exports.WHY_TEXT = { en, es, pt };
186
189
  exports.DECISION_TEXT = {
187
- en: { finished: (count, tokens, usd) => `The ${count} sub-agents that finished in this session averaged ${tokens} tokens each${usd ? ` (${usd} at API prices, not a bill)` : ''}. This one could differ.` },
188
- es: { finished: (count, tokens, usd) => `Los ${count} subagentes que terminaron en esta sesión promediaron ${tokens} tokens cada uno${usd ? ` (${usd} a precios de la API, no una factura)` : ''}. Este podría ser distinto.` },
189
- pt: { finished: (count, tokens, usd) => `Os ${count} subagentes que terminaram nesta sessão usaram em média ${tokens} tokens cada${usd ? ` (${usd} a preços da API, não uma fatura)` : ''}. Este pode ser diferente.` },
190
+ en: { finished: (count, tokens, usd, unfinished) => `The ${count} sub-agents that finished in this session averaged ${tokens} tokens each${usd ? ` (${usd} at API prices, not a bill)` : ''}.${!unfinished ? '' : unfinished.count === 1 ? ` 1 more ended without finishing and used ${unfinished.tokens} tokens.` : ` ${unfinished.count} more ended without finishing and used ${unfinished.tokens} tokens in total.`} This one could differ.` },
191
+ es: { finished: (count, tokens, usd, unfinished) => `Los ${count} subagentes que terminaron en esta sesión promediaron ${tokens} tokens cada uno${usd ? ` (${usd} a precios de la API, no una factura)` : ''}.${!unfinished ? '' : unfinished.count === 1 ? ` Otro quedó sin terminar y usó ${unfinished.tokens} tokens.` : ` Otros ${unfinished.count} quedaron sin terminar y usaron ${unfinished.tokens} tokens en total.`} Este podría ser distinto.` },
192
+ pt: { finished: (count, tokens, usd, unfinished) => `Os ${count} subagentes que terminaram nesta sessão usaram em média ${tokens} tokens cada${usd ? ` (${usd} a preços da API, não uma fatura)` : ''}.${!unfinished ? '' : unfinished.count === 1 ? ` Outro parou sem terminar e usou ${unfinished.tokens} tokens.` : ` Outros ${unfinished.count} pararam sem terminar e usaram ${unfinished.tokens} tokens no total.`} Este pode ser diferente.` },
190
193
  };
191
194
  const TWO_IDS = 'agentguard-burn compare SESSION_A SESSION_B';
192
195
  const compareEn = {
@@ -274,6 +277,7 @@ const calendarEn = {
274
277
  dollars: usd => usd === null ? 'no dollar total: no known API price for these models' : `${usd} at API prices, not a bill`,
275
278
  busiest: (date, count) => `busiest day: ${date} (${count} ${count === '1' ? 'token' : 'tokens'})`,
276
279
  subagents: share => `sub-agents used ${share} of tokens`,
280
+ unfinished: (count, total, tokens, share, usd) => `${count} of ${total} ${total === 1 ? 'sub-agent' : 'sub-agents'} ended without finishing (${tokens} ${tokens === '1' ? 'token' : 'tokens'}, ${share} of tokens${usd === null ? '' : `, ${usd} at API prices`})`,
277
281
  held: launches => `AgentGuard held ${launches} ${launches === 1 ? 'launch' : 'launches'}`,
278
282
  less: 'Less',
279
283
  more: 'More',
@@ -305,6 +309,7 @@ const calendarEs = {
305
309
  dollars: usd => usd === null ? 'sin total en dólares: no se conoce el precio de la API de estos modelos' : `${usd} a precios de la API, no es una factura`,
306
310
  busiest: (date, count) => `día con más tokens: ${date} (${count})`,
307
311
  subagents: share => `los subagentes usaron el ${share} de los tokens`,
312
+ unfinished: (count, total, tokens, share, usd) => `${count} de ${total} ${total === 1 ? 'subagente' : 'subagentes'} ${count === 1 ? 'quedó' : 'quedaron'} sin terminar (${tokens} ${tokens === '1' ? 'token' : 'tokens'}, el ${share} de los tokens${usd === null ? '' : `, ${usd} a precios de la API`})`,
308
313
  held: launches => launches === 1 ? 'AgentGuard retuvo 1 lanzamiento' : `AgentGuard retuvo ${launches} lanzamientos`,
309
314
  less: 'Menos',
310
315
  more: 'Más',
@@ -335,6 +340,7 @@ const calendarPt = {
335
340
  dollars: usd => usd === null ? 'sem total em dólares: o preço da API destes modelos não é conhecido' : `${usd} a preços da API, não é uma fatura`,
336
341
  busiest: (date, count) => `dia com mais tokens: ${date} (${count})`,
337
342
  subagents: share => `os subagentes usaram ${share} dos tokens`,
343
+ unfinished: (count, total, tokens, share, usd) => `${count} de ${total} ${total === 1 ? 'subagente' : 'subagentes'} ${count === 1 ? 'parou' : 'pararam'} sem terminar (${tokens} ${tokens === '1' ? 'token' : 'tokens'}, ${share} dos tokens${usd === null ? '' : `, ${usd} a preços da API`})`,
338
344
  held: launches => launches === 1 ? 'o AgentGuard reteve 1 lançamento' : `o AgentGuard reteve ${launches} lançamentos`,
339
345
  less: 'Menos',
340
346
  more: 'Mais',
@@ -99,6 +99,25 @@ export declare function whyTipInput(figures: Pick<SessionFigures, 'turns' | 'att
99
99
  * caller decides whether to show it.
100
100
  */
101
101
  export declare function whyTipLine(transcript: InsightTranscript, rates?: PricingTable, lang?: WhyLang, context?: TipContext): string | null;
102
+ /** The sub-agents of one session that ended without finishing, and what they used. */
103
+ export interface UnfinishedSubagents {
104
+ count: number;
105
+ /** Every sub-agent with a transcript in the session's `subagents` folder. */
106
+ total: number;
107
+ /** Their responses' tokens, counted once as everywhere in `why`. */
108
+ tokens: number;
109
+ /** Those tokens' API list equivalent; null when any of them is on an unpriced model. */
110
+ usd: DollarRange | null;
111
+ }
112
+ /**
113
+ * The session's sub-agents that ended without finishing: recorded as failed,
114
+ * killed or stopped, and never as completed or resumed. One that may still be
115
+ * running, or whose end no transcript records, is never counted. Their tokens
116
+ * are their own transcripts' responses after the same de-duplication the table
117
+ * uses. Null when there are none, and for a transcript read without its
118
+ * sub-agents.
119
+ */
120
+ export declare function unfinishedSubagents(transcript: Pick<InsightTranscript, 'subagents'>, figures: Pick<SessionFigures, 'turns' | 'prices'>): UnfinishedSubagents | null;
102
121
  /** Messages on each side of an event the measured change compares, at most and at least. */
103
122
  export declare const PROOF_WINDOW = 20;
104
123
  export declare const PROOF_MINIMUM = 5;
@@ -9,12 +9,14 @@ exports.modelLabel = modelLabel;
9
9
  exports.whyTip = whyTip;
10
10
  exports.whyTipInput = whyTipInput;
11
11
  exports.whyTipLine = whyTipLine;
12
+ exports.unfinishedSubagents = unfinishedSubagents;
12
13
  exports.proofLine = proofLine;
13
14
  exports.renderWhy = renderWhy;
14
15
  exports.rewriteReport = rewriteReport;
15
16
  exports.rewriteReportJson = rewriteReportJson;
16
17
  exports.renderRewrites = renderRewrites;
17
18
  exports.renderPricing = renderPricing;
19
+ const subagent_signals_1 = require("../history/subagent-signals");
18
20
  const attribution_1 = require("./attribution");
19
21
  const pricing_1 = require("./pricing");
20
22
  const live_1 = require("./live");
@@ -218,6 +220,32 @@ const figuresTip = (figures, rates, lang, context = 'why') => whyTip(whyTipInput
218
220
  function whyTipLine(transcript, rates = {}, lang = 'en', context = 'why') {
219
221
  return transcript.state.forkHistoryBoundaryUnknown ? null : figuresTip(sessionFigures(transcript, rates), rates, lang, context);
220
222
  }
223
+ /**
224
+ * The session's sub-agents that ended without finishing: recorded as failed,
225
+ * killed or stopped, and never as completed or resumed. One that may still be
226
+ * running, or whose end no transcript records, is never counted. Their tokens
227
+ * are their own transcripts' responses after the same de-duplication the table
228
+ * uses. Null when there are none, and for a transcript read without its
229
+ * sub-agents.
230
+ */
231
+ function unfinishedSubagents(transcript, figures) {
232
+ const outcome = transcript.subagents;
233
+ if (!outcome?.ended.length)
234
+ return null;
235
+ const sets = { completed: new Set(outcome.completed), ended: new Set(outcome.ended), resumed: new Set(outcome.resumed) };
236
+ const unfinished = new Set(outcome.ids.filter(id => (0, subagent_signals_1.endedWithoutFinishing)(id, sets)).map(id => `agent-${id}`));
237
+ if (!unfinished.size)
238
+ return null;
239
+ let tokens = 0;
240
+ const prices = [];
241
+ figures.turns.forEach((turn, i) => {
242
+ if (!turn.subagent || !unfinished.has(turn.sessionId))
243
+ return;
244
+ tokens += totalTokens(turn);
245
+ prices.push(figures.prices[i].usd);
246
+ });
247
+ return { count: unfinished.size, total: outcome.ids.length, tokens, usd: sumPrices(prices) };
248
+ }
221
249
  /** Messages on each side of an event the measured change compares, at most and at least. */
222
250
  exports.PROOF_WINDOW = 20;
223
251
  exports.PROOF_MINIMUM = 5;
@@ -281,8 +309,9 @@ function renderWhy(transcript, rates = {}, options = {}) {
281
309
  });
282
310
  const unknownModels = [...new Set(prices.filter(price => price.usd === null).map(price => price.model ?? text.missingModel))];
283
311
  const tip = options.tips ? figuresTip(figures, rates, lang) : null;
284
- // A measurement, not a tip: it prints whether or not tips are on.
312
+ // Measurements, not tips: they print whether or not tips are on.
285
313
  const proof = proofLine(turns, lang);
314
+ const unfinished = unfinishedSubagents(transcript, figures);
286
315
  return [
287
316
  `AgentGuard why: ${transcript.sessionId}`,
288
317
  text.summary(turns.length, (0, exports.count)(attribution.totalTokens), totalUsd === null ? null : money(totalUsd)),
@@ -291,6 +320,7 @@ function renderWhy(transcript, rates = {}, options = {}) {
291
320
  text.shares,
292
321
  text.increments(attribution.sharedTurns, attribution.prefixRebaselines, (0, exports.count)(attribution.previousOutputTokensReserved)),
293
322
  text.observed(transcript.observations),
323
+ ...(unfinished ? [text.unfinished(unfinished.count, unfinished.total, (0, exports.count)(unfinished.tokens), (0, exports.share)(unfinished.tokens, attribution.totalTokens), unfinished.usd === null ? null : money(unfinished.usd))] : []),
294
324
  '', text.methodTitle,
295
325
  ...types_1.INSIGHT_BUCKETS.map(bucket => `${text.labels[bucket]}: ${text.method[bucket]}`),
296
326
  ...(turns.some(turn => turn.explicitAttribution.length > 0) ? [text.explicit] : []),