@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
package/dist/job.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { mkdtempSync, rmSync, existsSync, mkdirSync, writeFileSync, copyFileSync, appendFileSync, chmodSync, readdirSync, } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
2
3
  import { homedir, tmpdir } from 'node:os';
3
4
  import { join, basename, dirname, relative, sep } from 'node:path';
4
5
  import {} from 'node:child_process';
@@ -12,14 +13,20 @@ import { FULL_SHA, changeReads, hardFirst, refusesPush, scanAddedLines, secretRe
12
13
  import { isNetworkError, networkFailureHint, waitForNetwork, withNetworkRetry } from './network.js';
13
14
  import { endedOnRefusal, modelDeclinedSentence } from './declined.js';
14
15
  import { endedBySignal, stoppedSentence } from './stopped.js';
15
- import { changeKind, pullRequestBody, pullRequestTitle } from './pr-title.js';
16
+ import { AGENT_PR_FILE, changeKind, parseAgentPullRequest, pullRequestBody, pullRequestTitle, } from './pr-title.js';
16
17
  import { savePendingResult } from './pending.js';
17
18
  import { runnerDir } from './config.js';
18
19
  import { attemptUsage, combineUsage, describeUsage, } from './usage.js';
19
20
  import { changesOf, dropKept, keepUntilFrom, keptDir, keptFor, reviseBrief, saveKept, } from './ask-first.js';
20
21
  import { makeStreamJsonParser } from './session-stream.js';
22
+ import { parkReasonFor, parkedLine, resumeFromParked, stepBrief, } from './ask/index.js';
23
+ import { changedWhilePlanning, phaseOf, planPhaseBrief } from './plan-phase/index.js';
21
24
  import { writeSkills, writtenSkillPaths } from './skills.js';
22
- import { createKeyedMutex, ensureHeavyScript, heavyLockDir, withHeavyLock } from './locks.js';
25
+ import { ATTACH_FOLDER, attachLimitsOf, prepareAttachFolder, uploadRunAttachments, } from './run-attachments.js';
26
+ import { REFERENCE_FOLDER, mergeWritten, writeReferenceFiles, } from './reference-files.js';
27
+ import { blankSecrets, heldSecretValues, blankSecretsDeep, blankingApi, registerSecretValues, releaseSecretValues, } from './secret-values.js';
28
+ import { fallbackKey, startFallback } from './api-fallback.js';
29
+ import { createKeyedMutex, deviceLockDir, ensureDeviceScript, ensureHeavyScript, heavyLockDir, withHeavyLock, } from './locks.js';
23
30
  import { getAdapter, stripForeignEngineCreds } from './engines/index.js';
24
31
  import { mcpFormatForEngine, prepareMcp } from './mcp.js';
25
32
  import { continueToFinishBrief, engineRules } from './brief.js';
@@ -29,8 +36,10 @@ import { cutFor, dropCut, keepUntil, promptHash, resumeAfterResetBrief, saveCut,
29
36
  import { liveWorktrees, updateHeld } from './held.js';
30
37
  import { killOrphans, reviewCopiesOf, trackEngineGroup, untrackEngineGroup } from './orphans.js';
31
38
  import { canonicalPath, removeRunnerWorktree, staleHolder } from './worktrees.js';
39
+ import { detailOf, startRunTrail, trailOff } from './trail/index.js';
40
+ import { RUNNER_VERSION } from './version.js';
32
41
  function log(msg) {
33
- console.log(`[firefunc-runner] ${new Date().toISOString()} ${msg}`);
42
+ console.log(`[firefunc-runner] ${new Date().toISOString()} ${blankSecrets(msg)}`);
34
43
  }
35
44
  const gitMutex = createKeyedMutex();
36
45
  function saveSessionLog(runId, stdout, stderr) {
@@ -47,7 +56,7 @@ function saveSessionLog(runId, stdout, stderr) {
47
56
  catch {
48
57
  }
49
58
  const p = join(dir, `${runId}.log`);
50
- writeFileSync(p, redact(`=== agent stdout ===\n${stdout}\n\n=== agent stderr ===\n${stderr}\n`), {
59
+ writeFileSync(p, blankSecrets(redact(`=== agent stdout ===\n${stdout}\n\n=== agent stderr ===\n${stderr}\n`)), {
51
60
  mode: 0o600,
52
61
  });
53
62
  return p;
@@ -167,21 +176,87 @@ function unfinishedSentence(engineName, open, changeRun, continued) {
167
176
  function resumeBrief(prompt, why = 'network') {
168
177
  const what = why === 'limit'
169
178
  ? "was stopped by the plan's usage limit, which has now reset, and that session could not be continued"
170
- : 'was cut short by a network outage';
179
+ : why === 'api'
180
+ ? "was stopped by the plan's usage limit; this session continues on the machine's API key"
181
+ : 'was cut short by a network outage';
171
182
  return (`Your previous session on this task ${what}. The worktree ` +
172
183
  'still holds everything you did; look at `git status` and `git diff`, continue from ' +
173
184
  'there, and finish the task. The original brief follows.\n\n' +
174
185
  prompt);
175
186
  }
176
187
  export async function runJob(job, cfg, api, viewer, opts) {
188
+ api = blankingApi(api);
177
189
  const now = opts?.now ?? (() => new Date());
178
190
  const rdir = runnerDir();
191
+ const trailWriteTools = new Set();
192
+ const trail = trailOff(job) || typeof api.trail !== 'function'
193
+ ? null
194
+ : startRunTrail({
195
+ runId: job.runId,
196
+ runnerDir: rdir,
197
+ detail: detailOf(job),
198
+ post: (batch) => api.trail(job.runId, batch),
199
+ worktree: () => {
200
+ try {
201
+ return worktree;
202
+ }
203
+ catch {
204
+ return null;
205
+ }
206
+ },
207
+ blank: blankSecretsDeep,
208
+ who: { runner_version: RUNNER_VERSION, ...(job.engine ? { engine: job.engine } : {}) },
209
+ writeTools: trailWriteTools,
210
+ now,
211
+ });
212
+ if (trail)
213
+ void trail.runStarted(job.repo ? { repo: job.repo } : {});
179
214
  let secretScan;
180
215
  let usage;
181
216
  let readHead;
182
217
  let openCommandAtEnd = false;
218
+ let attachFolder = null;
219
+ let attachmentsSent = false;
220
+ const sendAttachments = async (status) => {
221
+ if (attachmentsSent || !job.runAttachments)
222
+ return;
223
+ if (status !== 'pr_opened' && status !== 'no_pr')
224
+ return;
225
+ const client = api;
226
+ if (typeof client.offerAttachment !== 'function')
227
+ return;
228
+ attachmentsSent = true;
229
+ let wt = null;
230
+ try {
231
+ wt = worktree;
232
+ }
233
+ catch {
234
+ return;
235
+ }
236
+ if (!wt)
237
+ return;
238
+ const dir = attachFolder ?? prepareAttachFolder(wt, () => { }).dir;
239
+ if (!dir)
240
+ return;
241
+ await uploadRunAttachments({
242
+ runId: job.runId,
243
+ dir,
244
+ api: client,
245
+ log,
246
+ limits: attachLimitsOf(job.runAttachments),
247
+ }).catch((e) => {
248
+ log(`the pictures for the ticket were not uploaded: ${e.message}`);
249
+ });
250
+ };
183
251
  const report = async (reported) => {
184
- let payload = secretScan && !reported.secretScan ? { ...reported, secretScan } : reported;
252
+ await sendAttachments(reported.status);
253
+ await trail
254
+ ?.finish({
255
+ status: reported.status,
256
+ ...('pr' in reported && reported.pr ? { pr: reported.pr } : {}),
257
+ })
258
+ .catch(() => { });
259
+ let payload = blankSecretsDeep(secretScan && !reported.secretScan ? { ...reported, secretScan } : reported);
185
260
  if (usage && !payload.usage)
186
261
  payload = { ...payload, usage };
187
262
  if (readHead && !payload.readHead)
@@ -236,6 +311,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
236
311
  const step = askFirst ? (job.askFirstStep ?? null) : null;
237
312
  const revising = step?.kind === 'revise' ? step : null;
238
313
  const kept = step ? keptFor(rdir, job.runId) : null;
314
+ const parkStep = job.parkStep ?? null;
315
+ const parkKept = parkStep ? keptFor(rdir, job.runId) : null;
316
+ let activitySeen = (kept ?? parkKept)?.activitySeq ?? 0;
317
+ const phase = phaseOf(job);
318
+ const planRound = Math.max(1, Number(job.planRound) || 1);
239
319
  const adapter = getAdapter(job.engine ?? cfg.engine);
240
320
  const spent = opts?.limits?.isLimited(adapter.id) ?? null;
241
321
  if (spent) {
@@ -260,6 +340,85 @@ export async function runJob(job, cfg, api, viewer, opts) {
260
340
  limit: { kind: 'machine', detail: unattended.detail },
261
341
  });
262
342
  }
343
+ const engineRuns = step?.kind !== 'publish';
344
+ const agentEnv = {};
345
+ const carriedNotes = [];
346
+ if (engineRuns && !toolsOnly && !review) {
347
+ carriedNotes.push(`When you change code, write the pull request's title (the first line) and its description (the rest) to \`${AGENT_PR_FILE}\` in your working directory, in the form the project's instructions ask for pull request titles and descriptions. FireFunc opens the pull request with them, or updates the one you continue. Never stage or commit that file.`);
348
+ }
349
+ if (engineRuns && job.agentEnv?.length) {
350
+ let got;
351
+ try {
352
+ got = await withNetworkRetry(() => api.agentEnv(job.runId), {
353
+ label: `environment variables for ${job.runId}`,
354
+ maxWaitMs: 5 * 60_000,
355
+ probe: () => api.probe(),
356
+ log,
357
+ });
358
+ }
359
+ catch (e) {
360
+ return fail(`The agent's environment variables could not be fetched from FireFunc (${oneLine(e.message, 120)}), so the engine was not started. Fix: check this machine can reach FireFunc, then re-run the task.`);
361
+ }
362
+ if ('refused' in got) {
363
+ return fail(`FireFunc did not hand this run the agent's environment variables, so the engine was not started: ${got.refused.reason} Fix: ${got.refused.fix}`);
364
+ }
365
+ registerSecretValues(job.runId, got.env.filter((e) => e.secret).map((e) => ({ name: e.name, value: e.value })));
366
+ for (const e of got.env)
367
+ agentEnv[e.name] = e.value;
368
+ for (const m of got.missing)
369
+ log(`variable ${m.name} is not set for this run: ${m.reason} Fix: ${m.fix}`);
370
+ if (got.env.length) {
371
+ log(`the engine gets ${got.env.length} of the agent's variable(s): ${got.env
372
+ .map((e) => (e.secret ? `${e.name} (secret)` : e.name))
373
+ .join(', ')}`);
374
+ const secrets = got.env.filter((e) => e.secret).map((e) => e.name);
375
+ carriedNotes.push(`This agent's own environment variables are set in your environment: ${got.env
376
+ .map((e) => e.name)
377
+ .join(', ')}. Read them from the environment when the task needs them.` +
378
+ (secrets.length
379
+ ? ` ${secrets.join(', ')} ${secrets.length === 1 ? 'is a secret' : 'are secrets'}: never print, log or echo ${secrets.length === 1 ? 'its value' : 'their values'}, and never write ${secrets.length === 1 ? 'it' : 'them'} into a file or a commit — FireFunc blanks secret values from everything it reports, and refuses a push that contains one.`
380
+ : ''));
381
+ }
382
+ if (got.missing.length) {
383
+ carriedNotes.push(`These of the agent's variables could not be set for this run: ${got.missing
384
+ .map((m) => m.name)
385
+ .join(', ')}. Say so in your answer if the task needed them.`);
386
+ }
387
+ }
388
+ const writeRefs = async (dir) => {
389
+ if (!engineRuns || !job.referenceFiles?.length)
390
+ return null;
391
+ let got;
392
+ try {
393
+ got = await withNetworkRetry(() => api.referenceFiles(job.runId), {
394
+ label: `reference files for ${job.runId}`,
395
+ maxWaitMs: 5 * 60_000,
396
+ probe: () => api.probe(),
397
+ log,
398
+ });
399
+ }
400
+ catch (e) {
401
+ return {
402
+ failure: `The agent's reference files could not be fetched from FireFunc (${oneLine(e.message, 120)}), so the engine was not started. Fix: check this machine can reach FireFunc, then re-run the task.`,
403
+ };
404
+ }
405
+ if ('refused' in got) {
406
+ return {
407
+ failure: `FireFunc did not hand this run the agent's reference files, so the engine was not started: ${got.refused.reason} Fix: ${got.refused.fix}`,
408
+ };
409
+ }
410
+ for (const m of got.missing)
411
+ log(`reference file ${m.name} is not here for this run: ${m.reason} Fix: ${m.fix}`);
412
+ const written = await writeReferenceFiles(dir, got.files, log);
413
+ const notHere = [...got.missing.map((m) => m.name), ...written.skipped.map((x) => x.name)];
414
+ if (written.names.length) {
415
+ carriedNotes.push(`This agent's reference files are in \`${REFERENCE_FOLDER}/\` in your working directory: ${written.names.join(', ')}. Read the ones the task needs before you start. They are the agent's, not the repository's: never move, edit, stage or commit them.`);
416
+ }
417
+ if (notHere.length) {
418
+ carriedNotes.push(`These of the agent's reference files could not be put in the working directory: ${notHere.join(', ')}. Say so in your answer if the task needed them.`);
419
+ }
420
+ return written;
421
+ };
263
422
  let repoPath = toolsOnly ? null : resolveRepoPath(job.repo, cfg);
264
423
  if (!repoPath && job.repo) {
265
424
  const cred = await api.gitCredential(job.runId);
@@ -299,7 +458,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
299
458
  : budget
300
459
  : (cfg.jobTimeoutMinutes ?? 20);
301
460
  const timeoutMs = limitMinutes * 60_000;
302
- const cutMatch = step
461
+ const cutMatch = step || parkStep
303
462
  ? null
304
463
  : cutFor(rdir, {
305
464
  workItemId: job.workItemId,
@@ -333,6 +492,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
333
492
  ...(kept.writtenSkills ? { writtenSkills: kept.writtenSkills } : {}),
334
493
  };
335
494
  }
495
+ else if (parkStep && parkKept) {
496
+ resumeCut = resumeFromParked(parkKept, promptHash(job.prompt));
497
+ }
336
498
  else if (cutMatch && 'resume' in cutMatch && adapter.resumesSessions) {
337
499
  resumeCut = cutMatch.resume;
338
500
  }
@@ -367,6 +529,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
367
529
  });
368
530
  const ship = async (s) => {
369
531
  const { worktree, branch, base, title, kind, engineName, summary } = s;
532
+ const agentText = s.agentText ?? null;
370
533
  const scanIn = worktree;
371
534
  const tipOf = async () => {
372
535
  const r = await exec('git', ['-C', scanIn, 'rev-parse', '--verify', '--quiet', `refs/heads/${branch}^{commit}`], { timeoutMs: 30_000 }).catch(() => null);
@@ -390,8 +553,21 @@ export async function runJob(job, cfg, api, viewer, opts) {
390
553
  why: `git exit ${failed.code}: ${failed.stderr.trim().slice(0, 200)}`,
391
554
  };
392
555
  }
556
+ const messages = await readChange([
557
+ '--no-replace-objects',
558
+ 'log',
559
+ '--format=%B%x00',
560
+ `${from}..${scannedTip ?? `refs/heads/${branch}`}`,
561
+ ], reads.env);
562
+ const inMessages = messages.code === 0 && heldSecretValues().some((sv) => messages.stdout.includes(sv.value))
563
+ ? [{ path: '(a commit message)', kind: 'agent_secret', line: 0 }]
564
+ : [];
393
565
  return {
394
- hits: uniqueHits([...scanAddedLines(whole.stdout), ...scanAddedLines(commits.stdout)]),
566
+ hits: uniqueHits([
567
+ ...scanAddedLines(whole.stdout),
568
+ ...scanAddedLines(commits.stdout),
569
+ ...inMessages,
570
+ ]),
395
571
  };
396
572
  };
397
573
  const found = (hits, n = 5) => hits
@@ -470,6 +646,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
470
646
  writtenSkills,
471
647
  ...(usage ? { attemptUsage: usage } : {}),
472
648
  ...(s.keep.sessionReport ? { sessionReport: s.keep.sessionReport } : {}),
649
+ activitySeq: activitySeen,
473
650
  });
474
651
  if (!saved) {
475
652
  return fail(`The change was made and committed on ${branch}, but the runner could not keep it for a person: it could not write ${keptDir(rdir)}. Nothing was pushed. Make that folder writable for the runner's user, then re-run the task.`);
@@ -526,7 +703,8 @@ export async function runJob(job, cfg, api, viewer, opts) {
526
703
  }
527
704
  const skillLeaked = writtenSkillPaths(stagedPaths, writtenSkills);
528
705
  if (skillLeaked.length > 0) {
529
- return fail(`refusing to push: the agent added ${skillLeaked.join(', ')} to its commit — a skill ` +
706
+ return fail(`refusing to push: the agent added ${skillLeaked.join(', ')} to its commit — ` +
707
+ `${skillLeaked.some((p) => p.includes(ATTACH_FOLDER)) ? 'a picture for the ticket' : skillLeaked.some((p) => p.includes(REFERENCE_FOLDER)) ? 'a reference file' : 'a skill'} ` +
530
708
  `FireFunc writes into the checkout for this run only and never commits. Nothing was ` +
531
709
  `pushed. Fix: tell the agent not to stage or commit anything under ` +
532
710
  `${skillLeaked[0].split('/').slice(0, -1).join('/')} (check its instruction and ` +
@@ -561,6 +739,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
561
739
  ? `git push failed: ${oneLine(refused, 400)}`
562
740
  : `git push failed (exit ${push.code}); its output stayed on the machine — the runner’s log shows it.`);
563
741
  }
742
+ await trail?.pushed({ branch });
564
743
  if (secretScan && scannedTip && scanCoversPullRequest) {
565
744
  const pushedTip = await tipOf();
566
745
  if (pushedTip === scannedTip)
@@ -568,7 +747,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
568
747
  else
569
748
  log(`the branch ${branch} moved between the secret scan and the push (${scannedTip.slice(0, 12)} → ${pushedTip?.slice(0, 12) ?? 'unreadable'}) — the result reports the scan without the commit it covers`);
570
749
  }
571
- const body = pullRequestBody(kind, engineName, job.externalId, { continuesBranch });
750
+ const body = agentText?.body
751
+ ? `${agentText.body}\n\n---\nOpened by FireFunc (self-hosted ${engineName} runner) for ${job.externalId ?? 'this task'}. Review before merging.`
752
+ : pullRequestBody(kind, engineName, job.externalId, { continuesBranch });
572
753
  if (gitCred) {
573
754
  const pr = await withNetworkRetry(() => openDraftPr({
574
755
  repo: gitCred.repo,
@@ -577,6 +758,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
577
758
  title,
578
759
  body,
579
760
  cred: gitCred,
761
+ update: !!agentText,
580
762
  }), {
581
763
  label: `pull request for ${job.runId}`,
582
764
  maxWaitMs: 10 * 60_000,
@@ -674,6 +856,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
674
856
  };
675
857
  let base = '';
676
858
  try {
859
+ if (parkStep && (!parkKept || !existsSync(parkKept.worktree))) {
860
+ return fail('The session this attempt kept on this machine for a person’s answer is no longer here (its kept folder was removed, or the runner was reinstalled), so it cannot go on. Re-run the task.');
861
+ }
677
862
  if (step && (!kept || !existsSync(kept.worktree))) {
678
863
  return fail('The change this attempt kept for approval is no longer on this machine (its kept folder was removed, or the runner was reinstalled), so it cannot be pushed. Re-run the task to make it again.');
679
864
  }
@@ -715,6 +900,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
715
900
  worktree = mkdtempSync(join(tmpdir(), 'firefunc-tools-'));
716
901
  updateHeld(rdir, job.runId, { scratch: [worktree] });
717
902
  writeSkills(worktree, job.skills, log);
903
+ const refs = await writeRefs(worktree);
904
+ if (refs && 'failure' in refs)
905
+ return fail(refs.failure);
718
906
  await exec('git', ['-C', worktree, 'init', '--quiet']);
719
907
  log(`no repository for ${job.runId} — the agent works through its tools in ${worktree}`);
720
908
  }
@@ -864,12 +1052,31 @@ export async function runJob(job, cfg, api, viewer, opts) {
864
1052
  }
865
1053
  if (resumeCut) {
866
1054
  writtenSkills = resumeCut.writtenSkills ?? { written: [], pathspecs: [] };
1055
+ if (job.referenceFiles?.length &&
1056
+ writtenSkills.written.some((p) => p.endsWith(REFERENCE_FOLDER))) {
1057
+ carriedNotes.push(`This agent's reference files are in \`${REFERENCE_FOLDER}/\` in your working directory: ${job.referenceFiles
1058
+ .map((f) => f.name)
1059
+ .join(', ')}. Never move, edit, stage or commit them.`);
1060
+ }
867
1061
  }
868
1062
  else if (!toolsOnly) {
869
1063
  writtenSkills = writeSkills(worktree, job.skills, log);
1064
+ const refs = await writeRefs(worktree);
1065
+ if (refs && 'failure' in refs)
1066
+ return fail(refs.failure);
1067
+ if (refs)
1068
+ writtenSkills = mergeWritten(writtenSkills, refs);
1069
+ }
1070
+ if (job.runAttachments && worktree) {
1071
+ const prepared = prepareAttachFolder(worktree, log);
1072
+ if (prepared.dir) {
1073
+ attachFolder = prepared.dir;
1074
+ writtenSkills = mergeWritten(writtenSkills, prepared);
1075
+ }
870
1076
  }
871
1077
  const heavyLock = !toolsOnly && job.repo && cfg.heavyLock !== false ? heavyLockDir(rdir, job.repo) : null;
872
1078
  const heavyHelper = heavyLock ? ensureHeavyScript(rdir) : null;
1079
+ const deviceHelper = heavyHelper ? ensureDeviceScript(rdir) : null;
873
1080
  const heavily = (fn) => heavyLock
874
1081
  ? withHeavyLock(heavyLock, fn, {
875
1082
  label: `setup of ${job.runId}`,
@@ -884,12 +1091,14 @@ export async function runJob(job, cfg, api, viewer, opts) {
884
1091
  for (const cmd of cfg.setupCommands) {
885
1092
  log(`setup: ${cmd}`);
886
1093
  const setupCwd = worktree;
1094
+ const setupAt = Date.now();
887
1095
  const r = await heavily(() => exec(cmd, [], {
888
1096
  cwd: setupCwd,
889
1097
  env: runEnv,
890
1098
  timeoutMs: setupMs,
891
1099
  shell: true,
892
1100
  }));
1101
+ await trail?.setupRan({ command: cmd, exitCode: r.code, durationMs: Date.now() - setupAt });
893
1102
  if (r.code !== 0) {
894
1103
  log(`setup output for ${job.runId} (kept on this machine):\n${r.stderr.slice(-4000)}` +
895
1104
  `${r.stdout.trim() ? `\n--- stdout ---\n${r.stdout.slice(-2000)}` : ''}`);
@@ -919,8 +1128,18 @@ export async function runJob(job, cfg, api, viewer, opts) {
919
1128
  const effort = job.effort ?? cfg.effort ?? null;
920
1129
  const ultracode = effort === 'ultracode';
921
1130
  const observeNote = 'Dev/observation tooling MAY be available here: the app may be runnable (setup ran), a dev server may be up, and AWS read creds / a staging URL / a test account may be in your environment. PREFER reproducing the reported symptom LIVE (run the app, curl the API, drive the UI) before reasoning statically, and re-observe after your change to confirm the fix. Treat any cloud/staging access as READ-ONLY.\n\n';
922
- const rules = engineRules({ minutes: limitMinutes, heavy: heavyHelper !== null });
923
- const prompt = rules + observeNote + attachNote + (ultracode ? `ultracode\n\n${job.prompt}` : job.prompt);
1131
+ const rules = engineRules({
1132
+ minutes: limitMinutes,
1133
+ heavy: heavyHelper !== null,
1134
+ device: deviceHelper !== null,
1135
+ attach: attachFolder !== null,
1136
+ });
1137
+ const carriedNote = carriedNotes.length ? `${carriedNotes.join('\n\n')}\n\n` : '';
1138
+ const prompt = rules +
1139
+ observeNote +
1140
+ attachNote +
1141
+ carriedNote +
1142
+ (ultracode ? `ultracode\n\n${job.prompt}` : job.prompt);
924
1143
  const tools = cfg.allowedTools ??
925
1144
  'Read Edit Write Bash Glob Grep WebFetch WebSearch Task TodoWrite NotebookEdit';
926
1145
  const isWin = process.platform === 'win32';
@@ -952,28 +1171,42 @@ export async function runJob(job, cfg, api, viewer, opts) {
952
1171
  isWin,
953
1172
  runEnv: {
954
1173
  ...stripForeignEngineCreds(runEnv, adapter.id),
1174
+ ...agentEnv,
955
1175
  ...(heavyHelper && heavyLock
956
1176
  ? { FIREFUNC_HEAVY: heavyHelper, FIREFUNC_HEAVY_LOCK: heavyLock }
957
1177
  : {}),
1178
+ ...(deviceHelper
1179
+ ? { FIREFUNC_DEVICE: deviceHelper, FIREFUNC_DEVICE_LOCK: deviceLockDir(rdir) }
1180
+ : {}),
958
1181
  },
959
1182
  cfg,
960
1183
  ...(mcp ? { mcp } : {}),
961
1184
  };
962
- const firstCtx = revising
963
- ? resumeCut?.sessionId && adapter.resumesSessions
964
- ? {
965
- ...ctx,
966
- resumeSessionId: resumeCut.sessionId,
967
- prompt: reviseBrief(revising.note, revising.round),
968
- }
969
- : { ...ctx, prompt: `${reviseBrief(revising.note, revising.round)}\n\n${ctx.prompt}` }
970
- : resumeCut
971
- ? {
972
- ...ctx,
973
- resumeSessionId: resumeCut.sessionId,
974
- prompt: resumeAfterResetBrief(prompt, promptHash(job.prompt) !== resumeCut.promptHash),
975
- }
976
- : ctx;
1185
+ if (phase === 'plan')
1186
+ ctx.prompt = `${planPhaseBrief(planRound)}\n\n${ctx.prompt}`;
1187
+ const parkBrief = parkStep ? stepBrief(parkStep, phase) : null;
1188
+ const parkCtx = parkBrief && resumeCut
1189
+ ? resumeCut.sessionId && adapter.resumesSessions
1190
+ ? { ...ctx, resumeSessionId: resumeCut.sessionId, prompt: parkBrief }
1191
+ : { ...ctx, prompt: `${parkBrief}\n\n${ctx.prompt}` }
1192
+ : null;
1193
+ const firstCtx = parkCtx
1194
+ ? parkCtx
1195
+ : revising
1196
+ ? resumeCut?.sessionId && adapter.resumesSessions
1197
+ ? {
1198
+ ...ctx,
1199
+ resumeSessionId: resumeCut.sessionId,
1200
+ prompt: reviseBrief(revising.note, revising.round),
1201
+ }
1202
+ : { ...ctx, prompt: `${reviseBrief(revising.note, revising.round)}\n\n${ctx.prompt}` }
1203
+ : resumeCut
1204
+ ? {
1205
+ ...ctx,
1206
+ resumeSessionId: resumeCut.sessionId,
1207
+ prompt: resumeAfterResetBrief(prompt, promptHash(job.prompt) !== resumeCut.promptHash, resumeCut.reason),
1208
+ }
1209
+ : ctx;
977
1210
  let inv;
978
1211
  try {
979
1212
  inv = adapter.buildInvocation(firstCtx);
@@ -989,12 +1222,17 @@ export async function runJob(job, cfg, api, viewer, opts) {
989
1222
  worktree,
990
1223
  post: (steps) => api.activity(job.runId, steps),
991
1224
  writeTools: new Set(mcp?.writeToolNames ?? []),
1225
+ seqStart: activitySeen,
992
1226
  });
1227
+ for (const name of mcp?.writeToolNames ?? [])
1228
+ trailWriteTools.add(name);
993
1229
  const activityParser = makeStreamJsonParser(activity.push, { toolResults: true });
994
1230
  const onStdout = (chunk) => {
995
- printer?.(chunk);
996
- viewer?.push(job.runId, chunk);
1231
+ const shown = blankSecrets(chunk);
1232
+ printer?.(shown);
1233
+ viewer?.push(job.runId, shown);
997
1234
  activityParser(chunk);
1235
+ trail?.feed(chunk);
998
1236
  };
999
1237
  if (printer) {
1000
1238
  log(`── live ${engineName} session (shown here only — never sent to FireFunc) ──`);
@@ -1002,7 +1240,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1002
1240
  const heartbeat = setInterval(() => void api.event(job.runId, 'heartbeat'), 5 * 60_000);
1003
1241
  const engineCwd = worktree;
1004
1242
  let engineMs = 0;
1005
- const runEngine = async (limitMs = timeoutMs) => {
1243
+ const runEngineOnce = async (limitMs = timeoutMs) => {
1006
1244
  let group = 0;
1007
1245
  const started = Date.now();
1008
1246
  try {
@@ -1028,6 +1266,27 @@ export async function runJob(job, cfg, api, viewer, opts) {
1028
1266
  engineMs += Date.now() - started;
1029
1267
  }
1030
1268
  };
1269
+ const runEngine = async (limitMs = timeoutMs) => {
1270
+ await trail?.engineStarted({
1271
+ engine: adapter.id,
1272
+ model: model ?? null,
1273
+ where: {
1274
+ ...(job.repo ? { repo: job.repo } : {}),
1275
+ ...(toolsOnly ? {} : { branch }),
1276
+ ...(readHead ? { base_sha: readHead } : {}),
1277
+ },
1278
+ });
1279
+ const t0 = Date.now();
1280
+ let code = 1;
1281
+ try {
1282
+ const r = await runEngineOnce(limitMs);
1283
+ code = r.code;
1284
+ return r;
1285
+ }
1286
+ finally {
1287
+ await trail?.engineEnded({ exitCode: code, durationMs: Date.now() - t0 });
1288
+ }
1289
+ };
1031
1290
  const sessions = [];
1032
1291
  let lastReport = null;
1033
1292
  const meter = (stdout, continued = false) => {
@@ -1065,9 +1324,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
1065
1324
  log(`${engineName} could not continue the session a plan limit cut — starting a new session in the same worktree`);
1066
1325
  inv = adapter.buildInvocation({
1067
1326
  ...ctx,
1068
- prompt: revising
1069
- ? `${reviseBrief(revising.note, revising.round)}\n\n${ctx.prompt}`
1070
- : resumeBrief(ctx.prompt, 'limit'),
1327
+ prompt: parkBrief
1328
+ ? `${parkBrief}\n\n${ctx.prompt}`
1329
+ : revising
1330
+ ? `${reviseBrief(revising.note, revising.round)}\n\n${ctx.prompt}`
1331
+ : resumeBrief(ctx.prompt, 'limit'),
1071
1332
  });
1072
1333
  engineRun = await runEngine();
1073
1334
  meter(engineRun.stdout, false);
@@ -1097,6 +1358,16 @@ export async function runJob(job, cfg, api, viewer, opts) {
1097
1358
  engineRun = await runEngine();
1098
1359
  meter(engineRun.stdout, false);
1099
1360
  }
1361
+ {
1362
+ const planCut = limitOf(engineRun.stdout);
1363
+ if (planCut && adapter.id === 'claude_code' && fallbackKey(cfg, rdir)) {
1364
+ const until = startFallback(planCut.resetsAt, rdir, now());
1365
+ log(`${engineName}'s plan limit is spent — continuing on the API key until ${until.toISOString()}, in the same worktree`);
1366
+ inv = adapter.buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt, 'api') });
1367
+ engineRun = await runEngine();
1368
+ meter(engineRun.stdout, false);
1369
+ }
1370
+ }
1100
1371
  const openAtEnd = (stdout) => {
1101
1372
  try {
1102
1373
  return adapter.openCommandsAtEnd?.(stdout) ?? [];
@@ -1106,8 +1377,18 @@ export async function runJob(job, cfg, api, viewer, opts) {
1106
1377
  }
1107
1378
  };
1108
1379
  const endedOnItsAnswer = (r) => r.code === 0 && !limitOf(r.stdout) && !refused(r.stdout, r.stderr);
1109
- let open = endedOnItsAnswer(engineRun) ? openAtEnd(engineRun.stdout) : [];
1110
- let promising = endedOnItsAnswer(engineRun) && promisesLaterCheck(adapter.summarize(engineRun.stdout));
1380
+ const parkNow = endedOnItsAnswer(engineRun) && (job.askPerson === true || phase === 'plan')
1381
+ ? await parkReasonFor({
1382
+ askPerson: job.askPerson === true,
1383
+ phase,
1384
+ planRound,
1385
+ check: () => api.parkCheck(job.runId),
1386
+ })
1387
+ : null;
1388
+ let open = !parkNow && endedOnItsAnswer(engineRun) ? openAtEnd(engineRun.stdout) : [];
1389
+ let promising = !parkNow &&
1390
+ endedOnItsAnswer(engineRun) &&
1391
+ promisesLaterCheck(adapter.summarize(engineRun.stdout));
1111
1392
  const toContinue = adapter.resumesSessions
1112
1393
  ? (adapter.sessionId?.(engineRun.stdout) ?? null)
1113
1394
  : null;
@@ -1138,12 +1419,16 @@ export async function runJob(job, cfg, api, viewer, opts) {
1138
1419
  if (revising && kept?.attemptUsage) {
1139
1420
  usage = combineUsage([kept.attemptUsage, usage ?? null]) ?? usage;
1140
1421
  }
1422
+ if (parkStep && parkKept?.attemptUsage) {
1423
+ usage = combineUsage([parkKept.attemptUsage, usage ?? null]) ?? usage;
1424
+ }
1141
1425
  if (usage)
1142
1426
  log(`${engineName} spent: ${describeUsage(usage)}`);
1143
1427
  viewer?.end(job.runId, engineRun.code === 0 ? 'done' : 'failed');
1144
1428
  if (printer)
1145
1429
  log(`── end ${engineName} session ──`);
1146
1430
  await activity.flush();
1431
+ activitySeen = activity.seen;
1147
1432
  log(`reported ${activity.sent} of ${activity.seen} step(s) to FireFunc — names and verbs only; the session stayed here`);
1148
1433
  mcp?.cleanup();
1149
1434
  const sessionLogPath = saveSessionLog(job.runId, engineRun.stdout, engineRun.stderr);
@@ -1153,9 +1438,42 @@ export async function runJob(job, cfg, api, viewer, opts) {
1153
1438
  if (summary)
1154
1439
  log(`${engineName} said: ${summary.replace(/\s+/g, ' ').slice(0, 500)}`);
1155
1440
  if (engineRun.code === 124) {
1156
- return fail(budget !== null && limitMinutes === budget
1441
+ const timedOutSession = adapter.resumesSessions
1442
+ ? (adapter.sessionId?.(engineRun.stdout) ?? (resumeCut?.sessionId || null))
1443
+ : null;
1444
+ let keptOnTimeout = false;
1445
+ if (timedOutSession && worktree && !parkStep && !step) {
1446
+ const cutAt = now().getTime();
1447
+ keptOnTimeout = saveCut(rdir, {
1448
+ workItemId: job.workItemId,
1449
+ runId: job.runId,
1450
+ engine: adapter.id,
1451
+ sessionId: timedOutSession,
1452
+ repo: job.repo ?? null,
1453
+ branch: toolsOnly ? '' : branch,
1454
+ base,
1455
+ worktree,
1456
+ repoPath: toolsOnly ? null : repoPath,
1457
+ ...(readHead ? { readHead } : {}),
1458
+ resetsAt: null,
1459
+ cutAt: new Date(cutAt).toISOString(),
1460
+ keepUntil: keepUntil(null, cutAt),
1461
+ promptHash: promptHash(job.prompt),
1462
+ review,
1463
+ toolsOnly,
1464
+ continuesBranch,
1465
+ ...(lastReport ? { usage: lastReport } : {}),
1466
+ writtenSkills,
1467
+ reason: 'timeout',
1468
+ });
1469
+ }
1470
+ keepWorktree = keptOnTimeout;
1471
+ const limitWords = budget !== null && limitMinutes === budget
1157
1472
  ? `${engineName} timed out after ${limitMinutes} min — the agent's time budget.`
1158
- : `${engineName} timed out after ${limitMinutes} min.`);
1473
+ : `${engineName} timed out after ${limitMinutes} min.`;
1474
+ return fail(keptOnTimeout
1475
+ ? `${limitWords} Its work is kept on this machine for a day: Re-run continues it from where it stopped.`
1476
+ : limitWords);
1159
1477
  }
1160
1478
  const limit = limitOf(engineRun.stdout);
1161
1479
  if (limit) {
@@ -1220,6 +1538,53 @@ export async function runJob(job, cfg, api, viewer, opts) {
1220
1538
  }
1221
1539
  return null;
1222
1540
  };
1541
+ if (parkNow) {
1542
+ const head = (await execOut('git', ['-C', worktree, 'rev-parse', 'HEAD']).catch(() => '')).trim() ||
1543
+ '0'.repeat(40);
1544
+ const changedFiles = parkNow.kind === 'plan' && !toolsOnly ? await changedWhilePlanning(worktree) : null;
1545
+ const at = now();
1546
+ const saved = saveKept(rdir, {
1547
+ runId: job.runId,
1548
+ workItemId: job.workItemId,
1549
+ engine: adapter.id,
1550
+ sessionId: adapter.sessionId?.(engineRun.stdout) ?? (resumeCut?.sessionId || null),
1551
+ repo: job.repo ?? '',
1552
+ branch: toolsOnly ? '' : branch,
1553
+ base,
1554
+ worktree,
1555
+ repoPath: toolsOnly ? null : (repoPath ?? null),
1556
+ continuesBranch,
1557
+ ...(readHead ? { readHead } : {}),
1558
+ head,
1559
+ round: parkNow.seq,
1560
+ title: job.title ?? '',
1561
+ kind: 'fix',
1562
+ summary: summary ? reportedSummary(summary) : null,
1563
+ keptAt: at.toISOString(),
1564
+ keepUntil: keepUntilFrom(at.getTime()),
1565
+ writtenSkills,
1566
+ ...(usage ? { attemptUsage: usage } : {}),
1567
+ ...(lastReport ? { sessionReport: lastReport } : {}),
1568
+ park: { kind: parkNow.kind, seq: parkNow.seq, phase },
1569
+ activitySeq: activitySeen,
1570
+ review,
1571
+ toolsOnly,
1572
+ });
1573
+ if (!saved) {
1574
+ return fail(`The run stopped for a person, but the runner could not keep its session to go on with the answer: it could not write ${keptDir(rdir)}. Make that folder writable for the runner's user, then re-run the task.`);
1575
+ }
1576
+ keepWorktree = true;
1577
+ log(parkedLine(job.runId, parkNow));
1578
+ return report({
1579
+ status: 'parked',
1580
+ park: {
1581
+ kind: parkNow.kind,
1582
+ seq: parkNow.seq,
1583
+ ...(changedFiles !== null ? { changedFiles } : {}),
1584
+ },
1585
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
1586
+ });
1587
+ }
1223
1588
  if (engineRun.code !== 0) {
1224
1589
  const signal = endedBySignal(engineRun.code);
1225
1590
  if (signal) {
@@ -1277,6 +1642,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1277
1642
  '.',
1278
1643
  ':(exclude).env',
1279
1644
  ':(exclude).claude/skills',
1645
+ `:(exclude,literal)${AGENT_PR_FILE}`,
1280
1646
  ...writtenSkills.pathspecs,
1281
1647
  ]);
1282
1648
  const vsBase = await exec('git', [
@@ -1311,7 +1677,12 @@ export async function runJob(job, cfg, api, viewer, opts) {
1311
1677
  continuesBranch ? `origin/${branch}` : `origin/${base}`,
1312
1678
  ], { timeoutMs: 60_000 }).catch(() => null);
1313
1679
  const kind = changeKind(touched?.code === 0 ? touched.stdout.split('\0').filter(Boolean) : null);
1314
- const title = pullRequestTitle(job, kind);
1680
+ const agentText = await readFile(join(worktree, AGENT_PR_FILE), 'utf8')
1681
+ .then((t) => parseAgentPullRequest(blankSecrets(t.slice(0, 70_000))))
1682
+ .catch(() => null);
1683
+ const title = agentText?.title ?? pullRequestTitle(job, kind);
1684
+ if (agentText)
1685
+ log(`the agent named the pull request in ${AGENT_PR_FILE}`);
1315
1686
  log(`${kind === 'test' ? 'the change touches tests only — ' : ''}titled "${title}"`);
1316
1687
  const uncommitted = await exec('git', ['-C', worktree, 'diff', '--cached', '--quiet', 'HEAD']);
1317
1688
  if (uncommitted.code !== 0) {
@@ -1328,6 +1699,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1328
1699
  kind,
1329
1700
  engineName,
1330
1701
  summary,
1702
+ agentText,
1331
1703
  keep: askFirst
1332
1704
  ? {
1333
1705
  sessionId: adapter.sessionId?.(engineRun.stdout) ?? (resumeCut?.sessionId || null),
@@ -1342,6 +1714,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
1342
1714
  return report({ status: 'failed', error: err.message.slice(0, 400) });
1343
1715
  }
1344
1716
  finally {
1717
+ if (job.agentEnv?.length) {
1718
+ setTimeout(() => releaseSecretValues(job.runId), 15 * 60_000).unref();
1719
+ }
1345
1720
  mcp?.cleanup();
1346
1721
  viewer?.end(job.runId, 'failed');
1347
1722
  await Promise.all(bgProcs.map((p) => killProcessTree(p).catch(() => { })));
@@ -1370,6 +1745,8 @@ export async function runJob(job, cfg, api, viewer, opts) {
1370
1745
  dropCut(rdir, resumeCut.workItemId);
1371
1746
  if (kept && !keepWorktree)
1372
1747
  dropKept(rdir, job.runId);
1748
+ if (parkKept && !keepWorktree)
1749
+ dropKept(rdir, job.runId);
1373
1750
  if (!keepWorktree) {
1374
1751
  for (const copy of reviewCopies) {
1375
1752
  try {