@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
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.atText = exports.locationId = exports.identifier = exports.object = void 0;
|
|
4
|
+
exports.timestamp = timestamp;
|
|
5
|
+
exports.jsonRows = jsonRows;
|
|
6
|
+
exports.historyDecisions = historyDecisions;
|
|
7
|
+
exports.selectHistory = selectHistory;
|
|
8
|
+
exports.reportTable = reportTable;
|
|
9
|
+
const node_fs_1 = require("node:fs");
|
|
10
|
+
const node_path_1 = require("node:path");
|
|
11
|
+
const node_string_decoder_1 = require("node:string_decoder");
|
|
12
|
+
const receipt_1 = require("../receipt");
|
|
13
|
+
const sessions_1 = require("./sessions");
|
|
14
|
+
const object = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
15
|
+
exports.object = object;
|
|
16
|
+
const identifier = (value) => typeof value === 'string' && /^[A-Za-z0-9_.:/-]{1,160}$/.test(value) ? value : null;
|
|
17
|
+
exports.identifier = identifier;
|
|
18
|
+
function timestamp(value) {
|
|
19
|
+
const n = typeof value === 'string' ? Date.parse(value) : typeof value === 'number' ? value : NaN;
|
|
20
|
+
return Number.isFinite(n) && n >= 0 && n <= 8.64e15 ? n : null;
|
|
21
|
+
}
|
|
22
|
+
/** Bounded input buffers; no transcript content is retained or written. */
|
|
23
|
+
function* jsonRows(file, scan = { malformed: 0 }) {
|
|
24
|
+
const fd = (0, node_fs_1.openSync)(file, 'r'), bytes = Buffer.alloc(64 * 1024), decoder = new node_string_decoder_1.StringDecoder('utf8');
|
|
25
|
+
let pending = '';
|
|
26
|
+
function parse(line) {
|
|
27
|
+
if (!line.trim())
|
|
28
|
+
return null;
|
|
29
|
+
try {
|
|
30
|
+
return (0, exports.object)(JSON.parse(line));
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
scan.malformed++;
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
let length;
|
|
39
|
+
while ((length = (0, node_fs_1.readSync)(fd, bytes, 0, bytes.length, null))) {
|
|
40
|
+
pending += decoder.write(bytes.subarray(0, length));
|
|
41
|
+
let end;
|
|
42
|
+
while ((end = pending.indexOf('\n')) >= 0) {
|
|
43
|
+
const row = parse(pending.slice(0, end));
|
|
44
|
+
pending = pending.slice(end + 1);
|
|
45
|
+
if (row)
|
|
46
|
+
yield row;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const row = parse(pending + decoder.end());
|
|
50
|
+
if (row)
|
|
51
|
+
yield row;
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
(0, node_fs_1.closeSync)(fd);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** The receipt and flat ledger are two views of a decision, not two decisions. */
|
|
58
|
+
function historyDecisions(home) {
|
|
59
|
+
const scan = { malformed: 0 }, decisions = [], matched = new Set();
|
|
60
|
+
for (const file of ['decisions.ndjson', 'receipts.ndjson']) {
|
|
61
|
+
try {
|
|
62
|
+
for (const raw of jsonRows((0, node_path_1.join)(home, file), scan)) {
|
|
63
|
+
const p = Object.keys((0, exports.object)(raw.payload)).length ? (0, exports.object)(raw.payload) : raw;
|
|
64
|
+
if (!['OK', 'WARN', 'STOP'].includes(String(p.verdict)))
|
|
65
|
+
continue;
|
|
66
|
+
const sessionId = (0, exports.identifier)(p.sessionId ?? p.session_id);
|
|
67
|
+
const digest = sessionId ? (0, receipt_1.sha256)(sessionId) : typeof p.sessionDigest === 'string' && /^[a-f0-9]{64}$/.test(p.sessionDigest) ? p.sessionDigest : null;
|
|
68
|
+
if (!digest)
|
|
69
|
+
continue;
|
|
70
|
+
const findings = Array.isArray(p.findings) ? p.findings.map(exports.object) : [];
|
|
71
|
+
const reasons = Array.isArray(p.reasons) ? p.reasons : findings.map(f => f.detector);
|
|
72
|
+
const row = {
|
|
73
|
+
id: (0, exports.identifier)(p.decisionId ?? p.toolUseId) ?? (0, receipt_1.sha256)(JSON.stringify(p)), session: sessionId ?? `sha256:${digest}`, digest,
|
|
74
|
+
at: timestamp(p.at ?? p.timestamp), verdict: p.verdict,
|
|
75
|
+
mode: (0, exports.identifier)(p.mode ?? (0, exports.object)(p.policy).mode),
|
|
76
|
+
blocked: typeof p.enforced === 'boolean' ? p.enforced : typeof p.blocked === 'boolean' ? p.blocked : null,
|
|
77
|
+
wouldBlock: typeof p.wouldDeny === 'boolean' ? p.wouldDeny : p.verdict === 'STOP', action: (0, exports.identifier)(p.action ?? p.tool),
|
|
78
|
+
detectors: [...new Set(reasons.flatMap(r => typeof r === 'string' && /^[a-z][a-z0-9_]*(?::(?:OK|WARN|STOP))?$/.test(r) ? [r.split(':')[0]] : []))],
|
|
79
|
+
};
|
|
80
|
+
const duplicate = file === 'receipts.ndjson' ? decisions.findIndex((d, i) => !matched.has(i) && d.digest === digest && d.at === row.at
|
|
81
|
+
&& d.verdict === row.verdict && d.blocked === row.blocked && (!d.action || !row.action || d.action === row.action)) : -1;
|
|
82
|
+
if (duplicate >= 0) {
|
|
83
|
+
matched.add(duplicate);
|
|
84
|
+
const prior = decisions[duplicate];
|
|
85
|
+
decisions[duplicate] = { ...prior, id: row.id, mode: prior.mode ?? row.mode, detectors: [...new Set([...prior.detectors, ...row.detectors])] };
|
|
86
|
+
}
|
|
87
|
+
else
|
|
88
|
+
decisions.push(row);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (error.code !== 'ENOENT')
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return { decisions: decisions.sort((a, b) => (a.at ?? Infinity) - (b.at ?? Infinity)), malformed: scan.malformed };
|
|
97
|
+
}
|
|
98
|
+
const locationId = (item) => item.host === 'codex'
|
|
99
|
+
? /([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/i.exec(item.sessionId)?.[1] ?? item.sessionId : item.sessionId;
|
|
100
|
+
exports.locationId = locationId;
|
|
101
|
+
function selectHistory(session, locations, decisions) {
|
|
102
|
+
if (session === 'all')
|
|
103
|
+
return { locations, decisions };
|
|
104
|
+
const requested = session || process.env.AGENTGUARD_SESSION_ID || process.env.CLAUDE_SESSION_ID || process.env.CODEX_THREAD_ID;
|
|
105
|
+
let selected;
|
|
106
|
+
try {
|
|
107
|
+
selected = (0, sessions_1.selectInsightTranscript)(requested, locations.filter(l => !/[\\/]subagents[\\/]/.test(l.path)));
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (!requested || !decisions.some(d => d.session === requested || d.digest === requested.replace(/^sha256:/, '') || d.digest === (0, receipt_1.sha256)(requested)))
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
const ids = new Set([requested, selected?.sessionId, selected && (0, exports.locationId)(selected)].filter((x) => Boolean(x)));
|
|
114
|
+
const digests = new Set([...ids].flatMap(id => [(0, receipt_1.sha256)(id), id.replace(/^sha256:/, '')]));
|
|
115
|
+
return { locations: selected ? [selected] : [], decisions: decisions.filter(d => ids.has(d.session) || digests.has(d.digest)) };
|
|
116
|
+
}
|
|
117
|
+
function reportTable(headers, rows) {
|
|
118
|
+
const widths = headers.map((h, i) => rows.reduce((n, r) => Math.max(n, r[i]?.length ?? 0), h.length));
|
|
119
|
+
return [headers, ...rows].map(row => row.map((cell, i) => cell.padEnd(widths[i])).join(' ').trimEnd()).join('\n');
|
|
120
|
+
}
|
|
121
|
+
const atText = (at) => at === null ? 'unknown' : new Date(at).toISOString();
|
|
122
|
+
exports.atText = atText;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type HistoryDecision, type Row } from './history';
|
|
2
|
+
import { type TranscriptLocation } from './sessions';
|
|
3
|
+
export interface LimitEvent {
|
|
4
|
+
id: string;
|
|
5
|
+
at: number | null;
|
|
6
|
+
status: 'rejected' | 'allowed_warning' | 'rate_limit';
|
|
7
|
+
window: string | null;
|
|
8
|
+
resetsAt: number | null;
|
|
9
|
+
lockedMinutes: number | null;
|
|
10
|
+
model: string | null;
|
|
11
|
+
http429: boolean;
|
|
12
|
+
}
|
|
13
|
+
/** Known Claude metadata only. Text mentioning a limit is not a host event. */
|
|
14
|
+
export declare function parseLimitEvent(raw: Row): LimitEvent | null;
|
|
15
|
+
export interface CorrelatedLimit extends LimitEvent {
|
|
16
|
+
nearest: HistoryDecision | null;
|
|
17
|
+
gapMinutes: number | null;
|
|
18
|
+
fanoutWithin60: boolean;
|
|
19
|
+
}
|
|
20
|
+
export declare function correlateLimit(event: LimitEvent, decisions: HistoryDecision[]): CorrelatedLimit;
|
|
21
|
+
/** Union the recorded rejection-to-reset intervals, not repeated retry durations. */
|
|
22
|
+
export declare function lockedMinutes(events: LimitEvent[]): number;
|
|
23
|
+
export declare function limitsReport(home: string, session?: string, options?: {
|
|
24
|
+
locations?: TranscriptLocation[];
|
|
25
|
+
}): {
|
|
26
|
+
method: {
|
|
27
|
+
proximity: string;
|
|
28
|
+
duration: string;
|
|
29
|
+
codex: string;
|
|
30
|
+
};
|
|
31
|
+
sessions: {
|
|
32
|
+
events: CorrelatedLimit[];
|
|
33
|
+
lockedMinutes: number;
|
|
34
|
+
session: string;
|
|
35
|
+
host: string;
|
|
36
|
+
status: string;
|
|
37
|
+
unreadable: number;
|
|
38
|
+
}[];
|
|
39
|
+
totals: {
|
|
40
|
+
wallsHit: number;
|
|
41
|
+
warnings: number;
|
|
42
|
+
lockedMinutes: number;
|
|
43
|
+
sessionLockedMinutes: number;
|
|
44
|
+
unknownResetWalls: number;
|
|
45
|
+
fanoutWithin60: number;
|
|
46
|
+
unsupportedSessions: number;
|
|
47
|
+
};
|
|
48
|
+
malformedLines: number;
|
|
49
|
+
};
|
|
50
|
+
export declare function renderLimits(report: ReturnType<typeof limitsReport>): string;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseLimitEvent = parseLimitEvent;
|
|
4
|
+
exports.correlateLimit = correlateLimit;
|
|
5
|
+
exports.lockedMinutes = lockedMinutes;
|
|
6
|
+
exports.limitsReport = limitsReport;
|
|
7
|
+
exports.renderLimits = renderLimits;
|
|
8
|
+
const node_path_1 = require("node:path");
|
|
9
|
+
const receipt_1 = require("../receipt");
|
|
10
|
+
const history_1 = require("./history");
|
|
11
|
+
const sessions_1 = require("./sessions");
|
|
12
|
+
/** Known Claude metadata only. Text mentioning a limit is not a host event. */
|
|
13
|
+
function parseLimitEvent(raw) {
|
|
14
|
+
const info = (0, history_1.object)(raw.quotaLimits ?? raw.rateLimitInfo ?? raw.rateLimitEvent);
|
|
15
|
+
const error = (0, history_1.object)(raw.error);
|
|
16
|
+
const http429 = (raw.apiErrorStatus === 429 || raw.statusCode === 429 || error.status === 429)
|
|
17
|
+
&& (raw.error === 'rate_limit' || error.type === 'rate_limit_error');
|
|
18
|
+
const status = info.status === 'rejected' || info.status === 'allowed_warning' ? info.status : http429 ? 'rate_limit' : null;
|
|
19
|
+
if (!status)
|
|
20
|
+
return null;
|
|
21
|
+
const at = (0, history_1.timestamp)(raw.timestamp ?? raw.at);
|
|
22
|
+
const resetsAt = typeof info.resetsAt === 'number' && Number.isFinite(info.resetsAt) && info.resetsAt > 0 ? (0, history_1.timestamp)(info.resetsAt * 1000) : null;
|
|
23
|
+
let detail = (0, history_1.object)(raw.errorDetails);
|
|
24
|
+
if (typeof raw.errorDetails === 'string') {
|
|
25
|
+
try {
|
|
26
|
+
detail = (0, history_1.object)(JSON.parse(raw.errorDetails.replace(/^429\s+/, '')));
|
|
27
|
+
}
|
|
28
|
+
catch { /* No free-text quota or date inference. */ }
|
|
29
|
+
}
|
|
30
|
+
const detailMessage = (0, history_1.object)(detail.error).message;
|
|
31
|
+
const namedModels = typeof detailMessage === 'string' ? [...new Set(detailMessage.match(/\bclaude-[a-z0-9]+(?:-[a-z0-9]+)+\b/g) ?? [])] : [];
|
|
32
|
+
const model = (0, history_1.identifier)(info.model ?? error.model ?? (0, history_1.object)(detail.error).model ?? detail.model ?? raw.model ?? (0, history_1.object)(raw.message).model)
|
|
33
|
+
?? (http429 && namedModels.length === 1 ? namedModels[0] : null);
|
|
34
|
+
const value = { at, status, window: (0, history_1.identifier)(info.rateLimitType), resetsAt,
|
|
35
|
+
lockedMinutes: status === 'allowed_warning' && !http429 ? 0 : at !== null && resetsAt !== null ? Math.max(0, resetsAt - at) / 60000 : null,
|
|
36
|
+
model, http429 };
|
|
37
|
+
return { id: (0, history_1.identifier)(raw.uuid) ?? (0, receipt_1.sha256)(JSON.stringify(value)), ...value };
|
|
38
|
+
}
|
|
39
|
+
function correlateLimit(event, decisions) {
|
|
40
|
+
const before = event.at === null ? [] : decisions.filter(d => d.at !== null && d.at < event.at && (d.verdict === 'WARN' || d.verdict === 'STOP')).sort((a, b) => b.at - a.at);
|
|
41
|
+
const nearest = before[0] ?? null;
|
|
42
|
+
return { ...event, nearest, gapMinutes: nearest ? (event.at - nearest.at) / 60000 : null,
|
|
43
|
+
fanoutWithin60: before.some(d => event.at - d.at <= 3600000 && d.detectors.some(name => ['fanout', 'spawn_rate', 'depth'].includes(name))) };
|
|
44
|
+
}
|
|
45
|
+
/** Union the recorded rejection-to-reset intervals, not repeated retry durations. */
|
|
46
|
+
function lockedMinutes(events) {
|
|
47
|
+
const spans = events.filter(e => (e.status !== 'allowed_warning' || e.http429) && e.at !== null && e.resetsAt !== null && e.resetsAt > e.at)
|
|
48
|
+
.map(e => [e.at, e.resetsAt]).sort((a, b) => a[0] - b[0]);
|
|
49
|
+
let end = 0, total = 0;
|
|
50
|
+
for (const [start, reset] of spans) {
|
|
51
|
+
total += Math.max(0, reset - Math.max(start, end));
|
|
52
|
+
end = Math.max(end, reset);
|
|
53
|
+
}
|
|
54
|
+
return total / 60000;
|
|
55
|
+
}
|
|
56
|
+
function limitsReport(home, session, options = {}) {
|
|
57
|
+
const ledger = (0, history_1.historyDecisions)(home), all = options.locations ?? (0, sessions_1.discoverInsightTranscripts)();
|
|
58
|
+
const selected = (0, history_1.selectHistory)(session, all, ledger.decisions);
|
|
59
|
+
const groups = new Map();
|
|
60
|
+
const scan = { malformed: 0 };
|
|
61
|
+
const locations = session === 'all' ? all : selected.locations.flatMap(item => [item, ...all.filter(child => child.path.startsWith((0, node_path_1.join)(item.path.replace(/\.jsonl$/, ''), 'subagents') + '/'))]);
|
|
62
|
+
for (const item of locations) {
|
|
63
|
+
const id = item.host === 'claude' && (0, node_path_1.basename)((0, node_path_1.dirname)(item.path)) === 'subagents' ? (0, node_path_1.basename)((0, node_path_1.dirname)((0, node_path_1.dirname)(item.path))) : (0, history_1.locationId)(item);
|
|
64
|
+
let group = groups.get(id);
|
|
65
|
+
if (!group) {
|
|
66
|
+
group = { session: id, host: item.host, status: item.host === 'codex' ? 'unsupported' : 'supported', events: [], unreadable: 0 };
|
|
67
|
+
groups.set(id, group);
|
|
68
|
+
}
|
|
69
|
+
if (item.host === 'codex')
|
|
70
|
+
continue;
|
|
71
|
+
const decisions = ledger.decisions.filter(d => d.digest === (0, receipt_1.sha256)(id));
|
|
72
|
+
try {
|
|
73
|
+
for (const row of (0, history_1.jsonRows)(item.path, scan)) {
|
|
74
|
+
const event = parseLimitEvent(row);
|
|
75
|
+
if (event && !group.events.some(e => e.id === event.id))
|
|
76
|
+
group.events.push(correlateLimit(event, decisions));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
group.unreadable++;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
for (const d of selected.decisions)
|
|
84
|
+
if (![...groups.values()].some(g => (0, receipt_1.sha256)(g.session) === d.digest) && !groups.has(d.session))
|
|
85
|
+
groups.set(d.session, { session: d.session, host: 'unknown', status: 'transcript missing', events: [], unreadable: 1 });
|
|
86
|
+
const sessions = [...groups.values()].map(group => ({ ...group, events: group.events.sort((a, b) => (a.at ?? Infinity) - (b.at ?? Infinity)), lockedMinutes: lockedMinutes(group.events) }));
|
|
87
|
+
const events = sessions.flatMap(g => g.events), walls = events.filter(e => e.status !== 'allowed_warning' || e.http429);
|
|
88
|
+
return { method: { proximity: 'Proximity is correlation.', duration: 'Recorded rejection-to-reset interval union, not measured inability to work.', codex: 'unsupported' },
|
|
89
|
+
sessions, totals: { wallsHit: walls.length, warnings: events.length - walls.length, lockedMinutes: lockedMinutes(walls),
|
|
90
|
+
sessionLockedMinutes: sessions.reduce((n, s) => n + s.lockedMinutes, 0), unknownResetWalls: walls.filter(e => e.lockedMinutes === null).length,
|
|
91
|
+
fanoutWithin60: walls.filter(e => e.fanoutWithin60).length, unsupportedSessions: sessions.filter(s => s.status === 'unsupported').length },
|
|
92
|
+
malformedLines: scan.malformed + ledger.malformed };
|
|
93
|
+
}
|
|
94
|
+
function renderLimits(report) {
|
|
95
|
+
const lines = ['AgentGuard limits: local Claude Code plan-window events', 'Proximity is correlation, not evidence that fan-out caused a limit.',
|
|
96
|
+
'Allowed warnings are not walls and add zero lockout minutes. HTTP 429 without a reset has unknown lockout.',
|
|
97
|
+
'Minutes are time from rejection until the recorded reset, not measured time unable to work. Overlapping intervals count once.',
|
|
98
|
+
'Codex limit format is unsupported. No Codex limits are inferred.'];
|
|
99
|
+
for (const s of report.sessions) {
|
|
100
|
+
lines.push('', `Session ${s.session} (${s.host}): ${s.status}`);
|
|
101
|
+
if (s.status === 'unsupported')
|
|
102
|
+
continue;
|
|
103
|
+
if (s.unreadable)
|
|
104
|
+
lines.push(`${s.unreadable} transcripts missing or unreadable. Coverage is incomplete.`);
|
|
105
|
+
if (!s.events.length) {
|
|
106
|
+
lines.push('No known limit events found in readable transcripts.');
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
lines.push((0, history_1.reportTable)(['Time (UTC)', 'Status', 'Window', 'Reset (UTC)', 'Locked minutes', 'Model', 'HTTP 429', 'Prior Burn', 'Gap minutes', 'Fan-out within 60 min'], s.events.map(e => [(0, history_1.atText)(e.at), e.status, e.window ?? 'unknown', (0, history_1.atText)(e.resetsAt), e.lockedMinutes?.toFixed(3) ?? 'unknown', e.model ?? 'unknown', e.http429 ? 'yes' : 'no',
|
|
110
|
+
e.nearest ? `${e.nearest.verdict} ${e.nearest.detectors.join(',')} at ${(0, history_1.atText)(e.nearest.at)}` : 'none', e.gapMinutes?.toFixed(3) ?? 'unknown', e.fanoutWithin60 ? 'yes' : 'no'])));
|
|
111
|
+
lines.push(`Session lockout interval union: ${s.lockedMinutes.toFixed(3)} minutes.`);
|
|
112
|
+
}
|
|
113
|
+
const t = report.totals;
|
|
114
|
+
lines.push('', `Rollup: ${t.wallsHit} walls hit; ${t.warnings} allowed warnings; ${t.lockedMinutes.toFixed(3)} minutes locked out until recorded resets (machine interval union).`, `Sum of session interval unions: ${t.sessionLockedMinutes.toFixed(3)} minutes. Concurrent sessions can share plan windows.`, `${t.unknownResetWalls} walls have unknown reset duration; ${t.fanoutWithin60} walls had a fan-out WARN or STOP within 60 minutes before them.`, `${t.unsupportedSessions} Codex sessions unsupported; ${report.malformedLines} malformed lines skipped. Proximity is correlation.`);
|
|
115
|
+
return lines.join('\n');
|
|
116
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { childStatistics, type ChildEconomics } from './blocks';
|
|
2
|
+
import { type DollarRange } from './pricing';
|
|
3
|
+
import { type TranscriptLocation } from './sessions';
|
|
4
|
+
export declare const PRICE_LABEL = "Dollars are list-price equivalents, not the bill.";
|
|
5
|
+
export interface ShadowChild extends ChildEconomics {
|
|
6
|
+
startedAt: number | null;
|
|
7
|
+
found: boolean;
|
|
8
|
+
models: string[];
|
|
9
|
+
responses: number;
|
|
10
|
+
reason: string | null;
|
|
11
|
+
}
|
|
12
|
+
export interface Exposure {
|
|
13
|
+
children: ShadowChild[];
|
|
14
|
+
statistics: ReturnType<typeof childStatistics>;
|
|
15
|
+
found: number;
|
|
16
|
+
unknownStartChildren: number;
|
|
17
|
+
unresolvedSpawns: number;
|
|
18
|
+
usd: DollarRange | null;
|
|
19
|
+
knownUsd: DollarRange;
|
|
20
|
+
sensitivities: Record<string, DollarRange | null>;
|
|
21
|
+
knownSensitivities: Record<string, DollarRange | null>;
|
|
22
|
+
modelMix: Array<{
|
|
23
|
+
model: string;
|
|
24
|
+
responses: number;
|
|
25
|
+
tokens: number;
|
|
26
|
+
usd: DollarRange | null;
|
|
27
|
+
input: number;
|
|
28
|
+
cacheRead: number;
|
|
29
|
+
cacheWrite: number;
|
|
30
|
+
write5m: number;
|
|
31
|
+
write1h: number;
|
|
32
|
+
writeUnknown: number;
|
|
33
|
+
output: number;
|
|
34
|
+
}>;
|
|
35
|
+
}
|
|
36
|
+
export declare function priceShadowReport(home: string, session?: string, options?: {
|
|
37
|
+
locations?: TranscriptLocation[];
|
|
38
|
+
}): {
|
|
39
|
+
method: {
|
|
40
|
+
dollars: string;
|
|
41
|
+
total: string;
|
|
42
|
+
sensitivity: string;
|
|
43
|
+
snapshot: string;
|
|
44
|
+
missing: string;
|
|
45
|
+
};
|
|
46
|
+
sessions: {
|
|
47
|
+
session: string;
|
|
48
|
+
notes: string[];
|
|
49
|
+
malformedLines: number;
|
|
50
|
+
decisions: {
|
|
51
|
+
exposure: Exposure;
|
|
52
|
+
id: string;
|
|
53
|
+
session: string;
|
|
54
|
+
digest: string;
|
|
55
|
+
at: number | null;
|
|
56
|
+
verdict: "OK" | "WARN" | "STOP";
|
|
57
|
+
mode: string | null;
|
|
58
|
+
blocked: boolean | null;
|
|
59
|
+
wouldBlock: boolean;
|
|
60
|
+
action: string | null;
|
|
61
|
+
detectors: string[];
|
|
62
|
+
}[];
|
|
63
|
+
firstWouldBlock: number | null;
|
|
64
|
+
hasWouldBlock: boolean;
|
|
65
|
+
total: Exposure | null;
|
|
66
|
+
}[];
|
|
67
|
+
totals: {
|
|
68
|
+
shadowDecisions: number;
|
|
69
|
+
wouldBlockDecisions: number;
|
|
70
|
+
sessionsWithWouldBlock: number;
|
|
71
|
+
unpricedSessions: number;
|
|
72
|
+
usd: DollarRange | null;
|
|
73
|
+
knownUsd: DollarRange;
|
|
74
|
+
sensitivities: {
|
|
75
|
+
[k: string]: DollarRange | null;
|
|
76
|
+
};
|
|
77
|
+
knownSensitivities: {
|
|
78
|
+
[k: string]: DollarRange | null;
|
|
79
|
+
};
|
|
80
|
+
};
|
|
81
|
+
pricing: Readonly<Record<string, import("./pricing").ModelPricing>>;
|
|
82
|
+
malformedLedgerLines: number;
|
|
83
|
+
};
|
|
84
|
+
export declare function renderPriceShadow(report: ReturnType<typeof priceShadowReport>): string;
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PRICE_LABEL = void 0;
|
|
4
|
+
exports.priceShadowReport = priceShadowReport;
|
|
5
|
+
exports.renderPriceShadow = renderPriceShadow;
|
|
6
|
+
const node_fs_1 = require("node:fs");
|
|
7
|
+
const node_path_1 = require("node:path");
|
|
8
|
+
const receipt_1 = require("../receipt");
|
|
9
|
+
const blocks_1 = require("./blocks");
|
|
10
|
+
const history_1 = require("./history");
|
|
11
|
+
const pricing_1 = require("./pricing");
|
|
12
|
+
const render_1 = require("./render");
|
|
13
|
+
const sessions_1 = require("./sessions");
|
|
14
|
+
const transcript_1 = require("./transcript");
|
|
15
|
+
exports.PRICE_LABEL = 'Dollars are list-price equivalents, not the bill.';
|
|
16
|
+
const SENSITIVITY = ['claude-fable-5-1', 'claude-sonnet-5'];
|
|
17
|
+
/** Reuse the usage parser incrementally, retaining metadata and response counts only. */
|
|
18
|
+
function readHistory(location, onRow) {
|
|
19
|
+
let result = (0, transcript_1.parseInsightTranscript)('', { host: location.host, sessionId: (0, history_1.locationId)(location), spawnedSession: /[\\/]subagents[\\/]/.test(location.path) });
|
|
20
|
+
const scan = { malformed: 0 };
|
|
21
|
+
let batch = [];
|
|
22
|
+
const flush = () => { if (batch.length) {
|
|
23
|
+
result = (0, transcript_1.parseInsightTranscript)(batch.join('\n'), { state: result.state });
|
|
24
|
+
batch = [];
|
|
25
|
+
} };
|
|
26
|
+
for (const row of (0, history_1.jsonRows)(location.path, scan)) {
|
|
27
|
+
onRow(row);
|
|
28
|
+
batch.push(JSON.stringify(row));
|
|
29
|
+
if (batch.length >= 128)
|
|
30
|
+
flush();
|
|
31
|
+
}
|
|
32
|
+
flush();
|
|
33
|
+
result.diagnostics.malformedLines += scan.malformed;
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
36
|
+
/** Only structured tool results establish child ids. Never mine prompt text. */
|
|
37
|
+
function collectSpawns(row, calls) {
|
|
38
|
+
const message = (0, history_1.object)(row.message), payload = (0, history_1.object)(row.payload), at = (0, history_1.timestamp)(row.timestamp);
|
|
39
|
+
const content = Array.isArray(message.content) ? message.content.map(history_1.object) : [];
|
|
40
|
+
if (row.type === 'response_item')
|
|
41
|
+
content.push(payload);
|
|
42
|
+
for (const block of content) {
|
|
43
|
+
const name = (0, history_1.identifier)(block.name), id = (0, history_1.identifier)(block.id ?? block.call_id ?? block.tool_use_id);
|
|
44
|
+
if (!id)
|
|
45
|
+
continue;
|
|
46
|
+
if (['tool_use', 'function_call', 'custom_tool_call'].includes(String(block.type)) && name && /^(?:(?:functions\.)?(?:Agent|Task|spawn_agent))$/.test(name)) {
|
|
47
|
+
if (!calls.has(id))
|
|
48
|
+
calls.set(id, { at });
|
|
49
|
+
}
|
|
50
|
+
if (!['tool_result', 'function_call_output', 'custom_tool_call_output'].includes(String(block.type)))
|
|
51
|
+
continue;
|
|
52
|
+
const call = calls.get(id);
|
|
53
|
+
if (!call)
|
|
54
|
+
continue;
|
|
55
|
+
let result = (0, history_1.object)(row.toolUseResult);
|
|
56
|
+
if (typeof block.output === 'string') {
|
|
57
|
+
try {
|
|
58
|
+
result = (0, history_1.object)(JSON.parse(block.output));
|
|
59
|
+
}
|
|
60
|
+
catch { /* A text summary is not child lineage. */ }
|
|
61
|
+
}
|
|
62
|
+
const child = (0, history_1.identifier)(result.agentId ?? result.agent_id);
|
|
63
|
+
if (child)
|
|
64
|
+
call.child = child;
|
|
65
|
+
if (block.is_error === true || result.status === 'failed')
|
|
66
|
+
call.failed = true;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function loadChildren(parentLocation, locations) {
|
|
70
|
+
const notes = [], calls = new Map();
|
|
71
|
+
let parent;
|
|
72
|
+
try {
|
|
73
|
+
parent = readHistory(parentLocation, row => collectSpawns(row, calls));
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return { children: [], available: false, notes: ['Parent transcript missing or unreadable: unpriced.'], malformed: 0, unresolved: [] };
|
|
77
|
+
}
|
|
78
|
+
const ids = new Set([parentLocation.sessionId, (0, history_1.locationId)(parentLocation), parent.state.lineage?.sessionId].filter(Boolean));
|
|
79
|
+
let candidates, available = true;
|
|
80
|
+
if (parentLocation.host === 'claude') {
|
|
81
|
+
const directory = (0, node_path_1.join)(parentLocation.path.replace(/\.jsonl$/, ''), 'subagents');
|
|
82
|
+
try {
|
|
83
|
+
candidates = (0, node_fs_1.readdirSync)(directory).filter(n => n.endsWith('.jsonl')).sort().map(n => ({ path: (0, node_path_1.join)(directory, n), host: 'claude', sessionId: (0, node_path_1.basename)(n, '.jsonl'), modifiedAt: 0 }));
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
candidates = [];
|
|
87
|
+
available = false;
|
|
88
|
+
notes.push('Child directory missing or unreadable: unpriced, never evidence of zero children.');
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
else
|
|
92
|
+
candidates = locations.filter(l => l.host === 'codex' && l.path !== parentLocation.path);
|
|
93
|
+
const children = [];
|
|
94
|
+
let malformed = parent.diagnostics.malformedLines;
|
|
95
|
+
for (const item of candidates) {
|
|
96
|
+
let startedAt = null, declaredParent = null;
|
|
97
|
+
const childName = (0, history_1.locationId)(item).replace(/^agent-/, '');
|
|
98
|
+
try {
|
|
99
|
+
const parsed = readHistory(item, row => {
|
|
100
|
+
if (row.type === 'session_meta') {
|
|
101
|
+
const p = (0, history_1.object)(row.payload);
|
|
102
|
+
declaredParent = (0, history_1.identifier)(p.parent_thread_id ?? (0, history_1.object)((0, history_1.object)((0, history_1.object)(p.source).subagent).thread_spawn).parent_thread_id);
|
|
103
|
+
startedAt = (0, history_1.timestamp)(p.timestamp ?? row.timestamp);
|
|
104
|
+
}
|
|
105
|
+
else if (row.type === 'fork-context-ref') {
|
|
106
|
+
declaredParent = (0, history_1.identifier)(row.parentSessionId);
|
|
107
|
+
startedAt = (0, history_1.timestamp)(row.timestamp);
|
|
108
|
+
}
|
|
109
|
+
else if (item.host === 'claude' && startedAt === null && row.type === 'user'
|
|
110
|
+
&& (0, history_1.identifier)(row.agentId) === childName && row.isSidechain === true)
|
|
111
|
+
startedAt = (0, history_1.timestamp)(row.timestamp);
|
|
112
|
+
});
|
|
113
|
+
if ((declaredParent && !ids.has(declaredParent)) || (item.host === 'codex' && !declaredParent))
|
|
114
|
+
continue;
|
|
115
|
+
malformed += parsed.diagnostics.malformedLines;
|
|
116
|
+
children.push({ child: childName, startedAt, turns: parsed.turns, missing: false,
|
|
117
|
+
unknownBoundary: parsed.state.forkHistoryBoundaryUnknown === true, forked: parsed.state.lineage?.forked === true });
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
if (item.host === 'claude')
|
|
121
|
+
children.push({ child: childName, startedAt, turns: [], missing: true, unknownBoundary: false, forked: false });
|
|
122
|
+
else {
|
|
123
|
+
available = false;
|
|
124
|
+
notes.push('A Codex transcript is unreadable; child discovery is incomplete.');
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
for (const call of calls.values())
|
|
129
|
+
if (call.child && !call.failed && !children.some(c => c.child === call.child))
|
|
130
|
+
children.push({ child: call.child, startedAt: call.at, turns: [], missing: true, unknownBoundary: false, forked: false });
|
|
131
|
+
const parentIds = new Set(parent.turns.map(turn => turn.id));
|
|
132
|
+
const own = (0, transcript_1.deduplicateTurns)(children.flatMap(c => c.turns).filter(turn => !parentIds.has(turn.id)));
|
|
133
|
+
for (const child of children) {
|
|
134
|
+
const sessionIds = new Set(child.turns.map(t => t.sessionId));
|
|
135
|
+
child.turns = own.filter(t => sessionIds.has(t.sessionId));
|
|
136
|
+
}
|
|
137
|
+
if (malformed) {
|
|
138
|
+
available = false;
|
|
139
|
+
notes.push('Malformed transcript rows make full exposure unpriced; the known subset is shown separately.');
|
|
140
|
+
}
|
|
141
|
+
return { children, available, notes, malformed, unresolved: [...calls.values()].filter(c => !c.child && !c.failed).map(c => c.at) };
|
|
142
|
+
}
|
|
143
|
+
function exposure(history, at) {
|
|
144
|
+
const eligible = history.children.filter(c => at !== null && c.startedAt !== null && c.startedAt > at);
|
|
145
|
+
const unknown = history.children.filter(c => c.startedAt === null).length;
|
|
146
|
+
const unresolvedSpawns = history.unresolved.filter(start => start === null || at === null || start > at).length;
|
|
147
|
+
const children = eligible.map(c => {
|
|
148
|
+
const reason = c.missing ? 'transcript missing' : c.unknownBoundary ? 'inherited usage boundary unknown' : !c.turns.length ? 'no attributable usage' : null;
|
|
149
|
+
return { child: c.child, startedAt: c.startedAt, found: !c.missing, kind: c.forked ? 'fork' : 'fresh', forkContextRef: c.forked,
|
|
150
|
+
tokens: reason ? null : c.turns.reduce((n, t) => n + (0, render_1.totalTokens)(t), 0), usd: reason ? null : (0, render_1.sumPrices)(c.turns.map(t => (0, pricing_1.priceTurn)(t).usd)),
|
|
151
|
+
unknownModels: [...new Set(c.turns.filter(t => !(0, pricing_1.priceTurn)(t).usd).map(t => t.model ?? 'unknown'))],
|
|
152
|
+
models: [...new Set(c.turns.map(t => t.model ?? 'unknown'))], responses: c.turns.length, reason };
|
|
153
|
+
});
|
|
154
|
+
const complete = history.available && at !== null && !unknown && !unresolvedSpawns && children.every(c => c.tokens !== null);
|
|
155
|
+
const turns = (0, transcript_1.deduplicateTurns)(eligible.filter(c => !c.missing && !c.unknownBoundary).flatMap(c => c.turns));
|
|
156
|
+
const knownTurns = turns.filter(t => (0, pricing_1.priceTurn)(t).usd !== null);
|
|
157
|
+
const modelMix = [...new Set(turns.map(t => t.model ?? 'unknown'))].sort().map(model => {
|
|
158
|
+
const selected = turns.filter(t => (t.model ?? 'unknown') === model);
|
|
159
|
+
const sum = (key) => selected.reduce((n, t) => n + t[key], 0);
|
|
160
|
+
const writes = selected.reduce((totals, t) => {
|
|
161
|
+
const five = t.cacheWrite5mTokens ?? 0, hour = t.cacheWrite1hTokens ?? 0, other = t.cacheWriteTokens - five - hour;
|
|
162
|
+
totals.write5m += five + (t.cacheTtlSeconds === 300 ? other : 0);
|
|
163
|
+
totals.write1h += hour + (t.cacheTtlSeconds === 3600 ? other : 0);
|
|
164
|
+
totals.writeUnknown += t.cacheTtlSeconds ? 0 : other;
|
|
165
|
+
return totals;
|
|
166
|
+
}, { write5m: 0, write1h: 0, writeUnknown: 0 });
|
|
167
|
+
return { model, responses: selected.length, tokens: selected.reduce((n, t) => n + (0, render_1.totalTokens)(t), 0), usd: (0, render_1.sumPrices)(selected.map(t => (0, pricing_1.priceTurn)(t).usd)),
|
|
168
|
+
input: sum('inputTokens'), cacheRead: sum('cacheReadTokens'), cacheWrite: sum('cacheWriteTokens'), output: sum('outputTokens'), ...writes };
|
|
169
|
+
});
|
|
170
|
+
return { children, statistics: (0, blocks_1.childStatistics)(children), found: children.filter(c => c.found).length, unknownStartChildren: unknown, unresolvedSpawns,
|
|
171
|
+
usd: complete ? (0, render_1.sumPrices)(turns.map(t => (0, pricing_1.priceTurn)(t).usd)) : null,
|
|
172
|
+
knownUsd: (0, render_1.sumPrices)(turns.map(t => (0, pricing_1.priceTurn)(t).usd).filter((x) => x !== null)),
|
|
173
|
+
sensitivities: Object.fromEntries(SENSITIVITY.map(model => [model, complete ? (0, render_1.sumPrices)(turns.map(t => (0, pricing_1.priceTurn)({ ...t, model }).usd)) : null])),
|
|
174
|
+
knownSensitivities: Object.fromEntries(SENSITIVITY.map(model => [model, (0, render_1.sumPrices)(knownTurns.map(t => (0, pricing_1.priceTurn)({ ...t, model }).usd))])), modelMix };
|
|
175
|
+
}
|
|
176
|
+
function priceShadowReport(home, session, options = {}) {
|
|
177
|
+
const ledger = (0, history_1.historyDecisions)(home), locations = options.locations ?? (0, sessions_1.discoverInsightTranscripts)();
|
|
178
|
+
const selection = (0, history_1.selectHistory)(session, locations, ledger.decisions);
|
|
179
|
+
const decisions = selection.decisions.filter(d => d.mode === 'shadow' && d.blocked !== true);
|
|
180
|
+
const aliases = new Map();
|
|
181
|
+
for (const item of [...selection.locations, ...locations])
|
|
182
|
+
for (const id of [item.sessionId, (0, history_1.locationId)(item)])
|
|
183
|
+
if (!aliases.has((0, receipt_1.sha256)(id)))
|
|
184
|
+
aliases.set((0, receipt_1.sha256)(id), item);
|
|
185
|
+
const groups = new Map();
|
|
186
|
+
for (const d of decisions)
|
|
187
|
+
groups.set(d.digest, [...groups.get(d.digest) ?? [], d]);
|
|
188
|
+
const sessions = [...groups].map(([digest, rows]) => {
|
|
189
|
+
const location = aliases.get(digest);
|
|
190
|
+
const history = location ? loadChildren(location, locations) : { children: [], available: false, notes: ['No matching local transcript: unpriced.'], malformed: 0, unresolved: [] };
|
|
191
|
+
const first = rows.find(d => d.wouldBlock && d.at === null) ?? rows.find(d => d.wouldBlock);
|
|
192
|
+
return { session: location ? (0, history_1.locationId)(location) : rows[0].session, notes: history.notes, malformedLines: history.malformed,
|
|
193
|
+
decisions: rows.map(d => ({ ...d, exposure: exposure(history, d.at) })), firstWouldBlock: first ? first.at : null,
|
|
194
|
+
hasWouldBlock: Boolean(first), total: first ? exposure(history, first.at) : null };
|
|
195
|
+
});
|
|
196
|
+
const totals = sessions.flatMap(s => s.total ? [s.total] : []);
|
|
197
|
+
return { method: { dollars: exports.PRICE_LABEL, total: 'Upper bound after the first would-block point per session.', sensitivity: 'Sensitivity, never measurement.',
|
|
198
|
+
snapshot: 'Shipped MODEL_PRICING; local overrides are not used.', missing: 'Unpriced, never imputed.' },
|
|
199
|
+
sessions, totals: { shadowDecisions: decisions.length, wouldBlockDecisions: decisions.filter(d => d.wouldBlock).length,
|
|
200
|
+
sessionsWithWouldBlock: totals.length, unpricedSessions: totals.filter(t => t.usd === null).length,
|
|
201
|
+
usd: (0, render_1.sumPrices)(totals.map(t => t.usd)), knownUsd: (0, render_1.sumPrices)(totals.map(t => t.knownUsd)),
|
|
202
|
+
sensitivities: Object.fromEntries(SENSITIVITY.map(model => [model, (0, render_1.sumPrices)(totals.map(t => t.sensitivities[model] ?? null))])),
|
|
203
|
+
knownSensitivities: Object.fromEntries(SENSITIVITY.map(model => [model, (0, render_1.sumPrices)(totals.map(t => t.knownSensitivities[model] ?? null))])) },
|
|
204
|
+
pricing: pricing_1.MODEL_PRICING, malformedLedgerLines: ledger.malformed };
|
|
205
|
+
}
|
|
206
|
+
function dollars(value) {
|
|
207
|
+
if (!value)
|
|
208
|
+
return 'unpriced';
|
|
209
|
+
return value.min === value.max ? `$${value.min.toFixed(6)}` : `$${value.min.toFixed(6)} to $${value.max.toFixed(6)}`;
|
|
210
|
+
}
|
|
211
|
+
const number = (n) => n === null ? 'unpriced' : n.toLocaleString('en-US');
|
|
212
|
+
function modelTable(value) {
|
|
213
|
+
return exports.PRICE_LABEL + '\n' + (0, history_1.reportTable)(['Model', 'Responses', 'Input tokens', 'Cache-read tokens', 'Write 5m tokens', 'Write 1h tokens', 'Write unknown TTL tokens', 'Output tokens', 'List USD'], value.modelMix.map(m => [m.model, String(m.responses), number(m.input), number(m.cacheRead), number(m.write5m), number(m.write1h), number(m.writeUnknown), number(m.output), dollars(m.usd)]));
|
|
214
|
+
}
|
|
215
|
+
function renderPriceShadow(report) {
|
|
216
|
+
const lines = ['AgentGuard price-shadow: stored local shadow decisions', exports.PRICE_LABEL,
|
|
217
|
+
'Pinned API list snapshot. Child usage is deduplicated by provider response id; inherited parent responses are excluded.',
|
|
218
|
+
'Children must start strictly after the decision. A Claude child start is its first own sidechain user event or timestamped fork marker; Codex uses session metadata.',
|
|
219
|
+
'Missing transcripts, unknown start times, unresolved spawns and unknown inherited boundaries are unpriced. Nothing is imputed.',
|
|
220
|
+
'Each cohort covers the full available child transcript. Decision cohorts overlap and must not be added together.',
|
|
221
|
+
'Exposure after the first would-block point is an upper bound, not attributable prevention. Sensitivity re-prices recorded token categories, never a measurement.'];
|
|
222
|
+
for (const s of report.sessions) {
|
|
223
|
+
lines.push('', `Session ${s.session}`, ...s.notes, exports.PRICE_LABEL, (0, history_1.reportTable)(['Decision (UTC)', 'Verdict', 'Would block', 'Children found', 'Measured', 'Median tokens', 'Max tokens', 'Median list USD', 'Max list USD', 'Model mix'], s.decisions.map(d => {
|
|
224
|
+
const e = d.exposure, stats = e.statistics;
|
|
225
|
+
return [(0, history_1.atText)(d.at), d.verdict, d.wouldBlock ? 'yes' : 'no', String(e.found), String(stats.measuredCount), number(stats.medianTokens), number(stats.maxTokens),
|
|
226
|
+
dollars(e.usd === null ? null : stats.medianUsd), dollars(e.usd === null ? null : stats.maxUsd), e.modelMix.map(m => `${m.model}:${m.responses} responses`).join(', ') || 'unpriced'];
|
|
227
|
+
})));
|
|
228
|
+
for (const d of s.decisions)
|
|
229
|
+
if (d.exposure.unknownStartChildren || d.exposure.unresolvedSpawns || d.exposure.children.some(c => c.reason))
|
|
230
|
+
lines.push(`${(0, history_1.atText)(d.at)}: ${d.exposure.unknownStartChildren} children with unknown start; ${d.exposure.unresolvedSpawns} unresolved spawns; ${d.exposure.children.filter(c => c.reason).length} children unpriced.`);
|
|
231
|
+
if (!s.total) {
|
|
232
|
+
lines.push('No would-block point in this session; no exposure total.');
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
lines.push(`First would-block point: ${(0, history_1.atText)(s.firstWouldBlock)}. Upper bound: ${dollars(s.total.usd)}. Known priced subset: ${dollars(s.total.knownUsd)}.`, `Sensitivity, never measurement: Fable 5.1 ${dollars(s.total.sensitivities[SENSITIVITY[0]] ?? null)}; Sonnet 5 ${dollars(s.total.sensitivities[SENSITIVITY[1]] ?? null)}.`, modelTable(s.total), exports.PRICE_LABEL, (0, history_1.reportTable)(['Child', 'Start (UTC)', 'Found', 'Responses', 'Tokens', 'List USD', 'Models', 'Unpriced reason'], s.total.children.map(c => [c.child, (0, history_1.atText)(c.startedAt), c.found ? 'yes' : 'no', String(c.responses), number(c.tokens), dollars(c.usd), c.models.join(',') || 'unknown', c.reason ?? c.unknownModels.join(',')])));
|
|
236
|
+
}
|
|
237
|
+
const t = report.totals;
|
|
238
|
+
lines.push('', exports.PRICE_LABEL, `Rollup: ${t.shadowDecisions} shadow decisions; ${t.wouldBlockDecisions} would-block decisions in ${t.sessionsWithWouldBlock} sessions.`, `Upper bound after each session's first would-block point: ${dollars(t.usd)}; ${t.unpricedSessions} sessions unpriced. Known priced subset: ${dollars(t.knownUsd)}.`, `Sensitivity, never measurement: all children on Fable 5.1 ${dollars(t.sensitivities[SENSITIVITY[0]] ?? null)}; all children on Sonnet 5 ${dollars(t.sensitivities[SENSITIVITY[1]] ?? null)}.`, `Known priced subset sensitivity, never measurement: Fable 5.1 ${dollars(t.knownSensitivities[SENSITIVITY[0]] ?? null)}; Sonnet 5 ${dollars(t.knownSensitivities[SENSITIVITY[1]] ?? null)}.`, 'Arithmetic: each native token category multiplied by its pinned USD per million rate, divided by 1,000,000; sum distinct responses once per session.', 'Pinned long-context multipliers apply where the original request input exceeds the snapshot threshold. Sensitivity preserves token categories, not model behavior.', 'Unknown cache-write TTL yields the range between the pinned five-minute and one-hour rates. Unknown model prices remain unpriced.', exports.PRICE_LABEL, (0, history_1.reportTable)(['Pinned model', 'Input per M', 'Cache read per M', 'Write 5 min per M', 'Write 1 hour per M', 'Output per M', 'Snapshot date'], Object.entries(report.pricing).map(([model, r]) => [model, ...[r.input, r.cacheRead, r.cacheWrite5m, r.cacheWrite1h, r.output].map(v => v === null ? 'unpriced' : String(v)), r.verifiedAt])), `${report.malformedLedgerLines + report.sessions.reduce((n, s) => n + s.malformedLines, 0)} malformed lines skipped.`);
|
|
239
|
+
return lines.join('\n');
|
|
240
|
+
}
|
package/dist/src/recording.js
CHANGED
|
@@ -9,6 +9,7 @@ exports.recordingArguments = recordingArguments;
|
|
|
9
9
|
/** Explicit, local-only frame recording. Never capture rendered output. */
|
|
10
10
|
const node_fs_1 = require("node:fs");
|
|
11
11
|
const node_path_1 = require("node:path");
|
|
12
|
+
const bench_panel_1 = require("./bench-panel");
|
|
12
13
|
let destination;
|
|
13
14
|
let frames = 0;
|
|
14
15
|
function configureRecording(file) { destination = file; frames = 0; }
|
|
@@ -42,12 +43,14 @@ function readRecording(file) {
|
|
|
42
43
|
catch {
|
|
43
44
|
throw new Error(`Invalid recording JSON at line ${index + 1}.`);
|
|
44
45
|
}
|
|
45
|
-
if (row?.version !== 1 || typeof row.at !== 'string' || !Number.isFinite(Date.parse(row.at)) || !row.data || !['audit', 'report', 'replay', 'command', 'live'].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'].includes(row.data.kind))
|
|
46
47
|
throw new Error(`Invalid frame at line ${index + 1}.`);
|
|
47
48
|
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))
|
|
48
49
|
throw new Error(`Invalid viewport at line ${index + 1}.`);
|
|
49
50
|
if (result.length && Date.parse(row.at) < Date.parse(result.at(-1).at))
|
|
50
51
|
throw new Error(`Recording timestamps go backwards at line ${index + 1}.`);
|
|
52
|
+
if (row.data.kind === 'bench' && (!(0, bench_panel_1.validateBenchPanelSnapshot)(row.data.snapshot) || row.at !== row.data.snapshot.observed_at))
|
|
53
|
+
throw new Error(`Invalid bench frame at line ${index + 1}.`);
|
|
51
54
|
if (row.data.kind === 'live') {
|
|
52
55
|
const snapshot = row.data.snapshot;
|
|
53
56
|
const count = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0;
|