@agentguard-run/burn 0.3.18 → 0.3.20

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +105 -5
  3. package/dist/src/canvas.d.ts +7 -1
  4. package/dist/src/canvas.js +10 -1
  5. package/dist/src/cli.js +101 -7
  6. package/dist/src/frames.d.ts +10 -0
  7. package/dist/src/frames.js +5 -0
  8. package/dist/src/history/claude-transcript.d.ts +26 -1
  9. package/dist/src/history/claude-transcript.js +58 -2
  10. package/dist/src/hook/pre-tool-use.d.ts +6 -2
  11. package/dist/src/hook/pre-tool-use.js +35 -8
  12. package/dist/src/insights/calendar-render.d.ts +48 -0
  13. package/dist/src/insights/calendar-render.js +196 -0
  14. package/dist/src/insights/calendar.d.ts +138 -0
  15. package/dist/src/insights/calendar.js +431 -0
  16. package/dist/src/insights/compare.d.ts +104 -0
  17. package/dist/src/insights/compare.js +210 -0
  18. package/dist/src/insights/i18n.d.ts +134 -8
  19. package/dist/src/insights/i18n.js +200 -13
  20. package/dist/src/insights/render.d.ts +93 -13
  21. package/dist/src/insights/render.js +212 -28
  22. package/dist/src/insights/sessions.d.ts +25 -0
  23. package/dist/src/insights/sessions.js +72 -5
  24. package/dist/src/insights/transcript.d.ts +13 -2
  25. package/dist/src/insights/transcript.js +61 -6
  26. package/dist/src/insights/types.d.ts +17 -0
  27. package/dist/src/insights/types.js +3 -1
  28. package/dist/src/recording.js +5 -1
  29. package/dist/src/replay/render.d.ts +2 -0
  30. package/dist/src/replay/render.js +4 -0
  31. package/dist/src/stop-text.d.ts +16 -5
  32. package/dist/src/stop-text.js +28 -6
  33. package/dist/src/subagent-cost.d.ts +38 -0
  34. package/dist/src/subagent-cost.js +65 -0
  35. package/package.json +1 -1
@@ -0,0 +1,431 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.weeksThatFit = exports.cachePath = exports.rollupPath = exports.calendarDirectory = exports.weekdayOf = exports.addDays = exports.dayNumber = exports.CALENDAR_GRID_PREFIX = exports.CALENDAR_MAX_WEEKS = void 0;
4
+ exports.localDay = localDay;
5
+ exports.collectCalendar = collectCalendar;
6
+ exports.calendarLevels = calendarLevels;
7
+ exports.calendarReport = calendarReport;
8
+ /**
9
+ * `calendar`: every local Claude Code and Codex session on one heatmap of
10
+ * measured tokens per local calendar day, sub-agents included. Each response is
11
+ * read with the parser and pricing `why` uses (sessionFigures): its tokens, its
12
+ * API list price and whether a sub-agent recorded it, binned by the local day
13
+ * the response was recorded. Measurement only: nothing here compares with anyone.
14
+ *
15
+ * Retention: Claude Code deletes transcripts after 30 days by default, so Burn
16
+ * keeps a content-free daily count per transcript file in the Burn home
17
+ * (calendar/daily.json: token, sub-agent token and dollar totals per file per
18
+ * day; no paths, no content). A file still on disk is recomputed from its
19
+ * transcript; a file that is gone comes from the daily count; no file-day is
20
+ * taken from both. A per-transcript cache (calendar/cache.json, keyed by path
21
+ * digest, size and modification time) keeps each response's counts, so a second
22
+ * run re-reads only the transcripts that changed.
23
+ */
24
+ const node_crypto_1 = require("node:crypto");
25
+ const node_fs_1 = require("node:fs");
26
+ const node_path_1 = require("node:path");
27
+ const history_1 = require("./history");
28
+ const pricing_1 = require("./pricing");
29
+ const render_1 = require("./render");
30
+ const sessions_1 = require("./sessions");
31
+ const transcript_1 = require("./transcript");
32
+ const i18n_1 = require("./i18n");
33
+ /** A span of at most 53 weeks: a year of Sundays plus the week in progress. */
34
+ exports.CALENDAR_MAX_WEEKS = 53;
35
+ /**
36
+ * Weekday labels plus one space, in the widest language, so the span a width
37
+ * allows, and so `calendar json`, is the same in every language.
38
+ */
39
+ exports.CALENDAR_GRID_PREFIX = Math.max(...Object.values(i18n_1.CALENDAR_TEXT).flatMap(text => text.weekdays.map(label => label.length))) + 1;
40
+ /** Transcripts larger than this are parsed in pieces (see InsightReadOptions), which bounds memory on a machine of 400 MB sessions. */
41
+ const CHUNK_BYTES = 16 * 1024 * 1024;
42
+ const CACHE_SCHEMA = 3, ROLLUP_SCHEMA = 1;
43
+ const sha256 = (text) => (0, node_crypto_1.createHash)('sha256').update(text).digest('hex');
44
+ const pad = (n) => String(n).padStart(2, '0');
45
+ /** The local calendar day of an instant, YYYY-MM-DD, in this process's time zone. */
46
+ function localDay(at) {
47
+ const date = new Date(at);
48
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
49
+ }
50
+ /** Days since the epoch for a YYYY-MM-DD date: date arithmetic without clock time or daylight saving. */
51
+ const dayNumber = (day) => Date.UTC(Number(day.slice(0, 4)), Number(day.slice(5, 7)) - 1, Number(day.slice(8, 10))) / 86_400_000;
52
+ exports.dayNumber = dayNumber;
53
+ const dayText = (n) => new Date(n * 86_400_000).toISOString().slice(0, 10);
54
+ const addDays = (day, days) => dayText((0, exports.dayNumber)(day) + days);
55
+ exports.addDays = addDays;
56
+ /** 0 is Sunday. */
57
+ const weekdayOf = (day) => new Date((0, exports.dayNumber)(day) * 86_400_000).getUTCDay();
58
+ exports.weekdayOf = weekdayOf;
59
+ function transcriptUnits(locations) {
60
+ const units = [];
61
+ for (const location of locations) {
62
+ const child = location.host === 'claude' && (0, node_path_1.basename)((0, node_path_1.dirname)(location.path)) === 'subagents';
63
+ if (location.host === 'claude' && !child && (0, sessions_1.isSessionSidecar)(location))
64
+ continue;
65
+ let info;
66
+ try {
67
+ info = (0, node_fs_1.statSync)(location.path);
68
+ }
69
+ catch {
70
+ continue;
71
+ }
72
+ if (!info.isFile())
73
+ continue;
74
+ units.push({ host: location.host, path: location.path, size: info.size, mtimeMs: info.mtimeMs,
75
+ key: child ? `${(0, node_path_1.basename)((0, node_path_1.dirname)((0, node_path_1.dirname)(location.path)))}/${location.sessionId}` : location.sessionId });
76
+ }
77
+ return units.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
78
+ }
79
+ /** Parser ids are SHA-256 digests; 64 bits of one tell a machine's responses apart. */
80
+ const turnKey = (id) => /^[0-9a-f]{64}$/.test(id) ? id.slice(0, 16) : sha256(id).slice(0, 16);
81
+ const rowTokens = (row) => row[5] + row[6] + row[7] + row[8];
82
+ /** One file's responses, read with the parser and pricing `why` uses. */
83
+ function readUnit(unit, rates) {
84
+ // A stored child is a spawned session by its path, as readInsightSession reads it.
85
+ const transcript = (0, transcript_1.readInsightTranscript)(unit.path, { host: unit.host }, { chunkBytes: CHUNK_BYTES });
86
+ if (transcript.state.forkHistoryBoundaryUnknown)
87
+ return { host: unit.host, key: unit.key, models: [], rows: [], forkUnknown: true };
88
+ const figures = (0, render_1.sessionFigures)(transcript, rates);
89
+ const models = [], modelIndex = new Map();
90
+ const rows = figures.turns.map((turn, i) => {
91
+ const usd = figures.prices[i].usd, model = turn.model ?? null;
92
+ if (!modelIndex.has(model)) {
93
+ modelIndex.set(model, models.length);
94
+ models.push(model);
95
+ }
96
+ const split = turn.cacheWrite5mTokens !== undefined && turn.cacheWrite1hTokens !== undefined;
97
+ return [turnKey(turn.id), turn.at !== undefined && Number.isFinite(turn.at) ? turn.at : null, usd?.min ?? null, usd?.max ?? null, modelIndex.get(model),
98
+ turn.inputTokens, turn.cacheWriteTokens, turn.cacheReadTokens, turn.outputTokens,
99
+ split ? turn.cacheWrite5mTokens : null, split ? turn.cacheWrite1hTokens : null, turn.cacheTtlSeconds ?? null, turn.subagent ? 1 : 0];
100
+ });
101
+ return { host: unit.host, key: unit.key, models, rows, forkUnknown: false };
102
+ }
103
+ /**
104
+ * A cached response as a turn again, for the rare response recorded in more
105
+ * than one file. Its session id is its file's key, so the merged turn names the
106
+ * file that owns it. Only what de-duplication and pricing read is restored.
107
+ */
108
+ function turnOf(copy) {
109
+ const [id, at, , , , input, write, read, output, write5m, write1h, ttl, subagent] = copy.row;
110
+ return {
111
+ id, sessionId: copy.key, host: copy.host, ...(at !== null ? { at } : {}), ...(subagent ? { subagent: true } : {}), ...(copy.model !== null ? { model: copy.model } : {}),
112
+ inputTokens: input, cacheWriteTokens: write, cacheReadTokens: read, outputTokens: output,
113
+ ...(write5m !== null && write1h !== null ? { cacheWrite5mTokens: write5m, cacheWrite1hTokens: write1h } : {}), ...(ttl !== null ? { cacheTtlSeconds: ttl } : {}),
114
+ contextTokens: input + write + read, signals: { afterCompaction: false, firstSpawnedTurn: false }, explicitAttribution: [], uncertainties: [],
115
+ };
116
+ }
117
+ const calendarDirectory = (home) => (0, node_path_1.join)(home, 'calendar');
118
+ exports.calendarDirectory = calendarDirectory;
119
+ const rollupPath = (home) => (0, node_path_1.join)((0, exports.calendarDirectory)(home), 'daily.json');
120
+ exports.rollupPath = rollupPath;
121
+ const cachePath = (home) => (0, node_path_1.join)((0, exports.calendarDirectory)(home), 'cache.json');
122
+ exports.cachePath = cachePath;
123
+ /** Owner-only file written beside its target and renamed over it, so a reader never sees half of it. */
124
+ function writeAtomic(file, text) {
125
+ (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(file), { recursive: true, mode: 0o700 });
126
+ const temporary = `${file}.${process.pid}.${(0, node_crypto_1.randomUUID)()}.tmp`;
127
+ try {
128
+ (0, node_fs_1.writeFileSync)(temporary, text, { mode: 0o600, flag: 'wx' });
129
+ (0, node_fs_1.renameSync)(temporary, file);
130
+ }
131
+ catch (error) {
132
+ try {
133
+ (0, node_fs_1.unlinkSync)(temporary);
134
+ }
135
+ catch { /* never created */ }
136
+ throw error;
137
+ }
138
+ }
139
+ const record = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
140
+ const count = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;
141
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
142
+ function figuresOf(value) {
143
+ const raw = record(value), usd = record(raw.usd);
144
+ const models = Array.isArray(raw.unpricedModels) ? raw.unpricedModels.filter((model) => model === null || typeof model === 'string') : [];
145
+ 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 };
147
+ }
148
+ /** The daily count on disk. An unreadable file is moved aside, never overwritten, so it can still be recovered. */
149
+ function readRollup(home) {
150
+ const file = (0, exports.rollupPath)(home);
151
+ const empty = () => ({ schema: ROLLUP_SCHEMA, files: {}, shared: {} });
152
+ let text;
153
+ try {
154
+ text = (0, node_fs_1.readFileSync)(file, 'utf8');
155
+ }
156
+ catch {
157
+ return empty();
158
+ }
159
+ let raw;
160
+ try {
161
+ raw = record(JSON.parse(text));
162
+ if (raw.schema !== ROLLUP_SCHEMA)
163
+ throw new Error('schema');
164
+ }
165
+ catch {
166
+ try {
167
+ (0, node_fs_1.renameSync)(file, `${file}.unreadable-${Date.now()}`);
168
+ }
169
+ catch { /* left in place */ }
170
+ return empty();
171
+ }
172
+ const rollup = empty();
173
+ for (const [key, value] of Object.entries(record(raw.files))) {
174
+ const entry = record(value);
175
+ if (entry.host !== 'claude' && entry.host !== 'codex')
176
+ continue;
177
+ const days = {};
178
+ for (const [day, figures] of Object.entries(record(entry.days)))
179
+ if (DAY.test(day))
180
+ days[day] = figuresOf(figures);
181
+ rollup.files[key] = { host: entry.host, days };
182
+ }
183
+ for (const [id, owner] of Object.entries(record(raw.shared)))
184
+ if (typeof owner === 'string')
185
+ rollup.shared[id] = owner;
186
+ return rollup;
187
+ }
188
+ function readCache(home, signature) {
189
+ try {
190
+ const raw = record(JSON.parse((0, node_fs_1.readFileSync)((0, exports.cachePath)(home), 'utf8')));
191
+ if (raw.schema === CACHE_SCHEMA && raw.signature === signature)
192
+ return { schema: CACHE_SCHEMA, signature, units: record(raw.units) };
193
+ }
194
+ catch { /* first run, or unreadable: rebuilt below */ }
195
+ return { schema: CACHE_SCHEMA, signature, units: {} };
196
+ }
197
+ /** Parser, pricing and cache format: a new Burn release or a pricing override change recomputes every transcript once. */
198
+ function cacheSignature(rates) {
199
+ const table = { ...pricing_1.MODEL_PRICING, ...rates };
200
+ const version = require('../../../package.json').version;
201
+ return `${CACHE_SCHEMA}:${version}:${sha256(JSON.stringify(Object.keys(table).sort().map(model => [model, table[model]])))}`;
202
+ }
203
+ function cachedUnit(value, file) {
204
+ const unit = record(value);
205
+ 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)
207
+ && (unit.host === 'claude' || unit.host === 'codex') && typeof unit.forkUnknown === 'boolean' ? unit : undefined;
208
+ }
209
+ /* ----------------------------------------------------------------- ledger */
210
+ /**
211
+ * Sub-agent launches AgentGuard held, per local day, from the decisions ledger:
212
+ * a spawn refused by an enforced STOP, or held by the ask prompt (`asked: true`).
213
+ * A decision id, or a session and tool call, counts once. Shadow and overridden
214
+ * decisions were not held, and a refused model call or override attempt is not
215
+ * a launch.
216
+ */
217
+ function ledgerDays(home) {
218
+ const held = new Map(), seen = new Set();
219
+ let row = 0;
220
+ try {
221
+ for (const raw of (0, history_1.jsonRows)((0, node_path_1.join)(home, 'decisions.ndjson'))) {
222
+ row++;
223
+ const action = typeof raw.action === 'string' ? raw.action : 'spawn';
224
+ if (action !== 'spawn' || raw.verdict !== 'STOP' || !(raw.enforced === true || raw.blocked === true || raw.asked === true))
225
+ continue;
226
+ const at = (0, history_1.timestamp)(raw.at ?? raw.timestamp);
227
+ if (at === null)
228
+ continue;
229
+ const id = typeof raw.decisionId === 'string' ? `decision:${raw.decisionId}`
230
+ : typeof raw.sessionId === 'string' && typeof raw.toolUseId === 'string' ? `call:${raw.sessionId}:${raw.toolUseId}` : `row:${row}`;
231
+ if (seen.has(id))
232
+ continue;
233
+ seen.add(id);
234
+ const day = localDay(at);
235
+ held.set(day, (held.get(day) ?? 0) + 1);
236
+ }
237
+ }
238
+ catch { /* No ledger yet, or unreadable: no marks. */ }
239
+ return held;
240
+ }
241
+ const emptyFigures = () => ({ tokens: 0, subagentTokens: 0, usd: { min: 0, max: 0 }, unpricedTokens: 0, unpricedModels: [] });
242
+ /**
243
+ * Reads every local transcript (from the cache when unchanged), merges the daily
244
+ * count of files that are gone, writes both back, and reads the ledger.
245
+ */
246
+ function collectCalendar(options) {
247
+ const { home } = options, rates = options.rates ?? {};
248
+ const units = transcriptUnits((0, sessions_1.discoverInsightTranscripts)(options.roots ?? (0, sessions_1.transcriptRoots)()));
249
+ const signature = cacheSignature(rates), cache = readCache(home, signature);
250
+ const nextCache = {}, loaded = [];
251
+ let cacheChanged = false, unreadable = 0;
252
+ for (const unit of units) {
253
+ const id = sha256(unit.path), file = [id.slice(0, 16), unit.size, unit.mtimeMs];
254
+ let entry = cachedUnit(cache.units[id], file);
255
+ if (!entry) {
256
+ try {
257
+ entry = { file, ...readUnit(unit, rates) };
258
+ }
259
+ catch {
260
+ unreadable++;
261
+ continue;
262
+ }
263
+ cacheChanged = true;
264
+ }
265
+ nextCache[id] = entry;
266
+ loaded.push(entry);
267
+ }
268
+ if (Object.keys(cache.units).some(id => !(id in nextCache)))
269
+ cacheChanged = true;
270
+ const rollup = readRollup(home);
271
+ const present = new Map();
272
+ for (const entry of loaded)
273
+ present.set(entry.key, entry.host);
274
+ const first = new Map(), groups = new Map();
275
+ for (const entry of loaded)
276
+ for (const row of entry.rows) {
277
+ const copy = { key: entry.key, host: entry.host, row, model: entry.models[row[4]] ?? null }, seen = first.get(row[0]);
278
+ if (!seen)
279
+ first.set(row[0], copy);
280
+ else
281
+ groups.set(row[0], [...groups.get(row[0]) ?? [seen], copy]);
282
+ }
283
+ const shared = {};
284
+ for (const [id, owner] of Object.entries(rollup.shared))
285
+ if (!present.has(owner))
286
+ shared[id] = owner;
287
+ const fresh = new Map();
288
+ for (const key of present.keys())
289
+ fresh.set(key, {});
290
+ let undatedTokens = 0;
291
+ const add = (key, at, tokens, subagent, usd, model) => {
292
+ if (at === null) {
293
+ undatedTokens += tokens;
294
+ return;
295
+ }
296
+ const target = fresh.get(key)[localDay(at)] ??= emptyFigures();
297
+ target.tokens += tokens;
298
+ if (subagent)
299
+ target.subagentTokens += tokens;
300
+ if (usd === null) {
301
+ target.unpricedTokens += tokens;
302
+ if (tokens > 0 && !target.unpricedModels.includes(model))
303
+ target.unpricedModels.push(model);
304
+ }
305
+ else
306
+ target.usd = { min: target.usd.min + usd.min, max: target.usd.max + usd.max };
307
+ };
308
+ for (const [id, copy] of first) {
309
+ if (id in shared)
310
+ continue;
311
+ const group = groups.get(id), row = copy.row;
312
+ if (!group) {
313
+ add(copy.key, row[1], rowTokens(row), row[12] === 1, row[2] === null || row[3] === null ? null : { min: row[2], max: row[3] }, copy.model);
314
+ continue;
315
+ }
316
+ const merged = (0, transcript_1.deduplicateTurns)(group.map(turnOf))[0];
317
+ shared[id] = merged.sessionId;
318
+ 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
+ }
320
+ // Files on disk replace their own days; files that are gone keep theirs.
321
+ const files = {};
322
+ let rollupFiles = 0;
323
+ for (const [key, entry] of Object.entries(rollup.files))
324
+ if (!present.has(key) && Object.keys(entry.days).length) {
325
+ files[key] = entry;
326
+ rollupFiles++;
327
+ }
328
+ for (const [key, host] of present)
329
+ if (Object.keys(fresh.get(key)).length)
330
+ files[key] = { host, days: fresh.get(key) };
331
+ const sorted = (value) => Object.fromEntries(Object.keys(value).sort().map(key => [key, value[key]]));
332
+ const nextRollup = { schema: ROLLUP_SCHEMA, files: sorted(files), shared: sorted(shared) };
333
+ let saved = true;
334
+ try {
335
+ const text = JSON.stringify(nextRollup);
336
+ let previous = '';
337
+ try {
338
+ previous = (0, node_fs_1.readFileSync)((0, exports.rollupPath)(home), 'utf8');
339
+ }
340
+ catch { /* none yet */ }
341
+ if (text !== previous)
342
+ writeAtomic((0, exports.rollupPath)(home), text);
343
+ }
344
+ catch {
345
+ saved = false;
346
+ }
347
+ if (cacheChanged) {
348
+ try {
349
+ writeAtomic((0, exports.cachePath)(home), JSON.stringify({ schema: CACHE_SCHEMA, signature, units: nextCache }));
350
+ }
351
+ catch { /* A cache that cannot be written (a full disk) only costs the next run time. */ }
352
+ }
353
+ const days = new Map();
354
+ let claudeSeen = [...present.values()].includes('claude');
355
+ for (const entry of Object.values(nextRollup.files)) {
356
+ if (entry.host === 'claude')
357
+ claudeSeen = true;
358
+ for (const [day, figures] of Object.entries(entry.days)) {
359
+ const total = days.get(day) ?? { ...emptyFigures(), claudeTokens: 0, codexTokens: 0 };
360
+ total.tokens += figures.tokens;
361
+ total.subagentTokens += figures.subagentTokens;
362
+ total.usd = { min: total.usd.min + figures.usd.min, max: total.usd.max + figures.usd.max };
363
+ total.unpricedTokens += figures.unpricedTokens;
364
+ for (const model of figures.unpricedModels)
365
+ if (!total.unpricedModels.includes(model))
366
+ total.unpricedModels.push(model);
367
+ if (entry.host === 'claude')
368
+ total.claudeTokens += figures.tokens;
369
+ else
370
+ total.codexTokens += figures.tokens;
371
+ days.set(day, total);
372
+ }
373
+ }
374
+ const recorded = [...days].filter(([, figures]) => figures.tokens > 0).map(([day]) => day).sort();
375
+ return {
376
+ days, heldLaunches: ledgerDays(home), firstDay: recorded[0] ?? null, claudeSeen, saved,
377
+ sources: { transcripts: loaded.length, rollupFiles, forkBoundaryUnknown: loaded.filter(entry => entry.forkUnknown).length, unreadable, undatedTokens },
378
+ };
379
+ }
380
+ /** Weeks of two columns each that fit beside the weekday labels in `columns`, 1 to 53. */
381
+ const weeksThatFit = (columns) => Math.min(exports.CALENDAR_MAX_WEEKS, Math.max(1, Math.floor((columns - exports.CALENDAR_GRID_PREFIX + 1) / 2)));
382
+ exports.weeksThatFit = weeksThatFit;
383
+ /** A day's shade: the quarter of the shown days with tokens that it reaches, so the busiest shown day is always level 4. */
384
+ function calendarLevels(values) {
385
+ const sorted = values.filter(value => value > 0).sort((a, b) => a - b);
386
+ return tokens => {
387
+ if (!(tokens > 0) || !sorted.length)
388
+ return 0;
389
+ let low = 0, high = sorted.length;
390
+ while (low < high) {
391
+ const middle = (low + high) >> 1;
392
+ if (sorted[middle] <= tokens)
393
+ low = middle + 1;
394
+ else
395
+ high = middle;
396
+ }
397
+ return Math.max(1, Math.min(4, Math.ceil(4 * low / sorted.length)));
398
+ };
399
+ }
400
+ function calendarReport(data, options = {}) {
401
+ const today = localDay(options.now ?? Date.now()), lastSunday = (0, exports.addDays)(today, -(0, exports.weekdayOf)(today));
402
+ const oldest = data.firstDay;
403
+ const span = options.weeks ?? (0, exports.weeksThatFit)(options.columns ?? 80);
404
+ const history = oldest === null ? 0 : Math.max(1, ((0, exports.dayNumber)(lastSunday) - (0, exports.dayNumber)((0, exports.addDays)(oldest, -(0, exports.weekdayOf)(oldest)))) / 7 + 1);
405
+ const weeks = options.weeks ?? Math.max(1, Math.min(span, history));
406
+ const from = (0, exports.addDays)(lastSunday, -7 * (weeks - 1));
407
+ const days = [];
408
+ for (let n = (0, exports.dayNumber)(from); n <= (0, exports.dayNumber)(today); n++) {
409
+ const date = dayText(n), figures = data.days.get(date), tokens = figures?.tokens ?? 0, subagentTokens = figures?.subagentTokens ?? 0;
410
+ days.push({ date, recorded: oldest !== null && date >= oldest, tokens, subagentTokens, usd: { ...figures?.usd ?? { min: 0, max: 0 } },
411
+ unpricedTokens: figures?.unpricedTokens ?? 0, claudeTokens: figures?.claudeTokens ?? 0, codexTokens: figures?.codexTokens ?? 0,
412
+ level: null, subagentsOverHalf: tokens > 0 && subagentTokens * 2 > tokens, heldLaunches: data.heldLaunches.get(date) ?? 0 });
413
+ }
414
+ const level = calendarLevels(days.filter(day => day.recorded).map(day => day.tokens));
415
+ for (const day of days)
416
+ day.level = day.recorded ? level(day.tokens) : null;
417
+ const sum = (field) => days.reduce((total, day) => total + day[field], 0);
418
+ const tokens = sum('tokens'), subagentTokens = sum('subagentTokens'), unpricedTokens = sum('unpricedTokens');
419
+ const unpricedModels = [...new Set(days.flatMap(day => data.days.get(day.date)?.unpricedModels ?? []))]
420
+ .sort((a, b) => a === b ? 0 : a === null ? 1 : b === null ? -1 : a < b ? -1 : 1);
421
+ 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
+ const busiest = days.reduce((best, day) => day.tokens > (best?.tokens ?? 0) ? day : best, null);
423
+ return {
424
+ from, to: today, weeks, firstRecordedDay: oldest, days,
425
+ totals: { tokens, subagentTokens, subagentShare: tokens ? subagentTokens / tokens : null, usd, unpricedTokens, unpricedModels,
426
+ heldLaunches: sum('heldLaunches'), claudeTokens: sum('claudeTokens'), codexTokens: sum('codexTokens') },
427
+ busiest: busiest ? { date: busiest.date, tokens: busiest.tokens } : null,
428
+ historyShort: data.claudeSeen && oldest !== null && history < span,
429
+ sources: data.sources, subagentsIncluded: true, basis: 'estimated_api_list_price',
430
+ };
431
+ }
@@ -0,0 +1,104 @@
1
+ import type { DollarRange, PricingTable } from './pricing';
2
+ import { type TranscriptLocation, type TranscriptOrigin } from './sessions';
3
+ import { type CompareMetric, type InsightHost, type InsightTranscript } from './types';
4
+ import { type WhyLang } from './i18n';
5
+ export interface CompareMetrics {
6
+ assistantResponses: number | null;
7
+ /** Cache reads plus cache writes plus fresh input. */
8
+ inputTokens: number | null;
9
+ cacheReadTokens: number | null;
10
+ cacheWriteTokens: number | null;
11
+ freshInputTokens: number | null;
12
+ /** Cache reads divided by all input, 0 to 1; 0 without input, as `why` prints a share of nothing. */
13
+ cacheShare: number | null;
14
+ outputTokens: number | null;
15
+ /** Agent, Task and spawn_agent calls in the session and its children: the spawns `why` counts. */
16
+ subagentsLaunched: number | null;
17
+ fullPrefixRewrites: number | null;
18
+ /** The API list equivalent `why` prints; null when a model is unpriced or usage is unavailable. */
19
+ usd: DollarRange | null;
20
+ }
21
+ export interface CompareModel {
22
+ /** Null when responses carry no model id. */
23
+ model: string | null;
24
+ responses: number;
25
+ outputTokens: number;
26
+ /** Share of the session's output tokens, 0 to 1; null when the session has no output tokens. */
27
+ share: number | null;
28
+ }
29
+ export interface CompareSession {
30
+ sessionId: string;
31
+ /** The last dash-separated part of the id: short, and accepted back as an id suffix. */
32
+ shortId: string;
33
+ host: InsightHost;
34
+ /** The transcript file. */
35
+ path: string;
36
+ /** The working directory the transcript recorded, else Claude Code's project directory; null when neither is known. */
37
+ project: string | null;
38
+ /** The earliest recorded response of the session itself (its children when it has none), ISO 8601 UTC. */
39
+ startedAt: string | null;
40
+ /** The model with the most output tokens; null without responses or when they carry no model id. */
41
+ dominantModel: string | null;
42
+ /** Every model, most output tokens first, children included. */
43
+ models: CompareModel[];
44
+ /** False when inherited Codex history has no verifiable boundary; every metric is then null, as `why` prints nothing. */
45
+ usageAvailable: boolean;
46
+ /** Models without a verified rate for at least one token category; null is a missing model id. */
47
+ unpricedModels: Array<string | null>;
48
+ metrics: CompareMetrics;
49
+ }
50
+ export interface CompareReport {
51
+ a: CompareSession;
52
+ b: CompareSession;
53
+ /** (B minus A) divided by A, unrounded; null unless both are numbers and A is not zero as printed. A dollar range compares midpoints. */
54
+ change: Record<CompareMetric, number | null>;
55
+ subagentsIncluded: true;
56
+ basis: 'estimated_api_list_price';
57
+ }
58
+ /** The last dash-separated part of a session id, which `why` and `compare` accept back as an id suffix. */
59
+ export declare const shortId: (sessionId: string) => string;
60
+ /** One session's figures. `origin` supplies the recorded working directory; without it a Claude session shows its project directory. */
61
+ export declare function compareSession(location: Pick<TranscriptLocation, 'path' | 'host'>, transcript: InsightTranscript, rates?: PricingTable, origin?: TranscriptOrigin | null): CompareSession;
62
+ export declare function compareReport(a: CompareSession, b: CompareSession): CompareReport;
63
+ export type ComparePick = {
64
+ ok: true;
65
+ a: TranscriptLocation;
66
+ b: TranscriptLocation;
67
+ explicit: boolean;
68
+ } | {
69
+ ok: false;
70
+ found: 0 | 1;
71
+ project: string | null;
72
+ };
73
+ export interface ComparePickOptions {
74
+ locations?: TranscriptLocation[];
75
+ roots?: {
76
+ claude: string;
77
+ codex: string;
78
+ };
79
+ origin?: (location: TranscriptLocation) => TranscriptOrigin;
80
+ }
81
+ /**
82
+ * Two selectors: those two sessions, in that order. One: that session and the
83
+ * newest other top-level session of its project. None: the two newest top-level
84
+ * sessions of the newest one's project. Selectors resolve exactly as `why`
85
+ * resolves one (id, id suffix or JSONL path). A top-level Claude Code session is
86
+ * a transcript directly inside its project directory, never a sub-agent file or
87
+ * any other file a session keeps beside it; a Codex rollout is top-level unless
88
+ * its first records mark a spawned sub-agent, and its project is the working
89
+ * directory it recorded. The session variables `why` falls back on are not read:
90
+ * with nothing given, recency decides.
91
+ */
92
+ export declare function pickCompareSessions(selectors: string[], options?: ComparePickOptions): ComparePick;
93
+ /** Reads each picked session the way `why` reads one. Unless the order was given, A is the session that started first. */
94
+ export declare function comparePicked(pick: {
95
+ a: TranscriptLocation;
96
+ b: TranscriptLocation;
97
+ explicit: boolean;
98
+ }, rates?: PricingTable, origin?: (location: TranscriptLocation) => TranscriptOrigin): CompareReport;
99
+ /** A signed percentage with one decimal, as `why` prints shares; a change that rounds to zero has no sign. */
100
+ export declare function signedChange(change: number | null): string;
101
+ /** A difference in share, in percentage points: "+2.6 pp" reads the same in English, Spanish and Portuguese. */
102
+ export declare function signedPoints(change: number | null): string;
103
+ /** `lang` changes words only; every figure, id, model id, path and command prints as it does in English. */
104
+ export declare function renderCompare(report: CompareReport, lang?: WhyLang): string;