@agentguard-run/burn 0.3.18 → 0.3.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +105 -5
- package/dist/src/canvas.d.ts +7 -1
- package/dist/src/canvas.js +10 -1
- package/dist/src/cli.js +101 -7
- package/dist/src/frames.d.ts +10 -0
- package/dist/src/frames.js +5 -0
- package/dist/src/history/claude-transcript.d.ts +26 -1
- package/dist/src/history/claude-transcript.js +58 -2
- package/dist/src/hook/pre-tool-use.d.ts +6 -2
- package/dist/src/hook/pre-tool-use.js +35 -8
- package/dist/src/insights/calendar-render.d.ts +48 -0
- package/dist/src/insights/calendar-render.js +196 -0
- package/dist/src/insights/calendar.d.ts +138 -0
- package/dist/src/insights/calendar.js +431 -0
- package/dist/src/insights/compare.d.ts +104 -0
- package/dist/src/insights/compare.js +210 -0
- package/dist/src/insights/i18n.d.ts +134 -8
- package/dist/src/insights/i18n.js +200 -13
- package/dist/src/insights/render.d.ts +93 -13
- package/dist/src/insights/render.js +212 -28
- package/dist/src/insights/sessions.d.ts +25 -0
- package/dist/src/insights/sessions.js +72 -5
- package/dist/src/insights/transcript.d.ts +13 -2
- package/dist/src/insights/transcript.js +61 -6
- package/dist/src/insights/types.d.ts +17 -0
- package/dist/src/insights/types.js +3 -1
- package/dist/src/recording.js +5 -1
- package/dist/src/replay/render.d.ts +2 -0
- package/dist/src/replay/render.js +4 -0
- package/dist/src/stop-text.d.ts +16 -5
- package/dist/src/stop-text.js +28 -6
- package/dist/src/subagent-cost.d.ts +38 -0
- package/dist/src/subagent-cost.js +65 -0
- package/package.json +1 -1
|
@@ -160,6 +160,12 @@ function observeImageBlocks(raw, state) {
|
|
|
160
160
|
state.imagesDroppedPending = (state.imagesDroppedPending ?? 0) + (previous - current);
|
|
161
161
|
state.imageBlocksByMessage[key] = current;
|
|
162
162
|
}
|
|
163
|
+
/** A /clear that Claude Code wrote into this transcript as a command record. Only the command name is matched; nothing of the message is kept. */
|
|
164
|
+
function isClearCommand(content) {
|
|
165
|
+
const texts = typeof content === 'string' ? [content]
|
|
166
|
+
: Array.isArray(content) ? content.map(block => object(block).text).filter((text) => typeof text === 'string') : [];
|
|
167
|
+
return texts.some(text => text.includes('<command-name>/clear</command-name>'));
|
|
168
|
+
}
|
|
163
169
|
function emptyInterval() {
|
|
164
170
|
return { toolOutputBytes: 0, reReadBytes: 0, conversationBytes: 0, toolResults: 0, userMessages: 0, shared: false };
|
|
165
171
|
}
|
|
@@ -374,6 +380,18 @@ function parseInsightTranscript(text, options = {}) {
|
|
|
374
380
|
if ((raw.type === 'system' && raw.subtype === 'compact_boundary') || raw.type === 'compacted' ||
|
|
375
381
|
payload.type === 'context_compacted' || payload.type === 'compaction')
|
|
376
382
|
state.compactionPending = true;
|
|
383
|
+
// The reset and its time, for the measured change `why` prints around it.
|
|
384
|
+
// Claude Code records whether a compaction was /compact or automatic.
|
|
385
|
+
if (raw.type === 'system' && raw.subtype === 'compact_boundary') {
|
|
386
|
+
const trigger = object(raw.compactMetadata).trigger;
|
|
387
|
+
state.pendingReset = { kind: 'compact', ...(trigger === 'manual' || trigger === 'auto' ? { trigger } : {}), ...(at !== undefined ? { at } : {}) };
|
|
388
|
+
}
|
|
389
|
+
else if (raw.type === 'compacted' || payload.type === 'context_compacted' || payload.type === 'compaction') {
|
|
390
|
+
state.pendingReset = { kind: 'compact', ...(at !== undefined ? { at } : {}) };
|
|
391
|
+
}
|
|
392
|
+
else if (raw.type === 'user' && isClearCommand(message.content)) {
|
|
393
|
+
state.pendingReset = { kind: 'clear', ...(at !== undefined ? { at } : {}) };
|
|
394
|
+
}
|
|
377
395
|
const prefix = raw.prompt_prefix_hash ?? raw.prefix_hash ?? message.prompt_prefix_hash ?? payload.prompt_prefix_hash ?? payload.prefix_hash;
|
|
378
396
|
const prefixDigest = typeof prefix === 'string' && prefix.length <= 256 ? digest(prefix) : undefined;
|
|
379
397
|
const changedPrefix = prefixDigest && state.prefixDigest ? prefixDigest !== state.prefixDigest : undefined;
|
|
@@ -455,7 +473,8 @@ function parseInsightTranscript(text, options = {}) {
|
|
|
455
473
|
...(state.prefixChangedPending !== undefined ? { prefixChanged: state.prefixChangedPending } : {}),
|
|
456
474
|
...(modelChanged ? { modelChanged: true, previousModel: state.lastTurnModel } : {}),
|
|
457
475
|
...(versionChanged ? { versionChanged: true, previousHostVersion: state.lastTurnVersion } : {}),
|
|
458
|
-
...(state.imagesDroppedPending ? { imagesDropped: state.imagesDroppedPending } : {})
|
|
476
|
+
...(state.imagesDroppedPending ? { imagesDropped: state.imagesDroppedPending } : {}),
|
|
477
|
+
...(state.pendingReset ? { reset: state.pendingReset } : {}) },
|
|
459
478
|
explicitAttribution: explicitAttribution(usage), uncertainties,
|
|
460
479
|
interval: existing?.interval ?? { ...state.pendingInterval } };
|
|
461
480
|
if (existing) {
|
|
@@ -484,6 +503,7 @@ function parseInsightTranscript(text, options = {}) {
|
|
|
484
503
|
state.compactionPending = false;
|
|
485
504
|
state.prefixChangedPending = undefined;
|
|
486
505
|
state.imagesDroppedPending = 0;
|
|
506
|
+
state.pendingReset = undefined;
|
|
487
507
|
state.lastTurnModel = state.model;
|
|
488
508
|
state.lastTurnVersion = state.hostVersion;
|
|
489
509
|
seenCount++;
|
|
@@ -496,12 +516,47 @@ function parseInsightTranscript(text, options = {}) {
|
|
|
496
516
|
return { host: state.host, sessionId: state.sessionId, turns: Object.values(state.seen), updatedTurns: [...updated.values()], diagnostics, state,
|
|
497
517
|
observations: observations(state.observedCalls ?? {}), acceptedQuotaLineNumbers };
|
|
498
518
|
}
|
|
499
|
-
|
|
500
|
-
|
|
519
|
+
const DIAGNOSTIC_KEYS = ['lines', 'malformedLines', 'duplicateUsageRecords', 'unsupportedUsageRecords', 'inheritedUsageRecords'];
|
|
520
|
+
function parseFile(filename, options, read) {
|
|
521
|
+
const limit = read.chunkBytes;
|
|
522
|
+
if (!limit || !(limit > 0))
|
|
523
|
+
return parseInsightTranscript((0, node_fs_1.readFileSync)(filename, 'utf8'), options);
|
|
524
|
+
const fd = (0, node_fs_1.openSync)(filename, 'r');
|
|
525
|
+
try {
|
|
526
|
+
if ((0, node_fs_1.fstatSync)(fd).size <= limit)
|
|
527
|
+
return parseInsightTranscript((0, node_fs_1.readFileSync)(fd, 'utf8'), options);
|
|
528
|
+
const buffer = Buffer.alloc(limit), totals = { lines: 0, malformedLines: 0, duplicateUsageRecords: 0, unsupportedUsageRecords: 0, inheritedUsageRecords: 0 };
|
|
529
|
+
let result, carry = Buffer.alloc(0), position = 0;
|
|
530
|
+
const parse = (text) => {
|
|
531
|
+
result = parseInsightTranscript(text, result ? { ...options, state: result.state } : options);
|
|
532
|
+
for (const key of DIAGNOSTIC_KEYS)
|
|
533
|
+
totals[key] += result.diagnostics[key] ?? 0;
|
|
534
|
+
};
|
|
535
|
+
for (let length = (0, node_fs_1.readSync)(fd, buffer, 0, limit, position); length > 0; length = (0, node_fs_1.readSync)(fd, buffer, 0, limit, position)) {
|
|
536
|
+
position += length;
|
|
537
|
+
const piece = carry.length ? Buffer.concat([carry, buffer.subarray(0, length)]) : buffer.subarray(0, length);
|
|
538
|
+
const end = piece.lastIndexOf(10);
|
|
539
|
+
if (end < 0) {
|
|
540
|
+
carry = Buffer.from(piece);
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
parse(piece.subarray(0, end + 1).toString('utf8'));
|
|
544
|
+
carry = Buffer.from(piece.subarray(end + 1));
|
|
545
|
+
}
|
|
546
|
+
if (carry.length || !result)
|
|
547
|
+
parse(carry.toString('utf8'));
|
|
548
|
+
return { ...result, diagnostics: totals, updatedTurns: result.turns, acceptedQuotaLineNumbers: undefined };
|
|
549
|
+
}
|
|
550
|
+
finally {
|
|
551
|
+
(0, node_fs_1.closeSync)(fd);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
function readInsightTranscript(filename, options = {}, read = {}) {
|
|
555
|
+
return parseFile(filename, { sessionId: (0, node_path_1.basename)(filename, '.jsonl'), spawnedSession: /(?:^|[\\/])subagents[\\/]/.test(filename), ...options }, read);
|
|
501
556
|
}
|
|
502
557
|
/** Read one Claude session plus its explicitly stored child transcripts. */
|
|
503
|
-
function readInsightSession(filename, options = {}) {
|
|
504
|
-
const parent = readInsightTranscript(filename, options);
|
|
558
|
+
function readInsightSession(filename, options = {}, read = {}) {
|
|
559
|
+
const parent = readInsightTranscript(filename, options, read);
|
|
505
560
|
const childDirectory = (0, node_path_1.join)(filename.replace(/\.jsonl$/, ''), 'subagents');
|
|
506
561
|
let files;
|
|
507
562
|
try {
|
|
@@ -515,7 +570,7 @@ function readInsightSession(filename, options = {}) {
|
|
|
515
570
|
const calls = { ...parent.state.observedCalls };
|
|
516
571
|
const turns = [...parent.turns];
|
|
517
572
|
for (const name of files) {
|
|
518
|
-
const child = readInsightTranscript((0, node_path_1.join)(childDirectory, name), { host: options.host, spawnedSession: true });
|
|
573
|
+
const child = readInsightTranscript((0, node_path_1.join)(childDirectory, name), { host: options.host, spawnedSession: true }, read);
|
|
519
574
|
const known = new Set(turns.map(turn => turn.id));
|
|
520
575
|
const firstOwn = child.turns.findIndex(turn => !known.has(turn.id));
|
|
521
576
|
if (firstOwn > 0 && child.turns.slice(0, firstOwn).some(turn => turn.signals.firstSpawnedTurn)) {
|
|
@@ -18,6 +18,16 @@ export interface InsightInterval {
|
|
|
18
18
|
userMessages: number;
|
|
19
19
|
shared: boolean;
|
|
20
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* A context reset the transcript records just before a usage turn: a compaction
|
|
23
|
+
* (with Claude Code's own trigger when it records one) or a /clear that kept
|
|
24
|
+
* writing to the same transcript. Only the kind, trigger and time are kept.
|
|
25
|
+
*/
|
|
26
|
+
export interface InsightReset {
|
|
27
|
+
kind: 'compact' | 'clear';
|
|
28
|
+
trigger?: 'manual' | 'auto';
|
|
29
|
+
at?: number;
|
|
30
|
+
}
|
|
21
31
|
export interface InsightTurn {
|
|
22
32
|
id: string;
|
|
23
33
|
sessionId: string;
|
|
@@ -51,6 +61,8 @@ export interface InsightTurn {
|
|
|
51
61
|
previousHostVersion?: string;
|
|
52
62
|
/** Image or PDF blocks that an earlier message was re-recorded without, since the previous usage turn. */
|
|
53
63
|
imagesDropped?: number;
|
|
64
|
+
/** The compaction or /clear recorded since the previous usage turn; absent when there was none. */
|
|
65
|
+
reset?: InsightReset;
|
|
54
66
|
};
|
|
55
67
|
explicitAttribution: ExplicitTokenAttribution[];
|
|
56
68
|
uncertainties: string[];
|
|
@@ -118,6 +130,8 @@ export interface InsightParserState {
|
|
|
118
130
|
/** Image or PDF block counts per message identity digest; only counts, never bytes. */
|
|
119
131
|
imageBlocksByMessage?: Record<string, number>;
|
|
120
132
|
imagesDroppedPending?: number;
|
|
133
|
+
/** A compaction or /clear seen since the last usage turn, handed to the next one. */
|
|
134
|
+
pendingReset?: InsightReset;
|
|
121
135
|
}
|
|
122
136
|
export interface InsightObservations {
|
|
123
137
|
readCalls: number;
|
|
@@ -158,6 +172,9 @@ export interface RewriteEvidence {
|
|
|
158
172
|
ttlUnknown: boolean;
|
|
159
173
|
explanation: string;
|
|
160
174
|
}
|
|
175
|
+
/** The rows `compare` prints for each session, in table order. */
|
|
176
|
+
export declare const COMPARE_METRICS: readonly ["assistantResponses", "inputTokens", "cacheReadTokens", "cacheWriteTokens", "freshInputTokens", "cacheShare", "outputTokens", "subagentsLaunched", "fullPrefixRewrites", "usd"];
|
|
177
|
+
export type CompareMetric = typeof COMPARE_METRICS[number];
|
|
161
178
|
export interface BucketAttribution {
|
|
162
179
|
bucket: InsightBucket;
|
|
163
180
|
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/recording.js
CHANGED
|
@@ -43,8 +43,12 @@ function readRecording(file) {
|
|
|
43
43
|
catch {
|
|
44
44
|
throw new Error(`Invalid recording JSON at line ${index + 1}.`);
|
|
45
45
|
}
|
|
46
|
-
if (row?.version !== 1 || typeof row.at !== 'string' || !Number.isFinite(Date.parse(row.at)) || !row.data || !['audit', 'report', 'replay', 'command', 'live', 'bench'].includes(row.data.kind))
|
|
46
|
+
if (row?.version !== 1 || typeof row.at !== 'string' || !Number.isFinite(Date.parse(row.at)) || !row.data || !['audit', 'report', 'replay', 'command', 'live', 'bench', 'calendar'].includes(row.data.kind))
|
|
47
47
|
throw new Error(`Invalid frame at line ${index + 1}.`);
|
|
48
|
+
if (row.data.kind === 'calendar' && (!row.data.report || !Array.isArray(row.data.report.days) || row.data.report.days.length > 7 * 53
|
|
49
|
+
|| typeof row.data.report.from !== 'string' || !Number.isInteger(row.data.report.weeks) || !row.data.report.totals
|
|
50
|
+
|| !['en', 'es', 'pt'].includes(row.data.lang) || !Number.isInteger(row.data.columns) || row.data.columns < 1 || row.data.columns > 500))
|
|
51
|
+
throw new Error(`Invalid calendar frame at line ${index + 1}.`);
|
|
48
52
|
if (row.viewport && (!Number.isInteger(row.viewport.width) || row.viewport.width < 1 || row.viewport.width > 104 || !Number.isInteger(row.viewport.height) || row.viewport.height < 1 || row.viewport.height > 35))
|
|
49
53
|
throw new Error(`Invalid viewport at line ${index + 1}.`);
|
|
50
54
|
if (result.length && Date.parse(row.at) < Date.parse(result.at(-1).at))
|
|
@@ -12,9 +12,11 @@ export declare function renderReplay(summary: ReplaySummary, opts?: {
|
|
|
12
12
|
colour?: boolean;
|
|
13
13
|
top?: number;
|
|
14
14
|
}): string;
|
|
15
|
+
/** `costLine`, when given, is what this session's finished sub-agents averaged; it prints under the "Session so far" line. */
|
|
15
16
|
export declare function renderStop(report: BurnReport, opts?: {
|
|
16
17
|
colour?: boolean;
|
|
17
18
|
subject?: 'spawn' | 'call';
|
|
18
19
|
host?: StopHost;
|
|
20
|
+
costLine?: string | null;
|
|
19
21
|
}): string;
|
|
20
22
|
export declare function renderSessionRow(s: SessionReplay): string;
|
|
@@ -177,6 +177,7 @@ function renderReplay(summary, opts = {}) {
|
|
|
177
177
|
// ---------------------------------------------------------------------------
|
|
178
178
|
// The mid-session STOP box. What Claude shows the user when a spawn is denied.
|
|
179
179
|
// ---------------------------------------------------------------------------
|
|
180
|
+
/** `costLine`, when given, is what this session's finished sub-agents averaged; it prints under the "Session so far" line. */
|
|
180
181
|
function renderStop(report, opts = {}) {
|
|
181
182
|
const on = opts.colour ?? false;
|
|
182
183
|
if (on)
|
|
@@ -193,6 +194,9 @@ function renderStop(report, opts = {}) {
|
|
|
193
194
|
for (const line of wrap((0, stop_text_1.stopSummary)(report), w - 1, ''))
|
|
194
195
|
lines.push(row(line));
|
|
195
196
|
lines.push(row((0, stop_text_1.sessionSoFar)(report, opts.subject), C.dim));
|
|
197
|
+
if (opts.costLine)
|
|
198
|
+
for (const line of wrap(opts.costLine, w - 1, ''))
|
|
199
|
+
lines.push(row(line, C.dim));
|
|
196
200
|
lines.push(paint(on, C.red, `├${bar}┤`));
|
|
197
201
|
lines.push(row('WHAT TO DO', C.bold));
|
|
198
202
|
report.prescriptions.slice(0, 2).forEach((p, i) => {
|
package/dist/src/stop-text.d.ts
CHANGED
|
@@ -10,10 +10,19 @@ import type { BurnReport } from './types';
|
|
|
10
10
|
/** Where the person continues from. */
|
|
11
11
|
export type StopHost = 'claude-code' | 'codex' | 'cursor';
|
|
12
12
|
/**
|
|
13
|
-
* The override the person runs. The
|
|
14
|
-
*
|
|
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.
|
|
15
17
|
*/
|
|
16
|
-
export declare const OVERRIDE_COMMAND = "npx
|
|
18
|
+
export declare const OVERRIDE_COMMAND = "npx agentguard-burn resume --once --reason \"...\"";
|
|
19
|
+
/**
|
|
20
|
+
* A token count as one short figure in en-US digits (850, 85K, 10.0M, 5.02B),
|
|
21
|
+
* the style of the "Session so far" line, for the lines that coach: the `why`
|
|
22
|
+
* tips, the measured change and the cost of one more sub-agent. Rounding moves
|
|
23
|
+
* to the next unit instead of printing 1000K.
|
|
24
|
+
*/
|
|
25
|
+
export declare function shortTokens(n: number): string;
|
|
17
26
|
/** The one limit that stopped this launch, in its own words and numbers. */
|
|
18
27
|
export declare function stopSummary(report: BurnReport): string;
|
|
19
28
|
/** The finding a one-line message should lead with: the STOP, else the first WARN, else the first finding. */
|
|
@@ -27,9 +36,11 @@ export declare function sessionSoFar(report: BurnReport, subject?: 'spawn' | 'ca
|
|
|
27
36
|
export declare function continueLines(host: StopHost | undefined, subject?: 'spawn' | 'call'): [string, string];
|
|
28
37
|
/**
|
|
29
38
|
* The text of Claude Code's permission prompt when a STOP holds a launch.
|
|
30
|
-
* Claude Code shows this to the person and not to Claude.
|
|
39
|
+
* Claude Code shows this to the person and not to Claude. `costLine` is what
|
|
40
|
+
* this session's finished sub-agents averaged (subagentCostLine), when at least
|
|
41
|
+
* three finished; the prompt is then four lines, never more.
|
|
31
42
|
*/
|
|
32
|
-
export declare function askReason(report: BurnReport): string;
|
|
43
|
+
export declare function askReason(report: BurnReport, costLine?: string | null): string;
|
|
33
44
|
/** The line after a person-approved override, naming the limit it passed. */
|
|
34
45
|
export declare function overriddenLine(report: BurnReport, override: {
|
|
35
46
|
once: boolean;
|
package/dist/src/stop-text.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.OVERRIDE_COMMAND = void 0;
|
|
4
|
+
exports.shortTokens = shortTokens;
|
|
4
5
|
exports.stopSummary = stopSummary;
|
|
5
6
|
exports.primarySummary = primarySummary;
|
|
6
7
|
exports.sessionSoFar = sessionSoFar;
|
|
@@ -8,10 +9,12 @@ exports.continueLines = continueLines;
|
|
|
8
9
|
exports.askReason = askReason;
|
|
9
10
|
exports.overriddenLine = overriddenLine;
|
|
10
11
|
/**
|
|
11
|
-
* The override the person runs. The
|
|
12
|
-
*
|
|
12
|
+
* The override the person runs. The unscoped `agentguard-burn` launcher runs
|
|
13
|
+
* the latest Burn through npx, so it works for everyone, including plugin-only
|
|
14
|
+
* installs that never put a Burn binary on PATH, and it has no "@" for X to
|
|
15
|
+
* turn into a mention link when it is quoted in a post.
|
|
13
16
|
*/
|
|
14
|
-
exports.OVERRIDE_COMMAND = 'npx
|
|
17
|
+
exports.OVERRIDE_COMMAND = 'npx agentguard-burn resume --once --reason "..."';
|
|
15
18
|
function fmt(n) {
|
|
16
19
|
if (n >= 1e9)
|
|
17
20
|
return `${(n / 1e9).toFixed(2)}B`;
|
|
@@ -21,6 +24,22 @@ function fmt(n) {
|
|
|
21
24
|
return `${(n / 1e3).toFixed(0)}K`;
|
|
22
25
|
return String(Math.round(n));
|
|
23
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* A token count as one short figure in en-US digits (850, 85K, 10.0M, 5.02B),
|
|
29
|
+
* the style of the "Session so far" line, for the lines that coach: the `why`
|
|
30
|
+
* tips, the measured change and the cost of one more sub-agent. Rounding moves
|
|
31
|
+
* to the next unit instead of printing 1000K.
|
|
32
|
+
*/
|
|
33
|
+
function shortTokens(n) {
|
|
34
|
+
const value = Math.round(Math.max(0, n));
|
|
35
|
+
if (value < 1_000)
|
|
36
|
+
return String(value);
|
|
37
|
+
if (value < 999_500)
|
|
38
|
+
return `${Math.round(value / 1e3)}K`;
|
|
39
|
+
if (value < 999_950_000)
|
|
40
|
+
return `${(value / 1e6).toFixed(1)}M`;
|
|
41
|
+
return `${(value / 1e9).toFixed(2)}B`;
|
|
42
|
+
}
|
|
24
43
|
/** The one limit that stopped this launch, in its own words and numbers. */
|
|
25
44
|
function stopSummary(report) {
|
|
26
45
|
return report.findings.find((f) => f.verdict === 'STOP')?.summary
|
|
@@ -48,10 +67,13 @@ function continueLines(host, subject = 'spawn') {
|
|
|
48
67
|
}
|
|
49
68
|
/**
|
|
50
69
|
* The text of Claude Code's permission prompt when a STOP holds a launch.
|
|
51
|
-
* Claude Code shows this to the person and not to Claude.
|
|
70
|
+
* Claude Code shows this to the person and not to Claude. `costLine` is what
|
|
71
|
+
* this session's finished sub-agents averaged (subagentCostLine), when at least
|
|
72
|
+
* three finished; the prompt is then four lines, never more.
|
|
52
73
|
*/
|
|
53
|
-
function askReason(report) {
|
|
54
|
-
return `AgentGuard: ${stopSummary(report)}
|
|
74
|
+
function askReason(report, costLine) {
|
|
75
|
+
return [`AgentGuard: ${stopSummary(report)}`, sessionSoFar(report), ...(costLine ? [costLine] : []),
|
|
76
|
+
'Allow this one launch? If you say no, nothing starts.'].join('\n');
|
|
55
77
|
}
|
|
56
78
|
/** The line after a person-approved override, naming the limit it passed. */
|
|
57
79
|
function overriddenLine(report, override) {
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The cost of one more sub-agent, at the decision: what this session's own
|
|
3
|
+
* finished sub-agents averaged, for the STOP prompt and box.
|
|
4
|
+
*
|
|
5
|
+
* Everything comes from state the Claude Code hook already keeps. While the hook
|
|
6
|
+
* reads each child transcript's new bytes (as it always has, for the session
|
|
7
|
+
* totals) it adds that child's usage up by model, and while it reads the parent
|
|
8
|
+
* transcript it notes which sub-agents Claude Code records as completed. Nothing
|
|
9
|
+
* here opens a transcript, so the line costs the hook no extra read.
|
|
10
|
+
*/
|
|
11
|
+
import type { ReaderCursor } from './history/claude-transcript';
|
|
12
|
+
import { type WhyLang } from './insights/i18n';
|
|
13
|
+
import { type DollarRange, type PricingTable } from './insights/pricing';
|
|
14
|
+
/** Fewer finished sub-agents than this say too little about the next one, so the line is left out. */
|
|
15
|
+
export declare const MIN_FINISHED_SUBAGENTS = 3;
|
|
16
|
+
export interface FinishedSubagents {
|
|
17
|
+
/** Completed sub-agents whose transcripts were measured from their first byte. */
|
|
18
|
+
count: number;
|
|
19
|
+
/** Mean tokens per finished sub-agent: input, cache writes, cache reads and output. */
|
|
20
|
+
meanTokens: number;
|
|
21
|
+
/** Mean API list-price equivalent per finished sub-agent; null when any of them has an unpriced model. */
|
|
22
|
+
meanUsd: DollarRange | null;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The sub-agents a session's transcripts record as completed (Claude Code's
|
|
26
|
+
* `agent-<id>.jsonl` children), each measured from its first byte; null when
|
|
27
|
+
* fewer than three qualify. A child an older Burn had already read part of has
|
|
28
|
+
* no measurement and is left out rather than undercounted. `priced` false
|
|
29
|
+
* leaves the dollars out.
|
|
30
|
+
*/
|
|
31
|
+
export declare function finishedSubagents(cursor: Pick<ReaderCursor, 'children' | 'completed'>, rates?: PricingTable, priced?: boolean): FinishedSubagents | null;
|
|
32
|
+
/**
|
|
33
|
+
* "The 15 sub-agents that finished in this session averaged 10.0M tokens each
|
|
34
|
+
* ($4.99 at API prices, not a bill). This one could differ." A measured average
|
|
35
|
+
* of what already ran, never a forecast; null without a summary. The STOP text
|
|
36
|
+
* is English on every host, so the hook passes 'en'.
|
|
37
|
+
*/
|
|
38
|
+
export declare function subagentCostLine(summary: FinishedSubagents | null, lang?: WhyLang): string | null;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MIN_FINISHED_SUBAGENTS = void 0;
|
|
4
|
+
exports.finishedSubagents = finishedSubagents;
|
|
5
|
+
exports.subagentCostLine = subagentCostLine;
|
|
6
|
+
const i18n_1 = require("./insights/i18n");
|
|
7
|
+
const live_1 = require("./insights/live");
|
|
8
|
+
const pricing_1 = require("./insights/pricing");
|
|
9
|
+
const stop_text_1 = require("./stop-text");
|
|
10
|
+
/** Fewer finished sub-agents than this say too little about the next one, so the line is left out. */
|
|
11
|
+
exports.MIN_FINISHED_SUBAGENTS = 3;
|
|
12
|
+
const rateOf = (model, rates) => Object.hasOwn(rates, model) ? rates[model] : Object.hasOwn(pricing_1.MODEL_PRICING, model) ? pricing_1.MODEL_PRICING[model] : undefined;
|
|
13
|
+
/** One child's list price, model by model; null when any model is unpriced. */
|
|
14
|
+
function childUsd(usage, rates) {
|
|
15
|
+
let total = { min: 0, max: 0 };
|
|
16
|
+
for (const [model, [input, output, write, read, fiveMinute, oneHour]] of usage) {
|
|
17
|
+
const rate = model ? rateOf(model, rates) : undefined;
|
|
18
|
+
// A long-context tier applies per request, which a sum of requests cannot show: such a model stays unpriced here.
|
|
19
|
+
const price = rate && !rate.longContext ? (0, pricing_1.priceTurn)({ id: model, sessionId: '', host: 'claude', model,
|
|
20
|
+
inputTokens: input, outputTokens: output, cacheWriteTokens: write, cacheReadTokens: read, cacheWrite5mTokens: fiveMinute, cacheWrite1hTokens: oneHour,
|
|
21
|
+
signals: { afterCompaction: false, firstSpawnedTurn: false }, explicitAttribution: [], uncertainties: [] }, rates).usd : null;
|
|
22
|
+
total = total && price ? { min: total.min + price.min, max: total.max + price.max } : null;
|
|
23
|
+
}
|
|
24
|
+
return total;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The sub-agents a session's transcripts record as completed (Claude Code's
|
|
28
|
+
* `agent-<id>.jsonl` children), each measured from its first byte; null when
|
|
29
|
+
* fewer than three qualify. A child an older Burn had already read part of has
|
|
30
|
+
* no measurement and is left out rather than undercounted. `priced` false
|
|
31
|
+
* leaves the dollars out.
|
|
32
|
+
*/
|
|
33
|
+
function finishedSubagents(cursor, rates = {}, priced = true) {
|
|
34
|
+
if (!cursor.completed?.size || !cursor.children?.size)
|
|
35
|
+
return null;
|
|
36
|
+
const rows = [];
|
|
37
|
+
for (const [name, child] of cursor.children) {
|
|
38
|
+
const id = /^agent-([A-Za-z0-9_-]{1,64})\.jsonl$/.exec(name)?.[1];
|
|
39
|
+
if (!id || !cursor.completed.has(id) || !child.usage)
|
|
40
|
+
continue;
|
|
41
|
+
let tokens = 0;
|
|
42
|
+
for (const [input, output, write, read] of child.usage.values())
|
|
43
|
+
tokens += input + output + write + read;
|
|
44
|
+
if (tokens > 0)
|
|
45
|
+
rows.push({ tokens, usd: priced ? childUsd(child.usage, rates) : null });
|
|
46
|
+
}
|
|
47
|
+
if (rows.length < exports.MIN_FINISHED_SUBAGENTS)
|
|
48
|
+
return null;
|
|
49
|
+
const count = rows.length;
|
|
50
|
+
const meanUsd = rows.every(row => row.usd !== null)
|
|
51
|
+
? { min: rows.reduce((sum, row) => sum + row.usd.min, 0) / count, max: rows.reduce((sum, row) => sum + row.usd.max, 0) / count }
|
|
52
|
+
: null;
|
|
53
|
+
return { count, meanTokens: rows.reduce((sum, row) => sum + row.tokens, 0) / count, meanUsd };
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* "The 15 sub-agents that finished in this session averaged 10.0M tokens each
|
|
57
|
+
* ($4.99 at API prices, not a bill). This one could differ." A measured average
|
|
58
|
+
* of what already ran, never a forecast; null without a summary. The STOP text
|
|
59
|
+
* is English on every host, so the hook passes 'en'.
|
|
60
|
+
*/
|
|
61
|
+
function subagentCostLine(summary, lang = 'en') {
|
|
62
|
+
if (!summary)
|
|
63
|
+
return null;
|
|
64
|
+
return i18n_1.DECISION_TEXT[lang].finished(summary.count, (0, stop_text_1.shortTokens)(summary.meanTokens), summary.meanUsd ? (0, live_1.dollars)(summary.meanUsd, i18n_1.WHY_TEXT[lang]) : null);
|
|
65
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentguard-run/burn",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.20",
|
|
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
|
"type": "commonjs",
|