@agentguard-run/burn 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,33 @@
1
+ import type { WhyLang } from './i18n';
2
+ interface SimpleText {
3
+ notice: string;
4
+ simple: string;
5
+ detailed: string;
6
+ saved: (mode: string) => string;
7
+ subscription: string;
8
+ metered: string;
9
+ unknown: string;
10
+ fiveHour: string;
11
+ weekly: string;
12
+ unavailable: string;
13
+ used: string;
14
+ reset: string;
15
+ left: string;
16
+ paceUnavailable: string;
17
+ today: string;
18
+ pace: string;
19
+ perHour: string;
20
+ dollarsUnavailable: string;
21
+ reported: string;
22
+ next: string;
23
+ live: string;
24
+ recorded: string;
25
+ controls: string;
26
+ replayUnavailable: string;
27
+ replayCaution: string;
28
+ helpers: (count: number, names: string) => string;
29
+ replay: (command: string, percent: string, days: number) => string;
30
+ steps: Record<'subagents' | 'reloads' | 'conversation' | 'setup' | 'model_switch' | 'idle_ttl_expired' | 'stopped', string>;
31
+ }
32
+ export declare const SIMPLE_TEXT: Record<WhyLang, SimpleText>;
33
+ export {};
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SIMPLE_TEXT = void 0;
4
+ exports.SIMPLE_TEXT = {
5
+ en: {
6
+ notice: 'Showing the simple view. For tokens and cache detail: agentguard-burn mode detailed',
7
+ simple: 'simple', detailed: 'detailed', saved: mode => `Saved ${mode} view.`,
8
+ subscription: 'Subscription', metered: 'API or usage credits', unknown: 'Billing not available',
9
+ fiveHour: '5-hour', weekly: 'Weekly', unavailable: 'limit not available', used: 'used', reset: 'resets in', left: 'left at this pace', paceUnavailable: 'time left not available',
10
+ today: 'Spent today', pace: 'At this pace', perHour: 'per hour', dollarsUnavailable: 'spending not available', reported: 'Host-reported USD from today’s recorded sessions', next: 'Next',
11
+ live: 'LIVE', recorded: 'RECORDED', controls: 'p pause | q quit',
12
+ helpers: (count, names) => `Helpers: ${count}${names ? ` (${names})` : ''}`,
13
+ replayUnavailable: 'There is not enough evidence to suggest a smaller window.',
14
+ replayCaution: 'This estimates recorded work, not plan-limit savings. Shorter memory can lose context and change answers.',
15
+ replay: (command, percent, days) => `${command} would have used about ${percent}% less over the last ${days} days (estimate).`,
16
+ steps: { subagents: 'Give related work to one helper instead of several.', reloads: 'Start a fresh session with a short handoff note.', conversation: 'Start a fresh session with a short handoff note.', setup: 'Keep CLAUDE.md short and disable unused tools.', model_switch: 'Keep one model for this task.', idle_ttl_expired: 'Group related requests into one work period.', stopped: 'Finish an active helper before starting another.' },
17
+ },
18
+ es: {
19
+ notice: 'Mostrando la vista simple. Para ver tokens y detalles de caché: agentguard-burn mode detailed',
20
+ simple: 'simple', detailed: 'detallada', saved: mode => `Vista ${mode} guardada.`,
21
+ subscription: 'Suscripción', metered: 'API o créditos de uso', unknown: 'Facturación no disponible',
22
+ fiveHour: '5 horas', weekly: 'Semanal', unavailable: 'límite no disponible', used: 'usado', reset: 'se reinicia en', left: 'restantes a este ritmo', paceUnavailable: 'tiempo restante no disponible',
23
+ today: 'Gastado hoy', pace: 'A este ritmo', perHour: 'por hora', dollarsUnavailable: 'gasto no disponible', reported: 'USD informados por el servicio en las sesiones registradas hoy', next: 'Próximo paso',
24
+ live: 'EN VIVO', recorded: 'GRABADO', controls: 'p pausa | q salir',
25
+ helpers: (count, names) => `Ayudantes: ${count}${names ? ` (${names})` : ''}`,
26
+ replayUnavailable: 'No hay datos suficientes para sugerir una ventana menor.',
27
+ replayCaution: 'Estima el trabajo registrado, no el ahorro del límite del plan. Menos memoria puede perder contexto y cambiar las respuestas.',
28
+ replay: (command, percent, days) => `${command} habría usado cerca de ${percent}% menos en los últimos ${days} días (estimación).`,
29
+ steps: { subagents: 'Asigna el trabajo relacionado a un solo ayudante.', reloads: 'Inicia una sesión nueva con una breve nota de continuidad.', conversation: 'Inicia una sesión nueva con una breve nota de continuidad.', setup: 'Mantén CLAUDE.md corto y desactiva las herramientas sin uso.', model_switch: 'Mantén un solo modelo para esta tarea.', idle_ttl_expired: 'Agrupa las solicitudes relacionadas en un período de trabajo.', stopped: 'Termina un ayudante activo antes de iniciar otro.' },
30
+ },
31
+ pt: {
32
+ notice: 'Mostrando a visão simples. Para ver tokens e detalhes de cache: agentguard-burn mode detailed',
33
+ simple: 'simples', detailed: 'detalhada', saved: mode => `Visão ${mode} salva.`,
34
+ subscription: 'Assinatura', metered: 'API ou créditos de uso', unknown: 'Cobrança indisponível',
35
+ fiveHour: '5 horas', weekly: 'Semanal', unavailable: 'limite não disponível', used: 'usado', reset: 'renova em', left: 'restantes neste ritmo', paceUnavailable: 'tempo restante indisponível',
36
+ today: 'Gasto hoje', pace: 'Neste ritmo', perHour: 'por hora', dollarsUnavailable: 'gasto indisponível', reported: 'USD informados pelo serviço nas sessões registradas hoje', next: 'Próximo passo',
37
+ live: 'AO VIVO', recorded: 'GRAVADO', controls: 'p pausar | q sair',
38
+ helpers: (count, names) => `Ajudantes: ${count}${names ? ` (${names})` : ''}`,
39
+ replayUnavailable: 'Não há dados suficientes para sugerir uma janela menor.',
40
+ replayCaution: 'Estima o trabalho registrado, não a economia do limite do plano. Menos memória pode perder contexto e mudar as respostas.',
41
+ replay: (command, percent, days) => `${command} teria usado cerca de ${percent}% menos nos últimos ${days} dias (estimativa).`,
42
+ steps: { subagents: 'Dê o trabalho relacionado a um só ajudante.', reloads: 'Inicie uma sessão nova com uma breve nota de continuidade.', conversation: 'Inicie uma sessão nova com uma breve nota de continuidade.', setup: 'Mantenha CLAUDE.md curto e desative as ferramentas sem uso.', model_switch: 'Mantenha um modelo para esta tarefa.', idle_ttl_expired: 'Agrupe pedidos relacionados em um período de trabalho.', stopped: 'Termine um ajudante ativo antes de iniciar outro.' },
43
+ },
44
+ };
@@ -67,8 +67,8 @@ export declare function formatStatusFields(input: StatusInput): {
67
67
  text: string;
68
68
  parts: StatusPart[];
69
69
  panel: string[];
70
- enabled: ("pace" | "spend" | "cost" | "cache")[];
70
+ enabled: ("spend" | "pace" | "cost" | "cache")[];
71
71
  unknown: string[];
72
- dropped: ("pace" | "spend" | "cost" | "cache")[];
72
+ dropped: ("spend" | "pace" | "cost" | "cache")[];
73
73
  clipped: boolean;
74
74
  };
@@ -0,0 +1,4 @@
1
+ import { type WhyLang } from './i18n';
2
+ import { type WeekReport } from './week';
3
+ /** Only fixed text, dates and figures appear in the weekly view. */
4
+ export declare function renderWeek(report: WeekReport, lang?: WhyLang): string;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.renderWeek = renderWeek;
4
+ const version_1 = require("../version");
5
+ const i18n_1 = require("./i18n");
6
+ const render_1 = require("./render");
7
+ const week_1 = require("./week");
8
+ /** Only fixed text, dates and figures appear in the weekly view. */
9
+ function renderWeek(report, lang = 'en') {
10
+ const text = i18n_1.WEEK_TEXT[lang], f = report.figures;
11
+ const priced = f.usdMicros.total !== null;
12
+ const total = priced ? f.usdMicros.total : f.tokens.total;
13
+ const dollar = (micros) => `$${(micros / 1_000_000).toFixed(2)}`;
14
+ const end = new Date(Date.parse(report.weekEnd) - 86_400_000).toISOString().slice(0, 10);
15
+ const shares = priced ? f.usdMicros : f.tokens;
16
+ return [
17
+ `Burn ${version_1.BURN_VERSION} | ${text.title(report.weekStart, end)}`,
18
+ text.summary((0, render_1.count)(f.tokens.total), priced ? dollar(f.usdMicros.total) : null),
19
+ ...(priced ? [text.spent(dollar(f.usdMicros.waste))] : [text.tokenBasis]),
20
+ text.shares((0, render_1.share)(shares.useful, total), (0, render_1.share)(shares.waste, total), (0, render_1.share)(shares.unattributed, total), priced),
21
+ ...week_1.WEEK_CAUSES.map(cause => {
22
+ const row = f.causes[cause];
23
+ return text.row(text.labels[cause], (0, render_1.share)(priced ? row.usdMicros : row.tokens, total), priced ? dollar(row.usdMicros) : null, (0, render_1.count)(row.tokens));
24
+ }),
25
+ ...(priced && f.wrongModel.tokens > 0 ? [text.wrongModel((0, render_1.count)(f.wrongModel.tokens), dollar(f.wrongModel.usdMicros - f.wrongModel.smallerUsdMicros))] : []),
26
+ f.topCause === null ? text.noCause : text.next(text.labels[f.topCause], text.fixes[f.topCause]),
27
+ ...(!report.complete ? [text.incomplete] : []),
28
+ ...(report.local.excludedForkSessions || report.local.undatedTokens ? [text.excluded((0, render_1.count)(report.local.excludedForkSessions), (0, render_1.count)(report.local.undatedTokens))] : []),
29
+ text.privacy,
30
+ ].join('\n');
31
+ }
@@ -0,0 +1,75 @@
1
+ import { type PricingTable } from './pricing';
2
+ import { transcriptRoots } from './sessions';
3
+ export declare const WEEK_SCHEMA = "agentguard.burn-week.v1";
4
+ export declare const SMALLER_MODEL = "claude-haiku-5-5";
5
+ export declare const WEEK_CAUSES: readonly ["history_resent", "reread_files", "subagent_fanout", "reloads"];
6
+ export declare const RELOAD_GROUPS: readonly ["idle", "model_switch", "other"];
7
+ export type WeekCause = typeof WEEK_CAUSES[number];
8
+ export type WeekTopCause = WeekCause | 'wrong_model' | 'reloads_idle' | 'reloads_model_switch';
9
+ export interface WeekAmount {
10
+ tokens: number;
11
+ usdMicros: number | null;
12
+ }
13
+ export interface WeekFigures {
14
+ tokens: {
15
+ total: number;
16
+ useful: number;
17
+ waste: number;
18
+ unattributed: number;
19
+ };
20
+ usdMicros: {
21
+ total: number | null;
22
+ useful: number | null;
23
+ waste: number | null;
24
+ unattributed: number | null;
25
+ };
26
+ causes: Record<WeekCause, WeekAmount>;
27
+ reloadsByCause: Record<typeof RELOAD_GROUPS[number], WeekAmount>;
28
+ subagentTokens: number;
29
+ wrongModel: WeekAmount & {
30
+ smallerUsdMicros: number | null;
31
+ };
32
+ topCause: WeekTopCause | null;
33
+ basis: 'estimated_api_list_price';
34
+ }
35
+ export interface WeekReport {
36
+ weekStart: string;
37
+ /** Exclusive Monday boundary, in UTC. */
38
+ weekEnd: string;
39
+ complete: boolean;
40
+ figures: WeekFigures;
41
+ /** Diagnostics stay on this machine, outside the saved file and upload. */
42
+ local: {
43
+ sessions: number;
44
+ excludedForkSessions: number;
45
+ undatedTokens: number;
46
+ unpricedModels: Array<string | null>;
47
+ };
48
+ }
49
+ export interface BurnWeekFile {
50
+ schema: typeof WEEK_SCHEMA;
51
+ weekStart: string;
52
+ viewedAt: string;
53
+ figures: WeekFigures;
54
+ }
55
+ export interface CollectWeekOptions {
56
+ weekStart?: string;
57
+ now?: number;
58
+ home?: string;
59
+ roots?: ReturnType<typeof transcriptRoots>;
60
+ rates?: PricingTable;
61
+ }
62
+ export interface SaveWeekResult {
63
+ saved: boolean;
64
+ reason: 'incomplete' | 'too_old' | 'empty' | 'write_failed' | null;
65
+ }
66
+ export declare function weekStartOf(ms: number): string;
67
+ export declare const lastCompletedWeekStart: (now?: number) => string;
68
+ export declare function isMonday(date: unknown): date is string;
69
+ /** Contract constants and tie order are copied in the plugin's weekly validator. */
70
+ export declare function topWeekCause(figures: WeekFigures): WeekTopCause | null;
71
+ /** Strict content-free contract: unknown keys and inconsistent arithmetic are errors. */
72
+ export declare function weekFigures(value: unknown): WeekFigures;
73
+ export declare function collectWeek({ weekStart, now, home, roots, rates }?: CollectWeekOptions): WeekReport;
74
+ /** Call only after this exact report has been displayed successfully. */
75
+ export declare function saveWeek(home: string, report: WeekReport, now?: number): SaveWeekResult;
@@ -0,0 +1,253 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.lastCompletedWeekStart = exports.RELOAD_GROUPS = exports.WEEK_CAUSES = exports.SMALLER_MODEL = exports.WEEK_SCHEMA = void 0;
4
+ exports.weekStartOf = weekStartOf;
5
+ exports.isMonday = isMonday;
6
+ exports.topWeekCause = topWeekCause;
7
+ exports.weekFigures = weekFigures;
8
+ exports.collectWeek = collectWeek;
9
+ exports.saveWeek = saveWeek;
10
+ const node_crypto_1 = require("node:crypto");
11
+ const node_fs_1 = require("node:fs");
12
+ const node_path_1 = require("node:path");
13
+ const node_os_1 = require("node:os");
14
+ const pre_tool_use_1 = require("../hook/pre-tool-use");
15
+ const attribution_1 = require("./attribution");
16
+ const live_1 = require("./live");
17
+ const pricing_1 = require("./pricing");
18
+ const render_1 = require("./render");
19
+ const sessions_1 = require("./sessions");
20
+ const transcript_1 = require("./transcript");
21
+ const types_1 = require("./types");
22
+ exports.WEEK_SCHEMA = 'agentguard.burn-week.v1';
23
+ exports.SMALLER_MODEL = 'claude-haiku-5-5';
24
+ const DAY = 86_400_000, WEEK = 7 * DAY;
25
+ exports.WEEK_CAUSES = ['history_resent', 'reread_files', 'subagent_fanout', 'reloads'];
26
+ exports.RELOAD_GROUPS = ['idle', 'model_switch', 'other'];
27
+ function weekStartOf(ms) {
28
+ const date = new Date(ms);
29
+ date.setUTCHours(0, 0, 0, 0);
30
+ date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 6) % 7);
31
+ return date.toISOString().slice(0, 10);
32
+ }
33
+ const lastCompletedWeekStart = (now = Date.now()) => weekStartOf(Date.parse(weekStartOf(now)) - WEEK);
34
+ exports.lastCompletedWeekStart = lastCompletedWeekStart;
35
+ function isMonday(date) {
36
+ if (typeof date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(date))
37
+ return false;
38
+ const at = Date.parse(date + 'T00:00:00.000Z');
39
+ return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === date && new Date(at).getUTCDay() === 1;
40
+ }
41
+ /** Contract constants and tie order are copied in the plugin's weekly validator. */
42
+ function topWeekCause(figures) {
43
+ const { tokens, usdMicros, causes, wrongModel, subagentTokens, reloadsByCause } = figures;
44
+ if (!tokens.total)
45
+ return null;
46
+ const priced = usdMicros.total !== null;
47
+ const size = (amount) => priced ? amount.usdMicros : amount.tokens;
48
+ const candidates = [
49
+ ['subagent_fanout', causes.subagent_fanout.tokens * 100 >= tokens.total * 20],
50
+ ['reloads', priced && usdMicros.total > 0 && causes.reloads.usdMicros * 100 >= usdMicros.total * 15],
51
+ ['history_resent', causes.history_resent.tokens * 100 >= tokens.total * 30],
52
+ ['reread_files', causes.reread_files.tokens * 100 >= tokens.total * 10],
53
+ ];
54
+ let winner = null;
55
+ for (const [cause, eligible] of candidates)
56
+ if (eligible && (winner === null || size(causes[cause]) > size(causes[winner])))
57
+ winner = cause;
58
+ if (winner === 'subagent_fanout' && subagentTokens > 0 && wrongModel.tokens * 2 >= subagentTokens)
59
+ return 'wrong_model';
60
+ if (winner === 'reloads') {
61
+ let group = 'idle';
62
+ for (const candidate of exports.RELOAD_GROUPS)
63
+ if (size(reloadsByCause[candidate]) > size(reloadsByCause[group]))
64
+ group = candidate;
65
+ if (group !== 'other')
66
+ return group === 'idle' ? 'reloads_idle' : 'reloads_model_switch';
67
+ }
68
+ return winner;
69
+ }
70
+ /** Strict content-free contract: unknown keys and inconsistent arithmetic are errors. */
71
+ function weekFigures(value) {
72
+ const fail = () => { throw new Error('Invalid weekly figures.'); };
73
+ const exact = (v, keys) => {
74
+ if (!v || typeof v !== 'object' || Array.isArray(v) || Object.keys(v).length !== keys.length || !keys.every(k => Object.hasOwn(v, k)))
75
+ return fail();
76
+ return v;
77
+ };
78
+ const integer = (n) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0 && n <= 1e13;
79
+ const groups = ['total', 'useful', 'waste', 'unattributed'];
80
+ const row = exact(value, ['tokens', 'usdMicros', 'causes', 'reloadsByCause', 'subagentTokens', 'wrongModel', 'topCause', 'basis']);
81
+ const tokens = exact(row.tokens, groups), usd = exact(row.usdMicros, groups);
82
+ const causes = exact(row.causes, exports.WEEK_CAUSES), reloads = exact(row.reloadsByCause, exports.RELOAD_GROUPS);
83
+ const amounts = [...Object.values(causes), ...Object.values(reloads)].map(v => exact(v, ['tokens', 'usdMicros']));
84
+ const wrong = exact(row.wrongModel, ['tokens', 'usdMicros', 'smallerUsdMicros']);
85
+ if (![...Object.values(tokens), ...amounts.map(v => v.tokens), row.subagentTokens, wrong.tokens].every(integer))
86
+ return fail();
87
+ const dollars = [...Object.values(usd), ...amounts.map(v => v.usdMicros), wrong.usdMicros, wrong.smallerUsdMicros];
88
+ if (!(dollars.every(v => v === null) || dollars.every(integer)))
89
+ return fail();
90
+ const f = value;
91
+ if (f.basis !== 'estimated_api_list_price' || f.wrongModel.tokens > f.subagentTokens || f.subagentTokens > f.tokens.total)
92
+ return fail();
93
+ if (f.tokens.total !== f.tokens.useful + f.tokens.waste + f.tokens.unattributed
94
+ || f.tokens.waste !== exports.WEEK_CAUSES.reduce((n, k) => n + f.causes[k].tokens, 0)
95
+ || f.causes.reloads.tokens !== exports.RELOAD_GROUPS.reduce((n, k) => n + f.reloadsByCause[k].tokens, 0))
96
+ return fail();
97
+ if (f.usdMicros.total !== null && (f.usdMicros.total !== f.usdMicros.useful + f.usdMicros.waste + f.usdMicros.unattributed
98
+ || f.usdMicros.waste !== exports.WEEK_CAUSES.reduce((n, k) => n + f.causes[k].usdMicros, 0)
99
+ || f.causes.reloads.usdMicros !== exports.RELOAD_GROUPS.reduce((n, k) => n + f.reloadsByCause[k].usdMicros, 0)
100
+ || f.wrongModel.smallerUsdMicros > f.wrongModel.usdMicros))
101
+ return fail();
102
+ if (f.topCause !== topWeekCause(f))
103
+ return fail();
104
+ return f;
105
+ }
106
+ function collectWeek({ weekStart, now = Date.now(), home = process.env.AGENTGUARD_HOME || (0, node_path_1.join)((0, node_os_1.homedir)(), '.agentguard'), roots = (0, sessions_1.transcriptRoots)(), rates } = {}) {
107
+ weekStart ??= (0, exports.lastCompletedWeekStart)(now);
108
+ if (!isMonday(weekStart))
109
+ throw new Error('The week must start on a Monday in UTC.');
110
+ rates ??= (0, live_1.readPricing)(home, (0, pre_tool_use_1.loadPolicy)(home));
111
+ const start = Date.parse(weekStart), end = start + WEEK;
112
+ const local = { sessions: 0, excludedForkSessions: 0, undatedTokens: 0, unpricedModels: [] };
113
+ const locations = (0, sessions_1.discoverInsightTranscripts)(roots);
114
+ const childrenModified = new Map();
115
+ for (const location of locations)
116
+ if (location.host === 'claude' && (0, sessions_1.isSubagentTranscript)(location)) {
117
+ const directory = (0, node_path_1.dirname)(location.path);
118
+ childrenModified.set(directory, Math.max(childrenModified.get(directory) ?? 0, location.modifiedAt));
119
+ }
120
+ const transcripts = [];
121
+ for (const location of locations) {
122
+ if (location.host === 'claude' && ((0, sessions_1.isSubagentTranscript)(location) || (0, sessions_1.isSessionSidecar)(location)))
123
+ continue;
124
+ if (Math.max(location.modifiedAt, childrenModified.get((0, node_path_1.join)(location.path.replace(/\.jsonl$/, ''), 'subagents')) ?? 0) < start)
125
+ continue;
126
+ const transcript = (location.host === 'claude' ? transcript_1.readInsightSession : transcript_1.readInsightTranscript)(location.path, { host: location.host }, { chunkBytes: 16 * 1024 * 1024 });
127
+ if (transcript.state.forkHistoryBoundaryUnknown) {
128
+ local.excludedForkSessions++;
129
+ continue;
130
+ }
131
+ local.sessions++;
132
+ transcripts.push(transcript);
133
+ }
134
+ // Equal-time copies should retain the transcript with the earlier history,
135
+ // whose prefix baseline exists, before a fork that starts with the copied turn.
136
+ const firstTime = (t) => t.turns.reduce((first, turn) => Math.min(first, turn.at ?? Infinity), Infinity);
137
+ transcripts.sort((a, b) => firstTime(a) - firstTime(b) || b.turns.length - a.turns.length);
138
+ const turns = (0, transcript_1.deduplicateTurns)(transcripts.flatMap(t => t.turns)).sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
139
+ // Attribute complete histories before filtering, preserving each session's prefix baseline.
140
+ const attribution = (0, attribution_1.attributeTurns)(turns);
141
+ const inside = (turn) => turn.at !== undefined && turn.at >= start && turn.at < end;
142
+ const window = turns.filter(inside), ids = new Set(window.map(t => t.id));
143
+ local.undatedTokens = turns.filter(t => t.at === undefined).reduce((sum, t) => sum + (0, render_1.totalTokens)(t), 0);
144
+ local.unpricedModels = [...new Set(window.filter(t => (0, pricing_1.priceTurn)(t, rates).usd === null).map(t => t.model ?? null))].sort();
145
+ let priced = local.unpricedModels.length === 0;
146
+ const buckets = new Map(types_1.INSIGHT_BUCKETS.map(b => [b, { tokens: 0, usd: 0 }]));
147
+ const windowById = new Map(window.map(t => [t.id, t]));
148
+ const rewrites = attribution.rewrites.filter(r => ids.has(r.turnId));
149
+ const rewriteGroup = (cause) => cause === 'idle_ttl_expired' ? 'idle' : cause === 'model_switch' ? 'model_switch' : 'other';
150
+ const reloads = { idle: { tokens: 0, usd: 0 }, model_switch: { tokens: 0, usd: 0 }, other: { tokens: 0, usd: 0 } };
151
+ const rewriteById = new Map(rewrites.map(r => [r.turnId, rewriteGroup(r.cause)]));
152
+ for (const allocation of attribution.turnAttributions) {
153
+ const turn = windowById.get(allocation.turnId);
154
+ if (!turn)
155
+ continue;
156
+ for (const bucket of allocation.buckets) {
157
+ const target = buckets.get(bucket.bucket);
158
+ target.tokens += bucket.tokens;
159
+ const price = (0, render_1.bucketPrice)(turn, bucket, rates);
160
+ if (price === null)
161
+ priced = false;
162
+ else
163
+ target.usd += (price.min + price.max) / 2;
164
+ if (bucket.bucket === 'full_prefix_rewrites')
165
+ reloads[rewriteById.get(turn.id) ?? 'other'].tokens += bucket.tokens;
166
+ }
167
+ }
168
+ for (const [cause, row] of (0, render_1.rewriteCausePrices)(window, rewrites, rates))
169
+ reloads[rewriteGroup(cause)].usd += row.usd;
170
+ // The overlay uses each stored child's dominant model, as the existing coach does.
171
+ const wrongIds = new Set();
172
+ const owned = new Map(turns.map(t => [t.id, t]));
173
+ for (const transcript of transcripts) {
174
+ const own = transcript.turns.map(t => owned.get(t.id)).filter((t, i) => t.sessionId === transcript.turns[i].sessionId);
175
+ const mainModel = (0, render_1.dominantModel)(own.filter(t => !t.subagent));
176
+ if (!mainModel || !render_1.HAS_SMALLER_MODEL.test(mainModel))
177
+ continue;
178
+ const children = new Map();
179
+ for (const turn of own)
180
+ if (turn.subagent) {
181
+ const child = children.get(turn.sessionId) ?? [];
182
+ child.push(turn);
183
+ children.set(turn.sessionId, child);
184
+ }
185
+ for (const child of children.values())
186
+ if ((0, render_1.dominantModel)(child) === mainModel)
187
+ for (const turn of child)
188
+ wrongIds.add(turn.id);
189
+ }
190
+ let wrongTokens = 0, wrongUsd = 0, smallerUsd = 0;
191
+ for (const turn of window)
192
+ if (turn.subagent && wrongIds.has(turn.id)) {
193
+ wrongTokens += (0, render_1.totalTokens)(turn);
194
+ const actual = (0, pricing_1.priceTurn)(turn, rates).usd, smaller = (0, pricing_1.priceTurn)({ ...turn, model: exports.SMALLER_MODEL }, rates).usd;
195
+ if (actual === null || smaller === null)
196
+ priced = false;
197
+ else {
198
+ wrongUsd += (actual.min + actual.max) / 2;
199
+ smallerUsd += (smaller.min + smaller.max) / 2;
200
+ }
201
+ }
202
+ const micros = (usd) => priced ? Math.round(usd * 1_000_000) : null;
203
+ const amount = (row) => ({ tokens: row.tokens, usdMicros: micros(row.usd) });
204
+ const reloadsByCause = Object.fromEntries(exports.RELOAD_GROUPS.map(k => [k, amount(reloads[k])]));
205
+ const causes = Object.fromEntries(exports.WEEK_CAUSES.map(k => [k, amount(buckets.get(k === 'reloads' ? 'full_prefix_rewrites' : k))]));
206
+ // Leaf buckets round once. Every containing total is a sum of those rounded leaves.
207
+ causes.reloads.usdMicros = priced ? exports.RELOAD_GROUPS.reduce((n, k) => n + reloadsByCause[k].usdMicros, 0) : null;
208
+ const useful = ['instruction_stack', 'tool_output', 'conversation', 'output'];
209
+ const tokens = { total: 0, useful: useful.reduce((n, k) => n + buckets.get(k).tokens, 0), waste: exports.WEEK_CAUSES.reduce((n, k) => n + causes[k].tokens, 0), unattributed: buckets.get('unattributed').tokens };
210
+ tokens.total = tokens.useful + tokens.waste + tokens.unattributed;
211
+ const usdMicros = { total: null, useful: null, waste: null, unattributed: null };
212
+ if (priced) {
213
+ usdMicros.useful = useful.reduce((n, k) => n + micros(buckets.get(k).usd), 0);
214
+ usdMicros.waste = exports.WEEK_CAUSES.reduce((n, k) => n + causes[k].usdMicros, 0);
215
+ usdMicros.unattributed = micros(buckets.get('unattributed').usd);
216
+ usdMicros.total = usdMicros.useful + usdMicros.waste + usdMicros.unattributed;
217
+ }
218
+ const figures = { tokens, usdMicros, causes, reloadsByCause,
219
+ subagentTokens: window.filter(t => t.subagent).reduce((n, t) => n + (0, render_1.totalTokens)(t), 0),
220
+ wrongModel: { tokens: wrongTokens, usdMicros: micros(wrongUsd), smallerUsdMicros: micros(smallerUsd) }, topCause: null, basis: 'estimated_api_list_price' };
221
+ figures.topCause = topWeekCause(figures);
222
+ return { weekStart, weekEnd: new Date(end).toISOString().slice(0, 10), complete: end <= now, figures: weekFigures(figures), local };
223
+ }
224
+ /** Call only after this exact report has been displayed successfully. */
225
+ function saveWeek(home, report, now = Date.now()) {
226
+ if (!isMonday(report.weekStart))
227
+ throw new Error('The week must start on a Monday in UTC.');
228
+ const start = Date.parse(report.weekStart);
229
+ if (!report.complete || start + WEEK > now)
230
+ return { saved: false, reason: 'incomplete' };
231
+ if (now - start > 28 * DAY)
232
+ return { saved: false, reason: 'too_old' };
233
+ const figures = weekFigures(report.figures);
234
+ if (!figures.tokens.total)
235
+ return { saved: false, reason: 'empty' };
236
+ const directory = (0, node_path_1.join)(home, 'week'), file = (0, node_path_1.join)(directory, `${report.weekStart}.json`);
237
+ const temporary = `${file}.${process.pid}.${(0, node_crypto_1.randomUUID)()}.tmp`;
238
+ const value = { schema: exports.WEEK_SCHEMA, weekStart: report.weekStart, viewedAt: new Date(now).toISOString(), figures };
239
+ try {
240
+ (0, node_fs_1.mkdirSync)(directory, { recursive: true, mode: 0o700 });
241
+ (0, node_fs_1.chmodSync)(directory, 0o700);
242
+ (0, node_fs_1.writeFileSync)(temporary, JSON.stringify(value) + '\n', { mode: 0o600, flag: 'wx' });
243
+ (0, node_fs_1.renameSync)(temporary, file);
244
+ return { saved: true, reason: null };
245
+ }
246
+ catch {
247
+ try {
248
+ (0, node_fs_1.unlinkSync)(temporary);
249
+ }
250
+ catch { /* no temporary file */ }
251
+ return { saved: false, reason: 'write_failed' };
252
+ }
253
+ }
@@ -1,6 +1,7 @@
1
1
  import { Canvas, type CanvasColor } from './canvas';
2
2
  import type { FrameOptions } from './frames';
3
3
  import type { BurnReport, Verdict } from './types';
4
+ import type { DisplayMode } from './display-mode';
4
5
  export interface PanelDecision {
5
6
  id: string;
6
7
  at: number;
@@ -55,4 +56,4 @@ export declare class StopHold {
55
56
  private latest?;
56
57
  update(snapshot: LivePanelSnapshot, now: number): LivePanelSnapshot;
57
58
  }
58
- export declare function runLivePanel(home: string, args: string[]): Promise<number>;
59
+ export declare function runLivePanel(home: string, args: string[], mode?: DisplayMode): Promise<number>;
@@ -15,6 +15,11 @@ const node_fs_1 = require("node:fs");
15
15
  const canvas_1 = require("./canvas");
16
16
  const ledger_panel_1 = require("./ledger-panel");
17
17
  const recording_1 = require("./recording");
18
+ const sessions_1 = require("./insights/sessions");
19
+ const simple_data_1 = require("./insights/simple-data");
20
+ const simple_render_1 = require("./insights/simple-render");
21
+ const i18n_1 = require("./insights/i18n");
22
+ const upgrade_moments_1 = require("./upgrade-moments");
18
23
  const digest = (text) => (0, node_crypto_1.createHash)('sha256').update(text).digest('hex');
19
24
  /** The ledger is the single source for decisions, counters and session selection. */
20
25
  function panelDecisions(home, sessionId, at = Date.now()) {
@@ -236,7 +241,7 @@ class StopHold {
236
241
  }
237
242
  }
238
243
  exports.StopHold = StopHold;
239
- async function runLivePanel(home, args) {
244
+ async function runLivePanel(home, args, mode = 'detailed') {
240
245
  const flag = (key) => {
241
246
  const i = args.indexOf(key);
242
247
  if (i < 0)
@@ -246,6 +251,7 @@ async function runLivePanel(home, args) {
246
251
  return args[i + 1];
247
252
  };
248
253
  const replayFile = flag('--replay'), selected = flag('--session');
254
+ const language = (0, i18n_1.detectWhyLang)({ flag: flag('--lang') ?? args.find(arg => arg.startsWith('--lang='))?.slice(7), env: process.env });
249
255
  const once = args.includes('--once') || !process.stdout.isTTY;
250
256
  const colour = !args.includes('--no-color') && process.env.NO_COLOR === undefined && Boolean(process.stdout.isTTY);
251
257
  const viewport = { width: Math.min(104, process.stdout.columns || 104), height: Math.min(35, process.stdout.rows || 35) };
@@ -256,7 +262,28 @@ async function runLivePanel(home, args) {
256
262
  const stop = () => { stopped = true; };
257
263
  const display = (snapshot, recorded, at) => {
258
264
  (0, recording_1.recordFrame)({ kind: 'live', snapshot }, at, viewport);
259
- process.stdout.write((process.stdout.isTTY ? '\x1b[H\x1b[2J' : '') + renderLivePanel(snapshot, { ...viewport, at, recorded, colour }).render() + '\n');
265
+ let panel;
266
+ if (mode === 'simple') {
267
+ let usage = { billing: 'unknown', now: snapshot.observedAt, windows: [], spentTodayUsd: null, paceUsdPerHour: null };
268
+ // Old recordings have no host quota/cost evidence. Do not borrow live data.
269
+ if (!recorded)
270
+ try {
271
+ const locations = (0, sessions_1.discoverInsightTranscripts)();
272
+ const location = selected ? (0, sessions_1.selectInsightTranscript)(selected, locations)
273
+ : snapshot.sessionDigest ? locations.find(item => digest(item.sessionId) === snapshot.sessionDigest)
274
+ : (0, sessions_1.selectInsightTranscript)(undefined, locations);
275
+ if (location)
276
+ usage = (0, simple_data_1.readSimpleUsage)(home, { location, locations, now: snapshot.observedAt });
277
+ }
278
+ catch { /* Missing transcripts leave both limits unavailable. */ }
279
+ const stop = snapshot.stop ?? snapshot.decisions.at(-1);
280
+ const next = !(0, node_fs_1.existsSync)((0, upgrade_moments_1.quietFile)(home)) && stop?.verdict === 'STOP' && /^(spawn_rate|fanout):STOP/.test(stop.reason)
281
+ ? i18n_1.SIMPLE_TEXT[language].steps.stopped : null;
282
+ panel = (0, simple_render_1.renderSimplePanel)(usage, { ...viewport, at, recorded, colour, lang: language, next });
283
+ }
284
+ else
285
+ panel = renderLivePanel(snapshot, { ...viewport, at, recorded, colour });
286
+ process.stdout.write((process.stdout.isTTY ? '\x1b[H\x1b[2J' : '') + panel.render() + '\n');
260
287
  };
261
288
  const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
262
289
  const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
@@ -4,7 +4,7 @@ Branches: `burn/launch-tree-tally-oct5` in the monorepo and `site/team-view-oct5
4
4
 
5
5
  ## Feature 1: real local launch tree
6
6
 
7
- Actual command: `node dist/src/cli.js tree /Users/soccer/.claude/projects/-Users-soccer/321cfac5-66b0-4e36-ada5-01dcf3f0ba17.jsonl`.
7
+ Actual command: `node dist/src/cli.js tree ~/.claude/projects/<project>/<session>.jsonl`.
8
8
 
9
9
  ```text
10
10
  Launch tree
@@ -0,0 +1,17 @@
1
+ ## Simple and detailed views
2
+
3
+ `statusline`, `why` and `live` start in simple mode. `compact-replay` starts detailed, because its table is the answer; a flag, the environment or a saved `mode simple` preference switches it. Save your preference with `agentguard-burn mode simple` or `agentguard-burn mode detailed`. Burn stores `displayMode` in `burn-config.json` inside `AGENTGUARD_HOME`, normally `~/.agentguard`. `AGENTGUARD_BURN_MODE=simple` or `detailed` overrides that setting. The per-command flags named `simple` and `detailed`, each prefixed by two hyphens, override both. Passing both flags is an error. Detailed mode preserves the previous reports. JSON is byte-identical across modes and does not consume the first-use notice.
4
+
5
+ Simple subscription views show the host's 5-hour and weekly percentages, reset times and remaining time at the observed pace. Without fresh host evidence they say "limit not available". They never show dollars. Remaining time needs two rising observations from the same host pool and reset period; Burn never converts recorded work into plan-limit points. A single fresh observation can show a percentage and reset time, with remaining time unavailable.
6
+
7
+ For explicitly identified API or usage-credit sessions, simple views total host-reported USD in today's local transcripts for that host. They use recorded `costUSD`, or a fresh statusline `cost.total_cost_usd` when the recorded session began today. Missing billing identity, missing amounts, incomplete history and sessions crossing midnight without daily amounts stay unavailable. Burn does not substitute API list prices. Next to today's total, simple views show the last ten minutes' reported dollar pace per hour. Burn never extends that pace into a day total: a short burst is not a forecast. These are locally recorded amounts, not an invoice fetched from the provider. Only numerical host observations and the billing category are saved under `display-observations`; no credentials or message content are read from account files or saved.
8
+
9
+ There is at most one next step, selected from Burn's existing findings. A reliable replay can suggest a smaller window; its percentage describes estimated recorded work, never plan-limit savings. English, Spanish and Portuguese use the existing language preference and language flag. On their first simple view, existing users see one line on stderr: "Showing the simple view. For tokens and cache detail: agentguard-burn mode detailed". That requested migration line is the only simple-view exception to the plain vocabulary. The local `simpleViewSeen` marker prevents repetition. Existing recordings lack these host figures, so simple playback leaves them unavailable.
10
+
11
+ ## Evidence and verification
12
+
13
+ Billing categories come from explicit host metadata such as `billing_type`, `billing.type`, `auth_type` or `plan_type`. Claude named plan windows also identify subscription usage. Burn does not infer API billing from a model name, an absent percentage or a credential in the shell. Unknown billing hides dollars. Percentages must be from the past minute; pace uses up to ten minutes of samples with the same pool, duration and reset. Codex quota samples obey the existing transcript ownership checks.
14
+
15
+ Reported per-response amounts are counted once by provider response ID and first observed date. A copied old response stays on its original day. Session totals with overlapping helper or copied history stay unavailable. Today means the local calendar day; a cumulative lifetime total is never split across midnight by guesswork.
16
+
17
+ The existing suite keeps its detailed-output assertions with `AGENTGUARD_BURN_MODE=detailed npm test`. New mode tests clear that preference, use temporary HOME and AGENTGUARD_HOME directories, and forbid real host home reads and network requests. They check the simple default, flag precedence, all four views, translations, dollars and limits, missing evidence, unchanged detailed output and byte-identical JSON. No existing tests are edited.
@@ -0,0 +1 @@
1
+ {"schema":"agentguard.burn-week.v1","weekStart":"2026-09-28","viewedAt":"2026-10-05T09:12:00.000Z","figures":{"tokens":{"total":10000000,"useful":4000000,"waste":5800000,"unattributed":200000},"usdMicros":{"total":18400000,"useful":9000000,"waste":9100000,"unattributed":300000},"causes":{"history_resent":{"tokens":4000000,"usdMicros":4000000},"reread_files":{"tokens":300000,"usdMicros":600000},"subagent_fanout":{"tokens":1200000,"usdMicros":3000000},"reloads":{"tokens":300000,"usdMicros":1500000}},"reloadsByCause":{"idle":{"tokens":200000,"usdMicros":1000000},"model_switch":{"tokens":50000,"usdMicros":250000},"other":{"tokens":50000,"usdMicros":250000}},"subagentTokens":1500000,"wrongModel":{"tokens":1000000,"usdMicros":2400000,"smallerUsdMicros":60000},"topCause":"history_resent","basis":"estimated_api_list_price"}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentguard-run/burn",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Local session usage and runaway-agent circuit breaker. Explain tokens, cache rewrites and API list cost, track pace, warn on heavy turns, and gate agent fan-out with signed receipts. Developer command ranking requires explicit --rank.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://agentguard.run/burn",
@@ -55,7 +55,7 @@
55
55
  },
56
56
  "scripts": {
57
57
  "build": "tsc -p tsconfig.json",
58
- "test": "tsc -p tsconfig.json && node --test \"dist/tests/**/*.test.js\"",
58
+ "test": "tsc -p tsconfig.json && AGENTGUARD_BURN_MODE=detailed node --test \"dist/tests/**/*.test.js\"",
59
59
  "typecheck": "tsc -p tsconfig.json --noEmit",
60
60
  "conformance": "tsc -p tsconfig.json && node dist/src/cli.js conformance",
61
61
  "replay": "node dist/src/cli.js replay"