@agentguard-run/burn 0.3.17 → 0.3.19
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 +21 -0
- package/README.md +67 -3
- package/dist/src/adapters/codex.js +4 -3
- package/dist/src/adapters/cursor.js +4 -3
- package/dist/src/cli.js +38 -4
- package/dist/src/conformance.js +2 -2
- package/dist/src/detectors/evaluate.js +36 -36
- package/dist/src/frames.d.ts +3 -1
- package/dist/src/frames.js +5 -4
- package/dist/src/hook/pre-tool-use.d.ts +20 -2
- package/dist/src/hook/pre-tool-use.js +84 -13
- package/dist/src/index.d.ts +2 -1
- package/dist/src/index.js +13 -2
- package/dist/src/insights/compare.d.ts +104 -0
- package/dist/src/insights/compare.js +210 -0
- package/dist/src/insights/i18n.d.ts +38 -7
- package/dist/src/insights/i18n.js +81 -7
- package/dist/src/insights/render.d.ts +24 -2
- package/dist/src/insights/render.js +25 -16
- package/dist/src/insights/sessions.d.ts +25 -0
- package/dist/src/insights/sessions.js +72 -5
- package/dist/src/insights/types.d.ts +3 -0
- package/dist/src/insights/types.js +3 -1
- package/dist/src/live-panel.d.ts +1 -1
- package/dist/src/live-panel.js +8 -7
- package/dist/src/replay/render.d.ts +2 -0
- package/dist/src/replay/render.js +15 -12
- package/dist/src/stop-text.d.ts +39 -0
- package/dist/src/stop-text.js +61 -0
- package/dist/src/types.d.ts +9 -0
- package/fixtures/live-sep20-stop-104x35.txt +1 -1
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.WHY_TEXT = void 0;
|
|
3
|
+
exports.COMPARE_TEXT = exports.WHY_TEXT = void 0;
|
|
4
4
|
exports.whyLangOf = whyLangOf;
|
|
5
5
|
exports.detectWhyLang = detectWhyLang;
|
|
6
6
|
/**
|
|
@@ -65,9 +65,9 @@ const en = {
|
|
|
65
65
|
mixedRanges: 'Some bucket cache-write costs are ranges because mixed cache lifetimes are not attributed to individual buckets. Range endpoints are not additive across buckets.',
|
|
66
66
|
diagnostics: (duplicates, malformed) => `Usage records de-duplicated: ${duplicates}. Malformed lines skipped: ${malformed}.`,
|
|
67
67
|
tipFanout: share => `Next: sub-agent fan-out is ${share} of this session's tokens. Spawn limits refuse the next sub-agent launch past your limit, free on one machine: agentguard.run/try`,
|
|
68
|
-
tipRewrites: (rewrites, total) => `Next: full-prefix rewrites are ${rewrites} of ${total} API list equivalent here. See the cause of each one: npx
|
|
68
|
+
tipRewrites: (rewrites, total) => `Next: full-prefix rewrites are ${rewrites} of ${total} API list equivalent here. See the cause of each one: npx agentguard-burn rewrites`,
|
|
69
69
|
tipHistory: share => `Next: history re-sent is ${share} of this session's tokens. A fresh session, or /compact, starts that history over.`,
|
|
70
|
-
hide: 'Hide tips like this: npx
|
|
70
|
+
hide: 'Hide tips like this: npx agentguard-burn quiet on',
|
|
71
71
|
};
|
|
72
72
|
/** Latin American Spanish: tú forms and vocabulary that reads the same from Mexico and Panama to Argentina. */
|
|
73
73
|
const es = {
|
|
@@ -105,9 +105,9 @@ const es = {
|
|
|
105
105
|
mixedRanges: 'Algunos costos de escritura en caché por categoría son rangos, porque las duraciones de caché mixtas no se atribuyen a categorías individuales. Los extremos de los rangos no se suman entre categorías.',
|
|
106
106
|
diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Líneas mal formadas omitidas: ${malformed}.`,
|
|
107
107
|
tipFanout: share => `Próximo paso: el fan-out de subagentes representa el ${share} de los tokens de esta sesión. Los límites de subagentes rechazan nuevos subagentes cuando llegas a tu límite, gratis en una máquina: agentguard.run/try`,
|
|
108
|
-
tipRewrites: (rewrites, total) => `Próximo paso: las reescrituras de prefijo completo suman ${rewrites} de ${total} (equivalente a precio de lista de la API) en esta sesión. Mira la causa de cada una: npx
|
|
108
|
+
tipRewrites: (rewrites, total) => `Próximo paso: las reescrituras de prefijo completo suman ${rewrites} de ${total} (equivalente a precio de lista de la API) en esta sesión. Mira la causa de cada una: npx agentguard-burn rewrites`,
|
|
109
109
|
tipHistory: share => `Próximo paso: el historial reenviado representa el ${share} de los tokens de esta sesión. Una sesión nueva, o /compact, reinicia ese historial.`,
|
|
110
|
-
hide: 'Para ocultar consejos como este: npx
|
|
110
|
+
hide: 'Para ocultar consejos como este: npx agentguard-burn quiet on',
|
|
111
111
|
};
|
|
112
112
|
/** Brazilian Portuguese: você forms. */
|
|
113
113
|
const pt = {
|
|
@@ -145,8 +145,82 @@ const pt = {
|
|
|
145
145
|
mixedRanges: 'Alguns custos de gravação em cache por categoria aparecem como faixas, porque durações de cache mistas não são atribuídas a categorias individuais. Os extremos das faixas não se somam entre categorias.',
|
|
146
146
|
diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Linhas malformadas ignoradas: ${malformed}.`,
|
|
147
147
|
tipFanout: share => `Próximo passo: o fan-out de subagentes representa ${share} dos tokens desta sessão. Os limites de subagentes recusam novos subagentes quando você chega ao seu limite, grátis em uma máquina: agentguard.run/try`,
|
|
148
|
-
tipRewrites: (rewrites, total) => `Próximo passo: as reescritas de prefixo completo somam ${rewrites} de ${total} (equivalente ao preço de tabela da API) nesta sessão. Veja a causa de cada uma: npx
|
|
148
|
+
tipRewrites: (rewrites, total) => `Próximo passo: as reescritas de prefixo completo somam ${rewrites} de ${total} (equivalente ao preço de tabela da API) nesta sessão. Veja a causa de cada uma: npx agentguard-burn rewrites`,
|
|
149
149
|
tipHistory: share => `Próximo passo: o histórico reenviado representa ${share} dos tokens desta sessão. Uma sessão nova, ou /compact, reinicia esse histórico.`,
|
|
150
|
-
hide: 'Para ocultar dicas como esta: npx
|
|
150
|
+
hide: 'Para ocultar dicas como esta: npx agentguard-burn quiet on',
|
|
151
151
|
};
|
|
152
152
|
exports.WHY_TEXT = { en, es, pt };
|
|
153
|
+
const TWO_IDS = 'agentguard-burn compare SESSION_A SESSION_B';
|
|
154
|
+
const compareEn = {
|
|
155
|
+
title: 'AgentGuard compare: B against A',
|
|
156
|
+
started: stamp => `started ${stamp}`,
|
|
157
|
+
startUnknown: 'start time not recorded',
|
|
158
|
+
model: model => `Model: ${model}`,
|
|
159
|
+
models: list => `Output by model: ${list}`,
|
|
160
|
+
noModel: 'Model: no assistant response recorded',
|
|
161
|
+
project: path => `Project: ${path ?? 'not recorded'}`,
|
|
162
|
+
headers: ['Metric', 'A', 'B', 'Change'],
|
|
163
|
+
labels: {
|
|
164
|
+
assistantResponses: 'Assistant responses', inputTokens: 'Input tokens', cacheReadTokens: 'read from cache', cacheWriteTokens: 'cache writes',
|
|
165
|
+
freshInputTokens: 'fresh input', cacheShare: 'Cache share', outputTokens: 'Output tokens', subagentsLaunched: 'Sub-agents launched',
|
|
166
|
+
fullPrefixRewrites: en.labels.full_prefix_rewrites, usd: en.headers[2],
|
|
167
|
+
},
|
|
168
|
+
unavailable: 'unavailable',
|
|
169
|
+
subagents: 'Totals include sub-agents.',
|
|
170
|
+
forkUnavailable: session => `${session}: inherited Codex history has no verifiable boundary, so its usage is unavailable. Copied usage is excluded, not counted as zero.`,
|
|
171
|
+
rangeMidpoint: 'A dollar range is compared at its midpoint.',
|
|
172
|
+
listPrice: 'Dollar figures are API list-price equivalents, not a bill.',
|
|
173
|
+
sameTask: 'AgentGuard cannot tell whether these sessions did the same task. Compare runs of the same task.',
|
|
174
|
+
fewerThanTwo: (found, project) => found === 0
|
|
175
|
+
? `No local top-level session found, and compare needs two. Pass two ids: ${TWO_IDS}`
|
|
176
|
+
: `Only one top-level session found${project ? ` in ${project}` : ''}, and compare needs two. Pass two ids: ${TWO_IDS}`,
|
|
177
|
+
};
|
|
178
|
+
const compareEs = {
|
|
179
|
+
title: 'AgentGuard compare: B frente a A',
|
|
180
|
+
started: stamp => `inicio ${stamp}`,
|
|
181
|
+
startUnknown: 'hora de inicio no registrada',
|
|
182
|
+
model: model => `Modelo: ${model}`,
|
|
183
|
+
models: list => `Salida por modelo: ${list}`,
|
|
184
|
+
noModel: 'Modelo: no hay respuestas del asistente registradas',
|
|
185
|
+
project: path => `Proyecto: ${path ?? 'no registrado'}`,
|
|
186
|
+
headers: ['Métrica', 'A', 'B', 'Cambio'],
|
|
187
|
+
labels: {
|
|
188
|
+
assistantResponses: 'Respuestas del asistente', inputTokens: 'Tokens de entrada', cacheReadTokens: 'lectura de caché', cacheWriteTokens: 'escritura en caché',
|
|
189
|
+
freshInputTokens: 'entrada nueva', cacheShare: 'Proporción de caché', outputTokens: 'Tokens de salida', subagentsLaunched: 'Subagentes lanzados',
|
|
190
|
+
fullPrefixRewrites: es.labels.full_prefix_rewrites, usd: es.headers[2],
|
|
191
|
+
},
|
|
192
|
+
unavailable: 'no disponible',
|
|
193
|
+
subagents: 'Los totales incluyen los subagentes.',
|
|
194
|
+
forkUnavailable: session => `${session}: el historial heredado de Codex no tiene un punto de corte verificable, así que el uso de esta sesión no está disponible. El uso copiado queda excluido, no se cuenta como cero.`,
|
|
195
|
+
rangeMidpoint: 'Un rango en dólares se compara por su punto medio.',
|
|
196
|
+
listPrice: 'Las cifras en dólares son equivalentes a precio de lista de la API, no una factura.',
|
|
197
|
+
sameTask: 'AgentGuard no puede saber si estas sesiones hicieron la misma tarea. Compara ejecuciones de la misma tarea.',
|
|
198
|
+
fewerThanTwo: (found, project) => found === 0
|
|
199
|
+
? `No se encontró ninguna sesión principal local, y compare necesita dos. Pasa dos ids: ${TWO_IDS}`
|
|
200
|
+
: `Solo se encontró una sesión principal${project ? ` en ${project}` : ''}, y compare necesita dos. Pasa dos ids: ${TWO_IDS}`,
|
|
201
|
+
};
|
|
202
|
+
const comparePt = {
|
|
203
|
+
title: 'AgentGuard compare: B em relação a A',
|
|
204
|
+
started: stamp => `início ${stamp}`,
|
|
205
|
+
startUnknown: 'horário de início não registrado',
|
|
206
|
+
model: model => `Modelo: ${model}`,
|
|
207
|
+
models: list => `Saída por modelo: ${list}`,
|
|
208
|
+
noModel: 'Modelo: nenhuma resposta do assistente registrada',
|
|
209
|
+
project: path => `Projeto: ${path ?? 'não registrado'}`,
|
|
210
|
+
headers: ['Métrica', 'A', 'B', 'Variação'],
|
|
211
|
+
labels: {
|
|
212
|
+
assistantResponses: 'Respostas do assistente', inputTokens: 'Tokens de entrada', cacheReadTokens: 'leitura de cache', cacheWriteTokens: 'gravação em cache',
|
|
213
|
+
freshInputTokens: 'entrada nova', cacheShare: 'Proporção de cache', outputTokens: 'Tokens de saída', subagentsLaunched: 'Subagentes iniciados',
|
|
214
|
+
fullPrefixRewrites: pt.labels.full_prefix_rewrites, usd: pt.headers[2],
|
|
215
|
+
},
|
|
216
|
+
unavailable: 'indisponível',
|
|
217
|
+
subagents: 'Os totais incluem os subagentes.',
|
|
218
|
+
forkUnavailable: session => `${session}: o histórico herdado do Codex não tem um ponto de corte verificável, então o uso desta sessão fica indisponível. O uso copiado fica de fora, não é contado como zero.`,
|
|
219
|
+
rangeMidpoint: 'Uma faixa em dólares é comparada pelo ponto médio.',
|
|
220
|
+
listPrice: 'Os valores em dólares são equivalentes ao preço de tabela da API, não uma fatura.',
|
|
221
|
+
sameTask: 'O AgentGuard não consegue saber se estas sessões fizeram a mesma tarefa. Compare execuções da mesma tarefa.',
|
|
222
|
+
fewerThanTwo: (found, project) => found === 0
|
|
223
|
+
? `Nenhuma sessão principal local foi encontrada, e o compare precisa de duas. Passe dois ids: ${TWO_IDS}`
|
|
224
|
+
: `Só uma sessão principal foi encontrada${project ? ` em ${project}` : ''}, e o compare precisa de duas. Passe dois ids: ${TWO_IDS}`,
|
|
225
|
+
};
|
|
226
|
+
exports.COMPARE_TEXT = { en: compareEn, es: compareEs, pt: comparePt };
|
|
@@ -1,8 +1,30 @@
|
|
|
1
|
-
import { type DollarRange, type PricingTable } from './pricing';
|
|
2
|
-
import { type InsightHost, type InsightTranscript, type InsightTurn, type RewriteCause, type RewriteEvidence } from './types';
|
|
1
|
+
import { type DollarRange, type PricingTable, type TurnPrice } from './pricing';
|
|
2
|
+
import { type AttributionSummary, type InsightHost, type InsightTranscript, type InsightTurn, type RewriteCause, type RewriteEvidence } from './types';
|
|
3
3
|
import { type WhyLang } from './i18n';
|
|
4
4
|
export declare function sumPrices(values: Array<DollarRange | null>): DollarRange | null;
|
|
5
5
|
export declare function totalTokens(turn: InsightTurn): number;
|
|
6
|
+
/** What the two header lines of `why` are computed from; `compare` reads the same object, so both commands print the same figures. */
|
|
7
|
+
export interface SessionFigures {
|
|
8
|
+
/** Deduplicated responses in time order, child transcripts included when the transcript carries them. */
|
|
9
|
+
turns: InsightTurn[];
|
|
10
|
+
attribution: AttributionSummary;
|
|
11
|
+
prices: TurnPrice[];
|
|
12
|
+
totals: {
|
|
13
|
+
input: number;
|
|
14
|
+
write: number;
|
|
15
|
+
read: number;
|
|
16
|
+
output: number;
|
|
17
|
+
};
|
|
18
|
+
/** The API list equivalent `why` prints; null when any response has no verified rate. */
|
|
19
|
+
totalUsd: DollarRange | null;
|
|
20
|
+
}
|
|
21
|
+
export declare function sessionFigures(transcript: InsightTranscript, rates?: PricingTable): SessionFigures;
|
|
22
|
+
/** Left-aligned columns two spaces apart; widths follow the widest cell, so translated labels widen their column. */
|
|
23
|
+
export declare function table(headers: string[], rows: string[][]): string;
|
|
24
|
+
/** Token counts in en-US digits in every language. */
|
|
25
|
+
export declare const count: (n: number) => string;
|
|
26
|
+
/** The table's share column; the tip prints the same figure. */
|
|
27
|
+
export declare const share: (tokens: number, total: number) => string;
|
|
6
28
|
export declare const WHY_TIP_HIDE_LINE: string;
|
|
7
29
|
/**
|
|
8
30
|
* One next step from the session's own measured shares, first match wins; null
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.WHY_TIP_HIDE_LINE = void 0;
|
|
3
|
+
exports.WHY_TIP_HIDE_LINE = exports.share = exports.count = void 0;
|
|
4
4
|
exports.sumPrices = sumPrices;
|
|
5
5
|
exports.totalTokens = totalTokens;
|
|
6
|
+
exports.sessionFigures = sessionFigures;
|
|
7
|
+
exports.table = table;
|
|
6
8
|
exports.whyTip = whyTip;
|
|
7
9
|
exports.renderWhy = renderWhy;
|
|
8
10
|
exports.rewriteReport = rewriteReport;
|
|
@@ -19,6 +21,13 @@ function sumPrices(values) {
|
|
|
19
21
|
return values.some(value => value === null) ? null : values.reduce((sum, value) => ({ min: sum.min + value.min, max: sum.max + value.max }), { min: 0, max: 0 });
|
|
20
22
|
}
|
|
21
23
|
function totalTokens(turn) { return turn.inputTokens + turn.cacheWriteTokens + turn.cacheReadTokens + turn.outputTokens; }
|
|
24
|
+
function sessionFigures(transcript, rates = {}) {
|
|
25
|
+
const turns = (0, transcript_1.deduplicateTurns)(transcript.turns).sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
|
|
26
|
+
const prices = turns.map(turn => (0, pricing_1.priceTurn)(turn, rates));
|
|
27
|
+
const totals = { input: 0, write: 0, read: 0, output: 0 };
|
|
28
|
+
turns.forEach(turn => { totals.input += turn.inputTokens; totals.write += turn.cacheWriteTokens; totals.read += turn.cacheReadTokens; totals.output += turn.outputTokens; });
|
|
29
|
+
return { turns, attribution: (0, attribution_1.attributeTurns)(turns), prices, totals, totalUsd: sumPrices(prices.map(price => price.usd)) };
|
|
30
|
+
}
|
|
22
31
|
function bucketPrice(turn, allocation, rates) {
|
|
23
32
|
const quantities = allocation.categories;
|
|
24
33
|
if (Object.values(quantities).every(value => value === 0))
|
|
@@ -31,13 +40,17 @@ function bucketPrice(turn, allocation, rates) {
|
|
|
31
40
|
cacheWrite5mTokens: completeWrites ? turn.cacheWrite5mTokens : undefined,
|
|
32
41
|
cacheWrite1hTokens: completeWrites ? turn.cacheWrite1hTokens : undefined }, rates).usd;
|
|
33
42
|
}
|
|
43
|
+
/** Left-aligned columns two spaces apart; widths follow the widest cell, so translated labels widen their column. */
|
|
34
44
|
function table(headers, rows) {
|
|
35
45
|
const widths = headers.map((header, i) => Math.max(header.length, ...rows.map(row => row[i]?.length ?? 0)));
|
|
36
46
|
return [headers, ...rows].map(row => row.map((cell, i) => cell.padEnd(widths[i])).join(' ').trimEnd()).join('\n');
|
|
37
47
|
}
|
|
48
|
+
/** Token counts in en-US digits in every language. */
|
|
38
49
|
const count = (n) => n.toLocaleString('en-US');
|
|
50
|
+
exports.count = count;
|
|
39
51
|
/** The table's share column; the tip prints the same figure. */
|
|
40
52
|
const share = (tokens, total) => `${(total ? tokens / total * 100 : 0).toFixed(1)}%`;
|
|
53
|
+
exports.share = share;
|
|
41
54
|
const midpoint = (value) => (value.min + value.max) / 2;
|
|
42
55
|
exports.WHY_TIP_HIDE_LINE = i18n_1.WHY_TEXT.en.hide;
|
|
43
56
|
/**
|
|
@@ -50,11 +63,11 @@ function whyTip(input, lang = 'en') {
|
|
|
50
63
|
const { totalTokens, fanoutTokens, historyTokens, rewriteUsd, totalUsd } = input;
|
|
51
64
|
const text = i18n_1.WHY_TEXT[lang];
|
|
52
65
|
if (totalTokens > 0 && fanoutTokens / totalTokens >= 0.2)
|
|
53
|
-
return text.tipFanout(share(fanoutTokens, totalTokens));
|
|
66
|
+
return text.tipFanout((0, exports.share)(fanoutTokens, totalTokens));
|
|
54
67
|
if (rewriteUsd && totalUsd && midpoint(totalUsd) > 0 && midpoint(rewriteUsd) / midpoint(totalUsd) >= 0.15)
|
|
55
68
|
return text.tipRewrites((0, live_1.dollars)(rewriteUsd, text), (0, live_1.dollars)(totalUsd, text));
|
|
56
69
|
if (totalTokens > 0 && historyTokens / totalTokens >= 0.3)
|
|
57
|
-
return text.tipHistory(share(historyTokens, totalTokens));
|
|
70
|
+
return text.tipHistory((0, exports.share)(historyTokens, totalTokens));
|
|
58
71
|
return null;
|
|
59
72
|
}
|
|
60
73
|
/** `lang` changes words only: every figure, id, command and URL prints as it does in English, and `why json` never passes through here. */
|
|
@@ -67,31 +80,27 @@ function renderWhy(transcript, rates = {}, options = {}) {
|
|
|
67
80
|
text.forkUnavailable,
|
|
68
81
|
table(text.headers, types_1.INSIGHT_BUCKETS.map(bucket => [text.labels[bucket], text.unattributed, text.unattributed, text.unattributed, text.unattributed])),
|
|
69
82
|
].join('\n');
|
|
70
|
-
const turns
|
|
71
|
-
const
|
|
83
|
+
const { turns, attribution, prices, totals, totalUsd } = sessionFigures(transcript, rates);
|
|
84
|
+
const lastAttribution = attribution.turnAttributions.at(-1);
|
|
72
85
|
const byTurn = new Map(attribution.turnAttributions.map(turn => [turn.turnId, turn]));
|
|
73
|
-
const prices = turns.map(turn => (0, pricing_1.priceTurn)(turn, rates));
|
|
74
86
|
const mixedWriteAllocation = turns.some(turn => (turn.cacheWrite5mTokens ?? 0) > 0 && (turn.cacheWrite1hTokens ?? 0) > 0
|
|
75
87
|
&& byTurn.get(turn.id).buckets.some(bucket => bucket.categories.cacheCreation > 0 && bucket.categories.cacheCreation < turn.cacheWriteTokens));
|
|
76
|
-
const totals = { input: 0, write: 0, read: 0, output: 0 };
|
|
77
|
-
turns.forEach(turn => { totals.input += turn.inputTokens; totals.write += turn.cacheWriteTokens; totals.read += turn.cacheReadTokens; totals.output += turn.outputTokens; });
|
|
78
88
|
const bucketTokens = (bucket) => attribution.buckets.find(item => item.bucket === bucket).tokens;
|
|
79
89
|
const bucketUsd = (bucket) => sumPrices(turns.map(turn => bucketPrice(turn, byTurn.get(turn.id).buckets.find(item => item.bucket === bucket), rates)));
|
|
80
|
-
const totalUsd = sumPrices(prices.map(price => price.usd));
|
|
81
90
|
const rows = types_1.INSIGHT_BUCKETS.map(bucket => {
|
|
82
91
|
const tokens = bucketTokens(bucket), lastTokens = lastAttribution?.buckets.find(item => item.bucket === bucket).tokens ?? 0;
|
|
83
|
-
return [text.labels[bucket], count(tokens), money(bucketUsd(bucket)), share(tokens, attribution.totalTokens), share(lastTokens, lastAttribution?.totalTokens ?? 0)];
|
|
92
|
+
return [text.labels[bucket], (0, exports.count)(tokens), money(bucketUsd(bucket)), (0, exports.share)(tokens, attribution.totalTokens), (0, exports.share)(lastTokens, lastAttribution?.totalTokens ?? 0)];
|
|
84
93
|
});
|
|
85
94
|
const unknownModels = [...new Set(prices.filter(price => price.usd === null).map(price => price.model ?? text.missingModel))];
|
|
86
95
|
const tip = options.tips ? whyTip({ totalTokens: attribution.totalTokens, fanoutTokens: bucketTokens('subagent_fanout'),
|
|
87
96
|
historyTokens: bucketTokens('history_resent'), rewriteUsd: bucketUsd('full_prefix_rewrites'), totalUsd }, lang) : null;
|
|
88
97
|
return [
|
|
89
98
|
`AgentGuard why: ${transcript.sessionId}`,
|
|
90
|
-
text.summary(turns.length, count(attribution.totalTokens), totalUsd === null ? null : money(totalUsd)),
|
|
91
|
-
text.usage(count(totals.input), count(totals.write), count(totals.read), count(totals.output)),
|
|
99
|
+
text.summary(turns.length, (0, exports.count)(attribution.totalTokens), totalUsd === null ? null : money(totalUsd)),
|
|
100
|
+
text.usage((0, exports.count)(totals.input), (0, exports.count)(totals.write), (0, exports.count)(totals.read), (0, exports.count)(totals.output)),
|
|
92
101
|
'', table(text.headers, rows), '',
|
|
93
102
|
text.shares,
|
|
94
|
-
text.increments(attribution.sharedTurns, attribution.prefixRebaselines, count(attribution.previousOutputTokensReserved)),
|
|
103
|
+
text.increments(attribution.sharedTurns, attribution.prefixRebaselines, (0, exports.count)(attribution.previousOutputTokensReserved)),
|
|
95
104
|
text.observed(transcript.observations),
|
|
96
105
|
'', text.methodTitle,
|
|
97
106
|
...types_1.INSIGHT_BUCKETS.map(bucket => `${text.labels[bucket]}: ${text.method[bucket]}`),
|
|
@@ -145,15 +154,15 @@ function renderRewrites(transcripts, rates = {}) {
|
|
|
145
154
|
for (const session of report.sessions) {
|
|
146
155
|
const groups = new Map();
|
|
147
156
|
session.records.forEach(record => {
|
|
148
|
-
detail.push([stamp(record.at), session.sessionId, session.host, record.model ?? 'unknown', record.cause, idle(record.idleMs), count(record.cacheWriteTokens), (0, live_1.dollars)(record.usd), record.explanation]);
|
|
157
|
+
detail.push([stamp(record.at), session.sessionId, session.host, record.model ?? 'unknown', record.cause, idle(record.idleMs), (0, exports.count)(record.cacheWriteTokens), (0, live_1.dollars)(record.usd), record.explanation]);
|
|
149
158
|
groups.set(record.cause, [...groups.get(record.cause) ?? [], record]);
|
|
150
159
|
totals.set(record.cause, [...totals.get(record.cause) ?? [], record]);
|
|
151
160
|
});
|
|
152
161
|
for (const [cause, records] of groups)
|
|
153
|
-
summary.push([session.sessionId, cause, String(records.length), count(records.reduce((sum, record) => sum + record.cacheWriteTokens, 0)), (0, live_1.dollars)(sumPrices(records.map(record => record.usd)))]);
|
|
162
|
+
summary.push([session.sessionId, cause, String(records.length), (0, exports.count)(records.reduce((sum, record) => sum + record.cacheWriteTokens, 0)), (0, live_1.dollars)(sumPrices(records.map(record => record.usd)))]);
|
|
154
163
|
}
|
|
155
164
|
for (const [cause, records] of totals)
|
|
156
|
-
summary.push(['ALL', cause, String(records.length), count(records.reduce((sum, record) => sum + record.cacheWriteTokens, 0)), (0, live_1.dollars)(sumPrices(records.map(record => record.usd)))]);
|
|
165
|
+
summary.push(['ALL', cause, String(records.length), (0, exports.count)(records.reduce((sum, record) => sum + record.cacheWriteTokens, 0)), (0, live_1.dollars)(sumPrices(records.map(record => record.usd)))]);
|
|
157
166
|
const sessions = report.sessions.length === 1 ? 'session' : 'combined session';
|
|
158
167
|
const share = report.usd && report.sessionUsd && report.shareOfSessionUsd !== null
|
|
159
168
|
? `Rewrites: ${(0, live_1.dollars)(report.usd)}, ${(report.shareOfSessionUsd * 100).toFixed(1)}% of the ${sessions} list total ${(0, live_1.dollars)(report.sessionUsd)} (API list equivalent, not a bill).`
|
|
@@ -4,11 +4,36 @@ export interface TranscriptLocation {
|
|
|
4
4
|
sessionId: string;
|
|
5
5
|
modifiedAt: number;
|
|
6
6
|
}
|
|
7
|
+
/** Claude Code keeps one directory per project here, each session a JSONL file directly inside it; Codex keeps dated rollouts. */
|
|
8
|
+
export declare function transcriptRoots(): {
|
|
9
|
+
claude: string;
|
|
10
|
+
codex: string;
|
|
11
|
+
};
|
|
7
12
|
/** Local locators only. Never follows directory symlinks or reads message content. */
|
|
8
13
|
export declare function discoverInsightTranscripts(roots?: {
|
|
9
14
|
claude: string;
|
|
10
15
|
codex: string;
|
|
11
16
|
}): TranscriptLocation[];
|
|
12
17
|
export declare function selectInsightTranscript(session?: string, locations?: TranscriptLocation[]): TranscriptLocation;
|
|
18
|
+
/**
|
|
19
|
+
* A file Claude Code keeps inside a session's own directory, such as
|
|
20
|
+
* `<session>/skill-injections.jsonl`. It is not a session, so a no-argument
|
|
21
|
+
* `why` must not pick it even when it is the newest file on disk.
|
|
22
|
+
*/
|
|
23
|
+
export declare function isSessionSidecar(location: Pick<TranscriptLocation, 'path' | 'sessionId'>): boolean;
|
|
13
24
|
/** Claude Code stores each subagent's transcript beside its parent under `subagents/`. */
|
|
14
25
|
export declare function isSubagentTranscript(location: Pick<TranscriptLocation, 'path' | 'sessionId'>): boolean;
|
|
26
|
+
export interface TranscriptOrigin {
|
|
27
|
+
/** The working directory the host recorded as the session began; null when the first megabyte records none. */
|
|
28
|
+
workingDirectory: string | null;
|
|
29
|
+
/** The usage parser's verdict on those same first records: a spawned sub-agent (Codex session_meta, Claude sidechain). */
|
|
30
|
+
spawned: boolean;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Where a transcript ran, from its first complete records only: the working
|
|
34
|
+
* directory the host recorded (Claude Code writes `cwd` on its records, Codex on
|
|
35
|
+
* its session_meta and turn_context payloads) and whether the usage parser marks
|
|
36
|
+
* those records a spawned sub-agent. Reads at most one megabyte, stops at the
|
|
37
|
+
* first recorded directory and keeps no other field.
|
|
38
|
+
*/
|
|
39
|
+
export declare function transcriptOrigin(location: Pick<TranscriptLocation, 'path' | 'host'>): TranscriptOrigin;
|
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.transcriptRoots = transcriptRoots;
|
|
3
4
|
exports.discoverInsightTranscripts = discoverInsightTranscripts;
|
|
4
5
|
exports.selectInsightTranscript = selectInsightTranscript;
|
|
6
|
+
exports.isSessionSidecar = isSessionSidecar;
|
|
5
7
|
exports.isSubagentTranscript = isSubagentTranscript;
|
|
8
|
+
exports.transcriptOrigin = transcriptOrigin;
|
|
6
9
|
const node_fs_1 = require("node:fs");
|
|
7
10
|
const node_path_1 = require("node:path");
|
|
8
11
|
const node_os_1 = require("node:os");
|
|
12
|
+
const transcript_1 = require("./transcript");
|
|
13
|
+
/** Claude Code keeps one directory per project here, each session a JSONL file directly inside it; Codex keeps dated rollouts. */
|
|
14
|
+
function transcriptRoots() {
|
|
15
|
+
return { claude: (0, node_path_1.join)((0, node_os_1.homedir)(), '.claude', 'projects'), codex: (0, node_path_1.join)((0, node_os_1.homedir)(), '.codex', 'sessions') };
|
|
16
|
+
}
|
|
9
17
|
/** Local locators only. Never follows directory symlinks or reads message content. */
|
|
10
|
-
function discoverInsightTranscripts(roots = {
|
|
11
|
-
claude: (0, node_path_1.join)((0, node_os_1.homedir)(), '.claude', 'projects'),
|
|
12
|
-
codex: (0, node_path_1.join)((0, node_os_1.homedir)(), '.codex', 'sessions'),
|
|
13
|
-
}) {
|
|
18
|
+
function discoverInsightTranscripts(roots = transcriptRoots()) {
|
|
14
19
|
const found = [];
|
|
15
20
|
function visit(directory, host, depth) {
|
|
16
21
|
if (depth > 8)
|
|
@@ -51,12 +56,74 @@ function selectInsightTranscript(session, locations) {
|
|
|
51
56
|
// nothing else, which tells the operator nothing. It stays reachable by id.
|
|
52
57
|
const selected = requested
|
|
53
58
|
? candidates.find(item => item.sessionId === requested || item.sessionId.endsWith(`-${requested}`))
|
|
54
|
-
: candidates.find(item => !isSubagentTranscript(item)) ?? candidates[0];
|
|
59
|
+
: candidates.find(item => !isSubagentTranscript(item) && !isSessionSidecar(item)) ?? candidates[0];
|
|
55
60
|
if (!selected)
|
|
56
61
|
throw new Error(requested ? 'Session transcript not found. Pass its local JSONL path.' : 'No local Claude Code or Codex transcript found.');
|
|
57
62
|
return selected;
|
|
58
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* A file Claude Code keeps inside a session's own directory, such as
|
|
66
|
+
* `<session>/skill-injections.jsonl`. It is not a session, so a no-argument
|
|
67
|
+
* `why` must not pick it even when it is the newest file on disk.
|
|
68
|
+
*/
|
|
69
|
+
function isSessionSidecar(location) {
|
|
70
|
+
return location.sessionId === 'skill-injections'
|
|
71
|
+
|| /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test((0, node_path_1.basename)((0, node_path_1.dirname)(location.path)));
|
|
72
|
+
}
|
|
59
73
|
/** Claude Code stores each subagent's transcript beside its parent under `subagents/`. */
|
|
60
74
|
function isSubagentTranscript(location) {
|
|
61
75
|
return (0, node_path_1.basename)((0, node_path_1.dirname)(location.path)) === 'subagents' || location.sessionId.startsWith('agent-');
|
|
62
76
|
}
|
|
77
|
+
const ORIGIN_CHUNK_BYTES = 64 * 1024, ORIGIN_LIMIT_BYTES = 1024 * 1024;
|
|
78
|
+
/**
|
|
79
|
+
* Where a transcript ran, from its first complete records only: the working
|
|
80
|
+
* directory the host recorded (Claude Code writes `cwd` on its records, Codex on
|
|
81
|
+
* its session_meta and turn_context payloads) and whether the usage parser marks
|
|
82
|
+
* those records a spawned sub-agent. Reads at most one megabyte, stops at the
|
|
83
|
+
* first recorded directory and keeps no other field.
|
|
84
|
+
*/
|
|
85
|
+
function transcriptOrigin(location) {
|
|
86
|
+
const lines = [];
|
|
87
|
+
let workingDirectory = null, fd;
|
|
88
|
+
try {
|
|
89
|
+
fd = (0, node_fs_1.openSync)(location.path, 'r');
|
|
90
|
+
let pending = Buffer.alloc(0), offset = 0;
|
|
91
|
+
while (workingDirectory === null && offset < ORIGIN_LIMIT_BYTES) {
|
|
92
|
+
const chunk = Buffer.alloc(Math.min(ORIGIN_CHUNK_BYTES, ORIGIN_LIMIT_BYTES - offset));
|
|
93
|
+
const read = (0, node_fs_1.readSync)(fd, chunk, 0, chunk.length, offset);
|
|
94
|
+
if (!read)
|
|
95
|
+
break;
|
|
96
|
+
offset += read;
|
|
97
|
+
pending = Buffer.concat([pending, chunk.subarray(0, read)]);
|
|
98
|
+
for (let newline = pending.indexOf(10); workingDirectory === null && newline >= 0; newline = pending.indexOf(10)) {
|
|
99
|
+
const line = pending.subarray(0, newline).toString('utf8');
|
|
100
|
+
pending = pending.subarray(newline + 1);
|
|
101
|
+
if (!line.trim())
|
|
102
|
+
continue;
|
|
103
|
+
lines.push(line);
|
|
104
|
+
workingDirectory = recordedDirectory(line);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
catch { /* unreadable or removed: nothing is recorded */ }
|
|
109
|
+
finally {
|
|
110
|
+
if (fd !== undefined)
|
|
111
|
+
(0, node_fs_1.closeSync)(fd);
|
|
112
|
+
}
|
|
113
|
+
return { workingDirectory, spawned: lines.length > 0 && (0, transcript_1.parseInsightTranscript)(`${lines.join('\n')}\n`, { host: location.host }).state.spawnedSession };
|
|
114
|
+
}
|
|
115
|
+
function recordedDirectory(line) {
|
|
116
|
+
let value;
|
|
117
|
+
try {
|
|
118
|
+
value = JSON.parse(line);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
if (!value || typeof value !== 'object')
|
|
124
|
+
return null;
|
|
125
|
+
const record = value;
|
|
126
|
+
const payload = record.payload && typeof record.payload === 'object' ? record.payload : {};
|
|
127
|
+
const cwd = typeof record.cwd === 'string' ? record.cwd : record.type === 'session_meta' || record.type === 'turn_context' ? payload.cwd : undefined;
|
|
128
|
+
return typeof cwd === 'string' && cwd.length > 0 ? cwd : null;
|
|
129
|
+
}
|
|
@@ -158,6 +158,9 @@ export interface RewriteEvidence {
|
|
|
158
158
|
ttlUnknown: boolean;
|
|
159
159
|
explanation: string;
|
|
160
160
|
}
|
|
161
|
+
/** The rows `compare` prints for each session, in table order. */
|
|
162
|
+
export declare const COMPARE_METRICS: readonly ["assistantResponses", "inputTokens", "cacheReadTokens", "cacheWriteTokens", "freshInputTokens", "cacheShare", "outputTokens", "subagentsLaunched", "fullPrefixRewrites", "usd"];
|
|
163
|
+
export type CompareMetric = typeof COMPARE_METRICS[number];
|
|
161
164
|
export interface BucketAttribution {
|
|
162
165
|
bucket: InsightBucket;
|
|
163
166
|
tokens: number;
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.REWRITE_CAUSES = exports.INSIGHT_BUCKETS = void 0;
|
|
3
|
+
exports.COMPARE_METRICS = exports.REWRITE_CAUSES = exports.INSIGHT_BUCKETS = void 0;
|
|
4
4
|
exports.INSIGHT_BUCKETS = ['instruction_stack', 'history_resent', 'reread_files', 'subagent_fanout', 'tool_output', 'conversation', 'full_prefix_rewrites', 'output', 'unattributed'];
|
|
5
5
|
exports.REWRITE_CAUSES = ['model_switch', 'version_upgrade', 'compaction', 'first_spawned_turn', 'idle_ttl_expired', 'image_pruning', 'prefix_change', 'unknown_ttl', 'unknown'];
|
|
6
|
+
/** The rows `compare` prints for each session, in table order. */
|
|
7
|
+
exports.COMPARE_METRICS = ['assistantResponses', 'inputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'freshInputTokens', 'cacheShare', 'outputTokens', 'subagentsLaunched', 'fullPrefixRewrites', 'usd'];
|
package/dist/src/live-panel.d.ts
CHANGED
|
@@ -46,7 +46,7 @@ export declare function renderShowcasePanel(snapshot: LivePanelSnapshot, options
|
|
|
46
46
|
export declare function renderPhonePanel(snapshot: LivePanelSnapshot, options?: FrameOptions): Canvas;
|
|
47
47
|
export declare function renderLivePanel(snapshot: LivePanelSnapshot, options?: FrameOptions): Canvas;
|
|
48
48
|
/** STOP report adaptation uses only already-computed metadata, never local I/O. */
|
|
49
|
-
export declare function panelFromReport(report: BurnReport, at: number, outcome?: 'blocked' | 'shadow' | 'overridden' | 'allowed', subject?: 'spawn' | 'call'): LivePanelSnapshot;
|
|
49
|
+
export declare function panelFromReport(report: BurnReport, at: number, outcome?: 'blocked' | 'asked' | 'shadow' | 'overridden' | 'allowed', subject?: 'spawn' | 'call'): LivePanelSnapshot;
|
|
50
50
|
/** Display-only hold. Intake continues and the latest observation follows the card. */
|
|
51
51
|
export declare class StopHold {
|
|
52
52
|
private held?;
|
package/dist/src/live-panel.js
CHANGED
|
@@ -90,7 +90,7 @@ function renderShowcasePanel(snapshot, options = {}) {
|
|
|
90
90
|
for (let i = 0; i < 5; i++)
|
|
91
91
|
c.put(top + i, right, ' '.repeat(room), 'none');
|
|
92
92
|
c.put(top - 1, right, '─'.repeat(room), 'red');
|
|
93
|
-
c.put(top, right, 'STOP · ' + (snapshot.stop.blocked === true ? '
|
|
93
|
+
c.put(top, right, 'STOP · ' + (snapshot.stop.blocked === true ? 'refused' : snapshot.stop.blocked === false ? 'shadow / allowed' : 'outcome unknown'), 'red');
|
|
94
94
|
c.put(top + 1, right, snapshot.stop.reason.slice(0, room), 'red');
|
|
95
95
|
c.put(top + 2, right, snapshot.stopHold === false ? 'Latest STOP reason.' : 'Reason held for 2 seconds.', 'slate');
|
|
96
96
|
c.put(top + 3, right, '─'.repeat(room), 'red');
|
|
@@ -141,7 +141,7 @@ function renderPhonePanel(snapshot, options = {}) {
|
|
|
141
141
|
c.put(29, 0, (options.label ? options.label.toUpperCase() : 'Each copy runs its own context window.').slice(0, w), options.label ? 'slate' : 'white');
|
|
142
142
|
if (snapshot.stop) {
|
|
143
143
|
c.put(30, 0, '─'.repeat(w), 'red');
|
|
144
|
-
c.put(31, 0, ('STOP · ' + (snapshot.stop.blocked === true ? '
|
|
144
|
+
c.put(31, 0, ('STOP · ' + (snapshot.stop.blocked === true ? 'refused' : snapshot.stop.blocked === false ? 'shadow / allowed' : 'outcome unknown') + ' · ' + snapshot.stop.reason).slice(0, w), 'red');
|
|
145
145
|
c.put(32, 0, '─'.repeat(w), 'red');
|
|
146
146
|
}
|
|
147
147
|
c.put(33, 0, 'At the ceiling, the attempt is refused.'.slice(0, w), 'white');
|
|
@@ -186,7 +186,7 @@ function renderLivePanel(snapshot, options = {}) {
|
|
|
186
186
|
const y = h >= 30 ? h - 11 : 16;
|
|
187
187
|
for (let i = 0; i < 5; i++)
|
|
188
188
|
c.put(y + i, right, ' '.repeat(room), 'none');
|
|
189
|
-
c.put(y, right, 'STOP · ' + (snapshot.stop.blocked === true ? '
|
|
189
|
+
c.put(y, right, 'STOP · ' + (snapshot.stop.blocked === true ? 'refused' : snapshot.stop.blocked === false ? 'shadow / allowed' : 'outcome unknown'), 'red');
|
|
190
190
|
c.put(y + 1, right, snapshot.stop.reason.slice(0, room), 'red');
|
|
191
191
|
c.put(y + 2, right, snapshot.stopHold === false ? 'Latest STOP reason.' : 'Reason held for 2 seconds.', 'slate');
|
|
192
192
|
}
|
|
@@ -197,10 +197,11 @@ function renderLivePanel(snapshot, options = {}) {
|
|
|
197
197
|
function panelFromReport(report, at, outcome, subject) {
|
|
198
198
|
const rate = report.findings.find(f => f.detector === 'spawn_rate');
|
|
199
199
|
const decision = { id: digest(`${report.sessionId}:${at}`), at, tool: subject === 'call' ? 'model_call' : 'spawn', verdict: report.verdict,
|
|
200
|
-
reason: report.findings.map(f => `${f.detector}:${f.verdict} ${f.observed}/${f.threshold}`).join(' + ') || 'Reason not recorded.', blocked: outcome === undefined ? null : outcome === 'blocked' };
|
|
201
|
-
const note = outcome === 'blocked' ? (subject === 'call' ? 'model call
|
|
202
|
-
: outcome === '
|
|
203
|
-
: outcome === '
|
|
200
|
+
reason: report.findings.map(f => `${f.detector}:${f.verdict} ${f.observed}/${f.threshold}`).join(' + ') || 'Reason not recorded.', blocked: outcome === undefined ? null : outcome === 'blocked' || outcome === 'asked' };
|
|
201
|
+
const note = outcome === 'blocked' ? (subject === 'call' ? 'model call refused' : 'sub-agent launch refused')
|
|
202
|
+
: outcome === 'asked' ? 'sub-agent launch held for your yes'
|
|
203
|
+
: outcome === 'shadow' ? 'shadow: would have refused, call allowed' : outcome === 'overridden' ? 'override: call allowed'
|
|
204
|
+
: outcome === 'allowed' ? 'call allowed' : 'STOP boundary · enforcement outcome not recorded';
|
|
204
205
|
return { session: (/^[A-Za-z0-9_-]+$/.test(report.sessionId) ? report.sessionId : digest(report.sessionId)).slice(0, 8), startedAt: at, observedAt: at, elapsedMs: null, controls: false, stopHold: false,
|
|
205
206
|
spawns: rate?.observed ?? null, tokens: null, replayShare: Number.isFinite(report.cacheReadRatio) ? report.cacheReadRatio : null,
|
|
206
207
|
windowActiveMinutes: null, spawnCeiling: rate?.verdict === 'STOP' ? rate.threshold : null,
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* runaway in, one line worth quoting. Pure ASCII/ANSI, degrades cleanly.
|
|
5
5
|
*/
|
|
6
6
|
import type { BurnReport } from '../types';
|
|
7
|
+
import { type StopHost } from '../stop-text';
|
|
7
8
|
import type { ReplaySummary, SessionReplay } from './simulate';
|
|
8
9
|
export declare function sparkline(curve: number[], stopAt: number | null, on: boolean): string;
|
|
9
10
|
export declare function comparison(tokens: number): string;
|
|
@@ -14,5 +15,6 @@ export declare function renderReplay(summary: ReplaySummary, opts?: {
|
|
|
14
15
|
export declare function renderStop(report: BurnReport, opts?: {
|
|
15
16
|
colour?: boolean;
|
|
16
17
|
subject?: 'spawn' | 'call';
|
|
18
|
+
host?: StopHost;
|
|
17
19
|
}): string;
|
|
18
20
|
export declare function renderSessionRow(s: SessionReplay): string;
|
|
@@ -12,6 +12,7 @@ exports.renderStop = renderStop;
|
|
|
12
12
|
exports.renderSessionRow = renderSessionRow;
|
|
13
13
|
const frames_1 = require("../frames");
|
|
14
14
|
const evaluate_1 = require("../detectors/evaluate");
|
|
15
|
+
const stop_text_1 = require("../stop-text");
|
|
15
16
|
const C = {
|
|
16
17
|
reset: '\x1b[0m',
|
|
17
18
|
bold: '\x1b[1m',
|
|
@@ -179,27 +180,29 @@ function renderReplay(summary, opts = {}) {
|
|
|
179
180
|
function renderStop(report, opts = {}) {
|
|
180
181
|
const on = opts.colour ?? false;
|
|
181
182
|
if (on)
|
|
182
|
-
return (0, frames_1.renderFrame)({ kind: 'report', report, subject: opts.subject, outcome: 'blocked' }, { colour: true }).render();
|
|
183
|
-
const lead = report.findings.find((f) => f.verdict === 'STOP')?.summary ?? 'Fan-out ceiling reached.';
|
|
183
|
+
return (0, frames_1.renderFrame)({ kind: 'report', report, subject: opts.subject, outcome: 'blocked', host: opts.host }, { colour: true }).render();
|
|
184
184
|
const w = 64;
|
|
185
185
|
const bar = '─'.repeat(w);
|
|
186
|
-
const title = opts.subject === 'call' ? ' model call
|
|
186
|
+
const title = opts.subject === 'call' ? ' model call refused' : ' sub-agent launch refused';
|
|
187
|
+
// One cause, one context line, two actions, one way to continue.
|
|
188
|
+
const row = (text, style = '') => paint(on, C.red, '│ ') + paint(on, style, text.padEnd(w - 1).slice(0, w - 1)) + paint(on, C.red, '│');
|
|
187
189
|
const lines = [];
|
|
188
190
|
lines.push(paint(on, C.red, `┌${bar}┐`));
|
|
189
191
|
lines.push(paint(on, C.red, '│ ') + paint(on, C.bold + C.bgRed + C.white, ' AGENTGUARD STOP ') + paint(on, C.bold, title) + paint(on, C.red, ' '.repeat(w - 18 - title.length) + '│'));
|
|
190
192
|
lines.push(paint(on, C.red, `├${bar}┤`));
|
|
191
|
-
|
|
192
|
-
|
|
193
|
+
for (const line of wrap((0, stop_text_1.stopSummary)(report), w - 1, ''))
|
|
194
|
+
lines.push(row(line));
|
|
195
|
+
lines.push(row((0, stop_text_1.sessionSoFar)(report, opts.subject), C.dim));
|
|
193
196
|
lines.push(paint(on, C.red, `├${bar}┤`));
|
|
194
|
-
lines.push(
|
|
195
|
-
report.prescriptions.slice(0,
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
lines.push(paint(on, C.red, '│ ') + line.padEnd(w - 1) + paint(on, C.red, '│'));
|
|
199
|
-
}
|
|
197
|
+
lines.push(row('WHAT TO DO', C.bold));
|
|
198
|
+
report.prescriptions.slice(0, 2).forEach((p, i) => {
|
|
199
|
+
for (const line of wrap(`${i + 1}. ${p}`, w - 2, ' '))
|
|
200
|
+
lines.push(row(line));
|
|
200
201
|
});
|
|
201
202
|
lines.push(paint(on, C.red, `├${bar}┤`));
|
|
202
|
-
|
|
203
|
+
const [label, command] = (0, stop_text_1.continueLines)(opts.host, opts.subject);
|
|
204
|
+
lines.push(row(label, C.dim));
|
|
205
|
+
lines.push(row(command));
|
|
203
206
|
lines.push(paint(on, C.red, `└${bar}┘`));
|
|
204
207
|
return lines.join('\n');
|
|
205
208
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The words of a STOP, shared by every surface that shows one: the plain box
|
|
3
|
+
* a hook returns, the canvas frame, the permission prompt, the override
|
|
4
|
+
* confirmation and each host adapter. One source keeps them from drifting
|
|
5
|
+
* apart. On Sep 26 2026 the box named the token limit while the override
|
|
6
|
+
* confirmation quoted the first finding in the list, a fan-out warning with
|
|
7
|
+
* a different number, so one refusal showed three different limits.
|
|
8
|
+
*/
|
|
9
|
+
import type { BurnReport } from './types';
|
|
10
|
+
/** Where the person continues from. */
|
|
11
|
+
export type StopHost = 'claude-code' | 'codex' | 'cursor';
|
|
12
|
+
/**
|
|
13
|
+
* The override the person runs. The unscoped `agentguard-burn` launcher runs
|
|
14
|
+
* the latest Burn through npx, so it works for everyone, including plugin-only
|
|
15
|
+
* installs that never put a Burn binary on PATH, and it has no "@" for X to
|
|
16
|
+
* turn into a mention link when it is quoted in a post.
|
|
17
|
+
*/
|
|
18
|
+
export declare const OVERRIDE_COMMAND = "npx agentguard-burn resume --once --reason \"...\"";
|
|
19
|
+
/** The one limit that stopped this launch, in its own words and numbers. */
|
|
20
|
+
export declare function stopSummary(report: BurnReport): string;
|
|
21
|
+
/** The finding a one-line message should lead with: the STOP, else the first WARN, else the first finding. */
|
|
22
|
+
export declare function primarySummary(report: BurnReport): string;
|
|
23
|
+
export declare function sessionSoFar(report: BurnReport, subject?: 'spawn' | 'call'): string;
|
|
24
|
+
/**
|
|
25
|
+
* How the person continues once. In Claude Code a command typed with `!` runs
|
|
26
|
+
* in the person's own shell and never passes through a hook, so it is the
|
|
27
|
+
* person's key; the same command attempted by the agent is refused.
|
|
28
|
+
*/
|
|
29
|
+
export declare function continueLines(host: StopHost | undefined, subject?: 'spawn' | 'call'): [string, string];
|
|
30
|
+
/**
|
|
31
|
+
* The text of Claude Code's permission prompt when a STOP holds a launch.
|
|
32
|
+
* Claude Code shows this to the person and not to Claude.
|
|
33
|
+
*/
|
|
34
|
+
export declare function askReason(report: BurnReport): string;
|
|
35
|
+
/** The line after a person-approved override, naming the limit it passed. */
|
|
36
|
+
export declare function overriddenLine(report: BurnReport, override: {
|
|
37
|
+
once: boolean;
|
|
38
|
+
reason: string;
|
|
39
|
+
}): string;
|