@agentguard-run/burn 0.3.28 → 0.4.0
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 +13 -0
- package/dist/src/adapters/codex.d.ts +4 -2
- package/dist/src/adapters/codex.js +55 -9
- package/dist/src/cli.js +35 -5
- package/dist/src/history/claude-transcript.d.ts +0 -13
- package/dist/src/history/claude-transcript.js +11 -10
- package/dist/src/hook/pre-tool-use.d.ts +0 -16
- package/dist/src/hook/pre-tool-use.js +15 -10
- package/dist/src/index.d.ts +4 -1
- package/dist/src/index.js +18 -1
- package/dist/src/insights/launch-evidence.d.ts +25 -0
- package/dist/src/insights/launch-evidence.js +54 -0
- package/dist/src/insights/price-shadow.js +2 -1
- package/dist/src/insights/tally.d.ts +45 -0
- package/dist/src/insights/tally.js +266 -0
- package/dist/src/insights/transcript.js +9 -1
- package/dist/src/insights/tree.d.ts +36 -0
- package/dist/src/insights/tree.js +285 -0
- package/dist/src/insights/types.d.ts +2 -0
- package/dist/src/receipt.d.ts +10 -0
- package/dist/src/receipt.js +53 -2
- package/dist/src/tool-names.d.ts +6 -0
- package/dist/src/tool-names.js +10 -0
- package/dist/src/upgrade-moments.js +2 -1
- package/docs/OCT5_VERIFICATION.md +118 -0
- package/docs/TREE_AND_TALLY.md +70 -0
- package/docs/launch-tree-local-oct5.txt +7 -0
- package/docs/oct5-followup/REPORT.md +105 -0
- package/docs/oct5-followup/checks.json +20 -0
- package/docs/oct5-followup/free-plugin-fixture-output.txt +12 -0
- package/docs/oct5-followup/tally-after.json +5 -0
- package/docs/oct5-followup/tally-after.txt +1 -0
- package/docs/oct5-followup/tree-after.json +40 -0
- package/docs/oct5-followup/tree-after.txt +7 -0
- package/docs/oct5-followup/tree-before.txt +7 -0
- package/docs/oct5-followup/verify-free-receipts.cjs +81 -0
- package/docs/session-tally-local-oct5.txt +1 -0
- package/package.json +7 -3
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.verifyTallyLedger = verifyTallyLedger;
|
|
4
|
+
exports.sessionLaunchReceipts = sessionLaunchReceipts;
|
|
5
|
+
exports.tallyEntries = tallyEntries;
|
|
6
|
+
exports.pluginLedgerDirectories = pluginLedgerDirectories;
|
|
7
|
+
exports.readLedgerTallies = readLedgerTallies;
|
|
8
|
+
exports.readLedgerDailyTallies = readLedgerDailyTallies;
|
|
9
|
+
exports.sessionTally = sessionTally;
|
|
10
|
+
exports.renderSessionTally = renderSessionTally;
|
|
11
|
+
const tool_names_1 = require("../tool-names");
|
|
12
|
+
const node_fs_1 = require("node:fs");
|
|
13
|
+
const node_os_1 = require("node:os");
|
|
14
|
+
const node_path_1 = require("node:path");
|
|
15
|
+
const spend_1 = require("@agentguard-run/spend");
|
|
16
|
+
const spawn = tool_names_1.LAUNCH_TOOLS;
|
|
17
|
+
const missing = (session, reason = 'Signed session receipts are missing.') => ({ status: 'missing', session, reason });
|
|
18
|
+
const failed = (session) => ({ status: 'verification_failed', session, reason: 'Receipt signature or hash chain verification failed.' });
|
|
19
|
+
const meta = (entry) => entry.decision?.plugin ?? {};
|
|
20
|
+
/** Verify the whole physical chain before selecting any session or counting. */
|
|
21
|
+
async function verifyTallyLedger(entries, publicKeyHex) {
|
|
22
|
+
if (!/^[a-f0-9]{64}$/i.test(publicKeyHex))
|
|
23
|
+
return false;
|
|
24
|
+
try {
|
|
25
|
+
if (entries.some(e => e.publicKeyHex && e.publicKeyHex.toLowerCase() !== publicKeyHex.toLowerCase()))
|
|
26
|
+
return false;
|
|
27
|
+
return (await (0, spend_1.verifyChain)(entries, Buffer.from(publicKeyHex, 'hex'))).ok;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function countedSession(entries, session) {
|
|
34
|
+
const own = entries.filter(e => meta(e).sessionId === session);
|
|
35
|
+
const endings = own.filter(e => meta(e).event === 'session_receipt');
|
|
36
|
+
const ending = endings.at(-1);
|
|
37
|
+
if (!ending)
|
|
38
|
+
return missing(session);
|
|
39
|
+
if (own.at(-1) !== ending)
|
|
40
|
+
return missing(session, 'Signed receipts for the resumed session are incomplete.');
|
|
41
|
+
const calls = new Map(), outcomes = new Map();
|
|
42
|
+
for (const e of own) {
|
|
43
|
+
const m = meta(e);
|
|
44
|
+
if (!spawn.has(m.toolName) || typeof m.toolUseId !== 'string')
|
|
45
|
+
continue;
|
|
46
|
+
if (m.gate === 'receipt' && m.event === 'outcome') {
|
|
47
|
+
outcomes.set(m.toolUseId, [...(outcomes.get(m.toolUseId) ?? []), e]);
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (m.gate !== 'burn' || !['decision', 'fail_open', 'fail_closed'].includes(m.event))
|
|
51
|
+
continue;
|
|
52
|
+
calls.set(m.toolUseId, e);
|
|
53
|
+
}
|
|
54
|
+
const c = { launches: calls.size, allowed: 0, asked: 0, saidYes: 0, stopped: 0, shadow: 0, unrecorded: 0, unresolvedAsked: 0 };
|
|
55
|
+
for (const [id, e] of calls) {
|
|
56
|
+
const m = meta(e), d = e.decision;
|
|
57
|
+
if ([m.reasonCode, m.policyReasonCode].includes('burn_external_hook'))
|
|
58
|
+
return missing(session, 'Launch receipts belong to an external hook and are incomplete here.');
|
|
59
|
+
if (m.event === 'fail_open')
|
|
60
|
+
c.unrecorded++;
|
|
61
|
+
else if (m.asked === true || typeof m.approvalRuleId === 'string') {
|
|
62
|
+
if (m.host === 'codex')
|
|
63
|
+
return missing(session, 'This receipt labels a Codex launch as asked; its outcome cannot be tallied.');
|
|
64
|
+
c.asked++;
|
|
65
|
+
if (outcomes.get(id)?.some(o => o.sequence > e.sequence && o.decision.originalDecisionId === d.decisionId))
|
|
66
|
+
c.saidYes++;
|
|
67
|
+
}
|
|
68
|
+
else if (m.event === 'fail_closed' || d.action === 'block')
|
|
69
|
+
c.stopped++;
|
|
70
|
+
else if (d.action === 'allow' || d.action === 'downgrade')
|
|
71
|
+
c.allowed++;
|
|
72
|
+
else if (d.action === 'shadow')
|
|
73
|
+
c.shadow++;
|
|
74
|
+
else
|
|
75
|
+
return missing(session, 'A launch verdict is not supported by this reader.');
|
|
76
|
+
}
|
|
77
|
+
c.unresolvedAsked = c.asked - c.saidYes;
|
|
78
|
+
const receipt = meta(ending).receipt;
|
|
79
|
+
if (!receipt || receipt.version !== 1)
|
|
80
|
+
return missing(session, 'The signed session summary is missing or unsupported.');
|
|
81
|
+
// A signed summary with launches but no matching decisions is not a zero.
|
|
82
|
+
if (receipt?.subagents?.started > c.allowed + c.saidYes + c.shadow + c.unrecorded)
|
|
83
|
+
return missing(session, 'Signed launch receipts are incomplete for this session.');
|
|
84
|
+
if (!/^\d{4}-\d{2}-\d{2}T/.test(ending.decision.timestamp) || !Number.isFinite(Date.parse(ending.decision.timestamp)))
|
|
85
|
+
return failed(session);
|
|
86
|
+
return { status: 'verified', session, host: meta(ending).host ?? meta(calls.values().next().value ?? ending).host ?? 'unknown', counts: c,
|
|
87
|
+
tokens: Number.isSafeInteger(receipt?.tokens) && receipt.tokens >= 0 ? receipt.tokens : null,
|
|
88
|
+
date: new Date(ending.decision.timestamp).toISOString().slice(0, 10),
|
|
89
|
+
lineage: [...calls.values()].filter(e => meta(e).launch || meta(e).agent_id).map(e => {
|
|
90
|
+
const m = meta(e);
|
|
91
|
+
return { toolUseId: m.toolUseId, agent_id: m.agent_id ?? m.launch?.callerId ?? null,
|
|
92
|
+
agent_type: m.agent_type ?? m.launch?.callerType ?? null, depth: m.depth ?? null, launchDepth: m.launch?.depth ?? null };
|
|
93
|
+
}) };
|
|
94
|
+
}
|
|
95
|
+
/** Only verified, complete local ledgers can supply receipt lineage to tree. */
|
|
96
|
+
async function sessionLaunchReceipts(session, options = {}) {
|
|
97
|
+
const result = [];
|
|
98
|
+
for (const data of options.data ? [options.data] : pluginLedgerDirectories(options.home)) {
|
|
99
|
+
if (!(0, node_fs_1.existsSync)((0, node_path_1.join)(data, 'ledger', 'decisions.ndjson')))
|
|
100
|
+
continue;
|
|
101
|
+
const tallies = await readLedgerTallies(data);
|
|
102
|
+
if (tallies.some(t => t.status === 'verification_failed'))
|
|
103
|
+
throw new Error('Receipt signature or hash chain verification failed.');
|
|
104
|
+
if (!tallies.some(t => t.session === session && t.status === 'verified'))
|
|
105
|
+
continue;
|
|
106
|
+
const entries = (0, node_fs_1.readFileSync)((0, node_path_1.join)(data, 'ledger', 'decisions.ndjson'), 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l));
|
|
107
|
+
if (!await verifyTallyLedger(entries, (0, node_fs_1.readFileSync)((0, node_path_1.join)(data, 'public-key.hex'), 'utf8').trim()))
|
|
108
|
+
throw new Error('Receipt signature or hash chain verification failed.');
|
|
109
|
+
result.push(...entries.filter(e => meta(e).sessionId === session));
|
|
110
|
+
}
|
|
111
|
+
return result;
|
|
112
|
+
}
|
|
113
|
+
async function tallyEntries(entries, publicKeyHex, session) {
|
|
114
|
+
if (!entries.length)
|
|
115
|
+
return missing(session);
|
|
116
|
+
if (!await verifyTallyLedger(entries, publicKeyHex))
|
|
117
|
+
return failed(session);
|
|
118
|
+
return countedSession(entries, session);
|
|
119
|
+
}
|
|
120
|
+
function pluginLedgerDirectories(home = process.env.AGENTGUARD_HOME || (0, node_path_1.join)((0, node_os_1.homedir)(), '.agentguard')) {
|
|
121
|
+
const dirs = new Set([process.env.PLUGIN_DATA || process.env.CLAUDE_PLUGIN_DATA || (0, node_path_1.join)(home, 'codex-plugin')]);
|
|
122
|
+
const registry = (0, node_path_1.join)(home, 'plugin-ledgers');
|
|
123
|
+
let files;
|
|
124
|
+
try {
|
|
125
|
+
files = (0, node_fs_1.readdirSync)(registry);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return [...dirs];
|
|
129
|
+
}
|
|
130
|
+
for (const file of files) {
|
|
131
|
+
if (!file.endsWith('.json'))
|
|
132
|
+
continue;
|
|
133
|
+
const entry = (0, node_path_1.join)(registry, file);
|
|
134
|
+
try {
|
|
135
|
+
const text = (0, node_fs_1.readFileSync)(entry, 'utf8'), row = JSON.parse(text);
|
|
136
|
+
if (typeof row?.data !== 'string' || !row.data.trim())
|
|
137
|
+
continue;
|
|
138
|
+
const data = (0, node_path_1.resolve)(row.data);
|
|
139
|
+
let missing = false;
|
|
140
|
+
try {
|
|
141
|
+
missing = !(0, node_fs_1.statSync)(data).isDirectory();
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
if (!['ENOENT', 'ENOTDIR'].includes(error.code ?? ''))
|
|
145
|
+
continue;
|
|
146
|
+
missing = true;
|
|
147
|
+
}
|
|
148
|
+
if (!missing) {
|
|
149
|
+
dirs.add(data);
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
// Prune only the stale pointer, never its target. A concurrently replaced
|
|
153
|
+
// entry is retained. Unreadable or malformed neighbors do not stop discovery.
|
|
154
|
+
if ((0, node_fs_1.readFileSync)(entry, 'utf8') === text)
|
|
155
|
+
(0, node_fs_1.unlinkSync)(entry);
|
|
156
|
+
}
|
|
157
|
+
catch { /* One inaccessible entry must not hide healthy ledgers. */ }
|
|
158
|
+
}
|
|
159
|
+
return [...dirs];
|
|
160
|
+
}
|
|
161
|
+
async function readLedgerTallies(data) {
|
|
162
|
+
let entries, key;
|
|
163
|
+
try {
|
|
164
|
+
const ledgerPath = (0, node_path_1.join)(data, 'ledger', 'decisions.ndjson');
|
|
165
|
+
const text = (0, node_fs_1.readFileSync)(ledgerPath, 'utf8');
|
|
166
|
+
entries = text.split('\n').filter(l => l.trim()).map(l => JSON.parse(l));
|
|
167
|
+
key = (0, node_fs_1.readFileSync)((0, node_path_1.join)(data, 'public-key.hex'), 'utf8').trim();
|
|
168
|
+
if (!await verifyTallyLedger(entries, key))
|
|
169
|
+
return [failed('unknown')];
|
|
170
|
+
// An intact prefix is not complete when the worker's durable head records
|
|
171
|
+
// later rows. Read this existing checkpoint without changing the ledger.
|
|
172
|
+
if ((0, node_fs_1.existsSync)(ledgerPath + '.durable-head.json')) {
|
|
173
|
+
const head = JSON.parse((0, node_fs_1.readFileSync)(ledgerPath + '.durable-head.json', 'utf8'));
|
|
174
|
+
const end = head?.sequence;
|
|
175
|
+
if (head?.version !== 1 || !Number.isSafeInteger(end) || end < -1 || end >= entries.length
|
|
176
|
+
|| head.signerFingerprint !== (0, spend_1.computeSignerFingerprint)(Buffer.from(key, 'hex'))
|
|
177
|
+
|| head.entryHash !== (end < 0 ? spend_1.GENESIS_PREVIOUS_HASH : entries[end]?.entryHash))
|
|
178
|
+
return [failed('unknown')];
|
|
179
|
+
const bytes = Buffer.from(text), prefix = bytes.subarray(0, head.byteLength);
|
|
180
|
+
if (!Number.isSafeInteger(head.byteLength) || head.byteLength < 0 || head.byteLength > bytes.length
|
|
181
|
+
|| (head.byteLength > 0 && bytes[head.byteLength - 1] !== 10)
|
|
182
|
+
|| prefix.toString('utf8').split('\n').filter(l => l.trim()).length !== end + 1)
|
|
183
|
+
return [failed('unknown')];
|
|
184
|
+
}
|
|
185
|
+
for (const file of ['fail-open-pending.ndjson', 'fail-open-pending.ndjson.recovering', 'session-receipts-pending.ndjson', 'ledger/unrecorded.ndjson', 'ledger/decisions.ndjson.sync-error.json']) {
|
|
186
|
+
if ((0, node_fs_1.existsSync)((0, node_path_1.join)(data, file)) && (0, node_fs_1.readFileSync)((0, node_path_1.join)(data, file), 'utf8').trim())
|
|
187
|
+
return [missing('unknown', 'Some decisions have no signed receipt yet.')];
|
|
188
|
+
}
|
|
189
|
+
if (entries.some(e => meta(e).integrity?.truncatedBytes > 0))
|
|
190
|
+
return [missing('unknown', 'The ledger records lost receipt data; a complete tally is unavailable.')];
|
|
191
|
+
}
|
|
192
|
+
catch (e) {
|
|
193
|
+
return e.code === 'ENOENT' ? [missing('unknown')] : [failed('unknown')];
|
|
194
|
+
}
|
|
195
|
+
return [...new Set(entries.filter(e => meta(e).event === 'session_receipt' || (meta(e).gate === 'burn' && spawn.has(meta(e).toolName))).map(e => meta(e).sessionId).filter((s) => typeof s === 'string'))].map(s => countedSession(entries, s));
|
|
196
|
+
}
|
|
197
|
+
/** Completion-day increments, so a resumed session's cumulative totals upload once. */
|
|
198
|
+
async function readLedgerDailyTallies(data) {
|
|
199
|
+
const complete = await readLedgerTallies(data);
|
|
200
|
+
if (complete.some(t => t.status !== 'verified'))
|
|
201
|
+
return complete;
|
|
202
|
+
const entries = (0, node_fs_1.readFileSync)((0, node_path_1.join)(data, 'ledger', 'decisions.ndjson'), 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l));
|
|
203
|
+
if (!await verifyTallyLedger(entries, (0, node_fs_1.readFileSync)((0, node_path_1.join)(data, 'public-key.hex'), 'utf8').trim()))
|
|
204
|
+
return [failed('unknown')];
|
|
205
|
+
const result = [];
|
|
206
|
+
for (const session of new Set(entries.filter(e => meta(e).event === 'session_receipt').map(e => meta(e).sessionId))) {
|
|
207
|
+
if (countedSession(entries, session).status !== 'verified')
|
|
208
|
+
return [missing(session)];
|
|
209
|
+
const days = new Map();
|
|
210
|
+
let priorId;
|
|
211
|
+
for (let index = 0; index < entries.length; index++) {
|
|
212
|
+
const entry = entries[index];
|
|
213
|
+
if (meta(entry).sessionId !== session || meta(entry).event !== 'session_receipt')
|
|
214
|
+
continue;
|
|
215
|
+
if (meta(entry).previousReceiptId && meta(entry).previousReceiptId !== priorId)
|
|
216
|
+
return [missing(session, 'Resumed receipt linkage is incomplete.')];
|
|
217
|
+
priorId = entry.decision.decisionId;
|
|
218
|
+
const tally = countedSession(entries.slice(0, index + 1), session);
|
|
219
|
+
if (tally.status !== 'verified')
|
|
220
|
+
return [tally];
|
|
221
|
+
days.set(tally.date, tally);
|
|
222
|
+
}
|
|
223
|
+
let previous;
|
|
224
|
+
for (const tally of days.values()) {
|
|
225
|
+
const counts = Object.fromEntries(Object.entries(tally.counts).map(([key, value]) => [key, value - (previous?.counts[key] ?? 0)]));
|
|
226
|
+
const tokens = tally.tokens === null || previous?.tokens === null ? null : tally.tokens - (previous?.tokens ?? 0);
|
|
227
|
+
if (Object.values(counts).some(n => n < 0) || (tokens !== null && tokens < 0))
|
|
228
|
+
return [missing(session, 'A resumed session revised an earlier day. Daily counts are unavailable.')];
|
|
229
|
+
result.push({ ...tally, counts, tokens });
|
|
230
|
+
previous = tally;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return result;
|
|
234
|
+
}
|
|
235
|
+
async function sessionTally(session, options = {}) {
|
|
236
|
+
const results = [];
|
|
237
|
+
for (const data of options.data ? [options.data] : pluginLedgerDirectories(options.home)) {
|
|
238
|
+
if (!(0, node_fs_1.existsSync)((0, node_path_1.join)(data, 'ledger', 'decisions.ndjson')))
|
|
239
|
+
continue;
|
|
240
|
+
const rows = await readLedgerTallies(data);
|
|
241
|
+
if (rows.some(r => r.status === 'verification_failed'))
|
|
242
|
+
return failed(session);
|
|
243
|
+
if (rows.some(r => r.session === 'unknown' && r.status === 'missing'))
|
|
244
|
+
return missing(session, 'Signed receipts or their public verification key are incomplete.');
|
|
245
|
+
results.push(...rows.filter(r => r.session === session));
|
|
246
|
+
}
|
|
247
|
+
if (results.length > 1)
|
|
248
|
+
return missing(session, 'This session spans multiple receipt ledgers; a complete tally is unavailable.');
|
|
249
|
+
return results[0] ?? missing(session);
|
|
250
|
+
}
|
|
251
|
+
function renderSessionTally(tally) {
|
|
252
|
+
if (tally.status !== 'verified')
|
|
253
|
+
return tally.reason;
|
|
254
|
+
const c = tally.counts;
|
|
255
|
+
const parts = [`${c.launches} launches`, `${c.allowed} allowed`];
|
|
256
|
+
if (tally.host !== 'codex' || c.asked)
|
|
257
|
+
parts.push(`${c.asked} asked`, `${c.saidYes} you approved`);
|
|
258
|
+
parts.push(`${c.stopped} refused`);
|
|
259
|
+
if (c.unresolvedAsked)
|
|
260
|
+
parts.push(`${c.unresolvedAsked} approval outcome not recorded`);
|
|
261
|
+
if (c.shadow)
|
|
262
|
+
parts.push(`${c.shadow} shadow`);
|
|
263
|
+
if (c.unrecorded)
|
|
264
|
+
parts.push(`${c.unrecorded} fail open`);
|
|
265
|
+
return parts.join(' · ');
|
|
266
|
+
}
|
|
@@ -5,10 +5,12 @@ exports.parseInsightTranscript = parseInsightTranscript;
|
|
|
5
5
|
exports.readInsightTranscript = readInsightTranscript;
|
|
6
6
|
exports.readInsightSession = readInsightSession;
|
|
7
7
|
exports.deduplicateTurns = deduplicateTurns;
|
|
8
|
+
const tool_names_1 = require("../tool-names");
|
|
8
9
|
const node_crypto_1 = require("node:crypto");
|
|
9
10
|
const node_fs_1 = require("node:fs");
|
|
10
11
|
const node_path_1 = require("node:path");
|
|
11
12
|
const subagent_signals_1 = require("../history/subagent-signals");
|
|
13
|
+
const launch_evidence_1 = require("./launch-evidence");
|
|
12
14
|
const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
13
15
|
const count = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0;
|
|
14
16
|
const hasCount = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
|
@@ -91,7 +93,7 @@ function observeTools(raw, state) {
|
|
|
91
93
|
continue;
|
|
92
94
|
const name = typeof block.name === 'string' ? block.name : '';
|
|
93
95
|
const isRead = /^(?:(?:functions\.)?Read|(?:functions\.)?read_file)$/.test(name);
|
|
94
|
-
const isSpawn =
|
|
96
|
+
const isSpawn = (0, tool_names_1.isLaunchTool)(name);
|
|
95
97
|
if (!isRead && !isSpawn)
|
|
96
98
|
continue;
|
|
97
99
|
const id = digest(['tool', toolId]);
|
|
@@ -298,6 +300,8 @@ function observations(calls) {
|
|
|
298
300
|
*/
|
|
299
301
|
function parseInsightTranscript(text, options = {}) {
|
|
300
302
|
const state = options.state ?? emptyState(options);
|
|
303
|
+
if (options.collectLaunchTree)
|
|
304
|
+
state.launchEvidence ??= { nodes: Object.create(null), calls: Object.create(null), edges: [], owners: Object.create(null) };
|
|
301
305
|
state.intervalStateVersion = 1;
|
|
302
306
|
const diagnostics = { lines: 0, malformedLines: 0, duplicateUsageRecords: 0, unsupportedUsageRecords: 0, inheritedUsageRecords: 0 };
|
|
303
307
|
const updated = new Map();
|
|
@@ -368,6 +372,8 @@ function parseInsightTranscript(text, options = {}) {
|
|
|
368
372
|
diagnostics.inheritedUsageRecords++;
|
|
369
373
|
continue;
|
|
370
374
|
}
|
|
375
|
+
if (state.launchEvidence)
|
|
376
|
+
(0, launch_evidence_1.observeLaunchRecord)(raw, state, at);
|
|
371
377
|
observeTools(raw, state);
|
|
372
378
|
observeInputEvents(raw, state);
|
|
373
379
|
observeImageBlocks(raw, state);
|
|
@@ -524,6 +530,8 @@ function parseInsightTranscript(text, options = {}) {
|
|
|
524
530
|
}
|
|
525
531
|
state.seen[id] = turn;
|
|
526
532
|
updated.set(id, turn);
|
|
533
|
+
if (state.launchEvidence?.current)
|
|
534
|
+
state.launchEvidence.owners[id] = state.launchEvidence.current;
|
|
527
535
|
}
|
|
528
536
|
return { host: state.host, sessionId: state.sessionId, turns: Object.values(state.seen), updatedTurns: [...updated.values()], diagnostics, state,
|
|
529
537
|
observations: observations(state.observedCalls ?? {}), acceptedQuotaLineNumbers };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type TranscriptLocation } from './sessions';
|
|
2
|
+
import type { InsightTranscript } from './types';
|
|
3
|
+
import type { LaunchEvidence } from './launch-evidence';
|
|
4
|
+
export interface LaunchNode {
|
|
5
|
+
id: string;
|
|
6
|
+
parent: string | null;
|
|
7
|
+
parentEvidence: string | null;
|
|
8
|
+
name: string;
|
|
9
|
+
models: string[];
|
|
10
|
+
ownTokens: number | null;
|
|
11
|
+
subtreeTokens: number | null;
|
|
12
|
+
tokenShare: number | null;
|
|
13
|
+
/** Active time, with each gap between recorded timestamps capped as in Burn. */
|
|
14
|
+
durationMs: number | null;
|
|
15
|
+
/** Elapsed time between the first and last recorded timestamps, including idle gaps. */
|
|
16
|
+
spanMs: number | null;
|
|
17
|
+
endedWithoutFinishing: boolean;
|
|
18
|
+
children: LaunchNode[];
|
|
19
|
+
depth?: number;
|
|
20
|
+
}
|
|
21
|
+
export interface LaunchTree {
|
|
22
|
+
session: string;
|
|
23
|
+
totalTokens: number | null;
|
|
24
|
+
root: LaunchNode;
|
|
25
|
+
unlinked: LaunchNode[];
|
|
26
|
+
notes: string[];
|
|
27
|
+
}
|
|
28
|
+
/** Edges require recorded parent metadata or a matched launch and result. */
|
|
29
|
+
export declare function buildLaunchTree(transcripts: InsightTranscript[], receipts?: LaunchEvidence): LaunchTree;
|
|
30
|
+
export declare function readLaunchTree(location: TranscriptLocation, locations?: TranscriptLocation[], receipts?: LaunchEvidence): LaunchTree;
|
|
31
|
+
export declare function readLaunchTreeWithReceipts(location: TranscriptLocation, options?: {
|
|
32
|
+
home?: string;
|
|
33
|
+
data?: string;
|
|
34
|
+
locations?: TranscriptLocation[];
|
|
35
|
+
}): Promise<LaunchTree>;
|
|
36
|
+
export declare function renderLaunchTree(tree: LaunchTree, short?: boolean): string;
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildLaunchTree = buildLaunchTree;
|
|
4
|
+
exports.readLaunchTree = readLaunchTree;
|
|
5
|
+
exports.readLaunchTreeWithReceipts = readLaunchTreeWithReceipts;
|
|
6
|
+
exports.renderLaunchTree = renderLaunchTree;
|
|
7
|
+
const node_fs_1 = require("node:fs");
|
|
8
|
+
const node_path_1 = require("node:path");
|
|
9
|
+
const defaults_1 = require("../defaults");
|
|
10
|
+
const subagent_signals_1 = require("../history/subagent-signals");
|
|
11
|
+
const sessions_1 = require("./sessions");
|
|
12
|
+
const transcript_1 = require("./transcript");
|
|
13
|
+
const tally_1 = require("./tally");
|
|
14
|
+
const tokens = (t) => t.inputTokens + t.outputTokens + t.cacheReadTokens + t.cacheWriteTokens;
|
|
15
|
+
const sourceId = (t) => t.state.lineage?.sessionId ?? t.sessionId.replace(/^agent-/, '');
|
|
16
|
+
/** Edges require recorded parent metadata or a matched launch and result. */
|
|
17
|
+
function buildLaunchTree(transcripts, receipts) {
|
|
18
|
+
if (!transcripts.length)
|
|
19
|
+
throw new Error('No session transcript recorded.');
|
|
20
|
+
const rootId = sourceId(transcripts[0]);
|
|
21
|
+
const nodes = new Map(), times = new Map();
|
|
22
|
+
const incomplete = new Set(), owners = new Map();
|
|
23
|
+
const candidates = new Map();
|
|
24
|
+
const signals = { completed: new Set(), ended: new Set(), resumed: new Set() };
|
|
25
|
+
const notes = new Set();
|
|
26
|
+
const get = (id) => {
|
|
27
|
+
if (!nodes.has(id))
|
|
28
|
+
nodes.set(id, { id, parent: null, parentEvidence: null, name: id === rootId ? 'main session' : 'agent', models: [], ownTokens: null, subtreeTokens: null, tokenShare: null, durationMs: null, spanMs: null, endedWithoutFinishing: false, children: [] });
|
|
29
|
+
return nodes.get(id);
|
|
30
|
+
};
|
|
31
|
+
for (const t of transcripts) {
|
|
32
|
+
const sid = sourceId(t), node = get(sid);
|
|
33
|
+
const original = t.state.launchEvidence;
|
|
34
|
+
const mergedNodes = { ...original?.nodes };
|
|
35
|
+
if (t === transcripts[0])
|
|
36
|
+
for (const [id, value] of Object.entries(receipts?.nodes ?? {}))
|
|
37
|
+
mergedNodes[id] = { ...mergedNodes[id], ...value };
|
|
38
|
+
const e = t === transcripts[0] && receipts ? { ...original, nodes: mergedNodes,
|
|
39
|
+
edges: [...(original?.edges ?? []), ...receipts.edges], owners: original?.owners ?? {}, calls: original?.calls ?? {} } : original;
|
|
40
|
+
if (t.state.forkHistoryBoundaryUnknown || t.diagnostics.malformedLines) {
|
|
41
|
+
incomplete.add(sid);
|
|
42
|
+
for (const id of Object.keys(e?.nodes ?? {}))
|
|
43
|
+
incomplete.add(id);
|
|
44
|
+
notes.add('Some token usage is unavailable because transcript ownership or records are incomplete.');
|
|
45
|
+
}
|
|
46
|
+
for (const [id, meta] of Object.entries(e?.nodes ?? {})) {
|
|
47
|
+
const n = get(id);
|
|
48
|
+
if (meta.name)
|
|
49
|
+
n.name = meta.name;
|
|
50
|
+
if (meta.depth !== undefined)
|
|
51
|
+
n.depth = meta.depth;
|
|
52
|
+
if (meta.model && !n.models.includes(meta.model))
|
|
53
|
+
n.models.push(meta.model);
|
|
54
|
+
const activity = times.get(id) ?? new Set();
|
|
55
|
+
for (const at of meta.activityAt ?? [])
|
|
56
|
+
activity.add(at);
|
|
57
|
+
times.set(id, activity);
|
|
58
|
+
}
|
|
59
|
+
const edges = [...(e?.edges ?? [])];
|
|
60
|
+
if (t.state.lineage?.parentSessionId)
|
|
61
|
+
edges.push({ child: sid, parent: t.state.lineage.parentSessionId, source: 'parent metadata' });
|
|
62
|
+
for (const edge of edges) {
|
|
63
|
+
get(edge.child);
|
|
64
|
+
const parents = candidates.get(edge.child) ?? new Map();
|
|
65
|
+
parents.set(edge.parent, edge.source);
|
|
66
|
+
candidates.set(edge.child, parents);
|
|
67
|
+
}
|
|
68
|
+
for (const signal of ['completed', 'ended', 'resumed'])
|
|
69
|
+
for (const id of Object.keys(t.state.subagentSignals?.[signal] ?? {}))
|
|
70
|
+
signals[signal].add(id);
|
|
71
|
+
for (const turn of t.turns) {
|
|
72
|
+
const prior = owners.get(turn.id);
|
|
73
|
+
if (!prior || (turn.at !== undefined && (prior.at === undefined || turn.at < prior.at)))
|
|
74
|
+
owners.set(turn.id, { at: turn.at, id: e?.owners[turn.id] ?? sid });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// Attribute a provider response once, using the same deduplication as why.
|
|
78
|
+
for (const turn of (0, transcript_1.deduplicateTurns)(transcripts.flatMap(t => t.turns))) {
|
|
79
|
+
const id = owners.get(turn.id).id, node = get(id);
|
|
80
|
+
if (!incomplete.has(id))
|
|
81
|
+
node.ownTokens = (node.ownTokens ?? 0) + tokens(turn);
|
|
82
|
+
if (turn.model && !node.models.includes(turn.model))
|
|
83
|
+
node.models.push(turn.model);
|
|
84
|
+
}
|
|
85
|
+
for (const node of nodes.values()) {
|
|
86
|
+
const parents = candidates.get(node.id);
|
|
87
|
+
if (node.id !== rootId && parents?.size === 1) {
|
|
88
|
+
const [parent, evidence] = [...parents][0];
|
|
89
|
+
if (nodes.has(parent) && parent !== node.id) {
|
|
90
|
+
node.parent = parent;
|
|
91
|
+
node.parentEvidence = evidence;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (parents && parents.size > 1)
|
|
95
|
+
notes.add('Conflicting parent records are shown under parent not recorded.');
|
|
96
|
+
node.endedWithoutFinishing = (0, subagent_signals_1.endedWithoutFinishing)(node.id, signals);
|
|
97
|
+
const ts = [...(times.get(node.id) ?? [])].sort((a, b) => a - b);
|
|
98
|
+
if (ts.length) {
|
|
99
|
+
node.spanMs = ts[ts.length - 1] - ts[0];
|
|
100
|
+
node.durationMs = 0;
|
|
101
|
+
for (let i = 1; i < ts.length; i++)
|
|
102
|
+
node.durationMs += Math.min(ts[i] - ts[i - 1], defaults_1.ACTIVE_GAP_CAP_MS);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// Break every edge involved in a cycle. Never choose a guessed parent.
|
|
106
|
+
for (const node of nodes.values()) {
|
|
107
|
+
const seen = new Set([node.id]);
|
|
108
|
+
let current = node;
|
|
109
|
+
while (current.parent) {
|
|
110
|
+
if (seen.has(current.parent)) {
|
|
111
|
+
for (const id of seen) {
|
|
112
|
+
get(id).parent = null;
|
|
113
|
+
get(id).parentEvidence = null;
|
|
114
|
+
}
|
|
115
|
+
notes.add('Cyclic parent records are shown under parent not recorded.');
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
seen.add(current.parent);
|
|
119
|
+
current = get(current.parent);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const unlinked = [];
|
|
123
|
+
for (const node of nodes.values()) {
|
|
124
|
+
if (node.parent)
|
|
125
|
+
get(node.parent).children.push(node);
|
|
126
|
+
else if (node.id !== rootId)
|
|
127
|
+
unlinked.push(node);
|
|
128
|
+
}
|
|
129
|
+
const total = [...nodes.values()].some(n => n.ownTokens === null) ? null : [...nodes.values()].reduce((sum, n) => sum + n.ownTokens, 0);
|
|
130
|
+
const sum = (n) => {
|
|
131
|
+
const child = n.children.map(sum);
|
|
132
|
+
n.subtreeTokens = n.ownTokens === null || child.includes(null) ? null : n.ownTokens + child.reduce((s, v) => s + v, 0);
|
|
133
|
+
n.tokenShare = total === null || total === 0 || n.ownTokens === null ? null : n.ownTokens / total;
|
|
134
|
+
n.children.sort((a, b) => a.id.localeCompare(b.id));
|
|
135
|
+
return n.subtreeTokens;
|
|
136
|
+
};
|
|
137
|
+
const root = get(rootId);
|
|
138
|
+
sum(root);
|
|
139
|
+
unlinked.forEach(sum);
|
|
140
|
+
if ([...nodes.values()].some(n => n.ownTokens === null))
|
|
141
|
+
notes.add('Missing usage is unknown, including children without a recorded transcript.');
|
|
142
|
+
return { session: rootId, totalTokens: total, root, unlinked, notes: [...notes] };
|
|
143
|
+
}
|
|
144
|
+
// Codex records identity and the parent in its first session_meta row. Inspect
|
|
145
|
+
// that bounded header before opening the full history of a related child.
|
|
146
|
+
function codexHeader(location) {
|
|
147
|
+
let fd;
|
|
148
|
+
try {
|
|
149
|
+
fd = (0, node_fs_1.openSync)(location.path, 'r');
|
|
150
|
+
const buffer = Buffer.alloc(1024 * 1024), length = (0, node_fs_1.readSync)(fd, buffer, 0, buffer.length, 0);
|
|
151
|
+
const first = buffer.subarray(0, length).toString('utf8').split('\n').find(line => line.trim());
|
|
152
|
+
if (!first)
|
|
153
|
+
return null;
|
|
154
|
+
const row = JSON.parse(first);
|
|
155
|
+
if (row.type !== 'session_meta')
|
|
156
|
+
return null;
|
|
157
|
+
const p = row.payload, parent = p?.parent_thread_id ?? p?.source?.subagent?.thread_spawn?.parent_thread_id;
|
|
158
|
+
return typeof p?.id === 'string' ? { id: p.id, ...(typeof parent === 'string' ? { parent } : {}) } : null;
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
if (fd !== undefined)
|
|
165
|
+
(0, node_fs_1.closeSync)(fd);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function readLaunchTree(location, locations, receipts) {
|
|
169
|
+
const load = (item) => (0, transcript_1.readInsightTranscript)(item.path, { host: item.host, sessionId: item.sessionId, collectLaunchTree: true });
|
|
170
|
+
const root = load(location), list = [root];
|
|
171
|
+
if (location.host === 'claude') {
|
|
172
|
+
const directory = (0, node_path_1.join)(location.path.replace(/\.jsonl$/, ''), 'subagents');
|
|
173
|
+
try {
|
|
174
|
+
for (const name of (0, node_fs_1.readdirSync)(directory).filter(n => /^agent-.+\.jsonl$/.test(n)).sort())
|
|
175
|
+
list.push(load({ path: (0, node_path_1.join)(directory, name), sessionId: (0, node_path_1.basename)(name, '.jsonl'), host: 'claude', modifiedAt: 0 }));
|
|
176
|
+
}
|
|
177
|
+
catch (e) {
|
|
178
|
+
if (e.code !== 'ENOENT')
|
|
179
|
+
throw e;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
else {
|
|
183
|
+
const all = (locations ?? (0, sessions_1.discoverInsightTranscripts)()).filter(l => l.host === 'codex' && l.path !== location.path).map(location => ({ location, header: codexHeader(location) }));
|
|
184
|
+
const ids = new Set([sourceId(root)]);
|
|
185
|
+
const loaded = new Set([location.path]);
|
|
186
|
+
const recordedChildren = new Set(Object.keys(root.state.launchEvidence?.nodes ?? {}));
|
|
187
|
+
for (let changed = true; changed;) {
|
|
188
|
+
changed = false;
|
|
189
|
+
for (const { location: item, header } of all)
|
|
190
|
+
if (!loaded.has(item.path) && header && ((header.parent && ids.has(header.parent)) || recordedChildren.has(header.id))) {
|
|
191
|
+
const t = load(item);
|
|
192
|
+
loaded.add(item.path);
|
|
193
|
+
ids.add(sourceId(t));
|
|
194
|
+
list.push(t);
|
|
195
|
+
changed = true;
|
|
196
|
+
for (const child of Object.keys(t.state.launchEvidence?.nodes ?? {}))
|
|
197
|
+
recordedChildren.add(child);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return buildLaunchTree(list, receipts);
|
|
202
|
+
}
|
|
203
|
+
async function readLaunchTreeWithReceipts(location, options = {}) {
|
|
204
|
+
const evidence = { nodes: {}, calls: {}, edges: [], owners: {} };
|
|
205
|
+
const session = (location.host === 'codex' ? codexHeader(location)?.id : location.sessionId) ?? location.sessionId;
|
|
206
|
+
const id = (v) => typeof v === 'string' && /^[A-Za-z0-9_.:@/-]{1,256}$/.test(v) ? v : null;
|
|
207
|
+
const caller = (v) => v === 'main' ? session : id(v);
|
|
208
|
+
for (const row of await (0, tally_1.sessionLaunchReceipts)(session, options)) {
|
|
209
|
+
const m = row.decision.plugin, who = caller(m.agent_id ?? m.launch?.callerId);
|
|
210
|
+
if (who) {
|
|
211
|
+
const old = evidence.nodes[who] ??= {};
|
|
212
|
+
const name = id(m.agent_type ?? m.launch?.callerType);
|
|
213
|
+
if (name)
|
|
214
|
+
old.name = name;
|
|
215
|
+
if (Number.isSafeInteger(m.depth) && m.depth >= 0)
|
|
216
|
+
old.depth = m.depth;
|
|
217
|
+
const parent = caller(m.parent_agent_id ?? m.launch?.parentAgentId);
|
|
218
|
+
if (parent)
|
|
219
|
+
evidence.edges.push({ child: who, parent, source: 'signed caller metadata' });
|
|
220
|
+
}
|
|
221
|
+
const child = id(m.spawned_agent_id);
|
|
222
|
+
if (child && who && m.event === 'outcome' && m.success !== false) {
|
|
223
|
+
evidence.nodes[child] ??= {};
|
|
224
|
+
const name = id(m.launch?.agentType);
|
|
225
|
+
if (name)
|
|
226
|
+
evidence.nodes[child].name = name;
|
|
227
|
+
if (Number.isSafeInteger(m.launch?.depth))
|
|
228
|
+
evidence.nodes[child].depth = m.launch.depth;
|
|
229
|
+
evidence.edges.push({ child, parent: who, source: 'signed launch outcome' });
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return readLaunchTree(location, options.locations, evidence);
|
|
233
|
+
}
|
|
234
|
+
const compact = (n) => n === null ? '?' : n >= 1e9 ? `${(n / 1e9).toFixed(1)}B` : n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : String(n);
|
|
235
|
+
function humanDuration(ms, days = false) {
|
|
236
|
+
const minutes = Math.floor(ms / 60000), hours = Math.floor(minutes / 60);
|
|
237
|
+
if (ms > 0 && minutes === 0)
|
|
238
|
+
return '<1m';
|
|
239
|
+
if (days && hours >= 24)
|
|
240
|
+
return `${Math.floor(hours / 24)}d ${hours % 24}h`;
|
|
241
|
+
return hours ? `${hours}h ${minutes % 60}m` : `${minutes}m`;
|
|
242
|
+
}
|
|
243
|
+
function renderLaunchTree(tree, short = false) {
|
|
244
|
+
const lines = ['Launch tree', 'Own / subtree tokens | share of session tokens | active time'];
|
|
245
|
+
const cut = (v, size) => [...v].length > size ? [...v].slice(0, size - 1).join('') + '…' : v;
|
|
246
|
+
let shown = 0;
|
|
247
|
+
const print = (n, depth) => {
|
|
248
|
+
if (short && shown >= 5)
|
|
249
|
+
return;
|
|
250
|
+
shown++;
|
|
251
|
+
const indent = ' '.repeat(Math.min(depth, 8));
|
|
252
|
+
lines.push(cut(`${indent}${depth > 8 ? 'depth ' + depth + ': ' : ''}${n.name} [${n.id.slice(0, 12)}] ${n.models.join(', ') || 'model not recorded'}`, 80));
|
|
253
|
+
const active = n.durationMs === null ? '?' : humanDuration(n.durationMs);
|
|
254
|
+
const span = n.spanMs !== null && n.spanMs !== n.durationMs ? ` · span ${humanDuration(n.spanMs, true)}` : '';
|
|
255
|
+
lines.push(cut(`${indent} ${compact(n.ownTokens)} / ${compact(n.subtreeTokens)} | ${n.tokenShare === null ? '?' : (100 * n.tokenShare).toFixed(1) + '%'} | active ${active}${span}`, 80));
|
|
256
|
+
if (n.endedWithoutFinishing)
|
|
257
|
+
lines.push(`${indent} ended without finishing`);
|
|
258
|
+
let visible = 0;
|
|
259
|
+
for (const child of n.children.slice(0, short ? 5 : 6)) {
|
|
260
|
+
if (short && shown >= 5)
|
|
261
|
+
break;
|
|
262
|
+
print(child, depth + 1);
|
|
263
|
+
visible++;
|
|
264
|
+
}
|
|
265
|
+
if (n.children.length > visible)
|
|
266
|
+
lines.push(`${indent} + ${n.children.length - visible} more like this`);
|
|
267
|
+
};
|
|
268
|
+
print(tree.root, 0);
|
|
269
|
+
if (tree.unlinked.length) {
|
|
270
|
+
lines.push('parent not recorded');
|
|
271
|
+
let visible = 0;
|
|
272
|
+
for (const node of tree.unlinked.slice(0, short ? 5 : 6)) {
|
|
273
|
+
if (short && shown >= 5)
|
|
274
|
+
break;
|
|
275
|
+
print(node, 1);
|
|
276
|
+
visible++;
|
|
277
|
+
}
|
|
278
|
+
if (tree.unlinked.length > visible)
|
|
279
|
+
lines.push(` + ${tree.unlinked.length - visible} more like this`);
|
|
280
|
+
}
|
|
281
|
+
lines.push(`Session tokens: ${compact(tree.totalTokens)}. Shares use each node's own tokens.`);
|
|
282
|
+
for (const note of tree.notes)
|
|
283
|
+
lines.push(cut(note, 80));
|
|
284
|
+
return lines.join('\n');
|
|
285
|
+
}
|
|
@@ -77,6 +77,7 @@ export interface InsightDiagnostics {
|
|
|
77
77
|
inheritedUsageRecords?: number;
|
|
78
78
|
}
|
|
79
79
|
export interface InsightParserState {
|
|
80
|
+
launchEvidence?: import('./launch-evidence').LaunchEvidence;
|
|
80
81
|
host: InsightHost;
|
|
81
82
|
sessionId: string;
|
|
82
83
|
model?: string;
|
|
@@ -177,6 +178,7 @@ export interface InsightParseOptions {
|
|
|
177
178
|
sessionId?: string;
|
|
178
179
|
state?: InsightParserState;
|
|
179
180
|
spawnedSession?: boolean;
|
|
181
|
+
collectLaunchTree?: boolean;
|
|
180
182
|
}
|
|
181
183
|
/** A commit up to ten minutes after the session's last record still counts: the commit that closes a session often lands just after its last reply. */
|
|
182
184
|
export declare const COMMIT_GRACE_MS: number;
|