@firefunc-agent/runner 0.9.14 → 0.9.35

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 (158) hide show
  1. package/README.md +184 -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 +66 -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 +39 -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.d.ts +2 -0
  50. package/dist/engines/antigravity.js +74 -4
  51. package/dist/engines/claude.js +22 -9
  52. package/dist/engines/codex.js +16 -2
  53. package/dist/engines/copilot.js +12 -0
  54. package/dist/engines/crush.d.ts +2 -0
  55. package/dist/engines/crush.js +58 -0
  56. package/dist/engines/cursor.js +12 -0
  57. package/dist/engines/gemini.js +14 -9
  58. package/dist/engines/index.d.ts +8 -0
  59. package/dist/engines/index.js +73 -1
  60. package/dist/engines/kilo.d.ts +2 -0
  61. package/dist/engines/kilo.js +63 -0
  62. package/dist/engines/opencode.d.ts +9 -0
  63. package/dist/engines/opencode.js +234 -0
  64. package/dist/engines/openhands.d.ts +10 -0
  65. package/dist/engines/openhands.js +271 -0
  66. package/dist/engines/pi.d.ts +10 -0
  67. package/dist/engines/pi.js +248 -0
  68. package/dist/engines/qwen.d.ts +8 -0
  69. package/dist/engines/qwen.js +153 -0
  70. package/dist/engines/sessions.d.ts +6 -0
  71. package/dist/engines/sessions.js +68 -0
  72. package/dist/engines/types.d.ts +3 -3
  73. package/dist/exec.d.ts +1 -0
  74. package/dist/exec.js +10 -4
  75. package/dist/firefunc/agents.d.ts +8 -1
  76. package/dist/firefunc/agents.js +53 -3
  77. package/dist/firefunc/auth.js +72 -19
  78. package/dist/firefunc/automations.d.ts +2 -0
  79. package/dist/firefunc/automations.js +290 -0
  80. package/dist/firefunc/cli.js +25 -0
  81. package/dist/firefunc/client.d.ts +5 -1
  82. package/dist/firefunc/client.js +12 -2
  83. package/dist/firefunc/config.d.ts +11 -1
  84. package/dist/firefunc/config.js +6 -4
  85. package/dist/firefunc/io.d.ts +1 -0
  86. package/dist/firefunc/main.js +34 -2
  87. package/dist/firefunc/oauth-login.d.ts +23 -0
  88. package/dist/firefunc/oauth-login.js +304 -0
  89. package/dist/firefunc/tasks.d.ts +4 -0
  90. package/dist/firefunc/tasks.js +89 -2
  91. package/dist/fleet-words.d.ts +2 -0
  92. package/dist/fleet-words.js +7 -0
  93. package/dist/git-auth.d.ts +15 -0
  94. package/dist/git-auth.js +39 -1
  95. package/dist/held.d.ts +3 -0
  96. package/dist/job.d.ts +26 -3
  97. package/dist/job.js +763 -152
  98. package/dist/keep-awake.d.ts +17 -0
  99. package/dist/keep-awake.js +90 -0
  100. package/dist/keep-local.d.ts +1 -1
  101. package/dist/keep-local.js +5 -3
  102. package/dist/limit.d.ts +9 -1
  103. package/dist/limit.js +260 -3
  104. package/dist/local-checks.d.ts +19 -0
  105. package/dist/local-checks.js +79 -0
  106. package/dist/locks.d.ts +18 -1
  107. package/dist/locks.js +249 -69
  108. package/dist/machine-commands.d.ts +21 -0
  109. package/dist/machine-commands.js +107 -0
  110. package/dist/machine-profile.d.ts +18 -0
  111. package/dist/machine-profile.js +69 -0
  112. package/dist/mcp-init.d.ts +2 -0
  113. package/dist/mcp-init.js +28 -0
  114. package/dist/mcp.d.ts +13 -1
  115. package/dist/mcp.js +48 -4
  116. package/dist/network.js +3 -2
  117. package/dist/openrouter.d.ts +15 -0
  118. package/dist/openrouter.js +39 -0
  119. package/dist/orphans.d.ts +4 -0
  120. package/dist/orphans.js +96 -4
  121. package/dist/pool.d.ts +1 -0
  122. package/dist/pool.js +25 -2
  123. package/dist/pr-title.d.ts +10 -0
  124. package/dist/pr-title.js +15 -0
  125. package/dist/recover.d.ts +3 -1
  126. package/dist/recover.js +27 -7
  127. package/dist/release-draft.d.ts +79 -0
  128. package/dist/release-draft.js +301 -0
  129. package/dist/resources.d.ts +86 -0
  130. package/dist/resources.js +217 -0
  131. package/dist/restart-idle.d.ts +23 -0
  132. package/dist/restart-idle.js +67 -0
  133. package/dist/run-attachments.d.ts +5 -0
  134. package/dist/run-attachments.js +14 -9
  135. package/dist/run-stops.d.ts +15 -0
  136. package/dist/run-stops.js +90 -0
  137. package/dist/run-temp.d.ts +12 -0
  138. package/dist/run-temp.js +57 -0
  139. package/dist/secret-scan.d.ts +5 -0
  140. package/dist/secret-scan.js +30 -0
  141. package/dist/self-upgrade.d.ts +36 -0
  142. package/dist/self-upgrade.js +78 -0
  143. package/dist/service.d.ts +7 -1
  144. package/dist/service.js +50 -7
  145. package/dist/sign-in.d.ts +42 -0
  146. package/dist/sign-in.js +243 -0
  147. package/dist/tool-call.d.ts +59 -0
  148. package/dist/tool-call.js +375 -0
  149. package/dist/transport.d.ts +26 -0
  150. package/dist/transport.js +118 -0
  151. package/dist/work-dir.d.ts +11 -0
  152. package/dist/work-dir.js +69 -0
  153. package/dist/worktree-report.d.ts +10 -0
  154. package/dist/worktree-report.js +17 -0
  155. package/dist/worktrees.d.ts +16 -1
  156. package/dist/worktrees.js +62 -17
  157. package/package.json +4 -4
  158. package/skill/firefunc/SKILL.md +22 -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,23 @@ 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 { jobClaudeEndpoint } from './openrouter.js';
40
+ import { ACCOUNT_RETRY_FIRST_MS, accountBlock, accountProblemOf, cannotWorkSentence, } from './engine-account.js';
41
+ import { createKeyedMutex, deviceLockDir, ensureDeviceScript, ensureHeavyScript, heavyLockDir, heavySlots, heavyTag, withHeavyLock, } from './locks.js';
30
42
  import { getAdapter, stripForeignEngineCreds } from './engines/index.js';
31
43
  import { mcpFormatForEngine, prepareMcp } from './mcp.js';
32
44
  import { continueToFinishBrief, engineRules } from './brief.js';
45
+ import { BRIEF_FOLDER, fenceBrief, prepareBriefFolder } from './brief-file.js';
46
+ import { prepareReleaseFolder, stageDraftRelease } from './release-draft.js';
33
47
  import { limitSentence } from './limit.js';
34
48
  import { cannotRunUnattendedSentence, unattendedContext } from './unattended.js';
35
49
  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';
50
+ import { updateHeld } from './held.js';
51
+ import { deviceSerials, emulatorBudget, releaseDeviceHolds } from './device-lease.js';
52
+ import { killOrphans, reviewCopiesOf, signalGroupSparingDevices, trackEngineGroup, untrackEngineGroup, } from './orphans.js';
53
+ import { branchHeldSentence, branchHolderOf, removeRunnerWorktree, staleHolder, } from './worktrees.js';
39
54
  import { detailOf, startRunTrail, trailOff } from './trail/index.js';
40
55
  import { RUNNER_VERSION } from './version.js';
41
56
  function log(msg) {
@@ -174,18 +189,64 @@ function unfinishedSentence(engineName, open, changeRun, continued) {
174
189
  '. 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
190
  }
176
191
  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';
192
+ const what = why === 'plan'
193
+ ? "was stopped because the machine's API key ran out of credit; this session continues on the plan"
194
+ : why === 'limit'
195
+ ? "was stopped by the plan's usage limit, which has now reset, and that session could not be continued"
196
+ : why === 'api'
197
+ ? "was stopped by the plan's usage limit; this session continues on the machine's API key"
198
+ : 'was cut short by a network outage';
182
199
  return (`Your previous session on this task ${what}. The worktree ` +
183
200
  'still holds everything you did; look at `git status` and `git diff`, continue from ' +
184
201
  'there, and finish the task. The original brief follows.\n\n' +
185
202
  prompt);
186
203
  }
204
+ 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.';
205
+ const SESSION_ID_IN_STREAM = /"session_id"\s*:\s*"([A-Za-z0-9-]{8,80})"/;
206
+ const DISK_FULL_WORDS = /no space left on device|\benospc\b|disk quota exceeded|\bedquot\b/i;
207
+ const DISK_NEARLY_FULL_BYTES = 1024 ** 3;
208
+ export function diskFullFailure(stderr, folder, free = (dir) => diskOf(dir)?.freeBytes ?? null) {
209
+ const said = DISK_FULL_WORDS.test(stderr);
210
+ const unableToWrite = /unable to (?:write|create)|could not (?:write|create)/i.test(stderr);
211
+ const freeBytes = free(folder);
212
+ const nearlyFull = freeBytes !== null && freeBytes < DISK_NEARLY_FULL_BYTES;
213
+ if (!said && !(unableToWrite && nearlyFull))
214
+ return null;
215
+ const left = freeBytes !== null ? ` (${(freeBytes / 1024 ** 3).toFixed(1)} GB free)` : '';
216
+ const detail = `the disk is full${left}`;
217
+ return {
218
+ 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. ` +
219
+ 'Fix: free space on this machine (old worktrees, build output, caches), or pin the agent to another machine.',
220
+ limit: { kind: 'machine', detail },
221
+ };
222
+ }
223
+ export const STOPPED_HOLDER_WAIT_MS = 90_000;
224
+ export async function waitForStoppedHolder(runnerDir, worktree, holder, deps = {}) {
225
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
226
+ const pollMs = deps.pollMs ?? 3_000;
227
+ let left = deps.waitMs ?? STOPPED_HOLDER_WAIT_MS;
228
+ let now = holder;
229
+ while (now && left > 0) {
230
+ await sleep(pollMs);
231
+ left -= pollMs;
232
+ now = branchHolderOf(runnerDir, worktree);
233
+ }
234
+ return now;
235
+ }
187
236
  export async function runJob(job, cfg, api, viewer, opts) {
188
237
  api = blankingApi(api);
238
+ setWorkDir(cfg.workDir);
239
+ const heartbeatMs = opts?.heartbeatMs ?? 5 * 60_000;
240
+ const jobHeartbeat = setInterval(() => void Promise.resolve(api.event(job.runId, 'heartbeat')).catch(() => { }), heartbeatMs);
241
+ jobHeartbeat.unref?.();
242
+ try {
243
+ return await runJobBody(job, cfg, api, viewer, opts);
244
+ }
245
+ finally {
246
+ clearInterval(jobHeartbeat);
247
+ }
248
+ }
249
+ async function runJobBody(job, cfg, api, viewer, opts) {
189
250
  const now = opts?.now ?? (() => new Date());
190
251
  const rdir = runnerDir();
191
252
  const trailWriteTools = new Set();
@@ -212,8 +273,10 @@ export async function runJob(job, cfg, api, viewer, opts) {
212
273
  if (trail)
213
274
  void trail.runStarted(job.repo ? { repo: job.repo } : {});
214
275
  let secretScan;
276
+ const localChecks = makeLocalChecksReader(declaredChecksOf(job.checks));
215
277
  let usage;
216
278
  let readHead;
279
+ let restoredFrom = null;
217
280
  let openCommandAtEnd = false;
218
281
  let attachFolder = null;
219
282
  let attachmentsSent = false;
@@ -248,8 +311,47 @@ export async function runJob(job, cfg, api, viewer, opts) {
248
311
  log(`the pictures for the ticket were not uploaded: ${e.message}`);
249
312
  });
250
313
  };
314
+ let releaseFolder = null;
315
+ let releaseBase = null;
316
+ let releaseStaged = false;
317
+ const stageRelease = async (status) => {
318
+ if (releaseStaged || !releaseFolder || !job.release || !job.repo)
319
+ return null;
320
+ if (status !== 'pr_opened' && status !== 'no_pr')
321
+ return null;
322
+ releaseStaged = true;
323
+ try {
324
+ const cred = await api.gitCredential(job.runId);
325
+ if (!cred) {
326
+ return {
327
+ staged: false,
328
+ why: 'FireFunc gave this machine no repository token to stage the draft release with',
329
+ tag: null,
330
+ };
331
+ }
332
+ return await stageDraftRelease({
333
+ repo: job.repo,
334
+ base: releaseBase,
335
+ offer: job.release,
336
+ dir: releaseFolder,
337
+ cred,
338
+ log,
339
+ });
340
+ }
341
+ catch (e) {
342
+ log(`the release was not staged: ${e.message}`);
343
+ return {
344
+ staged: false,
345
+ why: 'the machine could not get a repository token to stage the draft release',
346
+ tag: null,
347
+ };
348
+ }
349
+ };
251
350
  const report = async (reported) => {
252
351
  await sendAttachments(reported.status);
352
+ const release = reported.release ? null : await stageRelease(reported.status);
353
+ if (release)
354
+ reported = { ...reported, release };
253
355
  await trail
254
356
  ?.finish({
255
357
  status: reported.status,
@@ -259,6 +361,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
259
361
  let payload = blankSecretsDeep(secretScan && !reported.secretScan ? { ...reported, secretScan } : reported);
260
362
  if (usage && !payload.usage)
261
363
  payload = { ...payload, usage };
364
+ const checks = localChecks.report();
365
+ if (checks && !payload.localChecks)
366
+ payload = { ...payload, localChecks: checks };
262
367
  if (readHead && !payload.readHead)
263
368
  payload = { ...payload, readHead };
264
369
  if (openCommandAtEnd && !payload.openCommandAtEnd) {
@@ -321,12 +426,45 @@ export async function runJob(job, cfg, api, viewer, opts) {
321
426
  if (spent) {
322
427
  const limit = { kind: 'plan', resetsAt: spent.resetsAt };
323
428
  log(`${adapter.displayName}'s plan limit is spent until ${spent.until} — answering ${job.runId} without starting it`);
324
- return report({
429
+ return await report({
325
430
  status: 'failed',
326
431
  error: limitSentence(adapter.displayName, limit, false),
327
432
  limit: { kind: 'plan', resetsAt: limit.resetsAt },
328
433
  });
329
434
  }
435
+ if (job.signIn === 'plan' || job.signIn === 'key') {
436
+ const machine = cfg.name ?? hostname();
437
+ const said = opts?.signIn?.()[adapter.id] ??
438
+ (() => {
439
+ const source = keySourceOf(adapter.id, cfg, process.env, rdir);
440
+ return {
441
+ plan: 'unknown',
442
+ key: (ENGINE_KEY_VARS[adapter.id] ?? []).length === 0
443
+ ? 'none'
444
+ : source
445
+ ? 'found'
446
+ : 'missing',
447
+ };
448
+ })();
449
+ const how = jobSignIn(adapter.id, job.signIn, cfg, machine, said);
450
+ if (!how.ok) {
451
+ log(`${job.runId}: ${how.reason}`);
452
+ return await report({ status: 'failed', error: `${how.reason} ${how.fix}` });
453
+ }
454
+ cfg = how.cfg;
455
+ if (how.note)
456
+ log(`${job.runId}: signs in with ${how.note}`);
457
+ }
458
+ if (job.claudeEndpoint === 'openrouter') {
459
+ const how = jobClaudeEndpoint(adapter.id, job.claudeEndpoint, cfg, cfg.name ?? hostname());
460
+ if (!how.ok) {
461
+ log(`${job.runId}: ${how.reason}`);
462
+ return await report({ status: 'failed', error: `${how.reason} ${how.fix}` });
463
+ }
464
+ cfg = how.cfg;
465
+ if (how.note)
466
+ log(`${job.runId}: Claude Code sends its requests to ${how.note}`);
467
+ }
330
468
  const unattended = adapter.unattendedBlock?.({
331
469
  ...unattendedContext(cfg, job.permissionMode),
332
470
  ...opts?.unattended,
@@ -334,12 +472,22 @@ export async function runJob(job, cfg, api, viewer, opts) {
334
472
  if (unattended) {
335
473
  const sentence = cannotRunUnattendedSentence(adapter.displayName, unattended);
336
474
  log(`${job.runId}: ${sentence}`);
337
- return report({
475
+ return await report({
338
476
  status: 'failed',
339
477
  error: sentence,
340
478
  limit: { kind: 'machine', detail: unattended.detail },
341
479
  });
342
480
  }
481
+ const heldForAccount = opts?.account?.held(adapter.id) ?? null;
482
+ if (heldForAccount) {
483
+ const sentence = cannotWorkSentence(adapter.displayName, heldForAccount);
484
+ log(`${job.runId}: ${sentence}`);
485
+ return await report({
486
+ status: 'failed',
487
+ error: sentence,
488
+ limit: { kind: 'machine', detail: heldForAccount.detail },
489
+ });
490
+ }
343
491
  const engineRuns = step?.kind !== 'publish';
344
492
  const agentEnv = {};
345
493
  const carriedNotes = [];
@@ -357,10 +505,10 @@ export async function runJob(job, cfg, api, viewer, opts) {
357
505
  });
358
506
  }
359
507
  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.`);
508
+ 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
509
  }
362
510
  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}`);
511
+ 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
512
  }
365
513
  registerSecretValues(job.runId, got.env.filter((e) => e.secret).map((e) => ({ name: e.name, value: e.value })));
366
514
  for (const e of got.env)
@@ -432,7 +580,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
432
580
  rememberRepoPath(job.repo, dest, cfg);
433
581
  }
434
582
  else {
435
- return report({
583
+ return await report({
436
584
  status: 'failed',
437
585
  error: `Could not clone ${job.repo}: ${redact(cloned.stderr, cred.token).slice(0, 300)}`,
438
586
  });
@@ -441,7 +589,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
441
589
  }
442
590
  if (!repoPath && !toolsOnly) {
443
591
  log(`no local checkout for ${job.repo} and no credential to clone with`);
444
- return report({
592
+ return await report({
445
593
  status: 'failed',
446
594
  error: `Runner has no local checkout for ${job.repo} and could not obtain a ` +
447
595
  `credential to clone it. Either map it with \`firefunc-runner repo ` +
@@ -495,7 +643,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
495
643
  else if (parkStep && parkKept) {
496
644
  resumeCut = resumeFromParked(parkKept, promptHash(job.prompt));
497
645
  }
498
- else if (cutMatch && 'resume' in cutMatch && adapter.resumesSessions) {
646
+ else if (cutMatch &&
647
+ 'resume' in cutMatch &&
648
+ (adapter.resumesSessions || cutMatch.resume.sessionId === '')) {
499
649
  resumeCut = cutMatch.resume;
500
650
  }
501
651
  else if (cutMatch) {
@@ -520,6 +670,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
520
670
  const engineGroups = [];
521
671
  let worktree = null;
522
672
  let attachDir = null;
673
+ let runTemp = null;
523
674
  let mcp = null;
524
675
  let writtenSkills = { written: [], pathspecs: [] };
525
676
  const bgProcs = [];
@@ -585,7 +736,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
585
736
  secretScan = asReported(added);
586
737
  if (added.some(refusesPush)) {
587
738
  log(`secret scan for ${job.runId}: ${added.length} finding(s) — ${found(added)} — refusing to push`);
588
- return fail(secretRefusal(added, branch));
739
+ return await fail(secretRefusal(added, branch));
589
740
  }
590
741
  if (added.length > 0) {
591
742
  log(`secret scan for ${job.runId}: ${added.length} looser match(es) — ${found(added)} — pushing; ` +
@@ -621,7 +772,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
621
772
  if (s.keep) {
622
773
  const changes = await changesOf(scanIn, continuesBranch ? `origin/${branch}` : `origin/${base}`, branch);
623
774
  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.`);
775
+ 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
776
  }
626
777
  const at = now();
627
778
  const saved = saveKept(rdir, {
@@ -649,11 +800,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
649
800
  activitySeq: activitySeen,
650
801
  });
651
802
  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.`);
803
+ 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
804
  }
654
805
  keepWorktree = true;
655
806
  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({
807
+ return await report({
657
808
  status: 'awaiting_approval',
658
809
  changes,
659
810
  head: scannedTip,
@@ -698,21 +849,24 @@ export async function runJob(job, cfg, api, viewer, opts) {
698
849
  .filter(Boolean);
699
850
  const leaked = stagedPaths.filter((l) => l === '.env' || l.endsWith('/.env') || (mcpStaged !== null && l === mcpStaged));
700
851
  if (leaked.length > 0) {
701
- return fail(`refusing to push: the commit contains ${leaked.join(', ')}, which can hold live credentials. ` +
852
+ return await fail(`refusing to push: the commit contains ${leaked.join(', ')}, which can hold live credentials. ` +
702
853
  `This is a FireFunc bug — please report it. Nothing was pushed.`);
703
854
  }
704
855
  const skillLeaked = writtenSkillPaths(stagedPaths, writtenSkills);
705
856
  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'} ` +
857
+ return await fail(`refusing to push: the agent added ${skillLeaked.join(', ')} to its commit — ` +
858
+ `${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
859
  `FireFunc writes into the checkout for this run only and never commits. Nothing was ` +
709
860
  `pushed. Fix: tell the agent not to stage or commit anything under ` +
710
861
  `${skillLeaked[0].split('/').slice(0, -1).join('/')} (check its instruction and ` +
711
862
  `its skills for "git add -f" or "commit everything"), then re-run the task.`);
712
863
  }
713
864
  const pushFrom = worktree;
714
- const pushOnce = async () => gitCred
715
- ? pushBranch(pushFrom, branch, gitCred.repo, gitCred, { force: !continuesBranch })
865
+ const pushOnce = async (timeoutMs = PUSH_TIMEOUT_MS) => gitCred
866
+ ? pushBranch(pushFrom, branch, gitCred.repo, gitCred, {
867
+ force: !continuesBranch,
868
+ timeoutMs,
869
+ })
716
870
  : exec('git', [
717
871
  '-C',
718
872
  pushFrom,
@@ -721,23 +875,78 @@ export async function runJob(job, cfg, api, viewer, opts) {
721
875
  'origin',
722
876
  `${branch}:${branch}`,
723
877
  ], {
724
- timeoutMs: 120_000,
878
+ timeoutMs,
879
+ });
880
+ if (isStopped(job.runId))
881
+ return await fail(stoppedByPersonSentence(engineName, 'push'));
882
+ if (continuesBranch && gitCred) {
883
+ const ended = await endedPullRequestForHead({
884
+ repo: gitCred.repo,
885
+ head: branch,
886
+ cred: gitCred,
887
+ });
888
+ if (ended)
889
+ return await fail(endedPullRequestSentence(branch, ended, base || null));
890
+ }
891
+ let pushTimeoutMs = PUSH_TIMEOUT_MS;
892
+ const pushLanded = async () => {
893
+ const local = await exec('git', ['-C', pushFrom, 'rev-parse', `refs/heads/${branch}`]);
894
+ const head = local.code === 0 ? local.stdout.trim() : '';
895
+ if (!FULL_SHA.test(head))
896
+ return false;
897
+ const remote = await exec('git', ['-C', pushFrom, 'ls-remote', 'origin', `refs/heads/${branch}`], {
898
+ timeoutMs: 60_000,
899
+ ...(gitCred ? { env: gitAuthEnv(gitCred.token, gitCred.repo) } : {}),
725
900
  });
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)
901
+ return remote.code === 0 && remote.stdout.trim().split(/\s+/)[0] === head;
902
+ };
903
+ let push = await pushOnce(pushTimeoutMs);
904
+ for (let netTries = 0, slowTries = 0; push.code !== 0;) {
905
+ if (push.code === 124 && (await pushLanded())) {
906
+ log(`the push of ${branch} timed out, but the remote already holds its commit — pushed`);
907
+ push = { code: 0, stdout: '', stderr: '' };
731
908
  break;
732
- push = await pushOnce();
909
+ }
910
+ if (isNetworkError(push.stderr) && netTries < 3) {
911
+ netTries += 1;
912
+ log(`push failed because the network seems to be away — waiting for it (try ${netTries} of 3)`);
913
+ const back = await waitForNetwork({
914
+ probe: () => api.probe(),
915
+ maxWaitMs: 10 * 60_000,
916
+ log,
917
+ });
918
+ if (!back)
919
+ break;
920
+ }
921
+ else if (push.code === 124 && slowTries < 2) {
922
+ slowTries += 1;
923
+ 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`);
924
+ pushTimeoutMs *= 3;
925
+ }
926
+ else
927
+ break;
928
+ if (isStopped(job.runId))
929
+ return await fail(stoppedByPersonSentence(engineName, 'push'));
930
+ push = await pushOnce(pushTimeoutMs);
931
+ }
932
+ if (push.code === 124) {
933
+ log(`git push output for ${job.runId} (kept on this machine):\n${redact(push.stderr, gitCred?.token).slice(-4000)}`);
934
+ const kept = s.keepOnPushFailure?.() ?? false;
935
+ 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. ` +
936
+ (kept
937
+ ? `${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.`
938
+ : `The commit is still on this machine's checkout as ${branch}. ` +
939
+ '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
940
  }
734
941
  if (push.code !== 0) {
735
942
  const said = redact(push.stderr, gitCred?.token);
736
943
  log(`git push output for ${job.runId} (kept on this machine):\n${said.slice(-4000)}`);
737
944
  const refused = pushRefusal(said);
738
- return fail(refused
945
+ const kept = s.keepOnPushFailure?.() ?? false;
946
+ return await fail((refused
739
947
  ? `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.`);
948
+ : `git push failed (exit ${push.code}); its output stayed on the machine — the runner’s log shows it.`) +
949
+ (kept ? ` ${KEPT_FOR_PUSH} Fix what refused the push first.` : ''));
741
950
  }
742
951
  await trail?.pushed({ branch });
743
952
  if (secretScan && scannedTip && scanCoversPullRequest) {
@@ -747,9 +956,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
747
956
  else
748
957
  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
958
  }
750
- const body = agentText?.body
959
+ const body = withProvenanceFooter(agentText?.body
751
960
  ? `${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 });
961
+ : pullRequestBody(kind, engineName, job.externalId, { continuesBranch }), job);
962
+ if (isStopped(job.runId))
963
+ return await fail(stoppedByPersonSentence(engineName, 'pr'));
753
964
  if (gitCred) {
754
965
  const pr = await withNetworkRetry(() => openDraftPr({
755
966
  repo: gitCred.repo,
@@ -768,7 +979,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
768
979
  if (!('error' in pr)) {
769
980
  await api.event(job.runId, 'pr_opened', { url: pr.url, branch });
770
981
  log(`opened PR for ${job.runId}: ${pr.url}`);
771
- return report({
982
+ return await report({
772
983
  status: 'pr_opened',
773
984
  pr: {
774
985
  repo: job.repo ?? undefined,
@@ -782,7 +993,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
782
993
  }
783
994
  const why = redact(pr.error, gitCred.token);
784
995
  if (!(await hasGh(worktree)))
785
- return fail(why);
996
+ return await fail(why);
786
997
  log(`could not open the PR as FireFunc (${why}); falling back to gh`);
787
998
  }
788
999
  const createCwd = worktree;
@@ -841,14 +1052,14 @@ export async function runJob(job, cfg, api, viewer, opts) {
841
1052
  }
842
1053
  if (!resolved) {
843
1054
  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}` : ''}. ` +
1055
+ return await fail(`The branch ${branch} was pushed, but the pull request could not be created${why ? `: ${why}` : ''}. ` +
845
1056
  `Open it from that branch on GitHub (FireFunc will link it to this task), or re-run.`);
846
1057
  }
847
1058
  const url = resolved.url;
848
1059
  const number = resolved.number;
849
1060
  await api.event(job.runId, 'pr_opened', { url, branch });
850
1061
  log(`opened PR for ${job.runId}: ${url}`);
851
- return report({
1062
+ return await report({
852
1063
  status: 'pr_opened',
853
1064
  pr: { repo: job.repo ?? undefined, number, url: url || undefined, branch, summary: title },
854
1065
  ...(summary ? { summary: reportedSummary(summary) } : {}),
@@ -857,10 +1068,10 @@ export async function runJob(job, cfg, api, viewer, opts) {
857
1068
  let base = '';
858
1069
  try {
859
1070
  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.');
1071
+ 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
1072
  }
862
1073
  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.');
1074
+ 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
1075
  }
865
1076
  if (step?.kind === 'publish' && kept) {
866
1077
  worktree = kept.worktree;
@@ -877,7 +1088,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
877
1088
  `refs/heads/${kept.branch}^{commit}`,
878
1089
  ]).catch(() => '');
879
1090
  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.`);
1091
+ 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
1092
  }
882
1093
  log(`approved: pushing the change kept for ${job.runId} (${kept.branch}) and opening its pull request`);
883
1094
  return await ship({
@@ -897,19 +1108,19 @@ export async function runJob(job, cfg, api, viewer, opts) {
897
1108
  log(`continuing the session a plan limit cut for this task, in ${worktree}`);
898
1109
  }
899
1110
  else if (toolsOnly) {
900
- worktree = mkdtempSync(join(tmpdir(), 'firefunc-tools-'));
1111
+ worktree = mkdtempSync(join(workRoot(), 'firefunc-tools-'));
901
1112
  updateHeld(rdir, job.runId, { scratch: [worktree] });
902
1113
  writeSkills(worktree, job.skills, log);
903
1114
  const refs = await writeRefs(worktree);
904
1115
  if (refs && 'failure' in refs)
905
- return fail(refs.failure);
1116
+ return await fail(refs.failure);
906
1117
  await exec('git', ['-C', worktree, 'init', '--quiet']);
907
1118
  log(`no repository for ${job.runId} — the agent works through its tools in ${worktree}`);
908
1119
  }
909
1120
  else {
910
1121
  await api.event(job.runId, 'cloning', { repo: job.repo, branch });
911
1122
  const checkout = repoPath;
912
- const prep = await gitMutex.run(checkout, async () => {
1123
+ const prepare = () => gitMutex.run(checkout, async () => {
913
1124
  await exec('git', ['-C', checkout, 'fetch', 'origin', '--quiet'], { timeoutMs: 120_000 });
914
1125
  if (resumeCut) {
915
1126
  const known = await exec('git', ['-C', resumeCut.worktree, 'rev-parse', '--git-dir']);
@@ -920,6 +1131,8 @@ export async function runJob(job, cfg, api, viewer, opts) {
920
1131
  add: { code: 0, stdout: '', stderr: '' },
921
1132
  branchMissing: false,
922
1133
  startPoint: '',
1134
+ heldBy: null,
1135
+ holder: null,
923
1136
  };
924
1137
  }
925
1138
  log(`the worktree the plan limit's cut session kept is no longer a worktree of ${job.repo} — starting over`);
@@ -948,29 +1161,71 @@ export async function runJob(job, cfg, api, viewer, opts) {
948
1161
  `refs/remotes/origin/${branch}`,
949
1162
  ]);
950
1163
  if (has.code !== 0) {
951
- return { base: b, wt: '', add: has, branchMissing: true, startPoint };
1164
+ return {
1165
+ base: b,
1166
+ wt: '',
1167
+ add: has,
1168
+ branchMissing: true,
1169
+ startPoint,
1170
+ heldBy: null,
1171
+ holder: null,
1172
+ };
952
1173
  }
953
1174
  startPoint = `origin/${branch}`;
954
1175
  }
955
- const wt = mkdtempSync(join(tmpdir(), 'firefunc-'));
1176
+ let wt;
1177
+ try {
1178
+ wt = mkdtempSync(join(workRoot(), 'firefunc-'));
1179
+ }
1180
+ catch (err) {
1181
+ const msg = err.message ?? String(err);
1182
+ return {
1183
+ base: b,
1184
+ wt: '',
1185
+ add: {
1186
+ code: 1,
1187
+ stdout: '',
1188
+ stderr: `fatal: could not create the worktree folder: ${msg}`,
1189
+ },
1190
+ branchMissing: false,
1191
+ startPoint,
1192
+ heldBy: null,
1193
+ holder: null,
1194
+ };
1195
+ }
956
1196
  const add = () => exec('git', ['-C', checkout, 'worktree', 'add', '--force', '-B', branch, wt, startPoint], {
957
1197
  timeoutMs: 120_000,
958
1198
  });
959
1199
  let result = await add();
960
1200
  const holder = result.code !== 0 ? staleHolder(result.stderr) : null;
1201
+ let heldBy = null;
961
1202
  if (holder) {
962
- const live = new Set([...liveWorktrees(rdir)].map(canonicalPath));
963
- if (!live.has(canonicalPath(holder))) {
1203
+ heldBy = branchHolderOf(rdir, holder);
1204
+ if (!heldBy) {
964
1205
  log(`a worktree a stopped runner left holds ${branch} (${holder}) — removing it and trying again`);
965
1206
  await removeRunnerWorktree(checkout, holder, log);
966
1207
  result = await add();
967
1208
  }
968
1209
  }
969
- return { base: b, wt, add: result, branchMissing: false, startPoint };
1210
+ return { base: b, wt, add: result, branchMissing: false, startPoint, heldBy, holder };
970
1211
  });
1212
+ let prep = await prepare();
1213
+ if (prep.add.code !== 0 &&
1214
+ prep.heldBy?.kind === 'live' &&
1215
+ prep.heldBy.runId &&
1216
+ prep.holder &&
1217
+ isStopped(prep.heldBy.runId)) {
1218
+ log(`${branch} is held by ${prep.heldBy.runId}, which a person stopped — waiting for it to end`);
1219
+ if (!(await waitForStoppedHolder(rdir, prep.holder, prep.heldBy))) {
1220
+ if (prep.wt)
1221
+ rmSync(prep.wt, { recursive: true, force: true });
1222
+ prep = await prepare();
1223
+ }
1224
+ }
971
1225
  base = prep.base;
1226
+ releaseBase = prep.base || null;
972
1227
  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. ` +
1228
+ 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
1229
  `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
1230
  }
976
1231
  worktree = prep.wt;
@@ -990,17 +1245,41 @@ export async function runJob(job, cfg, api, viewer, opts) {
990
1245
  if (FULL_SHA.test(sha))
991
1246
  readHead = sha;
992
1247
  }
1248
+ if (prep.add.code !== 0 && prep.heldBy) {
1249
+ log(`git worktree add output for ${job.runId} (kept on this machine):\n${prep.add.stderr}`);
1250
+ return await fail(branchHeldSentence(branch, prep.heldBy));
1251
+ }
993
1252
  if (prep.add.code !== 0) {
994
1253
  log(`git worktree add output for ${job.runId} (kept on this machine):\n${prep.add.stderr}`);
1254
+ const full = diskFullFailure(prep.add.stderr, workRoot());
1255
+ if (full)
1256
+ return await report({ status: 'failed', ...full });
995
1257
  const said = pushRefusal(prep.add.stderr);
996
- return fail(said
1258
+ return await fail(said
997
1259
  ? `git worktree add failed: ${oneLine(said, 400)}`
998
1260
  : `git worktree add failed (exit ${prep.add.code}); its output stayed on the machine — the runner’s log shows it.`);
999
1261
  }
1262
+ const saved = readCheckpoint(job.checkpoint);
1263
+ if (saved && !resumeCut && !continuesBranch && !askFirst && !step && !parkStep) {
1264
+ const cred = await api.gitCredential(job.runId).catch(() => null);
1265
+ const restored = await restoreCheckpoint({
1266
+ worktree,
1267
+ ref: saved.ref,
1268
+ sha: saved.sha,
1269
+ env: cred ? gitAuthEnv(cred.token, job.repo) : {},
1270
+ });
1271
+ if (restored) {
1272
+ restoredFrom = saved;
1273
+ log(`${job.runId} goes on from the work saved at ${saved.ref} (${saved.sha.slice(0, 8)})`);
1274
+ }
1275
+ else {
1276
+ log(`${job.runId}: the saved work at ${saved.ref} could not be fetched — starting from ${base}`);
1277
+ }
1278
+ }
1000
1279
  }
1001
1280
  const attachPaths = [];
1002
1281
  if (job.attachments?.length) {
1003
- attachDir = mkdtempSync(join(tmpdir(), 'firefunc-attach-'));
1282
+ attachDir = mkdtempSync(join(workRoot(), 'firefunc-attach-'));
1004
1283
  updateHeld(rdir, job.runId, { scratch: [attachDir] });
1005
1284
  mkdirSync(attachDir, { recursive: true });
1006
1285
  job.attachments.forEach((att, i) => {
@@ -1023,9 +1302,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
1023
1302
  .join('\n')}\n\n`
1024
1303
  : '';
1025
1304
  const runEnv = {
1305
+ ...cargoTargetEnv(cfg, rdir, job.repo),
1026
1306
  ...cfg.claudeEnv,
1027
1307
  ...(cfg.claudeCodeOAuthToken ? { CLAUDE_CODE_OAUTH_TOKEN: cfg.claudeCodeOAuthToken } : {}),
1028
1308
  ...(opts?.devServerPort ? { PORT: String(opts.devServerPort) } : {}),
1309
+ ...workTempEnv(),
1029
1310
  };
1030
1311
  if (opts?.devServerPort && cfg.backgroundCommands?.length) {
1031
1312
  log(`session dev-server PORT=${opts.devServerPort} (parallel-safe)`);
@@ -1063,7 +1344,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1063
1344
  writtenSkills = writeSkills(worktree, job.skills, log);
1064
1345
  const refs = await writeRefs(worktree);
1065
1346
  if (refs && 'failure' in refs)
1066
- return fail(refs.failure);
1347
+ return await fail(refs.failure);
1067
1348
  if (refs)
1068
1349
  writtenSkills = mergeWritten(writtenSkills, refs);
1069
1350
  }
@@ -1074,14 +1355,39 @@ export async function runJob(job, cfg, api, viewer, opts) {
1074
1355
  writtenSkills = mergeWritten(writtenSkills, prepared);
1075
1356
  }
1076
1357
  }
1358
+ if (job.release && job.repo && !toolsOnly && worktree) {
1359
+ const prepared = prepareReleaseFolder(worktree, log);
1360
+ if (prepared.dir) {
1361
+ releaseFolder = prepared.dir;
1362
+ writtenSkills = mergeWritten(writtenSkills, prepared);
1363
+ }
1364
+ }
1077
1365
  const heavyLock = !toolsOnly && job.repo && cfg.heavyLock !== false ? heavyLockDir(rdir, job.repo) : null;
1078
1366
  const heavyHelper = heavyLock ? ensureHeavyScript(rdir) : null;
1367
+ let briefSeq = 0;
1368
+ let briefDir;
1369
+ const buildInvocation = (c) => fenceBrief(adapter.buildInvocation(c), c.prompt, {
1370
+ seq: ++briefSeq,
1371
+ log,
1372
+ folder: () => {
1373
+ if (briefDir === undefined) {
1374
+ const prepared = worktree ? prepareBriefFolder(worktree, log) : null;
1375
+ briefDir = prepared?.dir ?? null;
1376
+ if (prepared?.dir)
1377
+ writtenSkills = mergeWritten(writtenSkills, prepared);
1378
+ }
1379
+ return briefDir;
1380
+ },
1381
+ }).invocation;
1382
+ const slots = heavySlots(cfg.heavySlots);
1079
1383
  const deviceHelper = heavyHelper ? ensureDeviceScript(rdir) : null;
1080
1384
  const heavily = (fn) => heavyLock
1081
1385
  ? withHeavyLock(heavyLock, fn, {
1082
1386
  label: `setup of ${job.runId}`,
1387
+ slots,
1388
+ tag: heavyTag(job.runId),
1083
1389
  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`),
1390
+ 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
1391
  })
1086
1392
  : fn();
1087
1393
  const setupMs = (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000;
@@ -1106,7 +1412,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1106
1412
  const fold = (text) => foldHome(stripWorktree(text, checkout), homedir());
1107
1413
  const why = setupReason(fold(r.stderr), fold(r.stdout));
1108
1414
  const said = why ? oneLine(why, 200).replace(/[.\s]+$/, '') : '';
1109
- return fail(`Setup command failed (exit ${r.code}): ${setupCommandName(cmd)}` +
1415
+ return await fail(`Setup command failed (exit ${r.code}): ${setupCommandName(cmd)}` +
1110
1416
  `${said ? ` — ${said}` : ''}. ` +
1111
1417
  '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
1418
  }
@@ -1123,8 +1429,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
1123
1429
  bgProcs.push(spawnBackground(cmd, { cwd: worktree, env: runEnv }));
1124
1430
  }
1125
1431
  await api.event(job.runId, 'fixing', { title: job.title });
1432
+ await reportWorktree(api, job.runId, worktree, 'live');
1126
1433
  const mode = job.permissionMode ?? cfg.permissionMode ?? 'bypassPermissions';
1127
- const model = job.model ?? cfg.model ?? null;
1434
+ const model = (phase === 'plan' && job.planModel ? job.planModel : null) ?? job.model ?? cfg.model ?? null;
1128
1435
  const effort = job.effort ?? cfg.effort ?? null;
1129
1436
  const ultracode = effort === 'ultracode';
1130
1437
  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 +1440,12 @@ export async function runJob(job, cfg, api, viewer, opts) {
1133
1440
  heavy: heavyHelper !== null,
1134
1441
  device: deviceHelper !== null,
1135
1442
  attach: attachFolder !== null,
1443
+ release: releaseFolder !== null ? (job.release ?? null) : null,
1444
+ toolsOnly,
1136
1445
  });
1137
1446
  const carriedNote = carriedNotes.length ? `${carriedNotes.join('\n\n')}\n\n` : '';
1138
- const prompt = rules +
1447
+ const prompt = (restoredFrom ? resumeFromCheckpointBrief(restoredFrom.at) : '') +
1448
+ rules +
1139
1449
  observeNote +
1140
1450
  attachNote +
1141
1451
  carriedNote +
@@ -1158,6 +1468,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
1158
1468
  }
1159
1469
  log(mcp ? `mcp: ${mcp.logLine}` : 'mcp: no server was injected for this run');
1160
1470
  }
1471
+ const temp = makeRunTemp(job.runId);
1472
+ if (temp) {
1473
+ runTemp = temp.dir;
1474
+ updateHeld(rdir, job.runId, { scratch: [temp.dir] });
1475
+ }
1161
1476
  const ctx = {
1162
1477
  prompt,
1163
1478
  model,
@@ -1171,12 +1486,27 @@ export async function runJob(job, cfg, api, viewer, opts) {
1171
1486
  isWin,
1172
1487
  runEnv: {
1173
1488
  ...stripForeignEngineCreds(runEnv, adapter.id),
1489
+ ...workTempEnv(),
1490
+ ...(temp?.env ?? {}),
1174
1491
  ...agentEnv,
1175
1492
  ...(heavyHelper && heavyLock
1176
- ? { FIREFUNC_HEAVY: heavyHelper, FIREFUNC_HEAVY_LOCK: heavyLock }
1493
+ ? {
1494
+ FIREFUNC_HEAVY: heavyHelper,
1495
+ FIREFUNC_HEAVY_LOCK: heavyLock,
1496
+ FIREFUNC_HEAVY_SLOTS: String(slots),
1497
+ FIREFUNC_HEAVY_TAG: heavyTag(job.runId),
1498
+ }
1177
1499
  : {}),
1178
1500
  ...(deviceHelper
1179
- ? { FIREFUNC_DEVICE: deviceHelper, FIREFUNC_DEVICE_LOCK: deviceLockDir(rdir) }
1501
+ ? {
1502
+ FIREFUNC_DEVICE: deviceHelper,
1503
+ FIREFUNC_DEVICE_LOCK: deviceLockDir(rdir),
1504
+ FIREFUNC_DEVICE_SESSION: job.runId,
1505
+ FIREFUNC_DEVICE_EMULATORS: String(emulatorBudget(cfg.maxEmulators)),
1506
+ ...(deviceSerials(cfg.devices)
1507
+ ? { FIREFUNC_DEVICE_SERIALS: deviceSerials(cfg.devices) }
1508
+ : {}),
1509
+ }
1180
1510
  : {}),
1181
1511
  },
1182
1512
  cfg,
@@ -1200,19 +1530,22 @@ export async function runJob(job, cfg, api, viewer, opts) {
1200
1530
  prompt: reviseBrief(revising.note, revising.round),
1201
1531
  }
1202
1532
  : { ...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;
1533
+ : resumeCut && !(resumeCut.sessionId && adapter.resumesSessions)
1534
+ ?
1535
+ { ...ctx, prompt: resumeBrief(ctx.prompt, 'limit') }
1536
+ : resumeCut
1537
+ ? {
1538
+ ...ctx,
1539
+ resumeSessionId: resumeCut.sessionId,
1540
+ prompt: resumeAfterResetBrief(prompt, promptHash(job.prompt) !== resumeCut.promptHash, resumeCut.reason),
1541
+ }
1542
+ : ctx;
1210
1543
  let inv;
1211
1544
  try {
1212
- inv = adapter.buildInvocation(firstCtx);
1545
+ inv = buildInvocation(firstCtx);
1213
1546
  }
1214
1547
  catch (e) {
1215
- return fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
1548
+ return await fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
1216
1549
  }
1217
1550
  const engineName = adapter.displayName;
1218
1551
  log(`running ${inv.bin} (${engineName}) on ${toolsOnly ? 'no repository — tools only' : `${job.repo} (${branch})`} — model=${model ?? 'default'} effort=${effort ?? 'default'} mode=${mode}`);
@@ -1227,20 +1560,49 @@ export async function runJob(job, cfg, api, viewer, opts) {
1227
1560
  for (const name of mcp?.writeToolNames ?? [])
1228
1561
  trailWriteTools.add(name);
1229
1562
  const activityParser = makeStreamJsonParser(activity.push, { toolResults: true });
1563
+ let heldSession = null;
1564
+ const noteSession = (chunk) => {
1565
+ if (!adapter.resumesSessions || parkStep || step)
1566
+ return;
1567
+ const id = SESSION_ID_IN_STREAM.exec(chunk)?.[1];
1568
+ if (!id || id === heldSession)
1569
+ return;
1570
+ heldSession = id;
1571
+ updateHeld(rdir, job.runId, {
1572
+ resume: {
1573
+ workItemId: job.workItemId,
1574
+ engine: adapter.id,
1575
+ sessionId: id,
1576
+ repo: job.repo ?? null,
1577
+ branch: toolsOnly ? '' : branch,
1578
+ base,
1579
+ repoPath: toolsOnly ? null : (repoPath ?? null),
1580
+ ...(readHead ? { readHead } : {}),
1581
+ promptHash: promptHash(job.prompt),
1582
+ review,
1583
+ toolsOnly,
1584
+ continuesBranch,
1585
+ writtenSkills,
1586
+ },
1587
+ });
1588
+ };
1230
1589
  const onStdout = (chunk) => {
1590
+ noteSession(chunk);
1231
1591
  const shown = blankSecrets(chunk);
1232
1592
  printer?.(shown);
1233
1593
  viewer?.push(job.runId, shown);
1234
1594
  activityParser(chunk);
1235
1595
  trail?.feed(chunk);
1596
+ localChecks.feed(chunk);
1236
1597
  };
1237
1598
  if (printer) {
1238
1599
  log(`── live ${engineName} session (shown here only — never sent to FireFunc) ──`);
1239
1600
  }
1240
- const heartbeat = setInterval(() => void api.event(job.runId, 'heartbeat'), 5 * 60_000);
1241
1601
  const engineCwd = worktree;
1242
1602
  let engineMs = 0;
1243
1603
  const runEngineOnce = async (limitMs = timeoutMs) => {
1604
+ if (isStopped(job.runId))
1605
+ return { code: 143, stdout: '', stderr: '' };
1244
1606
  let group = 0;
1245
1607
  const started = Date.now();
1246
1608
  try {
@@ -1252,17 +1614,21 @@ export async function runJob(job, cfg, api, viewer, opts) {
1252
1614
  shell: inv.shell,
1253
1615
  onStdout,
1254
1616
  ownGroup: true,
1617
+ signalGroup: signalGroupSparingDevices,
1255
1618
  onSpawn: (pid) => {
1256
1619
  group = pid;
1257
1620
  engineGroups.push({ pgid: pid, startedAt: started });
1258
1621
  trackEngineGroup(pid);
1622
+ trackRunGroup(job.runId, pid);
1259
1623
  updateHeld(rdir, job.runId, { engineGroup: pid, engineStartedAt: started });
1260
1624
  },
1261
1625
  });
1262
1626
  }
1263
1627
  finally {
1264
- if (group)
1628
+ if (group) {
1265
1629
  untrackEngineGroup(group);
1630
+ untrackRunGroup(job.runId, group);
1631
+ }
1266
1632
  engineMs += Date.now() - started;
1267
1633
  }
1268
1634
  };
@@ -1302,9 +1668,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
1302
1668
  lastReport = u;
1303
1669
  sessions.push({ usage: u, session: adapter.sessionId?.(stdout) ?? null, continued });
1304
1670
  };
1305
- const limitOf = (stdout) => {
1671
+ const limitOf = (stdout, stderr = '') => {
1306
1672
  try {
1307
- return adapter.planLimit?.(stdout, now()) ?? null;
1673
+ return adapter.planLimit?.(stdout, now(), stderr) ?? null;
1308
1674
  }
1309
1675
  catch {
1310
1676
  return null;
@@ -1315,14 +1681,71 @@ export async function runJob(job, cfg, api, viewer, opts) {
1315
1681
  summary: adapter.summarize(stdout),
1316
1682
  stderr,
1317
1683
  });
1318
- let engineRun = await runEngine();
1684
+ const checkpointMs = !toolsOnly && !review && !askFirst && job.repo ? checkpointEveryMs(cfg.checkpointMinutes) : 0;
1685
+ let lastCheckpoint = null;
1686
+ let checkpointing = null;
1687
+ const checkpointNow = async () => {
1688
+ if (isStopped(job.runId) || !worktree || !job.repo)
1689
+ return;
1690
+ if (!existsSync(worktree)) {
1691
+ if (checkpointTimer)
1692
+ clearInterval(checkpointTimer);
1693
+ return;
1694
+ }
1695
+ const cred = await api.gitCredential(job.runId).catch(() => null);
1696
+ const saved = await saveCheckpoint({
1697
+ worktree,
1698
+ runId: job.runId,
1699
+ from: readHead ?? `origin/${base}`,
1700
+ excludes: [
1701
+ ':(exclude).env',
1702
+ ':(exclude).claude/skills',
1703
+ ':(exclude).firefunc',
1704
+ `:(exclude,literal)${AGENT_PR_FILE}`,
1705
+ ...writtenSkills.pathspecs,
1706
+ ],
1707
+ env: cred ? gitAuthEnv(cred.token, job.repo) : {},
1708
+ last: lastCheckpoint,
1709
+ }, { log });
1710
+ if (saved.tree)
1711
+ lastCheckpoint = { tree: saved.tree };
1712
+ if (saved.saved && !isStopped(job.runId)) {
1713
+ const at = now().toISOString();
1714
+ log(`saved ${job.runId}'s work to ${saved.ref} (${saved.sha.slice(0, 8)})`);
1715
+ await api.event(job.runId, 'checkpoint', { ref: saved.ref, sha: saved.sha, at });
1716
+ }
1717
+ else if (!saved.saved && saved.why !== 'unchanged') {
1718
+ log(`checkpoint of ${job.runId} not saved (${saved.why})`);
1719
+ }
1720
+ };
1721
+ const checkpointTimer = checkpointMs > 0
1722
+ ? setInterval(() => {
1723
+ if (checkpointing)
1724
+ return;
1725
+ checkpointing = checkpointNow()
1726
+ .catch(() => { })
1727
+ .finally(() => {
1728
+ checkpointing = null;
1729
+ });
1730
+ }, checkpointMs)
1731
+ : null;
1732
+ checkpointTimer?.unref();
1733
+ let engineRun;
1734
+ try {
1735
+ engineRun = await runEngine();
1736
+ }
1737
+ catch (err) {
1738
+ if (checkpointTimer)
1739
+ clearInterval(checkpointTimer);
1740
+ throw err;
1741
+ }
1319
1742
  meter(engineRun.stdout, false);
1320
1743
  if (resumeCut &&
1321
1744
  firstCtx.resumeSessionId &&
1322
1745
  engineRun.code !== 0 &&
1323
1746
  !adapter.sessionId?.(engineRun.stdout)) {
1324
1747
  log(`${engineName} could not continue the session a plan limit cut — starting a new session in the same worktree`);
1325
- inv = adapter.buildInvocation({
1748
+ inv = buildInvocation({
1326
1749
  ...ctx,
1327
1750
  prompt: parkBrief
1328
1751
  ? `${parkBrief}\n\n${ctx.prompt}`
@@ -1334,7 +1757,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1334
1757
  meter(engineRun.stdout, false);
1335
1758
  }
1336
1759
  for (let resumes = 0; resumes < 2 && engineRun.code !== 0; resumes++) {
1337
- if (limitOf(engineRun.stdout))
1760
+ if (limitOf(engineRun.stdout, engineRun.stderr))
1338
1761
  break;
1339
1762
  if (refused(engineRun.stdout, engineRun.stderr))
1340
1763
  break;
@@ -1354,16 +1777,76 @@ export async function runJob(job, cfg, api, viewer, opts) {
1354
1777
  break;
1355
1778
  }
1356
1779
  log(`the network is back — resuming ${engineName} in the same worktree`);
1357
- inv = adapter.buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt) });
1780
+ inv = buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt) });
1358
1781
  engineRun = await runEngine();
1359
1782
  meter(engineRun.stdout, false);
1360
1783
  }
1784
+ let firefuncAway = null;
1785
+ if (engineRun.code === 0 &&
1786
+ mcp?.serverIds.includes('firefunc') &&
1787
+ !parkStep &&
1788
+ !step &&
1789
+ !limitOf(engineRun.stdout, engineRun.stderr) &&
1790
+ !refused(engineRun.stdout, engineRun.stderr) &&
1791
+ mcpServersFailedAtStart(engineRun.stdout).includes('firefunc')) {
1792
+ log(`${engineName}'s session started without FireFunc's own tools — the firefunc MCP server failed to connect; checking the network before continuing it`);
1793
+ const back = (await api.probe()) ||
1794
+ (await waitForNetwork({ probe: () => api.probe(), maxWaitMs: 20 * 60_000, log }));
1795
+ if (!back) {
1796
+ log('the network did not come back within 20 minutes — giving up on this attempt');
1797
+ firefuncAway = 'network';
1798
+ }
1799
+ else {
1800
+ const again = adapter.resumesSessions
1801
+ ? (adapter.sessionId?.(engineRun.stdout) ?? null)
1802
+ : null;
1803
+ log(`continuing ${engineName}'s session once now that FireFunc can be reached`);
1804
+ inv = buildInvocation({
1805
+ ...ctx,
1806
+ prompt: again ? firefuncReconnectedBrief() : resumeBrief(ctx.prompt),
1807
+ ...(again ? { resumeSessionId: again } : {}),
1808
+ });
1809
+ engineRun = await runEngine();
1810
+ meter(engineRun.stdout, !!again);
1811
+ if (engineRun.code === 0 &&
1812
+ mcpServersFailedAtStart(engineRun.stdout).includes('firefunc')) {
1813
+ firefuncAway = 'still_failed';
1814
+ }
1815
+ }
1816
+ }
1361
1817
  {
1362
- const planCut = limitOf(engineRun.stdout);
1363
- if (planCut && adapter.id === 'claude_code' && fallbackKey(cfg, rdir)) {
1818
+ const planCut = limitOf(engineRun.stdout, engineRun.stderr);
1819
+ if (planCut &&
1820
+ adapter.id === 'claude_code' &&
1821
+ fallbackKey(cfg, rdir) &&
1822
+ !opts?.account?.held(adapter.id)) {
1364
1823
  const until = startFallback(planCut.resetsAt, rdir, now());
1365
1824
  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') });
1825
+ inv = buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt, 'api') });
1826
+ engineRun = await runEngine();
1827
+ meter(engineRun.stdout, false);
1828
+ }
1829
+ }
1830
+ if (adapter.id === 'claude_code' &&
1831
+ cfg.claudeUseApiKey === true &&
1832
+ cfg.claudeKeyToPlan === true &&
1833
+ claudeApiKeyNow(cfg, rdir, now()).why === 'opted-in' &&
1834
+ !opts?.account?.held(adapter.id)) {
1835
+ let closing;
1836
+ try {
1837
+ closing = adapter.ending?.(engineRun.stdout);
1838
+ }
1839
+ catch {
1840
+ closing = undefined;
1841
+ }
1842
+ const spentKey = accountProblemOf(closing, {
1843
+ billedKey: true,
1844
+ stderr: engineRun.code === 0 ? '' : engineRun.stderr,
1845
+ }) === 'api_key_no_credit';
1846
+ if (spentKey) {
1847
+ const until = startKeySpent(rdir, now());
1848
+ log(`${engineName}'s API key is out of credit — continuing on the plan until ${until.toISOString()}, in the same worktree`);
1849
+ inv = buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt, 'plan') });
1367
1850
  engineRun = await runEngine();
1368
1851
  meter(engineRun.stdout, false);
1369
1852
  }
@@ -1376,7 +1859,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1376
1859
  return [];
1377
1860
  }
1378
1861
  };
1379
- const endedOnItsAnswer = (r) => r.code === 0 && !limitOf(r.stdout) && !refused(r.stdout, r.stderr);
1862
+ const endedOnItsAnswer = (r) => r.code === 0 && !limitOf(r.stdout, r.stderr) && !refused(r.stdout, r.stderr);
1380
1863
  const parkNow = endedOnItsAnswer(engineRun) && (job.askPerson === true || phase === 'plan')
1381
1864
  ? await parkReasonFor({
1382
1865
  askPerson: job.askPerson === true,
@@ -1399,7 +1882,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1399
1882
  }
1400
1883
  else if ((open.length > 0 || promising) && toContinue) {
1401
1884
  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({
1885
+ inv = buildInvocation({
1403
1886
  ...ctx,
1404
1887
  prompt: continueToFinishBrief(open),
1405
1888
  resumeSessionId: toContinue,
@@ -1413,7 +1896,55 @@ export async function runJob(job, cfg, api, viewer, opts) {
1413
1896
  }
1414
1897
  openCommandAtEnd = open.length > 0;
1415
1898
  const unfinished = open.length > 0 || promising;
1416
- clearInterval(heartbeat);
1899
+ const stageArgs = [
1900
+ '-C',
1901
+ worktree,
1902
+ 'add',
1903
+ '-A',
1904
+ '--',
1905
+ '.',
1906
+ ':(exclude).env',
1907
+ ':(exclude).claude/skills',
1908
+ `:(exclude,literal)${AGENT_PR_FILE}`,
1909
+ ...writtenSkills.pathspecs,
1910
+ ];
1911
+ if (!review &&
1912
+ !toolsOnly &&
1913
+ !parkNow &&
1914
+ !unfinished &&
1915
+ toContinue &&
1916
+ endedOnItsAnswer(engineRun) &&
1917
+ !isStopped(job.runId)) {
1918
+ const from = continuesBranch ? `origin/${branch}` : `origin/${base}`;
1919
+ await exec('git', stageArgs).catch(() => null);
1920
+ const read = secretFixRead(from);
1921
+ const staged = await exec('git', ['-C', worktree, ...read.args], {
1922
+ timeoutMs: 120_000,
1923
+ env: read.env,
1924
+ }).catch(() => null);
1925
+ const refusing = staged?.code === 0 ? uniqueHits(scanAddedLines(staged.stdout)).filter(refusesPush) : [];
1926
+ const leftMs = timeoutMs - engineMs;
1927
+ if (refusing.length > 0 && leftMs >= 60_000) {
1928
+ const ahead = await exec('git', ['-C', worktree, 'rev-list', '--count', `${from}..HEAD`], {
1929
+ timeoutMs: 30_000,
1930
+ }).catch(() => null);
1931
+ const committed = ahead?.code === 0 && Number(ahead.stdout.trim()) > 0;
1932
+ log(`secret scan before the push for ${job.runId}: ${refusing.length} line(s) would refuse it — ${refusing
1933
+ .slice(0, 5)
1934
+ .map((h) => `${h.kind} at ${h.path}:${h.line}`)
1935
+ .join(', ')} — continuing ${engineName}'s session once to rewrite them`);
1936
+ inv = adapter.buildInvocation({
1937
+ ...ctx,
1938
+ prompt: secretFixBrief(refusing, from, committed),
1939
+ resumeSessionId: toContinue,
1940
+ });
1941
+ const fixRun = await runEngine(leftMs);
1942
+ meter(fixRun.stdout, true);
1943
+ log(fixRun.code === 0
1944
+ ? `${engineName} rewrote the lines; the push's own scan reads the change again`
1945
+ : `${engineName}'s continued session ended with exit ${fixRun.code}; the push's own scan decides`);
1946
+ }
1947
+ }
1417
1948
  usage =
1418
1949
  attemptUsage(sessions, resumeCut ? { session: resumeCut.sessionId, baseline: resumeCut.usage } : undefined) ?? undefined;
1419
1950
  if (revising && kept?.attemptUsage) {
@@ -1432,63 +1963,116 @@ export async function runJob(job, cfg, api, viewer, opts) {
1432
1963
  log(`reported ${activity.sent} of ${activity.seen} step(s) to FireFunc — names and verbs only; the session stayed here`);
1433
1964
  mcp?.cleanup();
1434
1965
  const sessionLogPath = saveSessionLog(job.runId, engineRun.stdout, engineRun.stderr);
1966
+ if (checkpointTimer)
1967
+ clearInterval(checkpointTimer);
1968
+ if (checkpointing)
1969
+ await checkpointing;
1435
1970
  const summary = adapter.summarize(engineRun.stdout);
1436
1971
  if (sessionLogPath)
1437
1972
  log(`${engineName} session saved → ${sessionLogPath}`);
1438
1973
  if (summary)
1439
1974
  log(`${engineName} said: ${summary.replace(/\s+/g, ' ').slice(0, 500)}`);
1440
- if (engineRun.code === 124) {
1441
- const timedOutSession = adapter.resumesSessions
1975
+ if (isStopped(job.runId))
1976
+ return await fail(stoppedByPersonSentence(engineName, 'engine'));
1977
+ const keepForNextRun = (reason) => {
1978
+ const sessionId = adapter.resumesSessions
1442
1979
  ? (adapter.sessionId?.(engineRun.stdout) ?? (resumeCut?.sessionId || null))
1443
1980
  : 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',
1981
+ if (!sessionId || !worktree || parkStep || step)
1982
+ return false;
1983
+ const cutAt = now().getTime();
1984
+ const kept = saveCut(rdir, {
1985
+ workItemId: job.workItemId,
1986
+ runId: job.runId,
1987
+ engine: adapter.id,
1988
+ sessionId,
1989
+ repo: job.repo ?? null,
1990
+ branch: toolsOnly ? '' : branch,
1991
+ base,
1992
+ worktree,
1993
+ repoPath: toolsOnly ? null : repoPath,
1994
+ ...(readHead ? { readHead } : {}),
1995
+ resetsAt: null,
1996
+ cutAt: new Date(cutAt).toISOString(),
1997
+ keepUntil: keepUntil(null, cutAt),
1998
+ promptHash: promptHash(job.prompt),
1999
+ review,
2000
+ toolsOnly,
2001
+ continuesBranch,
2002
+ ...(lastReport ? { usage: lastReport } : {}),
2003
+ writtenSkills,
2004
+ reason,
2005
+ });
2006
+ if (kept)
2007
+ keepWorktree = true;
2008
+ return kept;
2009
+ };
2010
+ {
2011
+ let ending;
2012
+ try {
2013
+ ending = adapter.ending?.(engineRun.stdout);
2014
+ }
2015
+ catch {
2016
+ ending = undefined;
2017
+ }
2018
+ const billing = claudeApiKeyNow(cfg, rdir, now());
2019
+ const billedKey = adapter.id === 'claude_code' && (billing.why === 'opted-in' || billing.key !== null);
2020
+ const problem = adapter.id === 'claude_code'
2021
+ ? accountProblemOf(ending, {
2022
+ billedKey,
2023
+ stderr: engineRun.code === 0 ? '' : engineRun.stderr,
2024
+ })
2025
+ : null;
2026
+ if (problem) {
2027
+ opts?.account?.met(adapter.id, problem, engineName);
2028
+ const block = opts?.account?.held(adapter.id) ??
2029
+ accountBlock(problem, engineName, ACCOUNT_RETRY_FIRST_MS / 60_000);
2030
+ const kept = keepForNextRun('auth');
2031
+ const sentence = cannotWorkSentence(engineName, block);
2032
+ log(`${job.runId}: ${sentence}`);
2033
+ return await report({
2034
+ status: 'failed',
2035
+ error: kept
2036
+ ? `${sentence} What the session made is kept on this machine for a day; the next run continues it.`
2037
+ : sentence,
2038
+ limit: { kind: 'machine', detail: block.detail },
1468
2039
  });
1469
2040
  }
1470
- keepWorktree = keptOnTimeout;
2041
+ }
2042
+ if (firefuncAway === 'network') {
2043
+ const kept = keepForNextRun('network');
2044
+ 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. ` +
2045
+ (kept
2046
+ ? 'Its work is kept on this machine for a day: Re-run continues it from where it stopped.'
2047
+ : 'Re-run the task once the machine is back online.'));
2048
+ }
2049
+ if (firefuncAway === 'still_failed') {
2050
+ 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. ` +
2051
+ "Re-run the task; if it happens again, check this machine's runner log for the MCP server's error.");
2052
+ }
2053
+ if (engineRun.code === 124) {
2054
+ const keptOnTimeout = keepForNextRun('timeout');
1471
2055
  const limitWords = budget !== null && limitMinutes === budget
1472
2056
  ? `${engineName} timed out after ${limitMinutes} min — the agent's time budget.`
1473
2057
  : `${engineName} timed out after ${limitMinutes} min.`;
1474
- return fail(keptOnTimeout
2058
+ return await fail(keptOnTimeout
1475
2059
  ? `${limitWords} Its work is kept on this machine for a day: Re-run continues it from where it stopped.`
1476
2060
  : limitWords);
1477
2061
  }
1478
- const limit = limitOf(engineRun.stdout);
2062
+ const limit = limitOf(engineRun.stdout, engineRun.stderr);
1479
2063
  if (limit) {
1480
2064
  opts?.limits?.set(adapter.id, limit);
1481
2065
  const cutSession = adapter.resumesSessions
1482
2066
  ? (adapter.sessionId?.(engineRun.stdout) ?? null)
1483
2067
  : null;
1484
2068
  let kept = false;
1485
- if (cutSession && worktree) {
2069
+ if (worktree) {
1486
2070
  const cutAt = now().getTime();
1487
2071
  kept = saveCut(rdir, {
1488
2072
  workItemId: job.workItemId,
1489
2073
  runId: job.runId,
1490
2074
  engine: adapter.id,
1491
- sessionId: cutSession,
2075
+ sessionId: cutSession ?? '',
1492
2076
  repo: job.repo ?? null,
1493
2077
  branch: toolsOnly ? '' : branch,
1494
2078
  base,
@@ -1509,10 +2093,14 @@ export async function runJob(job, cfg, api, viewer, opts) {
1509
2093
  keepWorktree = kept;
1510
2094
  log(`${engineName} was stopped by the plan's usage limit${limit.said ? ` ("${limit.said}")` : ''} — ` +
1511
2095
  (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({
2096
+ (kept
2097
+ ? cutSession
2098
+ ? '; the session and its worktree are kept to continue after the reset'
2099
+ : '; its worktree is kept for a new session to go on from after the reset'
2100
+ : ''));
2101
+ return await report({
1514
2102
  status: 'failed',
1515
- error: limitSentence(engineName, limit, kept),
2103
+ error: limitSentence(engineName, limit, kept ? (cutSession ? 'session' : 'worktree') : false),
1516
2104
  limit: { kind: 'plan', resetsAt: limit.resetsAt },
1517
2105
  });
1518
2106
  }
@@ -1522,6 +2110,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1522
2110
  log(`the model declined ${job.runId}: its safety system refused the session`);
1523
2111
  return { status: 'failed', error: modelDeclinedSentence(engineName) };
1524
2112
  };
2113
+ let authFailed = false;
1525
2114
  const scanHints = () => {
1526
2115
  const declined = declinedHint();
1527
2116
  if (declined)
@@ -1529,6 +2118,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1529
2118
  const authMsg = adapter.authFailureHint(`${summary}\n${engineRun.stderr}`);
1530
2119
  if (authMsg) {
1531
2120
  log(`auth/billing failure for ${job.runId}: ${authMsg}`);
2121
+ authFailed = true;
1532
2122
  return { status: 'failed', error: authMsg };
1533
2123
  }
1534
2124
  const rateMsg = adapter.rateLimitHint(`${summary}\n${engineRun.stderr}`);
@@ -1571,11 +2161,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
1571
2161
  toolsOnly,
1572
2162
  });
1573
2163
  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.`);
2164
+ 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
2165
  }
1576
2166
  keepWorktree = true;
1577
2167
  log(parkedLine(job.runId, parkNow));
1578
- return report({
2168
+ return await report({
1579
2169
  status: 'parked',
1580
2170
  park: {
1581
2171
  kind: parkNow.kind,
@@ -1589,20 +2179,35 @@ export async function runJob(job, cfg, api, viewer, opts) {
1589
2179
  const signal = endedBySignal(engineRun.code);
1590
2180
  if (signal) {
1591
2181
  log(`${engineName} was ended by ${signal} (exit ${engineRun.code}) for ${job.runId}`);
1592
- return fail(stoppedSentence(engineName, engineRun.code, signal, sessionLogPath ? basename(sessionLogPath) : null));
2182
+ return await fail(stoppedSentence(engineName, engineRun.code, signal, sessionLogPath ? basename(sessionLogPath) : null));
2183
+ }
2184
+ const outage = networkFailureHint(`${adapter.summarize(engineRun.stdout)}\n${engineRun.stderr.slice(-2000)}`);
2185
+ if (outage && !refused(engineRun.stdout, engineRun.stderr)) {
2186
+ const kept = keepForNextRun('network');
2187
+ return await fail(`${engineName} stopped because ${outage}, and the network did not come back in time for the runner to resume it. ` +
2188
+ (kept
2189
+ ? 'Its work is kept on this machine for a day: Re-run continues it from where it stopped.'
2190
+ : 'Re-run the task once the machine is back online.'));
1593
2191
  }
1594
2192
  const hinted = scanHints();
1595
- if (hinted)
1596
- return report(hinted);
2193
+ if (hinted) {
2194
+ if (authFailed && keepForNextRun('auth')) {
2195
+ return await report({
2196
+ ...hinted,
2197
+ 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.`,
2198
+ });
2199
+ }
2200
+ return await report(hinted);
2201
+ }
1597
2202
  const why = summary ? null : errorLine(engineRun.stderr);
1598
- return fail(summary
2203
+ return await fail(summary
1599
2204
  ? `${engineName} exited abnormally (code ${engineRun.code}). Last message: ${oneLine(shareable(summary), 500)}`
1600
2205
  : `${engineName} exited abnormally (code ${engineRun.code})${why ? `: ${oneLine(stripWorktree(why, worktree), 200)}` : ''}. ` +
1601
2206
  `Its output stayed on the machine${sessionLogPath ? ` — the session log is logs/${basename(sessionLogPath)} in the runner’s folder` : ''}.`);
1602
2207
  }
1603
2208
  if (unfinished) {
1604
2209
  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));
2210
+ return await fail(unfinishedSentence(engineName, open, !review && !toolsOnly, continuedOnce));
1606
2211
  }
1607
2212
  if (review) {
1608
2213
  const dirty = await exec('git', ['-C', worktree, 'status', '--porcelain']);
@@ -1612,9 +2217,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
1612
2217
  }
1613
2218
  const declinedReview = declinedHint();
1614
2219
  if (declinedReview)
1615
- return report(declinedReview);
2220
+ return await report(declinedReview);
1616
2221
  log(`review run ${job.runId} finished — reporting the agent's review`);
1617
- return report({
2222
+ return await report({
1618
2223
  status: 'no_pr',
1619
2224
  ...(summary
1620
2225
  ? { summary: reportedSummary(summary) }
@@ -1624,27 +2229,16 @@ export async function runJob(job, cfg, api, viewer, opts) {
1624
2229
  if (toolsOnly) {
1625
2230
  const declinedAnswer = declinedHint();
1626
2231
  if (declinedAnswer)
1627
- return report(declinedAnswer);
2232
+ return await report(declinedAnswer);
1628
2233
  log(`tools-only run ${job.runId} finished — reporting the agent's summary`);
1629
- return report({
2234
+ return await report({
1630
2235
  status: 'no_pr',
1631
2236
  ...(summary
1632
2237
  ? { summary: reportedSummary(summary) }
1633
2238
  : { error: `${engineName} finished without a summary of what it did.` }),
1634
2239
  });
1635
2240
  }
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
- ]);
2241
+ await exec('git', stageArgs);
1648
2242
  const vsBase = await exec('git', [
1649
2243
  '-C',
1650
2244
  worktree,
@@ -1656,9 +2250,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
1656
2250
  if (vsBase.code === 0) {
1657
2251
  const hinted = scanHints();
1658
2252
  if (hinted)
1659
- return report(hinted);
2253
+ return await report(hinted);
1660
2254
  log(`no changes produced for ${job.runId} — reporting no_pr`);
1661
- return report({
2255
+ return await report({
1662
2256
  status: 'no_pr',
1663
2257
  error: summary
1664
2258
  ? `No code change made. ${engineName}: ${oneLine(shareable(summary), 800)}`
@@ -1686,7 +2280,16 @@ export async function runJob(job, cfg, api, viewer, opts) {
1686
2280
  log(`${kind === 'test' ? 'the change touches tests only — ' : ''}titled "${title}"`);
1687
2281
  const uncommitted = await exec('git', ['-C', worktree, 'diff', '--cached', '--quiet', 'HEAD']);
1688
2282
  if (uncommitted.code !== 0) {
1689
- await exec('git', ['-C', worktree, 'commit', '-m', title, '--quiet']);
2283
+ const trailers = provenanceTrailers(job);
2284
+ await exec('git', [
2285
+ '-C',
2286
+ worktree,
2287
+ 'commit',
2288
+ '-m',
2289
+ title,
2290
+ ...(trailers ? ['-m', trailers] : []),
2291
+ '--quiet',
2292
+ ]);
1690
2293
  }
1691
2294
  else {
1692
2295
  log(`agent already committed its changes for ${job.runId} — reconciling to a PR`);
@@ -1700,6 +2303,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1700
2303
  engineName,
1701
2304
  summary,
1702
2305
  agentText,
2306
+ keepOnPushFailure: () => keepForNextRun('push'),
1703
2307
  keep: askFirst
1704
2308
  ? {
1705
2309
  sessionId: adapter.sessionId?.(engineRun.stdout) ?? (resumeCut?.sessionId || null),
@@ -1711,7 +2315,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1711
2315
  }
1712
2316
  catch (err) {
1713
2317
  log(`job ${job.runId} errored: ${err.message}`);
1714
- return report({ status: 'failed', error: err.message.slice(0, 400) });
2318
+ return await report({ status: 'failed', error: err.message.slice(0, 400) });
1715
2319
  }
1716
2320
  finally {
1717
2321
  if (job.agentEnv?.length) {
@@ -1721,9 +2325,12 @@ export async function runJob(job, cfg, api, viewer, opts) {
1721
2325
  viewer?.end(job.runId, 'failed');
1722
2326
  await Promise.all(bgProcs.map((p) => killProcessTree(p).catch(() => { })));
1723
2327
  const reviewCopies = worktree ? reviewCopiesOf(worktree) : [];
1724
- if (worktree || engineGroups.length > 0) {
2328
+ const letGo = await releaseDeviceHolds(deviceLockDir(rdir), job.runId).catch(() => []);
2329
+ if (letGo.length > 0)
2330
+ log(`let go of the device this session still held (${letGo.join(', ')})`);
2331
+ if (worktree || runTemp || engineGroups.length > 0) {
1725
2332
  await killOrphans({
1726
- roots: [worktree, attachDir, ...reviewCopies].filter((p) => !!p),
2333
+ roots: [worktree, attachDir, runTemp, ...reviewCopies].filter((p) => !!p),
1727
2334
  ...(worktree ? { reviewCopiesOf: basename(worktree) } : {}),
1728
2335
  groups: engineGroups.map((g) => ({ ...g, leaderExited: true })),
1729
2336
  }, { log }).catch(() => { });
@@ -1763,6 +2370,10 @@ export async function runJob(job, cfg, api, viewer, opts) {
1763
2370
  catch {
1764
2371
  }
1765
2372
  }
2373
+ if (!keepWorktree)
2374
+ removeRunTemp(runTemp);
2375
+ if (worktree)
2376
+ await reportWorktree(api, job.runId, worktree, endedState(worktree, keepWorktree));
1766
2377
  }
1767
2378
  }
1768
2379
  //# sourceMappingURL=job.js.map