@agentguard-run/burn 0.5.1 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +78 -1
- package/dist/src/cli.js +150 -4
- package/dist/src/display-mode.d.ts +12 -0
- package/dist/src/display-mode.js +67 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +12 -1
- package/dist/src/insights/compact-replay.d.ts +97 -0
- package/dist/src/insights/compact-replay.js +414 -0
- package/dist/src/insights/compact-settings.d.ts +30 -0
- package/dist/src/insights/compact-settings.js +122 -0
- package/dist/src/insights/i18n.d.ts +19 -0
- package/dist/src/insights/i18n.js +82 -1
- package/dist/src/insights/render.d.ts +13 -1
- package/dist/src/insights/render.js +32 -19
- package/dist/src/insights/simple-data.d.ts +20 -0
- package/dist/src/insights/simple-data.js +229 -0
- package/dist/src/insights/simple-render.d.ts +26 -0
- package/dist/src/insights/simple-render.js +92 -0
- package/dist/src/insights/simple-text.d.ts +33 -0
- package/dist/src/insights/simple-text.js +44 -0
- package/dist/src/insights/status-fields.d.ts +7 -2
- package/dist/src/insights/status-fields.js +18 -1
- package/dist/src/insights/status-text.d.ts +18 -0
- package/dist/src/insights/status-text.js +6 -0
- package/dist/src/insights/week-render.d.ts +4 -0
- package/dist/src/insights/week-render.js +31 -0
- package/dist/src/insights/week.d.ts +75 -0
- package/dist/src/insights/week.js +253 -0
- package/dist/src/live-panel.d.ts +2 -1
- package/dist/src/live-panel.js +29 -2
- package/docs/OCT5_VERIFICATION.md +1 -1
- package/docs/simple-views.md +17 -0
- package/fixtures/burn-week-v1.json +1 -0
- package/package.json +3 -3
|
@@ -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
|
+
};
|
|
@@ -49,6 +49,11 @@ export interface StatusInput extends StatusMetrics {
|
|
|
49
49
|
share?: number | null;
|
|
50
50
|
windows?: UsageWindow[];
|
|
51
51
|
fields?: string;
|
|
52
|
+
/** The live main-conversation context and the token count where Claude Code auto-compacts. */
|
|
53
|
+
context?: {
|
|
54
|
+
tokens: number;
|
|
55
|
+
threshold: number;
|
|
56
|
+
} | null;
|
|
52
57
|
width?: number;
|
|
53
58
|
lang?: keyof typeof STATUS_TEXT;
|
|
54
59
|
now?: number;
|
|
@@ -67,8 +72,8 @@ export declare function formatStatusFields(input: StatusInput): {
|
|
|
67
72
|
text: string;
|
|
68
73
|
parts: StatusPart[];
|
|
69
74
|
panel: string[];
|
|
70
|
-
enabled: ("
|
|
75
|
+
enabled: ("spend" | "pace" | "cost" | "cache")[];
|
|
71
76
|
unknown: string[];
|
|
72
|
-
dropped: ("
|
|
77
|
+
dropped: ("spend" | "pace" | "cost" | "cache")[];
|
|
73
78
|
clipped: boolean;
|
|
74
79
|
};
|
|
@@ -67,6 +67,9 @@ function formatStatusFields(input) {
|
|
|
67
67
|
const elapsed = (input.now ?? Date.now()) - window.observedAt;
|
|
68
68
|
return elapsed > 60000 ? words.ago.replace('{minutes}', String(Math.floor(elapsed / 60000))) : '';
|
|
69
69
|
};
|
|
70
|
+
const ctx = input.context && Number.isFinite(input.context.tokens) && input.context.tokens >= 0 &&
|
|
71
|
+
Number.isFinite(input.context.threshold) && input.context.threshold > 0 ? input.context : null;
|
|
72
|
+
const left = ctx ? Math.max(0, Math.round(100 - (100 * ctx.tokens) / ctx.threshold)) : null;
|
|
70
73
|
const optional = new Map();
|
|
71
74
|
if (pace !== null)
|
|
72
75
|
optional.set('pace', { text: `${words.limit} ${duration(pace)}`, color: pace < 30 ? 'yellow' : null });
|
|
@@ -92,7 +95,19 @@ function formatStatusFields(input) {
|
|
|
92
95
|
const color = statusColor(win.count, win.limit);
|
|
93
96
|
out.push({ text: ` ${short > 1 ? 'a' : words.agents} ${win.count}${short ? '/' : ` ${words.of} `}${win.limit}`, color, dim: !color });
|
|
94
97
|
const add = (text, extra = {}) => out.push({ text: ` · ${text}`, dim: !extra.color, ...extra });
|
|
95
|
-
|
|
98
|
+
const label = short > 1 ? 't' : words.tokens, limit = statusCount(burn.tokens.limit);
|
|
99
|
+
// A session past its ceiling keeps counting. "24B of 5B" reads as broken, so say what the state is.
|
|
100
|
+
if (burn.tokens.limit > 0 && burn.tokens.used >= burn.tokens.limit) {
|
|
101
|
+
const past = (short ? words.pastShort : words.pastLimit).replace('{limit}', limit);
|
|
102
|
+
add(`${label} ${statusCount(burn.tokens.used)}, ${past}${!short && burn.mode !== 'shadow' ? `: ${words.waits}` : ''}`, { color: 'red' });
|
|
103
|
+
}
|
|
104
|
+
else
|
|
105
|
+
add(`${label} ${statusCount(burn.tokens.used)}${short ? '/' : ` ${words.of} `}${limit}`, { color: statusColor(burn.tokens.used, burn.tokens.limit) });
|
|
106
|
+
if (ctx && left !== null) {
|
|
107
|
+
// The colour follows the number shown, so "30%" is always yellow and "10%" always red.
|
|
108
|
+
const color = left <= 10 ? 'red' : left <= 30 ? 'yellow' : null;
|
|
109
|
+
add(short > 1 ? `ac ${left}%` : `${left}% ${short ? words.compactShort : words.compact}`, color ? { color } : {});
|
|
110
|
+
}
|
|
96
111
|
if (typeof input.share === 'number' && Number.isFinite(input.share))
|
|
97
112
|
add(`${Math.round(input.share)}% ${short ? words.sub : words.share}`);
|
|
98
113
|
if (plan)
|
|
@@ -123,6 +138,8 @@ function formatStatusFields(input) {
|
|
|
123
138
|
const fullText = output.map(part => part.text).join('');
|
|
124
139
|
const text = [...fullText].slice(0, width).join('');
|
|
125
140
|
const panel = [
|
|
141
|
+
...(ctx && left !== null ? [words.contextLine.replace('{used}', Math.round(ctx.tokens).toLocaleString('en-US'))
|
|
142
|
+
.replace('{threshold}', Math.round(ctx.threshold).toLocaleString('en-US')).replace('{left}', String(left))] : []),
|
|
126
143
|
...plans.map(window => `${words.plan} ${Math.round(window.usedPercent)}% (${planName(window)}). ${words.reset} ${Number.isFinite(window.resetsAt) ? new Date(window.resetsAt).toISOString() : words.none}.${age(window) ? ` ${words.lastRead} ${age(window)}.` : ''}`),
|
|
127
144
|
pace !== null ? `${words.limit} ${duration(pace)}.` : words.paceEmpty,
|
|
128
145
|
input.cost ? `${words.costLead} ≈ ${money(input.cost, words.range)} ${words.costFull}.` : words.costEmpty,
|
|
@@ -10,6 +10,12 @@ export declare const STATUS_TEXT: {
|
|
|
10
10
|
share: string;
|
|
11
11
|
sub: string;
|
|
12
12
|
weekly: string;
|
|
13
|
+
pastLimit: string;
|
|
14
|
+
pastShort: string;
|
|
15
|
+
waits: string;
|
|
16
|
+
compact: string;
|
|
17
|
+
compactShort: string;
|
|
18
|
+
contextLine: string;
|
|
13
19
|
limit: string;
|
|
14
20
|
cache: string;
|
|
15
21
|
spend: string;
|
|
@@ -45,6 +51,12 @@ export declare const STATUS_TEXT: {
|
|
|
45
51
|
share: string;
|
|
46
52
|
sub: string;
|
|
47
53
|
weekly: string;
|
|
54
|
+
pastLimit: string;
|
|
55
|
+
pastShort: string;
|
|
56
|
+
waits: string;
|
|
57
|
+
compact: string;
|
|
58
|
+
compactShort: string;
|
|
59
|
+
contextLine: string;
|
|
48
60
|
limit: string;
|
|
49
61
|
cache: string;
|
|
50
62
|
spend: string;
|
|
@@ -80,6 +92,12 @@ export declare const STATUS_TEXT: {
|
|
|
80
92
|
share: string;
|
|
81
93
|
sub: string;
|
|
82
94
|
weekly: string;
|
|
95
|
+
pastLimit: string;
|
|
96
|
+
pastShort: string;
|
|
97
|
+
waits: string;
|
|
98
|
+
compact: string;
|
|
99
|
+
compactShort: string;
|
|
100
|
+
contextLine: string;
|
|
83
101
|
limit: string;
|
|
84
102
|
cache: string;
|
|
85
103
|
spend: string;
|
|
@@ -4,6 +4,8 @@ exports.STATUS_TEXT = void 0;
|
|
|
4
4
|
// Display-only words shared with the Claude mod. No environment or I/O here.
|
|
5
5
|
exports.STATUS_TEXT = {
|
|
6
6
|
en: { ago: '{minutes}m ago', lastRead: 'Last read', range: 'to', fiveHour: '5-hour', agents: 'sub-agents', tokens: 'tokens', of: 'of', share: 'to sub-agents', sub: 'sub', weekly: 'weekly',
|
|
7
|
+
pastLimit: 'past the {limit} limit', pastShort: 'past {limit}', waits: 'sub-agents wait for your yes', compact: 'to auto-compact', compactShort: 'to compact',
|
|
8
|
+
contextLine: 'Context: {used} of {threshold} tokens, {left}% left before Claude Code compacts the conversation.',
|
|
7
9
|
limit: 'limit in', cache: 'cache waste', spend: 'spend', today: 'today', list: 'list', watching: 'watching only',
|
|
8
10
|
unavailable: 'status unavailable', starting: 'starting', costFull: 'at API list price, not a bill',
|
|
9
11
|
paceEmpty: 'Pace needs two rising plan usage samples and a limit reached before reset.',
|
|
@@ -14,6 +16,8 @@ exports.STATUS_TEXT = {
|
|
|
14
16
|
enabled: 'Optional status fields on:', none: 'none', change: 'Change status_fields in the AgentGuard plugin settings, or pass the fields flag to Burn statusline.',
|
|
15
17
|
unknown: 'Ignored unknown status fields:', reset: 'Resets at', plan: 'Plan usage:', hidden: 'Fields hidden to fit this width:' },
|
|
16
18
|
es: { ago: 'hace {minutes}min', lastRead: 'Última lectura', range: 'a', fiveHour: '5 horas', agents: 'subagentes', tokens: 'tokens', of: 'de', share: 'a subagentes', sub: 'sub', weekly: 'semanal',
|
|
19
|
+
pastLimit: 'pasó el límite de {limit}', pastShort: 'pasó {limit}', waits: 'los subagentes esperan tu sí', compact: 'para autocompactar', compactShort: 'hasta compactar',
|
|
20
|
+
contextLine: 'Contexto: {used} de {threshold} tokens, queda {left}% antes de que Claude Code compacte la conversación.',
|
|
17
21
|
limit: 'límite en', cache: 'caché reescrita', spend: 'gasto', today: 'hoy', list: 'lista', watching: 'solo observando',
|
|
18
22
|
unavailable: 'estado no disponible', starting: 'iniciando', costFull: 'a precio de lista de la API, no es una factura',
|
|
19
23
|
paceEmpty: 'El ritmo necesita dos muestras crecientes del plan y alcanzar el límite antes del reinicio.',
|
|
@@ -24,6 +28,8 @@ exports.STATUS_TEXT = {
|
|
|
24
28
|
enabled: 'Campos opcionales activos:', none: 'ninguno', change: 'Cambia status_fields en los ajustes del plugin AgentGuard o pasa la opción fields a Burn statusline.',
|
|
25
29
|
unknown: 'Campos de estado desconocidos ignorados:', reset: 'Se reinicia a las', plan: 'Uso del plan:', hidden: 'Campos ocultos para caber en este ancho:' },
|
|
26
30
|
pt: { ago: 'há {minutes}min', lastRead: 'Última leitura', range: 'a', fiveHour: '5 horas', agents: 'subagentes', tokens: 'tokens', of: 'de', share: 'para subagentes', sub: 'sub', weekly: 'semanal',
|
|
31
|
+
pastLimit: 'passou do limite de {limit}', pastShort: 'passou {limit}', waits: 'subagentes esperam seu sim', compact: 'até autocompactar', compactShort: 'até compactar',
|
|
32
|
+
contextLine: 'Contexto: {used} de {threshold} tokens, resta {left}% antes de o Claude Code compactar a conversa.',
|
|
27
33
|
limit: 'limite em', cache: 'cache regravado', spend: 'gasto', today: 'hoje', list: 'lista', watching: 'só observando',
|
|
28
34
|
unavailable: 'status indisponível', starting: 'iniciando', costFull: 'a preço de lista da API, não é uma fatura',
|
|
29
35
|
paceEmpty: 'O ritmo precisa de duas amostras crescentes do plano e atingir o limite antes da renovação.',
|
|
@@ -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
|
+
}
|
package/dist/src/live-panel.d.ts
CHANGED
|
@@ -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>;
|