@agentguard-run/burn 0.3.19 → 0.3.21
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 +41 -0
- package/README.md +63 -2
- package/dist/src/canvas.d.ts +7 -1
- package/dist/src/canvas.js +10 -1
- package/dist/src/cli.js +70 -6
- package/dist/src/frames.d.ts +10 -0
- package/dist/src/frames.js +5 -0
- package/dist/src/gateway.js +11 -7
- package/dist/src/history/claude-transcript.d.ts +63 -1
- package/dist/src/history/claude-transcript.js +105 -2
- package/dist/src/hook/pre-tool-use.d.ts +2 -10
- package/dist/src/hook/pre-tool-use.js +9 -18
- package/dist/src/index.d.ts +4 -1
- package/dist/src/index.js +18 -2
- package/dist/src/insights/calendar-render.d.ts +71 -0
- package/dist/src/insights/calendar-render.js +251 -0
- package/dist/src/insights/calendar.d.ts +138 -0
- package/dist/src/insights/calendar.js +431 -0
- package/dist/src/insights/i18n.d.ts +103 -6
- package/dist/src/insights/i18n.js +123 -7
- package/dist/src/insights/render.d.ts +85 -12
- package/dist/src/insights/render.js +207 -17
- package/dist/src/insights/session-tip.d.ts +33 -0
- package/dist/src/insights/session-tip.js +32 -0
- package/dist/src/insights/sessions.d.ts +6 -0
- package/dist/src/insights/sessions.js +15 -4
- package/dist/src/insights/transcript.d.ts +13 -2
- package/dist/src/insights/transcript.js +61 -6
- package/dist/src/insights/types.d.ts +14 -0
- package/dist/src/policy.d.ts +25 -0
- package/dist/src/policy.js +82 -9
- 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 +11 -2
- package/dist/src/stop-text.js +23 -3
- package/dist/src/subagent-cost.d.ts +49 -0
- package/dist/src/subagent-cost.js +90 -0
- package/package.json +5 -1
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sessionTip = sessionTip;
|
|
4
|
+
const node_os_1 = require("node:os");
|
|
5
|
+
const node_path_1 = require("node:path");
|
|
6
|
+
const policy_1 = require("../policy");
|
|
7
|
+
const live_1 = require("./live");
|
|
8
|
+
const render_1 = require("./render");
|
|
9
|
+
const sessions_1 = require("./sessions");
|
|
10
|
+
const transcript_1 = require("./transcript");
|
|
11
|
+
/** A transcript larger than this is read in pieces of this size, as `calendar` reads it. */
|
|
12
|
+
const CHUNK_BYTES = 16 * 1024 * 1024;
|
|
13
|
+
/**
|
|
14
|
+
* The "Next: ..." line `why <transcriptPath>` ends with, or null when nothing
|
|
15
|
+
* stands out. The transcript is read as `why` reads it: Codex when the path is
|
|
16
|
+
* a rollout, Claude Code otherwise, with every sub-agent transcript in the
|
|
17
|
+
* session's `subagents` folder, priced with the home's overrides. The words and
|
|
18
|
+
* figures come from the function `why` prints the tip with, so the two cannot
|
|
19
|
+
* differ. A long transcript is read in pieces cut at line ends, which gives the
|
|
20
|
+
* same turns as reading it whole and keeps it out of memory as one string. It
|
|
21
|
+
* ignores the quiet flag (the caller decides whether to show the line), writes
|
|
22
|
+
* nothing, and throws when the path is not a transcript file.
|
|
23
|
+
*/
|
|
24
|
+
function sessionTip(transcriptPath, options = {}) {
|
|
25
|
+
const location = (0, sessions_1.transcriptFileLocation)(transcriptPath);
|
|
26
|
+
if (!location)
|
|
27
|
+
throw new Error('Session transcript not found. Pass its local JSONL path.');
|
|
28
|
+
const home = options.home ?? process.env.AGENTGUARD_HOME ?? (0, node_path_1.join)((0, node_os_1.homedir)(), '.agentguard');
|
|
29
|
+
const rates = options.rates ?? (0, live_1.readPricing)(home, (0, policy_1.loadPolicy)(home, { notice: false }));
|
|
30
|
+
const transcript = (0, transcript_1.readInsightSession)(location.path, { host: location.host, sessionId: location.sessionId }, { chunkBytes: options.chunkBytes ?? CHUNK_BYTES });
|
|
31
|
+
return (0, render_1.whyTipLine)(transcript, rates, options.lang ?? 'en', options.context === 'plugin' ? 'plugin' : 'why');
|
|
32
|
+
}
|
|
@@ -14,6 +14,12 @@ export declare function discoverInsightTranscripts(roots?: {
|
|
|
14
14
|
claude: string;
|
|
15
15
|
codex: string;
|
|
16
16
|
}): TranscriptLocation[];
|
|
17
|
+
/**
|
|
18
|
+
* A transcript named by its path, as `why <path>` reads it: Codex when the path
|
|
19
|
+
* is a rollout or sits under `.codex`, Claude Code otherwise, and the session id
|
|
20
|
+
* from the file name. Null when the path is not a file.
|
|
21
|
+
*/
|
|
22
|
+
export declare function transcriptFileLocation(file: string): TranscriptLocation | null;
|
|
17
23
|
export declare function selectInsightTranscript(session?: string, locations?: TranscriptLocation[]): TranscriptLocation;
|
|
18
24
|
/**
|
|
19
25
|
* A file Claude Code keeps inside a session's own directory, such as
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.transcriptRoots = transcriptRoots;
|
|
4
4
|
exports.discoverInsightTranscripts = discoverInsightTranscripts;
|
|
5
|
+
exports.transcriptFileLocation = transcriptFileLocation;
|
|
5
6
|
exports.selectInsightTranscript = selectInsightTranscript;
|
|
6
7
|
exports.isSessionSidecar = isSessionSidecar;
|
|
7
8
|
exports.isSubagentTranscript = isSubagentTranscript;
|
|
@@ -43,12 +44,22 @@ function discoverInsightTranscripts(roots = transcriptRoots()) {
|
|
|
43
44
|
visit(roots.codex, 'codex', 0);
|
|
44
45
|
return found.sort((a, b) => b.modifiedAt - a.modifiedAt || a.path.localeCompare(b.path));
|
|
45
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* A transcript named by its path, as `why <path>` reads it: Codex when the path
|
|
49
|
+
* is a rollout or sits under `.codex`, Claude Code otherwise, and the session id
|
|
50
|
+
* from the file name. Null when the path is not a file.
|
|
51
|
+
*/
|
|
52
|
+
function transcriptFileLocation(file) {
|
|
53
|
+
if (!file || !(0, node_fs_1.existsSync)(file) || !(0, node_fs_1.statSync)(file).isFile())
|
|
54
|
+
return null;
|
|
55
|
+
const path = (0, node_path_1.resolve)(file);
|
|
56
|
+
return { path, host: /(?:rollout-|[\\/]\.codex[\\/])/.test(path) ? 'codex' : 'claude', sessionId: (0, node_path_1.basename)(path, '.jsonl'), modifiedAt: (0, node_fs_1.statSync)(path).mtimeMs };
|
|
57
|
+
}
|
|
46
58
|
function selectInsightTranscript(session, locations) {
|
|
47
59
|
const requested = session || process.env.AGENTGUARD_SESSION_ID || process.env.CLAUDE_SESSION_ID || process.env.CODEX_THREAD_ID;
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
return
|
|
51
|
-
}
|
|
60
|
+
const file = requested ? transcriptFileLocation(requested) : null;
|
|
61
|
+
if (file)
|
|
62
|
+
return file;
|
|
52
63
|
const candidates = locations ?? discoverInsightTranscripts();
|
|
53
64
|
// With nothing requested, the newest top-level session wins. A subagent's own
|
|
54
65
|
// transcript (Claude Code keeps them under <session>/subagents/agent-*.jsonl) is
|
|
@@ -7,8 +7,19 @@ export declare const providerResponseIdentity: (host: InsightHost, id: unknown)
|
|
|
7
7
|
* to previous totals because an assistant message can gain output usage later.
|
|
8
8
|
*/
|
|
9
9
|
export declare function parseInsightTranscript(text: string, options?: InsightParseOptions): InsightTranscript;
|
|
10
|
-
|
|
10
|
+
/** How a transcript file is read, never how it is parsed. */
|
|
11
|
+
export interface InsightReadOptions {
|
|
12
|
+
/**
|
|
13
|
+
* A file larger than this many bytes is read in pieces cut at line ends, each
|
|
14
|
+
* parsed with the parser state the previous piece returned, so no single string
|
|
15
|
+
* holds the whole file (V8 cannot hold a string past about 512 MB). The turns,
|
|
16
|
+
* observations and summed diagnostics equal a whole-file parse. Unset reads the
|
|
17
|
+
* whole file at once, as `why` does.
|
|
18
|
+
*/
|
|
19
|
+
chunkBytes?: number;
|
|
20
|
+
}
|
|
21
|
+
export declare function readInsightTranscript(filename: string, options?: InsightParseOptions, read?: InsightReadOptions): InsightTranscript;
|
|
11
22
|
/** Read one Claude session plus its explicitly stored child transcripts. */
|
|
12
|
-
export declare function readInsightSession(filename: string, options?: InsightParseOptions): InsightTranscript;
|
|
23
|
+
export declare function readInsightSession(filename: string, options?: InsightParseOptions, read?: InsightReadOptions): InsightTranscript;
|
|
13
24
|
/** Forked transcript copies can repeat provider response ids across files. */
|
|
14
25
|
export declare function deduplicateTurns(turns: InsightTurn[]): InsightTurn[];
|
|
@@ -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;
|
package/dist/src/policy.d.ts
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
import type { Policy } from './types';
|
|
2
2
|
/** Normalize before evaluating or hashing so receipts bind the actual policy. */
|
|
3
3
|
export declare function normalizePolicy(policy: Policy): Policy;
|
|
4
|
+
/** Why a burn-policy.json that exists was not used. */
|
|
5
|
+
export type PolicyFileProblem = 'unreadable' | 'invalid_json' | 'not_object' | 'missing_mode' | 'invalid_mode' | 'missing_thresholds';
|
|
6
|
+
/**
|
|
7
|
+
* The policy file at a home: missing (the defaults apply, as intended), loaded,
|
|
8
|
+
* or present but ignored, with every reason and one plain line that says so.
|
|
9
|
+
*/
|
|
10
|
+
export type PolicyFileCheck = {
|
|
11
|
+
status: 'missing';
|
|
12
|
+
file: string;
|
|
13
|
+
} | {
|
|
14
|
+
status: 'loaded';
|
|
15
|
+
file: string;
|
|
16
|
+
} | {
|
|
17
|
+
status: 'ignored';
|
|
18
|
+
file: string;
|
|
19
|
+
problems: PolicyFileProblem[];
|
|
20
|
+
line: string;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Whether the home's burn-policy.json is missing, loaded or ignored, decided
|
|
24
|
+
* exactly as loadPolicy decides. An ignored file leaves the defaults in place,
|
|
25
|
+
* which only watch, so a hand-edited file with a mistake would otherwise turn
|
|
26
|
+
* enforcement off without a word. Reads the file; writes nothing.
|
|
27
|
+
*/
|
|
28
|
+
export declare function checkPolicyFile(home: string): PolicyFileCheck;
|
|
4
29
|
export declare function loadPolicy(home: string, options?: {
|
|
5
30
|
notice?: boolean;
|
|
6
31
|
}): Policy;
|
package/dist/src/policy.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.normalizePolicy = normalizePolicy;
|
|
4
|
+
exports.checkPolicyFile = checkPolicyFile;
|
|
4
5
|
exports.loadPolicy = loadPolicy;
|
|
5
6
|
/** Load additive policy defaults without rewriting the operator's policy. */
|
|
6
7
|
const node_fs_1 = require("node:fs");
|
|
8
|
+
const node_os_1 = require("node:os");
|
|
7
9
|
const node_path_1 = require("node:path");
|
|
8
10
|
const defaults_1 = require("./defaults");
|
|
9
11
|
const noticed = new Set();
|
|
@@ -82,22 +84,93 @@ function noticeOnce(home, fields) {
|
|
|
82
84
|
}
|
|
83
85
|
process.stderr.write(`AgentGuard loaded missing policy fields from defaults: ${fields.join(', ')}; existing overrides are unchanged.\n`);
|
|
84
86
|
}
|
|
85
|
-
|
|
87
|
+
const REASON = {
|
|
88
|
+
unreadable: "it can't be read",
|
|
89
|
+
invalid_json: 'it is not valid JSON',
|
|
90
|
+
not_object: 'it is not a JSON object',
|
|
91
|
+
missing_mode: 'it has no "mode"',
|
|
92
|
+
invalid_mode: 'its "mode" is not "enforce" or "shadow"',
|
|
93
|
+
missing_thresholds: 'it has no "thresholds"',
|
|
94
|
+
};
|
|
95
|
+
const FIX = {
|
|
96
|
+
unreadable: 'Make it readable',
|
|
97
|
+
invalid_json: 'Fix the JSON',
|
|
98
|
+
not_object: 'Write it as {"mode": "enforce", "thresholds": {}}',
|
|
99
|
+
missing_mode: 'Add "mode": "enforce"',
|
|
100
|
+
invalid_mode: 'Set "mode" to "enforce"',
|
|
101
|
+
missing_thresholds: 'Add "thresholds": {}',
|
|
102
|
+
};
|
|
103
|
+
/** The path as a person types it: ~ for their home directory. */
|
|
104
|
+
function shownPath(file) {
|
|
105
|
+
const home = (0, node_os_1.homedir)();
|
|
106
|
+
return home && file.startsWith(home + node_path_1.sep) ? `~${file.slice(home.length)}` : file;
|
|
107
|
+
}
|
|
108
|
+
function ignored(file, problems, mode) {
|
|
109
|
+
// A file whose mode already says "shadow" only watches anyway; the fix makes it count again.
|
|
110
|
+
const lost = mode === 'shadow' ? 'so AgentGuard uses it' : 'to turn limits back on';
|
|
111
|
+
const reason = problems.length === 2 && problems[1] === 'missing_thresholds'
|
|
112
|
+
? problems[0] === 'missing_mode' ? 'it has no "mode" and no "thresholds"' : `${REASON[problems[0]]}, and it has no "thresholds"`
|
|
113
|
+
: REASON[problems[0]];
|
|
114
|
+
const fix = problems.length === 2 ? `${FIX[problems[0]]} and ${problems[0] === 'missing_mode' ? '' : 'add '}"thresholds": {}` : FIX[problems[0]];
|
|
115
|
+
return { status: 'ignored', file, problems,
|
|
116
|
+
line: `AgentGuard ignored ${shownPath(file)}: ${reason}. Using the defaults, which only watch. ${fix} ${lost}.` };
|
|
117
|
+
}
|
|
118
|
+
/** What loadPolicy reads: the check, and the parsed policy when the file is used. */
|
|
119
|
+
function readPolicyFile(home) {
|
|
120
|
+
const file = (0, node_path_1.join)(home, 'burn-policy.json');
|
|
121
|
+
let text;
|
|
122
|
+
try {
|
|
123
|
+
text = (0, node_fs_1.readFileSync)(file, 'utf8');
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
const code = error.code;
|
|
127
|
+
return { check: code === 'ENOENT' || code === 'ENOTDIR' ? { status: 'missing', file } : ignored(file, ['unreadable']) };
|
|
128
|
+
}
|
|
129
|
+
let parsed;
|
|
86
130
|
try {
|
|
87
|
-
|
|
88
|
-
|
|
131
|
+
parsed = JSON.parse(text);
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return { check: ignored(file, ['invalid_json']) };
|
|
135
|
+
}
|
|
136
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
137
|
+
return { check: ignored(file, ['not_object']) };
|
|
138
|
+
const { mode, thresholds } = parsed;
|
|
139
|
+
const problems = [];
|
|
140
|
+
if (mode === undefined)
|
|
141
|
+
problems.push('missing_mode');
|
|
142
|
+
else if (mode !== 'shadow' && mode !== 'enforce')
|
|
143
|
+
problems.push('invalid_mode');
|
|
144
|
+
if (!thresholds)
|
|
145
|
+
problems.push('missing_thresholds');
|
|
146
|
+
return problems.length ? { check: ignored(file, problems, mode) } : { check: { status: 'loaded', file }, policy: parsed };
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Whether the home's burn-policy.json is missing, loaded or ignored, decided
|
|
150
|
+
* exactly as loadPolicy decides. An ignored file leaves the defaults in place,
|
|
151
|
+
* which only watch, so a hand-edited file with a mistake would otherwise turn
|
|
152
|
+
* enforcement off without a word. Reads the file; writes nothing.
|
|
153
|
+
*/
|
|
154
|
+
function checkPolicyFile(home) {
|
|
155
|
+
return readPolicyFile(home).check;
|
|
156
|
+
}
|
|
157
|
+
function loadPolicy(home, options = {}) {
|
|
158
|
+
const { policy } = readPolicyFile(home);
|
|
159
|
+
if (policy) {
|
|
160
|
+
try {
|
|
89
161
|
const missing = [];
|
|
90
|
-
if (
|
|
162
|
+
if (policy.thresholds.fanout?.windowActiveMinutes === undefined)
|
|
91
163
|
missing.push('fanout.windowActiveMinutes=120');
|
|
92
|
-
if (
|
|
164
|
+
if (policy.thresholds.spawnRate?.enforce === undefined)
|
|
93
165
|
missing.push('spawnRate.enforce=true');
|
|
94
166
|
if (missing.length && options.notice !== false)
|
|
95
167
|
noticeOnce(home, missing);
|
|
96
|
-
return normalizePolicy(withTeamThresholds(home,
|
|
168
|
+
return normalizePolicy(withTeamThresholds(home, policy));
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
/* unusable after all: shadow defaults */
|
|
97
172
|
}
|
|
98
173
|
}
|
|
99
|
-
|
|
100
|
-
/* no policy yet: shadow defaults */
|
|
101
|
-
}
|
|
174
|
+
// No policy yet, or one that is ignored (checkPolicyFile says why): shadow defaults.
|
|
102
175
|
return normalizePolicy(defaults_1.DEFAULT_POLICY);
|
|
103
176
|
}
|
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
|
@@ -16,6 +16,13 @@ export type StopHost = 'claude-code' | 'codex' | 'cursor';
|
|
|
16
16
|
* turn into a mention link when it is quoted in a post.
|
|
17
17
|
*/
|
|
18
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;
|
|
19
26
|
/** The one limit that stopped this launch, in its own words and numbers. */
|
|
20
27
|
export declare function stopSummary(report: BurnReport): string;
|
|
21
28
|
/** The finding a one-line message should lead with: the STOP, else the first WARN, else the first finding. */
|
|
@@ -29,9 +36,11 @@ export declare function sessionSoFar(report: BurnReport, subject?: 'spawn' | 'ca
|
|
|
29
36
|
export declare function continueLines(host: StopHost | undefined, subject?: 'spawn' | 'call'): [string, string];
|
|
30
37
|
/**
|
|
31
38
|
* 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.
|
|
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.
|
|
33
42
|
*/
|
|
34
|
-
export declare function askReason(report: BurnReport): string;
|
|
43
|
+
export declare function askReason(report: BurnReport, costLine?: string | null): string;
|
|
35
44
|
/** The line after a person-approved override, naming the limit it passed. */
|
|
36
45
|
export declare function overriddenLine(report: BurnReport, override: {
|
|
37
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;
|
|
@@ -23,6 +24,22 @@ function fmt(n) {
|
|
|
23
24
|
return `${(n / 1e3).toFixed(0)}K`;
|
|
24
25
|
return String(Math.round(n));
|
|
25
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
|
+
}
|
|
26
43
|
/** The one limit that stopped this launch, in its own words and numbers. */
|
|
27
44
|
function stopSummary(report) {
|
|
28
45
|
return report.findings.find((f) => f.verdict === 'STOP')?.summary
|
|
@@ -50,10 +67,13 @@ function continueLines(host, subject = 'spawn') {
|
|
|
50
67
|
}
|
|
51
68
|
/**
|
|
52
69
|
* The text of Claude Code's permission prompt when a STOP holds a launch.
|
|
53
|
-
* 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.
|
|
54
73
|
*/
|
|
55
|
-
function askReason(report) {
|
|
56
|
-
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');
|
|
57
77
|
}
|
|
58
78
|
/** The line after a person-approved override, naming the limit it passed. */
|
|
59
79
|
function overriddenLine(report, override) {
|
|
@@ -0,0 +1,49 @@
|
|
|
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
|
+
import type { Policy } from './types';
|
|
15
|
+
/** Fewer finished sub-agents than this say too little about the next one, so the line is left out. */
|
|
16
|
+
export declare const MIN_FINISHED_SUBAGENTS = 3;
|
|
17
|
+
export interface FinishedSubagents {
|
|
18
|
+
/** Completed sub-agents whose transcripts were measured from their first byte. */
|
|
19
|
+
count: number;
|
|
20
|
+
/** Mean tokens per finished sub-agent: input, cache writes, cache reads and output. */
|
|
21
|
+
meanTokens: number;
|
|
22
|
+
/** Mean API list-price equivalent per finished sub-agent; null when any of them has an unpriced model. */
|
|
23
|
+
meanUsd: DollarRange | null;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The sub-agents a session's transcripts record as completed (Claude Code's
|
|
27
|
+
* `agent-<id>.jsonl` children), each measured from its first byte; null when
|
|
28
|
+
* fewer than three qualify. A child an older Burn had already read part of has
|
|
29
|
+
* no measurement and is left out rather than undercounted. `priced` false
|
|
30
|
+
* leaves the dollars out.
|
|
31
|
+
*/
|
|
32
|
+
export declare function finishedSubagents(cursor: Pick<ReaderCursor, 'children' | 'completed'>, rates?: PricingTable, priced?: boolean): FinishedSubagents | null;
|
|
33
|
+
/**
|
|
34
|
+
* "The 15 sub-agents that finished in this session averaged 10.0M tokens each
|
|
35
|
+
* ($4.99 at API prices, not a bill). This one could differ." A measured average
|
|
36
|
+
* of what already ran, never a forecast; null without a summary. The STOP text
|
|
37
|
+
* is English on every host, so the hook passes 'en'.
|
|
38
|
+
*/
|
|
39
|
+
export declare function subagentCostLine(summary: FinishedSubagents | null, lang?: WhyLang): string | null;
|
|
40
|
+
/**
|
|
41
|
+
* The line a STOP prints, exactly as Burn's own Claude Code hook prints it: the
|
|
42
|
+
* summary of a cursor that readSessionIncremental advanced, priced with the
|
|
43
|
+
* rates `why` uses (burn-pricing.json under `home`, or the policy's pricing
|
|
44
|
+
* file), in English like the rest of the STOP text. Null below three finished
|
|
45
|
+
* sub-agents. Best effort: a pricing file that cannot be read costs the line its
|
|
46
|
+
* dollars, and nothing here throws, so it can never turn a prompt into a
|
|
47
|
+
* failed-closed refusal.
|
|
48
|
+
*/
|
|
49
|
+
export declare function decisionCostLine(cursor: Pick<ReaderCursor, 'children' | 'completed'>, home: string, policy?: Policy): string | null;
|