@agentguard-run/burn 0.3.2 → 0.3.4
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 +13 -0
- package/README.md +103 -2
- package/dist/src/bench-import.d.ts +74 -0
- package/dist/src/bench-import.js +232 -0
- package/dist/src/bench-panel.d.ts +42 -0
- package/dist/src/bench-panel.js +119 -0
- package/dist/src/cli.js +71 -2
- package/dist/src/frames.d.ts +4 -0
- package/dist/src/frames.js +3 -0
- package/dist/src/guard-candidates-ranker.d.ts +27 -0
- package/dist/src/guard-candidates-ranker.js +134 -0
- package/dist/src/guard-candidates.d.ts +34 -0
- package/dist/src/guard-candidates.js +226 -0
- package/dist/src/insights/history.d.ts +34 -0
- package/dist/src/insights/history.js +122 -0
- package/dist/src/insights/limits.d.ts +50 -0
- package/dist/src/insights/limits.js +116 -0
- package/dist/src/insights/price-shadow.d.ts +84 -0
- package/dist/src/insights/price-shadow.js +240 -0
- package/dist/src/recording.js +4 -1
- package/docs/assets/burn-bench-fixture.evidence.json +18 -0
- package/docs/assets/burn-bench-fixture.gif +0 -0
- package/docs/assets/burn-bench-fixture.mp4 +0 -0
- package/docs/assets/burn-bench-fixture.mp4.provenance.json +70 -0
- package/docs/assets/burn-bench-fixture.png +0 -0
- package/docs/assets/burn-bench-fixture.recording.jsonl +8 -0
- package/fixtures/bench-panel-104x35.txt +35 -0
- package/fixtures/bench-panel-80x24.txt +24 -0
- package/fixtures/bench-run/burn-postrun.json +1 -0
- package/fixtures/bench-run/fixture-note.txt +1 -0
- package/fixtures/bench-run/grader.json +1 -0
- package/fixtures/bench-run/ledger.ndjson +8 -0
- package/fixtures/bench-run/manifest.json +1 -0
- package/fixtures/bench-run/measurement-key.json +1 -0
- package/fixtures/bench-run/patch.diff +0 -0
- package/fixtures/bench-run/policy.json +1 -0
- package/fixtures/bench-run/pricing.json +1 -0
- package/fixtures/bench-run/run.json +1 -0
- package/fixtures/bench-run/sensitivity-policy.json +1 -0
- package/fixtures/guard-candidates-ledger.ndjson +11 -0
- package/package.json +7 -4
- package/vendor/disciplinebench/LICENSE +202 -0
- package/vendor/disciplinebench/PROVENANCE.json +17 -0
- package/vendor/disciplinebench/harness/reducer.cjs +168 -0
- package/vendor/disciplinebench/harness/schema.cjs +14 -0
- package/vendor/disciplinebench/harness/util.cjs +23 -0
- package/vendor/disciplinebench/harness/verify.cjs +111 -0
- package/vendor/disciplinebench/schemas/aggregate.json +51 -0
- package/vendor/disciplinebench/schemas/event.json +62 -0
- package/vendor/disciplinebench/schemas/grader.json +38 -0
- package/vendor/disciplinebench/schemas/run.json +197 -0
package/dist/src/cli.js
CHANGED
|
@@ -138,6 +138,21 @@ async function main(argv) {
|
|
|
138
138
|
+ (result.clippedStopHold ? 'The requested end clips the final STOP hold. No decision timestamps were extended.\n' : ''));
|
|
139
139
|
return 0;
|
|
140
140
|
}
|
|
141
|
+
case 'import-bench': {
|
|
142
|
+
const source = rest[0];
|
|
143
|
+
if (!source || source.startsWith('--') || (has('--out') && (!flag('--out') || flag('--out').startsWith('--'))))
|
|
144
|
+
throw new Error('Usage: agentguard-burn import-bench <run-dir> [--out <directory>] [--publisher-key-id <id>]');
|
|
145
|
+
if (has('--publisher-key-id') && (!flag('--publisher-key-id') || flag('--publisher-key-id').startsWith('--')))
|
|
146
|
+
throw new Error('Use --publisher-key-id <trusted-key-id>.');
|
|
147
|
+
const { importBench } = await Promise.resolve().then(() => __importStar(require('./bench-import')));
|
|
148
|
+
const result = await importBench(source, { out: flag('--out'), expectedPublisherKeyId: flag('--publisher-key-id') });
|
|
149
|
+
show({ kind: 'command', command, values: { ...result } }, `Verified DisciplineBench run: ${result.run.run_id}${result.run.fixture ? ' (fixture)' : ''}\n`
|
|
150
|
+
+ `Publisher: ${result.verification.publisher_key_id} | Measurement: ${result.verification.measurement_key_id}\n`
|
|
151
|
+
+ (result.verification.publisher_pinned ? 'Publisher key: pinned\n' : 'Embedded keys prove integrity, not external identity. Use --publisher-key-id to pin a trusted publisher.\n')
|
|
152
|
+
+ `Replay input: ${result.replayPath}\nRound pricing: ${result.pricingPath}\nRecording: ${result.recordingPath}\n`
|
|
153
|
+
+ 'Replay requires --pricing <round-pricing-path>. The recording uses the same signed snapshot.\n');
|
|
154
|
+
return 0;
|
|
155
|
+
}
|
|
141
156
|
case 'ps':
|
|
142
157
|
case 'reap':
|
|
143
158
|
return (0, cli_1.runIdleCommand)(command, rawRest, HOME);
|
|
@@ -206,6 +221,29 @@ async function main(argv) {
|
|
|
206
221
|
return 0;
|
|
207
222
|
}
|
|
208
223
|
case 'replay': {
|
|
224
|
+
// A bench import is a verified projection, not a native transcript. Never send it
|
|
225
|
+
// through the hypothetical-cost replay or this machine's pricing overrides.
|
|
226
|
+
if (rest[0]?.endsWith('.json') || has('--pricing')) {
|
|
227
|
+
const source = rest[0], pricing = flag('--pricing');
|
|
228
|
+
if (!source || source.startsWith('--') || !pricing || pricing.startsWith('--'))
|
|
229
|
+
throw new Error('DisciplineBench replay requires replay.json --pricing <snapshot.json>.');
|
|
230
|
+
if (has('--publisher-key-id') && (!flag('--publisher-key-id') || flag('--publisher-key-id').startsWith('--')))
|
|
231
|
+
throw new Error('Use --publisher-key-id <trusted-key-id>.');
|
|
232
|
+
const { replayBench, renderBenchReplay } = await Promise.resolve().then(() => __importStar(require('./bench-import')));
|
|
233
|
+
const result = await replayBench(source, pricing, { expectedPublisherKeyId: flag('--publisher-key-id') });
|
|
234
|
+
for (const frame of result.frames)
|
|
235
|
+
(0, recording_1.recordFrame)(frame.data, frame.at, frame.viewport);
|
|
236
|
+
if (has('--json'))
|
|
237
|
+
process.stdout.write(JSON.stringify({ run: result.run, verification: result.verification, pricing_sha256: result.pricing_sha256 }, null, 2) + '\n');
|
|
238
|
+
else if (process.stdout.isTTY && !noColor && process.env.NO_COLOR === undefined) {
|
|
239
|
+
const { renderFrame } = await Promise.resolve().then(() => __importStar(require('./frames')));
|
|
240
|
+
const last = result.frames.at(-1);
|
|
241
|
+
process.stdout.write(renderFrame(last.data, { recorded: true, at: last.at }).render() + '\n');
|
|
242
|
+
}
|
|
243
|
+
else
|
|
244
|
+
process.stdout.write(renderBenchReplay(result));
|
|
245
|
+
return 0;
|
|
246
|
+
}
|
|
209
247
|
const policy = (0, pre_tool_use_1.loadPolicy)(HOME);
|
|
210
248
|
const paths = rest.filter((a) => a.endsWith('.jsonl'));
|
|
211
249
|
const targets = paths.length ? paths : (0, simulate_1.discoverTranscripts)();
|
|
@@ -382,7 +420,7 @@ async function main(argv) {
|
|
|
382
420
|
return 0;
|
|
383
421
|
}
|
|
384
422
|
default:
|
|
385
|
-
show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'why', 'rewrites', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|why|rewrites|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|proxy|conformance>\n' +
|
|
423
|
+
show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'why', 'rewrites', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|why|rewrites|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|proxy|conformance>\n' +
|
|
386
424
|
' ps [--json] local agent processes, held memory and workspace disk\n' +
|
|
387
425
|
' render <run.jsonl> --mp4 <out.mp4> [--gif <out.gif>] local recorded-run export\n' +
|
|
388
426
|
' record --session <id> [--from <iso>] [--to <iso>] --out <run.jsonl> reconstruct local ledger frames\n' +
|
|
@@ -390,12 +428,16 @@ async function main(argv) {
|
|
|
390
428
|
' --record <file.jsonl> append structured frames for any command; --no-color keeps plain output\n' +
|
|
391
429
|
' reap numbered interactive SIGTERM, never delete or force-kill\n' +
|
|
392
430
|
' blocks [session|all] stored WARN/STOP receipts and that session\'s child usage\n' +
|
|
431
|
+
' limits [session|all] local plan walls and prior Burn decisions\n' +
|
|
432
|
+
' price-shadow [session|all] local child list-price exposure and sensitivity\n' +
|
|
393
433
|
' why [session] token attribution and API list-price equivalents\n' +
|
|
394
434
|
' rewrites [session|all] full-prefix cache writes by cause\n' +
|
|
395
435
|
' pace [session] ten-minute pace and next-hour projection\n' +
|
|
396
436
|
' statusline [session] one-line local status; accepts Claude status JSON\n' +
|
|
397
437
|
' pricing verified model rates and local overrides\n' +
|
|
398
438
|
' replay [files...] [--json] [--top N] [--min-tokens N]\n' +
|
|
439
|
+
' import-bench <run-dir> [--out <directory>] [--publisher-key-id ID] verify and convert a signed bundle\n' +
|
|
440
|
+
' replay <replay.json> --pricing <snapshot.json> [--json] pinned DisciplineBench replay\n' +
|
|
399
441
|
' calibrate fit thresholds to your history (writes shadow policy)\n' +
|
|
400
442
|
' status mode, shadow observations, eligibility, hook health, every host\n' +
|
|
401
443
|
' init [claude|cursor|codex] [--write] print the hook snippet, or merge it into the config (with a backup)\n' +
|
|
@@ -404,12 +446,39 @@ async function main(argv) {
|
|
|
404
446
|
' resume --once --reason "..." let the next STOP through, once, on any host\n' +
|
|
405
447
|
' resume --reason "..." let STOPs through for 15 minutes; --clear ends it\n' +
|
|
406
448
|
' proxy --upstream http://127.0.0.1:11434 --host ollama|vllm|lm-studio|openai-compatible [--listen 127.0.0.1:18080] [--session ID]\n' +
|
|
407
|
-
' conformance replay the storm and the grind through every adapter shape\n'
|
|
449
|
+
' conformance replay the storm and the grind through every adapter shape\n' +
|
|
450
|
+
'Developer review commands (never installed as hooks):\n' +
|
|
451
|
+
' guard-candidates [--ledger <local.ndjson>] [--out <name.review.json>] [--rank]\n' +
|
|
452
|
+
' deduplicate recorded shell text; --rank explicitly permits jsort provider requests\n');
|
|
408
453
|
return command ? 64 : 0;
|
|
409
454
|
}
|
|
410
455
|
}
|
|
411
456
|
async function run() {
|
|
412
457
|
const parsed = (0, recording_1.recordingArguments)(process.argv.slice(2));
|
|
458
|
+
if (parsed.args[0] === 'limits' || parsed.args[0] === 'price-shadow') {
|
|
459
|
+
if (parsed.file)
|
|
460
|
+
throw new Error('These reports are read-only; recording is not supported.');
|
|
461
|
+
const args = parsed.args.slice(1), json = args.includes('json'), selectors = args.filter(arg => arg !== 'json');
|
|
462
|
+
if (selectors.length > 1 || selectors.some(arg => arg.startsWith('-')))
|
|
463
|
+
throw new Error(`Usage: agentguard-burn ${parsed.args[0]} [session|all] [json]`);
|
|
464
|
+
if (parsed.args[0] === 'limits') {
|
|
465
|
+
const { limitsReport, renderLimits } = await Promise.resolve().then(() => __importStar(require('./insights/limits')));
|
|
466
|
+
const report = limitsReport(HOME, selectors[0]);
|
|
467
|
+
process.stdout.write((json ? JSON.stringify(report, null, 2) : renderLimits(report)) + '\n');
|
|
468
|
+
}
|
|
469
|
+
else {
|
|
470
|
+
const { priceShadowReport, renderPriceShadow } = await Promise.resolve().then(() => __importStar(require('./insights/price-shadow')));
|
|
471
|
+
const report = priceShadowReport(HOME, selectors[0]);
|
|
472
|
+
process.stdout.write((json ? JSON.stringify(report, null, 2) : renderPriceShadow(report)) + '\n');
|
|
473
|
+
}
|
|
474
|
+
return 0;
|
|
475
|
+
}
|
|
476
|
+
if (parsed.args[0] === 'guard-candidates') {
|
|
477
|
+
if (parsed.file)
|
|
478
|
+
throw new Error('guard-candidates creates review files only. --record is not supported.');
|
|
479
|
+
const { runGuardCandidates } = await Promise.resolve().then(() => __importStar(require('./guard-candidates')));
|
|
480
|
+
return runGuardCandidates(HOME, parsed.args.slice(1));
|
|
481
|
+
}
|
|
413
482
|
if (parsed.args[0] === 'record' && parsed.file) {
|
|
414
483
|
const { recordLedgerArguments, validateCompanionRecording } = await Promise.resolve().then(() => __importStar(require('./record-ledger')));
|
|
415
484
|
const options = recordLedgerArguments(parsed.args.slice(1).filter(arg => arg !== '--no-color'));
|
package/dist/src/frames.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** Recorded frames carry observations, not ANSI, screen text or process arguments. */
|
|
2
2
|
import { Canvas } from './canvas';
|
|
3
|
+
import { type BenchPanelSnapshot } from './bench-panel';
|
|
3
4
|
import { type LivePanelSnapshot } from './live-panel';
|
|
4
5
|
import type { AuditReport, AuditRow } from './idle/types';
|
|
5
6
|
import type { BurnReport } from './types';
|
|
@@ -8,6 +9,9 @@ export type AuditFrameReport = Omit<AuditReport, 'processes' | 'rows'> & {
|
|
|
8
9
|
rows: Array<Omit<AuditRow, 'processes'>>;
|
|
9
10
|
};
|
|
10
11
|
export type BurnFrame = {
|
|
12
|
+
kind: 'bench';
|
|
13
|
+
snapshot: BenchPanelSnapshot;
|
|
14
|
+
} | {
|
|
11
15
|
kind: 'live';
|
|
12
16
|
snapshot: LivePanelSnapshot;
|
|
13
17
|
} | {
|
package/dist/src/frames.js
CHANGED
|
@@ -5,6 +5,7 @@ exports.framePageCount = framePageCount;
|
|
|
5
5
|
exports.renderFrame = renderFrame;
|
|
6
6
|
/** Recorded frames carry observations, not ANSI, screen text or process arguments. */
|
|
7
7
|
const canvas_1 = require("./canvas");
|
|
8
|
+
const bench_panel_1 = require("./bench-panel");
|
|
8
9
|
const live_panel_1 = require("./live-panel");
|
|
9
10
|
function auditFrame(command, report) {
|
|
10
11
|
const { processes: ignored, rows, ...metadata } = report;
|
|
@@ -33,6 +34,8 @@ function valueRows(values, prefix = '', depth = 0) {
|
|
|
33
34
|
});
|
|
34
35
|
}
|
|
35
36
|
function renderFrame(data, options = {}) {
|
|
37
|
+
if (data.kind === 'bench')
|
|
38
|
+
return (0, bench_panel_1.renderBenchPanel)(data.snapshot, options);
|
|
36
39
|
if (data.kind === 'live')
|
|
37
40
|
return (0, live_panel_1.renderLivePanel)(data.snapshot, options);
|
|
38
41
|
if (data.kind === 'report' && data.report.verdict === 'STOP') {
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { ReviewOutput } from './guard-candidates';
|
|
2
|
+
export interface RankProvider {
|
|
3
|
+
name: 'typesafe' | 'openrouter';
|
|
4
|
+
url: string;
|
|
5
|
+
model: string;
|
|
6
|
+
key: string;
|
|
7
|
+
}
|
|
8
|
+
export interface RankRequest {
|
|
9
|
+
commands: string[];
|
|
10
|
+
criterion: string;
|
|
11
|
+
provider: RankProvider;
|
|
12
|
+
}
|
|
13
|
+
export interface RankedCommand {
|
|
14
|
+
command: string;
|
|
15
|
+
score: number;
|
|
16
|
+
standardError: number | null;
|
|
17
|
+
comparisons: number;
|
|
18
|
+
}
|
|
19
|
+
export declare function rankProvider(env: NodeJS.ProcessEnv): RankProvider | null;
|
|
20
|
+
/** Require one finite result for every exact input. Never accept partial or invented rows. */
|
|
21
|
+
export declare function parseRankedCommands(text: string, commands: string[]): RankedCommand[];
|
|
22
|
+
export declare function rankWithJsort(request: RankRequest, output: ReviewOutput, runtime?: {
|
|
23
|
+
executable?: string;
|
|
24
|
+
prefixArgs?: string[];
|
|
25
|
+
fetch?: typeof fetch;
|
|
26
|
+
env?: NodeJS.ProcessEnv;
|
|
27
|
+
}): Promise<RankedCommand[]>;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.rankProvider = rankProvider;
|
|
4
|
+
exports.parseRankedCommands = parseRankedCommands;
|
|
5
|
+
exports.rankWithJsort = rankWithJsort;
|
|
6
|
+
/** Optional jsort CLI adapter. All provider requests pass the printed-body gate. */
|
|
7
|
+
const node_child_process_1 = require("node:child_process");
|
|
8
|
+
const node_crypto_1 = require("node:crypto");
|
|
9
|
+
const node_http_1 = require("node:http");
|
|
10
|
+
function rankProvider(env) {
|
|
11
|
+
const typesafe = env.TYPESAFE_API_KEY?.trim(), openrouter = env.OPENROUTER_API_KEY?.trim();
|
|
12
|
+
if (typesafe)
|
|
13
|
+
return { name: 'typesafe', url: 'https://api.typesafe.ai/v1/systemone', model: 'jev-latest', key: typesafe };
|
|
14
|
+
if (openrouter)
|
|
15
|
+
return { name: 'openrouter', url: 'https://openrouter.ai/api/alpha/decisions', model: '~typesafe/jev-latest', key: openrouter };
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
/** Require one finite result for every exact input. Never accept partial or invented rows. */
|
|
19
|
+
function parseRankedCommands(text, commands) {
|
|
20
|
+
const remaining = new Set(commands), ranked = [];
|
|
21
|
+
for (const line of text.split('\n').filter(line => line.trim())) {
|
|
22
|
+
const row = JSON.parse(line);
|
|
23
|
+
if (!row || typeof row.command !== 'string' || !remaining.delete(row.command)
|
|
24
|
+
|| typeof row.jsort_score !== 'number' || !Number.isFinite(row.jsort_score)
|
|
25
|
+
|| !(row.jsort_se === null || typeof row.jsort_se === 'number' && Number.isFinite(row.jsort_se) && row.jsort_se >= 0)
|
|
26
|
+
|| !Number.isSafeInteger(row.jsort_n) || row.jsort_n < 1 || row.jsort_partial === true)
|
|
27
|
+
throw new Error('Invalid or incomplete jsort result.');
|
|
28
|
+
ranked.push({ command: row.command, score: row.jsort_score, standardError: row.jsort_se, comparisons: row.jsort_n });
|
|
29
|
+
}
|
|
30
|
+
if (remaining.size)
|
|
31
|
+
throw new Error('Missing jsort results.');
|
|
32
|
+
return ranked.sort((a, b) => b.score - a.score);
|
|
33
|
+
}
|
|
34
|
+
async function rankWithJsort(request, output, runtime = {}) {
|
|
35
|
+
const { provider, commands, criterion } = request;
|
|
36
|
+
const allowed = new Set(commands), secret = (0, node_crypto_1.randomUUID)(), controllers = new Set();
|
|
37
|
+
const question = { type: 'noul', instructions: `Text A ranks higher than text B on this criterion: "${criterion}"` };
|
|
38
|
+
const input = commands.map(command => JSON.stringify({ command })).join('\n') + '\n';
|
|
39
|
+
// Either HTTPX JSON encoding is valid: literal UTF-8 or six-byte escapes per
|
|
40
|
+
// UTF-16 code unit, for both commands in a comparison. Never truncate input.
|
|
41
|
+
const maxBody = commands.reduce((maximum, command) => Math.max(maximum, command.length * 12 + 4096), 65536);
|
|
42
|
+
let failed = false;
|
|
43
|
+
const server = (0, node_http_1.createServer)(async (req, res) => {
|
|
44
|
+
const fail = (status) => { failed = true; res.writeHead(status).end('{}'); };
|
|
45
|
+
if (req.method !== 'POST' || req.url !== '/' || req.headers.authorization !== `Bearer ${secret}`) {
|
|
46
|
+
fail(403);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const chunks = [];
|
|
50
|
+
let bytes = 0;
|
|
51
|
+
const controller = new AbortController();
|
|
52
|
+
controllers.add(controller);
|
|
53
|
+
const timeout = setTimeout(() => controller.abort(), 20000);
|
|
54
|
+
try {
|
|
55
|
+
for await (const chunk of req) {
|
|
56
|
+
bytes += Buffer.byteLength(chunk);
|
|
57
|
+
if (bytes > maxBody) {
|
|
58
|
+
fail(413);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
chunks.push(Buffer.from(chunk));
|
|
62
|
+
}
|
|
63
|
+
const body = Buffer.concat(chunks), text = body.toString('utf8');
|
|
64
|
+
if (!Buffer.from(text, 'utf8').equals(body)) {
|
|
65
|
+
fail(400);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const parsed = JSON.parse(text);
|
|
69
|
+
const keys = (value) => value && typeof value === 'object' ? Object.keys(value).sort().join(',') : '';
|
|
70
|
+
if (keys(parsed) !== 'model,questions,state' || parsed.model !== provider.model || keys(parsed.state) !== 'A,B'
|
|
71
|
+
|| !allowed.has(parsed.state.A) || !allowed.has(parsed.state.B) || keys(parsed.questions) !== 'q'
|
|
72
|
+
|| keys(parsed.questions.q) !== 'instructions,type' || parsed.questions.q.type !== question.type
|
|
73
|
+
|| parsed.questions.q.instructions !== question.instructions) {
|
|
74
|
+
fail(400);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
// Write and flush the exact body bytes before starting the external request.
|
|
78
|
+
// No headers containing either the provider key or local token are printed.
|
|
79
|
+
await output(`Sending JSON to ${provider.url}:\n${body.toString('utf8')}\n`);
|
|
80
|
+
if (controller.signal.aborted)
|
|
81
|
+
throw new Error('Request timed out before forwarding.');
|
|
82
|
+
const response = await (runtime.fetch ?? fetch)(provider.url, { method: 'POST', body,
|
|
83
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${provider.key}`, 'X-Title': 'AgentGuard Burn guard-candidates' },
|
|
84
|
+
signal: controller.signal, redirect: 'error' });
|
|
85
|
+
const responseBody = await response.text();
|
|
86
|
+
res.writeHead(response.status, { 'Content-Type': 'application/json' }).end(responseBody);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
fail(502);
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
clearTimeout(timeout);
|
|
93
|
+
controllers.delete(controller);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
server.requestTimeout = 25000;
|
|
97
|
+
const parentEnv = runtime.env ?? process.env;
|
|
98
|
+
try {
|
|
99
|
+
await new Promise((resolve, reject) => {
|
|
100
|
+
server.once('error', reject);
|
|
101
|
+
server.listen(0, '127.0.0.1', () => { server.removeListener('error', reject); resolve(); });
|
|
102
|
+
});
|
|
103
|
+
const address = server.address();
|
|
104
|
+
if (!address || typeof address === 'string')
|
|
105
|
+
throw new Error('Local preview gate unavailable.');
|
|
106
|
+
// Do not inherit gateway overrides, model overrides, provider keys, proxies,
|
|
107
|
+
// Python startup code or other credentials. jsort receives only a local token.
|
|
108
|
+
const env = {};
|
|
109
|
+
for (const key of ['PATH', 'HOME', 'USERPROFILE', 'SYSTEMROOT', 'WINDIR', 'TMPDIR', 'TEMP', 'TMP', 'LANG', 'LC_ALL']) {
|
|
110
|
+
if (parentEnv[key] !== undefined)
|
|
111
|
+
env[key] = parentEnv[key];
|
|
112
|
+
}
|
|
113
|
+
Object.assign(env, { JEV_URL: `http://127.0.0.1:${address.port}/`, PYTHONIOENCODING: 'utf-8', PYTHONDONTWRITEBYTECODE: '1',
|
|
114
|
+
[provider.name === 'typesafe' ? 'TYPESAFE_API_KEY' : 'OPENROUTER_API_KEY']: secret });
|
|
115
|
+
const maxChars = commands.reduce((maximum, command) => Math.max(maximum, command.length), 1);
|
|
116
|
+
const args = [...runtime.prefixArgs ?? [], '--jsonl', '--field', 'command', '-o', '--no-cache', '--no-stats',
|
|
117
|
+
'--api', provider.name, '--model', provider.model, '--max-chars', String(maxChars), '--budget', '1', '--timeout', '15', '-j', '8', criterion];
|
|
118
|
+
const stdout = await new Promise((resolve, reject) => {
|
|
119
|
+
const child = (0, node_child_process_1.execFile)(runtime.executable ?? 'jsort', args, { env, encoding: 'utf8', shell: false, windowsHide: true,
|
|
120
|
+
timeout: 300000, maxBuffer: Math.max(1024 * 1024, Buffer.byteLength(input) * 2 + commands.length * 512) }, (error, stdout) => error ? reject(new Error('jsort did not complete.')) : resolve(stdout));
|
|
121
|
+
child.stdin?.on('error', () => { });
|
|
122
|
+
child.stdin?.end(input);
|
|
123
|
+
});
|
|
124
|
+
if (failed)
|
|
125
|
+
throw new Error('A request did not pass the preview gate.');
|
|
126
|
+
return parseRankedCommands(stdout, commands);
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
for (const controller of controllers)
|
|
130
|
+
controller.abort();
|
|
131
|
+
server.closeAllConnections();
|
|
132
|
+
await new Promise(resolve => server.close(() => resolve()));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type RankRequest, type RankedCommand } from './guard-candidates-ranker';
|
|
2
|
+
export declare const GUARD_CRITERION = "how likely is this command to destroy data, leak a secret, escalate privilege, or change infrastructure";
|
|
3
|
+
export interface CandidateOptions {
|
|
4
|
+
ledgers: string[];
|
|
5
|
+
out?: string;
|
|
6
|
+
rank: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface CandidateReview {
|
|
9
|
+
schema: 'agentguard.guard-candidates.review.v1';
|
|
10
|
+
generatedAt: string;
|
|
11
|
+
sources: string[];
|
|
12
|
+
records: number;
|
|
13
|
+
shellRecordsWithoutText: number;
|
|
14
|
+
malformed: Array<{
|
|
15
|
+
source: string;
|
|
16
|
+
line: number;
|
|
17
|
+
}>;
|
|
18
|
+
raw: Array<{
|
|
19
|
+
command: string;
|
|
20
|
+
occurrences: number;
|
|
21
|
+
}>;
|
|
22
|
+
}
|
|
23
|
+
export type ReviewOutput = (text: string) => Promise<void>;
|
|
24
|
+
export type CandidateRanker = (request: RankRequest, output: ReviewOutput) => Promise<RankedCommand[]>;
|
|
25
|
+
export declare function candidateArguments(args: string[]): CandidateOptions;
|
|
26
|
+
/** Only named ledger files, not transcripts, shell history or arbitrary JSON. */
|
|
27
|
+
export declare function discoverCandidateLedgers(home: string, env: NodeJS.ProcessEnv): string[];
|
|
28
|
+
/** Read all records up to each file's opening size, including its last complete line. */
|
|
29
|
+
export declare function collectCandidates(files: string[]): Promise<CandidateReview>;
|
|
30
|
+
export declare function runGuardCandidates(home: string, args: string[], dependencies?: {
|
|
31
|
+
env?: NodeJS.ProcessEnv;
|
|
32
|
+
output?: ReviewOutput;
|
|
33
|
+
ranker?: CandidateRanker;
|
|
34
|
+
}): Promise<number>;
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GUARD_CRITERION = void 0;
|
|
4
|
+
exports.candidateArguments = candidateArguments;
|
|
5
|
+
exports.discoverCandidateLedgers = discoverCandidateLedgers;
|
|
6
|
+
exports.collectCandidates = collectCandidates;
|
|
7
|
+
exports.runGuardCandidates = runGuardCandidates;
|
|
8
|
+
/** Developer review only. Never imported by a hook or an enforcement path. */
|
|
9
|
+
const node_fs_1 = require("node:fs");
|
|
10
|
+
const node_path_1 = require("node:path");
|
|
11
|
+
const node_readline_1 = require("node:readline");
|
|
12
|
+
const node_crypto_1 = require("node:crypto");
|
|
13
|
+
const guard_candidates_ranker_1 = require("./guard-candidates-ranker");
|
|
14
|
+
exports.GUARD_CRITERION = 'how likely is this command to destroy data, leak a secret, escalate privilege, or change infrastructure';
|
|
15
|
+
const USAGE = 'Usage: agentguard-burn guard-candidates [--ledger <local.ndjson>] [--out <name.review.json>] [--rank]';
|
|
16
|
+
const SHELL = /(?:^|[._])(?:bash|powershell|shell|exec_command|run_command|execute_command|run_shell_command|shell_command)$/i;
|
|
17
|
+
const object = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
18
|
+
function candidateArguments(args) {
|
|
19
|
+
const result = { ledgers: [], rank: false };
|
|
20
|
+
for (let index = 0; index < args.length; index++) {
|
|
21
|
+
const flag = args[index];
|
|
22
|
+
if (flag === '--no-color')
|
|
23
|
+
continue;
|
|
24
|
+
if (flag === '--rank' && !result.rank) {
|
|
25
|
+
result.rank = true;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (flag !== '--ledger' && flag !== '--out')
|
|
29
|
+
throw new Error(USAGE);
|
|
30
|
+
const value = args[++index];
|
|
31
|
+
if (!value || value.startsWith('--') || /[\x00-\x1f\x7f]/.test(value))
|
|
32
|
+
throw new Error(USAGE);
|
|
33
|
+
if (flag === '--ledger')
|
|
34
|
+
result.ledgers.push(value);
|
|
35
|
+
else if (result.out)
|
|
36
|
+
throw new Error(USAGE);
|
|
37
|
+
else
|
|
38
|
+
result.out = value;
|
|
39
|
+
}
|
|
40
|
+
if (result.out && !result.out.endsWith('.review.json'))
|
|
41
|
+
throw new Error('Use --out <name.review.json>. Only review files can be created.');
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
/** Only named ledger files, not transcripts, shell history or arbitrary JSON. */
|
|
45
|
+
function discoverCandidateLedgers(home, env) {
|
|
46
|
+
const found = [];
|
|
47
|
+
const visited = new Set();
|
|
48
|
+
const walk = (directory) => {
|
|
49
|
+
let physical;
|
|
50
|
+
try {
|
|
51
|
+
physical = (0, node_fs_1.realpathSync)(directory);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (error.code === 'ENOENT')
|
|
55
|
+
return;
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
if (visited.has(physical))
|
|
59
|
+
return;
|
|
60
|
+
visited.add(physical);
|
|
61
|
+
for (const entry of (0, node_fs_1.readdirSync)(physical, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
62
|
+
const file = (0, node_path_1.join)(physical, entry.name);
|
|
63
|
+
if (entry.isDirectory())
|
|
64
|
+
walk(file);
|
|
65
|
+
else if (entry.isFile() && /^(?:decisions|receipts|ledger)(?:[.-].*)?\.(?:ndjson|jsonl)(?:\.[0-9TZ_.:-]+)?$/.test(entry.name))
|
|
66
|
+
found.push(file);
|
|
67
|
+
// Do not follow nested links outside a local state root.
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
for (const root of [home, env.PLUGIN_DATA, env.CLAUDE_PLUGIN_DATA])
|
|
71
|
+
if (root)
|
|
72
|
+
walk(root);
|
|
73
|
+
return [...new Set(found)].sort();
|
|
74
|
+
}
|
|
75
|
+
/** Recognized tool records only: response text and incidental command fields are not input. */
|
|
76
|
+
function shellCommands(value) {
|
|
77
|
+
const row = object(value), decision = object(row.decision);
|
|
78
|
+
const records = [row, decision, object(row.plugin), object(decision.plugin)];
|
|
79
|
+
if (row.type === 'tool_request')
|
|
80
|
+
records.push(object(row.data));
|
|
81
|
+
const commands = new Set();
|
|
82
|
+
let shell = false;
|
|
83
|
+
for (const record of records) {
|
|
84
|
+
const tool = object(record.tool);
|
|
85
|
+
const name = record.tool_name ?? record.toolName ?? (typeof record.tool === 'string' ? record.tool : tool.name)
|
|
86
|
+
?? (record.type === 'function_call' ? record.name : undefined);
|
|
87
|
+
if (typeof name !== 'string' || !SHELL.test(name))
|
|
88
|
+
continue;
|
|
89
|
+
shell = true;
|
|
90
|
+
const inputs = [record, record.tool_input, record.toolInput, record.input, record.arguments, record.args, tool.input, tool.arguments];
|
|
91
|
+
for (let input of inputs) {
|
|
92
|
+
if (typeof input === 'string') {
|
|
93
|
+
// Codex function arguments are JSON. A recorded toolInput string can
|
|
94
|
+
// instead be the entire shell program, including embedded newlines.
|
|
95
|
+
if (input.trimStart().startsWith('{')) {
|
|
96
|
+
try {
|
|
97
|
+
input = JSON.parse(input);
|
|
98
|
+
}
|
|
99
|
+
catch { /* Keep the recorded string. */ }
|
|
100
|
+
}
|
|
101
|
+
if (typeof input === 'string') {
|
|
102
|
+
if (input.trim())
|
|
103
|
+
commands.add(input);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const fields = object(input);
|
|
108
|
+
for (const field of ['command', 'cmd', 'script']) {
|
|
109
|
+
const values = Array.isArray(fields[field]) ? fields[field] : [fields[field]];
|
|
110
|
+
for (const command of values)
|
|
111
|
+
if (typeof command === 'string' && command.trim())
|
|
112
|
+
commands.add(command);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return { shell, commands: [...commands] };
|
|
117
|
+
}
|
|
118
|
+
/** Read all records up to each file's opening size, including its last complete line. */
|
|
119
|
+
async function collectCandidates(files) {
|
|
120
|
+
const sources = [...new Set(files.map(file => (0, node_fs_1.realpathSync)(file)))].sort();
|
|
121
|
+
const review = { schema: 'agentguard.guard-candidates.review.v1', generatedAt: new Date().toISOString(),
|
|
122
|
+
sources, records: 0, shellRecordsWithoutText: 0, malformed: [], raw: [] };
|
|
123
|
+
const counts = new Map();
|
|
124
|
+
for (const source of sources) {
|
|
125
|
+
const stat = (0, node_fs_1.statSync)(source);
|
|
126
|
+
if (!stat.isFile())
|
|
127
|
+
throw new Error('A ledger must be a regular local file.');
|
|
128
|
+
if (!stat.size)
|
|
129
|
+
continue;
|
|
130
|
+
const stream = (0, node_fs_1.createReadStream)(source, { start: 0, end: stat.size - 1, encoding: 'utf8' });
|
|
131
|
+
const lines = (0, node_readline_1.createInterface)({ input: stream, crlfDelay: Infinity });
|
|
132
|
+
let lineNumber = 0;
|
|
133
|
+
try {
|
|
134
|
+
for await (const line of lines) {
|
|
135
|
+
lineNumber++;
|
|
136
|
+
const text = lineNumber === 1 ? line.replace(/^\uFEFF/, '') : line;
|
|
137
|
+
if (!text.trim())
|
|
138
|
+
continue;
|
|
139
|
+
let row;
|
|
140
|
+
try {
|
|
141
|
+
row = JSON.parse(text);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
review.malformed.push({ source, line: lineNumber });
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (!row || typeof row !== 'object' || Array.isArray(row)) {
|
|
148
|
+
review.malformed.push({ source, line: lineNumber });
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
review.records++;
|
|
152
|
+
const extracted = shellCommands(row);
|
|
153
|
+
if (extracted.shell && !extracted.commands.length)
|
|
154
|
+
review.shellRecordsWithoutText++;
|
|
155
|
+
for (const command of extracted.commands)
|
|
156
|
+
counts.set(command, (counts.get(command) ?? 0) + 1);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
lines.close();
|
|
161
|
+
stream.destroy();
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
review.raw = [...counts].map(([command, occurrences]) => ({ command, occurrences }));
|
|
165
|
+
return review;
|
|
166
|
+
}
|
|
167
|
+
function requireFresh(file) {
|
|
168
|
+
// lstat catches dangling links too. Creation below also uses exclusive open.
|
|
169
|
+
try {
|
|
170
|
+
(0, node_fs_1.lstatSync)(file);
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
if (error.code === 'ENOENT')
|
|
174
|
+
return;
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
throw new Error('Review output already exists. Choose a new --out <name.review.json>.');
|
|
178
|
+
}
|
|
179
|
+
const writeReview = (file, value) => (0, node_fs_1.writeFileSync)(file, JSON.stringify(value, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
|
180
|
+
const print = text => new Promise((resolve, reject) => process.stdout.write(text, error => error ? reject(error) : resolve()));
|
|
181
|
+
async function runGuardCandidates(home, args, dependencies = {}) {
|
|
182
|
+
const options = candidateArguments(args), env = dependencies.env ?? process.env, output = dependencies.output ?? print;
|
|
183
|
+
const file = (0, node_path_1.resolve)(options.out ?? `guard-candidates-${Date.now()}-${(0, node_crypto_1.randomUUID)().slice(0, 8)}.review.json`);
|
|
184
|
+
const rankedFile = file.replace(/\.review\.json$/, '.ranked.review.json');
|
|
185
|
+
requireFresh(file);
|
|
186
|
+
if (options.rank)
|
|
187
|
+
requireFresh(rankedFile);
|
|
188
|
+
const review = await collectCandidates(options.ledgers.length ? options.ledgers : discoverCandidateLedgers(home, env));
|
|
189
|
+
writeReview(file, review);
|
|
190
|
+
await output(`Raw review: ${file}\n${review.raw.length} unique commands from ${review.records} ledger records.\n`
|
|
191
|
+
+ `${review.shellRecordsWithoutText} shell records have no command text; ${review.malformed.length} malformed rows.\n`);
|
|
192
|
+
if (!options.rank) {
|
|
193
|
+
await output('Local review only. Use --rank to request external ranking.\n');
|
|
194
|
+
return 0;
|
|
195
|
+
}
|
|
196
|
+
const provider = (0, guard_candidates_ranker_1.rankProvider)(env);
|
|
197
|
+
if (!provider) {
|
|
198
|
+
await output('Ranking skipped: set TYPESAFE_API_KEY or OPENROUTER_API_KEY in the environment. Nothing sent.\n');
|
|
199
|
+
return 0;
|
|
200
|
+
}
|
|
201
|
+
if (review.malformed.length) {
|
|
202
|
+
await output('Ranking skipped: repair malformed ledger rows first. Raw review retained; nothing sent.\n');
|
|
203
|
+
return 4;
|
|
204
|
+
}
|
|
205
|
+
if (review.raw.length < 2) {
|
|
206
|
+
await output('Ranking skipped: at least two unique commands are needed. Nothing sent.\n');
|
|
207
|
+
return 0;
|
|
208
|
+
}
|
|
209
|
+
const request = { commands: review.raw.map(row => row.command), criterion: exports.GUARD_CRITERION, provider };
|
|
210
|
+
// JSON escaping preserves newlines and terminal control characters literally.
|
|
211
|
+
await output(`External ranking requested: ${provider.name} at ${provider.url}\n`
|
|
212
|
+
+ `Criterion: ${JSON.stringify(exports.GUARD_CRITERION)}\nCommand texts to send, without truncation (JSON):\n${JSON.stringify(request.commands, null, 2)}\n`
|
|
213
|
+
+ 'Every outgoing JSON request body will be printed before forwarding. The API key is used only as an authentication header.\n');
|
|
214
|
+
try {
|
|
215
|
+
const ranked = await (dependencies.ranker ?? guard_candidates_ranker_1.rankWithJsort)(request, output);
|
|
216
|
+
writeReview(rankedFile, { schema: 'agentguard.guard-candidates.ranked-review.v1', generatedAt: new Date().toISOString(), rawReview: file,
|
|
217
|
+
criterion: exports.GUARD_CRITERION, provider: provider.name, endpoint: provider.url, model: provider.model,
|
|
218
|
+
scoreMeaning: 'Relative jsort Bradley-Terry scores in logit units, not calibrated probabilities or enforcement rules.', ranked });
|
|
219
|
+
await output(`Ranked review: ${rankedFile}\nReview only. No policy or rule was changed.\n`);
|
|
220
|
+
return 0;
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
await output('Ranking failed. Raw review retained; no ranked review written. Install jsort 0.1.3 (jev-sort) and check the provider or budget before retrying.\n');
|
|
224
|
+
return 4;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type TranscriptLocation } from './sessions';
|
|
2
|
+
export type Row = Record<string, unknown>;
|
|
3
|
+
export declare const object: (value: unknown) => Row;
|
|
4
|
+
export declare const identifier: (value: unknown) => string | null;
|
|
5
|
+
export declare function timestamp(value: unknown): number | null;
|
|
6
|
+
export interface Scan {
|
|
7
|
+
malformed: number;
|
|
8
|
+
}
|
|
9
|
+
/** Bounded input buffers; no transcript content is retained or written. */
|
|
10
|
+
export declare function jsonRows(file: string, scan?: Scan): Generator<Row>;
|
|
11
|
+
export interface HistoryDecision {
|
|
12
|
+
id: string;
|
|
13
|
+
session: string;
|
|
14
|
+
digest: string;
|
|
15
|
+
at: number | null;
|
|
16
|
+
verdict: 'OK' | 'WARN' | 'STOP';
|
|
17
|
+
mode: string | null;
|
|
18
|
+
blocked: boolean | null;
|
|
19
|
+
wouldBlock: boolean;
|
|
20
|
+
action: string | null;
|
|
21
|
+
detectors: string[];
|
|
22
|
+
}
|
|
23
|
+
/** The receipt and flat ledger are two views of a decision, not two decisions. */
|
|
24
|
+
export declare function historyDecisions(home: string): {
|
|
25
|
+
decisions: HistoryDecision[];
|
|
26
|
+
malformed: number;
|
|
27
|
+
};
|
|
28
|
+
export declare const locationId: (item: TranscriptLocation) => string;
|
|
29
|
+
export declare function selectHistory(session: string | undefined, locations: TranscriptLocation[], decisions: HistoryDecision[]): {
|
|
30
|
+
locations: TranscriptLocation[];
|
|
31
|
+
decisions: HistoryDecision[];
|
|
32
|
+
};
|
|
33
|
+
export declare function reportTable(headers: string[], rows: string[][]): string;
|
|
34
|
+
export declare const atText: (at: number | null) => string;
|