@agentguard-run/burn 0.7.1 → 0.7.3

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.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WEEK_TEXT = exports.CALENDAR_TEXT = exports.COMPARE_TEXT = exports.DECISION_TEXT = exports.WHY_TEXT = exports.SIMPLE_TEXT = exports.STATUS_TEXT = void 0;
3
+ exports.WEEK_TEXT = exports.CALENDAR_TEXT = exports.MODELS_TEXT = exports.COMPARE_TEXT = exports.DECISION_TEXT = exports.WHY_TEXT = exports.SIMPLE_TEXT = exports.STATUS_TEXT = void 0;
4
4
  exports.whyLangOf = whyLangOf;
5
5
  exports.detectWhyLang = detectWhyLang;
6
6
  /**
@@ -347,6 +347,85 @@ const comparePt = {
347
347
  : `Só uma sessão principal foi encontrada${project ? ` em ${project}` : ''}, e o compare precisa de duas. Passe dois ids: ${TWO_IDS}`,
348
348
  };
349
349
  exports.COMPARE_TEXT = { en: compareEn, es: compareEs, pt: comparePt };
350
+ const lastDays = (days) => days === 1 ? 'last day' : `last ${days} days`;
351
+ const sessionsEn = (n) => `${n} ${n === 1 ? 'session' : 'sessions'}`;
352
+ const modelsEn = {
353
+ title: days => `AgentGuard models: your sessions on each model, ${lastDays(days)}`,
354
+ scope: (sessions, since) => `${sessionsEn(sessions)} that started since ${since}: top-level Claude Code and Codex sessions, each under the model with the most of its output tokens, oldest model first.`,
355
+ none: days => `No top-level Claude Code or Codex session started in the ${lastDays(days)}.`,
356
+ unknownModel: 'unknown model',
357
+ sessions: sessionsEn,
358
+ dates: (first, last) => first === last ? first : `${first} to ${last}`,
359
+ medianHeader: 'Per session, median',
360
+ totalHeader: 'All sessions, total',
361
+ unfinished: ' ended without finishing',
362
+ unknown: 'unknown',
363
+ unfinishedUnknown: (label, unknown, sessions) => unknown === sessions
364
+ ? `${label}: how its sub-agents ended is unknown in ${sessions === 1 ? 'its one session' : `all ${sessions} sessions`}.`
365
+ : `${label}: how its sub-agents ended is unknown for ${unknown} of ${sessionsEn(sessions)}, so the ended without finishing row covers the other ${sessions - unknown === 1 ? 'one' : sessions - unknown}.`,
366
+ unfinishedSource: 'Burn reads how a sub-agent ended from the sub-agent transcripts Claude Code keeps beside a session; Codex records nothing it reads for this.',
367
+ unpricedGroup: (label, unpriced, sessions) => `${label}: ${unpriced === sessions ? (sessions === 1 ? 'its one session' : `all ${sessions} sessions`) : `${unpriced} of ${sessionsEn(sessions)}`} used a model with no verified rate, so its List USD is unpriced.`,
368
+ overSize: (count, megabytes) => `Skipped ${sessionsEn(count)} over ${megabytes} MB (transcript plus sub-agent transcripts). Run why on one to see it alone, or raise the cap with --max-mb.`,
369
+ unreadable: count => `${sessionsEn(count)} could not be read and ${count === 1 ? 'is' : 'are'} left out.`,
370
+ usageUnavailable: count => `${count} Codex ${count === 1 ? 'session' : 'sessions'}: inherited history has no verifiable boundary, so usage is unavailable. Copied usage is excluded, not counted as zero.`,
371
+ overLimit: (count, limit, maxLimit) => `${count} older ${count === 1 ? 'session' : 'sessions'} changed in this window ${count === 1 ? 'was' : 'were'} not read: the report reads the ${limit} most recent. Raise it with --limit, up to ${maxLimit}.`,
372
+ startedBefore: count => `${sessionsEn(count)} changed in this window but started before it, so ${count === 1 ? 'it is' : 'they are'} left out.`,
373
+ noResponseTime: count => `${sessionsEn(count)} ${count === 1 ? 'records' : 'record'} no timed assistant response, so ${count === 1 ? 'it has' : 'they have'} no start time and ${count === 1 ? 'is' : 'are'} in no group.`,
374
+ sameWork: 'AgentGuard cannot tell whether the sessions on each model did comparable work, so a difference can come from the work as well as from the model.',
375
+ };
376
+ const ultimosDias = (days) => days === 1 ? 'último día' : `últimos ${days} días`;
377
+ const sesiones = (n) => plural(n, 'sesión', 'sesiones');
378
+ const modelsEs = {
379
+ title: days => `AgentGuard models: tus sesiones en cada modelo, ${ultimosDias(days)}`,
380
+ scope: (sessions, since) => `${sesiones(sessions)} ${sessions === 1 ? 'iniciada' : 'iniciadas'} desde ${since}: sesiones principales de Claude Code y Codex, cada una bajo el modelo con más de sus tokens de salida, del modelo más antiguo al más reciente.`,
381
+ none: days => `Ninguna sesión principal de Claude Code ni de Codex comenzó ${days === 1 ? 'en el último día' : `en los últimos ${days} días`}.`,
382
+ unknownModel: 'modelo desconocido',
383
+ sessions: sesiones,
384
+ dates: (first, last) => first === last ? first : `${first} a ${last}`,
385
+ medianHeader: 'Por sesión, mediana',
386
+ totalHeader: 'Todas las sesiones, total',
387
+ unfinished: ' quedaron sin terminar',
388
+ unknown: 'desconocido',
389
+ unfinishedUnknown: (label, unknown, sessions) => unknown === sessions
390
+ ? `${label}: no se sabe cómo terminaron sus subagentes en ${sessions === 1 ? 'su única sesión' : `ninguna de sus ${sessions} sesiones`}.`
391
+ : `${label}: no se sabe cómo terminaron sus subagentes en ${unknown} de ${sesiones(sessions)}, así que la fila de los que quedaron sin terminar cubre ${sessions - unknown === 1 ? 'la otra' : `las otras ${sessions - unknown}`}.`,
392
+ unfinishedSource: 'Burn lee cómo terminó un subagente en las transcripciones de subagentes que Claude Code guarda junto a cada sesión; Codex no registra nada que Burn pueda leer para esto.',
393
+ unpricedGroup: (label, unpriced, sessions) => `${label}: ${unpriced === sessions ? (sessions === 1 ? 'su única sesión usó' : `sus ${sessions} sesiones usaron`) : `${unpriced} de ${sesiones(sessions)} ${unpriced === 1 ? 'usó' : 'usaron'}`} un modelo sin tarifa verificada, así que su USD de lista queda sin precio.`,
394
+ overSize: (count, megabytes) => `${count === 1 ? 'Se omitió' : 'Se omitieron'} ${sesiones(count)} de más de ${megabytes} MB (transcripción más transcripciones de subagentes). Ejecuta why en una para verla sola, o sube el límite con --max-mb.`,
395
+ unreadable: count => `${count === 1 ? 'No se pudo leer 1 sesión y queda fuera.' : `No se pudieron leer ${count} sesiones y quedan fuera.`}`,
396
+ usageUnavailable: count => `${count === 1 ? '1 sesión' : `${count} sesiones`} de Codex: el historial heredado no tiene un punto de corte verificable, así que su uso no está disponible. El uso copiado queda excluido, no se cuenta como cero.`,
397
+ overLimit: (count, limit, maxLimit) => `${count === 1 ? 'No se leyó 1 sesión más antigua' : `No se leyeron ${count} sesiones más antiguas`} con cambios en este período: el informe lee las ${limit} más recientes. Súbelo con --limit, hasta ${maxLimit}.`,
398
+ startedBefore: count => `${sesiones(count)} con cambios en este período ${count === 1 ? 'comenzó' : 'comenzaron'} antes, así que ${count === 1 ? 'queda' : 'quedan'} fuera.`,
399
+ noResponseTime: count => `${sesiones(count)} no ${count === 1 ? 'registra' : 'registran'} ninguna respuesta del asistente con hora, así que no ${count === 1 ? 'tiene' : 'tienen'} hora de inicio y no ${count === 1 ? 'entra' : 'entran'} en ningún grupo.`,
400
+ sameWork: 'AgentGuard no puede saber si las sesiones de cada modelo hicieron un trabajo comparable, así que una diferencia puede venir del trabajo tanto como del modelo.',
401
+ };
402
+ const ultimosDiasPt = (days) => days === 1 ? 'último dia' : `últimos ${days} dias`;
403
+ const sessoes = (n) => plural(n, 'sessão', 'sessões');
404
+ const modelsPt = {
405
+ title: days => `AgentGuard models: suas sessões em cada modelo, ${ultimosDiasPt(days)}`,
406
+ scope: (sessions, since) => `${sessoes(sessions)} ${sessions === 1 ? 'iniciada' : 'iniciadas'} desde ${since}: sessões principais do Claude Code e do Codex, cada uma sob o modelo com mais tokens de saída dela, do modelo mais antigo ao mais recente.`,
407
+ none: days => `Nenhuma sessão principal do Claude Code ou do Codex começou ${days === 1 ? 'no último dia' : `nos últimos ${days} dias`}.`,
408
+ unknownModel: 'modelo desconhecido',
409
+ sessions: sessoes,
410
+ dates: (first, last) => first === last ? first : `${first} a ${last}`,
411
+ medianHeader: 'Por sessão, mediana',
412
+ totalHeader: 'Todas as sessões, total',
413
+ unfinished: ' pararam sem terminar',
414
+ unknown: 'desconhecido',
415
+ unfinishedUnknown: (label, unknown, sessions) => unknown === sessions
416
+ ? `${label}: não se sabe como os subagentes terminaram ${sessions === 1 ? 'na única sessão' : `em nenhuma das ${sessions} sessões`}.`
417
+ : `${label}: não se sabe como os subagentes terminaram em ${unknown} de ${sessoes(sessions)}, então a linha dos que pararam sem terminar cobre ${sessions - unknown === 1 ? 'a outra' : `as outras ${sessions - unknown}`}.`,
418
+ unfinishedSource: 'O Burn lê como um subagente terminou nas transcrições de subagentes que o Claude Code guarda junto de cada sessão; o Codex não registra nada que o Burn leia para isso.',
419
+ unpricedGroup: (label, unpriced, sessions) => `${label}: ${unpriced === sessions ? (sessions === 1 ? 'a única sessão usou' : `as ${sessions} sessões usaram`) : `${unpriced} de ${sessoes(sessions)} ${unpriced === 1 ? 'usou' : 'usaram'}`} um modelo sem tarifa verificada, então o USD de tabela fica sem preço.`,
420
+ overSize: (count, megabytes) => `${count === 1 ? '1 sessão acima' : `${count} sessões acima`} de ${megabytes} MB ${count === 1 ? 'ficou' : 'ficaram'} de fora (transcrição mais transcrições de subagentes). Rode why em uma para vê-la sozinha, ou aumente o limite com --max-mb.`,
421
+ unreadable: count => `${count === 1 ? 'Não foi possível ler 1 sessão, que fica de fora.' : `Não foi possível ler ${count} sessões, que ficam de fora.`}`,
422
+ usageUnavailable: count => `${count === 1 ? '1 sessão' : `${count} sessões`} do Codex: o histórico herdado não tem um ponto de corte verificável, então o uso fica indisponível. O uso copiado fica de fora, não é contado como zero.`,
423
+ overLimit: (count, limit, maxLimit) => `${count === 1 ? '1 sessão mais antiga' : `${count} sessões mais antigas`} com mudanças neste período não ${count === 1 ? 'foi lida' : 'foram lidas'}: o relatório lê as ${limit} mais recentes. Aumente com --limit, até ${maxLimit}.`,
424
+ startedBefore: count => `${sessoes(count)} com mudanças neste período ${count === 1 ? 'começou' : 'começaram'} antes dele, então ${count === 1 ? 'fica' : 'ficam'} de fora.`,
425
+ noResponseTime: count => `${sessoes(count)} não ${count === 1 ? 'registra' : 'registram'} nenhuma resposta do assistente com horário, então não ${count === 1 ? 'tem' : 'têm'} horário de início e não ${count === 1 ? 'entra' : 'entram'} em nenhum grupo.`,
426
+ sameWork: 'O AgentGuard não consegue saber se as sessões de cada modelo fizeram um trabalho comparável, então uma diferença pode vir do trabalho tanto quanto do modelo.',
427
+ };
428
+ exports.MODELS_TEXT = { en: modelsEn, es: modelsEs, pt: modelsPt };
350
429
  const hostList = (claude, codex, and, of = '') => [claude ? `${of}Claude Code` : '', codex ? `${of}Codex` : ''].filter(Boolean).join(` ${and} `);
351
430
  const calendarEn = {
352
431
  weekdays: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
@@ -0,0 +1,169 @@
1
+ import type { DollarRange, PricingTable } from './pricing';
2
+ import { type CompareSession } from './compare';
3
+ import { type TranscriptLocation, type TranscriptOrigin } from './sessions';
4
+ import type { InsightTranscript } from './types';
5
+ import { type WhyLang } from './i18n';
6
+ export declare const MODELS_DEFAULT_DAYS = 30;
7
+ export declare const MODELS_MAX_DAYS = 365;
8
+ /** The most recent sessions read by default, and the most `--limit` allows. */
9
+ export declare const MODELS_DEFAULT_LIMIT = 300;
10
+ export declare const MODELS_MAX_LIMIT = 2000;
11
+ /**
12
+ * A session whose transcript plus sub-agent transcripts pass this many bytes is
13
+ * skipped and counted, never read. 256 MB is the size above which `why` itself
14
+ * stops reading a file whole (WHOLE_FILE_MAX_BYTES); on the machine this was
15
+ * built on, a 30-day window of 84 sessions holding 14 GB read 1 GB under it.
16
+ */
17
+ export declare const MODELS_DEFAULT_MAX_SESSION_BYTES: number;
18
+ /** The most `--max-mb` allows. */
19
+ export declare const MODELS_MAX_SESSION_MEGABYTES = 4096;
20
+ /** One session the report counted: compare's figures plus how many of its sub-agents ended without finishing. */
21
+ export interface ModelsSession extends CompareSession {
22
+ /**
23
+ * Sub-agents recorded as failed, killed or stopped and never as completed or
24
+ * resumed, the count `why` prints. 0 when the session launched none. Null
25
+ * when it launched some and no transcript Burn reads records how they ended:
26
+ * every Codex session with a launch, and a Claude Code session with no
27
+ * sub-agent transcripts beside it.
28
+ */
29
+ subagentsUnfinished: number | null;
30
+ /** The transcript plus its sub-agent transcripts, in bytes. */
31
+ bytes: number;
32
+ }
33
+ /** What a group is computed from; `ModelsSession` carries it all. */
34
+ export type ModelsSessionInput = Pick<ModelsSession, 'host' | 'startedAt' | 'dominantModel' | 'usageAvailable' | 'metrics' | 'unpricedModels' | 'subagentsUnfinished'>;
35
+ export interface ModelsGroup {
36
+ /** The dominant model of every session in the group; null groups sessions whose responses carry no model id. */
37
+ model: string | null;
38
+ sessions: number;
39
+ hosts: {
40
+ claude: number;
41
+ codex: number;
42
+ };
43
+ /** The earliest and latest session start, ISO 8601 UTC. */
44
+ firstSessionAt: string;
45
+ lastSessionAt: string;
46
+ /** Cache reads plus cache writes plus fresh input, per session. */
47
+ inputTokens: {
48
+ median: number;
49
+ total: number;
50
+ };
51
+ outputTokens: {
52
+ median: number;
53
+ total: number;
54
+ };
55
+ /** Per-session cache reads over all input, 0 to 1; `pooled` is the group's cache reads over its input. Both are 0 without input, as `compare` prints a share of nothing. */
56
+ cacheShare: {
57
+ median: number;
58
+ pooled: number;
59
+ };
60
+ subagentsLaunched: {
61
+ median: number;
62
+ total: number;
63
+ };
64
+ /**
65
+ * Over the `known` sessions only; `unknown` sessions are left out, never
66
+ * counted as 0. Median and total are null when no session is known.
67
+ */
68
+ subagentsUnfinished: {
69
+ median: number | null;
70
+ total: number | null;
71
+ known: number;
72
+ unknown: number;
73
+ };
74
+ /**
75
+ * API list equivalents. Null while any session of the group is unpriced
76
+ * (`unpricedSessions`), as `why` prints a session unpriced. The median of
77
+ * dollar ranges is the median of their low ends to the median of their high
78
+ * ends, which holds the median of the true figures.
79
+ */
80
+ usd: {
81
+ median: DollarRange | null;
82
+ total: DollarRange | null;
83
+ unpricedSessions: number;
84
+ };
85
+ /** Models without a verified rate in any session of the group; null is a missing model id. */
86
+ unpricedModels: Array<string | null>;
87
+ }
88
+ export interface ModelsSkipped {
89
+ /** Not read: transcript plus sub-agent transcripts over `maxSessionBytes`. */
90
+ overSizeCap: number;
91
+ /** Not read: the file or its sub-agent folder could not be read. */
92
+ unreadable: number;
93
+ /** Read, but inherited Codex history has no verifiable boundary, so its usage is unavailable (compare prints nothing for it). */
94
+ usageUnavailable: number;
95
+ /** Not read: changed in the window but older than the `limit` most recent. */
96
+ overLimit: number;
97
+ /** Read: changed in the window, but its first response is before it. */
98
+ startedBeforeWindow: number;
99
+ /** Read: no assistant response with a time, so no start time and no group. */
100
+ noResponseTime: number;
101
+ }
102
+ export interface ModelsSkippedSession {
103
+ sessionId: string;
104
+ host: TranscriptLocation['host'];
105
+ path: string;
106
+ reason: 'over_size_cap' | 'unreadable' | 'usage_unavailable';
107
+ /** Null when the size could not be read. */
108
+ bytes: number | null;
109
+ /** For an unreadable session, the system error code (EACCES, ENOTDIR) or the error's name; null otherwise. */
110
+ error: string | null;
111
+ }
112
+ export interface ModelsReport {
113
+ window: {
114
+ days: number;
115
+ since: string;
116
+ until: string;
117
+ };
118
+ limit: number;
119
+ maxSessionBytes: number;
120
+ /** Oldest first session first, so the report reads as before, then after. */
121
+ models: ModelsGroup[];
122
+ /** Every counted session, earliest start first. */
123
+ sessions: ModelsSession[];
124
+ skipped: ModelsSkipped;
125
+ /** The sessions behind overSizeCap, unreadable and usageUnavailable, so each can be opened with `why`. */
126
+ skippedSessions: ModelsSkippedSession[];
127
+ subagentsIncluded: true;
128
+ basis: 'estimated_api_list_price';
129
+ }
130
+ export interface ModelsOptions {
131
+ /** 1 to 365; default 30. Sessions that started in the last N days count. */
132
+ days?: number;
133
+ /** 1 to 2000; default 300. At most this many of the most recently changed sessions are read. */
134
+ limit?: number;
135
+ /** Default 256 MB. */
136
+ maxSessionBytes?: number;
137
+ now?: number;
138
+ roots?: {
139
+ claude: string;
140
+ codex: string;
141
+ };
142
+ /** Discovered transcripts, when the caller already has them; else discovered under `roots`. */
143
+ locations?: TranscriptLocation[];
144
+ rates?: PricingTable;
145
+ origin?: (location: TranscriptLocation) => TranscriptOrigin;
146
+ }
147
+ /**
148
+ * The sub-agents of one session that ended without finishing, or null when that
149
+ * cannot be known. `unfinishedSubagents` is `why`'s own count; it reads only the
150
+ * session's sub-agent transcripts and the outcomes recorded in it and them.
151
+ */
152
+ export declare function subagentsUnfinished(transcript: Pick<InsightTranscript, 'subagents' | 'observations'>): number | null;
153
+ /** The bytes `readInsightSession` reads for a session: its transcript and every `.jsonl` in its `subagents` folder. Throws when either cannot be listed. */
154
+ export declare function sessionBytes(path: string): number;
155
+ /** Sessions grouped under their dominant model, groups ordered by first session, oldest first (then by model id, a missing one last). */
156
+ export declare function modelGroups(sessions: readonly ModelsSessionInput[]): ModelsGroup[];
157
+ /**
158
+ * Reads and groups the window's top-level sessions. A top-level session is the
159
+ * one `compare` picks: a Claude Code transcript directly inside its project
160
+ * directory (never a sub-agent's file or another file a session keeps beside
161
+ * it), or a Codex rollout whose first records do not mark a spawned sub-agent.
162
+ * A file last changed before the window cannot hold a session that started in
163
+ * it, so only files changed in the window are candidates; the `limit` most
164
+ * recently changed are read, and a session counts when its first response is
165
+ * in the window. Everything not counted is counted by reason.
166
+ */
167
+ export declare function modelsReport(options?: ModelsOptions): ModelsReport;
168
+ /** `lang` changes words only; every figure, id, model id, date and command prints as it does in English. */
169
+ export declare function renderModels(report: ModelsReport, lang?: WhyLang): string;
@@ -0,0 +1,280 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MODELS_MAX_SESSION_MEGABYTES = exports.MODELS_DEFAULT_MAX_SESSION_BYTES = exports.MODELS_MAX_LIMIT = exports.MODELS_DEFAULT_LIMIT = exports.MODELS_MAX_DAYS = exports.MODELS_DEFAULT_DAYS = void 0;
4
+ exports.subagentsUnfinished = subagentsUnfinished;
5
+ exports.sessionBytes = sessionBytes;
6
+ exports.modelGroups = modelGroups;
7
+ exports.modelsReport = modelsReport;
8
+ exports.renderModels = renderModels;
9
+ /**
10
+ * `models`: every top-level session of a window, grouped under its dominant
11
+ * model, for someone who switched models and wants to see, from their own
12
+ * transcripts, how sessions on the new model differ from sessions on the old
13
+ * one. Each session's figures are the ones `compare` (and so `why`) prints for
14
+ * it, child transcripts included; this file only selects sessions, reads them
15
+ * within a bound and summarizes each group. Measurement only: nothing here
16
+ * judges which model did better.
17
+ */
18
+ const node_fs_1 = require("node:fs");
19
+ const node_path_1 = require("node:path");
20
+ const live_1 = require("./live");
21
+ const compare_1 = require("./compare");
22
+ const render_1 = require("./render");
23
+ const sessions_1 = require("./sessions");
24
+ const transcript_1 = require("./transcript");
25
+ const i18n_1 = require("./i18n");
26
+ exports.MODELS_DEFAULT_DAYS = 30;
27
+ exports.MODELS_MAX_DAYS = 365;
28
+ /** The most recent sessions read by default, and the most `--limit` allows. */
29
+ exports.MODELS_DEFAULT_LIMIT = 300;
30
+ exports.MODELS_MAX_LIMIT = 2000;
31
+ /**
32
+ * A session whose transcript plus sub-agent transcripts pass this many bytes is
33
+ * skipped and counted, never read. 256 MB is the size above which `why` itself
34
+ * stops reading a file whole (WHOLE_FILE_MAX_BYTES); on the machine this was
35
+ * built on, a 30-day window of 84 sessions holding 14 GB read 1 GB under it.
36
+ */
37
+ exports.MODELS_DEFAULT_MAX_SESSION_BYTES = 256 * 1024 * 1024;
38
+ /** The most `--max-mb` allows. */
39
+ exports.MODELS_MAX_SESSION_MEGABYTES = 4096;
40
+ /** Files are read in pieces this size, so no session needs one string of its whole transcript. The figures equal a whole-file read. */
41
+ const READ_CHUNK_BYTES = 16 * 1024 * 1024;
42
+ const DAY_MS = 86_400_000;
43
+ const median = (values) => {
44
+ if (!values.length)
45
+ return null;
46
+ const sorted = [...values].sort((a, b) => a - b), middle = Math.floor(sorted.length / 2);
47
+ return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
48
+ };
49
+ const sum = (values) => values.reduce((total, value) => total + value, 0);
50
+ const byName = (a, b) => a === b ? 0 : a === null ? 1 : b === null ? -1 : a < b ? -1 : 1;
51
+ const wholeNumber = (value, low, high) => typeof value === 'number' && Number.isSafeInteger(value) && value >= low && value <= high;
52
+ /**
53
+ * The sub-agents of one session that ended without finishing, or null when that
54
+ * cannot be known. `unfinishedSubagents` is `why`'s own count; it reads only the
55
+ * session's sub-agent transcripts and the outcomes recorded in it and them.
56
+ */
57
+ function subagentsUnfinished(transcript) {
58
+ if (transcript.subagents)
59
+ return (0, render_1.unfinishedSubagents)(transcript, { turns: [], prices: [] })?.count ?? 0;
60
+ return transcript.observations.spawnCalls === 0 ? 0 : null;
61
+ }
62
+ /** The bytes `readInsightSession` reads for a session: its transcript and every `.jsonl` in its `subagents` folder. Throws when either cannot be listed. */
63
+ function sessionBytes(path) {
64
+ let bytes = (0, node_fs_1.statSync)(path).size, names;
65
+ const children = (0, node_path_1.join)(path.replace(/\.jsonl$/, ''), 'subagents');
66
+ try {
67
+ names = (0, node_fs_1.readdirSync)(children).filter(name => name.endsWith('.jsonl'));
68
+ }
69
+ catch (error) {
70
+ if (error.code === 'ENOENT')
71
+ return bytes;
72
+ throw error;
73
+ }
74
+ for (const name of names)
75
+ bytes += (0, node_fs_1.statSync)((0, node_path_1.join)(children, name)).size;
76
+ return bytes;
77
+ }
78
+ /** One group's figures. Every input must have usage and a start time; a row without either is a caller error, never silently left out. */
79
+ function group(model, rows) {
80
+ const starts = rows.map(row => row.startedAt).sort();
81
+ const figure = (key) => rows.map(row => row.metrics[key]);
82
+ const input = figure('inputTokens'), output = figure('outputTokens'), launched = figure('subagentsLaunched');
83
+ const known = rows.flatMap(row => row.subagentsUnfinished === null ? [] : [row.subagentsUnfinished]);
84
+ const usd = rows.map(row => row.metrics.usd);
85
+ const priced = usd.filter((value) => value !== null);
86
+ const totalInput = sum(input);
87
+ return {
88
+ model, sessions: rows.length,
89
+ hosts: { claude: rows.filter(row => row.host === 'claude').length, codex: rows.filter(row => row.host === 'codex').length },
90
+ firstSessionAt: starts[0], lastSessionAt: starts.at(-1),
91
+ inputTokens: { median: median(input), total: totalInput },
92
+ outputTokens: { median: median(output), total: sum(output) },
93
+ cacheShare: { median: median(figure('cacheShare')), pooled: totalInput ? sum(figure('cacheReadTokens')) / totalInput : 0 },
94
+ subagentsLaunched: { median: median(launched), total: sum(launched) },
95
+ subagentsUnfinished: { median: median(known), total: known.length ? sum(known) : null, known: known.length, unknown: rows.length - known.length },
96
+ usd: { median: priced.length === usd.length ? { min: median(priced.map(value => value.min)), max: median(priced.map(value => value.max)) } : null,
97
+ total: (0, render_1.sumPrices)(usd), unpricedSessions: usd.length - priced.length },
98
+ unpricedModels: [...new Set(rows.flatMap(row => row.unpricedModels))].sort(byName),
99
+ };
100
+ }
101
+ /** Sessions grouped under their dominant model, groups ordered by first session, oldest first (then by model id, a missing one last). */
102
+ function modelGroups(sessions) {
103
+ const byModel = new Map();
104
+ for (const session of sessions) {
105
+ if (!session.usageAvailable || session.startedAt === null)
106
+ throw new TypeError('modelGroups: every session needs usage and a start time');
107
+ const rows = byModel.get(session.dominantModel);
108
+ if (rows)
109
+ rows.push(session);
110
+ else
111
+ byModel.set(session.dominantModel, [session]);
112
+ }
113
+ return [...byModel].map(([model, rows]) => group(model, rows))
114
+ .sort((a, b) => a.firstSessionAt < b.firstSessionAt ? -1 : a.firstSessionAt > b.firstSessionAt ? 1 : byName(a.model, b.model));
115
+ }
116
+ /**
117
+ * Reads and groups the window's top-level sessions. A top-level session is the
118
+ * one `compare` picks: a Claude Code transcript directly inside its project
119
+ * directory (never a sub-agent's file or another file a session keeps beside
120
+ * it), or a Codex rollout whose first records do not mark a spawned sub-agent.
121
+ * A file last changed before the window cannot hold a session that started in
122
+ * it, so only files changed in the window are candidates; the `limit` most
123
+ * recently changed are read, and a session counts when its first response is
124
+ * in the window. Everything not counted is counted by reason.
125
+ */
126
+ function modelsReport(options = {}) {
127
+ const days = options.days ?? exports.MODELS_DEFAULT_DAYS, limit = options.limit ?? exports.MODELS_DEFAULT_LIMIT;
128
+ const maxSessionBytes = options.maxSessionBytes ?? exports.MODELS_DEFAULT_MAX_SESSION_BYTES;
129
+ if (!wholeNumber(days, 1, exports.MODELS_MAX_DAYS))
130
+ throw new RangeError(`days must be a whole number from 1 to ${exports.MODELS_MAX_DAYS}`);
131
+ if (!wholeNumber(limit, 1, exports.MODELS_MAX_LIMIT))
132
+ throw new RangeError(`limit must be a whole number from 1 to ${exports.MODELS_MAX_LIMIT}`);
133
+ if (!wholeNumber(maxSessionBytes, 1, Number.MAX_SAFE_INTEGER))
134
+ throw new RangeError('maxSessionBytes must be a positive whole number');
135
+ const now = options.now ?? Date.now(), since = now - days * DAY_MS;
136
+ const roots = options.roots ?? (0, sessions_1.transcriptRoots)(), rates = options.rates ?? {};
137
+ const origins = new Map(), readOrigin = options.origin ?? sessions_1.transcriptOrigin;
138
+ const origin = (location) => {
139
+ let value = origins.get(location.path);
140
+ if (!value) {
141
+ value = readOrigin(location);
142
+ origins.set(location.path, value);
143
+ }
144
+ return value;
145
+ };
146
+ const topLevel = (location) => !(0, sessions_1.isSubagentTranscript)(location)
147
+ && (location.host === 'claude' ? (0, node_path_1.dirname)((0, node_path_1.dirname)(location.path)) === roots.claude : !origin(location).spawned);
148
+ const candidates = (options.locations ?? (0, sessions_1.discoverInsightTranscripts)(roots))
149
+ .filter(location => location.modifiedAt >= since)
150
+ .sort((a, b) => b.modifiedAt - a.modifiedAt || a.path.localeCompare(b.path))
151
+ .filter(topLevel);
152
+ const skipped = { overSizeCap: 0, unreadable: 0, usageUnavailable: 0, overLimit: Math.max(0, candidates.length - limit), startedBeforeWindow: 0, noResponseTime: 0 };
153
+ const skippedSessions = [];
154
+ const skip = (location, reason, bytes, error = null) => {
155
+ skipped[reason === 'over_size_cap' ? 'overSizeCap' : reason === 'unreadable' ? 'unreadable' : 'usageUnavailable']++;
156
+ const code = error === null ? null : error?.code ?? (error instanceof Error ? error.name : 'Error');
157
+ skippedSessions.push({ sessionId: location.sessionId, host: location.host, path: location.path, reason, bytes, error: typeof code === 'string' ? code : null });
158
+ };
159
+ const sessions = [];
160
+ for (const location of candidates.slice(0, limit)) {
161
+ let bytes;
162
+ try {
163
+ bytes = sessionBytes(location.path);
164
+ }
165
+ catch (error) {
166
+ skip(location, 'unreadable', null, error);
167
+ continue;
168
+ }
169
+ if (bytes > maxSessionBytes) {
170
+ skip(location, 'over_size_cap', bytes);
171
+ continue;
172
+ }
173
+ let session;
174
+ try {
175
+ const transcript = (0, transcript_1.readInsightSession)(location.path, { host: location.host, sessionId: location.sessionId }, { chunkBytes: READ_CHUNK_BYTES });
176
+ session = { ...(0, compare_1.compareSession)(location, transcript, rates, origin(location)), subagentsUnfinished: subagentsUnfinished(transcript), bytes };
177
+ }
178
+ catch (error) {
179
+ skip(location, 'unreadable', bytes, error);
180
+ continue;
181
+ }
182
+ if (!session.usageAvailable) {
183
+ skip(location, 'usage_unavailable', bytes);
184
+ continue;
185
+ }
186
+ if (session.startedAt === null) {
187
+ skipped.noResponseTime++;
188
+ continue;
189
+ }
190
+ if (Date.parse(session.startedAt) < since) {
191
+ skipped.startedBeforeWindow++;
192
+ continue;
193
+ }
194
+ sessions.push(session);
195
+ }
196
+ sessions.sort((a, b) => a.startedAt < b.startedAt ? -1 : a.startedAt > b.startedAt ? 1 : a.path.localeCompare(b.path));
197
+ return {
198
+ window: { days, since: new Date(since).toISOString(), until: new Date(now).toISOString() }, limit, maxSessionBytes,
199
+ models: modelGroups(sessions), sessions, skipped, skippedSessions, subagentsIncluded: true, basis: 'estimated_api_list_price',
200
+ };
201
+ }
202
+ const stamp = (iso) => `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`;
203
+ const isRange = (value) => value !== null && Math.abs(value.max - value.min) >= 0.000001;
204
+ /** A median of counts is whole or a half; tokens print whole, as everywhere in `why`. */
205
+ const tokens = (value) => (0, render_1.count)(Math.round(value));
206
+ const subagents = (value) => Number.isInteger(value) ? (0, render_1.count)(value) : value.toFixed(1);
207
+ const percent = (value) => `${(value * 100).toFixed(1)}%`;
208
+ /** Columns per table, so three groups of ordinary figures fit 80 columns; more groups continue in another table. */
209
+ const COLUMNS = 3;
210
+ /** `lang` changes words only; every figure, id, model id, date and command prints as it does in English. */
211
+ function renderModels(report, lang = 'en') {
212
+ const text = i18n_1.MODELS_TEXT[lang], words = i18n_1.WHY_TEXT[lang], labels = i18n_1.COMPARE_TEXT[lang].labels;
213
+ const name = (model) => model ?? text.unknownModel;
214
+ const groups = report.models.map((group, index) => ({ label: String(index + 1), group }));
215
+ const lines = [text.title(report.window.days)];
216
+ if (!groups.length)
217
+ lines.push(text.none(report.window.days));
218
+ else {
219
+ lines.push(text.scope(report.sessions.length, stamp(report.window.since)), '');
220
+ const width = Math.max(...groups.map(({ group }) => name(group.model).length));
221
+ const counts = Math.max(...groups.map(({ group }) => text.sessions(group.sessions).length));
222
+ for (const { label, group } of groups) {
223
+ lines.push(`${label.padEnd(String(groups.length).length)} ${name(group.model).padEnd(width)} ${text.sessions(group.sessions).padEnd(counts)} ${text.dates(group.firstSessionAt.slice(0, 10), group.lastSessionAt.slice(0, 10))}`);
224
+ }
225
+ const unfinished = (value) => value === null ? text.unknown : subagents(value);
226
+ const money = (value) => (0, live_1.dollars)(value, words);
227
+ for (let start = 0; start < groups.length; start += COLUMNS) {
228
+ const shown = groups.slice(start, start + COLUMNS), heads = shown.map(({ label }) => label);
229
+ const row = (label, cell) => [label, ...shown.map(({ group }) => cell(group))];
230
+ // One table, so both halves share their column widths; the empty row prints as a blank line.
231
+ lines.push('', (0, render_1.table)([text.medianHeader, ...heads], [
232
+ row(labels.inputTokens, group => tokens(group.inputTokens.median)),
233
+ row(labels.outputTokens, group => tokens(group.outputTokens.median)),
234
+ row(labels.cacheShare, group => percent(group.cacheShare.median)),
235
+ row(labels.subagentsLaunched, group => subagents(group.subagentsLaunched.median)),
236
+ row(text.unfinished, group => unfinished(group.subagentsUnfinished.median)),
237
+ row(labels.usd, group => money(group.usd.median)),
238
+ [],
239
+ [text.totalHeader, ...heads],
240
+ row(labels.inputTokens, group => (0, render_1.count)(group.inputTokens.total)),
241
+ row(labels.outputTokens, group => (0, render_1.count)(group.outputTokens.total)),
242
+ row(labels.cacheShare, group => percent(group.cacheShare.pooled)),
243
+ row(labels.subagentsLaunched, group => (0, render_1.count)(group.subagentsLaunched.total)),
244
+ row(text.unfinished, group => unfinished(group.subagentsUnfinished.total)),
245
+ row(labels.usd, group => money(group.usd.total)),
246
+ ]));
247
+ }
248
+ lines.push(i18n_1.COMPARE_TEXT[lang].subagents);
249
+ }
250
+ const notes = [];
251
+ const unknownOutcomes = groups.filter(({ group }) => group.subagentsUnfinished.unknown > 0);
252
+ for (const { label, group } of unknownOutcomes)
253
+ notes.push(text.unfinishedUnknown(label, group.subagentsUnfinished.unknown, group.sessions));
254
+ if (unknownOutcomes.length)
255
+ notes.push(text.unfinishedSource);
256
+ for (const { label, group } of groups)
257
+ if (group.usd.unpricedSessions > 0)
258
+ notes.push(text.unpricedGroup(label, group.usd.unpricedSessions, group.sessions));
259
+ const unpriced = [...new Set(groups.flatMap(({ group }) => group.unpricedModels.map(name => name ?? words.missingModel)))];
260
+ if (unpriced.length)
261
+ notes.push(words.unpricedModels(unpriced.join(', ')));
262
+ if (groups.some(({ group }) => isRange(group.usd.median) || isRange(group.usd.total)))
263
+ notes.push(words.missingTtl);
264
+ const { skipped } = report;
265
+ if (skipped.overSizeCap)
266
+ notes.push(text.overSize(skipped.overSizeCap, Math.round(report.maxSessionBytes / 1024 / 1024 * 100) / 100));
267
+ if (skipped.unreadable)
268
+ notes.push(text.unreadable(skipped.unreadable));
269
+ if (skipped.usageUnavailable)
270
+ notes.push(text.usageUnavailable(skipped.usageUnavailable));
271
+ if (skipped.overLimit)
272
+ notes.push(text.overLimit(skipped.overLimit, report.limit, exports.MODELS_MAX_LIMIT));
273
+ if (skipped.startedBeforeWindow)
274
+ notes.push(text.startedBefore(skipped.startedBeforeWindow));
275
+ if (skipped.noResponseTime)
276
+ notes.push(text.noResponseTime(skipped.noResponseTime));
277
+ if (groups.length)
278
+ notes.push(i18n_1.COMPARE_TEXT[lang].listPrice, text.sameWork);
279
+ return [...lines, ...(notes.length ? ['', ...notes] : [])].join('\n');
280
+ }
@@ -27,6 +27,8 @@ const openaiRates = (input, cacheRead, cacheWrite, output, sourceUrl, longContex
27
27
  cacheWriteTtl: 'not_tiered', ...(longContext ? { longContext: Object.freeze({ aboveInputTokens: 272_000, inputMultiplier: 2, outputMultiplier: 1.5 }) } : {}) });
28
28
  /** Exact IDs only. Never price an unknown model by a similar family name. */
29
29
  exports.MODEL_PRICING = Object.freeze({
30
+ // Verified 2026-11-13: Fable 5.2 lists at $8 input, $10 and $16 cache writes, $0.20 cache hits (0.025x base input), $40 output; no prompt-length tier.
31
+ 'claude-fable-5-2': Object.freeze({ ...rates(8, 0.2, 10, 16, 40), verifiedAt: '2026-11-13' }),
30
32
  'claude-fable-5-1': rates(10, 0.25, 12.5, 20, 50),
31
33
  'claude-fable-5': rates(10, 1, 12.5, 20, 50),
32
34
  // Verified 2026-09-22: cache hits on Opus 5.5 are 0.05x base input.
@@ -44,7 +44,26 @@ export interface StatusMetrics {
44
44
  resetsAt: number;
45
45
  } | null;
46
46
  }
47
+ /**
48
+ * This machine's memory and disk, already judged by the reader. Display only:
49
+ * memory null hides the part (a system we cannot read), availablePercent null
50
+ * shows it as unknown, disk and swap are present only when they need a look.
51
+ */
52
+ export interface StatusMachine {
53
+ memory?: {
54
+ availablePercent: number | null;
55
+ level: 'ok' | 'warn' | 'crit' | 'unknown';
56
+ } | null;
57
+ disk?: {
58
+ freeBytes: number;
59
+ level: 'warn' | 'crit';
60
+ } | null;
61
+ swap?: {
62
+ usedBytes: number;
63
+ } | null;
64
+ }
47
65
  export interface StatusInput extends StatusMetrics {
66
+ machine?: StatusMachine | null;
48
67
  burn?: StatusBurn | null;
49
68
  share?: number | null;
50
69
  windows?: UsageWindow[];