@firefunc-agent/runner 0.9.14 → 0.9.34

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 (153) hide show
  1. package/README.md +167 -10
  2. package/dist/alive.d.ts +40 -0
  3. package/dist/alive.js +138 -0
  4. package/dist/api-fallback.d.ts +4 -2
  5. package/dist/api-fallback.js +26 -1
  6. package/dist/api.d.ts +65 -3
  7. package/dist/api.js +164 -3
  8. package/dist/brief-file.d.ts +15 -0
  9. package/dist/brief-file.js +36 -0
  10. package/dist/brief.d.ts +3 -0
  11. package/dist/brief.js +14 -4
  12. package/dist/build-caches.d.ts +7 -0
  13. package/dist/build-caches.js +63 -0
  14. package/dist/build-info.json +2 -2
  15. package/dist/checkpoint.d.ts +40 -0
  16. package/dist/checkpoint.js +98 -0
  17. package/dist/cli.js +184 -18
  18. package/dist/cloud-boot.d.ts +41 -0
  19. package/dist/cloud-boot.js +239 -0
  20. package/dist/command-activity.d.ts +23 -0
  21. package/dist/command-activity.js +89 -0
  22. package/dist/command-step.d.ts +58 -0
  23. package/dist/command-step.js +248 -0
  24. package/dist/config.d.ts +38 -0
  25. package/dist/config.js +23 -0
  26. package/dist/cut.d.ts +1 -1
  27. package/dist/cut.js +13 -3
  28. package/dist/daemon.js +364 -15
  29. package/dist/device-lease.d.ts +15 -0
  30. package/dist/device-lease.js +608 -0
  31. package/dist/editor/fs-server.d.ts +31 -0
  32. package/dist/editor/fs-server.js +159 -0
  33. package/dist/editor/relay-crypto.d.ts +68 -0
  34. package/dist/editor/relay-crypto.js +191 -0
  35. package/dist/editor/sessions.d.ts +50 -0
  36. package/dist/editor/sessions.js +279 -0
  37. package/dist/editor/worktree-of.d.ts +1 -0
  38. package/dist/editor/worktree-of.js +23 -0
  39. package/dist/editor/ws-client.d.ts +26 -0
  40. package/dist/editor/ws-client.js +227 -0
  41. package/dist/engine-account.d.ts +24 -0
  42. package/dist/engine-account.js +118 -0
  43. package/dist/engine-login.d.ts +12 -0
  44. package/dist/engine-login.js +88 -0
  45. package/dist/engine-models.d.ts +13 -0
  46. package/dist/engine-models.js +71 -0
  47. package/dist/engine-watch.d.ts +1 -0
  48. package/dist/engine-watch.js +22 -6
  49. package/dist/engines/antigravity.js +19 -4
  50. package/dist/engines/claude.js +10 -9
  51. package/dist/engines/codex.js +16 -2
  52. package/dist/engines/copilot.js +12 -0
  53. package/dist/engines/crush.d.ts +2 -0
  54. package/dist/engines/crush.js +58 -0
  55. package/dist/engines/cursor.js +12 -0
  56. package/dist/engines/gemini.js +14 -9
  57. package/dist/engines/index.d.ts +8 -0
  58. package/dist/engines/index.js +73 -1
  59. package/dist/engines/kilo.d.ts +2 -0
  60. package/dist/engines/kilo.js +63 -0
  61. package/dist/engines/opencode.d.ts +9 -0
  62. package/dist/engines/opencode.js +234 -0
  63. package/dist/engines/openhands.d.ts +10 -0
  64. package/dist/engines/openhands.js +271 -0
  65. package/dist/engines/pi.d.ts +10 -0
  66. package/dist/engines/pi.js +248 -0
  67. package/dist/engines/qwen.d.ts +8 -0
  68. package/dist/engines/qwen.js +153 -0
  69. package/dist/engines/sessions.d.ts +6 -0
  70. package/dist/engines/sessions.js +68 -0
  71. package/dist/engines/types.d.ts +3 -3
  72. package/dist/exec.d.ts +1 -0
  73. package/dist/exec.js +10 -4
  74. package/dist/firefunc/agents.d.ts +8 -1
  75. package/dist/firefunc/agents.js +53 -3
  76. package/dist/firefunc/auth.js +72 -19
  77. package/dist/firefunc/cli.js +25 -0
  78. package/dist/firefunc/client.d.ts +5 -1
  79. package/dist/firefunc/client.js +12 -2
  80. package/dist/firefunc/config.d.ts +11 -1
  81. package/dist/firefunc/config.js +6 -4
  82. package/dist/firefunc/io.d.ts +1 -0
  83. package/dist/firefunc/main.js +8 -1
  84. package/dist/firefunc/oauth-login.d.ts +23 -0
  85. package/dist/firefunc/oauth-login.js +304 -0
  86. package/dist/firefunc/tasks.d.ts +4 -0
  87. package/dist/firefunc/tasks.js +89 -2
  88. package/dist/fleet-words.d.ts +2 -0
  89. package/dist/fleet-words.js +7 -0
  90. package/dist/git-auth.d.ts +15 -0
  91. package/dist/git-auth.js +39 -1
  92. package/dist/held.d.ts +3 -0
  93. package/dist/job.d.ts +26 -3
  94. package/dist/job.js +752 -152
  95. package/dist/keep-awake.d.ts +17 -0
  96. package/dist/keep-awake.js +90 -0
  97. package/dist/keep-local.d.ts +1 -1
  98. package/dist/keep-local.js +5 -3
  99. package/dist/limit.d.ts +9 -1
  100. package/dist/limit.js +260 -3
  101. package/dist/local-checks.d.ts +19 -0
  102. package/dist/local-checks.js +79 -0
  103. package/dist/locks.d.ts +18 -1
  104. package/dist/locks.js +249 -69
  105. package/dist/machine-commands.d.ts +21 -0
  106. package/dist/machine-commands.js +107 -0
  107. package/dist/machine-profile.d.ts +18 -0
  108. package/dist/machine-profile.js +69 -0
  109. package/dist/mcp-init.d.ts +2 -0
  110. package/dist/mcp-init.js +28 -0
  111. package/dist/mcp.d.ts +13 -1
  112. package/dist/mcp.js +23 -2
  113. package/dist/network.js +3 -2
  114. package/dist/orphans.d.ts +4 -0
  115. package/dist/orphans.js +96 -4
  116. package/dist/pool.d.ts +1 -0
  117. package/dist/pool.js +25 -2
  118. package/dist/pr-title.d.ts +10 -0
  119. package/dist/pr-title.js +15 -0
  120. package/dist/recover.d.ts +3 -1
  121. package/dist/recover.js +27 -7
  122. package/dist/release-draft.d.ts +79 -0
  123. package/dist/release-draft.js +301 -0
  124. package/dist/resources.d.ts +86 -0
  125. package/dist/resources.js +217 -0
  126. package/dist/restart-idle.d.ts +23 -0
  127. package/dist/restart-idle.js +67 -0
  128. package/dist/run-attachments.d.ts +5 -0
  129. package/dist/run-attachments.js +14 -9
  130. package/dist/run-stops.d.ts +15 -0
  131. package/dist/run-stops.js +90 -0
  132. package/dist/run-temp.d.ts +12 -0
  133. package/dist/run-temp.js +57 -0
  134. package/dist/secret-scan.d.ts +5 -0
  135. package/dist/secret-scan.js +30 -0
  136. package/dist/self-upgrade.d.ts +36 -0
  137. package/dist/self-upgrade.js +78 -0
  138. package/dist/service.d.ts +7 -1
  139. package/dist/service.js +50 -7
  140. package/dist/sign-in.d.ts +41 -0
  141. package/dist/sign-in.js +239 -0
  142. package/dist/tool-call.d.ts +59 -0
  143. package/dist/tool-call.js +375 -0
  144. package/dist/transport.d.ts +26 -0
  145. package/dist/transport.js +118 -0
  146. package/dist/work-dir.d.ts +11 -0
  147. package/dist/work-dir.js +69 -0
  148. package/dist/worktree-report.d.ts +10 -0
  149. package/dist/worktree-report.js +17 -0
  150. package/dist/worktrees.d.ts +16 -1
  151. package/dist/worktrees.js +62 -17
  152. package/package.json +4 -4
  153. package/skill/firefunc/SKILL.md +4 -3
package/dist/job.js CHANGED
@@ -1,19 +1,28 @@
1
+ import { declaredChecksOf, makeLocalChecksReader } from './local-checks.js';
2
+ import { endedState, reportWorktree } from './worktree-report.js';
1
3
  import { mkdtempSync, rmSync, existsSync, mkdirSync, writeFileSync, copyFileSync, appendFileSync, chmodSync, readdirSync, } from 'node:fs';
2
4
  import { readFile } from 'node:fs/promises';
3
- import { homedir, tmpdir } from 'node:os';
5
+ import { homedir, hostname } from 'node:os';
6
+ import { diskOf } from './resources.js';
7
+ import { cargoTargetEnv } from './build-caches.js';
8
+ import { checkpointEveryMs, readCheckpoint, restoreCheckpoint, resumeFromCheckpointBrief, saveCheckpoint, } from './checkpoint.js';
9
+ import { setWorkDir, workRoot, workTempEnv } from './work-dir.js';
10
+ import { makeRunTemp, removeRunTemp } from './run-temp.js';
4
11
  import { join, basename, dirname, relative, sep } from 'node:path';
5
12
  import {} from 'node:child_process';
6
13
  import { exec, execOut, spawnBackground, killProcessTree } from './exec.js';
7
14
  import { REPORTED_SUMMARY_MAX, cutText } from './api.js';
8
15
  import { configPath, loadConfig, saveConfig } from './config.js';
9
- import { cloneRepo, openDraftPr, pushBranch, pushFlags, redact } from './git-auth.js';
16
+ import { cloneRepo, endedPullRequestForHead, endedPullRequestSentence, gitAuthEnv, openDraftPr, PUSH_TIMEOUT_MS, pushBranch, pushFlags, redact, } from './git-auth.js';
10
17
  import { createActivityReporter, redact as oneLine, stripWorktree } from './activity.js';
11
18
  import { errorLine, foldHome, promisesLaterCheck, pushRefusal, setupCommandName, setupReason, stripCode, } from './keep-local.js';
12
- import { FULL_SHA, changeReads, hardFirst, refusesPush, scanAddedLines, secretRefusal, uniqueHits, } from './secret-scan.js';
19
+ import { FULL_SHA, changeReads, hardFirst, refusesPush, scanAddedLines, secretFixBrief, secretFixRead, secretRefusal, uniqueHits, } from './secret-scan.js';
13
20
  import { isNetworkError, networkFailureHint, waitForNetwork, withNetworkRetry } from './network.js';
21
+ import { firefuncReconnectedBrief, mcpServersFailedAtStart } from './mcp-init.js';
14
22
  import { endedOnRefusal, modelDeclinedSentence } from './declined.js';
15
23
  import { endedBySignal, stoppedSentence } from './stopped.js';
16
- import { AGENT_PR_FILE, changeKind, parseAgentPullRequest, pullRequestBody, pullRequestTitle, } from './pr-title.js';
24
+ import { isStopped, stoppedByPersonSentence, trackRunGroup, untrackRunGroup } from './run-stops.js';
25
+ import { AGENT_PR_FILE, changeKind, parseAgentPullRequest, pullRequestBody, provenanceTrailers, withProvenanceFooter, pullRequestTitle, } from './pr-title.js';
17
26
  import { savePendingResult } from './pending.js';
18
27
  import { runnerDir } from './config.js';
19
28
  import { attemptUsage, combineUsage, describeUsage, } from './usage.js';
@@ -25,17 +34,22 @@ import { writeSkills, writtenSkillPaths } from './skills.js';
25
34
  import { ATTACH_FOLDER, attachLimitsOf, prepareAttachFolder, uploadRunAttachments, } from './run-attachments.js';
26
35
  import { REFERENCE_FOLDER, mergeWritten, writeReferenceFiles, } from './reference-files.js';
27
36
  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';
37
+ import { claudeApiKeyNow, fallbackKey, startFallback, startKeySpent } from './api-fallback.js';
38
+ import { ENGINE_KEY_VARS, jobSignIn, keySourceOf } from './sign-in.js';
39
+ import { ACCOUNT_RETRY_FIRST_MS, accountBlock, accountProblemOf, cannotWorkSentence, } from './engine-account.js';
40
+ import { createKeyedMutex, deviceLockDir, ensureDeviceScript, ensureHeavyScript, heavyLockDir, heavySlots, heavyTag, withHeavyLock, } from './locks.js';
30
41
  import { getAdapter, stripForeignEngineCreds } from './engines/index.js';
31
42
  import { mcpFormatForEngine, prepareMcp } from './mcp.js';
32
43
  import { continueToFinishBrief, engineRules } from './brief.js';
44
+ import { BRIEF_FOLDER, fenceBrief, prepareBriefFolder } from './brief-file.js';
45
+ import { prepareReleaseFolder, stageDraftRelease } from './release-draft.js';
33
46
  import { limitSentence } from './limit.js';
34
47
  import { cannotRunUnattendedSentence, unattendedContext } from './unattended.js';
35
48
  import { cutFor, dropCut, keepUntil, promptHash, resumeAfterResetBrief, saveCut, } from './cut.js';
36
- import { liveWorktrees, updateHeld } from './held.js';
37
- import { killOrphans, reviewCopiesOf, trackEngineGroup, untrackEngineGroup } from './orphans.js';
38
- import { canonicalPath, removeRunnerWorktree, staleHolder } from './worktrees.js';
49
+ import { updateHeld } from './held.js';
50
+ import { deviceSerials, emulatorBudget, releaseDeviceHolds } from './device-lease.js';
51
+ import { killOrphans, reviewCopiesOf, signalGroupSparingDevices, trackEngineGroup, untrackEngineGroup, } from './orphans.js';
52
+ import { branchHeldSentence, branchHolderOf, removeRunnerWorktree, staleHolder, } from './worktrees.js';
39
53
  import { detailOf, startRunTrail, trailOff } from './trail/index.js';
40
54
  import { RUNNER_VERSION } from './version.js';
41
55
  function log(msg) {
@@ -174,18 +188,64 @@ function unfinishedSentence(engineName, open, changeRun, continued) {
174
188
  '. Re-run the task; if it happens again, look in the agent’s instruction and skills for anything that runs its checks in the background.');
175
189
  }
176
190
  function resumeBrief(prompt, why = 'network') {
177
- const what = why === 'limit'
178
- ? "was stopped by the plan's usage limit, which has now reset, and that session could not be continued"
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';
191
+ const what = why === 'plan'
192
+ ? "was stopped because the machine's API key ran out of credit; this session continues on the plan"
193
+ : why === 'limit'
194
+ ? "was stopped by the plan's usage limit, which has now reset, and that session could not be continued"
195
+ : why === 'api'
196
+ ? "was stopped by the plan's usage limit; this session continues on the machine's API key"
197
+ : 'was cut short by a network outage';
182
198
  return (`Your previous session on this task ${what}. The worktree ` +
183
199
  'still holds everything you did; look at `git status` and `git diff`, continue from ' +
184
200
  'there, and finish the task. The original brief follows.\n\n' +
185
201
  prompt);
186
202
  }
203
+ const KEPT_FOR_PUSH = 'The work is committed and kept on this machine for a day: Re-run continues the session in the same worktree and pushes it again, instead of doing the work over.';
204
+ const SESSION_ID_IN_STREAM = /"session_id"\s*:\s*"([A-Za-z0-9-]{8,80})"/;
205
+ const DISK_FULL_WORDS = /no space left on device|\benospc\b|disk quota exceeded|\bedquot\b/i;
206
+ const DISK_NEARLY_FULL_BYTES = 1024 ** 3;
207
+ export function diskFullFailure(stderr, folder, free = (dir) => diskOf(dir)?.freeBytes ?? null) {
208
+ const said = DISK_FULL_WORDS.test(stderr);
209
+ const unableToWrite = /unable to (?:write|create)|could not (?:write|create)/i.test(stderr);
210
+ const freeBytes = free(folder);
211
+ const nearlyFull = freeBytes !== null && freeBytes < DISK_NEARLY_FULL_BYTES;
212
+ if (!said && !(unableToWrite && nearlyFull))
213
+ return null;
214
+ const left = freeBytes !== null ? ` (${(freeBytes / 1024 ** 3).toFixed(1)} GB free)` : '';
215
+ const detail = `the disk is full${left}`;
216
+ return {
217
+ error: `git worktree add failed: this machine could not create the run's folder because its disk is full${left}. Nothing was changed, and FireFunc runs the task again when a machine has room. ` +
218
+ 'Fix: free space on this machine (old worktrees, build output, caches), or pin the agent to another machine.',
219
+ limit: { kind: 'machine', detail },
220
+ };
221
+ }
222
+ export const STOPPED_HOLDER_WAIT_MS = 90_000;
223
+ export async function waitForStoppedHolder(runnerDir, worktree, holder, deps = {}) {
224
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
225
+ const pollMs = deps.pollMs ?? 3_000;
226
+ let left = deps.waitMs ?? STOPPED_HOLDER_WAIT_MS;
227
+ let now = holder;
228
+ while (now && left > 0) {
229
+ await sleep(pollMs);
230
+ left -= pollMs;
231
+ now = branchHolderOf(runnerDir, worktree);
232
+ }
233
+ return now;
234
+ }
187
235
  export async function runJob(job, cfg, api, viewer, opts) {
188
236
  api = blankingApi(api);
237
+ setWorkDir(cfg.workDir);
238
+ const heartbeatMs = opts?.heartbeatMs ?? 5 * 60_000;
239
+ const jobHeartbeat = setInterval(() => void Promise.resolve(api.event(job.runId, 'heartbeat')).catch(() => { }), heartbeatMs);
240
+ jobHeartbeat.unref?.();
241
+ try {
242
+ return await runJobBody(job, cfg, api, viewer, opts);
243
+ }
244
+ finally {
245
+ clearInterval(jobHeartbeat);
246
+ }
247
+ }
248
+ async function runJobBody(job, cfg, api, viewer, opts) {
189
249
  const now = opts?.now ?? (() => new Date());
190
250
  const rdir = runnerDir();
191
251
  const trailWriteTools = new Set();
@@ -212,8 +272,10 @@ export async function runJob(job, cfg, api, viewer, opts) {
212
272
  if (trail)
213
273
  void trail.runStarted(job.repo ? { repo: job.repo } : {});
214
274
  let secretScan;
275
+ const localChecks = makeLocalChecksReader(declaredChecksOf(job.checks));
215
276
  let usage;
216
277
  let readHead;
278
+ let restoredFrom = null;
217
279
  let openCommandAtEnd = false;
218
280
  let attachFolder = null;
219
281
  let attachmentsSent = false;
@@ -248,8 +310,47 @@ export async function runJob(job, cfg, api, viewer, opts) {
248
310
  log(`the pictures for the ticket were not uploaded: ${e.message}`);
249
311
  });
250
312
  };
313
+ let releaseFolder = null;
314
+ let releaseBase = null;
315
+ let releaseStaged = false;
316
+ const stageRelease = async (status) => {
317
+ if (releaseStaged || !releaseFolder || !job.release || !job.repo)
318
+ return null;
319
+ if (status !== 'pr_opened' && status !== 'no_pr')
320
+ return null;
321
+ releaseStaged = true;
322
+ try {
323
+ const cred = await api.gitCredential(job.runId);
324
+ if (!cred) {
325
+ return {
326
+ staged: false,
327
+ why: 'FireFunc gave this machine no repository token to stage the draft release with',
328
+ tag: null,
329
+ };
330
+ }
331
+ return await stageDraftRelease({
332
+ repo: job.repo,
333
+ base: releaseBase,
334
+ offer: job.release,
335
+ dir: releaseFolder,
336
+ cred,
337
+ log,
338
+ });
339
+ }
340
+ catch (e) {
341
+ log(`the release was not staged: ${e.message}`);
342
+ return {
343
+ staged: false,
344
+ why: 'the machine could not get a repository token to stage the draft release',
345
+ tag: null,
346
+ };
347
+ }
348
+ };
251
349
  const report = async (reported) => {
252
350
  await sendAttachments(reported.status);
351
+ const release = reported.release ? null : await stageRelease(reported.status);
352
+ if (release)
353
+ reported = { ...reported, release };
253
354
  await trail
254
355
  ?.finish({
255
356
  status: reported.status,
@@ -259,6 +360,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
259
360
  let payload = blankSecretsDeep(secretScan && !reported.secretScan ? { ...reported, secretScan } : reported);
260
361
  if (usage && !payload.usage)
261
362
  payload = { ...payload, usage };
363
+ const checks = localChecks.report();
364
+ if (checks && !payload.localChecks)
365
+ payload = { ...payload, localChecks: checks };
262
366
  if (readHead && !payload.readHead)
263
367
  payload = { ...payload, readHead };
264
368
  if (openCommandAtEnd && !payload.openCommandAtEnd) {
@@ -321,12 +425,35 @@ export async function runJob(job, cfg, api, viewer, opts) {
321
425
  if (spent) {
322
426
  const limit = { kind: 'plan', resetsAt: spent.resetsAt };
323
427
  log(`${adapter.displayName}'s plan limit is spent until ${spent.until} — answering ${job.runId} without starting it`);
324
- return report({
428
+ return await report({
325
429
  status: 'failed',
326
430
  error: limitSentence(adapter.displayName, limit, false),
327
431
  limit: { kind: 'plan', resetsAt: limit.resetsAt },
328
432
  });
329
433
  }
434
+ if (job.signIn === 'plan' || job.signIn === 'key') {
435
+ const machine = cfg.name ?? hostname();
436
+ const said = opts?.signIn?.()[adapter.id] ??
437
+ (() => {
438
+ const source = keySourceOf(adapter.id, cfg, process.env, rdir);
439
+ return {
440
+ plan: 'unknown',
441
+ key: (ENGINE_KEY_VARS[adapter.id] ?? []).length === 0
442
+ ? 'none'
443
+ : source
444
+ ? 'found'
445
+ : 'missing',
446
+ };
447
+ })();
448
+ const how = jobSignIn(adapter.id, job.signIn, cfg, machine, said);
449
+ if (!how.ok) {
450
+ log(`${job.runId}: ${how.reason}`);
451
+ return await report({ status: 'failed', error: `${how.reason} ${how.fix}` });
452
+ }
453
+ cfg = how.cfg;
454
+ if (how.note)
455
+ log(`${job.runId}: signs in with ${how.note}`);
456
+ }
330
457
  const unattended = adapter.unattendedBlock?.({
331
458
  ...unattendedContext(cfg, job.permissionMode),
332
459
  ...opts?.unattended,
@@ -334,12 +461,22 @@ export async function runJob(job, cfg, api, viewer, opts) {
334
461
  if (unattended) {
335
462
  const sentence = cannotRunUnattendedSentence(adapter.displayName, unattended);
336
463
  log(`${job.runId}: ${sentence}`);
337
- return report({
464
+ return await report({
338
465
  status: 'failed',
339
466
  error: sentence,
340
467
  limit: { kind: 'machine', detail: unattended.detail },
341
468
  });
342
469
  }
470
+ const heldForAccount = opts?.account?.held(adapter.id) ?? null;
471
+ if (heldForAccount) {
472
+ const sentence = cannotWorkSentence(adapter.displayName, heldForAccount);
473
+ log(`${job.runId}: ${sentence}`);
474
+ return await report({
475
+ status: 'failed',
476
+ error: sentence,
477
+ limit: { kind: 'machine', detail: heldForAccount.detail },
478
+ });
479
+ }
343
480
  const engineRuns = step?.kind !== 'publish';
344
481
  const agentEnv = {};
345
482
  const carriedNotes = [];
@@ -357,10 +494,10 @@ export async function runJob(job, cfg, api, viewer, opts) {
357
494
  });
358
495
  }
359
496
  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.`);
497
+ return await 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
498
  }
362
499
  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}`);
500
+ return await 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
501
  }
365
502
  registerSecretValues(job.runId, got.env.filter((e) => e.secret).map((e) => ({ name: e.name, value: e.value })));
366
503
  for (const e of got.env)
@@ -432,7 +569,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
432
569
  rememberRepoPath(job.repo, dest, cfg);
433
570
  }
434
571
  else {
435
- return report({
572
+ return await report({
436
573
  status: 'failed',
437
574
  error: `Could not clone ${job.repo}: ${redact(cloned.stderr, cred.token).slice(0, 300)}`,
438
575
  });
@@ -441,7 +578,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
441
578
  }
442
579
  if (!repoPath && !toolsOnly) {
443
580
  log(`no local checkout for ${job.repo} and no credential to clone with`);
444
- return report({
581
+ return await report({
445
582
  status: 'failed',
446
583
  error: `Runner has no local checkout for ${job.repo} and could not obtain a ` +
447
584
  `credential to clone it. Either map it with \`firefunc-runner repo ` +
@@ -495,7 +632,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
495
632
  else if (parkStep && parkKept) {
496
633
  resumeCut = resumeFromParked(parkKept, promptHash(job.prompt));
497
634
  }
498
- else if (cutMatch && 'resume' in cutMatch && adapter.resumesSessions) {
635
+ else if (cutMatch &&
636
+ 'resume' in cutMatch &&
637
+ (adapter.resumesSessions || cutMatch.resume.sessionId === '')) {
499
638
  resumeCut = cutMatch.resume;
500
639
  }
501
640
  else if (cutMatch) {
@@ -520,6 +659,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
520
659
  const engineGroups = [];
521
660
  let worktree = null;
522
661
  let attachDir = null;
662
+ let runTemp = null;
523
663
  let mcp = null;
524
664
  let writtenSkills = { written: [], pathspecs: [] };
525
665
  const bgProcs = [];
@@ -585,7 +725,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
585
725
  secretScan = asReported(added);
586
726
  if (added.some(refusesPush)) {
587
727
  log(`secret scan for ${job.runId}: ${added.length} finding(s) — ${found(added)} — refusing to push`);
588
- return fail(secretRefusal(added, branch));
728
+ return await fail(secretRefusal(added, branch));
589
729
  }
590
730
  if (added.length > 0) {
591
731
  log(`secret scan for ${job.runId}: ${added.length} looser match(es) — ${found(added)} — pushing; ` +
@@ -621,7 +761,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
621
761
  if (s.keep) {
622
762
  const changes = await changesOf(scanIn, continuesBranch ? `origin/${branch}` : `origin/${base}`, branch);
623
763
  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.`);
764
+ return await 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.`);
625
765
  }
626
766
  const at = now();
627
767
  const saved = saveKept(rdir, {
@@ -649,11 +789,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
649
789
  activitySeq: activitySeen,
650
790
  });
651
791
  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.`);
792
+ return await 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
793
  }
654
794
  keepWorktree = true;
655
795
  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({
796
+ return await report({
657
797
  status: 'awaiting_approval',
658
798
  changes,
659
799
  head: scannedTip,
@@ -698,21 +838,24 @@ export async function runJob(job, cfg, api, viewer, opts) {
698
838
  .filter(Boolean);
699
839
  const leaked = stagedPaths.filter((l) => l === '.env' || l.endsWith('/.env') || (mcpStaged !== null && l === mcpStaged));
700
840
  if (leaked.length > 0) {
701
- return fail(`refusing to push: the commit contains ${leaked.join(', ')}, which can hold live credentials. ` +
841
+ return await fail(`refusing to push: the commit contains ${leaked.join(', ')}, which can hold live credentials. ` +
702
842
  `This is a FireFunc bug — please report it. Nothing was pushed.`);
703
843
  }
704
844
  const skillLeaked = writtenSkillPaths(stagedPaths, writtenSkills);
705
845
  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'} ` +
846
+ return await fail(`refusing to push: the agent added ${skillLeaked.join(', ')} to its commit — ` +
847
+ `${skillLeaked.some((p) => p.includes(ATTACH_FOLDER)) ? 'a picture for the ticket' : skillLeaked.some((p) => p.includes(REFERENCE_FOLDER)) ? 'a reference file' : skillLeaked.some((p) => p.includes(BRIEF_FOLDER)) ? 'the brief' : 'a skill'} ` +
708
848
  `FireFunc writes into the checkout for this run only and never commits. Nothing was ` +
709
849
  `pushed. Fix: tell the agent not to stage or commit anything under ` +
710
850
  `${skillLeaked[0].split('/').slice(0, -1).join('/')} (check its instruction and ` +
711
851
  `its skills for "git add -f" or "commit everything"), then re-run the task.`);
712
852
  }
713
853
  const pushFrom = worktree;
714
- const pushOnce = async () => gitCred
715
- ? pushBranch(pushFrom, branch, gitCred.repo, gitCred, { force: !continuesBranch })
854
+ const pushOnce = async (timeoutMs = PUSH_TIMEOUT_MS) => gitCred
855
+ ? pushBranch(pushFrom, branch, gitCred.repo, gitCred, {
856
+ force: !continuesBranch,
857
+ timeoutMs,
858
+ })
716
859
  : exec('git', [
717
860
  '-C',
718
861
  pushFrom,
@@ -721,23 +864,78 @@ export async function runJob(job, cfg, api, viewer, opts) {
721
864
  'origin',
722
865
  `${branch}:${branch}`,
723
866
  ], {
724
- timeoutMs: 120_000,
867
+ timeoutMs,
868
+ });
869
+ if (isStopped(job.runId))
870
+ return await fail(stoppedByPersonSentence(engineName, 'push'));
871
+ if (continuesBranch && gitCred) {
872
+ const ended = await endedPullRequestForHead({
873
+ repo: gitCred.repo,
874
+ head: branch,
875
+ cred: gitCred,
725
876
  });
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)
877
+ if (ended)
878
+ return await fail(endedPullRequestSentence(branch, ended, base || null));
879
+ }
880
+ let pushTimeoutMs = PUSH_TIMEOUT_MS;
881
+ const pushLanded = async () => {
882
+ const local = await exec('git', ['-C', pushFrom, 'rev-parse', `refs/heads/${branch}`]);
883
+ const head = local.code === 0 ? local.stdout.trim() : '';
884
+ if (!FULL_SHA.test(head))
885
+ return false;
886
+ const remote = await exec('git', ['-C', pushFrom, 'ls-remote', 'origin', `refs/heads/${branch}`], {
887
+ timeoutMs: 60_000,
888
+ ...(gitCred ? { env: gitAuthEnv(gitCred.token, gitCred.repo) } : {}),
889
+ });
890
+ return remote.code === 0 && remote.stdout.trim().split(/\s+/)[0] === head;
891
+ };
892
+ let push = await pushOnce(pushTimeoutMs);
893
+ for (let netTries = 0, slowTries = 0; push.code !== 0;) {
894
+ if (push.code === 124 && (await pushLanded())) {
895
+ log(`the push of ${branch} timed out, but the remote already holds its commit — pushed`);
896
+ push = { code: 0, stdout: '', stderr: '' };
731
897
  break;
732
- push = await pushOnce();
898
+ }
899
+ if (isNetworkError(push.stderr) && netTries < 3) {
900
+ netTries += 1;
901
+ log(`push failed because the network seems to be away — waiting for it (try ${netTries} of 3)`);
902
+ const back = await waitForNetwork({
903
+ probe: () => api.probe(),
904
+ maxWaitMs: 10 * 60_000,
905
+ log,
906
+ });
907
+ if (!back)
908
+ break;
909
+ }
910
+ else if (push.code === 124 && slowTries < 2) {
911
+ slowTries += 1;
912
+ log(`the push of ${branch} timed out after ${Math.round(pushTimeoutMs / 60_000)} min — a slow connection or a large push; sending the same commit again with ${Math.round((pushTimeoutMs * 3) / 60_000)} min`);
913
+ pushTimeoutMs *= 3;
914
+ }
915
+ else
916
+ break;
917
+ if (isStopped(job.runId))
918
+ return await fail(stoppedByPersonSentence(engineName, 'push'));
919
+ push = await pushOnce(pushTimeoutMs);
920
+ }
921
+ if (push.code === 124) {
922
+ log(`git push output for ${job.runId} (kept on this machine):\n${redact(push.stderr, gitCred?.token).slice(-4000)}`);
923
+ const kept = s.keepOnPushFailure?.() ?? false;
924
+ return await fail(`git push of ${branch} timed out three times (the last after ${Math.round(pushTimeoutMs / 60_000)} min) — the connection is too slow for this push. ` +
925
+ (kept
926
+ ? `${KEPT_FOR_PUSH} Fix: re-run the task once the connection is faster, or push ${branch} from the machine by hand and link the pull request to the task.`
927
+ : `The commit is still on this machine's checkout as ${branch}. ` +
928
+ 'Fix: re-run the task on a faster connection, or push that branch from the machine by hand and link the pull request to the task.'));
733
929
  }
734
930
  if (push.code !== 0) {
735
931
  const said = redact(push.stderr, gitCred?.token);
736
932
  log(`git push output for ${job.runId} (kept on this machine):\n${said.slice(-4000)}`);
737
933
  const refused = pushRefusal(said);
738
- return fail(refused
934
+ const kept = s.keepOnPushFailure?.() ?? false;
935
+ return await fail((refused
739
936
  ? `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.`);
937
+ : `git push failed (exit ${push.code}); its output stayed on the machine — the runner’s log shows it.`) +
938
+ (kept ? ` ${KEPT_FOR_PUSH} Fix what refused the push first.` : ''));
741
939
  }
742
940
  await trail?.pushed({ branch });
743
941
  if (secretScan && scannedTip && scanCoversPullRequest) {
@@ -747,9 +945,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
747
945
  else
748
946
  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
947
  }
750
- const body = agentText?.body
948
+ const body = withProvenanceFooter(agentText?.body
751
949
  ? `${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 });
950
+ : pullRequestBody(kind, engineName, job.externalId, { continuesBranch }), job);
951
+ if (isStopped(job.runId))
952
+ return await fail(stoppedByPersonSentence(engineName, 'pr'));
753
953
  if (gitCred) {
754
954
  const pr = await withNetworkRetry(() => openDraftPr({
755
955
  repo: gitCred.repo,
@@ -768,7 +968,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
768
968
  if (!('error' in pr)) {
769
969
  await api.event(job.runId, 'pr_opened', { url: pr.url, branch });
770
970
  log(`opened PR for ${job.runId}: ${pr.url}`);
771
- return report({
971
+ return await report({
772
972
  status: 'pr_opened',
773
973
  pr: {
774
974
  repo: job.repo ?? undefined,
@@ -782,7 +982,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
782
982
  }
783
983
  const why = redact(pr.error, gitCred.token);
784
984
  if (!(await hasGh(worktree)))
785
- return fail(why);
985
+ return await fail(why);
786
986
  log(`could not open the PR as FireFunc (${why}); falling back to gh`);
787
987
  }
788
988
  const createCwd = worktree;
@@ -841,14 +1041,14 @@ export async function runJob(job, cfg, api, viewer, opts) {
841
1041
  }
842
1042
  if (!resolved) {
843
1043
  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}` : ''}. ` +
1044
+ return await fail(`The branch ${branch} was pushed, but the pull request could not be created${why ? `: ${why}` : ''}. ` +
845
1045
  `Open it from that branch on GitHub (FireFunc will link it to this task), or re-run.`);
846
1046
  }
847
1047
  const url = resolved.url;
848
1048
  const number = resolved.number;
849
1049
  await api.event(job.runId, 'pr_opened', { url, branch });
850
1050
  log(`opened PR for ${job.runId}: ${url}`);
851
- return report({
1051
+ return await report({
852
1052
  status: 'pr_opened',
853
1053
  pr: { repo: job.repo ?? undefined, number, url: url || undefined, branch, summary: title },
854
1054
  ...(summary ? { summary: reportedSummary(summary) } : {}),
@@ -857,10 +1057,10 @@ export async function runJob(job, cfg, api, viewer, opts) {
857
1057
  let base = '';
858
1058
  try {
859
1059
  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.');
1060
+ return await fail('The session this attempt kept on this machine for a person’s answer is no longer here (its kept folder was removed, or the runner was reinstalled), so it cannot go on. Re-run the task.');
861
1061
  }
862
1062
  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.');
1063
+ return await 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.');
864
1064
  }
865
1065
  if (step?.kind === 'publish' && kept) {
866
1066
  worktree = kept.worktree;
@@ -877,7 +1077,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
877
1077
  `refs/heads/${kept.branch}^{commit}`,
878
1078
  ]).catch(() => '');
879
1079
  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.`);
1080
+ return await 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
1081
  }
882
1082
  log(`approved: pushing the change kept for ${job.runId} (${kept.branch}) and opening its pull request`);
883
1083
  return await ship({
@@ -897,19 +1097,19 @@ export async function runJob(job, cfg, api, viewer, opts) {
897
1097
  log(`continuing the session a plan limit cut for this task, in ${worktree}`);
898
1098
  }
899
1099
  else if (toolsOnly) {
900
- worktree = mkdtempSync(join(tmpdir(), 'firefunc-tools-'));
1100
+ worktree = mkdtempSync(join(workRoot(), 'firefunc-tools-'));
901
1101
  updateHeld(rdir, job.runId, { scratch: [worktree] });
902
1102
  writeSkills(worktree, job.skills, log);
903
1103
  const refs = await writeRefs(worktree);
904
1104
  if (refs && 'failure' in refs)
905
- return fail(refs.failure);
1105
+ return await fail(refs.failure);
906
1106
  await exec('git', ['-C', worktree, 'init', '--quiet']);
907
1107
  log(`no repository for ${job.runId} — the agent works through its tools in ${worktree}`);
908
1108
  }
909
1109
  else {
910
1110
  await api.event(job.runId, 'cloning', { repo: job.repo, branch });
911
1111
  const checkout = repoPath;
912
- const prep = await gitMutex.run(checkout, async () => {
1112
+ const prepare = () => gitMutex.run(checkout, async () => {
913
1113
  await exec('git', ['-C', checkout, 'fetch', 'origin', '--quiet'], { timeoutMs: 120_000 });
914
1114
  if (resumeCut) {
915
1115
  const known = await exec('git', ['-C', resumeCut.worktree, 'rev-parse', '--git-dir']);
@@ -920,6 +1120,8 @@ export async function runJob(job, cfg, api, viewer, opts) {
920
1120
  add: { code: 0, stdout: '', stderr: '' },
921
1121
  branchMissing: false,
922
1122
  startPoint: '',
1123
+ heldBy: null,
1124
+ holder: null,
923
1125
  };
924
1126
  }
925
1127
  log(`the worktree the plan limit's cut session kept is no longer a worktree of ${job.repo} — starting over`);
@@ -948,29 +1150,71 @@ export async function runJob(job, cfg, api, viewer, opts) {
948
1150
  `refs/remotes/origin/${branch}`,
949
1151
  ]);
950
1152
  if (has.code !== 0) {
951
- return { base: b, wt: '', add: has, branchMissing: true, startPoint };
1153
+ return {
1154
+ base: b,
1155
+ wt: '',
1156
+ add: has,
1157
+ branchMissing: true,
1158
+ startPoint,
1159
+ heldBy: null,
1160
+ holder: null,
1161
+ };
952
1162
  }
953
1163
  startPoint = `origin/${branch}`;
954
1164
  }
955
- const wt = mkdtempSync(join(tmpdir(), 'firefunc-'));
1165
+ let wt;
1166
+ try {
1167
+ wt = mkdtempSync(join(workRoot(), 'firefunc-'));
1168
+ }
1169
+ catch (err) {
1170
+ const msg = err.message ?? String(err);
1171
+ return {
1172
+ base: b,
1173
+ wt: '',
1174
+ add: {
1175
+ code: 1,
1176
+ stdout: '',
1177
+ stderr: `fatal: could not create the worktree folder: ${msg}`,
1178
+ },
1179
+ branchMissing: false,
1180
+ startPoint,
1181
+ heldBy: null,
1182
+ holder: null,
1183
+ };
1184
+ }
956
1185
  const add = () => exec('git', ['-C', checkout, 'worktree', 'add', '--force', '-B', branch, wt, startPoint], {
957
1186
  timeoutMs: 120_000,
958
1187
  });
959
1188
  let result = await add();
960
1189
  const holder = result.code !== 0 ? staleHolder(result.stderr) : null;
1190
+ let heldBy = null;
961
1191
  if (holder) {
962
- const live = new Set([...liveWorktrees(rdir)].map(canonicalPath));
963
- if (!live.has(canonicalPath(holder))) {
1192
+ heldBy = branchHolderOf(rdir, holder);
1193
+ if (!heldBy) {
964
1194
  log(`a worktree a stopped runner left holds ${branch} (${holder}) — removing it and trying again`);
965
1195
  await removeRunnerWorktree(checkout, holder, log);
966
1196
  result = await add();
967
1197
  }
968
1198
  }
969
- return { base: b, wt, add: result, branchMissing: false, startPoint };
1199
+ return { base: b, wt, add: result, branchMissing: false, startPoint, heldBy, holder };
970
1200
  });
1201
+ let prep = await prepare();
1202
+ if (prep.add.code !== 0 &&
1203
+ prep.heldBy?.kind === 'live' &&
1204
+ prep.heldBy.runId &&
1205
+ prep.holder &&
1206
+ isStopped(prep.heldBy.runId)) {
1207
+ log(`${branch} is held by ${prep.heldBy.runId}, which a person stopped — waiting for it to end`);
1208
+ if (!(await waitForStoppedHolder(rdir, prep.holder, prep.heldBy))) {
1209
+ if (prep.wt)
1210
+ rmSync(prep.wt, { recursive: true, force: true });
1211
+ prep = await prepare();
1212
+ }
1213
+ }
971
1214
  base = prep.base;
1215
+ releaseBase = prep.base || null;
972
1216
  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. ` +
1217
+ return await 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
1218
  `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.`);
975
1219
  }
976
1220
  worktree = prep.wt;
@@ -990,17 +1234,41 @@ export async function runJob(job, cfg, api, viewer, opts) {
990
1234
  if (FULL_SHA.test(sha))
991
1235
  readHead = sha;
992
1236
  }
1237
+ if (prep.add.code !== 0 && prep.heldBy) {
1238
+ log(`git worktree add output for ${job.runId} (kept on this machine):\n${prep.add.stderr}`);
1239
+ return await fail(branchHeldSentence(branch, prep.heldBy));
1240
+ }
993
1241
  if (prep.add.code !== 0) {
994
1242
  log(`git worktree add output for ${job.runId} (kept on this machine):\n${prep.add.stderr}`);
1243
+ const full = diskFullFailure(prep.add.stderr, workRoot());
1244
+ if (full)
1245
+ return await report({ status: 'failed', ...full });
995
1246
  const said = pushRefusal(prep.add.stderr);
996
- return fail(said
1247
+ return await fail(said
997
1248
  ? `git worktree add failed: ${oneLine(said, 400)}`
998
1249
  : `git worktree add failed (exit ${prep.add.code}); its output stayed on the machine — the runner’s log shows it.`);
999
1250
  }
1251
+ const saved = readCheckpoint(job.checkpoint);
1252
+ if (saved && !resumeCut && !continuesBranch && !askFirst && !step && !parkStep) {
1253
+ const cred = await api.gitCredential(job.runId).catch(() => null);
1254
+ const restored = await restoreCheckpoint({
1255
+ worktree,
1256
+ ref: saved.ref,
1257
+ sha: saved.sha,
1258
+ env: cred ? gitAuthEnv(cred.token, job.repo) : {},
1259
+ });
1260
+ if (restored) {
1261
+ restoredFrom = saved;
1262
+ log(`${job.runId} goes on from the work saved at ${saved.ref} (${saved.sha.slice(0, 8)})`);
1263
+ }
1264
+ else {
1265
+ log(`${job.runId}: the saved work at ${saved.ref} could not be fetched — starting from ${base}`);
1266
+ }
1267
+ }
1000
1268
  }
1001
1269
  const attachPaths = [];
1002
1270
  if (job.attachments?.length) {
1003
- attachDir = mkdtempSync(join(tmpdir(), 'firefunc-attach-'));
1271
+ attachDir = mkdtempSync(join(workRoot(), 'firefunc-attach-'));
1004
1272
  updateHeld(rdir, job.runId, { scratch: [attachDir] });
1005
1273
  mkdirSync(attachDir, { recursive: true });
1006
1274
  job.attachments.forEach((att, i) => {
@@ -1023,9 +1291,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
1023
1291
  .join('\n')}\n\n`
1024
1292
  : '';
1025
1293
  const runEnv = {
1294
+ ...cargoTargetEnv(cfg, rdir, job.repo),
1026
1295
  ...cfg.claudeEnv,
1027
1296
  ...(cfg.claudeCodeOAuthToken ? { CLAUDE_CODE_OAUTH_TOKEN: cfg.claudeCodeOAuthToken } : {}),
1028
1297
  ...(opts?.devServerPort ? { PORT: String(opts.devServerPort) } : {}),
1298
+ ...workTempEnv(),
1029
1299
  };
1030
1300
  if (opts?.devServerPort && cfg.backgroundCommands?.length) {
1031
1301
  log(`session dev-server PORT=${opts.devServerPort} (parallel-safe)`);
@@ -1063,7 +1333,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1063
1333
  writtenSkills = writeSkills(worktree, job.skills, log);
1064
1334
  const refs = await writeRefs(worktree);
1065
1335
  if (refs && 'failure' in refs)
1066
- return fail(refs.failure);
1336
+ return await fail(refs.failure);
1067
1337
  if (refs)
1068
1338
  writtenSkills = mergeWritten(writtenSkills, refs);
1069
1339
  }
@@ -1074,14 +1344,39 @@ export async function runJob(job, cfg, api, viewer, opts) {
1074
1344
  writtenSkills = mergeWritten(writtenSkills, prepared);
1075
1345
  }
1076
1346
  }
1347
+ if (job.release && job.repo && !toolsOnly && worktree) {
1348
+ const prepared = prepareReleaseFolder(worktree, log);
1349
+ if (prepared.dir) {
1350
+ releaseFolder = prepared.dir;
1351
+ writtenSkills = mergeWritten(writtenSkills, prepared);
1352
+ }
1353
+ }
1077
1354
  const heavyLock = !toolsOnly && job.repo && cfg.heavyLock !== false ? heavyLockDir(rdir, job.repo) : null;
1078
1355
  const heavyHelper = heavyLock ? ensureHeavyScript(rdir) : null;
1356
+ let briefSeq = 0;
1357
+ let briefDir;
1358
+ const buildInvocation = (c) => fenceBrief(adapter.buildInvocation(c), c.prompt, {
1359
+ seq: ++briefSeq,
1360
+ log,
1361
+ folder: () => {
1362
+ if (briefDir === undefined) {
1363
+ const prepared = worktree ? prepareBriefFolder(worktree, log) : null;
1364
+ briefDir = prepared?.dir ?? null;
1365
+ if (prepared?.dir)
1366
+ writtenSkills = mergeWritten(writtenSkills, prepared);
1367
+ }
1368
+ return briefDir;
1369
+ },
1370
+ }).invocation;
1371
+ const slots = heavySlots(cfg.heavySlots);
1079
1372
  const deviceHelper = heavyHelper ? ensureDeviceScript(rdir) : null;
1080
1373
  const heavily = (fn) => heavyLock
1081
1374
  ? withHeavyLock(heavyLock, fn, {
1082
1375
  label: `setup of ${job.runId}`,
1376
+ slots,
1377
+ tag: heavyTag(job.runId),
1083
1378
  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`),
1379
+ onWait: (holder, ahead) => log(`every heavy slot in ${job.repo} is in use (${slots} at once${holder ? `, pid ${holder}` : ''}; ${ahead} waiting ahead) — setup waits its turn`),
1085
1380
  })
1086
1381
  : fn();
1087
1382
  const setupMs = (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000;
@@ -1106,7 +1401,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1106
1401
  const fold = (text) => foldHome(stripWorktree(text, checkout), homedir());
1107
1402
  const why = setupReason(fold(r.stderr), fold(r.stdout));
1108
1403
  const said = why ? oneLine(why, 200).replace(/[.\s]+$/, '') : '';
1109
- return fail(`Setup command failed (exit ${r.code}): ${setupCommandName(cmd)}` +
1404
+ return await fail(`Setup command failed (exit ${r.code}): ${setupCommandName(cmd)}` +
1110
1405
  `${said ? ` — ${said}` : ''}. ` +
1111
1406
  '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
1407
  }
@@ -1123,8 +1418,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
1123
1418
  bgProcs.push(spawnBackground(cmd, { cwd: worktree, env: runEnv }));
1124
1419
  }
1125
1420
  await api.event(job.runId, 'fixing', { title: job.title });
1421
+ await reportWorktree(api, job.runId, worktree, 'live');
1126
1422
  const mode = job.permissionMode ?? cfg.permissionMode ?? 'bypassPermissions';
1127
- const model = job.model ?? cfg.model ?? null;
1423
+ const model = (phase === 'plan' && job.planModel ? job.planModel : null) ?? job.model ?? cfg.model ?? null;
1128
1424
  const effort = job.effort ?? cfg.effort ?? null;
1129
1425
  const ultracode = effort === 'ultracode';
1130
1426
  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';
@@ -1133,9 +1429,12 @@ export async function runJob(job, cfg, api, viewer, opts) {
1133
1429
  heavy: heavyHelper !== null,
1134
1430
  device: deviceHelper !== null,
1135
1431
  attach: attachFolder !== null,
1432
+ release: releaseFolder !== null ? (job.release ?? null) : null,
1433
+ toolsOnly,
1136
1434
  });
1137
1435
  const carriedNote = carriedNotes.length ? `${carriedNotes.join('\n\n')}\n\n` : '';
1138
- const prompt = rules +
1436
+ const prompt = (restoredFrom ? resumeFromCheckpointBrief(restoredFrom.at) : '') +
1437
+ rules +
1139
1438
  observeNote +
1140
1439
  attachNote +
1141
1440
  carriedNote +
@@ -1158,6 +1457,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
1158
1457
  }
1159
1458
  log(mcp ? `mcp: ${mcp.logLine}` : 'mcp: no server was injected for this run');
1160
1459
  }
1460
+ const temp = makeRunTemp(job.runId);
1461
+ if (temp) {
1462
+ runTemp = temp.dir;
1463
+ updateHeld(rdir, job.runId, { scratch: [temp.dir] });
1464
+ }
1161
1465
  const ctx = {
1162
1466
  prompt,
1163
1467
  model,
@@ -1171,12 +1475,27 @@ export async function runJob(job, cfg, api, viewer, opts) {
1171
1475
  isWin,
1172
1476
  runEnv: {
1173
1477
  ...stripForeignEngineCreds(runEnv, adapter.id),
1478
+ ...workTempEnv(),
1479
+ ...(temp?.env ?? {}),
1174
1480
  ...agentEnv,
1175
1481
  ...(heavyHelper && heavyLock
1176
- ? { FIREFUNC_HEAVY: heavyHelper, FIREFUNC_HEAVY_LOCK: heavyLock }
1482
+ ? {
1483
+ FIREFUNC_HEAVY: heavyHelper,
1484
+ FIREFUNC_HEAVY_LOCK: heavyLock,
1485
+ FIREFUNC_HEAVY_SLOTS: String(slots),
1486
+ FIREFUNC_HEAVY_TAG: heavyTag(job.runId),
1487
+ }
1177
1488
  : {}),
1178
1489
  ...(deviceHelper
1179
- ? { FIREFUNC_DEVICE: deviceHelper, FIREFUNC_DEVICE_LOCK: deviceLockDir(rdir) }
1490
+ ? {
1491
+ FIREFUNC_DEVICE: deviceHelper,
1492
+ FIREFUNC_DEVICE_LOCK: deviceLockDir(rdir),
1493
+ FIREFUNC_DEVICE_SESSION: job.runId,
1494
+ FIREFUNC_DEVICE_EMULATORS: String(emulatorBudget(cfg.maxEmulators)),
1495
+ ...(deviceSerials(cfg.devices)
1496
+ ? { FIREFUNC_DEVICE_SERIALS: deviceSerials(cfg.devices) }
1497
+ : {}),
1498
+ }
1180
1499
  : {}),
1181
1500
  },
1182
1501
  cfg,
@@ -1200,19 +1519,22 @@ export async function runJob(job, cfg, api, viewer, opts) {
1200
1519
  prompt: reviseBrief(revising.note, revising.round),
1201
1520
  }
1202
1521
  : { ...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;
1522
+ : resumeCut && !(resumeCut.sessionId && adapter.resumesSessions)
1523
+ ?
1524
+ { ...ctx, prompt: resumeBrief(ctx.prompt, 'limit') }
1525
+ : resumeCut
1526
+ ? {
1527
+ ...ctx,
1528
+ resumeSessionId: resumeCut.sessionId,
1529
+ prompt: resumeAfterResetBrief(prompt, promptHash(job.prompt) !== resumeCut.promptHash, resumeCut.reason),
1530
+ }
1531
+ : ctx;
1210
1532
  let inv;
1211
1533
  try {
1212
- inv = adapter.buildInvocation(firstCtx);
1534
+ inv = buildInvocation(firstCtx);
1213
1535
  }
1214
1536
  catch (e) {
1215
- return fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
1537
+ return await fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
1216
1538
  }
1217
1539
  const engineName = adapter.displayName;
1218
1540
  log(`running ${inv.bin} (${engineName}) on ${toolsOnly ? 'no repository — tools only' : `${job.repo} (${branch})`} — model=${model ?? 'default'} effort=${effort ?? 'default'} mode=${mode}`);
@@ -1227,20 +1549,49 @@ export async function runJob(job, cfg, api, viewer, opts) {
1227
1549
  for (const name of mcp?.writeToolNames ?? [])
1228
1550
  trailWriteTools.add(name);
1229
1551
  const activityParser = makeStreamJsonParser(activity.push, { toolResults: true });
1552
+ let heldSession = null;
1553
+ const noteSession = (chunk) => {
1554
+ if (!adapter.resumesSessions || parkStep || step)
1555
+ return;
1556
+ const id = SESSION_ID_IN_STREAM.exec(chunk)?.[1];
1557
+ if (!id || id === heldSession)
1558
+ return;
1559
+ heldSession = id;
1560
+ updateHeld(rdir, job.runId, {
1561
+ resume: {
1562
+ workItemId: job.workItemId,
1563
+ engine: adapter.id,
1564
+ sessionId: id,
1565
+ repo: job.repo ?? null,
1566
+ branch: toolsOnly ? '' : branch,
1567
+ base,
1568
+ repoPath: toolsOnly ? null : (repoPath ?? null),
1569
+ ...(readHead ? { readHead } : {}),
1570
+ promptHash: promptHash(job.prompt),
1571
+ review,
1572
+ toolsOnly,
1573
+ continuesBranch,
1574
+ writtenSkills,
1575
+ },
1576
+ });
1577
+ };
1230
1578
  const onStdout = (chunk) => {
1579
+ noteSession(chunk);
1231
1580
  const shown = blankSecrets(chunk);
1232
1581
  printer?.(shown);
1233
1582
  viewer?.push(job.runId, shown);
1234
1583
  activityParser(chunk);
1235
1584
  trail?.feed(chunk);
1585
+ localChecks.feed(chunk);
1236
1586
  };
1237
1587
  if (printer) {
1238
1588
  log(`── live ${engineName} session (shown here only — never sent to FireFunc) ──`);
1239
1589
  }
1240
- const heartbeat = setInterval(() => void api.event(job.runId, 'heartbeat'), 5 * 60_000);
1241
1590
  const engineCwd = worktree;
1242
1591
  let engineMs = 0;
1243
1592
  const runEngineOnce = async (limitMs = timeoutMs) => {
1593
+ if (isStopped(job.runId))
1594
+ return { code: 143, stdout: '', stderr: '' };
1244
1595
  let group = 0;
1245
1596
  const started = Date.now();
1246
1597
  try {
@@ -1252,17 +1603,21 @@ export async function runJob(job, cfg, api, viewer, opts) {
1252
1603
  shell: inv.shell,
1253
1604
  onStdout,
1254
1605
  ownGroup: true,
1606
+ signalGroup: signalGroupSparingDevices,
1255
1607
  onSpawn: (pid) => {
1256
1608
  group = pid;
1257
1609
  engineGroups.push({ pgid: pid, startedAt: started });
1258
1610
  trackEngineGroup(pid);
1611
+ trackRunGroup(job.runId, pid);
1259
1612
  updateHeld(rdir, job.runId, { engineGroup: pid, engineStartedAt: started });
1260
1613
  },
1261
1614
  });
1262
1615
  }
1263
1616
  finally {
1264
- if (group)
1617
+ if (group) {
1265
1618
  untrackEngineGroup(group);
1619
+ untrackRunGroup(job.runId, group);
1620
+ }
1266
1621
  engineMs += Date.now() - started;
1267
1622
  }
1268
1623
  };
@@ -1302,9 +1657,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
1302
1657
  lastReport = u;
1303
1658
  sessions.push({ usage: u, session: adapter.sessionId?.(stdout) ?? null, continued });
1304
1659
  };
1305
- const limitOf = (stdout) => {
1660
+ const limitOf = (stdout, stderr = '') => {
1306
1661
  try {
1307
- return adapter.planLimit?.(stdout, now()) ?? null;
1662
+ return adapter.planLimit?.(stdout, now(), stderr) ?? null;
1308
1663
  }
1309
1664
  catch {
1310
1665
  return null;
@@ -1315,14 +1670,71 @@ export async function runJob(job, cfg, api, viewer, opts) {
1315
1670
  summary: adapter.summarize(stdout),
1316
1671
  stderr,
1317
1672
  });
1318
- let engineRun = await runEngine();
1673
+ const checkpointMs = !toolsOnly && !review && !askFirst && job.repo ? checkpointEveryMs(cfg.checkpointMinutes) : 0;
1674
+ let lastCheckpoint = null;
1675
+ let checkpointing = null;
1676
+ const checkpointNow = async () => {
1677
+ if (isStopped(job.runId) || !worktree || !job.repo)
1678
+ return;
1679
+ if (!existsSync(worktree)) {
1680
+ if (checkpointTimer)
1681
+ clearInterval(checkpointTimer);
1682
+ return;
1683
+ }
1684
+ const cred = await api.gitCredential(job.runId).catch(() => null);
1685
+ const saved = await saveCheckpoint({
1686
+ worktree,
1687
+ runId: job.runId,
1688
+ from: readHead ?? `origin/${base}`,
1689
+ excludes: [
1690
+ ':(exclude).env',
1691
+ ':(exclude).claude/skills',
1692
+ ':(exclude).firefunc',
1693
+ `:(exclude,literal)${AGENT_PR_FILE}`,
1694
+ ...writtenSkills.pathspecs,
1695
+ ],
1696
+ env: cred ? gitAuthEnv(cred.token, job.repo) : {},
1697
+ last: lastCheckpoint,
1698
+ }, { log });
1699
+ if (saved.tree)
1700
+ lastCheckpoint = { tree: saved.tree };
1701
+ if (saved.saved && !isStopped(job.runId)) {
1702
+ const at = now().toISOString();
1703
+ log(`saved ${job.runId}'s work to ${saved.ref} (${saved.sha.slice(0, 8)})`);
1704
+ await api.event(job.runId, 'checkpoint', { ref: saved.ref, sha: saved.sha, at });
1705
+ }
1706
+ else if (!saved.saved && saved.why !== 'unchanged') {
1707
+ log(`checkpoint of ${job.runId} not saved (${saved.why})`);
1708
+ }
1709
+ };
1710
+ const checkpointTimer = checkpointMs > 0
1711
+ ? setInterval(() => {
1712
+ if (checkpointing)
1713
+ return;
1714
+ checkpointing = checkpointNow()
1715
+ .catch(() => { })
1716
+ .finally(() => {
1717
+ checkpointing = null;
1718
+ });
1719
+ }, checkpointMs)
1720
+ : null;
1721
+ checkpointTimer?.unref();
1722
+ let engineRun;
1723
+ try {
1724
+ engineRun = await runEngine();
1725
+ }
1726
+ catch (err) {
1727
+ if (checkpointTimer)
1728
+ clearInterval(checkpointTimer);
1729
+ throw err;
1730
+ }
1319
1731
  meter(engineRun.stdout, false);
1320
1732
  if (resumeCut &&
1321
1733
  firstCtx.resumeSessionId &&
1322
1734
  engineRun.code !== 0 &&
1323
1735
  !adapter.sessionId?.(engineRun.stdout)) {
1324
1736
  log(`${engineName} could not continue the session a plan limit cut — starting a new session in the same worktree`);
1325
- inv = adapter.buildInvocation({
1737
+ inv = buildInvocation({
1326
1738
  ...ctx,
1327
1739
  prompt: parkBrief
1328
1740
  ? `${parkBrief}\n\n${ctx.prompt}`
@@ -1334,7 +1746,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1334
1746
  meter(engineRun.stdout, false);
1335
1747
  }
1336
1748
  for (let resumes = 0; resumes < 2 && engineRun.code !== 0; resumes++) {
1337
- if (limitOf(engineRun.stdout))
1749
+ if (limitOf(engineRun.stdout, engineRun.stderr))
1338
1750
  break;
1339
1751
  if (refused(engineRun.stdout, engineRun.stderr))
1340
1752
  break;
@@ -1354,16 +1766,76 @@ export async function runJob(job, cfg, api, viewer, opts) {
1354
1766
  break;
1355
1767
  }
1356
1768
  log(`the network is back — resuming ${engineName} in the same worktree`);
1357
- inv = adapter.buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt) });
1769
+ inv = buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt) });
1358
1770
  engineRun = await runEngine();
1359
1771
  meter(engineRun.stdout, false);
1360
1772
  }
1773
+ let firefuncAway = null;
1774
+ if (engineRun.code === 0 &&
1775
+ mcp?.serverIds.includes('firefunc') &&
1776
+ !parkStep &&
1777
+ !step &&
1778
+ !limitOf(engineRun.stdout, engineRun.stderr) &&
1779
+ !refused(engineRun.stdout, engineRun.stderr) &&
1780
+ mcpServersFailedAtStart(engineRun.stdout).includes('firefunc')) {
1781
+ log(`${engineName}'s session started without FireFunc's own tools — the firefunc MCP server failed to connect; checking the network before continuing it`);
1782
+ const back = (await api.probe()) ||
1783
+ (await waitForNetwork({ probe: () => api.probe(), maxWaitMs: 20 * 60_000, log }));
1784
+ if (!back) {
1785
+ log('the network did not come back within 20 minutes — giving up on this attempt');
1786
+ firefuncAway = 'network';
1787
+ }
1788
+ else {
1789
+ const again = adapter.resumesSessions
1790
+ ? (adapter.sessionId?.(engineRun.stdout) ?? null)
1791
+ : null;
1792
+ log(`continuing ${engineName}'s session once now that FireFunc can be reached`);
1793
+ inv = buildInvocation({
1794
+ ...ctx,
1795
+ prompt: again ? firefuncReconnectedBrief() : resumeBrief(ctx.prompt),
1796
+ ...(again ? { resumeSessionId: again } : {}),
1797
+ });
1798
+ engineRun = await runEngine();
1799
+ meter(engineRun.stdout, !!again);
1800
+ if (engineRun.code === 0 &&
1801
+ mcpServersFailedAtStart(engineRun.stdout).includes('firefunc')) {
1802
+ firefuncAway = 'still_failed';
1803
+ }
1804
+ }
1805
+ }
1361
1806
  {
1362
- const planCut = limitOf(engineRun.stdout);
1363
- if (planCut && adapter.id === 'claude_code' && fallbackKey(cfg, rdir)) {
1807
+ const planCut = limitOf(engineRun.stdout, engineRun.stderr);
1808
+ if (planCut &&
1809
+ adapter.id === 'claude_code' &&
1810
+ fallbackKey(cfg, rdir) &&
1811
+ !opts?.account?.held(adapter.id)) {
1364
1812
  const until = startFallback(planCut.resetsAt, rdir, now());
1365
1813
  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') });
1814
+ inv = buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt, 'api') });
1815
+ engineRun = await runEngine();
1816
+ meter(engineRun.stdout, false);
1817
+ }
1818
+ }
1819
+ if (adapter.id === 'claude_code' &&
1820
+ cfg.claudeUseApiKey === true &&
1821
+ cfg.claudeKeyToPlan === true &&
1822
+ claudeApiKeyNow(cfg, rdir, now()).why === 'opted-in' &&
1823
+ !opts?.account?.held(adapter.id)) {
1824
+ let closing;
1825
+ try {
1826
+ closing = adapter.ending?.(engineRun.stdout);
1827
+ }
1828
+ catch {
1829
+ closing = undefined;
1830
+ }
1831
+ const spentKey = accountProblemOf(closing, {
1832
+ billedKey: true,
1833
+ stderr: engineRun.code === 0 ? '' : engineRun.stderr,
1834
+ }) === 'api_key_no_credit';
1835
+ if (spentKey) {
1836
+ const until = startKeySpent(rdir, now());
1837
+ log(`${engineName}'s API key is out of credit — continuing on the plan until ${until.toISOString()}, in the same worktree`);
1838
+ inv = buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt, 'plan') });
1367
1839
  engineRun = await runEngine();
1368
1840
  meter(engineRun.stdout, false);
1369
1841
  }
@@ -1376,7 +1848,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1376
1848
  return [];
1377
1849
  }
1378
1850
  };
1379
- const endedOnItsAnswer = (r) => r.code === 0 && !limitOf(r.stdout) && !refused(r.stdout, r.stderr);
1851
+ const endedOnItsAnswer = (r) => r.code === 0 && !limitOf(r.stdout, r.stderr) && !refused(r.stdout, r.stderr);
1380
1852
  const parkNow = endedOnItsAnswer(engineRun) && (job.askPerson === true || phase === 'plan')
1381
1853
  ? await parkReasonFor({
1382
1854
  askPerson: job.askPerson === true,
@@ -1399,7 +1871,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1399
1871
  }
1400
1872
  else if ((open.length > 0 || promising) && toContinue) {
1401
1873
  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({
1874
+ inv = buildInvocation({
1403
1875
  ...ctx,
1404
1876
  prompt: continueToFinishBrief(open),
1405
1877
  resumeSessionId: toContinue,
@@ -1413,7 +1885,55 @@ export async function runJob(job, cfg, api, viewer, opts) {
1413
1885
  }
1414
1886
  openCommandAtEnd = open.length > 0;
1415
1887
  const unfinished = open.length > 0 || promising;
1416
- clearInterval(heartbeat);
1888
+ const stageArgs = [
1889
+ '-C',
1890
+ worktree,
1891
+ 'add',
1892
+ '-A',
1893
+ '--',
1894
+ '.',
1895
+ ':(exclude).env',
1896
+ ':(exclude).claude/skills',
1897
+ `:(exclude,literal)${AGENT_PR_FILE}`,
1898
+ ...writtenSkills.pathspecs,
1899
+ ];
1900
+ if (!review &&
1901
+ !toolsOnly &&
1902
+ !parkNow &&
1903
+ !unfinished &&
1904
+ toContinue &&
1905
+ endedOnItsAnswer(engineRun) &&
1906
+ !isStopped(job.runId)) {
1907
+ const from = continuesBranch ? `origin/${branch}` : `origin/${base}`;
1908
+ await exec('git', stageArgs).catch(() => null);
1909
+ const read = secretFixRead(from);
1910
+ const staged = await exec('git', ['-C', worktree, ...read.args], {
1911
+ timeoutMs: 120_000,
1912
+ env: read.env,
1913
+ }).catch(() => null);
1914
+ const refusing = staged?.code === 0 ? uniqueHits(scanAddedLines(staged.stdout)).filter(refusesPush) : [];
1915
+ const leftMs = timeoutMs - engineMs;
1916
+ if (refusing.length > 0 && leftMs >= 60_000) {
1917
+ const ahead = await exec('git', ['-C', worktree, 'rev-list', '--count', `${from}..HEAD`], {
1918
+ timeoutMs: 30_000,
1919
+ }).catch(() => null);
1920
+ const committed = ahead?.code === 0 && Number(ahead.stdout.trim()) > 0;
1921
+ log(`secret scan before the push for ${job.runId}: ${refusing.length} line(s) would refuse it — ${refusing
1922
+ .slice(0, 5)
1923
+ .map((h) => `${h.kind} at ${h.path}:${h.line}`)
1924
+ .join(', ')} — continuing ${engineName}'s session once to rewrite them`);
1925
+ inv = adapter.buildInvocation({
1926
+ ...ctx,
1927
+ prompt: secretFixBrief(refusing, from, committed),
1928
+ resumeSessionId: toContinue,
1929
+ });
1930
+ const fixRun = await runEngine(leftMs);
1931
+ meter(fixRun.stdout, true);
1932
+ log(fixRun.code === 0
1933
+ ? `${engineName} rewrote the lines; the push's own scan reads the change again`
1934
+ : `${engineName}'s continued session ended with exit ${fixRun.code}; the push's own scan decides`);
1935
+ }
1936
+ }
1417
1937
  usage =
1418
1938
  attemptUsage(sessions, resumeCut ? { session: resumeCut.sessionId, baseline: resumeCut.usage } : undefined) ?? undefined;
1419
1939
  if (revising && kept?.attemptUsage) {
@@ -1432,63 +1952,116 @@ export async function runJob(job, cfg, api, viewer, opts) {
1432
1952
  log(`reported ${activity.sent} of ${activity.seen} step(s) to FireFunc — names and verbs only; the session stayed here`);
1433
1953
  mcp?.cleanup();
1434
1954
  const sessionLogPath = saveSessionLog(job.runId, engineRun.stdout, engineRun.stderr);
1955
+ if (checkpointTimer)
1956
+ clearInterval(checkpointTimer);
1957
+ if (checkpointing)
1958
+ await checkpointing;
1435
1959
  const summary = adapter.summarize(engineRun.stdout);
1436
1960
  if (sessionLogPath)
1437
1961
  log(`${engineName} session saved → ${sessionLogPath}`);
1438
1962
  if (summary)
1439
1963
  log(`${engineName} said: ${summary.replace(/\s+/g, ' ').slice(0, 500)}`);
1440
- if (engineRun.code === 124) {
1441
- const timedOutSession = adapter.resumesSessions
1964
+ if (isStopped(job.runId))
1965
+ return await fail(stoppedByPersonSentence(engineName, 'engine'));
1966
+ const keepForNextRun = (reason) => {
1967
+ const sessionId = adapter.resumesSessions
1442
1968
  ? (adapter.sessionId?.(engineRun.stdout) ?? (resumeCut?.sessionId || null))
1443
1969
  : 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',
1970
+ if (!sessionId || !worktree || parkStep || step)
1971
+ return false;
1972
+ const cutAt = now().getTime();
1973
+ const kept = saveCut(rdir, {
1974
+ workItemId: job.workItemId,
1975
+ runId: job.runId,
1976
+ engine: adapter.id,
1977
+ sessionId,
1978
+ repo: job.repo ?? null,
1979
+ branch: toolsOnly ? '' : branch,
1980
+ base,
1981
+ worktree,
1982
+ repoPath: toolsOnly ? null : repoPath,
1983
+ ...(readHead ? { readHead } : {}),
1984
+ resetsAt: null,
1985
+ cutAt: new Date(cutAt).toISOString(),
1986
+ keepUntil: keepUntil(null, cutAt),
1987
+ promptHash: promptHash(job.prompt),
1988
+ review,
1989
+ toolsOnly,
1990
+ continuesBranch,
1991
+ ...(lastReport ? { usage: lastReport } : {}),
1992
+ writtenSkills,
1993
+ reason,
1994
+ });
1995
+ if (kept)
1996
+ keepWorktree = true;
1997
+ return kept;
1998
+ };
1999
+ {
2000
+ let ending;
2001
+ try {
2002
+ ending = adapter.ending?.(engineRun.stdout);
2003
+ }
2004
+ catch {
2005
+ ending = undefined;
2006
+ }
2007
+ const billing = claudeApiKeyNow(cfg, rdir, now());
2008
+ const billedKey = adapter.id === 'claude_code' && (billing.why === 'opted-in' || billing.key !== null);
2009
+ const problem = adapter.id === 'claude_code'
2010
+ ? accountProblemOf(ending, {
2011
+ billedKey,
2012
+ stderr: engineRun.code === 0 ? '' : engineRun.stderr,
2013
+ })
2014
+ : null;
2015
+ if (problem) {
2016
+ opts?.account?.met(adapter.id, problem, engineName);
2017
+ const block = opts?.account?.held(adapter.id) ??
2018
+ accountBlock(problem, engineName, ACCOUNT_RETRY_FIRST_MS / 60_000);
2019
+ const kept = keepForNextRun('auth');
2020
+ const sentence = cannotWorkSentence(engineName, block);
2021
+ log(`${job.runId}: ${sentence}`);
2022
+ return await report({
2023
+ status: 'failed',
2024
+ error: kept
2025
+ ? `${sentence} What the session made is kept on this machine for a day; the next run continues it.`
2026
+ : sentence,
2027
+ limit: { kind: 'machine', detail: block.detail },
1468
2028
  });
1469
2029
  }
1470
- keepWorktree = keptOnTimeout;
2030
+ }
2031
+ if (firefuncAway === 'network') {
2032
+ const kept = keepForNextRun('network');
2033
+ return await fail(`${engineName} stopped because the network went away (FireFunc's own tools could not connect at the session's start), and the network did not come back in time for the runner to resume it. ` +
2034
+ (kept
2035
+ ? 'Its work is kept on this machine for a day: Re-run continues it from where it stopped.'
2036
+ : 'Re-run the task once the machine is back online.'));
2037
+ }
2038
+ if (firefuncAway === 'still_failed') {
2039
+ return await fail(`${engineName}'s session could not use FireFunc's own tools: the firefunc MCP server failed to connect at the start of two sessions while this machine reached FireFunc, so nothing the run owes through them was recorded. ` +
2040
+ "Re-run the task; if it happens again, check this machine's runner log for the MCP server's error.");
2041
+ }
2042
+ if (engineRun.code === 124) {
2043
+ const keptOnTimeout = keepForNextRun('timeout');
1471
2044
  const limitWords = budget !== null && limitMinutes === budget
1472
2045
  ? `${engineName} timed out after ${limitMinutes} min — the agent's time budget.`
1473
2046
  : `${engineName} timed out after ${limitMinutes} min.`;
1474
- return fail(keptOnTimeout
2047
+ return await fail(keptOnTimeout
1475
2048
  ? `${limitWords} Its work is kept on this machine for a day: Re-run continues it from where it stopped.`
1476
2049
  : limitWords);
1477
2050
  }
1478
- const limit = limitOf(engineRun.stdout);
2051
+ const limit = limitOf(engineRun.stdout, engineRun.stderr);
1479
2052
  if (limit) {
1480
2053
  opts?.limits?.set(adapter.id, limit);
1481
2054
  const cutSession = adapter.resumesSessions
1482
2055
  ? (adapter.sessionId?.(engineRun.stdout) ?? null)
1483
2056
  : null;
1484
2057
  let kept = false;
1485
- if (cutSession && worktree) {
2058
+ if (worktree) {
1486
2059
  const cutAt = now().getTime();
1487
2060
  kept = saveCut(rdir, {
1488
2061
  workItemId: job.workItemId,
1489
2062
  runId: job.runId,
1490
2063
  engine: adapter.id,
1491
- sessionId: cutSession,
2064
+ sessionId: cutSession ?? '',
1492
2065
  repo: job.repo ?? null,
1493
2066
  branch: toolsOnly ? '' : branch,
1494
2067
  base,
@@ -1509,10 +2082,14 @@ export async function runJob(job, cfg, api, viewer, opts) {
1509
2082
  keepWorktree = kept;
1510
2083
  log(`${engineName} was stopped by the plan's usage limit${limit.said ? ` ("${limit.said}")` : ''} — ` +
1511
2084
  (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({
2085
+ (kept
2086
+ ? cutSession
2087
+ ? '; the session and its worktree are kept to continue after the reset'
2088
+ : '; its worktree is kept for a new session to go on from after the reset'
2089
+ : ''));
2090
+ return await report({
1514
2091
  status: 'failed',
1515
- error: limitSentence(engineName, limit, kept),
2092
+ error: limitSentence(engineName, limit, kept ? (cutSession ? 'session' : 'worktree') : false),
1516
2093
  limit: { kind: 'plan', resetsAt: limit.resetsAt },
1517
2094
  });
1518
2095
  }
@@ -1522,6 +2099,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1522
2099
  log(`the model declined ${job.runId}: its safety system refused the session`);
1523
2100
  return { status: 'failed', error: modelDeclinedSentence(engineName) };
1524
2101
  };
2102
+ let authFailed = false;
1525
2103
  const scanHints = () => {
1526
2104
  const declined = declinedHint();
1527
2105
  if (declined)
@@ -1529,6 +2107,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1529
2107
  const authMsg = adapter.authFailureHint(`${summary}\n${engineRun.stderr}`);
1530
2108
  if (authMsg) {
1531
2109
  log(`auth/billing failure for ${job.runId}: ${authMsg}`);
2110
+ authFailed = true;
1532
2111
  return { status: 'failed', error: authMsg };
1533
2112
  }
1534
2113
  const rateMsg = adapter.rateLimitHint(`${summary}\n${engineRun.stderr}`);
@@ -1571,11 +2150,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
1571
2150
  toolsOnly,
1572
2151
  });
1573
2152
  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.`);
2153
+ return await 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
2154
  }
1576
2155
  keepWorktree = true;
1577
2156
  log(parkedLine(job.runId, parkNow));
1578
- return report({
2157
+ return await report({
1579
2158
  status: 'parked',
1580
2159
  park: {
1581
2160
  kind: parkNow.kind,
@@ -1589,20 +2168,35 @@ export async function runJob(job, cfg, api, viewer, opts) {
1589
2168
  const signal = endedBySignal(engineRun.code);
1590
2169
  if (signal) {
1591
2170
  log(`${engineName} was ended by ${signal} (exit ${engineRun.code}) for ${job.runId}`);
1592
- return fail(stoppedSentence(engineName, engineRun.code, signal, sessionLogPath ? basename(sessionLogPath) : null));
2171
+ return await fail(stoppedSentence(engineName, engineRun.code, signal, sessionLogPath ? basename(sessionLogPath) : null));
2172
+ }
2173
+ const outage = networkFailureHint(`${adapter.summarize(engineRun.stdout)}\n${engineRun.stderr.slice(-2000)}`);
2174
+ if (outage && !refused(engineRun.stdout, engineRun.stderr)) {
2175
+ const kept = keepForNextRun('network');
2176
+ return await fail(`${engineName} stopped because ${outage}, and the network did not come back in time for the runner to resume it. ` +
2177
+ (kept
2178
+ ? 'Its work is kept on this machine for a day: Re-run continues it from where it stopped.'
2179
+ : 'Re-run the task once the machine is back online.'));
1593
2180
  }
1594
2181
  const hinted = scanHints();
1595
- if (hinted)
1596
- return report(hinted);
2182
+ if (hinted) {
2183
+ if (authFailed && keepForNextRun('auth')) {
2184
+ return await report({
2185
+ ...hinted,
2186
+ error: `${hinted.error} Its work is kept on this machine for a day: once the engine can run again (the fix above), Re-run continues it from where it stopped.`,
2187
+ });
2188
+ }
2189
+ return await report(hinted);
2190
+ }
1597
2191
  const why = summary ? null : errorLine(engineRun.stderr);
1598
- return fail(summary
2192
+ return await fail(summary
1599
2193
  ? `${engineName} exited abnormally (code ${engineRun.code}). Last message: ${oneLine(shareable(summary), 500)}`
1600
2194
  : `${engineName} exited abnormally (code ${engineRun.code})${why ? `: ${oneLine(stripWorktree(why, worktree), 200)}` : ''}. ` +
1601
2195
  `Its output stayed on the machine${sessionLogPath ? ` — the session log is logs/${basename(sessionLogPath)} in the runner’s folder` : ''}.`);
1602
2196
  }
1603
2197
  if (unfinished) {
1604
2198
  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));
2199
+ return await fail(unfinishedSentence(engineName, open, !review && !toolsOnly, continuedOnce));
1606
2200
  }
1607
2201
  if (review) {
1608
2202
  const dirty = await exec('git', ['-C', worktree, 'status', '--porcelain']);
@@ -1612,9 +2206,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
1612
2206
  }
1613
2207
  const declinedReview = declinedHint();
1614
2208
  if (declinedReview)
1615
- return report(declinedReview);
2209
+ return await report(declinedReview);
1616
2210
  log(`review run ${job.runId} finished — reporting the agent's review`);
1617
- return report({
2211
+ return await report({
1618
2212
  status: 'no_pr',
1619
2213
  ...(summary
1620
2214
  ? { summary: reportedSummary(summary) }
@@ -1624,27 +2218,16 @@ export async function runJob(job, cfg, api, viewer, opts) {
1624
2218
  if (toolsOnly) {
1625
2219
  const declinedAnswer = declinedHint();
1626
2220
  if (declinedAnswer)
1627
- return report(declinedAnswer);
2221
+ return await report(declinedAnswer);
1628
2222
  log(`tools-only run ${job.runId} finished — reporting the agent's summary`);
1629
- return report({
2223
+ return await report({
1630
2224
  status: 'no_pr',
1631
2225
  ...(summary
1632
2226
  ? { summary: reportedSummary(summary) }
1633
2227
  : { error: `${engineName} finished without a summary of what it did.` }),
1634
2228
  });
1635
2229
  }
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
- ]);
2230
+ await exec('git', stageArgs);
1648
2231
  const vsBase = await exec('git', [
1649
2232
  '-C',
1650
2233
  worktree,
@@ -1656,9 +2239,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
1656
2239
  if (vsBase.code === 0) {
1657
2240
  const hinted = scanHints();
1658
2241
  if (hinted)
1659
- return report(hinted);
2242
+ return await report(hinted);
1660
2243
  log(`no changes produced for ${job.runId} — reporting no_pr`);
1661
- return report({
2244
+ return await report({
1662
2245
  status: 'no_pr',
1663
2246
  error: summary
1664
2247
  ? `No code change made. ${engineName}: ${oneLine(shareable(summary), 800)}`
@@ -1686,7 +2269,16 @@ export async function runJob(job, cfg, api, viewer, opts) {
1686
2269
  log(`${kind === 'test' ? 'the change touches tests only — ' : ''}titled "${title}"`);
1687
2270
  const uncommitted = await exec('git', ['-C', worktree, 'diff', '--cached', '--quiet', 'HEAD']);
1688
2271
  if (uncommitted.code !== 0) {
1689
- await exec('git', ['-C', worktree, 'commit', '-m', title, '--quiet']);
2272
+ const trailers = provenanceTrailers(job);
2273
+ await exec('git', [
2274
+ '-C',
2275
+ worktree,
2276
+ 'commit',
2277
+ '-m',
2278
+ title,
2279
+ ...(trailers ? ['-m', trailers] : []),
2280
+ '--quiet',
2281
+ ]);
1690
2282
  }
1691
2283
  else {
1692
2284
  log(`agent already committed its changes for ${job.runId} — reconciling to a PR`);
@@ -1700,6 +2292,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1700
2292
  engineName,
1701
2293
  summary,
1702
2294
  agentText,
2295
+ keepOnPushFailure: () => keepForNextRun('push'),
1703
2296
  keep: askFirst
1704
2297
  ? {
1705
2298
  sessionId: adapter.sessionId?.(engineRun.stdout) ?? (resumeCut?.sessionId || null),
@@ -1711,7 +2304,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1711
2304
  }
1712
2305
  catch (err) {
1713
2306
  log(`job ${job.runId} errored: ${err.message}`);
1714
- return report({ status: 'failed', error: err.message.slice(0, 400) });
2307
+ return await report({ status: 'failed', error: err.message.slice(0, 400) });
1715
2308
  }
1716
2309
  finally {
1717
2310
  if (job.agentEnv?.length) {
@@ -1721,9 +2314,12 @@ export async function runJob(job, cfg, api, viewer, opts) {
1721
2314
  viewer?.end(job.runId, 'failed');
1722
2315
  await Promise.all(bgProcs.map((p) => killProcessTree(p).catch(() => { })));
1723
2316
  const reviewCopies = worktree ? reviewCopiesOf(worktree) : [];
1724
- if (worktree || engineGroups.length > 0) {
2317
+ const letGo = await releaseDeviceHolds(deviceLockDir(rdir), job.runId).catch(() => []);
2318
+ if (letGo.length > 0)
2319
+ log(`let go of the device this session still held (${letGo.join(', ')})`);
2320
+ if (worktree || runTemp || engineGroups.length > 0) {
1725
2321
  await killOrphans({
1726
- roots: [worktree, attachDir, ...reviewCopies].filter((p) => !!p),
2322
+ roots: [worktree, attachDir, runTemp, ...reviewCopies].filter((p) => !!p),
1727
2323
  ...(worktree ? { reviewCopiesOf: basename(worktree) } : {}),
1728
2324
  groups: engineGroups.map((g) => ({ ...g, leaderExited: true })),
1729
2325
  }, { log }).catch(() => { });
@@ -1763,6 +2359,10 @@ export async function runJob(job, cfg, api, viewer, opts) {
1763
2359
  catch {
1764
2360
  }
1765
2361
  }
2362
+ if (!keepWorktree)
2363
+ removeRunTemp(runTemp);
2364
+ if (worktree)
2365
+ await reportWorktree(api, job.runId, worktree, endedState(worktree, keepWorktree));
1766
2366
  }
1767
2367
  }
1768
2368
  //# sourceMappingURL=job.js.map