@agentguard-run/burn 0.3.1 → 0.3.3
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 +15 -0
- package/README.md +83 -8
- 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.d.ts +1 -0
- package/dist/src/cli.js +65 -2
- package/dist/src/frames.d.ts +4 -0
- package/dist/src/frames.js +3 -0
- package/dist/src/gateway.js +5 -3
- 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/hook/pre-tool-use.js +2 -1
- package/dist/src/ledger-panel.d.ts +40 -0
- package/dist/src/ledger-panel.js +174 -0
- package/dist/src/live-panel.d.ts +12 -0
- package/dist/src/live-panel.js +27 -107
- package/dist/src/record-ledger.d.ts +30 -0
- package/dist/src/record-ledger.js +165 -0
- package/dist/src/recording.js +8 -2
- package/dist/src/state/spawn-window.d.ts +13 -1
- package/dist/src/state/spawn-window.js +18 -3
- package/docs/LIVE_PANEL_2026_09.md +52 -28
- 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/docs/assets/burn-real-stop-sep20-stop-1920.png +0 -0
- package/docs/assets/burn-real-stop-sep20-stop-390.png +0 -0
- package/docs/assets/burn-real-stop-sep20.evidence.json +67 -0
- package/docs/assets/burn-real-stop-sep20.gif +0 -0
- package/docs/assets/burn-real-stop-sep20.jsonl +39 -0
- package/docs/assets/burn-real-stop-sep20.mp4 +0 -0
- package/docs/assets/{burn-live-sep19.mp4.provenance.json → burn-real-stop-sep20.mp4.provenance.json} +45 -81
- package/docs/assets/burn-real-stop-sep20.policy.json +47 -0
- package/docs/assets/burn-real-stop-sep20.receipts.ndjson +18 -0
- package/docs/burn-render.md +12 -2
- 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/fixtures/live-sep20-stop-104x35.txt +35 -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/docs/assets/burn-live-sep19-stop-1920.png +0 -0
- package/docs/assets/burn-live-sep19-stop-390.png +0 -0
- package/docs/assets/burn-live-sep19.evidence.json +0 -288
- package/docs/assets/burn-live-sep19.gif +0 -0
- package/docs/assets/burn-live-sep19.jsonl +0 -45
- package/docs/assets/burn-live-sep19.mp4 +0 -0
- package/docs/assets/burn-live-sep19.observations.jsonl +0 -45
- package/docs/assets/burn-live-sep19.receipt.json +0 -38
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.3 (2026-09-21)
|
|
4
|
+
|
|
5
|
+
- Add developer-only `guard-candidates` to deduplicate shell text already recorded in local ledgers into private review files. Optional `--rank` uses jsort with an environment key, prints every provider request body before forwarding, and adds relative scores without changing hooks, policies or rules.
|
|
6
|
+
- Add `import-bench` for signed DisciplineBench run bundles. Reuse the harness verifier for artifact hashes, publisher signature, measurement chain and reducer parity. Keep separate publisher and measurement identities, with an optional trusted publisher pin.
|
|
7
|
+
- Add pinned benchmark replay with required `--pricing`. Reject any snapshot whose bytes differ from the signed round artifact. Use the harness pricing rules, preserve native categories and reconciliation, and display missing measurements as unknown.
|
|
8
|
+
- Convert canonical events into recorded instrument frames at their original timestamps. Retain spawn lineage, rule IDs and `enforced:false`; would-STOP observations do not imply a blocked call. The existing renderer produces PNG, MP4 and GIF with provenance.
|
|
9
|
+
- Keep native transcript replay and hook enforcement behavior unchanged. All bundle verification, replay and rendering stay local; no publishing or model execution is part of import.
|
|
10
|
+
|
|
11
|
+
## 0.3.2 (2026-09-21)
|
|
12
|
+
|
|
13
|
+
- Follow the newest ledger decision on every live refresh, unless a session is pinned. Show the raw session ID prefix and record identity switches. A switch immediately releases a previous session's STOP hold.
|
|
14
|
+
- Read panel counters from the hook's decision window, including pending spawn reservations. Record the exact active window, token count and ceiling for future decisions. Elapsed starts at the first ledger decision, not the transcript start. Historical measurements that were never recorded remain unknown.
|
|
15
|
+
- Add `record --session ID --from ISO --to ISO --out run.jsonl` to reconstruct local ledger decisions at their original timestamps with one-second display ticks. No transcript contents or live state changes are needed.
|
|
16
|
+
- Replace the current showcase with the verified September 20 spawn-rate block: 16 proposals against 16, with a full red bar, the STOP reason and original timing. The older hashed display ID referred to this same session; the defect was stale transcript counters versus pending reservations.
|
|
17
|
+
|
|
3
18
|
## 0.3.1 (2026-09-20)
|
|
4
19
|
|
|
5
20
|
- Add the live session screen: block-digit counters for spawns, tokens in window and replay share, a spawn-rate bar against the policy ceiling, the last decisions with verdict chips, and a two-second STOP hold, all through the canvas. The same screen renders recorded runs.
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @agentguard-run/burn
|
|
2
2
|
|
|
3
|
-
See where a coding session's tokens went and what the next heavy turn could cost in time and limits. Burn explains recorded usage, warns about large cache rewrites and keeps its existing runaway-session circuit breaker.
|
|
3
|
+
See where a coding session's tokens went and what the next heavy turn could cost in time and limits. Burn explains recorded usage, warns about large cache rewrites and keeps its existing runaway-session circuit breaker. Runtime observation and enforcement stay on this machine. The developer review command below has an explicit external-ranking option.
|
|
4
4
|
|
|
5
5
|
## Install in five lines
|
|
6
6
|
|
|
@@ -16,6 +16,62 @@ The two init commands print hook configuration for review. Merge the relevant sn
|
|
|
16
16
|
|
|
17
17
|
For Claude Code, configure its `statusLine` command as `agentguard-burn statusline`. It receives the host JSON on stdin. Codex 0.154.0 has no external status command slot. Use `agentguard-burn statusline SESSION_ID` in a companion terminal and the native Codex limit indicators. See [host fields and setup](docs/USAGE_AND_PRICING.md#what-the-hosts-expose).
|
|
18
18
|
|
|
19
|
+
## Import a DisciplineBench run
|
|
20
|
+
|
|
21
|
+
Burn 0.3.3 can verify and replay a signed DisciplineBench bundle offline. This is a post-run display, outside benchmark scoring. It does not run an agent or change a benchmark result.
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
agentguard-burn import-bench ./run-bundle --out ./burn-import
|
|
25
|
+
agentguard-burn replay ./burn-import/replay.json --pricing ./burn-import/bundle/pricing.json
|
|
26
|
+
agentguard-burn replay ./burn-import/replay.json --pricing ./burn-import/bundle/pricing.json --json
|
|
27
|
+
agentguard-burn render ./burn-import/recording.jsonl --mp4 ./run.mp4 --gif ./run.gif
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The importer uses the bundled, unchanged DisciplineBench verifier to check the manifest signature, every declared artifact hash, the Ed25519 ledger chain, and the recomputed `run.json`. Only manifest-listed artifacts are copied into a new directory. The source bundle is unchanged. Existing output directories are refused. The default output is the bundle path with `.burn` appended.
|
|
31
|
+
|
|
32
|
+
Embedded keys prove integrity, not the publisher's external identity. Obtain a publisher fingerprint through a trusted channel and supply `--publisher-key-id ID` to import or replay when that identity matters. Publisher and measurement fingerprints remain separate. No AgentGuard license, provider credential, model call, or network request is required.
|
|
33
|
+
|
|
34
|
+
Replay requires `--pricing` on every invocation. Its bytes must match the signed round's pricing artifact exactly. Current Burn prices, local overrides and prices from another round are never substituted. Cache durations and long-context rates use the harness pricing rules. The display rounds the final list-price exposure to cents; JSON keeps the unrounded reducer value. List price is a comparability convention, never a bill.
|
|
35
|
+
|
|
36
|
+
The replay file keeps every canonical event, the complete spawn tree, rule IDs, `enforced:false`, all native and normalized token categories, and the usage reconciliation. Missing measurements remain null and render as `unknown`. A STOP in this recording is a would-STOP classification, not an execution block. Burn does not invent a spawn ceiling or an active window absent from the bundle.
|
|
37
|
+
|
|
38
|
+
Each event produces a frame at its original timestamp. Frames contain cumulative observations through that event, not a synthetic 15-minute enforcement window. The final frame agrees with the verified reducer. `replay ... --record frames.jsonl` also writes those event frames. `render` uses the existing local PNG, MP4 and GIF pipeline and records source SHA-256 provenance. Frames are display derivatives, not newly signed measurements; replay re-verifies the retained bundle and checks the conversion before producing new frames.
|
|
39
|
+
|
|
40
|
+
Imports are limited to 128 MB of declared artifacts and 10,000 events, matching the local renderer's frame limit. No task code or modules from the bundle are executed. The exact vendored verifier sources, Apache-2.0 license and source hashes are in `vendor/disciplinebench/`.
|
|
41
|
+
|
|
42
|
+
The bundled `fixtures/bench-run` is an authored fixture, not a scored host run. Its reducer and Burn both report $0.0155, displayed as $0.02. It declares two child agents, maximum depth two, and a would-STOP observation for GP001 and GP006. See the [rendered frame](docs/assets/burn-bench-fixture.png), [MP4](docs/assets/burn-bench-fixture.mp4), [GIF](docs/assets/burn-bench-fixture.gif), and [artifact hashes](docs/assets/burn-bench-fixture.evidence.json). The original harness's `burn-postrun.json` marker remains unchanged as signed evidence, including its older unsupported-import message.
|
|
43
|
+
|
|
44
|
+
## Developer guard candidates
|
|
45
|
+
|
|
46
|
+
`guard-candidates` reads local ledgers and writes a review file. It never executes a recorded command or changes a rule, policy, hook, or ledger.
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
agentguard-burn guard-candidates --out ./commands.review.json
|
|
50
|
+
agentguard-burn guard-candidates --ledger ./local-ledger.ndjson --out ./explicit.review.json
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The default scan covers all named decision, receipt and ledger NDJSON/JSONL files under `AGENTGUARD_HOME` (default `~/.agentguard`), plus `PLUGIN_DATA` and `CLAUDE_PLUGIN_DATA` when provided. Numbered/date suffix rotations are included. Nested symlinks are not followed. Use repeatable `--ledger` to choose other local ledger files. The command reads each file up to its opening size, across every session, including a complete last line without a newline. It does not read transcripts or shell history.
|
|
54
|
+
|
|
55
|
+
Commands are deduplicated by exact text, with occurrence counts. Whitespace, quoting, multiline programs and long strings stay intact. Recognized shell tool records can carry `command`, `cmd` or `script` in tool input, including signed `decision.plugin` envelopes and JSON function arguments. Non-shell tools, responses and incidental command fields are excluded.
|
|
56
|
+
|
|
57
|
+
**Current Burn and plugin ledgers omit command text.** They store metadata and input hashes. Those shell records are counted as missing text; hashes cannot reconstruct commands. This command does not enable new content logging. A metadata-only ledger produces an empty review, not invented candidates. Malformed rows are reported by file and line; ranking refuses an incomplete scan.
|
|
58
|
+
|
|
59
|
+
To rank, first install the optional [jsort](https://github.com/keltokhy/jsort) CLI, distributed as `jev-sort` under MIT. The adapter targets 0.1.3 ([reviewed source](https://github.com/keltokhy/jsort/tree/4fa1e5e6d68543f24e7c1f390fd7167612b2f6c2)). Burn does not install it automatically.
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
uv tool install 'jev-sort==0.1.3'
|
|
63
|
+
# Set TYPESAFE_API_KEY or OPENROUTER_API_KEY in your environment first.
|
|
64
|
+
agentguard-burn guard-candidates --ledger ./local-ledger.ndjson --out ./ranked-input.review.json --rank
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Only `--rank` with a nonempty environment key can start jsort or a provider request. TypeSafe takes precedence when both keys are present. Key files and gateway/model overrides do not enable ranking. With no key, or fewer than two unique commands, the raw review is kept and ranking is skipped.
|
|
68
|
+
|
|
69
|
+
The exact criterion is `how likely is this command to destroy data, leak a secret, escalate privilege, or change infrastructure`. Before jsort starts, the command prints the provider, endpoint, criterion and complete command texts as escaped JSON. Each exact outgoing JSON request body is then printed and flushed before it is forwarded. Authentication keys are never printed or stored in review files. Recorded command text is sent verbatim, including any secrets inside it, so inspect the local review before choosing `--rank`.
|
|
70
|
+
|
|
71
|
+
jsort receives only command strings through stdin. A local forwarding gate permits only comparisons between those strings, using that criterion and the selected provider/model. It rejects unexpected request data and redirects. The provider key stays in Burn; jsort gets a temporary local token. No cache is written. The adapter uses jsort's $1 budget, a 15-second comparison timeout and a five-minute process timeout. Incomplete, failed or malformed rankings leave the raw review intact and return a nonzero exit status.
|
|
72
|
+
|
|
73
|
+
Successful ranking creates `ranked-input.ranked.review.json` beside the raw file, with each command's score, standard error and comparison count, highest first. Scores are relative Bradley-Terry logit values, not calibrated risk probabilities. All outputs have owner-only permissions. Existing outputs, non-review output names and `--record` are refused. These commands have no automatic connection to Guard Pack rules and are never installed or called by hooks.
|
|
74
|
+
|
|
19
75
|
## Local idle audit
|
|
20
76
|
|
|
21
77
|
Burn 0.3.0 reports held memory and disk cost exposure on this machine:
|
|
@@ -382,14 +438,33 @@ A provenance JSON beside the requested MP4 records the source recording's SHA256
|
|
|
382
438
|
|
|
383
439
|
## What it never does
|
|
384
440
|
|
|
385
|
-
|
|
441
|
+
Runtime observation and enforcement do not persist or render prompts, responses, file contents or tool inputs. The explicit developer `guard-candidates` command copies shell text already present in a ledger into a private review; only its `--rank` option can send that text to the selected provider.
|
|
386
442
|
No telemetry. No provider-quota guesses. Account forecasts use only observed host percentages, never an invented allowance or cache weighting.
|
|
387
443
|
|
|
388
444
|
### Local live panel
|
|
389
445
|
|
|
390
|
-
`agentguard-burn live`
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
446
|
+
`agentguard-burn live` follows the session with the newest local ledger decision
|
|
447
|
+
on every refresh. `--session ID` pins a full ID, unique ID prefix or digest.
|
|
448
|
+
The header shows the raw session ID prefix when the decision ledger supplies it.
|
|
449
|
+
Spawn and token counters, the rate ceiling and the last eight decisions come
|
|
450
|
+
from that session's decision ledger. Pending spawn proposals are included,
|
|
451
|
+
exactly as the hook measured them. Elapsed starts at its first ledger decision.
|
|
452
|
+
A change of session is captured as `sessionSwitch` in `--record run.jsonl`.
|
|
453
|
+
|
|
454
|
+
Use `--once`, `--record run.jsonl`, or `--replay run.jsonl`. STOP reasons hold
|
|
455
|
+
for two seconds while observations continue, and a session switch releases
|
|
456
|
+
that hold immediately. The display never changes admission. Historical token
|
|
457
|
+
windows and cache-read share remain unknown when the ledger did not record them.
|
|
458
|
+
|
|
459
|
+
Reconstruct an event after it happened, entirely from local ledgers:
|
|
460
|
+
|
|
461
|
+
```sh
|
|
462
|
+
agentguard-burn record --session 0b0c2202 --from 2026-09-20T20:20:32Z --to 2026-09-20T20:20:52Z --out run.jsonl
|
|
463
|
+
agentguard-burn render run.jsonl --mp4 run.mp4 --gif run.gif
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
`record` writes each decision at its real timestamp, with one frame per second
|
|
467
|
+
between decisions. Bounds are optional and otherwise use the session's first
|
|
468
|
+
and last decisions. Earlier decisions still supply window context. The output
|
|
469
|
+
must be new. It contains identifiers and measured metadata, never tool input,
|
|
470
|
+
output or transcript content. See [the live panel and September 20 evidence](docs/LIVE_PANEL_2026_09.md).
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { BenchPanelSnapshot } from './bench-panel';
|
|
2
|
+
import type { RecordedFrame } from './recording';
|
|
3
|
+
export interface Metric {
|
|
4
|
+
value: number | null;
|
|
5
|
+
reason: string | null;
|
|
6
|
+
}
|
|
7
|
+
export interface BenchEvent {
|
|
8
|
+
schema_version: number;
|
|
9
|
+
event_id: string;
|
|
10
|
+
type: string;
|
|
11
|
+
timestamp: string;
|
|
12
|
+
run_id: string;
|
|
13
|
+
agent_id: string;
|
|
14
|
+
parent_agent_id: string | null;
|
|
15
|
+
spawn_depth: number;
|
|
16
|
+
data: Record<string, any>;
|
|
17
|
+
}
|
|
18
|
+
export interface BenchRun {
|
|
19
|
+
run_id: string;
|
|
20
|
+
fixture: boolean;
|
|
21
|
+
status: string;
|
|
22
|
+
identity: Record<string, string>;
|
|
23
|
+
metrics: {
|
|
24
|
+
spawn_count: Metric;
|
|
25
|
+
max_spawn_depth: Metric;
|
|
26
|
+
tokens: Record<string, number | null>;
|
|
27
|
+
native_tokens: Record<string, number | null>;
|
|
28
|
+
context_replay_share: Metric;
|
|
29
|
+
list_price_exposure: Metric;
|
|
30
|
+
[key: string]: unknown;
|
|
31
|
+
};
|
|
32
|
+
coverage: BenchPanelSnapshot['coverage'];
|
|
33
|
+
spawn_tree: BenchPanelSnapshot['spawn_tree'];
|
|
34
|
+
policy_decisions: BenchPanelSnapshot['policy_decisions'];
|
|
35
|
+
[key: string]: unknown;
|
|
36
|
+
}
|
|
37
|
+
export interface BenchVerification {
|
|
38
|
+
ok: true;
|
|
39
|
+
run_id: string;
|
|
40
|
+
ledger_sha256: string;
|
|
41
|
+
run_sha256: string;
|
|
42
|
+
publisher_key_id: string;
|
|
43
|
+
measurement_key_id: string;
|
|
44
|
+
publisher_pinned: boolean;
|
|
45
|
+
}
|
|
46
|
+
export declare function importBench(runDir: string, options?: {
|
|
47
|
+
out?: string;
|
|
48
|
+
expectedPublisherKeyId?: string;
|
|
49
|
+
}): Promise<{
|
|
50
|
+
directory: string;
|
|
51
|
+
replayPath: string;
|
|
52
|
+
recordingPath: string;
|
|
53
|
+
pricingPath: string;
|
|
54
|
+
verification: BenchVerification;
|
|
55
|
+
run: BenchRun;
|
|
56
|
+
}>;
|
|
57
|
+
export declare function replayBench(replayPath: string, pricingPath: string, options?: {
|
|
58
|
+
expectedPublisherKeyId?: string;
|
|
59
|
+
}): Promise<{
|
|
60
|
+
run: BenchRun;
|
|
61
|
+
events: BenchEvent[];
|
|
62
|
+
verification: {
|
|
63
|
+
publisher_pinned: boolean;
|
|
64
|
+
ok: true;
|
|
65
|
+
run_id: string;
|
|
66
|
+
ledger_sha256: string;
|
|
67
|
+
run_sha256: string;
|
|
68
|
+
publisher_key_id: string;
|
|
69
|
+
measurement_key_id: string;
|
|
70
|
+
};
|
|
71
|
+
frames: RecordedFrame[];
|
|
72
|
+
pricing_sha256: string;
|
|
73
|
+
}>;
|
|
74
|
+
export declare function renderBenchReplay(result: Awaited<ReturnType<typeof replayBench>>): string;
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.importBench = importBench;
|
|
4
|
+
exports.replayBench = replayBench;
|
|
5
|
+
exports.renderBenchReplay = renderBenchReplay;
|
|
6
|
+
/** Offline bridge from signed DisciplineBench bundles to Burn replay and frames. */
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const node_fs_1 = require("node:fs");
|
|
9
|
+
const node_os_1 = require("node:os");
|
|
10
|
+
const node_path_1 = require("node:path");
|
|
11
|
+
// Only package-owned code is loaded. No executable path comes from an imported bundle.
|
|
12
|
+
const harness = require('../../vendor/disciplinebench/harness/verify.cjs');
|
|
13
|
+
const reducer = require('../../vendor/disciplinebench/harness/reducer.cjs');
|
|
14
|
+
const { canonicalJson } = require('../../vendor/disciplinebench/harness/util.cjs');
|
|
15
|
+
const hash = (bytes) => (0, node_crypto_1.createHash)('sha256').update(bytes).digest('hex');
|
|
16
|
+
const MAX_BYTES = 128 * 1024 * 1024;
|
|
17
|
+
function localFile(path) {
|
|
18
|
+
const stat = (0, node_fs_1.lstatSync)(path);
|
|
19
|
+
if (!stat.isFile() || stat.size > MAX_BYTES)
|
|
20
|
+
throw new Error('Bundle artifacts must be regular local files no larger than 128 MB.');
|
|
21
|
+
const bytes = (0, node_fs_1.readFileSync)(path);
|
|
22
|
+
if (bytes.length > MAX_BYTES)
|
|
23
|
+
throw new Error('Bundle artifact exceeds 128 MB.');
|
|
24
|
+
return bytes;
|
|
25
|
+
}
|
|
26
|
+
function artifactPath(root, name) {
|
|
27
|
+
if (!name || (0, node_path_1.isAbsolute)(name) || name.split(/[\\/]/).some(part => !part || part === '..' || part === '.') || /[\x00-\x1f\x7f]/.test(name))
|
|
28
|
+
throw new Error('Unsafe bundle artifact path.');
|
|
29
|
+
const target = (0, node_path_1.resolve)(root, name);
|
|
30
|
+
if (!target.startsWith((0, node_fs_1.realpathSync)(root) + node_path_1.sep) || !(0, node_fs_1.realpathSync)(target).startsWith((0, node_fs_1.realpathSync)(root) + node_path_1.sep))
|
|
31
|
+
throw new Error('Bundle artifact escapes its directory.');
|
|
32
|
+
return target;
|
|
33
|
+
}
|
|
34
|
+
function writeFiles(root, files) {
|
|
35
|
+
(0, node_fs_1.mkdirSync)(root, { recursive: true, mode: 0o700 });
|
|
36
|
+
for (const [name, bytes] of files) {
|
|
37
|
+
const target = (0, node_path_1.join)(root, name);
|
|
38
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(target), { recursive: true, mode: 0o700 });
|
|
39
|
+
(0, node_fs_1.writeFileSync)(target, bytes, { flag: 'wx', mode: 0o600 });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** Freeze declared bytes first, then run the real harness verifier on that private copy. */
|
|
43
|
+
async function verifiedBundle(directory, expectedPublisherKeyId) {
|
|
44
|
+
const root = (0, node_fs_1.realpathSync)(directory), manifestBytes = localFile((0, node_path_1.join)(root, 'manifest.json'));
|
|
45
|
+
const manifest = JSON.parse(manifestBytes.toString('utf8'));
|
|
46
|
+
harness.verifyManifest(manifest);
|
|
47
|
+
if (!manifest.artifacts || typeof manifest.artifacts !== 'object' || Array.isArray(manifest.artifacts))
|
|
48
|
+
throw new Error('Invalid artifact manifest.');
|
|
49
|
+
const files = new Map([['manifest.json', manifestBytes]]);
|
|
50
|
+
let size = manifestBytes.length;
|
|
51
|
+
for (const [name, sha] of Object.entries(manifest.artifacts)) {
|
|
52
|
+
if (name === 'manifest.json' || !/^[0-9a-f]{64}$/.test(sha))
|
|
53
|
+
throw new Error('Invalid artifact manifest.');
|
|
54
|
+
const bytes = localFile(artifactPath(root, name));
|
|
55
|
+
if (hash(bytes) !== sha)
|
|
56
|
+
throw new Error(`Artifact hash mismatch: ${name}`);
|
|
57
|
+
size += bytes.length;
|
|
58
|
+
if (size > MAX_BYTES)
|
|
59
|
+
throw new Error('Bundle exceeds the 128 MB import limit.');
|
|
60
|
+
files.set(name, bytes);
|
|
61
|
+
}
|
|
62
|
+
const staging = (0, node_fs_1.mkdtempSync)((0, node_path_1.join)((0, node_os_1.tmpdir)(), 'burn-bench-verify-'));
|
|
63
|
+
let verification;
|
|
64
|
+
try {
|
|
65
|
+
writeFiles(staging, files);
|
|
66
|
+
verification = await harness.verifyBundle(staging, { expectedPublisherKeyId });
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
(0, node_fs_1.rmSync)(staging, { recursive: true, force: true });
|
|
70
|
+
}
|
|
71
|
+
const json = (name) => JSON.parse(files.get(name).toString('utf8'));
|
|
72
|
+
const events = files.get('ledger.ndjson').toString('utf8').trim().split('\n')
|
|
73
|
+
.map(line => JSON.parse(line).decision.governanceReceipt);
|
|
74
|
+
if (events.length > 10000)
|
|
75
|
+
throw new Error('Bundle exceeds the 10,000 frame render limit.');
|
|
76
|
+
return { files, verification, events, run: json('run.json'), pricing: json('pricing.json'),
|
|
77
|
+
pricing_sha256: manifest.artifacts['pricing.json'], policy: json('policy.json') };
|
|
78
|
+
}
|
|
79
|
+
function replayDocument(bundle, expectedPublisherKeyId) {
|
|
80
|
+
return { format: 'agentguard-burn/disciplinebench', version: 1, bundle: 'bundle',
|
|
81
|
+
expected_publisher_key_id: expectedPublisherKeyId ?? null, verification: bundle.verification,
|
|
82
|
+
pricing_sha256: bundle.pricing_sha256, run: bundle.run, events: bundle.events };
|
|
83
|
+
}
|
|
84
|
+
const known = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
|
|
85
|
+
function sum(values) { return values.every(value => value !== null) ? values.reduce((a, b) => a + b, 0) : null; }
|
|
86
|
+
function flatten(value, prefix = '', result = {}) {
|
|
87
|
+
for (const [key, item] of Object.entries(value)) {
|
|
88
|
+
const name = prefix ? `${prefix}.${key}` : key;
|
|
89
|
+
if (item && typeof item === 'object' && !Array.isArray(item))
|
|
90
|
+
flatten(item, name, result);
|
|
91
|
+
else if (typeof item === 'number' || item === null)
|
|
92
|
+
result[name] = known(item);
|
|
93
|
+
}
|
|
94
|
+
return result;
|
|
95
|
+
}
|
|
96
|
+
// Match the raster renderer's microsecond timestamps. Date.parse alone truncates
|
|
97
|
+
// fractions and can leave a verified ledger's out-of-order events unsorted.
|
|
98
|
+
function micros(at) {
|
|
99
|
+
const fraction = /\.(\d+)(?:Z|[+-]\d{2}:?\d{2})$/i.exec(at)?.[1] ?? '';
|
|
100
|
+
return BigInt(Date.parse(at)) * 1000n + BigInt(fraction.slice(3, 6).padEnd(3, '0'));
|
|
101
|
+
}
|
|
102
|
+
/** Prefix projections are displays, not scoring inputs. All original events remain intact. */
|
|
103
|
+
function projectFrames(bundle) {
|
|
104
|
+
const { run, events, pricing } = bundle;
|
|
105
|
+
const start = events.find(event => event.type === 'session_start');
|
|
106
|
+
const usage = new Map(), agents = new Map();
|
|
107
|
+
const requests = new Map(), decisions = new Map();
|
|
108
|
+
const rule_reasons = Object.fromEntries(bundle.policy.rules.filter(rule => rule.reason).map(rule => [rule.id, rule.reason]));
|
|
109
|
+
const sorted = events.map((event, order) => ({ event, order, time: micros(event.timestamp) }))
|
|
110
|
+
.sort((a, b) => a.time < b.time ? -1 : a.time > b.time ? 1 : a.order - b.order);
|
|
111
|
+
let status = null;
|
|
112
|
+
let recordingBytes = 0;
|
|
113
|
+
return sorted.map(({ event }, index) => {
|
|
114
|
+
if (event.type === 'session_start' || event.type === 'subagent_spawn')
|
|
115
|
+
agents.set(event.agent_id, { agent_id: event.agent_id, parent_agent_id: event.parent_agent_id, spawn_depth: event.spawn_depth });
|
|
116
|
+
if (event.type === 'model_usage')
|
|
117
|
+
usage.set(event.data.message_id, event.data);
|
|
118
|
+
if (event.type === 'tool_request')
|
|
119
|
+
requests.set(event.data.tool_call_id, event.data);
|
|
120
|
+
if (event.type === 'policy_decision')
|
|
121
|
+
decisions.set(event.data.tool_call_id, event.data);
|
|
122
|
+
if (event.type === 'session_end')
|
|
123
|
+
status = event.data.status;
|
|
124
|
+
const rows = [...usage.values()];
|
|
125
|
+
const tokens = Object.fromEntries(reducer.CATEGORIES.map(key => [key, rows.length ? sum(rows.map(row => known(row.host_usage[key]))) : null]));
|
|
126
|
+
const native = rows.map(row => flatten(row.native_usage || row.raw || {}));
|
|
127
|
+
const native_tokens = Object.fromEntries([...new Set(native.flatMap(row => Object.keys(row)))].sort().map(key => [key, sum(native.map(row => known(row[key])))]));
|
|
128
|
+
const input = sum(reducer.CATEGORIES.slice(0, 5).map(key => tokens[key]));
|
|
129
|
+
const replay = input === null || tokens.replay_input === null ? null : input === 0 ? null : tokens.replay_input / input;
|
|
130
|
+
const charges = rows.map(row => reducer.priceUsage(row.host_usage, row.model || run.identity.reported_model, pricing));
|
|
131
|
+
const exposure = !charges.length ? { value: null, reason: 'usage_not_exposed' }
|
|
132
|
+
: charges.find(charge => charge.value === null) ?? { value: sum(charges.map(charge => charge.value)), reason: null };
|
|
133
|
+
const lineage = start.data.coverage?.lineage === true;
|
|
134
|
+
const policy = start.data.coverage?.policy !== false && requests.size === decisions.size && [...decisions.values()].every(decision => !decision.uncertainty);
|
|
135
|
+
const snapshot = {
|
|
136
|
+
run_id: run.run_id, observed_at: event.timestamp, started_at: start.timestamp, event_type: event.type,
|
|
137
|
+
model: run.identity.reported_model ?? null, status, pricing_snapshot: bundle.pricing_sha256,
|
|
138
|
+
list_price_exposure: exposure.value, context_replay_share: replay,
|
|
139
|
+
spawn_count: lineage ? Math.max(0, agents.size - 1) : null,
|
|
140
|
+
max_spawn_depth: lineage ? Math.max(0, ...[...agents.values()].map(node => node.spawn_depth)) : null,
|
|
141
|
+
tokens, native_tokens, spawn_tree: [...agents.values()],
|
|
142
|
+
policy_decisions: [...decisions.values()].map(decision => ({ ...decision, tool_name: requests.get(decision.tool_call_id)?.tool_name ?? null })),
|
|
143
|
+
coverage: { lineage, usage: rows.length > 0, policy }, rule_reasons,
|
|
144
|
+
unknown_reasons: { ...(exposure.reason ? { list_price_exposure: exposure.reason } : {}),
|
|
145
|
+
...(!lineage ? { spawn_count: 'lineage_not_exposed', max_spawn_depth: 'lineage_not_exposed' } : {}),
|
|
146
|
+
...(replay === null ? { context_replay_share: input === 0 ? 'zero_input_tokens' : 'input_or_replay_unknown' } : {}) },
|
|
147
|
+
};
|
|
148
|
+
if (index === sorted.length - 1) {
|
|
149
|
+
// Assert that the independent prefix bookkeeping agrees with the signed reducer result.
|
|
150
|
+
for (const [field, actual, expected] of [
|
|
151
|
+
['exposure', exposure.value, run.metrics.list_price_exposure.value], ['tokens', tokens, run.metrics.tokens],
|
|
152
|
+
['native tokens', native_tokens, run.metrics.native_tokens], ['spawn count', snapshot.spawn_count, run.metrics.spawn_count.value],
|
|
153
|
+
['max depth', snapshot.max_spawn_depth, run.metrics.max_spawn_depth.value], ['replay share', replay, run.metrics.context_replay_share.value],
|
|
154
|
+
]) {
|
|
155
|
+
const equal = field === 'exposure' && typeof actual === 'number' && typeof expected === 'number'
|
|
156
|
+
? Math.abs(actual - expected) <= Math.max(1, Math.abs(expected)) * Number.EPSILON * Math.max(1, rows.length)
|
|
157
|
+
: canonicalJson(actual) === canonicalJson(expected);
|
|
158
|
+
if (!equal)
|
|
159
|
+
throw new Error(`Burn projection differs from the harness: ${field}.`);
|
|
160
|
+
}
|
|
161
|
+
// Use the signed reducer's exact summation order for the terminal amount.
|
|
162
|
+
snapshot.list_price_exposure = run.metrics.list_price_exposure.value;
|
|
163
|
+
}
|
|
164
|
+
const frame = { version: 1, at: event.timestamp, data: { kind: 'bench', snapshot }, viewport: { width: 104, height: 35 } };
|
|
165
|
+
recordingBytes += Buffer.byteLength(JSON.stringify(frame)) + 1;
|
|
166
|
+
if (recordingBytes > MAX_BYTES)
|
|
167
|
+
throw new Error('Projected recording exceeds the 128 MB render limit.');
|
|
168
|
+
return frame;
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
async function importBench(runDir, options = {}) {
|
|
172
|
+
const source = (0, node_fs_1.realpathSync)(runDir), directory = (0, node_path_1.resolve)(options.out ?? `${source}.burn`);
|
|
173
|
+
const relation = (0, node_path_1.relative)(source, directory);
|
|
174
|
+
if (!relation || (!relation.startsWith('..' + node_path_1.sep) && relation !== '..' && !(0, node_path_1.isAbsolute)(relation)))
|
|
175
|
+
throw new Error('Import output must be outside the signed bundle.');
|
|
176
|
+
if ((0, node_fs_1.existsSync)(directory))
|
|
177
|
+
throw new Error(`Refusing to overwrite existing output: ${directory}`);
|
|
178
|
+
const bundle = await verifiedBundle(source, options.expectedPublisherKeyId);
|
|
179
|
+
const frames = projectFrames(bundle);
|
|
180
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(directory), { recursive: true, mode: 0o700 });
|
|
181
|
+
const staging = (0, node_fs_1.mkdtempSync)((0, node_path_1.join)((0, node_path_1.dirname)(directory), '.burn-bench-import-'));
|
|
182
|
+
try {
|
|
183
|
+
writeFiles((0, node_path_1.join)(staging, 'bundle'), bundle.files);
|
|
184
|
+
(0, node_fs_1.writeFileSync)((0, node_path_1.join)(staging, 'replay.json'), canonicalJson(replayDocument(bundle, options.expectedPublisherKeyId)) + '\n', { flag: 'wx', mode: 0o600 });
|
|
185
|
+
(0, node_fs_1.writeFileSync)((0, node_path_1.join)(staging, 'recording.jsonl'), frames.map(frame => JSON.stringify(frame)).join('\n') + '\n', { flag: 'wx', mode: 0o600 });
|
|
186
|
+
if ((0, node_fs_1.existsSync)(directory))
|
|
187
|
+
throw new Error(`Refusing to overwrite existing output: ${directory}`);
|
|
188
|
+
(0, node_fs_1.renameSync)(staging, directory);
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
(0, node_fs_1.rmSync)(staging, { recursive: true, force: true });
|
|
192
|
+
}
|
|
193
|
+
return { directory, replayPath: (0, node_path_1.join)(directory, 'replay.json'), recordingPath: (0, node_path_1.join)(directory, 'recording.jsonl'),
|
|
194
|
+
pricingPath: (0, node_path_1.join)(directory, 'bundle', 'pricing.json'), verification: bundle.verification, run: bundle.run };
|
|
195
|
+
}
|
|
196
|
+
async function replayBench(replayPath, pricingPath, options = {}) {
|
|
197
|
+
if (!pricingPath)
|
|
198
|
+
throw new Error('DisciplineBench replay requires --pricing <snapshot.json>; no current prices are used.');
|
|
199
|
+
const path = (0, node_fs_1.realpathSync)(replayPath), document = JSON.parse(localFile(path).toString('utf8'));
|
|
200
|
+
if (document?.format !== 'agentguard-burn/disciplinebench' || document.version !== 1 || document.bundle !== 'bundle'
|
|
201
|
+
|| !(document.expected_publisher_key_id === null || typeof document.expected_publisher_key_id === 'string'))
|
|
202
|
+
throw new Error('Invalid DisciplineBench replay input.');
|
|
203
|
+
const pin = document.expected_publisher_key_id ?? undefined;
|
|
204
|
+
if (pin && options.expectedPublisherKeyId && pin !== options.expectedPublisherKeyId)
|
|
205
|
+
throw new Error('Publisher pin differs from the imported bundle.');
|
|
206
|
+
const bundle = await verifiedBundle((0, node_path_1.join)((0, node_path_1.dirname)(path), 'bundle'), pin);
|
|
207
|
+
if (options.expectedPublisherKeyId && options.expectedPublisherKeyId !== bundle.verification.publisher_key_id)
|
|
208
|
+
throw new Error('Untrusted publisher key.');
|
|
209
|
+
if (canonicalJson(document) !== canonicalJson(replayDocument(bundle, pin)))
|
|
210
|
+
throw new Error('Imported replay projection was modified. Re-import the signed bundle.');
|
|
211
|
+
if (hash(localFile(pricingPath)) !== bundle.pricing_sha256)
|
|
212
|
+
throw new Error('Pricing snapshot differs from the signed round snapshot.');
|
|
213
|
+
const frames = projectFrames(bundle);
|
|
214
|
+
return { run: bundle.run, events: bundle.events, verification: { ...bundle.verification, publisher_pinned: Boolean(pin || options.expectedPublisherKeyId) }, frames, pricing_sha256: bundle.pricing_sha256 };
|
|
215
|
+
}
|
|
216
|
+
function renderBenchReplay(result) {
|
|
217
|
+
const { run, verification } = result, value = (metric) => metric.value === null ? `unknown (${metric.reason})` : String(metric.value);
|
|
218
|
+
const exposure = run.metrics.list_price_exposure;
|
|
219
|
+
return [
|
|
220
|
+
'AGENTGUARD / BURN | RECORDED RUN | DisciplineBench', `Run: ${run.run_id}${run.fixture ? ' (fixture)' : ''}`,
|
|
221
|
+
`Chain and signatures: verified | Publisher ${verification.publisher_key_id} | Measurement ${verification.measurement_key_id}`,
|
|
222
|
+
verification.publisher_pinned ? 'Publisher key: pinned' : 'Embedded keys prove integrity, not external identity. Pin a trusted publisher key with --publisher-key-id.',
|
|
223
|
+
`Pricing snapshot SHA-256: ${result.pricing_sha256}`,
|
|
224
|
+
`List-price exposure: ${exposure.value === null ? value(exposure) : `$${exposure.value.toFixed(2)} USD (${exposure.value} unrounded)`}`,
|
|
225
|
+
`Spawns: ${value(run.metrics.spawn_count)} | Max depth: ${value(run.metrics.max_spawn_depth)}`,
|
|
226
|
+
`Context replay share: ${value(run.metrics.context_replay_share)}`,
|
|
227
|
+
...Object.entries(run.metrics.tokens).map(([name, count]) => `Tokens ${name}: ${count ?? 'unknown'}`),
|
|
228
|
+
...run.spawn_tree.map(node => `Agent ${node.agent_id} | parent ${node.parent_agent_id ?? 'root'} | depth ${node.spawn_depth}`),
|
|
229
|
+
...run.policy_decisions.map(decision => `${decision.tool_name ?? 'unknown'} | ${decision.classification} | ${decision.rule_ids.join(', ') || 'no matches'} | enforced:false`),
|
|
230
|
+
'List price is a comparability convention, never a bill. STOP is a classification; execution was not blocked.',
|
|
231
|
+
].join('\n') + '\n';
|
|
232
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Instrument frames projected only from verified DisciplineBench observations. */
|
|
2
|
+
import { Canvas } from './canvas';
|
|
3
|
+
import type { FrameOptions } from './frames';
|
|
4
|
+
export declare const BENCH_TOKEN_CATEGORIES: readonly ["input", "cache_read", "cache_write_5m", "cache_write_1h", "cache_write_unknown", "output", "reasoning_output", "replay_input", "context_input"];
|
|
5
|
+
export interface BenchPanelDecision {
|
|
6
|
+
tool_call_id: string;
|
|
7
|
+
classification: 'CLEAN' | 'WARN' | 'STOP';
|
|
8
|
+
rule_ids: string[];
|
|
9
|
+
enforced: false;
|
|
10
|
+
tool_name?: string | null;
|
|
11
|
+
}
|
|
12
|
+
export interface BenchPanelSnapshot {
|
|
13
|
+
run_id: string;
|
|
14
|
+
observed_at: string;
|
|
15
|
+
started_at: string | null;
|
|
16
|
+
event_type: string;
|
|
17
|
+
model: string | null;
|
|
18
|
+
status: string | null;
|
|
19
|
+
pricing_snapshot: string | null;
|
|
20
|
+
list_price_exposure: number | null;
|
|
21
|
+
context_replay_share: number | null;
|
|
22
|
+
spawn_count: number | null;
|
|
23
|
+
max_spawn_depth: number | null;
|
|
24
|
+
tokens: Record<string, number | null>;
|
|
25
|
+
native_tokens: Record<string, number | null>;
|
|
26
|
+
spawn_tree: Array<{
|
|
27
|
+
agent_id: string;
|
|
28
|
+
parent_agent_id: string | null;
|
|
29
|
+
spawn_depth: number;
|
|
30
|
+
}>;
|
|
31
|
+
policy_decisions: BenchPanelDecision[];
|
|
32
|
+
coverage: {
|
|
33
|
+
lineage: boolean;
|
|
34
|
+
usage: boolean;
|
|
35
|
+
policy: boolean;
|
|
36
|
+
};
|
|
37
|
+
rule_reasons?: Record<string, string>;
|
|
38
|
+
unknown_reasons?: Record<string, string>;
|
|
39
|
+
}
|
|
40
|
+
/** Recordings are user-controlled input; reject malformed frames before rasterizing. */
|
|
41
|
+
export declare function validateBenchPanelSnapshot(value: unknown): value is BenchPanelSnapshot;
|
|
42
|
+
export declare function renderBenchPanel(snapshot: BenchPanelSnapshot, options?: FrameOptions): Canvas;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.BENCH_TOKEN_CATEGORIES = void 0;
|
|
4
|
+
exports.validateBenchPanelSnapshot = validateBenchPanelSnapshot;
|
|
5
|
+
exports.renderBenchPanel = renderBenchPanel;
|
|
6
|
+
/** Instrument frames projected only from verified DisciplineBench observations. */
|
|
7
|
+
const canvas_1 = require("./canvas");
|
|
8
|
+
exports.BENCH_TOKEN_CATEGORIES = ['input', 'cache_read', 'cache_write_5m', 'cache_write_1h', 'cache_write_unknown', 'output', 'reasoning_output', 'replay_input', 'context_input'];
|
|
9
|
+
const object = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
10
|
+
const count = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0;
|
|
11
|
+
const optionalCount = (value) => value === null || count(value);
|
|
12
|
+
const optionalText = (value) => value === null || typeof value === 'string';
|
|
13
|
+
const timestamp = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value));
|
|
14
|
+
const dictionary = (value, test) => object(value) && Object.values(value).every(test);
|
|
15
|
+
/** Recordings are user-controlled input; reject malformed frames before rasterizing. */
|
|
16
|
+
function validateBenchPanelSnapshot(value) {
|
|
17
|
+
if (!object(value) || typeof value.run_id !== 'string' || !timestamp(value.observed_at)
|
|
18
|
+
|| !(value.started_at === null || timestamp(value.started_at) && Date.parse(value.started_at) <= Date.parse(value.observed_at))
|
|
19
|
+
|| typeof value.event_type !== 'string' || ![value.model, value.status, value.pricing_snapshot].every(optionalText)
|
|
20
|
+
|| ![value.list_price_exposure, value.spawn_count, value.max_spawn_depth].every(optionalCount)
|
|
21
|
+
|| !(value.context_replay_share === null || count(value.context_replay_share) && value.context_replay_share <= 1)
|
|
22
|
+
|| !dictionary(value.tokens, optionalCount) || !dictionary(value.native_tokens, optionalCount)
|
|
23
|
+
|| !object(value.coverage) || ![value.coverage.lineage, value.coverage.usage, value.coverage.policy].every(item => typeof item === 'boolean')
|
|
24
|
+
|| !(value.rule_reasons === undefined || dictionary(value.rule_reasons, item => typeof item === 'string'))
|
|
25
|
+
|| !(value.unknown_reasons === undefined || dictionary(value.unknown_reasons, item => typeof item === 'string')))
|
|
26
|
+
return false;
|
|
27
|
+
if (!Array.isArray(value.spawn_tree) || !value.spawn_tree.every(node => object(node) && typeof node.agent_id === 'string'
|
|
28
|
+
&& optionalText(node.parent_agent_id) && count(node.spawn_depth) && Number.isInteger(node.spawn_depth)))
|
|
29
|
+
return false;
|
|
30
|
+
return Array.isArray(value.policy_decisions) && value.policy_decisions.every(decision => object(decision)
|
|
31
|
+
&& typeof decision.tool_call_id === 'string' && ['CLEAN', 'WARN', 'STOP'].includes(String(decision.classification))
|
|
32
|
+
&& Array.isArray(decision.rule_ids) && decision.rule_ids.every(id => typeof id === 'string') && decision.enforced === false
|
|
33
|
+
&& (decision.tool_name === undefined || optionalText(decision.tool_name)));
|
|
34
|
+
}
|
|
35
|
+
const metric = (value) => value === null || value === undefined ? 'unknown' : value.toLocaleString('en-US', { maximumFractionDigits: 6 });
|
|
36
|
+
const fit = (text, width) => text.length <= width ? text : width > 3 ? text.slice(0, width - 3) + '...' : text.slice(0, width);
|
|
37
|
+
const tint = (decision) => decision.classification === 'STOP' ? 'red' : decision.classification === 'WARN' ? 'amber' : 'mint';
|
|
38
|
+
function pair(name, value, width) {
|
|
39
|
+
const labelWidth = Math.max(0, width - value.length - 1);
|
|
40
|
+
return `${fit(name, labelWidth).padEnd(labelWidth)} ${value}`;
|
|
41
|
+
}
|
|
42
|
+
function remaining(total, shown) { return `+${total - shown} more in recording`; }
|
|
43
|
+
function renderBenchPanel(snapshot, options = {}) {
|
|
44
|
+
const c = new canvas_1.Canvas(options), w = c.width, h = c.height, wide = w >= 80, tall = h >= 30;
|
|
45
|
+
const split = wide ? Math.floor(w / 2) : w, leftWidth = wide ? split - 2 : w, right = split + 2, rightWidth = w - right;
|
|
46
|
+
const line = (row, col, text, width, color = 'white') => { c.put(row, col, fit(text, width), color); };
|
|
47
|
+
c.header('AGENTGUARD / BURN', 'RECORDED RUN · 1x');
|
|
48
|
+
c.footer('list-price convention · enforced:false', snapshot.observed_at.slice(11, 19) + ' UTC');
|
|
49
|
+
line(2, 0, `${snapshot.run_id} · ${snapshot.event_type} · ${snapshot.status ?? 'unknown'}`, w, 'slate');
|
|
50
|
+
line(3, 0, `model ${snapshot.model ?? 'unknown'} · pricing ${snapshot.pricing_snapshot ?? 'unknown'}`, w, 'slate');
|
|
51
|
+
if (wide)
|
|
52
|
+
for (let row = 5; row < h - 3; row++)
|
|
53
|
+
c.put(row, split, '│', 'slate');
|
|
54
|
+
const exposure = snapshot.list_price_exposure === null ? 'unknown' : snapshot.list_price_exposure.toFixed(2);
|
|
55
|
+
const amount = snapshot.list_price_exposure === null ? 'unknown' : `$${exposure}`;
|
|
56
|
+
const cents = /^[0-9]+\.[0-9]{2}$/.test(exposure) ? BigInt(exposure.replace('.', '')).toString() : null;
|
|
57
|
+
const exposureRow = tall ? 5 : 4;
|
|
58
|
+
line(exposureRow, 0, `LIST-PRICE EXPOSURE · USD ${amount}`, leftWidth, 'mint');
|
|
59
|
+
if (tall) {
|
|
60
|
+
if (snapshot.list_price_exposure === null)
|
|
61
|
+
line(exposureRow + 2, 0, 'unknown', leftWidth, 'slate');
|
|
62
|
+
else if (cents !== null && cents.length * 4 <= leftWidth)
|
|
63
|
+
c.digits(exposureRow + 1, 0, cents, 'mint');
|
|
64
|
+
else
|
|
65
|
+
line(exposureRow + 2, 0, amount, leftWidth, 'mint');
|
|
66
|
+
const units = cents !== null && cents.length * 4 <= leftWidth ? 'CENTS · ' : '';
|
|
67
|
+
line(exposureRow + 4, 0, snapshot.unknown_reasons?.list_price_exposure ?? `${units}Pinned round snapshot · never a bill`, leftWidth, 'slate');
|
|
68
|
+
}
|
|
69
|
+
const replay = snapshot.context_replay_share === null ? 'unknown' : `${(snapshot.context_replay_share * 100).toFixed(1)}%`;
|
|
70
|
+
line(tall ? 10 : 5, 0, `CONTEXT REPLAY SHARE ${replay}`, leftWidth, 'white');
|
|
71
|
+
if (wide) {
|
|
72
|
+
line(exposureRow, right, `SPAWNS ${metric(snapshot.spawn_count)} · DEPTH ${metric(snapshot.max_spawn_depth)}`, rightWidth, 'mint');
|
|
73
|
+
line(exposureRow + 1, right, 'spawn ceiling unknown · window unknown', rightWidth, 'slate');
|
|
74
|
+
line(exposureRow + 2, right, 'policy decisions are observations', rightWidth, 'slate');
|
|
75
|
+
if (tall)
|
|
76
|
+
line(exposureRow + 3, right, `lineage ${snapshot.coverage.lineage ? 'recorded' : 'unknown'} · usage ${snapshot.coverage.usage ? 'recorded' : 'unknown'}`, rightWidth, 'slate');
|
|
77
|
+
}
|
|
78
|
+
const tokenHeader = tall ? 12 : 8, tokenFirst = tokenHeader + 1;
|
|
79
|
+
line(tokenHeader, 0, 'TOKEN CATEGORIES', leftWidth, 'mint');
|
|
80
|
+
exports.BENCH_TOKEN_CATEGORIES.forEach((category, index) => line(tokenFirst + index, 0, pair(category, metric(snapshot.tokens[category]), leftWidth), leftWidth));
|
|
81
|
+
if (wide) {
|
|
82
|
+
line(tokenHeader, right, 'POLICY DECISIONS · RULE IDS', rightWidth, 'mint');
|
|
83
|
+
const recent = snapshot.policy_decisions.slice(-2);
|
|
84
|
+
if (!recent.length)
|
|
85
|
+
line(tokenFirst, right, snapshot.coverage.policy ? 'No decisions recorded' : 'unknown', rightWidth, 'slate');
|
|
86
|
+
recent.forEach((decision, index) => {
|
|
87
|
+
const row = tokenFirst + index * 4, color = tint(decision);
|
|
88
|
+
line(row, right, `${decision.classification} · enforced:false · ${decision.tool_name ?? 'unknown'}`, rightWidth, color);
|
|
89
|
+
line(row + 1, right, `call ${decision.tool_call_id}`, rightWidth, 'white');
|
|
90
|
+
line(row + 2, right, `rules ${decision.rule_ids.length ? decision.rule_ids.join(', ') : 'none'}`, rightWidth, color);
|
|
91
|
+
const reasons = decision.rule_ids.map(id => snapshot.rule_reasons?.[id] ?? 'unknown').join('; ');
|
|
92
|
+
line(row + 3, right, reasons || (decision.classification === 'CLEAN' ? 'No rule matched' : 'unknown'), rightWidth, 'slate');
|
|
93
|
+
});
|
|
94
|
+
if (snapshot.policy_decisions.length > recent.length)
|
|
95
|
+
line(tokenFirst + 8, right, remaining(snapshot.policy_decisions.length, recent.length), rightWidth, 'slate');
|
|
96
|
+
}
|
|
97
|
+
const nativeHeader = tokenFirst + exports.BENCH_TOKEN_CATEGORIES.length + 1, nativeFirst = nativeHeader + 1;
|
|
98
|
+
const slots = Math.max(0, h - 3 - nativeFirst);
|
|
99
|
+
if (slots) {
|
|
100
|
+
line(nativeHeader, 0, 'NATIVE TOKEN CATEGORIES', leftWidth, 'mint');
|
|
101
|
+
const entries = Object.entries(snapshot.native_tokens), shown = entries.length > slots ? slots - 1 : slots;
|
|
102
|
+
if (!entries.length)
|
|
103
|
+
line(nativeFirst, 0, 'unknown', leftWidth, 'slate');
|
|
104
|
+
entries.slice(0, shown).forEach(([name, value], index) => line(nativeFirst + index, 0, pair(name, metric(value), leftWidth), leftWidth));
|
|
105
|
+
if (entries.length > slots)
|
|
106
|
+
line(nativeFirst + slots - 1, 0, remaining(entries.length, shown), leftWidth, 'slate');
|
|
107
|
+
if (wide) {
|
|
108
|
+
line(nativeHeader, right, 'SPAWN TREE · CHILD <- PARENT [DEPTH]', rightWidth, 'mint');
|
|
109
|
+
const nodes = snapshot.spawn_tree, treeShown = nodes.length > slots ? slots - 1 : slots;
|
|
110
|
+
if (!nodes.length)
|
|
111
|
+
line(nativeFirst, right, 'unknown', rightWidth, 'slate');
|
|
112
|
+
nodes.slice(0, treeShown).forEach((node, index) => line(nativeFirst + index, right, `${node.agent_id}${node.parent_agent_id === null ? ' (root)' : ` <- ${node.parent_agent_id}`} [${node.spawn_depth}]`, rightWidth));
|
|
113
|
+
if (nodes.length > slots)
|
|
114
|
+
line(nativeFirst + slots - 1, right, remaining(nodes.length, treeShown), rightWidth, 'slate');
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
line(h - 3, 0, 'Missing evidence: unknown · full tokens, lineage and decisions retained in recording', w, 'slate');
|
|
118
|
+
return c;
|
|
119
|
+
}
|
package/dist/src/cli.d.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*
|
|
5
5
|
* ps local agent processes, held memory and orphan workspace disk
|
|
6
6
|
* reap interactively SIGTERM selected safe processes, never delete
|
|
7
|
+
* record reconstruct a session recording from its ledger decisions
|
|
7
8
|
* replay what enforcement would have stopped, on your history
|
|
8
9
|
* calibrate fit thresholds to your own usage, write shadow policy
|
|
9
10
|
* status mode, shadow decisions, eligibility, every host's sessions
|