@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
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.0 (2026-10-05)
|
|
4
|
+
|
|
5
|
+
- Add recorded launch trees and signed approval tallies. Tree shows active time
|
|
6
|
+
in hours and minutes and elapsed span in days and hours, with five-minute gap
|
|
7
|
+
capping. Unknown lineage or usage stays unknown.
|
|
8
|
+
- Read explicit caller, type, depth and linked outcomes from verified plugin
|
|
9
|
+
receipts. Resumed summaries contribute daily increments without adding the
|
|
10
|
+
earlier cumulative total twice.
|
|
11
|
+
- Own Codex cumulative usage and all shared launch aliases. Cached input is
|
|
12
|
+
already in the total, and repeated observations replace earlier totals.
|
|
13
|
+
- Standalone Claude admission receipts sign the host tool-call ID and expose
|
|
14
|
+
verification against the pinned local public key, chain and persisted head.
|
|
15
|
+
- Pin Spend 0.21.0 for the receipt verifier.
|
|
16
|
+
|
|
17
|
+
|
|
3
18
|
## 0.3.28 (2026-10-03)
|
|
4
19
|
|
|
5
20
|
- `why --commits` gives no per-commit figure when other local sessions overlap the window in the same repository: the commits can't be split between sessions, so the line says so instead of printing a number that would credit this session with other sessions' commits.
|
package/README.md
CHANGED
|
@@ -16,6 +16,19 @@ The two init commands print hook configuration for review. Merge the relevant sn
|
|
|
16
16
|
|
|
17
17
|
`agentguard-burn --version` (or `-v`) prints the installed version.
|
|
18
18
|
|
|
19
|
+
## Launch tree and signed approval tally
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
agentguard-burn tree SESSION
|
|
23
|
+
agentguard-burn tree SESSION --json
|
|
24
|
+
agentguard-burn tally SESSION
|
|
25
|
+
agentguard-burn tally SESSION --json
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Omit `SESSION` to use the current or latest local session, or pass its transcript path. `tree` shows recorded parents, each agent's model, own and subtree tokens, token share, recorded duration and unfinished status. Missing parent links stay under `parent not recorded`. The terminal view fits 80 columns and collapses large fan-outs; JSON keeps every node. `why` includes a short tree when children were recorded.
|
|
29
|
+
|
|
30
|
+
`tally` verifies signed plugin receipts and their complete hash chain before counting launch decisions. Missing or invalid receipts print a reason instead of a number. Approvals are a subset of asks; policy refusals and unrecorded approval outcomes remain separate. Codex blocks launches until allowed and never receives an ask count. See [the field definitions, arithmetic and verification limits](docs/TREE_AND_TALLY.md).
|
|
31
|
+
|
|
19
32
|
For Claude Code, configure its `statusLine` command as `agentguard-burn statusline`. It receives the host JSON on stdin. Codex 0.154.0 has no external status command slot. Use `agentguard-burn statusline SESSION_ID` in a companion terminal and the native Codex limit indicators. See [host fields and setup](docs/USAGE_AND_PRICING.md#what-the-hosts-expose).
|
|
20
33
|
|
|
21
34
|
## Import a DisciplineBench run
|
|
@@ -42,7 +42,9 @@ export declare function handleCodexHook(raw: unknown, gateway: Gateway, now?: nu
|
|
|
42
42
|
* re-reading the file on every hook call is idempotent at the gateway.
|
|
43
43
|
*/
|
|
44
44
|
export declare function readCodexTranscriptUsage(path: string, sessionId: string, now: number): ModelUsageObserved[];
|
|
45
|
-
export declare function parseCodexTranscript(text: string, sessionId: string, now: number): ModelUsageObserved[];
|
|
45
|
+
export declare function parseCodexTranscript(text: string, sessionId: string, now: number, streamId?: string): ModelUsageObserved[];
|
|
46
46
|
/** The ~/.codex/hooks.json fragment. spawn_agent matches as Agent. */
|
|
47
47
|
export declare function codexHooksSnippet(command: string): Record<string, unknown>;
|
|
48
|
-
export declare const CODEX_SPAWN_TOOLS:
|
|
48
|
+
export declare const CODEX_SPAWN_TOOLS: Readonly<{
|
|
49
|
+
has: typeof import("../tool-names").isLaunchTool;
|
|
50
|
+
}>;
|
|
@@ -31,6 +31,8 @@ exports.parseCodexTranscript = parseCodexTranscript;
|
|
|
31
31
|
exports.codexHooksSnippet = codexHooksSnippet;
|
|
32
32
|
const node_crypto_1 = require("node:crypto");
|
|
33
33
|
const node_fs_1 = require("node:fs");
|
|
34
|
+
const node_path_1 = require("node:path");
|
|
35
|
+
const tool_names_1 = require("../tool-names");
|
|
34
36
|
const events_1 = require("../events");
|
|
35
37
|
const render_1 = require("../replay/render");
|
|
36
38
|
const stop_text_1 = require("../stop-text");
|
|
@@ -40,7 +42,7 @@ const pre_tool_use_1 = require("../hook/pre-tool-use");
|
|
|
40
42
|
/** Fields this renderer must never emit. Codex rejects the whole object if they appear. */
|
|
41
43
|
exports.CODEX_FORBIDDEN_FIELDS = ['continue', 'stopReason', 'suppressOutput', 'decision', 'reason'];
|
|
42
44
|
const HOST = 'codex';
|
|
43
|
-
const SPAWN_TOOLS =
|
|
45
|
+
const SPAWN_TOOLS = tool_names_1.LAUNCH_TOOLS;
|
|
44
46
|
function handleCodexHook(raw, gateway, now = Date.now()) {
|
|
45
47
|
const parsed = parse(raw);
|
|
46
48
|
if (!parsed)
|
|
@@ -74,8 +76,7 @@ function handleCodexSpawnHook(raw, gateway, now) {
|
|
|
74
76
|
sessionId: input.sessionId,
|
|
75
77
|
at: now,
|
|
76
78
|
spawnId,
|
|
77
|
-
//
|
|
78
|
-
proposedDepth: 1,
|
|
79
|
+
// The host does not provide a verified depth. Count enforcement still applies.
|
|
79
80
|
attribution: 'high',
|
|
80
81
|
});
|
|
81
82
|
if (decision.blocked) {
|
|
@@ -131,18 +132,41 @@ function parse(value) {
|
|
|
131
132
|
* re-reading the file on every hook call is idempotent at the gateway.
|
|
132
133
|
*/
|
|
133
134
|
function readCodexTranscriptUsage(path, sessionId, now) {
|
|
134
|
-
|
|
135
|
+
if (typeof path !== 'string' || !(0, node_path_1.isAbsolute)(path) || !path.endsWith('.jsonl'))
|
|
136
|
+
return [];
|
|
137
|
+
let fd;
|
|
135
138
|
try {
|
|
136
|
-
|
|
139
|
+
fd = (0, node_fs_1.openSync)(path, node_fs_1.constants.O_RDONLY | node_fs_1.constants.O_NOFOLLOW | node_fs_1.constants.O_NONBLOCK);
|
|
140
|
+
const stat = (0, node_fs_1.fstatSync)(fd);
|
|
141
|
+
if (!stat.isFile())
|
|
142
|
+
return [];
|
|
143
|
+
const size = Math.min(stat.size, 262144), offset = stat.size - size, buffer = Buffer.alloc(size);
|
|
144
|
+
const length = (0, node_fs_1.readSync)(fd, buffer, 0, size, offset);
|
|
145
|
+
let text = buffer.subarray(0, length).toString('utf8');
|
|
146
|
+
if (offset)
|
|
147
|
+
text = text.slice(text.indexOf('\n') + 1);
|
|
148
|
+
const events = parseCodexTranscript(text, sessionId, now, path);
|
|
149
|
+
// A tail can prove a cumulative snapshot, never a complete legacy total.
|
|
150
|
+
if (offset || events.some(e => e.callId) || !events.length)
|
|
151
|
+
return offset ? events.filter(e => e.callId) : events;
|
|
152
|
+
// Legacy per-call rows are also one replaceable stream total. If a host
|
|
153
|
+
// starts supplying cumulative snapshots later, they replace this total.
|
|
154
|
+
const tokens = events.reduce((sum, e) => sum + e.tokens, 0), cacheRead = events.reduce((sum, e) => sum + e.cacheRead, 0);
|
|
155
|
+
const callId = 'codex:launch-usage:' + (0, node_crypto_1.createHash)('sha256').update(path).digest('hex');
|
|
156
|
+
return [{ ...events.at(-1), tokens, cacheRead, callId, eventId: `${callId}:${tokens}:${cacheRead}` }];
|
|
137
157
|
}
|
|
138
158
|
catch {
|
|
139
159
|
return [];
|
|
140
160
|
}
|
|
141
|
-
|
|
161
|
+
finally {
|
|
162
|
+
if (fd !== undefined)
|
|
163
|
+
(0, node_fs_1.closeSync)(fd);
|
|
164
|
+
}
|
|
142
165
|
}
|
|
143
|
-
function parseCodexTranscript(text, sessionId, now) {
|
|
166
|
+
function parseCodexTranscript(text, sessionId, now, streamId = sessionId) {
|
|
144
167
|
const out = [];
|
|
145
168
|
const lines = text.split('\n');
|
|
169
|
+
let cumulative;
|
|
146
170
|
for (let i = 0; i < lines.length; i++) {
|
|
147
171
|
const line = lines[i].trim();
|
|
148
172
|
if (!line)
|
|
@@ -154,6 +178,24 @@ function parseCodexTranscript(text, sessionId, now) {
|
|
|
154
178
|
catch {
|
|
155
179
|
continue;
|
|
156
180
|
}
|
|
181
|
+
const row = rec;
|
|
182
|
+
if (row?.type === 'event_msg' && row.payload?.type === 'token_count') {
|
|
183
|
+
const usage = row.payload.info?.total_token_usage;
|
|
184
|
+
if (!usage || !Number.isSafeInteger(usage.total_tokens) || usage.total_tokens < 0
|
|
185
|
+
|| !Number.isSafeInteger(usage.cached_input_tokens) || usage.cached_input_tokens < 0
|
|
186
|
+
|| usage.cached_input_tokens > usage.total_tokens)
|
|
187
|
+
continue;
|
|
188
|
+
const at = Date.parse(row.timestamp);
|
|
189
|
+
if (!Number.isFinite(at))
|
|
190
|
+
continue;
|
|
191
|
+
// Keep the earlier plugin adapter's identity for a seamless handoff.
|
|
192
|
+
// Cached input is already included in total_tokens, never added again.
|
|
193
|
+
const callId = 'codex:launch-usage:' + (0, node_crypto_1.createHash)('sha256').update(streamId).digest('hex');
|
|
194
|
+
cumulative = { schemaVersion: 1, kind: 'model_usage', host: HOST, sessionId, at, callId,
|
|
195
|
+
eventId: `${callId}:${usage.total_tokens}:${usage.cached_input_tokens}`,
|
|
196
|
+
tokens: usage.total_tokens, cacheRead: usage.cached_input_tokens, usageCoverage: 'estimated' };
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
157
199
|
const usage = extractUsage(rec);
|
|
158
200
|
if (!usage)
|
|
159
201
|
continue;
|
|
@@ -171,7 +213,8 @@ function parseCodexTranscript(text, sessionId, now) {
|
|
|
171
213
|
usageCoverage: 'estimated',
|
|
172
214
|
});
|
|
173
215
|
}
|
|
174
|
-
|
|
216
|
+
// A cumulative stream includes the earlier individual call records.
|
|
217
|
+
return cumulative ? [cumulative] : out;
|
|
175
218
|
}
|
|
176
219
|
function extractUsage(rec) {
|
|
177
220
|
const num = (...paths) => {
|
|
@@ -188,7 +231,10 @@ function extractUsage(rec) {
|
|
|
188
231
|
const cached = num(['usage', 'cache_read_input_tokens'], ['usage', 'input_tokens_details', 'cached_tokens'], ['response', 'usage', 'input_tokens_details', 'cached_tokens'], ['token_usage', 'cached_input_tokens']);
|
|
189
232
|
if (input === undefined && output === undefined && total === undefined)
|
|
190
233
|
return null;
|
|
191
|
-
|
|
234
|
+
// OpenAI input tokens already include cache reads. Only the explicitly
|
|
235
|
+
// separate Anthropic-compatible cache_read_input_tokens shape adds them.
|
|
236
|
+
const separateCache = num(['usage', 'cache_read_input_tokens']) ?? 0;
|
|
237
|
+
const tokens = Math.max(total ?? 0, (input ?? 0) + (output ?? 0) + separateCache);
|
|
192
238
|
const tsRaw = walk(rec, ['timestamp']) ?? walk(rec, ['created_at']);
|
|
193
239
|
const at = typeof tsRaw === 'string' ? Date.parse(tsRaw) : typeof tsRaw === 'number' ? tsRaw : NaN;
|
|
194
240
|
return { tokens, cacheRead: cached ?? 0, at: Number.isFinite(at) ? at : undefined };
|
package/dist/src/cli.js
CHANGED
|
@@ -74,6 +74,8 @@ const simulate_1 = require("./replay/simulate");
|
|
|
74
74
|
const status_1 = require("./status");
|
|
75
75
|
const upgrade_moments_1 = require("./upgrade-moments");
|
|
76
76
|
const eligibility_1 = require("./eligibility");
|
|
77
|
+
const tree_1 = require("./insights/tree");
|
|
78
|
+
const tally_1 = require("./insights/tally");
|
|
77
79
|
const sessions_1 = require("./insights/sessions");
|
|
78
80
|
const transcript_1 = require("./insights/transcript");
|
|
79
81
|
const live_1 = require("./insights/live");
|
|
@@ -210,6 +212,30 @@ async function main(argv) {
|
|
|
210
212
|
show({ kind: 'command', command, values: { ...report } }, (rest.includes('json') || has('--json') ? JSON.stringify(report, null, 2) : (0, blocks_1.renderBlocks)(report)) + '\n', rest.includes('json') || has('--json'));
|
|
211
213
|
return 0;
|
|
212
214
|
}
|
|
215
|
+
case 'tree':
|
|
216
|
+
case 'tally': {
|
|
217
|
+
const args = rest.filter(v => v !== 'json' && v !== '--json');
|
|
218
|
+
if (args.length > 1 || args.some(v => v.startsWith('-')))
|
|
219
|
+
throw new Error('Pass one session or transcript path.');
|
|
220
|
+
const json = rest.includes('json') || rest.includes('--json');
|
|
221
|
+
if (command === 'tree') {
|
|
222
|
+
const report = await (0, tree_1.readLaunchTreeWithReceipts)((0, sessions_1.selectInsightTranscript)(args[0]), { home: HOME });
|
|
223
|
+
process.stdout.write((json ? JSON.stringify(report, null, 2) : (0, tree_1.renderLaunchTree)(report)) + '\n');
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
// An explicit id can be tallied even after its transcript was removed.
|
|
227
|
+
let session = args[0];
|
|
228
|
+
if (!session || (0, node_fs_1.existsSync)(session)) {
|
|
229
|
+
const location = (0, sessions_1.selectInsightTranscript)(session);
|
|
230
|
+
const parsed = (0, transcript_1.readInsightTranscript)(location.path, { host: location.host, sessionId: location.sessionId });
|
|
231
|
+
session = parsed.state.lineage?.sessionId ?? parsed.sessionId;
|
|
232
|
+
}
|
|
233
|
+
const report = await (0, tally_1.sessionTally)(session, { home: HOME });
|
|
234
|
+
process.stdout.write((json ? JSON.stringify(report, null, 2) : (0, tally_1.renderSessionTally)(report)) + '\n');
|
|
235
|
+
return report.status === 'verification_failed' ? 1 : 0;
|
|
236
|
+
}
|
|
237
|
+
return 0;
|
|
238
|
+
}
|
|
213
239
|
case 'why': {
|
|
214
240
|
// `--lang en|es|pt` (or --lang=es) picks the report's language and is never a session selector.
|
|
215
241
|
// `--commits` adds the commits that landed while the session ran. It is the only way `why` runs git.
|
|
@@ -233,14 +259,16 @@ async function main(argv) {
|
|
|
233
259
|
process.stderr.write('Usage: agentguard-burn why [session] [json] [--lang en|es|pt]\n');
|
|
234
260
|
return 64;
|
|
235
261
|
}
|
|
236
|
-
const location = (0, sessions_1.selectInsightTranscript)(args.find(value => value !== 'json'));
|
|
262
|
+
const location = (0, sessions_1.selectInsightTranscript)(args.find(value => value !== 'json' && value !== '--json'));
|
|
237
263
|
const transcript = (0, transcript_1.readInsightSession)(location.path, { host: location.host, sessionId: location.sessionId });
|
|
238
|
-
const json = args.includes('json');
|
|
264
|
+
const json = args.includes('json') || args.includes('--json');
|
|
239
265
|
// The commits reader is loaded only with the flag, so a plain `why` never reaches it.
|
|
240
266
|
const commits = withCommits ? await (await Promise.resolve().then(() => __importStar(require('./insights/commits')))).sessionCommits({ path: location.path }) : undefined;
|
|
267
|
+
const launchTree = (0, tree_1.readLaunchTree)(location);
|
|
268
|
+
const treeSection = launchTree.root.children.length || launchTree.unlinked.length ? '\n\n' + (0, tree_1.renderLaunchTree)(launchTree, true) : '';
|
|
241
269
|
const commitsValue = commits ? (0, render_2.commitsJson)(commits, transcript.state.forkHistoryBoundaryUnknown ? null : (0, render_2.sessionFigures)(transcript).attribution.totalTokens) : undefined;
|
|
242
|
-
show({ kind: 'command', command, values: { session: transcript.sessionId, observations: transcript.observations, diagnostics: transcript.diagnostics, attribution: (0, attribution_1.attributeTurns)((0, transcript_2.deduplicateTurns)(transcript.turns)).buckets, prices: (0, transcript_2.deduplicateTurns)(transcript.turns).map(turn => (0, pricing_1.priceTurn)(turn, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)))), ...(commitsValue ? { commits: commitsValue } : {}) } }, json ? JSON.stringify(
|
|
243
|
-
: (0, render_2.renderWhy)(transcript, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)), { tips: !quietOn(), lang: (0, i18n_1.detectWhyLang)({ flag: lang, env: process.env, intlLocale: intlLocale() }), ...(commits ? { commits } : {}) }) + '\n', json);
|
|
270
|
+
show({ kind: 'command', command, values: { session: transcript.sessionId, observations: transcript.observations, diagnostics: transcript.diagnostics, attribution: (0, attribution_1.attributeTurns)((0, transcript_2.deduplicateTurns)(transcript.turns)).buckets, prices: (0, transcript_2.deduplicateTurns)(transcript.turns).map(turn => (0, pricing_1.priceTurn)(turn, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)))), ...(commitsValue ? { commits: commitsValue } : {}) } }, json ? JSON.stringify({ ...transcript, ...(treeSection ? { launchTree } : {}), ...(commitsValue ? { commits: commitsValue } : {}) }, null, 2) + '\n'
|
|
271
|
+
: (treeSection ? treeSection.trim() + '\n\n' : '') + (0, render_2.renderWhy)(transcript, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)), { tips: !quietOn(), lang: (0, i18n_1.detectWhyLang)({ flag: lang, env: process.env, intlLocale: intlLocale() }), ...(commits ? { commits } : {}) }) + '\n', json);
|
|
244
272
|
return 0;
|
|
245
273
|
}
|
|
246
274
|
case 'compare': {
|
|
@@ -616,7 +644,7 @@ async function main(argv) {
|
|
|
616
644
|
return 0;
|
|
617
645
|
}
|
|
618
646
|
default:
|
|
619
|
-
show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'calendar', 'why', 'compare', 'rewrites', 'ttl', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'quiet', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|calendar|why|compare|rewrites|ttl|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|quiet|proxy|conformance>\n' +
|
|
647
|
+
show({ kind: 'command', command: 'help', values: { commands: ['tree', 'tally', 'ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'calendar', 'why', 'compare', 'rewrites', 'ttl', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'quiet', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|calendar|why|compare|rewrites|ttl|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|quiet|proxy|conformance>\n' +
|
|
620
648
|
' ps [--json] local agent processes, held memory and workspace disk\n' +
|
|
621
649
|
' render <run.jsonl> --mp4 <out.mp4> [--gif <out.gif>] [--phone] local recorded-run export\n' +
|
|
622
650
|
' render <run.jsonl> --mp4 <out.mp4> --dashboard [--wide] [--economics <blocks.json>] dashboard export\n' +
|
|
@@ -627,6 +655,8 @@ async function main(argv) {
|
|
|
627
655
|
' blocks [session|all] stored WARN/STOP receipts and that session\'s child usage\n' +
|
|
628
656
|
' limits [session|all] local plan walls and prior Burn decisions\n' +
|
|
629
657
|
' price-shadow [session|all] local child list-price exposure and sensitivity\n' +
|
|
658
|
+
' tree [session] recorded launch ancestry, tokens and duration\n' +
|
|
659
|
+
' tally [session] verified signed launch decisions\n' +
|
|
630
660
|
' why [session] token attribution and API list-price equivalents\n' +
|
|
631
661
|
' --lang es|pt the why report in Latin American Spanish or Brazilian Portuguese; your locale picks it by default\n' +
|
|
632
662
|
' --commits count the commits that landed in its git repository while it ran (runs git on this computer; off by default)\n' +
|
|
@@ -1,16 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Claude Code transcript reader.
|
|
3
|
-
*
|
|
4
|
-
* Reads ~/.claude/projects/<slug>/<session>.jsonl incrementally. The hot path
|
|
5
|
-
* (the PreToolUse hook) must never re-read a 25,000-line file, so the reader
|
|
6
|
-
* remembers the byte offset after the last complete newline and only parses
|
|
7
|
-
* what has been appended since.
|
|
8
|
-
*
|
|
9
|
-
* Transcript lines are not a stable contract. Every line is parsed defensively:
|
|
10
|
-
* a malformed line is counted and skipped, a partial trailing line is left
|
|
11
|
-
* uncommitted so it can be re-read once the host finishes writing it, and a
|
|
12
|
-
* truncated or replaced file resets the cursor rather than reading garbage.
|
|
13
|
-
*/
|
|
14
1
|
import type { BurnEvent } from '../types';
|
|
15
2
|
/** Component maxima for one provider response, never transcript contents. */
|
|
16
3
|
export type UsageSnapshot = [input: number, output: number, cacheCreation: number, cacheRead: number];
|
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.newCursor = newCursor;
|
|
4
|
+
exports.normaliseLine = normaliseLine;
|
|
5
|
+
exports.readIncremental = readIncremental;
|
|
6
|
+
exports.readSessionIncremental = readSessionIncremental;
|
|
7
|
+
exports.saveReaderCursor = saveReaderCursor;
|
|
8
|
+
exports.restoreReaderCursor = restoreReaderCursor;
|
|
9
|
+
exports.cloneReaderCursor = cloneReaderCursor;
|
|
10
|
+
exports.readAll = readAll;
|
|
11
|
+
const tool_names_1 = require("../tool-names");
|
|
2
12
|
/**
|
|
3
13
|
* Claude Code transcript reader.
|
|
4
14
|
*
|
|
@@ -12,22 +22,13 @@
|
|
|
12
22
|
* uncommitted so it can be re-read once the host finishes writing it, and a
|
|
13
23
|
* truncated or replaced file resets the cursor rather than reading garbage.
|
|
14
24
|
*/
|
|
15
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
-
exports.newCursor = newCursor;
|
|
17
|
-
exports.normaliseLine = normaliseLine;
|
|
18
|
-
exports.readIncremental = readIncremental;
|
|
19
|
-
exports.readSessionIncremental = readSessionIncremental;
|
|
20
|
-
exports.saveReaderCursor = saveReaderCursor;
|
|
21
|
-
exports.restoreReaderCursor = restoreReaderCursor;
|
|
22
|
-
exports.cloneReaderCursor = cloneReaderCursor;
|
|
23
|
-
exports.readAll = readAll;
|
|
24
25
|
const node_fs_1 = require("node:fs");
|
|
25
26
|
const node_path_1 = require("node:path");
|
|
26
27
|
const transcript_1 = require("../insights/transcript");
|
|
27
28
|
const subagent_signals_1 = require("./subagent-signals");
|
|
28
29
|
const CHUNK = 64 * 1024;
|
|
29
30
|
const MAX_LINE = 4 * 1024 * 1024;
|
|
30
|
-
const SPAWN_TOOLS =
|
|
31
|
+
const SPAWN_TOOLS = tool_names_1.LAUNCH_TOOLS;
|
|
31
32
|
const SURFACE_TOOLS = new Set(['Read', 'Grep', 'Glob']);
|
|
32
33
|
function newCursor() {
|
|
33
34
|
return { offset: 0, size: 0, malformedLines: 0, depthByUuid: new Map(), usageVersion: 1, usageByMessage: new Map() };
|
|
@@ -1,19 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Claude Code PreToolUse hook.
|
|
3
|
-
*
|
|
4
|
-
* Reads the hook payload from stdin, evaluates the proposed spawn under the
|
|
5
|
-
* reservation lock, and emits the nested permissionDecision Claude Code
|
|
6
|
-
* expects. Only Agent/Task spawns are ever denied; ordinary tools pass.
|
|
7
|
-
*
|
|
8
|
-
* Shadow mode evaluates and records the decision but always allows. That is
|
|
9
|
-
* the first-run default, because a blocker with untuned thresholds that fires
|
|
10
|
-
* on day one gets uninstalled on day one.
|
|
11
|
-
*
|
|
12
|
-
* Fail-closed on the reservation lock: if we cannot coordinate with sibling
|
|
13
|
-
* hook processes, we deny the spawn rather than let a burst through. We
|
|
14
|
-
* cannot fail closed if Claude Code times the hook out, so the hot path does
|
|
15
|
-
* as little as possible.
|
|
16
|
-
*/
|
|
17
1
|
import { type PersistedReaderCursor, type ReaderCursor } from '../history/claude-transcript';
|
|
18
2
|
import type { BurnReport, Policy, SessionState } from '../types';
|
|
19
3
|
export interface HookInput {
|
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AGENT_OVERRIDE_REASON = exports.loadPolicy = void 0;
|
|
4
|
+
exports.inflateHookSession = inflateHookSession;
|
|
5
|
+
exports.findingSignature = findingSignature;
|
|
6
|
+
exports.refreshSession = refreshSession;
|
|
7
|
+
exports.handlePreToolUse = handlePreToolUse;
|
|
8
|
+
exports.asksPerson = asksPerson;
|
|
9
|
+
exports.agentOverrideAttempt = agentOverrideAttempt;
|
|
10
|
+
exports.settingsSnippet = settingsSnippet;
|
|
11
|
+
const tool_names_1 = require("../tool-names");
|
|
2
12
|
/**
|
|
3
13
|
* Claude Code PreToolUse hook.
|
|
4
14
|
*
|
|
@@ -15,15 +25,6 @@
|
|
|
15
25
|
* cannot fail closed if Claude Code times the hook out, so the hot path does
|
|
16
26
|
* as little as possible.
|
|
17
27
|
*/
|
|
18
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
19
|
-
exports.AGENT_OVERRIDE_REASON = exports.loadPolicy = void 0;
|
|
20
|
-
exports.inflateHookSession = inflateHookSession;
|
|
21
|
-
exports.findingSignature = findingSignature;
|
|
22
|
-
exports.refreshSession = refreshSession;
|
|
23
|
-
exports.handlePreToolUse = handlePreToolUse;
|
|
24
|
-
exports.asksPerson = asksPerson;
|
|
25
|
-
exports.agentOverrideAttempt = agentOverrideAttempt;
|
|
26
|
-
exports.settingsSnippet = settingsSnippet;
|
|
27
28
|
const node_crypto_1 = require("node:crypto");
|
|
28
29
|
const events_1 = require("../events");
|
|
29
30
|
const receipt_1 = require("../receipt");
|
|
@@ -43,7 +44,7 @@ const node_os_1 = require("node:os");
|
|
|
43
44
|
const live_1 = require("../insights/live");
|
|
44
45
|
const hook_1 = require("../idle/hook");
|
|
45
46
|
const subagent_cost_1 = require("../subagent-cost");
|
|
46
|
-
const SPAWN_TOOLS =
|
|
47
|
+
const SPAWN_TOOLS = tool_names_1.LAUNCH_TOOLS;
|
|
47
48
|
function sessionFile(home, sessionId) {
|
|
48
49
|
return (0, node_path_1.join)(home, 'sessions', `${sessionId.replace(/[^a-zA-Z0-9_-]/g, '_')}.json`);
|
|
49
50
|
}
|
|
@@ -204,6 +205,10 @@ function handleSpawnPreToolUse(input, home, now) {
|
|
|
204
205
|
const receipt = signer.sign({
|
|
205
206
|
schema: 'agentguard.burn.decision.v1', decisionId: (0, node_crypto_1.randomUUID)(), at: now,
|
|
206
207
|
host: 'claude-code', action: 'spawn', sessionDigest: (0, receipt_1.sha256)(input.session_id),
|
|
208
|
+
...(typeof input.tool_use_id === 'string' && /^[A-Za-z0-9_.:@/-]{1,256}$/.test(input.tool_use_id) ? { toolUseId: input.tool_use_id } : {}),
|
|
209
|
+
agent_id: typeof input.agent_id === 'string' && /^[A-Za-z0-9_.:@/-]{1,256}$/.test(input.agent_id) ? input.agent_id : null,
|
|
210
|
+
agent_type: typeof input.agent_type === 'string' && /^[A-Za-z0-9_.:@/-]{1,128}$/.test(input.agent_type) ? input.agent_type : null,
|
|
211
|
+
depth: input.agent_id ? null : 0,
|
|
207
212
|
policy: { mode: policy.mode, digest: (0, receipt_1.sha256)((0, receipt_1.canonical)(policy)) },
|
|
208
213
|
measured: { sessionTokens: state.totalTokens, sessionSpawns: reservation.effectiveSpawns,
|
|
209
214
|
proposedDepth, inFlight: 0, occupiedMs: 0 },
|
package/dist/src/index.d.ts
CHANGED
|
@@ -15,10 +15,11 @@ export { calibrate, type CalibrationResult } from './calibrate';
|
|
|
15
15
|
export { handlePreToolUse, refreshSession, loadPolicy, settingsSnippet, asksPerson, agentOverrideAttempt, AGENT_OVERRIDE_REASON, type HookInput, type HookOutput } from './hook/pre-tool-use';
|
|
16
16
|
export * from './events';
|
|
17
17
|
export { Gateway, mergeCapabilities, type Decision, type GatewaySessionView, type UsageCoverage, type GatewayOptions } from './gateway';
|
|
18
|
-
export { ReceiptSigner, verifyReceipt, receiptDigest, canonical, sha256, type ReceiptPayload, type SignedReceipt } from './receipt';
|
|
18
|
+
export { ReceiptSigner, verifyReceipt, receiptDigest, readSpawnAdmission, canonical, sha256, type ReceiptPayload, type SignedReceipt } from './receipt';
|
|
19
19
|
export { createRawApiGuard, BurnStopError, type RawApiGuard, type RawGuardOptions } from './adapters/raw-api';
|
|
20
20
|
export { handleCursorHook, cursorHooksSnippet, type CursorHookOutput } from './adapters/cursor';
|
|
21
21
|
export { handleCodexHook, codexHooksSnippet, parseCodexTranscript, readCodexTranscriptUsage, CODEX_FORBIDDEN_FIELDS, type CodexHookOutput } from './adapters/codex';
|
|
22
|
+
export { isLaunchTool, LAUNCH_TOOLS } from './tool-names';
|
|
22
23
|
export { startProxy, profileFor, type ProxyOptions, type ProxyHost, type RunningProxy } from './proxy/server';
|
|
23
24
|
export { UsageObserver, type ProxyProfile, type ObservedUsage } from './proxy/usage-observer';
|
|
24
25
|
export { renderMachineStatus } from './status';
|
|
@@ -27,3 +28,5 @@ export { writeOverride, readOverride, consumeOverride, clearOverride, OVERRIDE_W
|
|
|
27
28
|
export { install, health, configPath, type InstallHost, type InstallResult, type HostHealth } from './install';
|
|
28
29
|
export { readHookSessions, renderHostHealth } from './status';
|
|
29
30
|
export { findingSignature, inflateHookSession, type PersistedSession } from './hook/pre-tool-use';
|
|
31
|
+
export { readLaunchTree, readLaunchTreeWithReceipts, buildLaunchTree, renderLaunchTree } from './insights/tree';
|
|
32
|
+
export { sessionTally, tallyEntries, readLedgerTallies, readLedgerDailyTallies, renderSessionTally, pluginLedgerDirectories, sessionLaunchReceipts, type SessionTally, type TallyCounts } from './insights/tally';
|
package/dist/src/index.js
CHANGED
|
@@ -15,7 +15,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
exports.agentOverrideAttempt = exports.asksPerson = exports.settingsSnippet = exports.loadPolicy = exports.refreshSession = exports.handlePreToolUse = exports.calibrate = exports.OVERRIDE_COMMAND = exports.stopSummary = exports.sessionSoFar = exports.primarySummary = exports.overriddenLine = exports.continueLines = exports.askReason = exports.renderStop = exports.renderReplay = exports.discoverTranscripts = exports.replayEvents = exports.replaySession = exports.replayAll = exports.RESERVATION_TTL_MS = exports.Transaction = exports.ReservationStore = exports.cacheReadRatio = exports.medianCompletedMinute = exports.windowSum = exports.newSessionState = exports.applyCorrection = exports.applyEvent = exports.checkPolicyFile = exports.sessionTip = exports.MIN_FINISHED_SUBAGENTS = exports.decisionCostLine = exports.subagentCostLine = exports.finishedSubagents = exports.cloneReaderCursor = exports.restoreReaderCursor = exports.saveReaderCursor = exports.readSessionIncremental = exports.normaliseLine = exports.newCursor = exports.readAll = exports.readIncremental = exports.evaluateLocalCompute = exports.fmt = exports.evaluate = exports.CALL_RESERVATION_TTL_MS = exports.DEFAULT_LOCAL_COMPUTE = exports.DEFAULT_THRESHOLDS = exports.DEFAULT_POLICY = void 0;
|
|
18
|
-
exports.inflateHookSession = exports.findingSignature = exports.renderHostHealth = exports.readHookSessions = exports.configPath = exports.health = exports.install = exports.OVERRIDE_WINDOW_MS = exports.clearOverride = exports.consumeOverride = exports.readOverride = exports.writeOverride = exports.runConformance = exports.renderMachineStatus = exports.UsageObserver = exports.profileFor = exports.startProxy = exports.CODEX_FORBIDDEN_FIELDS = exports.readCodexTranscriptUsage = exports.parseCodexTranscript = exports.codexHooksSnippet = exports.handleCodexHook = exports.cursorHooksSnippet = exports.handleCursorHook = exports.BurnStopError = exports.createRawApiGuard = exports.sha256 = exports.canonical = exports.receiptDigest = exports.verifyReceipt = exports.ReceiptSigner = exports.mergeCapabilities = exports.Gateway = exports.AGENT_OVERRIDE_REASON = void 0;
|
|
18
|
+
exports.sessionLaunchReceipts = exports.pluginLedgerDirectories = exports.renderSessionTally = exports.readLedgerDailyTallies = exports.readLedgerTallies = exports.tallyEntries = exports.sessionTally = exports.renderLaunchTree = exports.buildLaunchTree = exports.readLaunchTreeWithReceipts = exports.readLaunchTree = exports.inflateHookSession = exports.findingSignature = exports.renderHostHealth = exports.readHookSessions = exports.configPath = exports.health = exports.install = exports.OVERRIDE_WINDOW_MS = exports.clearOverride = exports.consumeOverride = exports.readOverride = exports.writeOverride = exports.runConformance = exports.renderMachineStatus = exports.UsageObserver = exports.profileFor = exports.startProxy = exports.LAUNCH_TOOLS = exports.isLaunchTool = exports.CODEX_FORBIDDEN_FIELDS = exports.readCodexTranscriptUsage = exports.parseCodexTranscript = exports.codexHooksSnippet = exports.handleCodexHook = exports.cursorHooksSnippet = exports.handleCursorHook = exports.BurnStopError = exports.createRawApiGuard = exports.sha256 = exports.canonical = exports.readSpawnAdmission = exports.receiptDigest = exports.verifyReceipt = exports.ReceiptSigner = exports.mergeCapabilities = exports.Gateway = exports.AGENT_OVERRIDE_REASON = void 0;
|
|
19
19
|
__exportStar(require("./types"), exports);
|
|
20
20
|
var defaults_1 = require("./defaults");
|
|
21
21
|
Object.defineProperty(exports, "DEFAULT_POLICY", { enumerable: true, get: function () { return defaults_1.DEFAULT_POLICY; } });
|
|
@@ -94,6 +94,7 @@ var receipt_1 = require("./receipt");
|
|
|
94
94
|
Object.defineProperty(exports, "ReceiptSigner", { enumerable: true, get: function () { return receipt_1.ReceiptSigner; } });
|
|
95
95
|
Object.defineProperty(exports, "verifyReceipt", { enumerable: true, get: function () { return receipt_1.verifyReceipt; } });
|
|
96
96
|
Object.defineProperty(exports, "receiptDigest", { enumerable: true, get: function () { return receipt_1.receiptDigest; } });
|
|
97
|
+
Object.defineProperty(exports, "readSpawnAdmission", { enumerable: true, get: function () { return receipt_1.readSpawnAdmission; } });
|
|
97
98
|
Object.defineProperty(exports, "canonical", { enumerable: true, get: function () { return receipt_1.canonical; } });
|
|
98
99
|
Object.defineProperty(exports, "sha256", { enumerable: true, get: function () { return receipt_1.sha256; } });
|
|
99
100
|
var raw_api_1 = require("./adapters/raw-api");
|
|
@@ -108,6 +109,9 @@ Object.defineProperty(exports, "codexHooksSnippet", { enumerable: true, get: fun
|
|
|
108
109
|
Object.defineProperty(exports, "parseCodexTranscript", { enumerable: true, get: function () { return codex_1.parseCodexTranscript; } });
|
|
109
110
|
Object.defineProperty(exports, "readCodexTranscriptUsage", { enumerable: true, get: function () { return codex_1.readCodexTranscriptUsage; } });
|
|
110
111
|
Object.defineProperty(exports, "CODEX_FORBIDDEN_FIELDS", { enumerable: true, get: function () { return codex_1.CODEX_FORBIDDEN_FIELDS; } });
|
|
112
|
+
var tool_names_1 = require("./tool-names");
|
|
113
|
+
Object.defineProperty(exports, "isLaunchTool", { enumerable: true, get: function () { return tool_names_1.isLaunchTool; } });
|
|
114
|
+
Object.defineProperty(exports, "LAUNCH_TOOLS", { enumerable: true, get: function () { return tool_names_1.LAUNCH_TOOLS; } });
|
|
111
115
|
var server_1 = require("./proxy/server");
|
|
112
116
|
Object.defineProperty(exports, "startProxy", { enumerable: true, get: function () { return server_1.startProxy; } });
|
|
113
117
|
Object.defineProperty(exports, "profileFor", { enumerable: true, get: function () { return server_1.profileFor; } });
|
|
@@ -133,3 +137,16 @@ Object.defineProperty(exports, "renderHostHealth", { enumerable: true, get: func
|
|
|
133
137
|
var pre_tool_use_2 = require("./hook/pre-tool-use");
|
|
134
138
|
Object.defineProperty(exports, "findingSignature", { enumerable: true, get: function () { return pre_tool_use_2.findingSignature; } });
|
|
135
139
|
Object.defineProperty(exports, "inflateHookSession", { enumerable: true, get: function () { return pre_tool_use_2.inflateHookSession; } });
|
|
140
|
+
var tree_1 = require("./insights/tree");
|
|
141
|
+
Object.defineProperty(exports, "readLaunchTree", { enumerable: true, get: function () { return tree_1.readLaunchTree; } });
|
|
142
|
+
Object.defineProperty(exports, "readLaunchTreeWithReceipts", { enumerable: true, get: function () { return tree_1.readLaunchTreeWithReceipts; } });
|
|
143
|
+
Object.defineProperty(exports, "buildLaunchTree", { enumerable: true, get: function () { return tree_1.buildLaunchTree; } });
|
|
144
|
+
Object.defineProperty(exports, "renderLaunchTree", { enumerable: true, get: function () { return tree_1.renderLaunchTree; } });
|
|
145
|
+
var tally_1 = require("./insights/tally");
|
|
146
|
+
Object.defineProperty(exports, "sessionTally", { enumerable: true, get: function () { return tally_1.sessionTally; } });
|
|
147
|
+
Object.defineProperty(exports, "tallyEntries", { enumerable: true, get: function () { return tally_1.tallyEntries; } });
|
|
148
|
+
Object.defineProperty(exports, "readLedgerTallies", { enumerable: true, get: function () { return tally_1.readLedgerTallies; } });
|
|
149
|
+
Object.defineProperty(exports, "readLedgerDailyTallies", { enumerable: true, get: function () { return tally_1.readLedgerDailyTallies; } });
|
|
150
|
+
Object.defineProperty(exports, "renderSessionTally", { enumerable: true, get: function () { return tally_1.renderSessionTally; } });
|
|
151
|
+
Object.defineProperty(exports, "pluginLedgerDirectories", { enumerable: true, get: function () { return tally_1.pluginLedgerDirectories; } });
|
|
152
|
+
Object.defineProperty(exports, "sessionLaunchReceipts", { enumerable: true, get: function () { return tally_1.sessionLaunchReceipts; } });
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { InsightParserState } from './types';
|
|
2
|
+
type Row = Record<string, any>;
|
|
3
|
+
export interface LaunchEvidence {
|
|
4
|
+
nodes: Record<string, {
|
|
5
|
+
activityAt?: number[];
|
|
6
|
+
name?: string;
|
|
7
|
+
model?: string;
|
|
8
|
+
depth?: number;
|
|
9
|
+
}>;
|
|
10
|
+
calls: Record<string, {
|
|
11
|
+
parent: string;
|
|
12
|
+
name?: string;
|
|
13
|
+
model?: string;
|
|
14
|
+
}>;
|
|
15
|
+
edges: Array<{
|
|
16
|
+
child: string;
|
|
17
|
+
parent: string;
|
|
18
|
+
source: string;
|
|
19
|
+
}>;
|
|
20
|
+
owners: Record<string, string>;
|
|
21
|
+
current?: string;
|
|
22
|
+
}
|
|
23
|
+
/** Called only for reports that explicitly request lineage collection. */
|
|
24
|
+
export declare function observeLaunchRecord(raw: Row, state: InsightParserState, at?: number): void;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.observeLaunchRecord = observeLaunchRecord;
|
|
4
|
+
const tool_names_1 = require("../tool-names");
|
|
5
|
+
const record = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
|
6
|
+
const id = (v) => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,127}$/.test(v) ? v : undefined;
|
|
7
|
+
// Only host metadata labels are retained. Never retain an Agent prompt or description.
|
|
8
|
+
const label = (v) => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9 _./:-]{0,63}$/.test(v) ? v : undefined;
|
|
9
|
+
/** Called only for reports that explicitly request lineage collection. */
|
|
10
|
+
function observeLaunchRecord(raw, state, at) {
|
|
11
|
+
const e = state.launchEvidence;
|
|
12
|
+
const payload = record(raw.payload), result = record(raw.toolUseResult);
|
|
13
|
+
const anonymousSidechain = raw.isSidechain === true && !id(raw.agentId) && !state.sessionId.startsWith('agent-');
|
|
14
|
+
const owner = id(raw.agentId) ?? (anonymousSidechain ? 'unidentified-sidechain:' + state.sessionId : state.lineage?.sessionId ?? state.sessionId.replace(/^agent-/, ''));
|
|
15
|
+
e.current = owner;
|
|
16
|
+
const node = e.nodes[owner] ??= {};
|
|
17
|
+
if (at !== undefined)
|
|
18
|
+
(node.activityAt ??= []).push(at);
|
|
19
|
+
node.name ??= anonymousSidechain ? 'sidechain identity not recorded' : label(raw.agentName ?? raw.agentType ?? payload.agent_nickname ?? payload.agent_role);
|
|
20
|
+
const parent = id(raw.parentAgentId) ?? state.lineage?.parentSessionId;
|
|
21
|
+
if (parent && parent !== owner)
|
|
22
|
+
e.edges.push({ child: owner, parent, source: 'parent metadata' });
|
|
23
|
+
const blocks = Array.isArray(raw.message?.content) ? [...raw.message.content] : [];
|
|
24
|
+
if (raw.type === 'response_item')
|
|
25
|
+
blocks.push(payload);
|
|
26
|
+
for (const value of blocks) {
|
|
27
|
+
const block = record(value);
|
|
28
|
+
const callId = id(block.id ?? block.call_id ?? block.tool_use_id);
|
|
29
|
+
if (['tool_use', 'function_call', 'custom_tool_call'].includes(block.type) && (0, tool_names_1.isLaunchTool)(block.name) && callId) {
|
|
30
|
+
let input = record(block.input);
|
|
31
|
+
if (typeof block.arguments === 'string') {
|
|
32
|
+
try {
|
|
33
|
+
input = record(JSON.parse(block.arguments));
|
|
34
|
+
}
|
|
35
|
+
catch { }
|
|
36
|
+
}
|
|
37
|
+
e.calls[callId] = { parent: owner, name: label(input.name ?? input.subagent_type ?? input.agent_type), model: label(input.model) };
|
|
38
|
+
}
|
|
39
|
+
if (['tool_result', 'function_call_output', 'custom_tool_call_output'].includes(block.type) && callId) {
|
|
40
|
+
let output = result;
|
|
41
|
+
if (typeof block.output === 'string') {
|
|
42
|
+
try {
|
|
43
|
+
output = record(JSON.parse(block.output));
|
|
44
|
+
}
|
|
45
|
+
catch { }
|
|
46
|
+
}
|
|
47
|
+
const child = id(output.agentId ?? output.agent_id), launch = e.calls[callId];
|
|
48
|
+
if (child && launch && block.is_error !== true && output.status !== 'failed') {
|
|
49
|
+
e.edges.push({ child, parent: launch.parent, source: 'launch tool result' });
|
|
50
|
+
e.nodes[child] = { ...e.nodes[child], ...(launch.name ? { name: launch.name } : {}), ...(launch.model ? { model: launch.model } : {}) };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.PRICE_LABEL = void 0;
|
|
4
4
|
exports.priceShadowReport = priceShadowReport;
|
|
5
5
|
exports.renderPriceShadow = renderPriceShadow;
|
|
6
|
+
const tool_names_1 = require("../tool-names");
|
|
6
7
|
const node_fs_1 = require("node:fs");
|
|
7
8
|
const node_path_1 = require("node:path");
|
|
8
9
|
const receipt_1 = require("../receipt");
|
|
@@ -43,7 +44,7 @@ function collectSpawns(row, calls) {
|
|
|
43
44
|
const name = (0, history_1.identifier)(block.name), id = (0, history_1.identifier)(block.id ?? block.call_id ?? block.tool_use_id);
|
|
44
45
|
if (!id)
|
|
45
46
|
continue;
|
|
46
|
-
if (['tool_use', 'function_call', 'custom_tool_call'].includes(String(block.type)) && name &&
|
|
47
|
+
if (['tool_use', 'function_call', 'custom_tool_call'].includes(String(block.type)) && name && (0, tool_names_1.isLaunchTool)(name)) {
|
|
47
48
|
if (!calls.has(id))
|
|
48
49
|
calls.set(id, { at });
|
|
49
50
|
}
|
|
@@ -0,0 +1,45 @@
|
|
|
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): string[];
|
|
37
|
+
export declare function readLedgerTallies(data: string): Promise<SessionTally[]>;
|
|
38
|
+
/** Completion-day increments, so a resumed session's cumulative totals upload once. */
|
|
39
|
+
export declare function readLedgerDailyTallies(data: string): Promise<SessionTally[]>;
|
|
40
|
+
export declare function sessionTally(session: string, options?: {
|
|
41
|
+
home?: string;
|
|
42
|
+
data?: string;
|
|
43
|
+
}): Promise<SessionTally>;
|
|
44
|
+
export declare function renderSessionTally(tally: SessionTally): string;
|
|
45
|
+
export {};
|