@firefunc-agent/runner 0.9.6 → 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 (59) 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 +138 -0
  7. package/dist/api.js +153 -4
  8. package/dist/ask/index.d.ts +20 -0
  9. package/dist/ask/index.js +64 -0
  10. package/dist/ask-first.d.ts +59 -0
  11. package/dist/ask-first.js +126 -0
  12. package/dist/brief.d.ts +2 -0
  13. package/dist/brief.js +6 -0
  14. package/dist/build-info.json +2 -2
  15. package/dist/config.d.ts +2 -0
  16. package/dist/cut.d.ts +3 -1
  17. package/dist/cut.js +15 -4
  18. package/dist/daemon.js +51 -5
  19. package/dist/engines/claude.js +10 -4
  20. package/dist/engines/copilot.js +3 -2
  21. package/dist/firefunc/agents.js +1 -1
  22. package/dist/git-auth.d.ts +1 -0
  23. package/dist/git-auth.js +9 -1
  24. package/dist/job.js +1324 -804
  25. package/dist/keep-local.d.ts +1 -0
  26. package/dist/keep-local.js +3 -0
  27. package/dist/limit.d.ts +1 -0
  28. package/dist/limit.js +4 -1
  29. package/dist/locks.d.ts +3 -0
  30. package/dist/locks.js +46 -13
  31. package/dist/plan-phase/index.d.ts +11 -0
  32. package/dist/plan-phase/index.js +46 -0
  33. package/dist/pool.js +4 -2
  34. package/dist/pr-title.d.ts +5 -0
  35. package/dist/pr-title.js +18 -0
  36. package/dist/reference-files.d.ts +27 -0
  37. package/dist/reference-files.js +202 -0
  38. package/dist/run-attachments.d.ts +79 -0
  39. package/dist/run-attachments.js +276 -0
  40. package/dist/secret-scan.d.ts +1 -1
  41. package/dist/secret-scan.js +3 -0
  42. package/dist/secret-values.d.ts +17 -0
  43. package/dist/secret-values.js +81 -0
  44. package/dist/trail/chain.d.ts +12 -0
  45. package/dist/trail/chain.js +89 -0
  46. package/dist/trail/deltas.d.ts +34 -0
  47. package/dist/trail/deltas.js +206 -0
  48. package/dist/trail/index.d.ts +27 -0
  49. package/dist/trail/index.js +128 -0
  50. package/dist/trail/keys.d.ts +14 -0
  51. package/dist/trail/keys.js +61 -0
  52. package/dist/trail/recorder.d.ts +118 -0
  53. package/dist/trail/recorder.js +697 -0
  54. package/dist/trail/rules.d.ts +30 -0
  55. package/dist/trail/rules.js +158 -0
  56. package/dist/trail/stream.d.ts +41 -0
  57. package/dist/trail/stream.js +86 -0
  58. package/package.json +1 -1
  59. package/skill/firefunc/SKILL.md +3 -3
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,13 +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
- import { attemptUsage, describeUsage } from './usage.js';
19
+ import { attemptUsage, combineUsage, describeUsage, } from './usage.js';
20
+ import { changesOf, dropKept, keepUntilFrom, keptDir, keptFor, reviseBrief, saveKept, } from './ask-first.js';
19
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';
20
24
  import { writeSkills, writtenSkillPaths } from './skills.js';
21
- 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';
22
30
  import { getAdapter, stripForeignEngineCreds } from './engines/index.js';
23
31
  import { mcpFormatForEngine, prepareMcp } from './mcp.js';
24
32
  import { continueToFinishBrief, engineRules } from './brief.js';
@@ -28,8 +36,10 @@ import { cutFor, dropCut, keepUntil, promptHash, resumeAfterResetBrief, saveCut,
28
36
  import { liveWorktrees, updateHeld } from './held.js';
29
37
  import { killOrphans, reviewCopiesOf, trackEngineGroup, untrackEngineGroup } from './orphans.js';
30
38
  import { canonicalPath, removeRunnerWorktree, staleHolder } from './worktrees.js';
39
+ import { detailOf, startRunTrail, trailOff } from './trail/index.js';
40
+ import { RUNNER_VERSION } from './version.js';
31
41
  function log(msg) {
32
- console.log(`[firefunc-runner] ${new Date().toISOString()} ${msg}`);
42
+ console.log(`[firefunc-runner] ${new Date().toISOString()} ${blankSecrets(msg)}`);
33
43
  }
34
44
  const gitMutex = createKeyedMutex();
35
45
  function saveSessionLog(runId, stdout, stderr) {
@@ -46,7 +56,7 @@ function saveSessionLog(runId, stdout, stderr) {
46
56
  catch {
47
57
  }
48
58
  const p = join(dir, `${runId}.log`);
49
- 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`)), {
50
60
  mode: 0o600,
51
61
  });
52
62
  return p;
@@ -166,21 +176,87 @@ function unfinishedSentence(engineName, open, changeRun, continued) {
166
176
  function resumeBrief(prompt, why = 'network') {
167
177
  const what = why === 'limit'
168
178
  ? "was stopped by the plan's usage limit, which has now reset, and that session could not be continued"
169
- : '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';
170
182
  return (`Your previous session on this task ${what}. The worktree ` +
171
183
  'still holds everything you did; look at `git status` and `git diff`, continue from ' +
172
184
  'there, and finish the task. The original brief follows.\n\n' +
173
185
  prompt);
174
186
  }
175
187
  export async function runJob(job, cfg, api, viewer, opts) {
188
+ api = blankingApi(api);
176
189
  const now = opts?.now ?? (() => new Date());
177
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 } : {});
178
214
  let secretScan;
179
215
  let usage;
180
216
  let readHead;
181
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
+ };
182
251
  const report = async (reported) => {
183
- 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);
184
260
  if (usage && !payload.usage)
185
261
  payload = { ...payload, usage };
186
262
  if (readHead && !payload.readHead)
@@ -231,6 +307,15 @@ export async function runJob(job, cfg, api, viewer, opts) {
231
307
  const toolsOnly = !job.repo;
232
308
  const continuesBranch = !toolsOnly && job.continuesBranch === true;
233
309
  const review = !toolsOnly && job.review === true;
310
+ const askFirst = !toolsOnly && !review && job.askFirst === true;
311
+ const step = askFirst ? (job.askFirstStep ?? null) : null;
312
+ const revising = step?.kind === 'revise' ? step : null;
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);
234
319
  const adapter = getAdapter(job.engine ?? cfg.engine);
235
320
  const spent = opts?.limits?.isLimited(adapter.id) ?? null;
236
321
  if (spent) {
@@ -255,6 +340,85 @@ export async function runJob(job, cfg, api, viewer, opts) {
255
340
  limit: { kind: 'machine', detail: unattended.detail },
256
341
  });
257
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
+ };
258
422
  let repoPath = toolsOnly ? null : resolveRepoPath(job.repo, cfg);
259
423
  if (!repoPath && job.repo) {
260
424
  const cred = await api.gitCredential(job.runId);
@@ -294,16 +458,44 @@ export async function runJob(job, cfg, api, viewer, opts) {
294
458
  : budget
295
459
  : (cfg.jobTimeoutMinutes ?? 20);
296
460
  const timeoutMs = limitMinutes * 60_000;
297
- const cutMatch = cutFor(rdir, {
298
- workItemId: job.workItemId,
299
- engine: adapter.id,
300
- repo: job.repo ?? null,
301
- branch: toolsOnly ? '' : branch,
302
- review,
303
- toolsOnly,
304
- }, now().getTime());
461
+ const cutMatch = step || parkStep
462
+ ? null
463
+ : cutFor(rdir, {
464
+ workItemId: job.workItemId,
465
+ engine: adapter.id,
466
+ repo: job.repo ?? null,
467
+ branch: toolsOnly ? '' : branch,
468
+ review,
469
+ toolsOnly,
470
+ }, now().getTime());
305
471
  let resumeCut = null;
306
- if (cutMatch && 'resume' in cutMatch && adapter.resumesSessions) {
472
+ if (revising && kept) {
473
+ resumeCut = {
474
+ workItemId: kept.workItemId,
475
+ runId: kept.runId,
476
+ engine: kept.engine,
477
+ sessionId: kept.sessionId ?? '',
478
+ repo: kept.repo,
479
+ branch: kept.branch,
480
+ base: kept.base,
481
+ worktree: kept.worktree,
482
+ repoPath: kept.repoPath,
483
+ ...(kept.readHead ? { readHead: kept.readHead } : {}),
484
+ resetsAt: null,
485
+ cutAt: kept.keptAt,
486
+ keepUntil: kept.keepUntil,
487
+ promptHash: '',
488
+ review: false,
489
+ toolsOnly: false,
490
+ continuesBranch: kept.continuesBranch,
491
+ ...(kept.sessionReport ? { usage: kept.sessionReport } : {}),
492
+ ...(kept.writtenSkills ? { writtenSkills: kept.writtenSkills } : {}),
493
+ };
494
+ }
495
+ else if (parkStep && parkKept) {
496
+ resumeCut = resumeFromParked(parkKept, promptHash(job.prompt));
497
+ }
498
+ else if (cutMatch && 'resume' in cutMatch && adapter.resumesSessions) {
307
499
  resumeCut = cutMatch.resume;
308
500
  }
309
501
  else if (cutMatch) {
@@ -335,865 +527,1186 @@ export async function runJob(job, cfg, api, viewer, opts) {
335
527
  title: job.title ?? job.externalId ?? undefined,
336
528
  repo: job.repo ?? undefined,
337
529
  });
338
- let base = '';
339
- try {
340
- if (toolsOnly && resumeCut) {
341
- worktree = resumeCut.worktree;
342
- writtenSkills = { written: [], pathspecs: [] };
343
- log(`continuing the session a plan limit cut for this task, in ${worktree}`);
344
- }
345
- else if (toolsOnly) {
346
- worktree = mkdtempSync(join(tmpdir(), 'firefunc-tools-'));
347
- updateHeld(rdir, job.runId, { scratch: [worktree] });
348
- writeSkills(worktree, job.skills, log);
349
- await exec('git', ['-C', worktree, 'init', '--quiet']);
350
- log(`no repository for ${job.runId} — the agent works through its tools in ${worktree}`);
351
- }
352
- else {
353
- await api.event(job.runId, 'cloning', { repo: job.repo, branch });
354
- const checkout = repoPath;
355
- const prep = await gitMutex.run(checkout, async () => {
356
- await exec('git', ['-C', checkout, 'fetch', 'origin', '--quiet'], { timeoutMs: 120_000 });
357
- if (resumeCut) {
358
- const known = await exec('git', ['-C', resumeCut.worktree, 'rev-parse', '--git-dir']);
359
- if (known.code === 0) {
360
- return {
361
- base: resumeCut.base,
362
- wt: resumeCut.worktree,
363
- add: { code: 0, stdout: '', stderr: '' },
364
- branchMissing: false,
365
- startPoint: '',
366
- };
367
- }
368
- log(`the worktree the plan limit's cut session kept is no longer a worktree of ${job.repo} — starting over`);
369
- dropCut(rdir, resumeCut.workItemId);
370
- try {
371
- rmSync(resumeCut.worktree, { recursive: true, force: true });
372
- }
373
- catch {
374
- }
375
- resumeCut = null;
376
- }
377
- let b = job.baseBranch ?? cfg.baseBranch ?? '';
378
- if (!b) {
379
- const head = await execOut('git', ['-C', checkout, 'symbolic-ref', 'refs/remotes/origin/HEAD'], checkout);
380
- b = head ? head.replace('refs/remotes/origin/', '') : 'main';
381
- }
382
- await exec('git', ['-C', checkout, 'worktree', 'prune']).catch(() => { });
383
- let startPoint = `origin/${b}`;
384
- if (continuesBranch) {
385
- const has = await exec('git', [
386
- '-C',
387
- checkout,
388
- 'rev-parse',
389
- '--verify',
390
- '--quiet',
391
- `refs/remotes/origin/${branch}`,
392
- ]);
393
- if (has.code !== 0) {
394
- return { base: b, wt: '', add: has, branchMissing: true, startPoint };
395
- }
396
- startPoint = `origin/${branch}`;
397
- }
398
- const wt = mkdtempSync(join(tmpdir(), 'firefunc-'));
399
- const add = () => exec('git', ['-C', checkout, 'worktree', 'add', '--force', '-B', branch, wt, startPoint], {
400
- timeoutMs: 120_000,
401
- });
402
- let result = await add();
403
- const holder = result.code !== 0 ? staleHolder(result.stderr) : null;
404
- if (holder) {
405
- const live = new Set([...liveWorktrees(rdir)].map(canonicalPath));
406
- if (!live.has(canonicalPath(holder))) {
407
- log(`a worktree a stopped runner left holds ${branch} (${holder}) — removing it and trying again`);
408
- await removeRunnerWorktree(checkout, holder, log);
409
- result = await add();
410
- }
411
- }
412
- return { base: b, wt, add: result, branchMissing: false, startPoint };
413
- });
414
- base = prep.base;
415
- if (prep.branchMissing) {
416
- return fail(`The pull request's branch "${branch}" is not in ${job.repo}, so it cannot be continued from this checkout — a pull request from a fork keeps its branch in the fork, and a merged or closed pull request's branch may have been deleted. Nothing was changed. ` +
417
- `Fix: for a fork, ask for the change on an issue or on a pull request from a branch of ${job.repo}; for a merged pull request, start a new task.`);
530
+ const ship = async (s) => {
531
+ const { worktree, branch, base, title, kind, engineName, summary } = s;
532
+ const agentText = s.agentText ?? null;
533
+ const scanIn = worktree;
534
+ const tipOf = async () => {
535
+ const r = await exec('git', ['-C', scanIn, 'rev-parse', '--verify', '--quiet', `refs/heads/${branch}^{commit}`], { timeoutMs: 30_000 }).catch(() => null);
536
+ const sha = r?.code === 0 ? r.stdout.trim() : '';
537
+ return FULL_SHA.test(sha) ? sha : null;
538
+ };
539
+ const scannedTip = await tipOf();
540
+ const readChange = (args, env) => exec('git', ['-C', scanIn, ...args], { timeoutMs: 120_000, env }).catch((e) => ({
541
+ code: 1,
542
+ stdout: '',
543
+ stderr: e.message,
544
+ }));
545
+ const scanSince = async (from) => {
546
+ const reads = changeReads(from, branch, scannedTip ?? undefined);
547
+ const whole = await readChange(reads.whole, reads.env);
548
+ const commits = whole.code === 0 ? await readChange(reads.commits, reads.env) : whole;
549
+ if (whole.code !== 0 || commits.code !== 0) {
550
+ const failed = whole.code !== 0 ? whole : commits;
551
+ return {
552
+ hits: null,
553
+ why: `git exit ${failed.code}: ${failed.stderr.trim().slice(0, 200)}`,
554
+ };
418
555
  }
419
- worktree = prep.wt;
420
- updateHeld(rdir, job.runId, { worktree, repoPath: checkout });
421
- if (resumeCut) {
422
- readHead = resumeCut.readHead;
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
+ : [];
565
+ return {
566
+ hits: uniqueHits([
567
+ ...scanAddedLines(whole.stdout),
568
+ ...scanAddedLines(commits.stdout),
569
+ ...inMessages,
570
+ ]),
571
+ };
572
+ };
573
+ const found = (hits, n = 5) => hits
574
+ .slice(0, n)
575
+ .map((h) => `${h.kind} at ${h.path}:${h.line}`)
576
+ .join(', ');
577
+ const asReported = (hits) => ({
578
+ scanned: true,
579
+ hits: hits.slice(0, 100).map((h) => ({ ...h, path: h.path.slice(0, 512) })),
580
+ });
581
+ let scanCoversPullRequest = false;
582
+ const own = await scanSince(continuesBranch ? `origin/${branch}` : `origin/${base}`);
583
+ if (own.hits) {
584
+ const added = hardFirst(own.hits);
585
+ secretScan = asReported(added);
586
+ if (added.some(refusesPush)) {
587
+ log(`secret scan for ${job.runId}: ${added.length} finding(s) — ${found(added)} — refusing to push`);
588
+ return fail(secretRefusal(added, branch));
423
589
  }
424
- else if (prep.add.code === 0 && prep.startPoint) {
425
- const sha = await execOut('git', [
426
- '-C',
427
- worktree,
428
- 'rev-parse',
429
- '--verify',
430
- '--quiet',
431
- `${prep.startPoint}^{commit}`,
432
- ]).catch(() => '');
433
- if (FULL_SHA.test(sha))
434
- readHead = sha;
590
+ if (added.length > 0) {
591
+ log(`secret scan for ${job.runId}: ${added.length} looser match(es) — ${found(added)} — pushing; ` +
592
+ 'the result reports them, and FireFunc does not auto-merge a pull request with a finding');
435
593
  }
436
- if (prep.add.code !== 0) {
437
- log(`git worktree add output for ${job.runId} (kept on this machine):\n${prep.add.stderr}`);
438
- const said = pushRefusal(prep.add.stderr);
439
- return fail(said
440
- ? `git worktree add failed: ${oneLine(said, 400)}`
441
- : `git worktree add failed (exit ${prep.add.code}); its output stayed on the machine — the runner’s log shows it.`);
594
+ else {
595
+ log(`secret scan for ${job.runId}: nothing found in what this push adds`);
442
596
  }
443
- }
444
- const attachPaths = [];
445
- if (job.attachments?.length) {
446
- attachDir = mkdtempSync(join(tmpdir(), 'firefunc-attach-'));
447
- updateHeld(rdir, job.runId, { scratch: [attachDir] });
448
- mkdirSync(attachDir, { recursive: true });
449
- job.attachments.forEach((att, i) => {
450
- if (!att?.dataB64)
451
- return;
452
- try {
453
- const p = join(attachDir, safeAttachmentName(att.filename, i, att.contentType));
454
- writeFileSync(p, Buffer.from(att.dataB64, 'base64'));
455
- attachPaths.push(p);
597
+ if (!continuesBranch) {
598
+ scanCoversPullRequest = true;
599
+ }
600
+ else {
601
+ const whole = await scanSince(`origin/${base}`);
602
+ if (whole.hits) {
603
+ const all = hardFirst(uniqueHits([...added, ...whole.hits]));
604
+ secretScan = asReported(all);
605
+ scanCoversPullRequest = true;
606
+ const before = all.length - added.length;
607
+ if (before > 0) {
608
+ log(`secret scan for ${job.runId}: the pull request already holds ${before} finding(s) from commits pushed before this run — ` +
609
+ 'they are on GitHub already, so the push goes on; the result reports them, and FireFunc does not auto-merge the pull request');
610
+ }
456
611
  }
457
- catch {
612
+ else {
613
+ log(`could not read the pull request from origin/${base} to scan it whole (${whole.why}) — ` +
614
+ 'the result reports what this run adds, without the commit it covers, so FireFunc does not auto-merge it');
458
615
  }
459
- });
460
- if (attachPaths.length)
461
- log(`wrote ${attachPaths.length} attachment(s) for ${job.runId}`);
616
+ }
462
617
  }
463
- const attachNote = attachPaths.length
464
- ? `The reporter attached ${attachPaths.length} file(s). Read EACH one with the Read tool before forming your fix — they may be screenshots, designs, logs, stack traces, or repro data that show the bug or the intended result:\n${attachPaths
465
- .map((p) => `- ${p}`)
466
- .join('\n')}\n\n`
467
- : '';
468
- const runEnv = {
469
- ...cfg.claudeEnv,
470
- ...(cfg.claudeCodeOAuthToken ? { CLAUDE_CODE_OAUTH_TOKEN: cfg.claudeCodeOAuthToken } : {}),
471
- ...(opts?.devServerPort ? { PORT: String(opts.devServerPort) } : {}),
472
- };
473
- if (opts?.devServerPort && cfg.backgroundCommands?.length) {
474
- log(`session dev-server PORT=${opts.devServerPort} (parallel-safe)`);
618
+ else {
619
+ log(`could not read the change to scan it for secrets (${own.why}) — pushing without a scan, and the result reports none`);
475
620
  }
476
- if (cfg.envFile && !toolsOnly) {
477
- try {
478
- const gitDir = (await execOut('git', ['-C', worktree, 'rev-parse', '--git-common-dir'])).trim();
479
- if (gitDir) {
480
- const abs = gitDir.startsWith('/') ? gitDir : join(worktree, gitDir);
481
- mkdirSync(join(abs, 'info'), { recursive: true });
482
- appendFileSync(join(abs, 'info', 'exclude'), '\n# FireFunc: never commit the injected env file\n.env\n');
483
- }
621
+ if (s.keep) {
622
+ const changes = await changesOf(scanIn, continuesBranch ? `origin/${branch}` : `origin/${base}`, branch);
623
+ if (!changes || !scannedTip) {
624
+ return fail(`The change was made and committed on ${branch}, but the runner could not read what it holds to ask a person about it, so it was not kept. Nothing was pushed. Re-run the task.`);
484
625
  }
485
- catch (e) {
486
- log(`could not write git exclude for .env: ${e.message}`);
626
+ const at = now();
627
+ const saved = saveKept(rdir, {
628
+ runId: job.runId,
629
+ workItemId: job.workItemId,
630
+ engine: adapter.id,
631
+ sessionId: s.keep.sessionId,
632
+ repo: job.repo ?? '',
633
+ branch,
634
+ base,
635
+ worktree,
636
+ repoPath: repoPath ?? null,
637
+ continuesBranch,
638
+ ...(readHead ? { readHead } : {}),
639
+ head: scannedTip,
640
+ round: s.keep.round,
641
+ title,
642
+ kind,
643
+ summary: summary ? reportedSummary(summary) : null,
644
+ keptAt: at.toISOString(),
645
+ keepUntil: keepUntilFrom(at.getTime()),
646
+ writtenSkills,
647
+ ...(usage ? { attemptUsage: usage } : {}),
648
+ ...(s.keep.sessionReport ? { sessionReport: s.keep.sessionReport } : {}),
649
+ activitySeq: activitySeen,
650
+ });
651
+ if (!saved) {
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.`);
653
+ }
654
+ keepWorktree = true;
655
+ log(`Ask first: ${job.runId}'s change is committed on ${branch} and kept here — ${changes.filesChanged} file(s), +${changes.added} −${changes.removed}; nothing is pushed until a person approves it`);
656
+ return report({
657
+ status: 'awaiting_approval',
658
+ changes,
659
+ head: scannedTip,
660
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
661
+ });
662
+ }
663
+ await api.event(job.runId, 'pushing', { branch });
664
+ const gitCred = job.repo ? await api.gitCredential(job.runId) : null;
665
+ if (gitCred)
666
+ log(`using a FireFunc-issued git credential for ${gitCred.repo}`);
667
+ const pushedCommits = await execOut('git', [
668
+ '-C',
669
+ worktree,
670
+ '--no-replace-objects',
671
+ '-c',
672
+ 'core.quotepath=off',
673
+ 'log',
674
+ '--name-only',
675
+ '--format=',
676
+ '--no-renames',
677
+ '--diff-filter=d',
678
+ `${continuesBranch ? `origin/${branch}` : `origin/${base}`}..${scannedTip ?? `refs/heads/${branch}`}`,
679
+ ]);
680
+ const staged = [
681
+ await execOut('git', [
682
+ '-C',
683
+ worktree,
684
+ 'show',
685
+ '--name-only',
686
+ '--format=',
687
+ '--diff-filter=d',
688
+ 'HEAD',
689
+ ]),
690
+ pushedCommits,
691
+ ].join('\n');
692
+ const mcpStaged = mcp?.configPath
693
+ ? relative(worktree, mcp.configPath).split(sep).join('/')
694
+ : null;
695
+ const stagedPaths = staged
696
+ .split('\n')
697
+ .map((l) => l.trim())
698
+ .filter(Boolean);
699
+ const leaked = stagedPaths.filter((l) => l === '.env' || l.endsWith('/.env') || (mcpStaged !== null && l === mcpStaged));
700
+ if (leaked.length > 0) {
701
+ return fail(`refusing to push: the commit contains ${leaked.join(', ')}, which can hold live credentials. ` +
702
+ `This is a FireFunc bug — please report it. Nothing was pushed.`);
703
+ }
704
+ const skillLeaked = writtenSkillPaths(stagedPaths, writtenSkills);
705
+ if (skillLeaked.length > 0) {
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'} ` +
708
+ `FireFunc writes into the checkout for this run only and never commits. Nothing was ` +
709
+ `pushed. Fix: tell the agent not to stage or commit anything under ` +
710
+ `${skillLeaked[0].split('/').slice(0, -1).join('/')} (check its instruction and ` +
711
+ `its skills for "git add -f" or "commit everything"), then re-run the task.`);
712
+ }
713
+ const pushFrom = worktree;
714
+ const pushOnce = async () => gitCred
715
+ ? pushBranch(pushFrom, branch, gitCred.repo, gitCred, { force: !continuesBranch })
716
+ : exec('git', [
717
+ '-C',
718
+ pushFrom,
719
+ 'push',
720
+ ...pushFlags(!continuesBranch),
721
+ 'origin',
722
+ `${branch}:${branch}`,
723
+ ], {
724
+ timeoutMs: 120_000,
725
+ });
726
+ let push = await pushOnce();
727
+ for (let tries = 0; tries < 3 && push.code !== 0 && isNetworkError(push.stderr); tries++) {
728
+ log(`push failed because the network seems to be away — waiting for it (try ${tries + 1} of 3)`);
729
+ const back = await waitForNetwork({ probe: () => api.probe(), maxWaitMs: 10 * 60_000, log });
730
+ if (!back)
731
+ break;
732
+ push = await pushOnce();
733
+ }
734
+ if (push.code !== 0) {
735
+ const said = redact(push.stderr, gitCred?.token);
736
+ log(`git push output for ${job.runId} (kept on this machine):\n${said.slice(-4000)}`);
737
+ const refused = pushRefusal(said);
738
+ return fail(refused
739
+ ? `git push failed: ${oneLine(refused, 400)}`
740
+ : `git push failed (exit ${push.code}); its output stayed on the machine — the runner’s log shows it.`);
741
+ }
742
+ await trail?.pushed({ branch });
743
+ if (secretScan && scannedTip && scanCoversPullRequest) {
744
+ const pushedTip = await tipOf();
745
+ if (pushedTip === scannedTip)
746
+ secretScan = { ...secretScan, head: scannedTip };
747
+ else
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`);
749
+ }
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 });
753
+ if (gitCred) {
754
+ const pr = await withNetworkRetry(() => openDraftPr({
755
+ repo: gitCred.repo,
756
+ head: branch,
757
+ base,
758
+ title,
759
+ body,
760
+ cred: gitCred,
761
+ update: !!agentText,
762
+ }), {
763
+ label: `pull request for ${job.runId}`,
764
+ maxWaitMs: 10 * 60_000,
765
+ probe: () => api.probe(),
766
+ log,
767
+ });
768
+ if (!('error' in pr)) {
769
+ await api.event(job.runId, 'pr_opened', { url: pr.url, branch });
770
+ log(`opened PR for ${job.runId}: ${pr.url}`);
771
+ return report({
772
+ status: 'pr_opened',
773
+ pr: {
774
+ repo: job.repo ?? undefined,
775
+ number: pr.number,
776
+ url: pr.url,
777
+ branch,
778
+ summary: title,
779
+ },
780
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
781
+ });
782
+ }
783
+ const why = redact(pr.error, gitCred.token);
784
+ if (!(await hasGh(worktree)))
785
+ return fail(why);
786
+ log(`could not open the PR as FireFunc (${why}); falling back to gh`);
787
+ }
788
+ const createCwd = worktree;
789
+ const create = await withNetworkRetry(async () => {
790
+ const r = await exec('gh', [
791
+ 'pr',
792
+ 'create',
793
+ '--draft',
794
+ '--head',
795
+ branch,
796
+ '--base',
797
+ base,
798
+ '--title',
799
+ title,
800
+ '--body',
801
+ body,
802
+ ], { cwd: createCwd, timeoutMs: 60_000 });
803
+ if (r.code !== 0 && networkFailureHint(`${r.stdout}\n${r.stderr}`)) {
804
+ throw new NetworkGoneError(r.stderr.trim() || 'gh pr create failed');
487
805
  }
806
+ return r;
807
+ }, {
808
+ label: `pull request for ${job.runId} (gh)`,
809
+ maxWaitMs: 10 * 60_000,
810
+ probe: () => api.probe(),
811
+ log,
812
+ }).catch((err) => ({
813
+ code: 1,
814
+ stdout: '',
815
+ stderr: err instanceof Error ? err.message : String(err),
816
+ }));
817
+ const wt = worktree;
818
+ const viewPr = async (b) => {
819
+ const out = await execOut('gh', ['pr', 'view', b, '--json', 'url,number'], wt);
488
820
  try {
489
- copyFileSync(cfg.envFile, join(worktree, '.env'));
490
- log(`copied ${cfg.envFile} → worktree/.env (excluded from commits)`);
821
+ const j = JSON.parse(out);
822
+ if (typeof j.url === 'string' && /\/pull\/\d+/.test(j.url) && Number.isFinite(j.number)) {
823
+ return { url: j.url, number: Number(j.number) };
824
+ }
491
825
  }
492
- catch (e) {
493
- log(`envFile copy failed (${cfg.envFile}): ${e.message}`);
826
+ catch {
494
827
  }
828
+ return null;
829
+ };
830
+ const headBranch = (await execOut('git', ['rev-parse', '--abbrev-ref', 'HEAD'], wt)) || branch;
831
+ let resolved = null;
832
+ for (const b of [...new Set([headBranch, branch].filter(Boolean))]) {
833
+ resolved = await viewPr(b);
834
+ if (resolved)
835
+ break;
495
836
  }
496
- if (resumeCut) {
497
- writtenSkills = resumeCut.writtenSkills ?? { written: [], pathspecs: [] };
837
+ if (!resolved) {
838
+ const m = `${create.stdout}\n${create.stderr}`.match(/https?:\/\/\S*\/pull\/(\d+)/);
839
+ if (m)
840
+ resolved = { url: m[0], number: Number(m[1]) };
498
841
  }
499
- else if (!toolsOnly) {
500
- writtenSkills = writeSkills(worktree, job.skills, log);
842
+ if (!resolved) {
843
+ const why = (create.stderr || create.stdout).replace(/\s+/g, ' ').trim().slice(0, 400);
844
+ return fail(`The branch ${branch} was pushed, but the pull request could not be created${why ? `: ${why}` : ''}. ` +
845
+ `Open it from that branch on GitHub (FireFunc will link it to this task), or re-run.`);
501
846
  }
502
- const heavyLock = !toolsOnly && job.repo && cfg.heavyLock !== false ? heavyLockDir(rdir, job.repo) : null;
503
- const heavyHelper = heavyLock ? ensureHeavyScript(rdir) : null;
504
- const heavily = (fn) => heavyLock
505
- ? withHeavyLock(heavyLock, fn, {
506
- label: `setup of ${job.runId}`,
507
- maxWaitMs: (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000,
508
- onWait: (holder) => log(`another heavy command is running in ${job.repo}${holder ? ` (pid ${holder})` : ''} — setup waits for it`),
509
- })
510
- : fn();
511
- const setupMs = (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000;
512
- if (toolsOnly) {
847
+ const url = resolved.url;
848
+ const number = resolved.number;
849
+ await api.event(job.runId, 'pr_opened', { url, branch });
850
+ log(`opened PR for ${job.runId}: ${url}`);
851
+ return report({
852
+ status: 'pr_opened',
853
+ pr: { repo: job.repo ?? undefined, number, url: url || undefined, branch, summary: title },
854
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
855
+ });
856
+ };
857
+ let base = '';
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.');
513
861
  }
514
- else if (cfg.setupCommands?.length) {
515
- for (const cmd of cfg.setupCommands) {
516
- log(`setup: ${cmd}`);
517
- const setupCwd = worktree;
518
- const r = await heavily(() => exec(cmd, [], {
519
- cwd: setupCwd,
520
- env: runEnv,
521
- timeoutMs: setupMs,
522
- shell: true,
523
- }));
524
- if (r.code !== 0) {
525
- log(`setup output for ${job.runId} (kept on this machine):\n${r.stderr.slice(-4000)}` +
526
- `${r.stdout.trim() ? `\n--- stdout ---\n${r.stdout.slice(-2000)}` : ''}`);
527
- const checkout = worktree;
528
- const fold = (text) => foldHome(stripWorktree(text, checkout), homedir());
529
- const why = setupReason(fold(r.stderr), fold(r.stdout));
530
- const said = why ? oneLine(why, 200).replace(/[.\s]+$/, '') : '';
531
- return fail(`Setup command failed (exit ${r.code}): ${setupCommandName(cmd)}` +
532
- `${said ? ` — ${said}` : ''}. ` +
533
- 'Its output stayed on the machine — the runner’s log shows it; fix the command or setupCommands in the runner config, then re-run.');
534
- }
535
- }
862
+ if (step && (!kept || !existsSync(kept.worktree))) {
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.');
536
864
  }
537
- else if (resumeCut) {
865
+ if (step?.kind === 'publish' && kept) {
866
+ worktree = kept.worktree;
867
+ base = kept.base;
868
+ writtenSkills = kept.writtenSkills ?? { written: [], pathspecs: [] };
869
+ if (kept.readHead)
870
+ readHead = kept.readHead;
871
+ const tip = await execOut('git', [
872
+ '-C',
873
+ kept.worktree,
874
+ 'rev-parse',
875
+ '--verify',
876
+ '--quiet',
877
+ `refs/heads/${kept.branch}^{commit}`,
878
+ ]).catch(() => '');
879
+ if (tip.trim() !== kept.head) {
880
+ return fail(`The change kept for approval moved after it was approved: ${kept.branch} is at ${tip.trim().slice(0, 12) || 'nothing'}, not the approved ${kept.head.slice(0, 12)}. Nothing was pushed. Re-run the task.`);
881
+ }
882
+ log(`approved: pushing the change kept for ${job.runId} (${kept.branch}) and opening its pull request`);
883
+ return await ship({
884
+ worktree: kept.worktree,
885
+ branch: kept.branch,
886
+ base: kept.base,
887
+ title: kept.title,
888
+ kind: kept.kind,
889
+ engineName: adapter.displayName,
890
+ summary: kept.summary,
891
+ keep: null,
892
+ });
538
893
  }
539
- else if (cfg.autoInstall ?? true) {
540
- const installIn = worktree;
541
- await heavily(() => autoInstallDeps(installIn, runEnv, setupMs));
894
+ if (toolsOnly && resumeCut) {
895
+ worktree = resumeCut.worktree;
896
+ writtenSkills = { written: [], pathspecs: [] };
897
+ log(`continuing the session a plan limit cut for this task, in ${worktree}`);
542
898
  }
543
- for (const cmd of toolsOnly ? [] : (cfg.backgroundCommands ?? [])) {
544
- log(`starting background: ${cmd}`);
545
- bgProcs.push(spawnBackground(cmd, { cwd: worktree, env: runEnv }));
899
+ else if (toolsOnly) {
900
+ worktree = mkdtempSync(join(tmpdir(), 'firefunc-tools-'));
901
+ updateHeld(rdir, job.runId, { scratch: [worktree] });
902
+ writeSkills(worktree, job.skills, log);
903
+ const refs = await writeRefs(worktree);
904
+ if (refs && 'failure' in refs)
905
+ return fail(refs.failure);
906
+ await exec('git', ['-C', worktree, 'init', '--quiet']);
907
+ log(`no repository for ${job.runId} — the agent works through its tools in ${worktree}`);
546
908
  }
547
- await api.event(job.runId, 'fixing', { title: job.title });
548
- const mode = job.permissionMode ?? cfg.permissionMode ?? 'bypassPermissions';
549
- const model = job.model ?? cfg.model ?? null;
550
- const effort = job.effort ?? cfg.effort ?? null;
551
- const ultracode = effort === 'ultracode';
552
- 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';
553
- const rules = engineRules({ minutes: limitMinutes, heavy: heavyHelper !== null });
554
- const prompt = rules + observeNote + attachNote + (ultracode ? `ultracode\n\n${job.prompt}` : job.prompt);
555
- const tools = cfg.allowedTools ??
556
- 'Read Edit Write Bash Glob Grep WebFetch WebSearch Task TodoWrite NotebookEdit';
557
- const isWin = process.platform === 'win32';
558
- if (job.mcpConfig != null) {
559
- const format = mcpFormatForEngine(adapter.id);
560
- if (format) {
561
- mcp = await prepareMcp({
562
- raw: job.mcpConfig,
563
- worktree,
564
- format,
565
- runId: job.runId,
566
- api,
567
- log,
568
- relay: cfg.mcpRelay !== false,
569
- });
570
- }
571
- log(mcp ? `mcp: ${mcp.logLine}` : 'mcp: no server was injected for this run');
572
- }
573
- const ctx = {
574
- prompt,
575
- model,
576
- effort,
577
- ultracode,
578
- permissionMode: mode,
579
- allowedTools: tools,
580
- maxBudgetUsd: cfg.maxBudgetUsd,
581
- attachDir: attachDir ?? undefined,
582
- attachPaths,
583
- isWin,
584
- runEnv: {
585
- ...stripForeignEngineCreds(runEnv, adapter.id),
586
- ...(heavyHelper && heavyLock
587
- ? { FIREFUNC_HEAVY: heavyHelper, FIREFUNC_HEAVY_LOCK: heavyLock }
588
- : {}),
589
- },
590
- cfg,
591
- ...(mcp ? { mcp } : {}),
592
- };
593
- const firstCtx = resumeCut
594
- ? {
595
- ...ctx,
596
- resumeSessionId: resumeCut.sessionId,
597
- prompt: resumeAfterResetBrief(prompt, promptHash(job.prompt) !== resumeCut.promptHash),
598
- }
599
- : ctx;
600
- let inv;
601
- try {
602
- inv = adapter.buildInvocation(firstCtx);
603
- }
604
- catch (e) {
605
- return fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
606
- }
607
- const engineName = adapter.displayName;
608
- log(`running ${inv.bin} (${engineName}) on ${toolsOnly ? 'no repository — tools only' : `${job.repo} (${branch})`} — model=${model ?? 'default'} effort=${effort ?? 'default'} mode=${mode}`);
609
- log(`${engineName} auth: ${inv.authLogLine}`);
610
- const printer = cfg.quiet ? undefined : adapter.makeStreamPrinter();
611
- const activity = createActivityReporter({
612
- worktree,
613
- post: (steps) => api.activity(job.runId, steps),
614
- writeTools: new Set(mcp?.writeToolNames ?? []),
615
- });
616
- const activityParser = makeStreamJsonParser(activity.push, { toolResults: true });
617
- const onStdout = (chunk) => {
618
- printer?.(chunk);
619
- viewer?.push(job.runId, chunk);
620
- activityParser(chunk);
621
- };
622
- if (printer) {
623
- log(`── live ${engineName} session (shown here only — never sent to FireFunc) ──`);
624
- }
625
- const heartbeat = setInterval(() => void api.event(job.runId, 'heartbeat'), 5 * 60_000);
626
- const engineCwd = worktree;
627
- let engineMs = 0;
628
- const runEngine = async (limitMs = timeoutMs) => {
629
- let group = 0;
630
- const started = Date.now();
631
- try {
632
- return await exec(inv.bin, inv.args, {
633
- cwd: engineCwd,
634
- timeoutMs: limitMs,
635
- env: inv.env,
636
- input: inv.stdinInput,
637
- shell: inv.shell,
638
- onStdout,
639
- ownGroup: true,
640
- onSpawn: (pid) => {
641
- group = pid;
642
- engineGroups.push({ pgid: pid, startedAt: started });
643
- trackEngineGroup(pid);
644
- updateHeld(rdir, job.runId, { engineGroup: pid, engineStartedAt: started });
645
- },
909
+ else {
910
+ await api.event(job.runId, 'cloning', { repo: job.repo, branch });
911
+ const checkout = repoPath;
912
+ const prep = await gitMutex.run(checkout, async () => {
913
+ await exec('git', ['-C', checkout, 'fetch', 'origin', '--quiet'], { timeoutMs: 120_000 });
914
+ if (resumeCut) {
915
+ const known = await exec('git', ['-C', resumeCut.worktree, 'rev-parse', '--git-dir']);
916
+ if (known.code === 0) {
917
+ return {
918
+ base: resumeCut.base,
919
+ wt: resumeCut.worktree,
920
+ add: { code: 0, stdout: '', stderr: '' },
921
+ branchMissing: false,
922
+ startPoint: '',
923
+ };
924
+ }
925
+ log(`the worktree the plan limit's cut session kept is no longer a worktree of ${job.repo} — starting over`);
926
+ dropCut(rdir, resumeCut.workItemId);
927
+ try {
928
+ rmSync(resumeCut.worktree, { recursive: true, force: true });
929
+ }
930
+ catch {
931
+ }
932
+ resumeCut = null;
933
+ }
934
+ let b = job.baseBranch ?? cfg.baseBranch ?? '';
935
+ if (!b) {
936
+ const head = await execOut('git', ['-C', checkout, 'symbolic-ref', 'refs/remotes/origin/HEAD'], checkout);
937
+ b = head ? head.replace('refs/remotes/origin/', '') : 'main';
938
+ }
939
+ await exec('git', ['-C', checkout, 'worktree', 'prune']).catch(() => { });
940
+ let startPoint = `origin/${b}`;
941
+ if (continuesBranch) {
942
+ const has = await exec('git', [
943
+ '-C',
944
+ checkout,
945
+ 'rev-parse',
946
+ '--verify',
947
+ '--quiet',
948
+ `refs/remotes/origin/${branch}`,
949
+ ]);
950
+ if (has.code !== 0) {
951
+ return { base: b, wt: '', add: has, branchMissing: true, startPoint };
952
+ }
953
+ startPoint = `origin/${branch}`;
954
+ }
955
+ const wt = mkdtempSync(join(tmpdir(), 'firefunc-'));
956
+ const add = () => exec('git', ['-C', checkout, 'worktree', 'add', '--force', '-B', branch, wt, startPoint], {
957
+ timeoutMs: 120_000,
646
958
  });
959
+ let result = await add();
960
+ const holder = result.code !== 0 ? staleHolder(result.stderr) : null;
961
+ if (holder) {
962
+ const live = new Set([...liveWorktrees(rdir)].map(canonicalPath));
963
+ if (!live.has(canonicalPath(holder))) {
964
+ log(`a worktree a stopped runner left holds ${branch} (${holder}) — removing it and trying again`);
965
+ await removeRunnerWorktree(checkout, holder, log);
966
+ result = await add();
967
+ }
968
+ }
969
+ return { base: b, wt, add: result, branchMissing: false, startPoint };
970
+ });
971
+ base = prep.base;
972
+ if (prep.branchMissing) {
973
+ return fail(`The pull request's branch "${branch}" is not in ${job.repo}, so it cannot be continued from this checkout — a pull request from a fork keeps its branch in the fork, and a merged or closed pull request's branch may have been deleted. Nothing was changed. ` +
974
+ `Fix: for a fork, ask for the change on an issue or on a pull request from a branch of ${job.repo}; for a merged pull request, start a new task.`);
647
975
  }
648
- finally {
649
- if (group)
650
- untrackEngineGroup(group);
651
- engineMs += Date.now() - started;
652
- }
653
- };
654
- const sessions = [];
655
- let lastReport = null;
656
- const meter = (stdout, continued = false) => {
657
- if (!adapter.meter)
658
- return;
659
- let u = null;
660
- try {
661
- u = adapter.meter(stdout);
662
- }
663
- catch {
664
- u = null;
976
+ worktree = prep.wt;
977
+ updateHeld(rdir, job.runId, { worktree, repoPath: checkout });
978
+ if (resumeCut) {
979
+ readHead = resumeCut.readHead;
665
980
  }
666
- lastReport = u;
667
- sessions.push({ usage: u, session: adapter.sessionId?.(stdout) ?? null, continued });
668
- };
669
- const limitOf = (stdout) => {
670
- try {
671
- return adapter.planLimit?.(stdout, now()) ?? null;
981
+ else if (prep.add.code === 0 && prep.startPoint) {
982
+ const sha = await execOut('git', [
983
+ '-C',
984
+ worktree,
985
+ 'rev-parse',
986
+ '--verify',
987
+ '--quiet',
988
+ `${prep.startPoint}^{commit}`,
989
+ ]).catch(() => '');
990
+ if (FULL_SHA.test(sha))
991
+ readHead = sha;
672
992
  }
673
- catch {
674
- return null;
993
+ if (prep.add.code !== 0) {
994
+ log(`git worktree add output for ${job.runId} (kept on this machine):\n${prep.add.stderr}`);
995
+ const said = pushRefusal(prep.add.stderr);
996
+ return fail(said
997
+ ? `git worktree add failed: ${oneLine(said, 400)}`
998
+ : `git worktree add failed (exit ${prep.add.code}); its output stayed on the machine — the runner’s log shows it.`);
675
999
  }
676
- };
677
- const refused = (stdout, stderr) => endedOnRefusal({
678
- ending: adapter.ending?.(stdout),
679
- summary: adapter.summarize(stdout),
680
- stderr,
681
- });
682
- let engineRun = await runEngine();
683
- meter(engineRun.stdout, false);
684
- if (resumeCut && engineRun.code !== 0 && !adapter.sessionId?.(engineRun.stdout)) {
685
- log(`${engineName} could not continue the session a plan limit cut — starting a new session in the same worktree`);
686
- inv = adapter.buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt, 'limit') });
687
- engineRun = await runEngine();
688
- meter(engineRun.stdout, false);
689
1000
  }
690
- for (let resumes = 0; resumes < 2 && engineRun.code !== 0; resumes++) {
691
- if (limitOf(engineRun.stdout))
692
- break;
693
- if (refused(engineRun.stdout, engineRun.stderr))
694
- break;
695
- if (endedBySignal(engineRun.code))
696
- break;
697
- const why = networkFailureHint(`${adapter.summarize(engineRun.stdout)}\n${engineRun.stderr.slice(-2000)}`);
698
- if (!why)
699
- break;
700
- log(`${engineName} stopped because ${why} — waiting for the network before resuming (resume ${resumes + 1} of 2)`);
701
- const back = await waitForNetwork({
702
- probe: () => api.probe(),
703
- maxWaitMs: 20 * 60_000,
704
- log,
1001
+ const attachPaths = [];
1002
+ if (job.attachments?.length) {
1003
+ attachDir = mkdtempSync(join(tmpdir(), 'firefunc-attach-'));
1004
+ updateHeld(rdir, job.runId, { scratch: [attachDir] });
1005
+ mkdirSync(attachDir, { recursive: true });
1006
+ job.attachments.forEach((att, i) => {
1007
+ if (!att?.dataB64)
1008
+ return;
1009
+ try {
1010
+ const p = join(attachDir, safeAttachmentName(att.filename, i, att.contentType));
1011
+ writeFileSync(p, Buffer.from(att.dataB64, 'base64'));
1012
+ attachPaths.push(p);
1013
+ }
1014
+ catch {
1015
+ }
705
1016
  });
706
- if (!back) {
707
- log('the network did not come back within 20 minutes — giving up on this attempt');
708
- break;
709
- }
710
- log(`the network is back — resuming ${engineName} in the same worktree`);
711
- inv = adapter.buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt) });
712
- engineRun = await runEngine();
713
- meter(engineRun.stdout, false);
1017
+ if (attachPaths.length)
1018
+ log(`wrote ${attachPaths.length} attachment(s) for ${job.runId}`);
714
1019
  }
715
- const openAtEnd = (stdout) => {
716
- try {
717
- return adapter.openCommandsAtEnd?.(stdout) ?? [];
718
- }
719
- catch {
720
- return [];
721
- }
1020
+ const attachNote = attachPaths.length
1021
+ ? `The reporter attached ${attachPaths.length} file(s). Read EACH one with the Read tool before forming your fix — they may be screenshots, designs, logs, stack traces, or repro data that show the bug or the intended result:\n${attachPaths
1022
+ .map((p) => `- ${p}`)
1023
+ .join('\n')}\n\n`
1024
+ : '';
1025
+ const runEnv = {
1026
+ ...cfg.claudeEnv,
1027
+ ...(cfg.claudeCodeOAuthToken ? { CLAUDE_CODE_OAUTH_TOKEN: cfg.claudeCodeOAuthToken } : {}),
1028
+ ...(opts?.devServerPort ? { PORT: String(opts.devServerPort) } : {}),
722
1029
  };
723
- const endedOnItsAnswer = (r) => r.code === 0 && !limitOf(r.stdout) && !refused(r.stdout, r.stderr);
724
- let open = endedOnItsAnswer(engineRun) ? openAtEnd(engineRun.stdout) : [];
725
- let promising = endedOnItsAnswer(engineRun) && promisesLaterCheck(adapter.summarize(engineRun.stdout));
726
- const toContinue = adapter.resumesSessions
727
- ? (adapter.sessionId?.(engineRun.stdout) ?? null)
728
- : null;
729
- const timeLeft = timeoutMs - engineMs;
730
- let continuedOnce = false;
731
- if ((open.length > 0 || promising) && toContinue && timeLeft < 60_000) {
732
- log(`${engineName}'s session ended before its result came, with under a minute of its time left — not continuing it`);
733
- }
734
- else if ((open.length > 0 || promising) && toContinue) {
735
- log(`${engineName}'s session ended ${open.length > 0 ? `while its own ${open.join(', ')} was still running` : 'on a promise to check a result later'} — continuing the same session once to get the result`);
736
- inv = adapter.buildInvocation({
737
- ...ctx,
738
- prompt: continueToFinishBrief(open),
739
- resumeSessionId: toContinue,
740
- });
741
- engineRun = await runEngine(timeLeft);
742
- meter(engineRun.stdout, true);
743
- continuedOnce = true;
744
- open = endedOnItsAnswer(engineRun) ? openAtEnd(engineRun.stdout) : [];
745
- promising =
746
- endedOnItsAnswer(engineRun) && promisesLaterCheck(adapter.summarize(engineRun.stdout));
747
- }
748
- openCommandAtEnd = open.length > 0;
749
- const unfinished = open.length > 0 || promising;
750
- clearInterval(heartbeat);
751
- usage =
752
- attemptUsage(sessions, resumeCut ? { session: resumeCut.sessionId, baseline: resumeCut.usage } : undefined) ?? undefined;
753
- if (usage)
754
- log(`${engineName} spent: ${describeUsage(usage)}`);
755
- viewer?.end(job.runId, engineRun.code === 0 ? 'done' : 'failed');
756
- if (printer)
757
- log(`── end ${engineName} session ──`);
758
- await activity.flush();
759
- log(`reported ${activity.sent} of ${activity.seen} step(s) to FireFunc — names and verbs only; the session stayed here`);
760
- mcp?.cleanup();
761
- const sessionLogPath = saveSessionLog(job.runId, engineRun.stdout, engineRun.stderr);
762
- const summary = adapter.summarize(engineRun.stdout);
763
- if (sessionLogPath)
764
- log(`${engineName} session saved → ${sessionLogPath}`);
765
- if (summary)
766
- log(`${engineName} said: ${summary.replace(/\s+/g, ' ').slice(0, 500)}`);
767
- if (engineRun.code === 124) {
768
- return fail(budget !== null && limitMinutes === budget
769
- ? `${engineName} timed out after ${limitMinutes} min — the agent's time budget.`
770
- : `${engineName} timed out after ${limitMinutes} min.`);
1030
+ if (opts?.devServerPort && cfg.backgroundCommands?.length) {
1031
+ log(`session dev-server PORT=${opts.devServerPort} (parallel-safe)`);
771
1032
  }
772
- const limit = limitOf(engineRun.stdout);
773
- if (limit) {
774
- opts?.limits?.set(adapter.id, limit);
775
- const cutSession = adapter.resumesSessions
776
- ? (adapter.sessionId?.(engineRun.stdout) ?? null)
777
- : null;
778
- let kept = false;
779
- if (cutSession && worktree) {
780
- const cutAt = now().getTime();
781
- kept = saveCut(rdir, {
782
- workItemId: job.workItemId,
783
- runId: job.runId,
784
- engine: adapter.id,
785
- sessionId: cutSession,
786
- repo: job.repo ?? null,
787
- branch: toolsOnly ? '' : branch,
788
- base,
789
- worktree,
790
- repoPath: toolsOnly ? null : repoPath,
791
- ...(readHead ? { readHead } : {}),
792
- resetsAt: limit.resetsAt,
793
- cutAt: new Date(cutAt).toISOString(),
794
- keepUntil: keepUntil(limit.resetsAt, cutAt),
795
- promptHash: promptHash(job.prompt),
796
- review,
797
- toolsOnly,
798
- continuesBranch,
799
- ...(lastReport ? { usage: lastReport } : {}),
800
- writtenSkills,
801
- });
1033
+ if (cfg.envFile && !toolsOnly) {
1034
+ try {
1035
+ const gitDir = (await execOut('git', ['-C', worktree, 'rev-parse', '--git-common-dir'])).trim();
1036
+ if (gitDir) {
1037
+ const abs = gitDir.startsWith('/') ? gitDir : join(worktree, gitDir);
1038
+ mkdirSync(join(abs, 'info'), { recursive: true });
1039
+ appendFileSync(join(abs, 'info', 'exclude'), '\n# FireFunc: never commit the injected env file\n.env\n');
1040
+ }
802
1041
  }
803
- keepWorktree = kept;
804
- log(`${engineName} was stopped by the plan's usage limit${limit.said ? ` ("${limit.said}")` : ''} — ` +
805
- (limit.resetsAt ? `it resets at ${limit.resetsAt}` : 'it did not say when it resets') +
806
- (kept ? '; the session and its worktree are kept to continue after the reset' : ''));
807
- return report({
808
- status: 'failed',
809
- error: limitSentence(engineName, limit, kept),
810
- limit: { kind: 'plan', resetsAt: limit.resetsAt },
811
- });
812
- }
813
- const declinedHint = () => {
814
- if (!refused(engineRun.stdout, engineRun.stderr))
815
- return null;
816
- log(`the model declined ${job.runId}: its safety system refused the session`);
817
- return { status: 'failed', error: modelDeclinedSentence(engineName) };
818
- };
819
- const scanHints = () => {
820
- const declined = declinedHint();
821
- if (declined)
822
- return declined;
823
- const authMsg = adapter.authFailureHint(`${summary}\n${engineRun.stderr}`);
824
- if (authMsg) {
825
- log(`auth/billing failure for ${job.runId}: ${authMsg}`);
826
- return { status: 'failed', error: authMsg };
1042
+ catch (e) {
1043
+ log(`could not write git exclude for .env: ${e.message}`);
1044
+ }
1045
+ try {
1046
+ copyFileSync(cfg.envFile, join(worktree, '.env'));
1047
+ log(`copied ${cfg.envFile} → worktree/.env (excluded from commits)`);
827
1048
  }
828
- const rateMsg = adapter.rateLimitHint(`${summary}\n${engineRun.stderr}`);
829
- if (rateMsg) {
830
- log(`rate limit for ${job.runId}: ${rateMsg}`);
831
- return { status: 'failed', error: rateMsg };
1049
+ catch (e) {
1050
+ log(`envFile copy failed (${cfg.envFile}): ${e.message}`);
832
1051
  }
833
- return null;
834
- };
835
- if (engineRun.code !== 0) {
836
- const signal = endedBySignal(engineRun.code);
837
- if (signal) {
838
- log(`${engineName} was ended by ${signal} (exit ${engineRun.code}) for ${job.runId}`);
839
- return fail(stoppedSentence(engineName, engineRun.code, signal, sessionLogPath ? basename(sessionLogPath) : null));
1052
+ }
1053
+ if (resumeCut) {
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.`);
840
1060
  }
841
- const hinted = scanHints();
842
- if (hinted)
843
- return report(hinted);
844
- const why = summary ? null : errorLine(engineRun.stderr);
845
- return fail(summary
846
- ? `${engineName} exited abnormally (code ${engineRun.code}). Last message: ${oneLine(shareable(summary), 500)}`
847
- : `${engineName} exited abnormally (code ${engineRun.code})${why ? `: ${oneLine(stripWorktree(why, worktree), 200)}` : ''}. ` +
848
- `Its output stayed on the machine${sessionLogPath ? ` — the session log is logs/${basename(sessionLogPath)} in the runner’s folder` : ''}.`);
849
1061
  }
850
- if (unfinished) {
851
- log(`${engineName} ended its session ${openCommandAtEnd ? `while its own ${open.join(', ')} was still running` : 'on a promise to check a result later'} — not reporting it as an answer${review || toolsOnly ? '' : ', pushing nothing'}`);
852
- return fail(unfinishedSentence(engineName, open, !review && !toolsOnly, continuedOnce));
1062
+ else if (!toolsOnly) {
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);
853
1069
  }
854
- if (review) {
855
- const dirty = await exec('git', ['-C', worktree, 'status', '--porcelain']);
856
- const left = dirty.stdout.split('\n').filter((l) => l.trim()).length;
857
- if (left > 0) {
858
- log(`review run ${job.runId}: ${left} changed path(s) in the checkout are discarded — a review pushes nothing`);
1070
+ if (job.runAttachments && worktree) {
1071
+ const prepared = prepareAttachFolder(worktree, log);
1072
+ if (prepared.dir) {
1073
+ attachFolder = prepared.dir;
1074
+ writtenSkills = mergeWritten(writtenSkills, prepared);
859
1075
  }
860
- const declinedReview = declinedHint();
861
- if (declinedReview)
862
- return report(declinedReview);
863
- log(`review run ${job.runId} finished — reporting the agent's review`);
864
- return report({
865
- status: 'no_pr',
866
- ...(summary
867
- ? { summary: reportedSummary(summary) }
868
- : { error: `${engineName} finished without saying what it found.` }),
869
- });
870
1076
  }
1077
+ const heavyLock = !toolsOnly && job.repo && cfg.heavyLock !== false ? heavyLockDir(rdir, job.repo) : null;
1078
+ const heavyHelper = heavyLock ? ensureHeavyScript(rdir) : null;
1079
+ const deviceHelper = heavyHelper ? ensureDeviceScript(rdir) : null;
1080
+ const heavily = (fn) => heavyLock
1081
+ ? withHeavyLock(heavyLock, fn, {
1082
+ label: `setup of ${job.runId}`,
1083
+ maxWaitMs: (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000,
1084
+ onWait: (holder) => log(`another heavy command is running in ${job.repo}${holder ? ` (pid ${holder})` : ''} — setup waits for it`),
1085
+ })
1086
+ : fn();
1087
+ const setupMs = (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000;
871
1088
  if (toolsOnly) {
872
- const declinedAnswer = declinedHint();
873
- if (declinedAnswer)
874
- return report(declinedAnswer);
875
- log(`tools-only run ${job.runId} finished — reporting the agent's summary`);
876
- return report({
877
- status: 'no_pr',
878
- ...(summary
879
- ? { summary: reportedSummary(summary) }
880
- : { error: `${engineName} finished without a summary of what it did.` }),
881
- });
882
1089
  }
883
- await exec('git', [
884
- '-C',
885
- worktree,
886
- 'add',
887
- '-A',
888
- '--',
889
- '.',
890
- ':(exclude).env',
891
- ':(exclude).claude/skills',
892
- ...writtenSkills.pathspecs,
893
- ]);
894
- const vsBase = await exec('git', [
895
- '-C',
896
- worktree,
897
- 'diff',
898
- '--cached',
899
- '--quiet',
900
- `origin/${base}`,
901
- ]);
902
- if (vsBase.code === 0) {
903
- const hinted = scanHints();
904
- if (hinted)
905
- return report(hinted);
906
- log(`no changes produced for ${job.runId} — reporting no_pr`);
907
- return report({
908
- status: 'no_pr',
909
- error: summary
910
- ? `No code change made. ${engineName}: ${oneLine(shareable(summary), 800)}`
911
- : `${engineName} made no changes (could not reproduce or fix).`,
912
- ...(summary ? { summary: reportedSummary(summary) } : {}),
913
- });
1090
+ else if (cfg.setupCommands?.length) {
1091
+ for (const cmd of cfg.setupCommands) {
1092
+ log(`setup: ${cmd}`);
1093
+ const setupCwd = worktree;
1094
+ const setupAt = Date.now();
1095
+ const r = await heavily(() => exec(cmd, [], {
1096
+ cwd: setupCwd,
1097
+ env: runEnv,
1098
+ timeoutMs: setupMs,
1099
+ shell: true,
1100
+ }));
1101
+ await trail?.setupRan({ command: cmd, exitCode: r.code, durationMs: Date.now() - setupAt });
1102
+ if (r.code !== 0) {
1103
+ log(`setup output for ${job.runId} (kept on this machine):\n${r.stderr.slice(-4000)}` +
1104
+ `${r.stdout.trim() ? `\n--- stdout ---\n${r.stdout.slice(-2000)}` : ''}`);
1105
+ const checkout = worktree;
1106
+ const fold = (text) => foldHome(stripWorktree(text, checkout), homedir());
1107
+ const why = setupReason(fold(r.stderr), fold(r.stdout));
1108
+ const said = why ? oneLine(why, 200).replace(/[.\s]+$/, '') : '';
1109
+ return fail(`Setup command failed (exit ${r.code}): ${setupCommandName(cmd)}` +
1110
+ `${said ? ` — ${said}` : ''}. ` +
1111
+ 'Its output stayed on the machine — the runner’s log shows it; fix the command or setupCommands in the runner config, then re-run.');
1112
+ }
1113
+ }
914
1114
  }
915
- const touched = await exec('git', [
916
- '-C',
917
- worktree,
918
- 'diff',
919
- '--cached',
920
- '--name-only',
921
- '--no-renames',
922
- '-z',
923
- continuesBranch ? `origin/${branch}` : `origin/${base}`,
924
- ], { timeoutMs: 60_000 }).catch(() => null);
925
- const kind = changeKind(touched?.code === 0 ? touched.stdout.split('\0').filter(Boolean) : null);
926
- const title = pullRequestTitle(job, kind);
927
- log(`${kind === 'test' ? 'the change touches tests only — ' : ''}titled "${title}"`);
928
- const uncommitted = await exec('git', ['-C', worktree, 'diff', '--cached', '--quiet', 'HEAD']);
929
- if (uncommitted.code !== 0) {
930
- await exec('git', ['-C', worktree, 'commit', '-m', title, '--quiet']);
1115
+ else if (resumeCut) {
931
1116
  }
932
- else {
933
- log(`agent already committed its changes for ${job.runId} — reconciling to a PR`);
1117
+ else if (cfg.autoInstall ?? true) {
1118
+ const installIn = worktree;
1119
+ await heavily(() => autoInstallDeps(installIn, runEnv, setupMs));
934
1120
  }
935
- const scanIn = worktree;
936
- const tipOf = async () => {
937
- const r = await exec('git', ['-C', scanIn, 'rev-parse', '--verify', '--quiet', `refs/heads/${branch}^{commit}`], { timeoutMs: 30_000 }).catch(() => null);
938
- const sha = r?.code === 0 ? r.stdout.trim() : '';
939
- return FULL_SHA.test(sha) ? sha : null;
1121
+ for (const cmd of toolsOnly ? [] : (cfg.backgroundCommands ?? [])) {
1122
+ log(`starting background: ${cmd}`);
1123
+ bgProcs.push(spawnBackground(cmd, { cwd: worktree, env: runEnv }));
1124
+ }
1125
+ await api.event(job.runId, 'fixing', { title: job.title });
1126
+ const mode = job.permissionMode ?? cfg.permissionMode ?? 'bypassPermissions';
1127
+ const model = job.model ?? cfg.model ?? null;
1128
+ const effort = job.effort ?? cfg.effort ?? null;
1129
+ const ultracode = effort === 'ultracode';
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';
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);
1143
+ const tools = cfg.allowedTools ??
1144
+ 'Read Edit Write Bash Glob Grep WebFetch WebSearch Task TodoWrite NotebookEdit';
1145
+ const isWin = process.platform === 'win32';
1146
+ if (job.mcpConfig != null) {
1147
+ const format = mcpFormatForEngine(adapter.id);
1148
+ if (format) {
1149
+ mcp = await prepareMcp({
1150
+ raw: job.mcpConfig,
1151
+ worktree,
1152
+ format,
1153
+ runId: job.runId,
1154
+ api,
1155
+ log,
1156
+ relay: cfg.mcpRelay !== false,
1157
+ });
1158
+ }
1159
+ log(mcp ? `mcp: ${mcp.logLine}` : 'mcp: no server was injected for this run');
1160
+ }
1161
+ const ctx = {
1162
+ prompt,
1163
+ model,
1164
+ effort,
1165
+ ultracode,
1166
+ permissionMode: mode,
1167
+ allowedTools: tools,
1168
+ maxBudgetUsd: cfg.maxBudgetUsd,
1169
+ attachDir: attachDir ?? undefined,
1170
+ attachPaths,
1171
+ isWin,
1172
+ runEnv: {
1173
+ ...stripForeignEngineCreds(runEnv, adapter.id),
1174
+ ...agentEnv,
1175
+ ...(heavyHelper && heavyLock
1176
+ ? { FIREFUNC_HEAVY: heavyHelper, FIREFUNC_HEAVY_LOCK: heavyLock }
1177
+ : {}),
1178
+ ...(deviceHelper
1179
+ ? { FIREFUNC_DEVICE: deviceHelper, FIREFUNC_DEVICE_LOCK: deviceLockDir(rdir) }
1180
+ : {}),
1181
+ },
1182
+ cfg,
1183
+ ...(mcp ? { mcp } : {}),
940
1184
  };
941
- const scannedTip = await tipOf();
942
- const readChange = (args, env) => exec('git', ['-C', scanIn, ...args], { timeoutMs: 120_000, env }).catch((e) => ({
943
- code: 1,
944
- stdout: '',
945
- stderr: e.message,
946
- }));
947
- const scanSince = async (from) => {
948
- const reads = changeReads(from, branch, scannedTip ?? undefined);
949
- const whole = await readChange(reads.whole, reads.env);
950
- const commits = whole.code === 0 ? await readChange(reads.commits, reads.env) : whole;
951
- if (whole.code !== 0 || commits.code !== 0) {
952
- const failed = whole.code !== 0 ? whole : commits;
953
- return {
954
- hits: null,
955
- why: `git exit ${failed.code}: ${failed.stderr.trim().slice(0, 200)}`,
956
- };
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;
1210
+ let inv;
1211
+ try {
1212
+ inv = adapter.buildInvocation(firstCtx);
1213
+ }
1214
+ catch (e) {
1215
+ return fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
1216
+ }
1217
+ const engineName = adapter.displayName;
1218
+ log(`running ${inv.bin} (${engineName}) on ${toolsOnly ? 'no repository — tools only' : `${job.repo} (${branch})`} — model=${model ?? 'default'} effort=${effort ?? 'default'} mode=${mode}`);
1219
+ log(`${engineName} auth: ${inv.authLogLine}`);
1220
+ const printer = cfg.quiet ? undefined : adapter.makeStreamPrinter();
1221
+ const activity = createActivityReporter({
1222
+ worktree,
1223
+ post: (steps) => api.activity(job.runId, steps),
1224
+ writeTools: new Set(mcp?.writeToolNames ?? []),
1225
+ seqStart: activitySeen,
1226
+ });
1227
+ for (const name of mcp?.writeToolNames ?? [])
1228
+ trailWriteTools.add(name);
1229
+ const activityParser = makeStreamJsonParser(activity.push, { toolResults: true });
1230
+ const onStdout = (chunk) => {
1231
+ const shown = blankSecrets(chunk);
1232
+ printer?.(shown);
1233
+ viewer?.push(job.runId, shown);
1234
+ activityParser(chunk);
1235
+ trail?.feed(chunk);
1236
+ };
1237
+ if (printer) {
1238
+ log(`── live ${engineName} session (shown here only — never sent to FireFunc) ──`);
1239
+ }
1240
+ const heartbeat = setInterval(() => void api.event(job.runId, 'heartbeat'), 5 * 60_000);
1241
+ const engineCwd = worktree;
1242
+ let engineMs = 0;
1243
+ const runEngineOnce = async (limitMs = timeoutMs) => {
1244
+ let group = 0;
1245
+ const started = Date.now();
1246
+ try {
1247
+ return await exec(inv.bin, inv.args, {
1248
+ cwd: engineCwd,
1249
+ timeoutMs: limitMs,
1250
+ env: inv.env,
1251
+ input: inv.stdinInput,
1252
+ shell: inv.shell,
1253
+ onStdout,
1254
+ ownGroup: true,
1255
+ onSpawn: (pid) => {
1256
+ group = pid;
1257
+ engineGroups.push({ pgid: pid, startedAt: started });
1258
+ trackEngineGroup(pid);
1259
+ updateHeld(rdir, job.runId, { engineGroup: pid, engineStartedAt: started });
1260
+ },
1261
+ });
1262
+ }
1263
+ finally {
1264
+ if (group)
1265
+ untrackEngineGroup(group);
1266
+ engineMs += Date.now() - started;
957
1267
  }
958
- return {
959
- hits: uniqueHits([...scanAddedLines(whole.stdout), ...scanAddedLines(commits.stdout)]),
960
- };
961
1268
  };
962
- const found = (hits, n = 5) => hits
963
- .slice(0, n)
964
- .map((h) => `${h.kind} at ${h.path}:${h.line}`)
965
- .join(', ');
966
- const asReported = (hits) => ({
967
- scanned: true,
968
- hits: hits.slice(0, 100).map((h) => ({ ...h, path: h.path.slice(0, 512) })),
969
- });
970
- let scanCoversPullRequest = false;
971
- const own = await scanSince(continuesBranch ? `origin/${branch}` : `origin/${base}`);
972
- if (own.hits) {
973
- const added = hardFirst(own.hits);
974
- secretScan = asReported(added);
975
- if (added.some(refusesPush)) {
976
- log(`secret scan for ${job.runId}: ${added.length} finding(s) — ${found(added)} — refusing to push`);
977
- return fail(secretRefusal(added, branch));
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;
978
1285
  }
979
- if (added.length > 0) {
980
- log(`secret scan for ${job.runId}: ${added.length} looser match(es) — ${found(added)} — pushing; ` +
981
- 'the result reports them, and FireFunc does not auto-merge a pull request with a finding');
1286
+ finally {
1287
+ await trail?.engineEnded({ exitCode: code, durationMs: Date.now() - t0 });
982
1288
  }
983
- else {
984
- log(`secret scan for ${job.runId}: nothing found in what this push adds`);
1289
+ };
1290
+ const sessions = [];
1291
+ let lastReport = null;
1292
+ const meter = (stdout, continued = false) => {
1293
+ if (!adapter.meter)
1294
+ return;
1295
+ let u = null;
1296
+ try {
1297
+ u = adapter.meter(stdout);
985
1298
  }
986
- if (!continuesBranch) {
987
- scanCoversPullRequest = true;
1299
+ catch {
1300
+ u = null;
988
1301
  }
989
- else {
990
- const whole = await scanSince(`origin/${base}`);
991
- if (whole.hits) {
992
- const all = hardFirst(uniqueHits([...added, ...whole.hits]));
993
- secretScan = asReported(all);
994
- scanCoversPullRequest = true;
995
- const before = all.length - added.length;
996
- if (before > 0) {
997
- log(`secret scan for ${job.runId}: the pull request already holds ${before} finding(s) from commits pushed before this run — ` +
998
- 'they are on GitHub already, so the push goes on; the result reports them, and FireFunc does not auto-merge the pull request');
999
- }
1000
- }
1001
- else {
1002
- log(`could not read the pull request from origin/${base} to scan it whole (${whole.why}) — ` +
1003
- 'the result reports what this run adds, without the commit it covers, so FireFunc does not auto-merge it');
1004
- }
1302
+ lastReport = u;
1303
+ sessions.push({ usage: u, session: adapter.sessionId?.(stdout) ?? null, continued });
1304
+ };
1305
+ const limitOf = (stdout) => {
1306
+ try {
1307
+ return adapter.planLimit?.(stdout, now()) ?? null;
1308
+ }
1309
+ catch {
1310
+ return null;
1005
1311
  }
1312
+ };
1313
+ const refused = (stdout, stderr) => endedOnRefusal({
1314
+ ending: adapter.ending?.(stdout),
1315
+ summary: adapter.summarize(stdout),
1316
+ stderr,
1317
+ });
1318
+ let engineRun = await runEngine();
1319
+ meter(engineRun.stdout, false);
1320
+ if (resumeCut &&
1321
+ firstCtx.resumeSessionId &&
1322
+ engineRun.code !== 0 &&
1323
+ !adapter.sessionId?.(engineRun.stdout)) {
1324
+ log(`${engineName} could not continue the session a plan limit cut — starting a new session in the same worktree`);
1325
+ inv = adapter.buildInvocation({
1326
+ ...ctx,
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'),
1332
+ });
1333
+ engineRun = await runEngine();
1334
+ meter(engineRun.stdout, false);
1006
1335
  }
1007
- else {
1008
- log(`could not read the change to scan it for secrets (${own.why}) — pushing without a scan, and the result reports none`);
1336
+ for (let resumes = 0; resumes < 2 && engineRun.code !== 0; resumes++) {
1337
+ if (limitOf(engineRun.stdout))
1338
+ break;
1339
+ if (refused(engineRun.stdout, engineRun.stderr))
1340
+ break;
1341
+ if (endedBySignal(engineRun.code))
1342
+ break;
1343
+ const why = networkFailureHint(`${adapter.summarize(engineRun.stdout)}\n${engineRun.stderr.slice(-2000)}`);
1344
+ if (!why)
1345
+ break;
1346
+ log(`${engineName} stopped because ${why} — waiting for the network before resuming (resume ${resumes + 1} of 2)`);
1347
+ const back = await waitForNetwork({
1348
+ probe: () => api.probe(),
1349
+ maxWaitMs: 20 * 60_000,
1350
+ log,
1351
+ });
1352
+ if (!back) {
1353
+ log('the network did not come back within 20 minutes — giving up on this attempt');
1354
+ break;
1355
+ }
1356
+ log(`the network is back — resuming ${engineName} in the same worktree`);
1357
+ inv = adapter.buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt) });
1358
+ engineRun = await runEngine();
1359
+ meter(engineRun.stdout, false);
1009
1360
  }
1010
- await api.event(job.runId, 'pushing', { branch });
1011
- const gitCred = job.repo ? await api.gitCredential(job.runId) : null;
1012
- if (gitCred)
1013
- log(`using a FireFunc-issued git credential for ${gitCred.repo}`);
1014
- const pushedCommits = await execOut('git', [
1015
- '-C',
1016
- worktree,
1017
- '--no-replace-objects',
1018
- '-c',
1019
- 'core.quotepath=off',
1020
- 'log',
1021
- '--name-only',
1022
- '--format=',
1023
- '--no-renames',
1024
- '--diff-filter=d',
1025
- `${continuesBranch ? `origin/${branch}` : `origin/${base}`}..${scannedTip ?? `refs/heads/${branch}`}`,
1026
- ]);
1027
- const staged = [
1028
- await execOut('git', [
1029
- '-C',
1030
- worktree,
1031
- 'show',
1032
- '--name-only',
1033
- '--format=',
1034
- '--diff-filter=d',
1035
- 'HEAD',
1036
- ]),
1037
- pushedCommits,
1038
- ].join('\n');
1039
- const mcpStaged = mcp?.configPath
1040
- ? relative(worktree, mcp.configPath).split(sep).join('/')
1041
- : null;
1042
- const stagedPaths = staged
1043
- .split('\n')
1044
- .map((l) => l.trim())
1045
- .filter(Boolean);
1046
- const leaked = stagedPaths.filter((l) => l === '.env' || l.endsWith('/.env') || (mcpStaged !== null && l === mcpStaged));
1047
- if (leaked.length > 0) {
1048
- return fail(`refusing to push: the commit contains ${leaked.join(', ')}, which can hold live credentials. ` +
1049
- `This is a FireFunc bug — please report it. Nothing was pushed.`);
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
+ }
1050
1370
  }
1051
- const skillLeaked = writtenSkillPaths(stagedPaths, writtenSkills);
1052
- if (skillLeaked.length > 0) {
1053
- return fail(`refusing to push: the agent added ${skillLeaked.join(', ')} to its commit — a skill ` +
1054
- `FireFunc writes into the checkout for this run only and never commits. Nothing was ` +
1055
- `pushed. Fix: tell the agent not to stage or commit anything under ` +
1056
- `${skillLeaked[0].split('/').slice(0, -1).join('/')} (check its instruction and ` +
1057
- `its skills for "git add -f" or "commit everything"), then re-run the task.`);
1371
+ const openAtEnd = (stdout) => {
1372
+ try {
1373
+ return adapter.openCommandsAtEnd?.(stdout) ?? [];
1374
+ }
1375
+ catch {
1376
+ return [];
1377
+ }
1378
+ };
1379
+ const endedOnItsAnswer = (r) => r.code === 0 && !limitOf(r.stdout) && !refused(r.stdout, r.stderr);
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));
1392
+ const toContinue = adapter.resumesSessions
1393
+ ? (adapter.sessionId?.(engineRun.stdout) ?? null)
1394
+ : null;
1395
+ const timeLeft = timeoutMs - engineMs;
1396
+ let continuedOnce = false;
1397
+ if ((open.length > 0 || promising) && toContinue && timeLeft < 60_000) {
1398
+ log(`${engineName}'s session ended before its result came, with under a minute of its time left — not continuing it`);
1058
1399
  }
1059
- const pushFrom = worktree;
1060
- const pushOnce = async () => gitCred
1061
- ? pushBranch(pushFrom, branch, gitCred.repo, gitCred, { force: !continuesBranch })
1062
- : exec('git', [
1063
- '-C',
1064
- pushFrom,
1065
- 'push',
1066
- ...pushFlags(!continuesBranch),
1067
- 'origin',
1068
- `${branch}:${branch}`,
1069
- ], {
1070
- timeoutMs: 120_000,
1400
+ else if ((open.length > 0 || promising) && toContinue) {
1401
+ log(`${engineName}'s session ended ${open.length > 0 ? `while its own ${open.join(', ')} was still running` : 'on a promise to check a result later'} — continuing the same session once to get the result`);
1402
+ inv = adapter.buildInvocation({
1403
+ ...ctx,
1404
+ prompt: continueToFinishBrief(open),
1405
+ resumeSessionId: toContinue,
1071
1406
  });
1072
- let push = await pushOnce();
1073
- for (let tries = 0; tries < 3 && push.code !== 0 && isNetworkError(push.stderr); tries++) {
1074
- log(`push failed because the network seems to be away — waiting for it (try ${tries + 1} of 3)`);
1075
- const back = await waitForNetwork({ probe: () => api.probe(), maxWaitMs: 10 * 60_000, log });
1076
- if (!back)
1077
- break;
1078
- push = await pushOnce();
1407
+ engineRun = await runEngine(timeLeft);
1408
+ meter(engineRun.stdout, true);
1409
+ continuedOnce = true;
1410
+ open = endedOnItsAnswer(engineRun) ? openAtEnd(engineRun.stdout) : [];
1411
+ promising =
1412
+ endedOnItsAnswer(engineRun) && promisesLaterCheck(adapter.summarize(engineRun.stdout));
1079
1413
  }
1080
- if (push.code !== 0) {
1081
- const said = redact(push.stderr, gitCred?.token);
1082
- log(`git push output for ${job.runId} (kept on this machine):\n${said.slice(-4000)}`);
1083
- const refused = pushRefusal(said);
1084
- return fail(refused
1085
- ? `git push failed: ${oneLine(refused, 400)}`
1086
- : `git push failed (exit ${push.code}); its output stayed on the machine — the runner’s log shows it.`);
1414
+ openCommandAtEnd = open.length > 0;
1415
+ const unfinished = open.length > 0 || promising;
1416
+ clearInterval(heartbeat);
1417
+ usage =
1418
+ attemptUsage(sessions, resumeCut ? { session: resumeCut.sessionId, baseline: resumeCut.usage } : undefined) ?? undefined;
1419
+ if (revising && kept?.attemptUsage) {
1420
+ usage = combineUsage([kept.attemptUsage, usage ?? null]) ?? usage;
1087
1421
  }
1088
- if (secretScan && scannedTip && scanCoversPullRequest) {
1089
- const pushedTip = await tipOf();
1090
- if (pushedTip === scannedTip)
1091
- secretScan = { ...secretScan, head: scannedTip };
1092
- else
1093
- 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`);
1422
+ if (parkStep && parkKept?.attemptUsage) {
1423
+ usage = combineUsage([parkKept.attemptUsage, usage ?? null]) ?? usage;
1094
1424
  }
1095
- const body = pullRequestBody(kind, engineName, job.externalId, { continuesBranch });
1096
- if (gitCred) {
1097
- const pr = await withNetworkRetry(() => openDraftPr({
1098
- repo: gitCred.repo,
1099
- head: branch,
1100
- base,
1101
- title,
1102
- body,
1103
- cred: gitCred,
1104
- }), {
1105
- label: `pull request for ${job.runId}`,
1106
- maxWaitMs: 10 * 60_000,
1107
- probe: () => api.probe(),
1108
- log,
1109
- });
1110
- if (!('error' in pr)) {
1111
- await api.event(job.runId, 'pr_opened', { url: pr.url, branch });
1112
- log(`opened PR for ${job.runId}: ${pr.url}`);
1113
- return report({
1114
- status: 'pr_opened',
1115
- pr: {
1116
- repo: job.repo ?? undefined,
1117
- number: pr.number,
1118
- url: pr.url,
1119
- branch,
1120
- summary: title,
1121
- },
1122
- ...(summary ? { summary: reportedSummary(summary) } : {}),
1425
+ if (usage)
1426
+ log(`${engineName} spent: ${describeUsage(usage)}`);
1427
+ viewer?.end(job.runId, engineRun.code === 0 ? 'done' : 'failed');
1428
+ if (printer)
1429
+ log(`── end ${engineName} session ──`);
1430
+ await activity.flush();
1431
+ activitySeen = activity.seen;
1432
+ log(`reported ${activity.sent} of ${activity.seen} step(s) to FireFunc — names and verbs only; the session stayed here`);
1433
+ mcp?.cleanup();
1434
+ const sessionLogPath = saveSessionLog(job.runId, engineRun.stdout, engineRun.stderr);
1435
+ const summary = adapter.summarize(engineRun.stdout);
1436
+ if (sessionLogPath)
1437
+ log(`${engineName} session saved → ${sessionLogPath}`);
1438
+ if (summary)
1439
+ log(`${engineName} said: ${summary.replace(/\s+/g, ' ').slice(0, 500)}`);
1440
+ if (engineRun.code === 124) {
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',
1123
1468
  });
1124
1469
  }
1125
- const why = redact(pr.error, gitCred.token);
1126
- if (!(await hasGh(worktree)))
1127
- return fail(why);
1128
- log(`could not open the PR as FireFunc (${why}); falling back to gh`);
1470
+ keepWorktree = keptOnTimeout;
1471
+ const limitWords = budget !== null && limitMinutes === budget
1472
+ ? `${engineName} timed out after ${limitMinutes} min — the agent's time budget.`
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);
1129
1477
  }
1130
- const createCwd = worktree;
1131
- const create = await withNetworkRetry(async () => {
1132
- const r = await exec('gh', [
1133
- 'pr',
1134
- 'create',
1135
- '--draft',
1136
- '--head',
1137
- branch,
1138
- '--base',
1139
- base,
1140
- '--title',
1141
- title,
1142
- '--body',
1143
- body,
1144
- ], { cwd: createCwd, timeoutMs: 60_000 });
1145
- if (r.code !== 0 && networkFailureHint(`${r.stdout}\n${r.stderr}`)) {
1146
- throw new NetworkGoneError(r.stderr.trim() || 'gh pr create failed');
1478
+ const limit = limitOf(engineRun.stdout);
1479
+ if (limit) {
1480
+ opts?.limits?.set(adapter.id, limit);
1481
+ const cutSession = adapter.resumesSessions
1482
+ ? (adapter.sessionId?.(engineRun.stdout) ?? null)
1483
+ : null;
1484
+ let kept = false;
1485
+ if (cutSession && worktree) {
1486
+ const cutAt = now().getTime();
1487
+ kept = saveCut(rdir, {
1488
+ workItemId: job.workItemId,
1489
+ runId: job.runId,
1490
+ engine: adapter.id,
1491
+ sessionId: cutSession,
1492
+ repo: job.repo ?? null,
1493
+ branch: toolsOnly ? '' : branch,
1494
+ base,
1495
+ worktree,
1496
+ repoPath: toolsOnly ? null : repoPath,
1497
+ ...(readHead ? { readHead } : {}),
1498
+ resetsAt: limit.resetsAt,
1499
+ cutAt: new Date(cutAt).toISOString(),
1500
+ keepUntil: keepUntil(limit.resetsAt, cutAt),
1501
+ promptHash: promptHash(job.prompt),
1502
+ review,
1503
+ toolsOnly,
1504
+ continuesBranch,
1505
+ ...(lastReport ? { usage: lastReport } : {}),
1506
+ writtenSkills,
1507
+ });
1147
1508
  }
1148
- return r;
1149
- }, {
1150
- label: `pull request for ${job.runId} (gh)`,
1151
- maxWaitMs: 10 * 60_000,
1152
- probe: () => api.probe(),
1153
- log,
1154
- }).catch((err) => ({
1155
- code: 1,
1156
- stdout: '',
1157
- stderr: err instanceof Error ? err.message : String(err),
1158
- }));
1159
- const wt = worktree;
1160
- const viewPr = async (b) => {
1161
- const out = await execOut('gh', ['pr', 'view', b, '--json', 'url,number'], wt);
1162
- try {
1163
- const j = JSON.parse(out);
1164
- if (typeof j.url === 'string' && /\/pull\/\d+/.test(j.url) && Number.isFinite(j.number)) {
1165
- return { url: j.url, number: Number(j.number) };
1166
- }
1509
+ keepWorktree = kept;
1510
+ log(`${engineName} was stopped by the plan's usage limit${limit.said ? ` ("${limit.said}")` : ''} — ` +
1511
+ (limit.resetsAt ? `it resets at ${limit.resetsAt}` : 'it did not say when it resets') +
1512
+ (kept ? '; the session and its worktree are kept to continue after the reset' : ''));
1513
+ return report({
1514
+ status: 'failed',
1515
+ error: limitSentence(engineName, limit, kept),
1516
+ limit: { kind: 'plan', resetsAt: limit.resetsAt },
1517
+ });
1518
+ }
1519
+ const declinedHint = () => {
1520
+ if (!refused(engineRun.stdout, engineRun.stderr))
1521
+ return null;
1522
+ log(`the model declined ${job.runId}: its safety system refused the session`);
1523
+ return { status: 'failed', error: modelDeclinedSentence(engineName) };
1524
+ };
1525
+ const scanHints = () => {
1526
+ const declined = declinedHint();
1527
+ if (declined)
1528
+ return declined;
1529
+ const authMsg = adapter.authFailureHint(`${summary}\n${engineRun.stderr}`);
1530
+ if (authMsg) {
1531
+ log(`auth/billing failure for ${job.runId}: ${authMsg}`);
1532
+ return { status: 'failed', error: authMsg };
1167
1533
  }
1168
- catch {
1534
+ const rateMsg = adapter.rateLimitHint(`${summary}\n${engineRun.stderr}`);
1535
+ if (rateMsg) {
1536
+ log(`rate limit for ${job.runId}: ${rateMsg}`);
1537
+ return { status: 'failed', error: rateMsg };
1169
1538
  }
1170
1539
  return null;
1171
1540
  };
1172
- const headBranch = (await execOut('git', ['rev-parse', '--abbrev-ref', 'HEAD'], wt)) || branch;
1173
- let resolved = null;
1174
- for (const b of [...new Set([headBranch, branch].filter(Boolean))]) {
1175
- resolved = await viewPr(b);
1176
- if (resolved)
1177
- break;
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
+ });
1178
1587
  }
1179
- if (!resolved) {
1180
- const m = `${create.stdout}\n${create.stderr}`.match(/https?:\/\/\S*\/pull\/(\d+)/);
1181
- if (m)
1182
- resolved = { url: m[0], number: Number(m[1]) };
1588
+ if (engineRun.code !== 0) {
1589
+ const signal = endedBySignal(engineRun.code);
1590
+ if (signal) {
1591
+ log(`${engineName} was ended by ${signal} (exit ${engineRun.code}) for ${job.runId}`);
1592
+ return fail(stoppedSentence(engineName, engineRun.code, signal, sessionLogPath ? basename(sessionLogPath) : null));
1593
+ }
1594
+ const hinted = scanHints();
1595
+ if (hinted)
1596
+ return report(hinted);
1597
+ const why = summary ? null : errorLine(engineRun.stderr);
1598
+ return fail(summary
1599
+ ? `${engineName} exited abnormally (code ${engineRun.code}). Last message: ${oneLine(shareable(summary), 500)}`
1600
+ : `${engineName} exited abnormally (code ${engineRun.code})${why ? `: ${oneLine(stripWorktree(why, worktree), 200)}` : ''}. ` +
1601
+ `Its output stayed on the machine${sessionLogPath ? ` — the session log is logs/${basename(sessionLogPath)} in the runner’s folder` : ''}.`);
1183
1602
  }
1184
- if (!resolved) {
1185
- const why = (create.stderr || create.stdout).replace(/\s+/g, ' ').trim().slice(0, 400);
1186
- return fail(`The branch ${branch} was pushed, but the pull request could not be created${why ? `: ${why}` : ''}. ` +
1187
- `Open it from that branch on GitHub (FireFunc will link it to this task), or re-run.`);
1603
+ if (unfinished) {
1604
+ log(`${engineName} ended its session ${openCommandAtEnd ? `while its own ${open.join(', ')} was still running` : 'on a promise to check a result later'} — not reporting it as an answer${review || toolsOnly ? '' : ', pushing nothing'}`);
1605
+ return fail(unfinishedSentence(engineName, open, !review && !toolsOnly, continuedOnce));
1188
1606
  }
1189
- const url = resolved.url;
1190
- const number = resolved.number;
1191
- await api.event(job.runId, 'pr_opened', { url, branch });
1192
- log(`opened PR for ${job.runId}: ${url}`);
1193
- return report({
1194
- status: 'pr_opened',
1195
- pr: { repo: job.repo ?? undefined, number, url: url || undefined, branch, summary: title },
1196
- ...(summary ? { summary: reportedSummary(summary) } : {}),
1607
+ if (review) {
1608
+ const dirty = await exec('git', ['-C', worktree, 'status', '--porcelain']);
1609
+ const left = dirty.stdout.split('\n').filter((l) => l.trim()).length;
1610
+ if (left > 0) {
1611
+ log(`review run ${job.runId}: ${left} changed path(s) in the checkout are discarded — a review pushes nothing`);
1612
+ }
1613
+ const declinedReview = declinedHint();
1614
+ if (declinedReview)
1615
+ return report(declinedReview);
1616
+ log(`review run ${job.runId} finished — reporting the agent's review`);
1617
+ return report({
1618
+ status: 'no_pr',
1619
+ ...(summary
1620
+ ? { summary: reportedSummary(summary) }
1621
+ : { error: `${engineName} finished without saying what it found.` }),
1622
+ });
1623
+ }
1624
+ if (toolsOnly) {
1625
+ const declinedAnswer = declinedHint();
1626
+ if (declinedAnswer)
1627
+ return report(declinedAnswer);
1628
+ log(`tools-only run ${job.runId} finished — reporting the agent's summary`);
1629
+ return report({
1630
+ status: 'no_pr',
1631
+ ...(summary
1632
+ ? { summary: reportedSummary(summary) }
1633
+ : { error: `${engineName} finished without a summary of what it did.` }),
1634
+ });
1635
+ }
1636
+ await exec('git', [
1637
+ '-C',
1638
+ worktree,
1639
+ 'add',
1640
+ '-A',
1641
+ '--',
1642
+ '.',
1643
+ ':(exclude).env',
1644
+ ':(exclude).claude/skills',
1645
+ `:(exclude,literal)${AGENT_PR_FILE}`,
1646
+ ...writtenSkills.pathspecs,
1647
+ ]);
1648
+ const vsBase = await exec('git', [
1649
+ '-C',
1650
+ worktree,
1651
+ 'diff',
1652
+ '--cached',
1653
+ '--quiet',
1654
+ `origin/${base}`,
1655
+ ]);
1656
+ if (vsBase.code === 0) {
1657
+ const hinted = scanHints();
1658
+ if (hinted)
1659
+ return report(hinted);
1660
+ log(`no changes produced for ${job.runId} — reporting no_pr`);
1661
+ return report({
1662
+ status: 'no_pr',
1663
+ error: summary
1664
+ ? `No code change made. ${engineName}: ${oneLine(shareable(summary), 800)}`
1665
+ : `${engineName} made no changes (could not reproduce or fix).`,
1666
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
1667
+ });
1668
+ }
1669
+ const touched = await exec('git', [
1670
+ '-C',
1671
+ worktree,
1672
+ 'diff',
1673
+ '--cached',
1674
+ '--name-only',
1675
+ '--no-renames',
1676
+ '-z',
1677
+ continuesBranch ? `origin/${branch}` : `origin/${base}`,
1678
+ ], { timeoutMs: 60_000 }).catch(() => null);
1679
+ const kind = changeKind(touched?.code === 0 ? touched.stdout.split('\0').filter(Boolean) : null);
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}`);
1686
+ log(`${kind === 'test' ? 'the change touches tests only — ' : ''}titled "${title}"`);
1687
+ const uncommitted = await exec('git', ['-C', worktree, 'diff', '--cached', '--quiet', 'HEAD']);
1688
+ if (uncommitted.code !== 0) {
1689
+ await exec('git', ['-C', worktree, 'commit', '-m', title, '--quiet']);
1690
+ }
1691
+ else {
1692
+ log(`agent already committed its changes for ${job.runId} — reconciling to a PR`);
1693
+ }
1694
+ return await ship({
1695
+ worktree: worktree,
1696
+ branch,
1697
+ base,
1698
+ title,
1699
+ kind,
1700
+ engineName,
1701
+ summary,
1702
+ agentText,
1703
+ keep: askFirst
1704
+ ? {
1705
+ sessionId: adapter.sessionId?.(engineRun.stdout) ?? (resumeCut?.sessionId || null),
1706
+ ...(lastReport ? { sessionReport: lastReport } : {}),
1707
+ round: revising ? revising.round : 1,
1708
+ }
1709
+ : null,
1197
1710
  });
1198
1711
  }
1199
1712
  catch (err) {
@@ -1201,6 +1714,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
1201
1714
  return report({ status: 'failed', error: err.message.slice(0, 400) });
1202
1715
  }
1203
1716
  finally {
1717
+ if (job.agentEnv?.length) {
1718
+ setTimeout(() => releaseSecretValues(job.runId), 15 * 60_000).unref();
1719
+ }
1204
1720
  mcp?.cleanup();
1205
1721
  viewer?.end(job.runId, 'failed');
1206
1722
  await Promise.all(bgProcs.map((p) => killProcessTree(p).catch(() => { })));
@@ -1227,6 +1743,10 @@ export async function runJob(job, cfg, api, viewer, opts) {
1227
1743
  }
1228
1744
  if (resumeCut && !keepWorktree)
1229
1745
  dropCut(rdir, resumeCut.workItemId);
1746
+ if (kept && !keepWorktree)
1747
+ dropKept(rdir, job.runId);
1748
+ if (parkKept && !keepWorktree)
1749
+ dropKept(rdir, job.runId);
1230
1750
  if (!keepWorktree) {
1231
1751
  for (const copy of reviewCopies) {
1232
1752
  try {