@agentguard-run/burn 0.3.28 → 0.5.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +67 -1
  3. package/dist/src/adapters/codex.d.ts +4 -2
  4. package/dist/src/adapters/codex.js +55 -9
  5. package/dist/src/cli.js +101 -13
  6. package/dist/src/history/claude-transcript.d.ts +0 -13
  7. package/dist/src/history/claude-transcript.js +11 -10
  8. package/dist/src/hook/pre-tool-use.d.ts +0 -16
  9. package/dist/src/hook/pre-tool-use.js +15 -10
  10. package/dist/src/index.d.ts +6 -1
  11. package/dist/src/index.js +27 -1
  12. package/dist/src/insights/i18n.d.ts +1 -0
  13. package/dist/src/insights/i18n.js +9 -7
  14. package/dist/src/insights/launch-evidence.d.ts +25 -0
  15. package/dist/src/insights/launch-evidence.js +54 -0
  16. package/dist/src/insights/price-shadow.js +2 -1
  17. package/dist/src/insights/pricing.js +8 -2
  18. package/dist/src/insights/status-data.d.ts +6 -0
  19. package/dist/src/insights/status-data.js +65 -0
  20. package/dist/src/insights/status-fields.d.ts +74 -0
  21. package/dist/src/insights/status-fields.js +136 -0
  22. package/dist/src/insights/status-text.d.ts +107 -0
  23. package/dist/src/insights/status-text.js +36 -0
  24. package/dist/src/insights/tally.d.ts +47 -0
  25. package/dist/src/insights/tally.js +266 -0
  26. package/dist/src/insights/transcript.js +9 -1
  27. package/dist/src/insights/tree.d.ts +36 -0
  28. package/dist/src/insights/tree.js +285 -0
  29. package/dist/src/insights/types.d.ts +2 -0
  30. package/dist/src/receipt.d.ts +10 -0
  31. package/dist/src/receipt.js +53 -2
  32. package/dist/src/telemetry-cli.d.ts +5 -0
  33. package/dist/src/telemetry-cli.js +57 -0
  34. package/dist/src/tool-names.d.ts +6 -0
  35. package/dist/src/tool-names.js +10 -0
  36. package/dist/src/upgrade-moments.js +2 -1
  37. package/docs/OCT5_VERIFICATION.md +118 -0
  38. package/docs/TREE_AND_TALLY.md +70 -0
  39. package/docs/USAGE_AND_PRICING.md +4 -2
  40. package/docs/launch-tree-local-oct5.txt +7 -0
  41. package/docs/oct5-followup/REPORT.md +105 -0
  42. package/docs/oct5-followup/checks.json +20 -0
  43. package/docs/oct5-followup/free-plugin-fixture-output.txt +12 -0
  44. package/docs/oct5-followup/tally-after.json +5 -0
  45. package/docs/oct5-followup/tally-after.txt +1 -0
  46. package/docs/oct5-followup/tree-after.json +40 -0
  47. package/docs/oct5-followup/tree-after.txt +7 -0
  48. package/docs/oct5-followup/tree-before.txt +7 -0
  49. package/docs/oct5-followup/verify-free-receipts.cjs +81 -0
  50. package/docs/session-tally-local-oct5.txt +1 -0
  51. package/package.json +7 -3
@@ -0,0 +1,107 @@
1
+ export declare const STATUS_TEXT: {
2
+ en: {
3
+ ago: string;
4
+ lastRead: string;
5
+ range: string;
6
+ fiveHour: string;
7
+ agents: string;
8
+ tokens: string;
9
+ of: string;
10
+ share: string;
11
+ sub: string;
12
+ weekly: string;
13
+ limit: string;
14
+ cache: string;
15
+ spend: string;
16
+ today: string;
17
+ list: string;
18
+ watching: string;
19
+ unavailable: string;
20
+ starting: string;
21
+ costFull: string;
22
+ paceEmpty: string;
23
+ costEmpty: string;
24
+ cacheEmpty: string;
25
+ spendEmpty: string;
26
+ costLead: string;
27
+ cacheLead: string;
28
+ spendLead: string;
29
+ enabled: string;
30
+ none: string;
31
+ change: string;
32
+ unknown: string;
33
+ reset: string;
34
+ plan: string;
35
+ hidden: string;
36
+ };
37
+ es: {
38
+ ago: string;
39
+ lastRead: string;
40
+ range: string;
41
+ fiveHour: string;
42
+ agents: string;
43
+ tokens: string;
44
+ of: string;
45
+ share: string;
46
+ sub: string;
47
+ weekly: string;
48
+ limit: string;
49
+ cache: string;
50
+ spend: string;
51
+ today: string;
52
+ list: string;
53
+ watching: string;
54
+ unavailable: string;
55
+ starting: string;
56
+ costFull: string;
57
+ paceEmpty: string;
58
+ costEmpty: string;
59
+ cacheEmpty: string;
60
+ spendEmpty: string;
61
+ costLead: string;
62
+ cacheLead: string;
63
+ spendLead: string;
64
+ enabled: string;
65
+ none: string;
66
+ change: string;
67
+ unknown: string;
68
+ reset: string;
69
+ plan: string;
70
+ hidden: string;
71
+ };
72
+ pt: {
73
+ ago: string;
74
+ lastRead: string;
75
+ range: string;
76
+ fiveHour: string;
77
+ agents: string;
78
+ tokens: string;
79
+ of: string;
80
+ share: string;
81
+ sub: string;
82
+ weekly: string;
83
+ limit: string;
84
+ cache: string;
85
+ spend: string;
86
+ today: string;
87
+ list: string;
88
+ watching: string;
89
+ unavailable: string;
90
+ starting: string;
91
+ costFull: string;
92
+ paceEmpty: string;
93
+ costEmpty: string;
94
+ cacheEmpty: string;
95
+ spendEmpty: string;
96
+ costLead: string;
97
+ cacheLead: string;
98
+ spendLead: string;
99
+ enabled: string;
100
+ none: string;
101
+ change: string;
102
+ unknown: string;
103
+ reset: string;
104
+ plan: string;
105
+ hidden: string;
106
+ };
107
+ };
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.STATUS_TEXT = void 0;
4
+ // Display-only words shared with the Claude mod. No environment or I/O here.
5
+ exports.STATUS_TEXT = {
6
+ en: { ago: '{minutes}m ago', lastRead: 'Last read', range: 'to', fiveHour: '5-hour', agents: 'sub-agents', tokens: 'tokens', of: 'of', share: 'to sub-agents', sub: 'sub', weekly: 'weekly',
7
+ limit: 'limit in', cache: 'cache waste', spend: 'spend', today: 'today', list: 'list', watching: 'watching only',
8
+ unavailable: 'status unavailable', starting: 'starting', costFull: 'at API list price, not a bill',
9
+ paceEmpty: 'Pace needs two rising plan usage samples and a limit reached before reset.',
10
+ costEmpty: 'Session cost is unavailable because recorded usage or API list prices are missing.',
11
+ cacheEmpty: 'No large prefix rewrites are recorded in this session.',
12
+ spendEmpty: 'Spend is hidden without a readable daily cap and local spend record.',
13
+ costLead: 'Session cost:', cacheLead: 'Large prefix rewrites in this session:', spendLead: 'Daily policy spend:',
14
+ enabled: 'Optional status fields on:', none: 'none', change: 'Change status_fields in the AgentGuard plugin settings, or pass the fields flag to Burn statusline.',
15
+ unknown: 'Ignored unknown status fields:', reset: 'Resets at', plan: 'Plan usage:', hidden: 'Fields hidden to fit this width:' },
16
+ es: { ago: 'hace {minutes}min', lastRead: 'Última lectura', range: 'a', fiveHour: '5 horas', agents: 'subagentes', tokens: 'tokens', of: 'de', share: 'a subagentes', sub: 'sub', weekly: 'semanal',
17
+ limit: 'límite en', cache: 'caché reescrita', spend: 'gasto', today: 'hoy', list: 'lista', watching: 'solo observando',
18
+ unavailable: 'estado no disponible', starting: 'iniciando', costFull: 'a precio de lista de la API, no es una factura',
19
+ paceEmpty: 'El ritmo necesita dos muestras crecientes del plan y alcanzar el límite antes del reinicio.',
20
+ costEmpty: 'El costo de la sesión no está disponible porque faltan datos de uso o precios de lista de la API.',
21
+ cacheEmpty: 'No hay reescrituras grandes del prefijo registradas en esta sesión.',
22
+ spendEmpty: 'El gasto se oculta sin un límite diario legible y un registro local del gasto.',
23
+ costLead: 'Costo de la sesión:', cacheLead: 'Reescrituras grandes del prefijo en esta sesión:', spendLead: 'Gasto diario de la política:',
24
+ enabled: 'Campos opcionales activos:', none: 'ninguno', change: 'Cambia status_fields en los ajustes del plugin AgentGuard o pasa la opción fields a Burn statusline.',
25
+ unknown: 'Campos de estado desconocidos ignorados:', reset: 'Se reinicia a las', plan: 'Uso del plan:', hidden: 'Campos ocultos para caber en este ancho:' },
26
+ pt: { ago: 'há {minutes}min', lastRead: 'Última leitura', range: 'a', fiveHour: '5 horas', agents: 'subagentes', tokens: 'tokens', of: 'de', share: 'para subagentes', sub: 'sub', weekly: 'semanal',
27
+ limit: 'limite em', cache: 'cache regravado', spend: 'gasto', today: 'hoje', list: 'lista', watching: 'só observando',
28
+ unavailable: 'status indisponível', starting: 'iniciando', costFull: 'a preço de lista da API, não é uma fatura',
29
+ paceEmpty: 'O ritmo precisa de duas amostras crescentes do plano e atingir o limite antes da renovação.',
30
+ costEmpty: 'O custo da sessão está indisponível porque faltam dados de uso ou preços de lista da API.',
31
+ cacheEmpty: 'Não há regravações grandes do prefixo registradas nesta sessão.',
32
+ spendEmpty: 'O gasto fica oculto sem um limite diário legível e um registro local do gasto.',
33
+ costLead: 'Custo da sessão:', cacheLead: 'Regravações grandes do prefixo nesta sessão:', spendLead: 'Gasto diário da política:',
34
+ enabled: 'Campos opcionais ativos:', none: 'nenhum', change: 'Altere status_fields nas configurações do plugin AgentGuard ou passe a opção fields ao Burn statusline.',
35
+ unknown: 'Campos de status desconhecidos ignorados:', reset: 'Renova às', plan: 'Uso do plano:', hidden: 'Campos ocultos para caber nesta largura:' },
36
+ };
@@ -0,0 +1,47 @@
1
+ import { type SignedDecisionLogEntry } from '@agentguard-run/spend';
2
+ export interface TallyCounts {
3
+ launches: number;
4
+ allowed: number;
5
+ asked: number;
6
+ saidYes: number;
7
+ stopped: number;
8
+ shadow: number;
9
+ unrecorded: number;
10
+ unresolvedAsked: number;
11
+ }
12
+ export type SessionTally = {
13
+ status: 'verified';
14
+ session: string;
15
+ host: string;
16
+ counts: TallyCounts;
17
+ tokens: number | null;
18
+ date: string;
19
+ lineage?: Array<Record<string, unknown>>;
20
+ } | {
21
+ status: 'missing' | 'verification_failed';
22
+ session: string;
23
+ reason: string;
24
+ };
25
+ type Entry = SignedDecisionLogEntry & {
26
+ publicKeyHex?: string;
27
+ };
28
+ /** Verify the whole physical chain before selecting any session or counting. */
29
+ export declare function verifyTallyLedger(entries: Entry[], publicKeyHex: string): Promise<boolean>;
30
+ /** Only verified, complete local ledgers can supply receipt lineage to tree. */
31
+ export declare function sessionLaunchReceipts(session: string, options?: {
32
+ home?: string;
33
+ data?: string;
34
+ }): Promise<Entry[]>;
35
+ export declare function tallyEntries(entries: Entry[], publicKeyHex: string, session: string): Promise<SessionTally>;
36
+ export declare function pluginLedgerDirectories(home?: string, options?: {
37
+ prune?: boolean;
38
+ }): string[];
39
+ export declare function readLedgerTallies(data: string): Promise<SessionTally[]>;
40
+ /** Completion-day increments, so a resumed session's cumulative totals upload once. */
41
+ export declare function readLedgerDailyTallies(data: string): Promise<SessionTally[]>;
42
+ export declare function sessionTally(session: string, options?: {
43
+ home?: string;
44
+ data?: string;
45
+ }): Promise<SessionTally>;
46
+ export declare function renderSessionTally(tally: SessionTally): string;
47
+ export {};
@@ -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'), options = {}) {
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 (options.prune !== false && (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 = /^(?:(?:functions\.)?(?:Agent|Task|spawn_agent))$/.test(name);
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;