@firefunc-agent/runner 0.9.7 → 0.9.14

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 (55) hide show
  1. package/README.md +2 -0
  2. package/dist/activity.d.ts +1 -0
  3. package/dist/activity.js +1 -1
  4. package/dist/api-fallback.d.ts +9 -0
  5. package/dist/api-fallback.js +55 -0
  6. package/dist/api.d.ts +121 -0
  7. package/dist/api.js +147 -3
  8. package/dist/ask/index.d.ts +20 -0
  9. package/dist/ask/index.js +64 -0
  10. package/dist/ask-first.d.ts +8 -0
  11. package/dist/brief.d.ts +2 -0
  12. package/dist/brief.js +6 -0
  13. package/dist/build-info.json +2 -2
  14. package/dist/config.d.ts +2 -0
  15. package/dist/cut.d.ts +2 -1
  16. package/dist/cut.js +8 -4
  17. package/dist/daemon.js +14 -2
  18. package/dist/engines/claude.js +10 -4
  19. package/dist/git-auth.d.ts +1 -0
  20. package/dist/git-auth.js +9 -1
  21. package/dist/job.js +415 -38
  22. package/dist/keep-local.d.ts +1 -0
  23. package/dist/keep-local.js +3 -0
  24. package/dist/limit.d.ts +1 -0
  25. package/dist/limit.js +4 -1
  26. package/dist/locks.d.ts +3 -0
  27. package/dist/locks.js +46 -13
  28. package/dist/plan-phase/index.d.ts +11 -0
  29. package/dist/plan-phase/index.js +46 -0
  30. package/dist/pool.js +4 -2
  31. package/dist/pr-title.d.ts +5 -0
  32. package/dist/pr-title.js +18 -0
  33. package/dist/reference-files.d.ts +27 -0
  34. package/dist/reference-files.js +202 -0
  35. package/dist/run-attachments.d.ts +79 -0
  36. package/dist/run-attachments.js +276 -0
  37. package/dist/secret-scan.d.ts +1 -1
  38. package/dist/secret-scan.js +3 -0
  39. package/dist/secret-values.d.ts +17 -0
  40. package/dist/secret-values.js +81 -0
  41. package/dist/trail/chain.d.ts +12 -0
  42. package/dist/trail/chain.js +89 -0
  43. package/dist/trail/deltas.d.ts +34 -0
  44. package/dist/trail/deltas.js +206 -0
  45. package/dist/trail/index.d.ts +27 -0
  46. package/dist/trail/index.js +128 -0
  47. package/dist/trail/keys.d.ts +14 -0
  48. package/dist/trail/keys.js +61 -0
  49. package/dist/trail/recorder.d.ts +118 -0
  50. package/dist/trail/recorder.js +697 -0
  51. package/dist/trail/rules.d.ts +30 -0
  52. package/dist/trail/rules.js +158 -0
  53. package/dist/trail/stream.d.ts +41 -0
  54. package/dist/trail/stream.js +86 -0
  55. package/package.json +1 -1
@@ -0,0 +1,697 @@
1
+ import { hostname } from 'node:os';
2
+ import { commandName } from '../keep-local.js';
3
+ import { relativePath } from '../activity.js';
4
+ import { digestText, eventHashOf, genesisHash, hmacHex, merkleRoot, signText, ulid, } from './chain.js';
5
+ import { createDeltaTracker } from './deltas.js';
6
+ import { flagsOfCommand, hostOf, isTestPath, LIMITS, riskOf, sensitiveClassOf, storablePath, storableWords, TYPE_CATEGORY, WITHHELD_WORDS, } from './rules.js';
7
+ import { makeTrailStreamParser } from './stream.js';
8
+ export const DETAIL_LEVELS = ['summary', 'standard', 'forensic'];
9
+ const EDIT_TOOLS = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit']);
10
+ const READ_TOOLS = new Set(['Read', 'NotebookRead']);
11
+ const SEARCH_TOOLS = new Set(['Grep', 'Glob', 'LS']);
12
+ const NO_LOOK = new Set([
13
+ ...READ_TOOLS,
14
+ ...SEARCH_TOOLS,
15
+ 'Skill',
16
+ 'WebFetch',
17
+ 'WebSearch',
18
+ 'TodoWrite',
19
+ ]);
20
+ export function createTrailRecorder(opts) {
21
+ const now = opts.now ?? (() => new Date());
22
+ const blank = opts.blank ?? ((v) => v);
23
+ const maxBatch = Math.min(opts.maxBatch ?? 100, 200);
24
+ const intervalMs = opts.intervalMs ?? 5000;
25
+ const cap = opts.cap ?? 20_000;
26
+ const forensic = opts.detail === 'forensic';
27
+ const deltas = createDeltaTracker({
28
+ worktree: opts.worktree,
29
+ contentKey: opts.keys.content.key,
30
+ forensic,
31
+ ...(opts.git ? { git: opts.git } : {}),
32
+ });
33
+ const hostFingerprint = hmacHex(opts.keys.content.key, `host:${hostname()}`);
34
+ let who = { run_id: opts.runId, ...(opts.who ?? {}) };
35
+ let seq = opts.resume?.seq ?? 0;
36
+ let prev = opts.resume?.prev ?? genesisHash(opts.runId, 'machine');
37
+ const hashes = [...(opts.resume?.hashes ?? [])];
38
+ const counts = { ...(opts.resume?.counts ?? {}) };
39
+ let gaps = opts.resume?.gaps ?? 0;
40
+ let dropped = 0;
41
+ let filtered = 0;
42
+ let streamLines = 0;
43
+ let firstDroppedAt = null;
44
+ let pending = [];
45
+ const unsent = [];
46
+ let gone = false;
47
+ let finished = false;
48
+ let timer = null;
49
+ let queue = Promise.resolve();
50
+ const open = new Map();
51
+ const iso = () => now().toISOString();
52
+ const arm = () => {
53
+ if (!timer && !gone) {
54
+ timer = setTimeout(() => {
55
+ timer = null;
56
+ void send(false);
57
+ }, intervalMs);
58
+ timer.unref?.();
59
+ }
60
+ };
61
+ const record = (input, at = iso()) => {
62
+ if (finished && input.type !== 'run.ended' && input.type !== 'gap')
63
+ return null;
64
+ const category = TYPE_CATEGORY[input.type];
65
+ if (!category)
66
+ return null;
67
+ const summaryKeeps = category !== 'data' && category !== 'control'
68
+ ? true
69
+ : input.readOnly === false ||
70
+ input.type === 'plan.updated' ||
71
+ (input.action.command?.files_changed
72
+ ?.length ?? 0) > 0;
73
+ if (opts.detail === 'summary' && !summaryKeeps) {
74
+ filtered += 1;
75
+ return null;
76
+ }
77
+ if (seq >= cap && !summaryKeeps) {
78
+ dropped += 1;
79
+ firstDroppedAt ??= at;
80
+ return null;
81
+ }
82
+ seq += 1;
83
+ const base = blank({
84
+ event_id: ulid(now().getTime()),
85
+ schema_version: 1,
86
+ source: 'machine',
87
+ seq,
88
+ prev_hash: prev,
89
+ occurred_at: at,
90
+ type: input.type,
91
+ category,
92
+ read_only: input.readOnly === undefined ? null : input.readOnly,
93
+ risk: input.risk ?? riskOf(input.type),
94
+ who,
95
+ ...(input.where ? { where: input.where } : {}),
96
+ action: input.action,
97
+ ...(input.decision ? { decision: input.decision } : {}),
98
+ ...(input.result ? { result: input.result } : {}),
99
+ ...(input.gap ? { gap: input.gap } : {}),
100
+ ...(input.addendum ? { addendum: input.addendum } : {}),
101
+ });
102
+ const hash = eventHashOf(base);
103
+ const ev = {
104
+ ...base,
105
+ event_hash: hash,
106
+ key_id: opts.keys.signing.keyId,
107
+ sig: signText(opts.keys.signing.privateKey, hash),
108
+ };
109
+ prev = hash;
110
+ hashes.push(hash);
111
+ counts[category] = (counts[category] ?? 0) + 1;
112
+ if (input.type === 'gap')
113
+ gaps += 1;
114
+ pending.push(ev);
115
+ if (pending.length >= maxBatch)
116
+ void send(false);
117
+ else
118
+ arm();
119
+ return ev;
120
+ };
121
+ const enqueue = (fn) => {
122
+ queue = queue.then(fn).catch(() => { });
123
+ return queue;
124
+ };
125
+ const batchOf = (events, digest) => ({
126
+ machine_key: { key_id: opts.keys.signing.keyId, public_key: opts.keys.signing.publicKey },
127
+ hmac_key_id: opts.keys.content.keyId,
128
+ detail: opts.detail,
129
+ events,
130
+ ...(digest ? { digest } : {}),
131
+ });
132
+ let sending = null;
133
+ const send = async (final, digest) => {
134
+ if (sending)
135
+ await sending;
136
+ if (gone)
137
+ return;
138
+ while (pending.length > 0)
139
+ unsent.push(batchOf(pending.splice(0, maxBatch)));
140
+ if (digest) {
141
+ const last = unsent[unsent.length - 1];
142
+ if (last && !last.digest)
143
+ last.digest = digest;
144
+ else
145
+ unsent.push(batchOf([], digest));
146
+ }
147
+ if (unsent.length === 0)
148
+ return;
149
+ sending = (async () => {
150
+ while (unsent.length > 0) {
151
+ const b = unsent[0];
152
+ let answer;
153
+ try {
154
+ answer = await opts.post(b);
155
+ }
156
+ catch {
157
+ if (!final)
158
+ arm();
159
+ return;
160
+ }
161
+ if (answer === 'gone') {
162
+ gone = true;
163
+ unsent.length = 0;
164
+ pending = [];
165
+ return;
166
+ }
167
+ unsent.shift();
168
+ }
169
+ })().finally(() => {
170
+ sending = null;
171
+ });
172
+ await sending;
173
+ };
174
+ const fileEvidence = (d, generatedBy) => {
175
+ const path = storablePath(d.path);
176
+ const cls = sensitiveClassOf(d.path);
177
+ return {
178
+ path,
179
+ generated_by: generatedBy,
180
+ ...(d.created ? { created: true } : {}),
181
+ ...(d.deleted ? { deleted: true } : {}),
182
+ ...(d.isBinary ? { is_binary: true } : {}),
183
+ ...(isTestPath(d.path) ? { is_test: true } : {}),
184
+ lines_added: d.linesAdded,
185
+ lines_removed: d.linesRemoved,
186
+ hunks: d.hunks,
187
+ ...(forensic && d.hunkRanges.length
188
+ ? { hunk_ranges: d.hunkRanges.slice(0, LIMITS.hunks) }
189
+ : {}),
190
+ ...(forensic && d.hashBefore ? { content_hash_before: d.hashBefore } : {}),
191
+ ...(forensic && d.hashAfter ? { content_hash_after: d.hashAfter } : {}),
192
+ _sensitive: cls,
193
+ };
194
+ };
195
+ const finishFiles = (files) => {
196
+ const classes = files.map((f) => f._sensitive).filter(Boolean);
197
+ return {
198
+ files: files.map(({ _sensitive: _s, ...f }) => f),
199
+ sensitive: classes.length > 0,
200
+ };
201
+ };
202
+ const look = async () => {
203
+ try {
204
+ return await deltas.snapshot();
205
+ }
206
+ catch {
207
+ return null;
208
+ }
209
+ };
210
+ const relPath = (p) => {
211
+ if (!p)
212
+ return undefined;
213
+ const wt = opts.worktree();
214
+ return storablePath(wt ? relativePath(p, wt) : p);
215
+ };
216
+ const target = (kind, id) => {
217
+ if (!id)
218
+ return [];
219
+ const cls = kind === 'file' ? sensitiveClassOf(id) : undefined;
220
+ return [{ kind, id, ...(cls ? { sensitive_class: cls } : {}) }];
221
+ };
222
+ const resultOf = (o, isError, at) => {
223
+ const started = Date.parse(o.startedAt);
224
+ const ended = Date.parse(at);
225
+ return {
226
+ ...(isError === null ? {} : { outcome: isError ? 'error' : 'ok' }),
227
+ started_at: o.startedAt,
228
+ ended_at: at,
229
+ ...(Number.isFinite(started) && Number.isFinite(ended)
230
+ ? { duration_ms: Math.max(0, ended - started) }
231
+ : {}),
232
+ };
233
+ };
234
+ const onCallEnd = async (id, o, isError) => {
235
+ const at = iso();
236
+ const res = resultOf(o, isError, at);
237
+ const result = 'outcome' in res ? res : { ...res, outcome: 'skipped', error_type: 'no_result_seen' };
238
+ const sub = o.parentId ? { subagent_id: o.parentId } : {};
239
+ const base = { tool_call_id: id };
240
+ const w = who;
241
+ if (o.parentId)
242
+ who = { ...who, ...sub };
243
+ try {
244
+ const mcp = /^mcp__([^_]+(?:_[^_]+)*)__(.+)$/.exec(o.name);
245
+ const changes = NO_LOOK.has(o.name) || mcp ? null : await look();
246
+ const changed = changes?.deltas ?? [];
247
+ if (changes && changes.truncated > 0) {
248
+ record({
249
+ type: 'gap',
250
+ action: { tool: 'fs', action: 'look' },
251
+ gap: {
252
+ reason: 'events_dropped',
253
+ dropped: changes.truncated,
254
+ detail: 'More files changed than one look records; the rest were not looked at.',
255
+ },
256
+ });
257
+ }
258
+ if (READ_TOOLS.has(o.name)) {
259
+ const p = relPath(o.input.file_path ?? o.input.notebook_path);
260
+ record({
261
+ type: 'file.read',
262
+ readOnly: true,
263
+ action: { tool: 'fs', action: 'read', ...base, targets: target('file', p) },
264
+ result,
265
+ }, o.startedAt);
266
+ }
267
+ else if (EDIT_TOOLS.has(o.name)) {
268
+ const p = relPath(o.input.file_path ?? o.input.notebook_path);
269
+ const { files, sensitive } = finishFiles(changed.map((d) => fileEvidence(d, storablePath(d.path) === p ? 'edit_tool' : 'unattributed')));
270
+ record({
271
+ type: 'file.edited',
272
+ readOnly: false,
273
+ risk: riskOf('file.edited', { sensitive: sensitive || !!(p && sensitiveClassOf(p)) }),
274
+ action: {
275
+ tool: 'fs',
276
+ action: o.name === 'Write' ? 'create' : 'edit',
277
+ ...base,
278
+ targets: target('file', p),
279
+ ...(files.length ? { file: files } : {}),
280
+ },
281
+ result,
282
+ }, o.startedAt);
283
+ }
284
+ else if (SEARCH_TOOLS.has(o.name)) {
285
+ const dir = relPath(o.input.path);
286
+ record({
287
+ type: 'search',
288
+ readOnly: true,
289
+ action: {
290
+ tool: 'fs',
291
+ action: o.name === 'LS' ? 'list' : 'search',
292
+ ...base,
293
+ targets: target('dir', dir),
294
+ },
295
+ result,
296
+ }, o.startedAt);
297
+ }
298
+ else if (o.name === 'Bash') {
299
+ const program = commandName(o.input.command ?? '');
300
+ const { files, sensitive } = finishFiles(changed.map((d) => fileEvidence(d, 'shell')));
301
+ record({
302
+ type: 'exec',
303
+ readOnly: null,
304
+ risk: riskOf('exec', { sensitive }),
305
+ action: {
306
+ tool: 'shell',
307
+ action: 'exec',
308
+ ...base,
309
+ command: {
310
+ program: storableWords(program, LIMITS.label) ?? 'a command',
311
+ argv_shape: flagsOfCommand(o.input.command ?? ''),
312
+ ...(o.input.run_in_background ? { background: true } : {}),
313
+ ...(files.length ? { files_changed: files.map((f) => f.path) } : {}),
314
+ },
315
+ ...(files.length ? { file: files } : {}),
316
+ },
317
+ result,
318
+ }, o.startedAt);
319
+ }
320
+ else if (o.name === 'Skill') {
321
+ record({
322
+ type: 'skill.read',
323
+ readOnly: true,
324
+ action: {
325
+ tool: 'engine',
326
+ action: 'skill',
327
+ ...base,
328
+ targets: target('skill', storableWords(o.input.skill ?? '', 80) ?? undefined),
329
+ },
330
+ result,
331
+ }, o.startedAt);
332
+ }
333
+ else if (o.name === 'WebFetch') {
334
+ const h = o.input.url ? hostOf(o.input.url) : null;
335
+ record({
336
+ type: 'web.fetch',
337
+ readOnly: true,
338
+ action: {
339
+ tool: 'web',
340
+ action: 'fetch',
341
+ ...base,
342
+ ...(h
343
+ ? {
344
+ targets: [{ kind: 'host', id: h.host }],
345
+ network: { ...h, method: 'GET', allowed: null, initiator: 'engine' },
346
+ }
347
+ : {}),
348
+ },
349
+ result,
350
+ }, o.startedAt);
351
+ }
352
+ else if (o.name === 'WebSearch') {
353
+ record({
354
+ type: 'web.search',
355
+ readOnly: true,
356
+ action: { tool: 'web', action: 'search', ...base },
357
+ result,
358
+ }, o.startedAt);
359
+ }
360
+ else if (o.name === 'Task' || o.name === 'Agent') {
361
+ const { files } = finishFiles(changed.map((d) => fileEvidence(d, 'unattributed')));
362
+ record({
363
+ type: 'subagent.started',
364
+ readOnly: null,
365
+ action: {
366
+ tool: 'engine',
367
+ action: 'subagent',
368
+ ...base,
369
+ ...(o.input.subagent_type
370
+ ? {
371
+ targets: target('agent', storableWords(o.input.subagent_type, 60) ?? undefined),
372
+ }
373
+ : {}),
374
+ ...(files.length ? { file: files } : {}),
375
+ },
376
+ result,
377
+ }, o.startedAt);
378
+ }
379
+ else if (mcp) {
380
+ const viaFireFunc = mcp[1] === 'firefunc' ? /^([a-z]+)_(.+)$/.exec(mcp[2]) : null;
381
+ const tool = viaFireFunc ? viaFireFunc[1] : mcp[1];
382
+ const action = viaFireFunc ? viaFireFunc[2] : mcp[2];
383
+ const write = opts.writeTools?.has(o.name) === true;
384
+ record({
385
+ type: 'tool.call',
386
+ readOnly: write ? false : viaFireFunc ? true : null,
387
+ risk: riskOf('tool.call', { write }),
388
+ action: {
389
+ tool: `mcp:${mcp[1]}`,
390
+ action: 'call',
391
+ ...base,
392
+ targets: [{ kind: 'mcp_tool', id: `${tool}/${action}`.slice(0, 200) }],
393
+ ...(write ? { vendor_write: { tool, mode: viaFireFunc ? 'live' : 'direct' } } : {}),
394
+ },
395
+ result,
396
+ }, o.startedAt);
397
+ }
398
+ else if (o.name !== 'TodoWrite') {
399
+ const { files, sensitive } = finishFiles(changed.map((d) => fileEvidence(d, 'unattributed')));
400
+ record({
401
+ type: 'tool.call',
402
+ readOnly: null,
403
+ risk: riskOf('tool.call', { write: files.length > 0 || sensitive }),
404
+ action: {
405
+ tool: 'engine',
406
+ action: 'call',
407
+ ...base,
408
+ targets: [
409
+ {
410
+ kind: 'mcp_tool',
411
+ id: (storableWords(o.name, 80) ?? 'a tool').replace(/\s+/g, '_'),
412
+ },
413
+ ],
414
+ ...(files.length ? { file: files } : {}),
415
+ },
416
+ result,
417
+ }, o.startedAt);
418
+ }
419
+ }
420
+ finally {
421
+ who = w;
422
+ }
423
+ };
424
+ const onStream = (ev) => {
425
+ streamLines += 1;
426
+ if (ev.kind === 'init') {
427
+ who = {
428
+ ...who,
429
+ ...(ev.model ? { model: ev.model.slice(0, 100) } : {}),
430
+ ...(ev.version ? { engine_version: ev.version.slice(0, 60) } : {}),
431
+ };
432
+ return;
433
+ }
434
+ if (ev.kind === 'tool_use') {
435
+ const o = {
436
+ name: ev.name,
437
+ input: ev.input,
438
+ startedAt: iso(),
439
+ ...(ev.parentId ? { parentId: ev.parentId } : {}),
440
+ };
441
+ if (ev.name === 'TodoWrite' && ev.input.todos) {
442
+ const items = ev.input.todos.slice(0, LIMITS.plan).map((t) => ({
443
+ title: storableWords(t.content) ?? WITHHELD_WORDS,
444
+ status: t.status === 'completed' || t.status === 'in_progress' ? t.status : 'pending',
445
+ }));
446
+ void enqueue(() => {
447
+ record({
448
+ type: 'plan.updated',
449
+ readOnly: true,
450
+ action: { tool: 'engine', action: 'plan', tool_call_id: ev.id, plan: items },
451
+ }, o.startedAt);
452
+ });
453
+ }
454
+ if (open.size < 5000)
455
+ open.set(ev.id, o);
456
+ return;
457
+ }
458
+ if (ev.kind === 'tool_result') {
459
+ const o = open.get(ev.id);
460
+ if (!o)
461
+ return;
462
+ open.delete(ev.id);
463
+ if (o.name === 'TodoWrite')
464
+ return;
465
+ void enqueue(() => onCallEnd(ev.id, o, ev.isError));
466
+ return;
467
+ }
468
+ if (ev.kind === 'result') {
469
+ lastSession = ev;
470
+ }
471
+ };
472
+ let lastSession = null;
473
+ const parse = makeTrailStreamParser(onStream);
474
+ let engineStartedAt = null;
475
+ let engineStreamAtStart = 0;
476
+ const api = {
477
+ get runId() {
478
+ return opts.runId;
479
+ },
480
+ get stats() {
481
+ return { recorded: seq, filtered, dropped, gaps, gone };
482
+ },
483
+ head() {
484
+ return { seq, prev, hashes: [...hashes], counts: { ...counts }, gaps };
485
+ },
486
+ feed(chunk) {
487
+ if (finished)
488
+ return;
489
+ try {
490
+ parse(chunk);
491
+ }
492
+ catch {
493
+ }
494
+ },
495
+ setWho(extra) {
496
+ who = { ...who, ...extra };
497
+ },
498
+ emit(input) {
499
+ const at = iso();
500
+ return enqueue(() => {
501
+ record(input, at);
502
+ });
503
+ },
504
+ async runStarted(where = {}) {
505
+ const nonRoot = typeof process.getuid === 'function' ? process.getuid() !== 0 : undefined;
506
+ await api.emit({
507
+ type: 'run.started',
508
+ readOnly: true,
509
+ ...(opts.resume
510
+ ? {
511
+ addendum: {
512
+ reason: 'The run resumed on this machine; its chain continues from the earlier session.',
513
+ },
514
+ }
515
+ : {}),
516
+ action: { tool: 'runner', action: 'start' },
517
+ where: {
518
+ host_fingerprint: hostFingerprint,
519
+ ...(nonRoot === undefined ? {} : { os_user_not_root: nonRoot }),
520
+ ...where,
521
+ },
522
+ });
523
+ },
524
+ async setupRan(info) {
525
+ await api.emit({
526
+ type: 'setup.ran',
527
+ readOnly: null,
528
+ action: {
529
+ tool: 'shell',
530
+ action: 'setup',
531
+ command: {
532
+ program: storableWords(commandName(info.command)) ?? 'a command',
533
+ exit_code: info.exitCode,
534
+ },
535
+ },
536
+ result: {
537
+ outcome: info.exitCode === 0 ? 'ok' : 'error',
538
+ duration_ms: Math.max(0, Math.round(info.durationMs)),
539
+ },
540
+ });
541
+ },
542
+ async engineStarted(info) {
543
+ engineStartedAt = iso();
544
+ engineStreamAtStart = streamLines;
545
+ if (info.engine)
546
+ who = { ...who, engine: info.engine.slice(0, 60) };
547
+ if (info.model)
548
+ who = { ...who, model: info.model.slice(0, 100) };
549
+ await enqueue(async () => {
550
+ await deltas.prime().catch(() => false);
551
+ const head = await deltas.head().catch(() => null);
552
+ record({
553
+ type: 'engine.started',
554
+ readOnly: true,
555
+ action: { tool: 'engine', action: 'start' },
556
+ where: { ...(info.where ?? {}), ...(head ? { head_sha_before: head } : {}) },
557
+ }, engineStartedAt ?? iso());
558
+ });
559
+ },
560
+ async engineEnded(info) {
561
+ const s = lastSession;
562
+ const sawSteps = streamLines > engineStreamAtStart;
563
+ const left = [...open.entries()];
564
+ open.clear();
565
+ for (const [id, o] of left)
566
+ void enqueue(() => onCallEnd(id, o, null));
567
+ await enqueue(async () => {
568
+ if (!sawSteps) {
569
+ record({
570
+ type: 'gap',
571
+ action: { tool: 'engine', action: 'stream' },
572
+ gap: {
573
+ reason: 'engine_stream_unreadable',
574
+ ...(engineStartedAt ? { from: engineStartedAt } : {}),
575
+ to: iso(),
576
+ detail: "The engine's steps could not be read from its output; what it did in this span is not recorded.",
577
+ },
578
+ });
579
+ }
580
+ const head = await deltas.head().catch(() => null);
581
+ record({
582
+ type: 'engine.ended',
583
+ readOnly: true,
584
+ action: { tool: 'engine', action: 'end' },
585
+ ...(head ? { where: { head_sha_after: head } } : {}),
586
+ result: {
587
+ outcome: info.exitCode === 0 ? 'ok' : info.exitCode === 124 ? 'timeout' : 'error',
588
+ ...(engineStartedAt ? { started_at: engineStartedAt } : {}),
589
+ ended_at: iso(),
590
+ duration_ms: Math.max(0, Math.round(info.durationMs)),
591
+ ...(s?.tokensIn !== undefined ? { tokens_in: s.tokensIn } : {}),
592
+ ...(s?.tokensOut !== undefined ? { tokens_out: s.tokensOut } : {}),
593
+ ...(s?.tokensCache !== undefined ? { tokens_cache: s.tokensCache } : {}),
594
+ },
595
+ });
596
+ });
597
+ lastSession = null;
598
+ },
599
+ async pushed(info) {
600
+ await enqueue(async () => {
601
+ const head = await deltas.head().catch(() => null);
602
+ record({
603
+ type: 'git.push',
604
+ readOnly: false,
605
+ action: {
606
+ tool: 'git',
607
+ action: 'push',
608
+ targets: [{ kind: 'ref', id: storablePath(info.branch) }],
609
+ },
610
+ where: { branch: storablePath(info.branch), ...(head ? { head_sha_after: head } : {}) },
611
+ result: { outcome: 'ok' },
612
+ });
613
+ });
614
+ },
615
+ async finish(info) {
616
+ if (finished)
617
+ return;
618
+ const left = [...open.entries()];
619
+ open.clear();
620
+ for (const [id, o] of left)
621
+ void enqueue(() => onCallEnd(id, o, null));
622
+ await enqueue(async () => {
623
+ const last = await look();
624
+ if (last && last.deltas.length) {
625
+ const { files, sensitive } = finishFiles(last.deltas.map((d) => fileEvidence(d, 'unattributed')));
626
+ record({
627
+ type: 'file.changed',
628
+ readOnly: false,
629
+ risk: riskOf('file.changed', { sensitive }),
630
+ action: { tool: 'fs', action: 'edit', file: files },
631
+ });
632
+ }
633
+ if (info.status === 'pr_opened' && info.pr?.number) {
634
+ record({
635
+ type: 'pr.opened',
636
+ readOnly: false,
637
+ action: {
638
+ tool: 'git',
639
+ action: 'open_pr',
640
+ targets: [{ kind: 'pr', id: String(info.pr.number) }],
641
+ },
642
+ result: { outcome: 'ok' },
643
+ });
644
+ }
645
+ if (dropped > 0) {
646
+ record({
647
+ type: 'gap',
648
+ action: { tool: 'runner', action: 'record' },
649
+ gap: {
650
+ reason: 'recorder_overflow',
651
+ dropped,
652
+ ...(firstDroppedAt ? { from: firstDroppedAt } : {}),
653
+ to: iso(),
654
+ },
655
+ });
656
+ }
657
+ finished = true;
658
+ const outcome = info.status === 'failed' ? 'error' : 'ok';
659
+ record({
660
+ type: 'run.ended',
661
+ readOnly: true,
662
+ action: { tool: 'runner', action: 'end' },
663
+ result: { outcome },
664
+ });
665
+ });
666
+ if (timer) {
667
+ clearTimeout(timer);
668
+ timer = null;
669
+ }
670
+ const digest = {
671
+ run_id: opts.runId,
672
+ source: 'machine',
673
+ first_seq: 1,
674
+ last_seq: Math.max(1, seq),
675
+ count: seq,
676
+ last_hash: prev,
677
+ root: merkleRoot(hashes),
678
+ counts_by_category: { ...counts },
679
+ gaps,
680
+ detail: opts.detail,
681
+ sealed_at: iso(),
682
+ };
683
+ const signed = { ...digest, key_id: opts.keys.signing.keyId };
684
+ signed.sig = signText(opts.keys.signing.privateKey, digestText(signed));
685
+ await send(true, signed);
686
+ if (!gone && unsent.length > 0 && opts.keep) {
687
+ try {
688
+ opts.keep([...unsent]);
689
+ }
690
+ catch {
691
+ }
692
+ }
693
+ },
694
+ };
695
+ return api;
696
+ }
697
+ //# sourceMappingURL=recorder.js.map