@agentguard-run/burn 0.3.7 → 0.3.8

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.
@@ -0,0 +1,426 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.INK = exports.DASHBOARD_SEED = void 0;
18
+ exports.renderDashboardFrame = renderDashboardFrame;
19
+ exports.renderDashboard = renderDashboard;
20
+ /** Dashboard frames for a recorded run: every mark is a function of the recording, the economics file and a fixed seed. */
21
+ const node_fs_1 = require("node:fs");
22
+ const promises_1 = require("node:fs/promises");
23
+ const node_crypto_1 = require("node:crypto");
24
+ const node_child_process_1 = require("node:child_process");
25
+ const node_util_1 = require("node:util");
26
+ const node_path_1 = require("node:path");
27
+ const canvas_1 = require("@napi-rs/canvas");
28
+ const live_1 = require("./insights/live");
29
+ const render_recording_1 = require("./render-recording");
30
+ const dashboard_model_1 = require("./dashboard-model");
31
+ __exportStar(require("./dashboard-model"), exports);
32
+ const run = (0, node_util_1.promisify)(node_child_process_1.execFile);
33
+ const FONT_DIR = (0, node_path_1.join)(__dirname, '../../fonts');
34
+ const TEXT = 'AgentGuardDashboardText', MONO = 'AgentGuardDashboardMono';
35
+ const FONT_FILES = [['Inter-Regular.ttf', TEXT], ['Inter-SemiBold.ttf', TEXT], ['JetBrainsMono-Regular.ttf', MONO], ['JetBrainsMono-Bold.ttf', MONO]];
36
+ exports.DASHBOARD_SEED = 20260920;
37
+ exports.INK = { paper: '#0B1117', ink: '#FFFFFF', secondary: '#B4BECF', teal: '#2ABCB4', amber: '#F59E0B', red: '#FF5A4E', grid: 'rgba(255,255,255,0.03)', panel: 'rgba(255,255,255,0.035)', line: 'rgba(255,255,255,0.10)' };
38
+ let registered = null;
39
+ async function registerFonts() {
40
+ if (registered)
41
+ return registered;
42
+ for (const [file, alias] of FONT_FILES) {
43
+ const path = (0, node_path_1.join)(FONT_DIR, file);
44
+ await (0, promises_1.access)(path, node_fs_1.constants.R_OK);
45
+ canvas_1.GlobalFonts.registerFromPath(path, alias);
46
+ }
47
+ if (!canvas_1.GlobalFonts.has(TEXT) || !canvas_1.GlobalFonts.has(MONO))
48
+ throw new Error('Dashboard fonts did not register from the package fonts directory.');
49
+ return (registered = { text: (0, node_path_1.join)(FONT_DIR, 'Inter-Regular.ttf'), numbers: (0, node_path_1.join)(FONT_DIR, 'JetBrainsMono-Regular.ttf') });
50
+ }
51
+ /** Small deterministic generator for particle phases; seeded once per model, never per frame. */
52
+ function mulberry(seed) {
53
+ let a = seed >>> 0;
54
+ return () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
55
+ }
56
+ const clamp01 = (v) => Math.max(0, Math.min(1, v));
57
+ const easeOut = (v) => 1 - Math.pow(1 - clamp01(v), 3);
58
+ const tokens = (n) => n >= 1e6 ? `${(n / 1e6).toFixed(2)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}K` : String(n);
59
+ const clock = (ms) => { const s = Math.max(0, Math.floor(ms / 1000)); return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`; };
60
+ const stamp = (atMs) => new Date(atMs).toISOString().slice(11, 19);
61
+ const verdictColor = (verdict) => verdict === 'STOP' ? exports.INK.red : verdict === 'WARN' ? exports.INK.amber : exports.INK.teal;
62
+ function geometry(layout) {
63
+ if (layout === 'phone')
64
+ return {
65
+ width: 1080, height: 1350, number: 44, bigNumber: 60, label: 19, body: 26, small: 21, margin: 48,
66
+ header: { y: 96, counters: { x: 470, step: 150 } },
67
+ ring: { cx: 540, cy: 412, r: 188, box: 104 },
68
+ bar: { x: 48, y: 800, w: 984, h: 22 },
69
+ log: { x: 48, y: 872, w: 500, h: 400, rows: 7 },
70
+ agents: { x: 592, y: 872, w: 440, h: 400, rows: 4 },
71
+ card: { x: 48, y: 636, w: 984, h: 90 },
72
+ footer: { y: 1316 },
73
+ };
74
+ return {
75
+ width: 1920, height: 1080, number: 78, bigNumber: 84, label: 22, body: 28, small: 22, margin: 60,
76
+ header: { y: 108, counters: { x: 840, step: 260 } },
77
+ ring: { cx: 470, cy: 466, r: 220, box: 120 },
78
+ bar: { x: 60, y: 812, w: 820, h: 24 },
79
+ log: { x: 960, y: 176, w: 900, h: 360, rows: 6 },
80
+ agents: { x: 960, y: 566, w: 900, h: 424, rows: 2 },
81
+ card: { x: 60, y: 880, w: 820, h: 120 },
82
+ footer: { y: 1046 },
83
+ };
84
+ }
85
+ function text(ctx, value, x, y, size, options = {}) {
86
+ const family = options.family === 'mono' ? MONO : TEXT;
87
+ const weight = options.weight ?? (options.family === 'mono' ? 400 : 400);
88
+ ctx.save();
89
+ ctx.globalAlpha *= options.alpha ?? 1;
90
+ ctx.font = `${weight} ${size}px "${family}"`;
91
+ ctx.fillStyle = options.color ?? exports.INK.ink;
92
+ ctx.textAlign = options.align ?? 'left';
93
+ ctx.textBaseline = 'alphabetic';
94
+ ctx.fillText(value, x, y);
95
+ const width = ctx.measureText(value).width;
96
+ ctx.restore();
97
+ return width;
98
+ }
99
+ function panel(ctx, x, y, w, h, title, g) {
100
+ ctx.save();
101
+ ctx.fillStyle = exports.INK.panel;
102
+ ctx.strokeStyle = exports.INK.line;
103
+ ctx.lineWidth = 1;
104
+ ctx.beginPath();
105
+ ctx.roundRect(x, y, w, h, 12);
106
+ ctx.fill();
107
+ ctx.stroke();
108
+ ctx.restore();
109
+ text(ctx, title.toUpperCase(), x + 20, y + 30, g.label, { color: exports.INK.secondary, weight: 600 });
110
+ }
111
+ function grid(ctx, g) {
112
+ ctx.fillStyle = exports.INK.paper;
113
+ ctx.fillRect(0, 0, g.width, g.height);
114
+ ctx.strokeStyle = exports.INK.grid;
115
+ ctx.lineWidth = 1;
116
+ for (let x = 0; x <= g.width; x += 60) {
117
+ ctx.beginPath();
118
+ ctx.moveTo(x + .5, 0);
119
+ ctx.lineTo(x + .5, g.height);
120
+ ctx.stroke();
121
+ }
122
+ for (let y = 0; y <= g.height; y += 60) {
123
+ ctx.beginPath();
124
+ ctx.moveTo(0, y + .5);
125
+ ctx.lineTo(g.width, y + .5);
126
+ ctx.stroke();
127
+ }
128
+ }
129
+ /** A counter tweens from its previous value over 400 ms after each recorded change. */
130
+ function counter(previous, current, changedAt, t) {
131
+ return Math.round(previous + (current - previous) * easeOut((t - changedAt) / 400));
132
+ }
133
+ function header(ctx, model, state, g) {
134
+ const wordSize = Math.round(g.number * 1.15);
135
+ const agent = text(ctx, 'Agent', g.margin, g.header.y, wordSize, { weight: 600 });
136
+ text(ctx, 'Guard', g.margin + agent, g.header.y, wordSize, { weight: 600, color: exports.INK.teal });
137
+ text(ctx, `session ${model.session} · ${model.startAt.slice(0, 10)} ${model.startAt.slice(11, 16)} UTC · spawn gate`, g.margin, g.header.y + 34, g.small, { color: exports.INK.secondary });
138
+ const lastEvent = state.log.at(-1), lastStop = [...state.log].reverse().find(event => event.verdict === 'STOP');
139
+ const values = [
140
+ ['copies', String(counter(state.previousCopies, state.copies, state.copiesChangedAt, state.t)), state.warned ? exports.INK.amber : exports.INK.teal],
141
+ ['decisions', String(counter(Math.max(0, state.decisions - 1), state.decisions, lastEvent?.offsetMs ?? 0, state.t)), exports.INK.ink],
142
+ ['refused', String(counter(Math.max(0, state.refused - 1), state.refused, lastStop?.offsetMs ?? 0, state.t)), state.refused ? exports.INK.red : exports.INK.ink],
143
+ ['elapsed', clock(state.elapsedMs), exports.INK.ink],
144
+ ];
145
+ values.forEach(([label, value, color], index) => {
146
+ const x = g.header.counters.x + index * g.header.counters.step;
147
+ text(ctx, label.toUpperCase(), x, g.header.y - g.number * .78 - 14, g.label, { color: exports.INK.secondary, weight: 600 });
148
+ text(ctx, value, x, g.header.y, g.number, { family: 'mono', weight: 700, color });
149
+ });
150
+ }
151
+ function ring(ctx, model, state, g, phases) {
152
+ const { cx, cy, r, box } = g.ring, slots = model.ceiling ?? 16, top = -Math.PI / 2;
153
+ const angle = (k) => top + (k - .5) * (Math.PI * 2 / slots);
154
+ ctx.save();
155
+ ctx.strokeStyle = exports.INK.line;
156
+ ctx.lineWidth = 2;
157
+ ctx.beginPath();
158
+ ctx.arc(cx, cy, r, 0, Math.PI * 2);
159
+ ctx.stroke();
160
+ const shown = Math.min(state.copies, slots);
161
+ if (shown > 0) {
162
+ ctx.strokeStyle = state.warned ? exports.INK.amber : exports.INK.teal;
163
+ ctx.lineWidth = 4;
164
+ ctx.globalAlpha = .55;
165
+ ctx.beginPath();
166
+ ctx.arc(cx, cy, r, top, angle(shown) + Math.PI / slots);
167
+ ctx.stroke();
168
+ ctx.globalAlpha = 1;
169
+ }
170
+ // Flow: particles run clockwise around the active arc, their phases fixed by the seed, their position by the recorded clock.
171
+ if (shown > 0) {
172
+ const span = angle(shown) + Math.PI / slots - top;
173
+ for (const [i, phase] of phases.entries()) {
174
+ const u = (phase + state.t / 2600 + i * 0.013) % 1, a = top + u * span, rr = r + (i % 3 - 1) * 9;
175
+ ctx.fillStyle = state.warned ? exports.INK.amber : exports.INK.teal;
176
+ ctx.globalAlpha = .35 + .45 * Math.sin(u * Math.PI);
177
+ ctx.beginPath();
178
+ ctx.arc(cx + Math.cos(a) * rr, cy + Math.sin(a) * rr, 3.2, 0, Math.PI * 2);
179
+ ctx.fill();
180
+ }
181
+ ctx.globalAlpha = 1;
182
+ }
183
+ // The gate sits at the top of the ring, between the last slot and the first.
184
+ const gateW = r * .22;
185
+ ctx.strokeStyle = exports.INK.ink;
186
+ ctx.lineWidth = 6;
187
+ ctx.lineCap = 'round';
188
+ ctx.beginPath();
189
+ ctx.moveTo(cx - gateW, cy - r);
190
+ ctx.lineTo(cx + gateW, cy - r);
191
+ ctx.stroke();
192
+ text(ctx, 'gate', cx - gateW - 14, cy - r + 8, g.small, { color: exports.INK.secondary, align: 'right' });
193
+ // One marker per recorded spawn, popping in at its decision time; amber once the warn threshold is reached.
194
+ for (let k = 1; k <= shown; k++) {
195
+ const event = model.events.filter(event => event.verdict !== 'STOP')[k - 1];
196
+ const born = event ? event.offsetMs : 0, scale = easeOut((state.t - born) / 320);
197
+ if (scale <= 0)
198
+ continue;
199
+ const a = angle(k), x = cx + Math.cos(a) * r, y = cy + Math.sin(a) * r, warm = model.warnAt !== null && k >= model.warnAt;
200
+ ctx.fillStyle = exports.INK.paper;
201
+ ctx.beginPath();
202
+ ctx.arc(x, y, 19 * scale, 0, Math.PI * 2);
203
+ ctx.fill();
204
+ ctx.fillStyle = warm ? exports.INK.amber : exports.INK.teal;
205
+ ctx.beginPath();
206
+ ctx.arc(x, y, 14 * scale, 0, Math.PI * 2);
207
+ ctx.fill();
208
+ }
209
+ // Refused attempts: a red X above the gate for each recorded STOP, in order.
210
+ const stops = state.log.filter(event => event.verdict === 'STOP');
211
+ stops.forEach((event, i) => {
212
+ const scale = easeOut((state.t - event.offsetMs) / 260);
213
+ if (scale <= 0)
214
+ return;
215
+ const x = cx + (i - 1) * 58, y = cy - r - 40, s = 14 * scale;
216
+ ctx.strokeStyle = exports.INK.red;
217
+ ctx.lineWidth = 7;
218
+ ctx.lineCap = 'round';
219
+ ctx.beginPath();
220
+ ctx.moveTo(x - s, y - s);
221
+ ctx.lineTo(x + s, y + s);
222
+ ctx.moveTo(x + s, y - s);
223
+ ctx.lineTo(x - s, y + s);
224
+ ctx.stroke();
225
+ });
226
+ // The original agent in the middle.
227
+ ctx.fillStyle = exports.INK.paper;
228
+ ctx.strokeStyle = exports.INK.teal;
229
+ ctx.lineWidth = 4;
230
+ ctx.beginPath();
231
+ ctx.roundRect(cx - box / 2, cy - box / 2, box, box, 22);
232
+ ctx.fill();
233
+ ctx.stroke();
234
+ text(ctx, 'agent', cx, cy + 10, Math.round(box * .3), { weight: 600, align: 'center', color: exports.INK.teal });
235
+ text(ctx, 'original', cx, cy + box / 2 + 30, g.small, { color: exports.INK.secondary, align: 'center' });
236
+ ctx.restore();
237
+ }
238
+ function bar(ctx, model, state, g) {
239
+ const { x, y, w, h } = g.bar, ceiling = model.ceiling ?? 16, fraction = clamp01(counter(state.previousCopies * 100, state.copies * 100, state.copiesChangedAt, state.t) / 100 / ceiling);
240
+ const color = state.refused ? exports.INK.red : state.warned ? exports.INK.amber : exports.INK.teal;
241
+ text(ctx, `SPAWN RATE · ${model.windowActiveMinutes ?? '?'} ACTIVE MIN`, x, y - 22, g.label, { color: exports.INK.secondary, weight: 600 });
242
+ text(ctx, `${state.copies} / ${ceiling}`, x + w, y - 12, g.number, { family: 'mono', weight: 700, color, align: 'right' });
243
+ ctx.fillStyle = exports.INK.line;
244
+ ctx.beginPath();
245
+ ctx.roundRect(x, y, w, h, h / 2);
246
+ ctx.fill();
247
+ if (fraction > 0) {
248
+ ctx.fillStyle = color;
249
+ ctx.beginPath();
250
+ ctx.roundRect(x, y, Math.max(h, w * fraction), h, h / 2);
251
+ ctx.fill();
252
+ }
253
+ if (model.warnAt !== null) {
254
+ const wx = x + w * model.warnAt / ceiling;
255
+ ctx.strokeStyle = exports.INK.amber;
256
+ ctx.lineWidth = 3;
257
+ ctx.beginPath();
258
+ ctx.moveTo(wx, y - 8);
259
+ ctx.lineTo(wx, y + h + 8);
260
+ ctx.stroke();
261
+ text(ctx, `warn ${model.warnAt}`, wx + 10, y + h + 30, g.small, { color: exports.INK.amber });
262
+ }
263
+ text(ctx, `ceiling ${ceiling}`, x + w, y + h + 30, g.small, { color: exports.INK.secondary, align: 'right' });
264
+ }
265
+ function log(ctx, state, g) {
266
+ const { x, y, w, h, rows } = g.log;
267
+ panel(ctx, x, y, w, h, 'decisions · signed locally', g);
268
+ const pitch = (h - 56) / rows, shown = state.log.slice(-rows), start = y + 52;
269
+ if (!shown.length)
270
+ text(ctx, 'waiting for the first decision', x + 20, start + pitch * .7, g.body, { color: exports.INK.secondary });
271
+ shown.forEach((event, i) => {
272
+ const arrive = easeOut((state.t - event.offsetMs) / 300), row = start + i * pitch + pitch * .7, offset = (1 - arrive) * 24;
273
+ text(ctx, stamp(event.atMs), x + 20 + offset, row, g.body, { family: 'mono', color: exports.INK.ink, alpha: arrive });
274
+ text(ctx, event.tool, x + 20 + offset + g.body * 5.4, row, g.body, { color: exports.INK.secondary, alpha: arrive });
275
+ const chip = event.verdict === 'OK' ? 'ok' : event.verdict, chipW = ctx.measureText(chip).width;
276
+ text(ctx, chip, x + w - 20 - offset, row, g.body, { family: 'mono', weight: 700, color: verdictColor(event.verdict), align: 'right', alpha: arrive });
277
+ void chipW;
278
+ });
279
+ }
280
+ function agents(ctx, model, state, g) {
281
+ const { x, y, w, h, rows } = g.agents, economics = model.economics;
282
+ panel(ctx, x, y, w, h, 'subagents · measured after the run', g);
283
+ if (!economics) {
284
+ text(ctx, 'no subagent economics supplied', x + 20, y + 90, g.body, { color: exports.INK.secondary });
285
+ return;
286
+ }
287
+ const revealAt = model.firstStopMs ?? model.durationMs, reveal = easeOut((state.t - revealAt) / 1200);
288
+ if (reveal <= 0) {
289
+ text(ctx, `${economics.children.length} subagent transcripts`, x + 20, y + 84, g.body, { color: exports.INK.secondary });
290
+ text(ctx, 'priced once the run ends', x + 20, y + 84 + g.body * 1.4, g.body, { color: exports.INK.secondary });
291
+ return;
292
+ }
293
+ const total = { min: economics.totalUsd.min * reveal, max: economics.totalUsd.max * reveal };
294
+ text(ctx, (0, live_1.dollars)(total), x + 20, y + 52 + g.bigNumber, g.bigNumber, { family: 'mono', weight: 700, color: exports.INK.ink });
295
+ text(ctx, `list cost of ${economics.pricedCount} subagent transcripts · not a bill`, x + 20, y + 76 + g.bigNumber, g.small, { color: exports.INK.secondary });
296
+ const sorted = [...economics.children].sort((a, b) => (b.tokens ?? 0) - (a.tokens ?? 0)), top = sorted.slice(0, rows), max = top[0]?.tokens ?? 1;
297
+ const first = y + 100 + g.bigNumber, pitch = (h - (first - y) - 44) / rows, barW = w - 40 - g.number * 3.6;
298
+ top.forEach((child, i) => {
299
+ const row = first + i * pitch, fill = clamp01((child.tokens ?? 0) / max) * reveal;
300
+ ctx.fillStyle = exports.INK.line;
301
+ ctx.beginPath();
302
+ ctx.roundRect(x + 20, row + pitch * .3, barW, 10, 5);
303
+ ctx.fill();
304
+ ctx.fillStyle = exports.INK.teal;
305
+ ctx.beginPath();
306
+ ctx.roundRect(x + 20, row + pitch * .3, Math.max(10, barW * fill), 10, 5);
307
+ ctx.fill();
308
+ text(ctx, child.tokens === null ? '?' : tokens(child.tokens), x + w - 20, row + pitch * .3 + g.number * .42, g.number, { family: 'mono', align: 'right', alpha: reveal });
309
+ });
310
+ if (sorted.length > rows)
311
+ text(ctx, `and ${sorted.length - rows} more transcripts`, x + 20, y + h - 14, g.small, { color: exports.INK.secondary, alpha: reveal });
312
+ }
313
+ function card(ctx, state, g) {
314
+ if (!state.stop)
315
+ return;
316
+ const { x, y, w, h } = g.card, grow = easeOut((state.t - state.stop.offsetMs) / 250);
317
+ ctx.save();
318
+ ctx.globalAlpha = grow;
319
+ ctx.fillStyle = exports.INK.paper;
320
+ ctx.strokeStyle = exports.INK.red;
321
+ ctx.lineWidth = 3;
322
+ ctx.beginPath();
323
+ ctx.roundRect(x, y, w, h, 12);
324
+ ctx.fill();
325
+ ctx.stroke();
326
+ const outcome = state.stop.blocked === true ? 'next copy refused' : state.stop.blocked === false ? 'shadow, copy allowed' : 'outcome not recorded';
327
+ text(ctx, 'STOP', x + 22, y + h / 2 + g.number * .36, g.number, { family: 'mono', weight: 700, color: exports.INK.red });
328
+ const ceiling = state.stop.ceiling ?? '?', window = state.stop.windowActiveMinutes ?? '?';
329
+ text(ctx, `${state.stop.copies} of ${ceiling} in ${window} active min · ${outcome}`, x + 22 + g.number * 3, y + h / 2 - 4, g.body, { color: exports.INK.ink });
330
+ text(ctx, `${state.stop.reason} · signed on this machine`, x + 22 + g.number * 3, y + h / 2 + g.small + 6, g.small, { color: exports.INK.secondary });
331
+ ctx.restore();
332
+ }
333
+ function footer(ctx, model, g) {
334
+ text(ctx, 'RECORDED RUN · SIGNED LEDGER · agentguard.run', g.margin, g.footer.y, g.small, { color: exports.INK.secondary, weight: 600 });
335
+ text(ctx, `${model.session} · ${model.startAt.slice(0, 10)}`, g.width - g.margin, g.footer.y, g.small, { family: 'mono', color: exports.INK.secondary, align: 'right' });
336
+ }
337
+ /** One frame at offset t (ms from the first recorded frame). */
338
+ async function renderDashboardFrame(model, t, layout = 'phone', seed = exports.DASHBOARD_SEED) {
339
+ await registerFonts();
340
+ const g = geometry(layout), state = (0, dashboard_model_1.dashboardState)(model, t);
341
+ const random = mulberry(seed), phases = Array.from({ length: 24 }, () => random());
342
+ const canvas = (0, canvas_1.createCanvas)(g.width, g.height), ctx = canvas.getContext('2d');
343
+ grid(ctx, g);
344
+ header(ctx, model, state, g);
345
+ ring(ctx, model, state, g, phases);
346
+ card(ctx, state, g);
347
+ bar(ctx, model, state, g);
348
+ log(ctx, state, g);
349
+ agents(ctx, model, state, g);
350
+ footer(ctx, model, g);
351
+ return canvas.encode('png');
352
+ }
353
+ /** Frames at a fixed rate across the recorded span plus the hold, encoded like the terminal render. */
354
+ async function renderDashboard(source, options) {
355
+ const fps = options.fps ?? 30;
356
+ if (!Number.isInteger(fps) || fps < 1 || fps > 60)
357
+ throw new Error('Dashboard fps must be an integer from 1 to 60.');
358
+ const sourcePath = (0, node_path_1.resolve)(source), mp4Path = (0, node_path_1.resolve)(options.mp4), provenancePath = `${mp4Path}.provenance.json`;
359
+ const economicsPath = options.economics ? (0, node_path_1.resolve)(options.economics) : null;
360
+ const outputs = [mp4Path, provenancePath];
361
+ for (const path of [sourcePath, ...outputs, ...(economicsPath ? [economicsPath] : [])])
362
+ if (/[\x00-\x1f\x7f]/.test(path))
363
+ throw new Error('Recording paths must not contain control characters.');
364
+ if (new Set([sourcePath, ...outputs]).size !== 3 || economicsPath && outputs.includes(economicsPath))
365
+ throw new Error('Recording source and each output must use different paths.');
366
+ for (const path of outputs)
367
+ await (0, render_recording_1.requireUnused)(path);
368
+ const sourceStat = await (0, promises_1.stat)(sourcePath);
369
+ if (!sourceStat.isFile() || sourceStat.size > 128 * 1024 * 1024)
370
+ throw new Error('Recording must be a regular local file no larger than 128 MB.');
371
+ const sourceBytes = await (0, promises_1.readFile)(sourcePath);
372
+ const frames = (0, dashboard_model_1.readDashboardRecording)(sourcePath);
373
+ const economicsBytes = economicsPath ? await (0, promises_1.readFile)(economicsPath) : null;
374
+ const economics = economicsPath ? (0, dashboard_model_1.readDashboardEconomics)(economicsPath, frames[0].snapshot.session) : null;
375
+ if (!sourceBytes.equals(await (0, promises_1.readFile)(sourcePath)))
376
+ throw new Error('Recording changed while it was being read; render the saved file again.');
377
+ const model = (0, dashboard_model_1.dashboardModel)(frames, economics, dashboard_model_1.DASHBOARD_HOLD_MS);
378
+ const layout = options.wide ? 'wide' : 'phone', g = geometry(layout), seed = options.seed ?? exports.DASHBOARD_SEED;
379
+ const fonts = await registerFonts();
380
+ const total = Math.round((model.durationMs + model.holdMs) / 1000 * fps), frameCount = total + 1;
381
+ await (0, promises_1.mkdir)((0, node_path_1.dirname)(mp4Path), { recursive: true });
382
+ const framesDir = await (0, promises_1.mkdtemp)((0, node_path_1.join)((0, node_path_1.dirname)(mp4Path), `${(0, node_path_1.basename)(mp4Path)}.frames-`));
383
+ const concatPath = (0, node_path_1.join)(framesDir, 'frames.ffconcat'), lines = ['ffconcat version 1.0'], frameTimes = [];
384
+ for (let index = 0; index < frameCount; index++) {
385
+ const offset = index * 1000 / fps, name = `frame-${String(index).padStart(6, '0')}.png`;
386
+ frameTimes.push(new Date(model.startMs + offset).toISOString());
387
+ await (0, promises_1.writeFile)((0, node_path_1.join)(framesDir, name), await renderDashboardFrame(model, offset, layout, seed), { flag: 'wx', mode: 0o600 });
388
+ if (index < total)
389
+ lines.push(`file '${name}'`, 'option framerate 1000000', `duration ${(1 / fps).toFixed(6)}`);
390
+ }
391
+ // The terminal entry is the last frame itself, so the hold ends on the final state without adding time.
392
+ lines.push(`file 'frame-${String(total).padStart(6, '0')}.png'`, 'option framerate 1000000');
393
+ await (0, promises_1.writeFile)(concatPath, `${lines.join('\n')}\n`, { flag: 'wx', mode: 0o600 });
394
+ const ffmpeg = options.ffmpeg === null ? null : await (0, render_recording_1.executable)(options.ffmpeg || 'ffmpeg');
395
+ const mp4Args = ['-hide_banner', '-loglevel', 'error', '-nostdin', '-n', '-protocol_whitelist', 'file,pipe', '-f', 'concat', '-safe', '0', '-i', concatPath,
396
+ '-fps_mode', 'vfr', '-c:v', 'libx264', '-crf', '16', '-preset', 'slow', '-bf', '0', '-enc_time_base', '1:1000000', '-video_track_timescale', '1000000', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', mp4Path];
397
+ const command = [ffmpeg || 'ffmpeg', ...mp4Args].map(render_recording_1.shellWord).join(' ');
398
+ const provenance = {
399
+ source_sha256: (0, node_crypto_1.createHash)('sha256').update(sourceBytes).digest('hex'),
400
+ economics_path: economicsPath, economics_sha256: economicsBytes ? (0, node_crypto_1.createHash)('sha256').update(economicsBytes).digest('hex') : null,
401
+ renderer_version: require('../../package.json').version,
402
+ rendered_at: new Date().toISOString(),
403
+ fonts, layout: 'dashboard', frame_size: { width: g.width, height: g.height }, aspect: layout, fps, seed,
404
+ frame_count: frameCount, frame_times: frameTimes,
405
+ recording_span_seconds: model.durationMs / 1000, final_hold_seconds: model.holdMs / 1000,
406
+ video_timestamp_precision: 'microseconds; fixed 1/fps frame durations from the first recorded timestamp',
407
+ ffmpeg_command: command,
408
+ format: `Dashboard layout, ${g.width}x${g.height} PNG, motion from recorded timestamps and seed ${seed}`,
409
+ video_status: ffmpeg ? 'rendering' : 'ffmpeg_unavailable_png_frames_written',
410
+ };
411
+ await (0, promises_1.writeFile)(provenancePath, `${JSON.stringify(provenance, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
412
+ if (ffmpeg) {
413
+ try {
414
+ await run(ffmpeg, mp4Args, { timeout: 600_000, maxBuffer: 1024 * 1024 });
415
+ provenance.video_status = 'complete';
416
+ }
417
+ catch (error) {
418
+ provenance.video_status = 'failed_png_frames_written';
419
+ throw new Error(`Video encoding failed; PNG frames remain at ${framesDir}: ${error.message}`);
420
+ }
421
+ finally {
422
+ await (0, promises_1.writeFile)(provenancePath, `${JSON.stringify(provenance, null, 2)}\n`, { mode: 0o600 });
423
+ }
424
+ }
425
+ return { framesDir, provenancePath, mp4: ffmpeg ? mp4Path : null, ffmpegCommand: command, frameCount };
426
+ }
@@ -371,6 +371,9 @@ class Gateway {
371
371
  at: d.at,
372
372
  host: d.host,
373
373
  action: d.action,
374
+ // The plugin's mirror row carries this id, so an unsigned decision still
375
+ // joins once in local counts.
376
+ decisionId,
374
377
  sessionId: d.sessionId,
375
378
  verdict: d.verdict,
376
379
  wouldDeny: d.wouldBlock,
@@ -71,7 +71,7 @@ function decision(raw, sequence) {
71
71
  const rate = findings.find(f => f.detector === 'spawn_rate' && number(f.observed) !== null && verdict(f.verdict));
72
72
  const totals = object(raw.totals), coverage = object(raw.coverage), window = parseWindow(raw.window);
73
73
  return { sessionId, sessionDigest: digest(sessionId), sequence, at, verdict: result,
74
- id: safe(raw.toolUseId, digest(JSON.stringify(raw)) + ':' + sequence), tool: safe(raw.action ?? raw.tool, 'spawn'),
74
+ id: safe(raw.decisionId, safe(raw.toolUseId, digest(JSON.stringify(raw)) + ':' + sequence)), tool: safe(raw.action ?? raw.tool, 'spawn'),
75
75
  blocked: typeof raw.enforced === 'boolean' ? raw.enforced : null,
76
76
  reason: findings.map(f => `${safe(f.detector, 'unknown')}:${verdict(f.verdict) ?? 'OK'}`).join(' + ')
77
77
  || (raw.failClosed === true ? 'local fail-closed condition' : result === 'OK' ? 'within policy' : 'reason unavailable'),
@@ -7,6 +7,10 @@ export interface RenderRecordingResult {
7
7
  ffmpegCommand: string;
8
8
  frameCount: number;
9
9
  }
10
+ export declare function executable(requested: string): Promise<string | null>;
11
+ export declare function requireUnused(path: string): Promise<void>;
12
+ /** For display only; execution always passes an argument array without a shell. */
13
+ export declare function shellWord(value: string): string;
10
14
  export type RenderStyle = 'default' | 'showcase' | 'phone';
11
15
  export declare const PHONE_VIEWPORT: Readonly<{
12
16
  width: 40;
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PHONE_FRAME = exports.PHONE_VIEWPORT = void 0;
4
+ exports.executable = executable;
5
+ exports.requireUnused = requireUnused;
6
+ exports.shellWord = shellWord;
4
7
  exports.renderCanvasPng = renderCanvasPng;
5
8
  exports.renderRecording = renderRecording;
6
9
  /** Offline PNG and video rendering from validated, recorded Canvas data. */
@@ -0,0 +1,13 @@
1
+ export declare const TEAM_LINE = "Using this at work? Team puts one policy on every seat. agentguard.run/pricing";
2
+ export interface MonthlySummary {
3
+ month: string;
4
+ spawnsStopped: number;
5
+ commandsBlocked: number | null;
6
+ partial: boolean;
7
+ teamLine: boolean;
8
+ /** The one Team line this month, present exactly when it is consumed, so a JSON status prints what it used. */
9
+ teamLineText: string | null;
10
+ }
11
+ export declare function pluginDirectories(home: string, env?: NodeJS.ProcessEnv): string[];
12
+ export declare function monthlySummary(home: string, now?: number, env?: NodeJS.ProcessEnv): MonthlySummary | null;
13
+ export declare function renderMonthlySummary(summary: MonthlySummary | null): string;
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TEAM_LINE = void 0;
4
+ exports.pluginDirectories = pluginDirectories;
5
+ exports.monthlySummary = monthlySummary;
6
+ exports.renderMonthlySummary = renderMonthlySummary;
7
+ /** Local month-to-date counts and a dismissible Team invitation. No network. */
8
+ const node_fs_1 = require("node:fs");
9
+ const node_path_1 = require("node:path");
10
+ const ledger_panel_1 = require("./ledger-panel");
11
+ exports.TEAM_LINE = 'Using this at work? Team puts one policy on every seat. agentguard.run/pricing';
12
+ const object = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
13
+ function read(file, limit = 1024 * 1024 * 64) {
14
+ const fd = (0, node_fs_1.openSync)(file, node_fs_1.constants.O_RDONLY | node_fs_1.constants.O_NOFOLLOW | node_fs_1.constants.O_NONBLOCK);
15
+ try {
16
+ const stat = (0, node_fs_1.fstatSync)(fd);
17
+ if (!stat.isFile() || stat.size > limit || process.getuid && stat.uid !== process.getuid())
18
+ throw new Error('local_summary_unreadable');
19
+ return (0, node_fs_1.readFileSync)(fd, 'utf8');
20
+ }
21
+ finally {
22
+ (0, node_fs_1.closeSync)(fd);
23
+ }
24
+ }
25
+ function pluginDirectories(home, env = process.env) {
26
+ const paths = new Set([(0, node_path_1.join)(home, 'codex-plugin'), ...[env.PLUGIN_DATA, env.CLAUDE_PLUGIN_DATA].filter((value) => Boolean(value)).map(value => (0, node_path_1.resolve)(value))]);
27
+ try {
28
+ for (const file of (0, node_fs_1.readdirSync)((0, node_path_1.join)(home, 'plugin-ledgers'))) {
29
+ if (!/^[a-f0-9]{64}\.json$/.test(file))
30
+ continue;
31
+ try {
32
+ const record = object(JSON.parse(read((0, node_path_1.join)(home, 'plugin-ledgers', file), 4096)));
33
+ if (typeof record.data === 'string' && (0, node_path_1.resolve)(record.data) === record.data)
34
+ paths.add(record.data);
35
+ }
36
+ catch { /* An unreadable locator cannot add a source. */ }
37
+ }
38
+ }
39
+ catch { /* Older installations have no registry. */ }
40
+ return [...paths];
41
+ }
42
+ function paidConfiguration(directories, env) {
43
+ if (env.AGENTGUARD_LICENSE_KEY?.trim())
44
+ return true;
45
+ return directories.some(directory => {
46
+ try {
47
+ return Boolean(object(JSON.parse(read((0, node_path_1.join)(directory, 'policy.json')))).licenseKey);
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ });
53
+ }
54
+ function monthlySummary(home, now = Date.now(), env = process.env) {
55
+ const moments = (0, node_path_1.join)(home, 'upgrade-moments');
56
+ if ((0, node_fs_1.existsSync)((0, node_path_1.join)(moments, 'quiet')))
57
+ return null;
58
+ const directories = pluginDirectories(home, env);
59
+ if (paidConfiguration(directories, env))
60
+ return null;
61
+ const month = new Date(now).toISOString().slice(0, 7), since = Date.parse(month + '-01T00:00:00Z');
62
+ const spawns = new Set(), commands = new Set();
63
+ let partial = false, pluginLedger = false;
64
+ try {
65
+ for (const row of (0, ledger_panel_1.readPanelLedger)(home))
66
+ if (row.at >= since && row.at <= now && row.blocked === true && row.verdict === 'STOP' && row.tool === 'spawn')
67
+ spawns.add('burn:' + row.id);
68
+ }
69
+ catch {
70
+ partial = true;
71
+ }
72
+ for (const directory of directories) {
73
+ const file = (0, node_path_1.join)(directory, 'ledger', 'decisions.ndjson');
74
+ if (!(0, node_fs_1.existsSync)(file))
75
+ continue;
76
+ try {
77
+ const lines = read(file).split('\n').filter(Boolean);
78
+ pluginLedger = true;
79
+ for (const line of lines) {
80
+ let entry;
81
+ try {
82
+ entry = object(JSON.parse(line));
83
+ }
84
+ catch {
85
+ partial = true;
86
+ continue;
87
+ }
88
+ const decision = object(entry.decision), meta = object(decision.plugin);
89
+ const at = typeof decision.timestamp === 'string' ? Date.parse(decision.timestamp) : NaN;
90
+ if (!(at >= since && at <= now) || meta.event !== 'decision' || decision.action !== 'block' || decision.enforcementMode !== 'enforce' || meta.approvalNeeded === true || typeof decision.decisionId !== 'string')
91
+ continue;
92
+ if (meta.gate === 'burn' && ['spawn_agent', 'Agent', 'Task'].includes(String(meta.toolName)))
93
+ spawns.add(typeof meta.burnReceiptId === 'string' ? 'burn:' + meta.burnReceiptId : 'plugin:' + decision.decisionId);
94
+ if (meta.gate === 'spend' && /(?:^|[._])(?:bash|powershell|shell|exec_command|run_command|execute_command|run_shell_command|shell_command)$/i.test(String(meta.toolName)))
95
+ commands.add(decision.decisionId);
96
+ }
97
+ }
98
+ catch {
99
+ partial = true;
100
+ }
101
+ }
102
+ let teamLine = false;
103
+ try {
104
+ (0, node_fs_1.mkdirSync)(moments, { recursive: true, mode: 0o700 });
105
+ (0, node_fs_1.writeFileSync)((0, node_path_1.join)(moments, 'burn-month-' + month), '1\n', { flag: 'wx', mode: 0o600 });
106
+ teamLine = !(0, node_fs_1.existsSync)((0, node_path_1.join)(moments, 'quiet'));
107
+ }
108
+ catch { /* Once per calendar month; persistence failure suppresses copy. */ }
109
+ return { month, spawnsStopped: spawns.size, commandsBlocked: pluginLedger ? commands.size : null, partial, teamLine, teamLineText: teamLine ? exports.TEAM_LINE : null };
110
+ }
111
+ function renderMonthlySummary(summary) {
112
+ if (!summary)
113
+ return '';
114
+ const lines = [`This month (${summary.month}, UTC), in local records: ${summary.spawnsStopped} spawns stopped; ${summary.commandsBlocked ?? 'unknown'} commands blocked.`];
115
+ if (summary.commandsBlocked === null)
116
+ lines.push('Command counts require a readable local plugin ledger.');
117
+ if (summary.partial)
118
+ lines.push('Some local records were unreadable. These counts include only the readable records.');
119
+ if (summary.teamLine)
120
+ lines.push(exports.TEAM_LINE);
121
+ return lines.join('\n');
122
+ }