@firefunc-agent/runner 0.9.7 → 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 (178) hide show
  1. package/README.md +169 -10
  2. package/dist/activity.d.ts +1 -0
  3. package/dist/activity.js +1 -1
  4. package/dist/alive.d.ts +40 -0
  5. package/dist/alive.js +138 -0
  6. package/dist/api-fallback.d.ts +11 -0
  7. package/dist/api-fallback.js +80 -0
  8. package/dist/api.d.ts +186 -3
  9. package/dist/api.js +311 -6
  10. package/dist/ask/index.d.ts +20 -0
  11. package/dist/ask/index.js +64 -0
  12. package/dist/ask-first.d.ts +8 -0
  13. package/dist/brief-file.d.ts +15 -0
  14. package/dist/brief-file.js +36 -0
  15. package/dist/brief.d.ts +5 -0
  16. package/dist/brief.js +19 -3
  17. package/dist/build-caches.d.ts +7 -0
  18. package/dist/build-caches.js +63 -0
  19. package/dist/build-info.json +2 -2
  20. package/dist/checkpoint.d.ts +40 -0
  21. package/dist/checkpoint.js +98 -0
  22. package/dist/cli.js +184 -18
  23. package/dist/cloud-boot.d.ts +41 -0
  24. package/dist/cloud-boot.js +239 -0
  25. package/dist/command-activity.d.ts +23 -0
  26. package/dist/command-activity.js +89 -0
  27. package/dist/command-step.d.ts +58 -0
  28. package/dist/command-step.js +248 -0
  29. package/dist/config.d.ts +40 -0
  30. package/dist/config.js +23 -0
  31. package/dist/cut.d.ts +2 -1
  32. package/dist/cut.js +19 -5
  33. package/dist/daemon.js +375 -14
  34. package/dist/device-lease.d.ts +15 -0
  35. package/dist/device-lease.js +608 -0
  36. package/dist/editor/fs-server.d.ts +31 -0
  37. package/dist/editor/fs-server.js +159 -0
  38. package/dist/editor/relay-crypto.d.ts +68 -0
  39. package/dist/editor/relay-crypto.js +191 -0
  40. package/dist/editor/sessions.d.ts +50 -0
  41. package/dist/editor/sessions.js +279 -0
  42. package/dist/editor/worktree-of.d.ts +1 -0
  43. package/dist/editor/worktree-of.js +23 -0
  44. package/dist/editor/ws-client.d.ts +26 -0
  45. package/dist/editor/ws-client.js +227 -0
  46. package/dist/engine-account.d.ts +24 -0
  47. package/dist/engine-account.js +118 -0
  48. package/dist/engine-login.d.ts +12 -0
  49. package/dist/engine-login.js +88 -0
  50. package/dist/engine-models.d.ts +13 -0
  51. package/dist/engine-models.js +71 -0
  52. package/dist/engine-watch.d.ts +1 -0
  53. package/dist/engine-watch.js +22 -6
  54. package/dist/engines/antigravity.js +19 -4
  55. package/dist/engines/claude.js +15 -8
  56. package/dist/engines/codex.js +16 -2
  57. package/dist/engines/copilot.js +12 -0
  58. package/dist/engines/crush.d.ts +2 -0
  59. package/dist/engines/crush.js +58 -0
  60. package/dist/engines/cursor.js +12 -0
  61. package/dist/engines/gemini.js +14 -9
  62. package/dist/engines/index.d.ts +8 -0
  63. package/dist/engines/index.js +73 -1
  64. package/dist/engines/kilo.d.ts +2 -0
  65. package/dist/engines/kilo.js +63 -0
  66. package/dist/engines/opencode.d.ts +9 -0
  67. package/dist/engines/opencode.js +234 -0
  68. package/dist/engines/openhands.d.ts +10 -0
  69. package/dist/engines/openhands.js +271 -0
  70. package/dist/engines/pi.d.ts +10 -0
  71. package/dist/engines/pi.js +248 -0
  72. package/dist/engines/qwen.d.ts +8 -0
  73. package/dist/engines/qwen.js +153 -0
  74. package/dist/engines/sessions.d.ts +6 -0
  75. package/dist/engines/sessions.js +68 -0
  76. package/dist/engines/types.d.ts +3 -3
  77. package/dist/exec.d.ts +1 -0
  78. package/dist/exec.js +10 -4
  79. package/dist/firefunc/agents.d.ts +8 -1
  80. package/dist/firefunc/agents.js +53 -3
  81. package/dist/firefunc/auth.js +72 -19
  82. package/dist/firefunc/cli.js +25 -0
  83. package/dist/firefunc/client.d.ts +5 -1
  84. package/dist/firefunc/client.js +12 -2
  85. package/dist/firefunc/config.d.ts +11 -1
  86. package/dist/firefunc/config.js +6 -4
  87. package/dist/firefunc/io.d.ts +1 -0
  88. package/dist/firefunc/main.js +8 -1
  89. package/dist/firefunc/oauth-login.d.ts +23 -0
  90. package/dist/firefunc/oauth-login.js +304 -0
  91. package/dist/firefunc/tasks.d.ts +4 -0
  92. package/dist/firefunc/tasks.js +89 -2
  93. package/dist/fleet-words.d.ts +2 -0
  94. package/dist/fleet-words.js +7 -0
  95. package/dist/git-auth.d.ts +16 -0
  96. package/dist/git-auth.js +48 -2
  97. package/dist/held.d.ts +3 -0
  98. package/dist/job.d.ts +26 -3
  99. package/dist/job.js +1109 -132
  100. package/dist/keep-awake.d.ts +17 -0
  101. package/dist/keep-awake.js +90 -0
  102. package/dist/keep-local.d.ts +2 -1
  103. package/dist/keep-local.js +8 -3
  104. package/dist/limit.d.ts +10 -1
  105. package/dist/limit.js +264 -4
  106. package/dist/local-checks.d.ts +19 -0
  107. package/dist/local-checks.js +79 -0
  108. package/dist/locks.d.ts +21 -1
  109. package/dist/locks.js +279 -66
  110. package/dist/machine-commands.d.ts +21 -0
  111. package/dist/machine-commands.js +107 -0
  112. package/dist/machine-profile.d.ts +18 -0
  113. package/dist/machine-profile.js +69 -0
  114. package/dist/mcp-init.d.ts +2 -0
  115. package/dist/mcp-init.js +28 -0
  116. package/dist/mcp.d.ts +13 -1
  117. package/dist/mcp.js +23 -2
  118. package/dist/network.js +3 -2
  119. package/dist/orphans.d.ts +4 -0
  120. package/dist/orphans.js +96 -4
  121. package/dist/plan-phase/index.d.ts +11 -0
  122. package/dist/plan-phase/index.js +46 -0
  123. package/dist/pool.d.ts +1 -0
  124. package/dist/pool.js +29 -4
  125. package/dist/pr-title.d.ts +15 -0
  126. package/dist/pr-title.js +33 -0
  127. package/dist/recover.d.ts +3 -1
  128. package/dist/recover.js +27 -7
  129. package/dist/reference-files.d.ts +27 -0
  130. package/dist/reference-files.js +202 -0
  131. package/dist/release-draft.d.ts +79 -0
  132. package/dist/release-draft.js +301 -0
  133. package/dist/resources.d.ts +86 -0
  134. package/dist/resources.js +217 -0
  135. package/dist/restart-idle.d.ts +23 -0
  136. package/dist/restart-idle.js +67 -0
  137. package/dist/run-attachments.d.ts +84 -0
  138. package/dist/run-attachments.js +281 -0
  139. package/dist/run-stops.d.ts +15 -0
  140. package/dist/run-stops.js +90 -0
  141. package/dist/run-temp.d.ts +12 -0
  142. package/dist/run-temp.js +57 -0
  143. package/dist/secret-scan.d.ts +6 -1
  144. package/dist/secret-scan.js +33 -0
  145. package/dist/secret-values.d.ts +17 -0
  146. package/dist/secret-values.js +81 -0
  147. package/dist/self-upgrade.d.ts +36 -0
  148. package/dist/self-upgrade.js +78 -0
  149. package/dist/service.d.ts +7 -1
  150. package/dist/service.js +50 -7
  151. package/dist/sign-in.d.ts +41 -0
  152. package/dist/sign-in.js +239 -0
  153. package/dist/tool-call.d.ts +59 -0
  154. package/dist/tool-call.js +375 -0
  155. package/dist/trail/chain.d.ts +12 -0
  156. package/dist/trail/chain.js +89 -0
  157. package/dist/trail/deltas.d.ts +34 -0
  158. package/dist/trail/deltas.js +206 -0
  159. package/dist/trail/index.d.ts +27 -0
  160. package/dist/trail/index.js +128 -0
  161. package/dist/trail/keys.d.ts +14 -0
  162. package/dist/trail/keys.js +61 -0
  163. package/dist/trail/recorder.d.ts +118 -0
  164. package/dist/trail/recorder.js +697 -0
  165. package/dist/trail/rules.d.ts +30 -0
  166. package/dist/trail/rules.js +158 -0
  167. package/dist/trail/stream.d.ts +41 -0
  168. package/dist/trail/stream.js +86 -0
  169. package/dist/transport.d.ts +26 -0
  170. package/dist/transport.js +118 -0
  171. package/dist/work-dir.d.ts +11 -0
  172. package/dist/work-dir.js +69 -0
  173. package/dist/worktree-report.d.ts +10 -0
  174. package/dist/worktree-report.js +17 -0
  175. package/dist/worktrees.d.ts +16 -1
  176. package/dist/worktrees.js +62 -17
  177. package/package.json +4 -4
  178. package/skill/firefunc/SKILL.md +4 -3
package/dist/job.js CHANGED
@@ -1,36 +1,59 @@
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
- import { homedir, tmpdir } from 'node:os';
4
+ import { readFile } from 'node:fs/promises';
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';
3
11
  import { join, basename, dirname, relative, sep } from 'node:path';
4
12
  import {} from 'node:child_process';
5
13
  import { exec, execOut, spawnBackground, killProcessTree } from './exec.js';
6
14
  import { REPORTED_SUMMARY_MAX, cutText } from './api.js';
7
15
  import { configPath, loadConfig, saveConfig } from './config.js';
8
- 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';
9
17
  import { createActivityReporter, redact as oneLine, stripWorktree } from './activity.js';
10
18
  import { errorLine, foldHome, promisesLaterCheck, pushRefusal, setupCommandName, setupReason, stripCode, } from './keep-local.js';
11
- 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';
12
20
  import { isNetworkError, networkFailureHint, waitForNetwork, withNetworkRetry } from './network.js';
21
+ import { firefuncReconnectedBrief, mcpServersFailedAtStart } from './mcp-init.js';
13
22
  import { endedOnRefusal, modelDeclinedSentence } from './declined.js';
14
23
  import { endedBySignal, stoppedSentence } from './stopped.js';
15
- import { changeKind, 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';
16
26
  import { savePendingResult } from './pending.js';
17
27
  import { runnerDir } from './config.js';
18
28
  import { attemptUsage, combineUsage, describeUsage, } from './usage.js';
19
29
  import { changesOf, dropKept, keepUntilFrom, keptDir, keptFor, reviseBrief, saveKept, } from './ask-first.js';
20
30
  import { makeStreamJsonParser } from './session-stream.js';
31
+ import { parkReasonFor, parkedLine, resumeFromParked, stepBrief, } from './ask/index.js';
32
+ import { changedWhilePlanning, phaseOf, planPhaseBrief } from './plan-phase/index.js';
21
33
  import { writeSkills, writtenSkillPaths } from './skills.js';
22
- import { createKeyedMutex, ensureHeavyScript, heavyLockDir, withHeavyLock } from './locks.js';
34
+ import { ATTACH_FOLDER, attachLimitsOf, prepareAttachFolder, uploadRunAttachments, } from './run-attachments.js';
35
+ import { REFERENCE_FOLDER, mergeWritten, writeReferenceFiles, } from './reference-files.js';
36
+ import { blankSecrets, heldSecretValues, blankSecretsDeep, blankingApi, registerSecretValues, releaseSecretValues, } from './secret-values.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';
23
41
  import { getAdapter, stripForeignEngineCreds } from './engines/index.js';
24
42
  import { mcpFormatForEngine, prepareMcp } from './mcp.js';
25
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';
26
46
  import { limitSentence } from './limit.js';
27
47
  import { cannotRunUnattendedSentence, unattendedContext } from './unattended.js';
28
48
  import { cutFor, dropCut, keepUntil, promptHash, resumeAfterResetBrief, saveCut, } from './cut.js';
29
- import { liveWorktrees, updateHeld } from './held.js';
30
- import { killOrphans, reviewCopiesOf, trackEngineGroup, untrackEngineGroup } from './orphans.js';
31
- 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';
53
+ import { detailOf, startRunTrail, trailOff } from './trail/index.js';
54
+ import { RUNNER_VERSION } from './version.js';
32
55
  function log(msg) {
33
- console.log(`[firefunc-runner] ${new Date().toISOString()} ${msg}`);
56
+ console.log(`[firefunc-runner] ${new Date().toISOString()} ${blankSecrets(msg)}`);
34
57
  }
35
58
  const gitMutex = createKeyedMutex();
36
59
  function saveSessionLog(runId, stdout, stderr) {
@@ -47,7 +70,7 @@ function saveSessionLog(runId, stdout, stderr) {
47
70
  catch {
48
71
  }
49
72
  const p = join(dir, `${runId}.log`);
50
- writeFileSync(p, redact(`=== agent stdout ===\n${stdout}\n\n=== agent stderr ===\n${stderr}\n`), {
73
+ writeFileSync(p, blankSecrets(redact(`=== agent stdout ===\n${stdout}\n\n=== agent stderr ===\n${stderr}\n`)), {
51
74
  mode: 0o600,
52
75
  });
53
76
  return p;
@@ -165,25 +188,181 @@ function unfinishedSentence(engineName, open, changeRun, continued) {
165
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.');
166
189
  }
167
190
  function resumeBrief(prompt, why = 'network') {
168
- const what = why === 'limit'
169
- ? "was stopped by the plan's usage limit, which has now reset, and that session could not be continued"
170
- : 'was cut short by a network outage';
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';
171
198
  return (`Your previous session on this task ${what}. The worktree ` +
172
199
  'still holds everything you did; look at `git status` and `git diff`, continue from ' +
173
200
  'there, and finish the task. The original brief follows.\n\n' +
174
201
  prompt);
175
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
+ }
176
235
  export async function runJob(job, cfg, api, viewer, opts) {
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) {
177
249
  const now = opts?.now ?? (() => new Date());
178
250
  const rdir = runnerDir();
251
+ const trailWriteTools = new Set();
252
+ const trail = trailOff(job) || typeof api.trail !== 'function'
253
+ ? null
254
+ : startRunTrail({
255
+ runId: job.runId,
256
+ runnerDir: rdir,
257
+ detail: detailOf(job),
258
+ post: (batch) => api.trail(job.runId, batch),
259
+ worktree: () => {
260
+ try {
261
+ return worktree;
262
+ }
263
+ catch {
264
+ return null;
265
+ }
266
+ },
267
+ blank: blankSecretsDeep,
268
+ who: { runner_version: RUNNER_VERSION, ...(job.engine ? { engine: job.engine } : {}) },
269
+ writeTools: trailWriteTools,
270
+ now,
271
+ });
272
+ if (trail)
273
+ void trail.runStarted(job.repo ? { repo: job.repo } : {});
179
274
  let secretScan;
275
+ const localChecks = makeLocalChecksReader(declaredChecksOf(job.checks));
180
276
  let usage;
181
277
  let readHead;
278
+ let restoredFrom = null;
182
279
  let openCommandAtEnd = false;
280
+ let attachFolder = null;
281
+ let attachmentsSent = false;
282
+ const sendAttachments = async (status) => {
283
+ if (attachmentsSent || !job.runAttachments)
284
+ return;
285
+ if (status !== 'pr_opened' && status !== 'no_pr')
286
+ return;
287
+ const client = api;
288
+ if (typeof client.offerAttachment !== 'function')
289
+ return;
290
+ attachmentsSent = true;
291
+ let wt = null;
292
+ try {
293
+ wt = worktree;
294
+ }
295
+ catch {
296
+ return;
297
+ }
298
+ if (!wt)
299
+ return;
300
+ const dir = attachFolder ?? prepareAttachFolder(wt, () => { }).dir;
301
+ if (!dir)
302
+ return;
303
+ await uploadRunAttachments({
304
+ runId: job.runId,
305
+ dir,
306
+ api: client,
307
+ log,
308
+ limits: attachLimitsOf(job.runAttachments),
309
+ }).catch((e) => {
310
+ log(`the pictures for the ticket were not uploaded: ${e.message}`);
311
+ });
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
+ };
183
349
  const report = async (reported) => {
184
- let payload = secretScan && !reported.secretScan ? { ...reported, secretScan } : reported;
350
+ await sendAttachments(reported.status);
351
+ const release = reported.release ? null : await stageRelease(reported.status);
352
+ if (release)
353
+ reported = { ...reported, release };
354
+ await trail
355
+ ?.finish({
356
+ status: reported.status,
357
+ ...('pr' in reported && reported.pr ? { pr: reported.pr } : {}),
358
+ })
359
+ .catch(() => { });
360
+ let payload = blankSecretsDeep(secretScan && !reported.secretScan ? { ...reported, secretScan } : reported);
185
361
  if (usage && !payload.usage)
186
362
  payload = { ...payload, usage };
363
+ const checks = localChecks.report();
364
+ if (checks && !payload.localChecks)
365
+ payload = { ...payload, localChecks: checks };
187
366
  if (readHead && !payload.readHead)
188
367
  payload = { ...payload, readHead };
189
368
  if (openCommandAtEnd && !payload.openCommandAtEnd) {
@@ -236,17 +415,45 @@ export async function runJob(job, cfg, api, viewer, opts) {
236
415
  const step = askFirst ? (job.askFirstStep ?? null) : null;
237
416
  const revising = step?.kind === 'revise' ? step : null;
238
417
  const kept = step ? keptFor(rdir, job.runId) : null;
418
+ const parkStep = job.parkStep ?? null;
419
+ const parkKept = parkStep ? keptFor(rdir, job.runId) : null;
420
+ let activitySeen = (kept ?? parkKept)?.activitySeq ?? 0;
421
+ const phase = phaseOf(job);
422
+ const planRound = Math.max(1, Number(job.planRound) || 1);
239
423
  const adapter = getAdapter(job.engine ?? cfg.engine);
240
424
  const spent = opts?.limits?.isLimited(adapter.id) ?? null;
241
425
  if (spent) {
242
426
  const limit = { kind: 'plan', resetsAt: spent.resetsAt };
243
427
  log(`${adapter.displayName}'s plan limit is spent until ${spent.until} — answering ${job.runId} without starting it`);
244
- return report({
428
+ return await report({
245
429
  status: 'failed',
246
430
  error: limitSentence(adapter.displayName, limit, false),
247
431
  limit: { kind: 'plan', resetsAt: limit.resetsAt },
248
432
  });
249
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
+ }
250
457
  const unattended = adapter.unattendedBlock?.({
251
458
  ...unattendedContext(cfg, job.permissionMode),
252
459
  ...opts?.unattended,
@@ -254,12 +461,101 @@ export async function runJob(job, cfg, api, viewer, opts) {
254
461
  if (unattended) {
255
462
  const sentence = cannotRunUnattendedSentence(adapter.displayName, unattended);
256
463
  log(`${job.runId}: ${sentence}`);
257
- return report({
464
+ return await report({
258
465
  status: 'failed',
259
466
  error: sentence,
260
467
  limit: { kind: 'machine', detail: unattended.detail },
261
468
  });
262
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
+ }
480
+ const engineRuns = step?.kind !== 'publish';
481
+ const agentEnv = {};
482
+ const carriedNotes = [];
483
+ if (engineRuns && !toolsOnly && !review) {
484
+ carriedNotes.push(`When you change code, write the pull request's title (the first line) and its description (the rest) to \`${AGENT_PR_FILE}\` in your working directory, in the form the project's instructions ask for pull request titles and descriptions. FireFunc opens the pull request with them, or updates the one you continue. Never stage or commit that file.`);
485
+ }
486
+ if (engineRuns && job.agentEnv?.length) {
487
+ let got;
488
+ try {
489
+ got = await withNetworkRetry(() => api.agentEnv(job.runId), {
490
+ label: `environment variables for ${job.runId}`,
491
+ maxWaitMs: 5 * 60_000,
492
+ probe: () => api.probe(),
493
+ log,
494
+ });
495
+ }
496
+ catch (e) {
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.`);
498
+ }
499
+ if ('refused' in got) {
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}`);
501
+ }
502
+ registerSecretValues(job.runId, got.env.filter((e) => e.secret).map((e) => ({ name: e.name, value: e.value })));
503
+ for (const e of got.env)
504
+ agentEnv[e.name] = e.value;
505
+ for (const m of got.missing)
506
+ log(`variable ${m.name} is not set for this run: ${m.reason} Fix: ${m.fix}`);
507
+ if (got.env.length) {
508
+ log(`the engine gets ${got.env.length} of the agent's variable(s): ${got.env
509
+ .map((e) => (e.secret ? `${e.name} (secret)` : e.name))
510
+ .join(', ')}`);
511
+ const secrets = got.env.filter((e) => e.secret).map((e) => e.name);
512
+ carriedNotes.push(`This agent's own environment variables are set in your environment: ${got.env
513
+ .map((e) => e.name)
514
+ .join(', ')}. Read them from the environment when the task needs them.` +
515
+ (secrets.length
516
+ ? ` ${secrets.join(', ')} ${secrets.length === 1 ? 'is a secret' : 'are secrets'}: never print, log or echo ${secrets.length === 1 ? 'its value' : 'their values'}, and never write ${secrets.length === 1 ? 'it' : 'them'} into a file or a commit — FireFunc blanks secret values from everything it reports, and refuses a push that contains one.`
517
+ : ''));
518
+ }
519
+ if (got.missing.length) {
520
+ carriedNotes.push(`These of the agent's variables could not be set for this run: ${got.missing
521
+ .map((m) => m.name)
522
+ .join(', ')}. Say so in your answer if the task needed them.`);
523
+ }
524
+ }
525
+ const writeRefs = async (dir) => {
526
+ if (!engineRuns || !job.referenceFiles?.length)
527
+ return null;
528
+ let got;
529
+ try {
530
+ got = await withNetworkRetry(() => api.referenceFiles(job.runId), {
531
+ label: `reference files for ${job.runId}`,
532
+ maxWaitMs: 5 * 60_000,
533
+ probe: () => api.probe(),
534
+ log,
535
+ });
536
+ }
537
+ catch (e) {
538
+ return {
539
+ failure: `The agent's reference files could not be fetched from FireFunc (${oneLine(e.message, 120)}), so the engine was not started. Fix: check this machine can reach FireFunc, then re-run the task.`,
540
+ };
541
+ }
542
+ if ('refused' in got) {
543
+ return {
544
+ failure: `FireFunc did not hand this run the agent's reference files, so the engine was not started: ${got.refused.reason} Fix: ${got.refused.fix}`,
545
+ };
546
+ }
547
+ for (const m of got.missing)
548
+ log(`reference file ${m.name} is not here for this run: ${m.reason} Fix: ${m.fix}`);
549
+ const written = await writeReferenceFiles(dir, got.files, log);
550
+ const notHere = [...got.missing.map((m) => m.name), ...written.skipped.map((x) => x.name)];
551
+ if (written.names.length) {
552
+ carriedNotes.push(`This agent's reference files are in \`${REFERENCE_FOLDER}/\` in your working directory: ${written.names.join(', ')}. Read the ones the task needs before you start. They are the agent's, not the repository's: never move, edit, stage or commit them.`);
553
+ }
554
+ if (notHere.length) {
555
+ carriedNotes.push(`These of the agent's reference files could not be put in the working directory: ${notHere.join(', ')}. Say so in your answer if the task needed them.`);
556
+ }
557
+ return written;
558
+ };
263
559
  let repoPath = toolsOnly ? null : resolveRepoPath(job.repo, cfg);
264
560
  if (!repoPath && job.repo) {
265
561
  const cred = await api.gitCredential(job.runId);
@@ -273,7 +569,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
273
569
  rememberRepoPath(job.repo, dest, cfg);
274
570
  }
275
571
  else {
276
- return report({
572
+ return await report({
277
573
  status: 'failed',
278
574
  error: `Could not clone ${job.repo}: ${redact(cloned.stderr, cred.token).slice(0, 300)}`,
279
575
  });
@@ -282,7 +578,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
282
578
  }
283
579
  if (!repoPath && !toolsOnly) {
284
580
  log(`no local checkout for ${job.repo} and no credential to clone with`);
285
- return report({
581
+ return await report({
286
582
  status: 'failed',
287
583
  error: `Runner has no local checkout for ${job.repo} and could not obtain a ` +
288
584
  `credential to clone it. Either map it with \`firefunc-runner repo ` +
@@ -299,7 +595,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
299
595
  : budget
300
596
  : (cfg.jobTimeoutMinutes ?? 20);
301
597
  const timeoutMs = limitMinutes * 60_000;
302
- const cutMatch = step
598
+ const cutMatch = step || parkStep
303
599
  ? null
304
600
  : cutFor(rdir, {
305
601
  workItemId: job.workItemId,
@@ -333,7 +629,12 @@ export async function runJob(job, cfg, api, viewer, opts) {
333
629
  ...(kept.writtenSkills ? { writtenSkills: kept.writtenSkills } : {}),
334
630
  };
335
631
  }
336
- else if (cutMatch && 'resume' in cutMatch && adapter.resumesSessions) {
632
+ else if (parkStep && parkKept) {
633
+ resumeCut = resumeFromParked(parkKept, promptHash(job.prompt));
634
+ }
635
+ else if (cutMatch &&
636
+ 'resume' in cutMatch &&
637
+ (adapter.resumesSessions || cutMatch.resume.sessionId === '')) {
337
638
  resumeCut = cutMatch.resume;
338
639
  }
339
640
  else if (cutMatch) {
@@ -358,6 +659,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
358
659
  const engineGroups = [];
359
660
  let worktree = null;
360
661
  let attachDir = null;
662
+ let runTemp = null;
361
663
  let mcp = null;
362
664
  let writtenSkills = { written: [], pathspecs: [] };
363
665
  const bgProcs = [];
@@ -367,6 +669,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
367
669
  });
368
670
  const ship = async (s) => {
369
671
  const { worktree, branch, base, title, kind, engineName, summary } = s;
672
+ const agentText = s.agentText ?? null;
370
673
  const scanIn = worktree;
371
674
  const tipOf = async () => {
372
675
  const r = await exec('git', ['-C', scanIn, 'rev-parse', '--verify', '--quiet', `refs/heads/${branch}^{commit}`], { timeoutMs: 30_000 }).catch(() => null);
@@ -390,8 +693,21 @@ export async function runJob(job, cfg, api, viewer, opts) {
390
693
  why: `git exit ${failed.code}: ${failed.stderr.trim().slice(0, 200)}`,
391
694
  };
392
695
  }
696
+ const messages = await readChange([
697
+ '--no-replace-objects',
698
+ 'log',
699
+ '--format=%B%x00',
700
+ `${from}..${scannedTip ?? `refs/heads/${branch}`}`,
701
+ ], reads.env);
702
+ const inMessages = messages.code === 0 && heldSecretValues().some((sv) => messages.stdout.includes(sv.value))
703
+ ? [{ path: '(a commit message)', kind: 'agent_secret', line: 0 }]
704
+ : [];
393
705
  return {
394
- hits: uniqueHits([...scanAddedLines(whole.stdout), ...scanAddedLines(commits.stdout)]),
706
+ hits: uniqueHits([
707
+ ...scanAddedLines(whole.stdout),
708
+ ...scanAddedLines(commits.stdout),
709
+ ...inMessages,
710
+ ]),
395
711
  };
396
712
  };
397
713
  const found = (hits, n = 5) => hits
@@ -409,7 +725,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
409
725
  secretScan = asReported(added);
410
726
  if (added.some(refusesPush)) {
411
727
  log(`secret scan for ${job.runId}: ${added.length} finding(s) — ${found(added)} — refusing to push`);
412
- return fail(secretRefusal(added, branch));
728
+ return await fail(secretRefusal(added, branch));
413
729
  }
414
730
  if (added.length > 0) {
415
731
  log(`secret scan for ${job.runId}: ${added.length} looser match(es) — ${found(added)} — pushing; ` +
@@ -445,7 +761,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
445
761
  if (s.keep) {
446
762
  const changes = await changesOf(scanIn, continuesBranch ? `origin/${branch}` : `origin/${base}`, branch);
447
763
  if (!changes || !scannedTip) {
448
- 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.`);
449
765
  }
450
766
  const at = now();
451
767
  const saved = saveKept(rdir, {
@@ -470,13 +786,14 @@ export async function runJob(job, cfg, api, viewer, opts) {
470
786
  writtenSkills,
471
787
  ...(usage ? { attemptUsage: usage } : {}),
472
788
  ...(s.keep.sessionReport ? { sessionReport: s.keep.sessionReport } : {}),
789
+ activitySeq: activitySeen,
473
790
  });
474
791
  if (!saved) {
475
- 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.`);
476
793
  }
477
794
  keepWorktree = true;
478
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`);
479
- return report({
796
+ return await report({
480
797
  status: 'awaiting_approval',
481
798
  changes,
482
799
  head: scannedTip,
@@ -521,20 +838,24 @@ export async function runJob(job, cfg, api, viewer, opts) {
521
838
  .filter(Boolean);
522
839
  const leaked = stagedPaths.filter((l) => l === '.env' || l.endsWith('/.env') || (mcpStaged !== null && l === mcpStaged));
523
840
  if (leaked.length > 0) {
524
- 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. ` +
525
842
  `This is a FireFunc bug — please report it. Nothing was pushed.`);
526
843
  }
527
844
  const skillLeaked = writtenSkillPaths(stagedPaths, writtenSkills);
528
845
  if (skillLeaked.length > 0) {
529
- return fail(`refusing to push: the agent added ${skillLeaked.join(', ')} to its commit — 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'} ` +
530
848
  `FireFunc writes into the checkout for this run only and never commits. Nothing was ` +
531
849
  `pushed. Fix: tell the agent not to stage or commit anything under ` +
532
850
  `${skillLeaked[0].split('/').slice(0, -1).join('/')} (check its instruction and ` +
533
851
  `its skills for "git add -f" or "commit everything"), then re-run the task.`);
534
852
  }
535
853
  const pushFrom = worktree;
536
- const pushOnce = async () => gitCred
537
- ? 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
+ })
538
859
  : exec('git', [
539
860
  '-C',
540
861
  pushFrom,
@@ -543,24 +864,80 @@ export async function runJob(job, cfg, api, viewer, opts) {
543
864
  'origin',
544
865
  `${branch}:${branch}`,
545
866
  ], {
546
- timeoutMs: 120_000,
867
+ timeoutMs,
547
868
  });
548
- let push = await pushOnce();
549
- for (let tries = 0; tries < 3 && push.code !== 0 && isNetworkError(push.stderr); tries++) {
550
- log(`push failed because the network seems to be away — waiting for it (try ${tries + 1} of 3)`);
551
- const back = await waitForNetwork({ probe: () => api.probe(), maxWaitMs: 10 * 60_000, log });
552
- if (!back)
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,
876
+ });
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: '' };
553
897
  break;
554
- 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.'));
555
929
  }
556
930
  if (push.code !== 0) {
557
931
  const said = redact(push.stderr, gitCred?.token);
558
932
  log(`git push output for ${job.runId} (kept on this machine):\n${said.slice(-4000)}`);
559
933
  const refused = pushRefusal(said);
560
- return fail(refused
934
+ const kept = s.keepOnPushFailure?.() ?? false;
935
+ return await fail((refused
561
936
  ? `git push failed: ${oneLine(refused, 400)}`
562
- : `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.` : ''));
563
939
  }
940
+ await trail?.pushed({ branch });
564
941
  if (secretScan && scannedTip && scanCoversPullRequest) {
565
942
  const pushedTip = await tipOf();
566
943
  if (pushedTip === scannedTip)
@@ -568,7 +945,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
568
945
  else
569
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`);
570
947
  }
571
- const body = pullRequestBody(kind, engineName, job.externalId, { continuesBranch });
948
+ const body = withProvenanceFooter(agentText?.body
949
+ ? `${agentText.body}\n\n---\nOpened by FireFunc (self-hosted ${engineName} runner) for ${job.externalId ?? 'this task'}. Review before merging.`
950
+ : pullRequestBody(kind, engineName, job.externalId, { continuesBranch }), job);
951
+ if (isStopped(job.runId))
952
+ return await fail(stoppedByPersonSentence(engineName, 'pr'));
572
953
  if (gitCred) {
573
954
  const pr = await withNetworkRetry(() => openDraftPr({
574
955
  repo: gitCred.repo,
@@ -577,6 +958,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
577
958
  title,
578
959
  body,
579
960
  cred: gitCred,
961
+ update: !!agentText,
580
962
  }), {
581
963
  label: `pull request for ${job.runId}`,
582
964
  maxWaitMs: 10 * 60_000,
@@ -586,7 +968,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
586
968
  if (!('error' in pr)) {
587
969
  await api.event(job.runId, 'pr_opened', { url: pr.url, branch });
588
970
  log(`opened PR for ${job.runId}: ${pr.url}`);
589
- return report({
971
+ return await report({
590
972
  status: 'pr_opened',
591
973
  pr: {
592
974
  repo: job.repo ?? undefined,
@@ -600,7 +982,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
600
982
  }
601
983
  const why = redact(pr.error, gitCred.token);
602
984
  if (!(await hasGh(worktree)))
603
- return fail(why);
985
+ return await fail(why);
604
986
  log(`could not open the PR as FireFunc (${why}); falling back to gh`);
605
987
  }
606
988
  const createCwd = worktree;
@@ -659,14 +1041,14 @@ export async function runJob(job, cfg, api, viewer, opts) {
659
1041
  }
660
1042
  if (!resolved) {
661
1043
  const why = (create.stderr || create.stdout).replace(/\s+/g, ' ').trim().slice(0, 400);
662
- 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}` : ''}. ` +
663
1045
  `Open it from that branch on GitHub (FireFunc will link it to this task), or re-run.`);
664
1046
  }
665
1047
  const url = resolved.url;
666
1048
  const number = resolved.number;
667
1049
  await api.event(job.runId, 'pr_opened', { url, branch });
668
1050
  log(`opened PR for ${job.runId}: ${url}`);
669
- return report({
1051
+ return await report({
670
1052
  status: 'pr_opened',
671
1053
  pr: { repo: job.repo ?? undefined, number, url: url || undefined, branch, summary: title },
672
1054
  ...(summary ? { summary: reportedSummary(summary) } : {}),
@@ -674,8 +1056,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
674
1056
  };
675
1057
  let base = '';
676
1058
  try {
1059
+ if (parkStep && (!parkKept || !existsSync(parkKept.worktree))) {
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.');
1061
+ }
677
1062
  if (step && (!kept || !existsSync(kept.worktree))) {
678
- 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.');
679
1064
  }
680
1065
  if (step?.kind === 'publish' && kept) {
681
1066
  worktree = kept.worktree;
@@ -692,7 +1077,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
692
1077
  `refs/heads/${kept.branch}^{commit}`,
693
1078
  ]).catch(() => '');
694
1079
  if (tip.trim() !== kept.head) {
695
- 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.`);
696
1081
  }
697
1082
  log(`approved: pushing the change kept for ${job.runId} (${kept.branch}) and opening its pull request`);
698
1083
  return await ship({
@@ -712,16 +1097,19 @@ export async function runJob(job, cfg, api, viewer, opts) {
712
1097
  log(`continuing the session a plan limit cut for this task, in ${worktree}`);
713
1098
  }
714
1099
  else if (toolsOnly) {
715
- worktree = mkdtempSync(join(tmpdir(), 'firefunc-tools-'));
1100
+ worktree = mkdtempSync(join(workRoot(), 'firefunc-tools-'));
716
1101
  updateHeld(rdir, job.runId, { scratch: [worktree] });
717
1102
  writeSkills(worktree, job.skills, log);
1103
+ const refs = await writeRefs(worktree);
1104
+ if (refs && 'failure' in refs)
1105
+ return await fail(refs.failure);
718
1106
  await exec('git', ['-C', worktree, 'init', '--quiet']);
719
1107
  log(`no repository for ${job.runId} — the agent works through its tools in ${worktree}`);
720
1108
  }
721
1109
  else {
722
1110
  await api.event(job.runId, 'cloning', { repo: job.repo, branch });
723
1111
  const checkout = repoPath;
724
- const prep = await gitMutex.run(checkout, async () => {
1112
+ const prepare = () => gitMutex.run(checkout, async () => {
725
1113
  await exec('git', ['-C', checkout, 'fetch', 'origin', '--quiet'], { timeoutMs: 120_000 });
726
1114
  if (resumeCut) {
727
1115
  const known = await exec('git', ['-C', resumeCut.worktree, 'rev-parse', '--git-dir']);
@@ -732,6 +1120,8 @@ export async function runJob(job, cfg, api, viewer, opts) {
732
1120
  add: { code: 0, stdout: '', stderr: '' },
733
1121
  branchMissing: false,
734
1122
  startPoint: '',
1123
+ heldBy: null,
1124
+ holder: null,
735
1125
  };
736
1126
  }
737
1127
  log(`the worktree the plan limit's cut session kept is no longer a worktree of ${job.repo} — starting over`);
@@ -760,29 +1150,71 @@ export async function runJob(job, cfg, api, viewer, opts) {
760
1150
  `refs/remotes/origin/${branch}`,
761
1151
  ]);
762
1152
  if (has.code !== 0) {
763
- 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
+ };
764
1162
  }
765
1163
  startPoint = `origin/${branch}`;
766
1164
  }
767
- 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
+ }
768
1185
  const add = () => exec('git', ['-C', checkout, 'worktree', 'add', '--force', '-B', branch, wt, startPoint], {
769
1186
  timeoutMs: 120_000,
770
1187
  });
771
1188
  let result = await add();
772
1189
  const holder = result.code !== 0 ? staleHolder(result.stderr) : null;
1190
+ let heldBy = null;
773
1191
  if (holder) {
774
- const live = new Set([...liveWorktrees(rdir)].map(canonicalPath));
775
- if (!live.has(canonicalPath(holder))) {
1192
+ heldBy = branchHolderOf(rdir, holder);
1193
+ if (!heldBy) {
776
1194
  log(`a worktree a stopped runner left holds ${branch} (${holder}) — removing it and trying again`);
777
1195
  await removeRunnerWorktree(checkout, holder, log);
778
1196
  result = await add();
779
1197
  }
780
1198
  }
781
- return { base: b, wt, add: result, branchMissing: false, startPoint };
1199
+ return { base: b, wt, add: result, branchMissing: false, startPoint, heldBy, holder };
782
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
+ }
783
1214
  base = prep.base;
1215
+ releaseBase = prep.base || null;
784
1216
  if (prep.branchMissing) {
785
- 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. ` +
786
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.`);
787
1219
  }
788
1220
  worktree = prep.wt;
@@ -802,17 +1234,41 @@ export async function runJob(job, cfg, api, viewer, opts) {
802
1234
  if (FULL_SHA.test(sha))
803
1235
  readHead = sha;
804
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
+ }
805
1241
  if (prep.add.code !== 0) {
806
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 });
807
1246
  const said = pushRefusal(prep.add.stderr);
808
- return fail(said
1247
+ return await fail(said
809
1248
  ? `git worktree add failed: ${oneLine(said, 400)}`
810
1249
  : `git worktree add failed (exit ${prep.add.code}); its output stayed on the machine — the runner’s log shows it.`);
811
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
+ }
812
1268
  }
813
1269
  const attachPaths = [];
814
1270
  if (job.attachments?.length) {
815
- attachDir = mkdtempSync(join(tmpdir(), 'firefunc-attach-'));
1271
+ attachDir = mkdtempSync(join(workRoot(), 'firefunc-attach-'));
816
1272
  updateHeld(rdir, job.runId, { scratch: [attachDir] });
817
1273
  mkdirSync(attachDir, { recursive: true });
818
1274
  job.attachments.forEach((att, i) => {
@@ -835,9 +1291,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
835
1291
  .join('\n')}\n\n`
836
1292
  : '';
837
1293
  const runEnv = {
1294
+ ...cargoTargetEnv(cfg, rdir, job.repo),
838
1295
  ...cfg.claudeEnv,
839
1296
  ...(cfg.claudeCodeOAuthToken ? { CLAUDE_CODE_OAUTH_TOKEN: cfg.claudeCodeOAuthToken } : {}),
840
1297
  ...(opts?.devServerPort ? { PORT: String(opts.devServerPort) } : {}),
1298
+ ...workTempEnv(),
841
1299
  };
842
1300
  if (opts?.devServerPort && cfg.backgroundCommands?.length) {
843
1301
  log(`session dev-server PORT=${opts.devServerPort} (parallel-safe)`);
@@ -864,17 +1322,61 @@ export async function runJob(job, cfg, api, viewer, opts) {
864
1322
  }
865
1323
  if (resumeCut) {
866
1324
  writtenSkills = resumeCut.writtenSkills ?? { written: [], pathspecs: [] };
1325
+ if (job.referenceFiles?.length &&
1326
+ writtenSkills.written.some((p) => p.endsWith(REFERENCE_FOLDER))) {
1327
+ carriedNotes.push(`This agent's reference files are in \`${REFERENCE_FOLDER}/\` in your working directory: ${job.referenceFiles
1328
+ .map((f) => f.name)
1329
+ .join(', ')}. Never move, edit, stage or commit them.`);
1330
+ }
867
1331
  }
868
1332
  else if (!toolsOnly) {
869
1333
  writtenSkills = writeSkills(worktree, job.skills, log);
1334
+ const refs = await writeRefs(worktree);
1335
+ if (refs && 'failure' in refs)
1336
+ return await fail(refs.failure);
1337
+ if (refs)
1338
+ writtenSkills = mergeWritten(writtenSkills, refs);
1339
+ }
1340
+ if (job.runAttachments && worktree) {
1341
+ const prepared = prepareAttachFolder(worktree, log);
1342
+ if (prepared.dir) {
1343
+ attachFolder = prepared.dir;
1344
+ writtenSkills = mergeWritten(writtenSkills, prepared);
1345
+ }
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
+ }
870
1353
  }
871
1354
  const heavyLock = !toolsOnly && job.repo && cfg.heavyLock !== false ? heavyLockDir(rdir, job.repo) : null;
872
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);
1372
+ const deviceHelper = heavyHelper ? ensureDeviceScript(rdir) : null;
873
1373
  const heavily = (fn) => heavyLock
874
1374
  ? withHeavyLock(heavyLock, fn, {
875
1375
  label: `setup of ${job.runId}`,
1376
+ slots,
1377
+ tag: heavyTag(job.runId),
876
1378
  maxWaitMs: (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000,
877
- 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`),
878
1380
  })
879
1381
  : fn();
880
1382
  const setupMs = (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000;
@@ -884,12 +1386,14 @@ export async function runJob(job, cfg, api, viewer, opts) {
884
1386
  for (const cmd of cfg.setupCommands) {
885
1387
  log(`setup: ${cmd}`);
886
1388
  const setupCwd = worktree;
1389
+ const setupAt = Date.now();
887
1390
  const r = await heavily(() => exec(cmd, [], {
888
1391
  cwd: setupCwd,
889
1392
  env: runEnv,
890
1393
  timeoutMs: setupMs,
891
1394
  shell: true,
892
1395
  }));
1396
+ await trail?.setupRan({ command: cmd, exitCode: r.code, durationMs: Date.now() - setupAt });
893
1397
  if (r.code !== 0) {
894
1398
  log(`setup output for ${job.runId} (kept on this machine):\n${r.stderr.slice(-4000)}` +
895
1399
  `${r.stdout.trim() ? `\n--- stdout ---\n${r.stdout.slice(-2000)}` : ''}`);
@@ -897,7 +1401,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
897
1401
  const fold = (text) => foldHome(stripWorktree(text, checkout), homedir());
898
1402
  const why = setupReason(fold(r.stderr), fold(r.stdout));
899
1403
  const said = why ? oneLine(why, 200).replace(/[.\s]+$/, '') : '';
900
- return fail(`Setup command failed (exit ${r.code}): ${setupCommandName(cmd)}` +
1404
+ return await fail(`Setup command failed (exit ${r.code}): ${setupCommandName(cmd)}` +
901
1405
  `${said ? ` — ${said}` : ''}. ` +
902
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.');
903
1407
  }
@@ -914,13 +1418,27 @@ export async function runJob(job, cfg, api, viewer, opts) {
914
1418
  bgProcs.push(spawnBackground(cmd, { cwd: worktree, env: runEnv }));
915
1419
  }
916
1420
  await api.event(job.runId, 'fixing', { title: job.title });
1421
+ await reportWorktree(api, job.runId, worktree, 'live');
917
1422
  const mode = job.permissionMode ?? cfg.permissionMode ?? 'bypassPermissions';
918
- const model = job.model ?? cfg.model ?? null;
1423
+ const model = (phase === 'plan' && job.planModel ? job.planModel : null) ?? job.model ?? cfg.model ?? null;
919
1424
  const effort = job.effort ?? cfg.effort ?? null;
920
1425
  const ultracode = effort === 'ultracode';
921
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';
922
- const rules = engineRules({ minutes: limitMinutes, heavy: heavyHelper !== null });
923
- const prompt = rules + observeNote + attachNote + (ultracode ? `ultracode\n\n${job.prompt}` : job.prompt);
1427
+ const rules = engineRules({
1428
+ minutes: limitMinutes,
1429
+ heavy: heavyHelper !== null,
1430
+ device: deviceHelper !== null,
1431
+ attach: attachFolder !== null,
1432
+ release: releaseFolder !== null ? (job.release ?? null) : null,
1433
+ toolsOnly,
1434
+ });
1435
+ const carriedNote = carriedNotes.length ? `${carriedNotes.join('\n\n')}\n\n` : '';
1436
+ const prompt = (restoredFrom ? resumeFromCheckpointBrief(restoredFrom.at) : '') +
1437
+ rules +
1438
+ observeNote +
1439
+ attachNote +
1440
+ carriedNote +
1441
+ (ultracode ? `ultracode\n\n${job.prompt}` : job.prompt);
924
1442
  const tools = cfg.allowedTools ??
925
1443
  'Read Edit Write Bash Glob Grep WebFetch WebSearch Task TodoWrite NotebookEdit';
926
1444
  const isWin = process.platform === 'win32';
@@ -939,6 +1457,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
939
1457
  }
940
1458
  log(mcp ? `mcp: ${mcp.logLine}` : 'mcp: no server was injected for this run');
941
1459
  }
1460
+ const temp = makeRunTemp(job.runId);
1461
+ if (temp) {
1462
+ runTemp = temp.dir;
1463
+ updateHeld(rdir, job.runId, { scratch: [temp.dir] });
1464
+ }
942
1465
  const ctx = {
943
1466
  prompt,
944
1467
  model,
@@ -952,34 +1475,66 @@ export async function runJob(job, cfg, api, viewer, opts) {
952
1475
  isWin,
953
1476
  runEnv: {
954
1477
  ...stripForeignEngineCreds(runEnv, adapter.id),
1478
+ ...workTempEnv(),
1479
+ ...(temp?.env ?? {}),
1480
+ ...agentEnv,
955
1481
  ...(heavyHelper && heavyLock
956
- ? { 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
+ }
1488
+ : {}),
1489
+ ...(deviceHelper
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
+ }
957
1499
  : {}),
958
1500
  },
959
1501
  cfg,
960
1502
  ...(mcp ? { mcp } : {}),
961
1503
  };
962
- const firstCtx = revising
963
- ? resumeCut?.sessionId && adapter.resumesSessions
964
- ? {
965
- ...ctx,
966
- resumeSessionId: resumeCut.sessionId,
967
- prompt: reviseBrief(revising.note, revising.round),
968
- }
969
- : { ...ctx, prompt: `${reviseBrief(revising.note, revising.round)}\n\n${ctx.prompt}` }
970
- : resumeCut
971
- ? {
972
- ...ctx,
973
- resumeSessionId: resumeCut.sessionId,
974
- prompt: resumeAfterResetBrief(prompt, promptHash(job.prompt) !== resumeCut.promptHash),
975
- }
976
- : ctx;
1504
+ if (phase === 'plan')
1505
+ ctx.prompt = `${planPhaseBrief(planRound)}\n\n${ctx.prompt}`;
1506
+ const parkBrief = parkStep ? stepBrief(parkStep, phase) : null;
1507
+ const parkCtx = parkBrief && resumeCut
1508
+ ? resumeCut.sessionId && adapter.resumesSessions
1509
+ ? { ...ctx, resumeSessionId: resumeCut.sessionId, prompt: parkBrief }
1510
+ : { ...ctx, prompt: `${parkBrief}\n\n${ctx.prompt}` }
1511
+ : null;
1512
+ const firstCtx = parkCtx
1513
+ ? parkCtx
1514
+ : revising
1515
+ ? resumeCut?.sessionId && adapter.resumesSessions
1516
+ ? {
1517
+ ...ctx,
1518
+ resumeSessionId: resumeCut.sessionId,
1519
+ prompt: reviseBrief(revising.note, revising.round),
1520
+ }
1521
+ : { ...ctx, prompt: `${reviseBrief(revising.note, revising.round)}\n\n${ctx.prompt}` }
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;
977
1532
  let inv;
978
1533
  try {
979
- inv = adapter.buildInvocation(firstCtx);
1534
+ inv = buildInvocation(firstCtx);
980
1535
  }
981
1536
  catch (e) {
982
- return fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
1537
+ return await fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
983
1538
  }
984
1539
  const engineName = adapter.displayName;
985
1540
  log(`running ${inv.bin} (${engineName}) on ${toolsOnly ? 'no repository — tools only' : `${job.repo} (${branch})`} — model=${model ?? 'default'} effort=${effort ?? 'default'} mode=${mode}`);
@@ -989,20 +1544,54 @@ export async function runJob(job, cfg, api, viewer, opts) {
989
1544
  worktree,
990
1545
  post: (steps) => api.activity(job.runId, steps),
991
1546
  writeTools: new Set(mcp?.writeToolNames ?? []),
1547
+ seqStart: activitySeen,
992
1548
  });
1549
+ for (const name of mcp?.writeToolNames ?? [])
1550
+ trailWriteTools.add(name);
993
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
+ };
994
1578
  const onStdout = (chunk) => {
995
- printer?.(chunk);
996
- viewer?.push(job.runId, chunk);
1579
+ noteSession(chunk);
1580
+ const shown = blankSecrets(chunk);
1581
+ printer?.(shown);
1582
+ viewer?.push(job.runId, shown);
997
1583
  activityParser(chunk);
1584
+ trail?.feed(chunk);
1585
+ localChecks.feed(chunk);
998
1586
  };
999
1587
  if (printer) {
1000
1588
  log(`── live ${engineName} session (shown here only — never sent to FireFunc) ──`);
1001
1589
  }
1002
- const heartbeat = setInterval(() => void api.event(job.runId, 'heartbeat'), 5 * 60_000);
1003
1590
  const engineCwd = worktree;
1004
1591
  let engineMs = 0;
1005
- const runEngine = async (limitMs = timeoutMs) => {
1592
+ const runEngineOnce = async (limitMs = timeoutMs) => {
1593
+ if (isStopped(job.runId))
1594
+ return { code: 143, stdout: '', stderr: '' };
1006
1595
  let group = 0;
1007
1596
  const started = Date.now();
1008
1597
  try {
@@ -1014,20 +1603,45 @@ export async function runJob(job, cfg, api, viewer, opts) {
1014
1603
  shell: inv.shell,
1015
1604
  onStdout,
1016
1605
  ownGroup: true,
1606
+ signalGroup: signalGroupSparingDevices,
1017
1607
  onSpawn: (pid) => {
1018
1608
  group = pid;
1019
1609
  engineGroups.push({ pgid: pid, startedAt: started });
1020
1610
  trackEngineGroup(pid);
1611
+ trackRunGroup(job.runId, pid);
1021
1612
  updateHeld(rdir, job.runId, { engineGroup: pid, engineStartedAt: started });
1022
1613
  },
1023
1614
  });
1024
1615
  }
1025
1616
  finally {
1026
- if (group)
1617
+ if (group) {
1027
1618
  untrackEngineGroup(group);
1619
+ untrackRunGroup(job.runId, group);
1620
+ }
1028
1621
  engineMs += Date.now() - started;
1029
1622
  }
1030
1623
  };
1624
+ const runEngine = async (limitMs = timeoutMs) => {
1625
+ await trail?.engineStarted({
1626
+ engine: adapter.id,
1627
+ model: model ?? null,
1628
+ where: {
1629
+ ...(job.repo ? { repo: job.repo } : {}),
1630
+ ...(toolsOnly ? {} : { branch }),
1631
+ ...(readHead ? { base_sha: readHead } : {}),
1632
+ },
1633
+ });
1634
+ const t0 = Date.now();
1635
+ let code = 1;
1636
+ try {
1637
+ const r = await runEngineOnce(limitMs);
1638
+ code = r.code;
1639
+ return r;
1640
+ }
1641
+ finally {
1642
+ await trail?.engineEnded({ exitCode: code, durationMs: Date.now() - t0 });
1643
+ }
1644
+ };
1031
1645
  const sessions = [];
1032
1646
  let lastReport = null;
1033
1647
  const meter = (stdout, continued = false) => {
@@ -1043,9 +1657,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
1043
1657
  lastReport = u;
1044
1658
  sessions.push({ usage: u, session: adapter.sessionId?.(stdout) ?? null, continued });
1045
1659
  };
1046
- const limitOf = (stdout) => {
1660
+ const limitOf = (stdout, stderr = '') => {
1047
1661
  try {
1048
- return adapter.planLimit?.(stdout, now()) ?? null;
1662
+ return adapter.planLimit?.(stdout, now(), stderr) ?? null;
1049
1663
  }
1050
1664
  catch {
1051
1665
  return null;
@@ -1056,24 +1670,83 @@ export async function runJob(job, cfg, api, viewer, opts) {
1056
1670
  summary: adapter.summarize(stdout),
1057
1671
  stderr,
1058
1672
  });
1059
- 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
+ }
1060
1731
  meter(engineRun.stdout, false);
1061
1732
  if (resumeCut &&
1062
1733
  firstCtx.resumeSessionId &&
1063
1734
  engineRun.code !== 0 &&
1064
1735
  !adapter.sessionId?.(engineRun.stdout)) {
1065
1736
  log(`${engineName} could not continue the session a plan limit cut — starting a new session in the same worktree`);
1066
- inv = adapter.buildInvocation({
1737
+ inv = buildInvocation({
1067
1738
  ...ctx,
1068
- prompt: revising
1069
- ? `${reviseBrief(revising.note, revising.round)}\n\n${ctx.prompt}`
1070
- : resumeBrief(ctx.prompt, 'limit'),
1739
+ prompt: parkBrief
1740
+ ? `${parkBrief}\n\n${ctx.prompt}`
1741
+ : revising
1742
+ ? `${reviseBrief(revising.note, revising.round)}\n\n${ctx.prompt}`
1743
+ : resumeBrief(ctx.prompt, 'limit'),
1071
1744
  });
1072
1745
  engineRun = await runEngine();
1073
1746
  meter(engineRun.stdout, false);
1074
1747
  }
1075
1748
  for (let resumes = 0; resumes < 2 && engineRun.code !== 0; resumes++) {
1076
- if (limitOf(engineRun.stdout))
1749
+ if (limitOf(engineRun.stdout, engineRun.stderr))
1077
1750
  break;
1078
1751
  if (refused(engineRun.stdout, engineRun.stderr))
1079
1752
  break;
@@ -1093,10 +1766,80 @@ export async function runJob(job, cfg, api, viewer, opts) {
1093
1766
  break;
1094
1767
  }
1095
1768
  log(`the network is back — resuming ${engineName} in the same worktree`);
1096
- inv = adapter.buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt) });
1769
+ inv = buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt) });
1097
1770
  engineRun = await runEngine();
1098
1771
  meter(engineRun.stdout, false);
1099
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
+ }
1806
+ {
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)) {
1812
+ const until = startFallback(planCut.resetsAt, rdir, now());
1813
+ log(`${engineName}'s plan limit is spent — continuing on the API key until ${until.toISOString()}, in the same worktree`);
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') });
1839
+ engineRun = await runEngine();
1840
+ meter(engineRun.stdout, false);
1841
+ }
1842
+ }
1100
1843
  const openAtEnd = (stdout) => {
1101
1844
  try {
1102
1845
  return adapter.openCommandsAtEnd?.(stdout) ?? [];
@@ -1105,9 +1848,19 @@ export async function runJob(job, cfg, api, viewer, opts) {
1105
1848
  return [];
1106
1849
  }
1107
1850
  };
1108
- const endedOnItsAnswer = (r) => r.code === 0 && !limitOf(r.stdout) && !refused(r.stdout, r.stderr);
1109
- let open = endedOnItsAnswer(engineRun) ? openAtEnd(engineRun.stdout) : [];
1110
- let promising = endedOnItsAnswer(engineRun) && promisesLaterCheck(adapter.summarize(engineRun.stdout));
1851
+ const endedOnItsAnswer = (r) => r.code === 0 && !limitOf(r.stdout, r.stderr) && !refused(r.stdout, r.stderr);
1852
+ const parkNow = endedOnItsAnswer(engineRun) && (job.askPerson === true || phase === 'plan')
1853
+ ? await parkReasonFor({
1854
+ askPerson: job.askPerson === true,
1855
+ phase,
1856
+ planRound,
1857
+ check: () => api.parkCheck(job.runId),
1858
+ })
1859
+ : null;
1860
+ let open = !parkNow && endedOnItsAnswer(engineRun) ? openAtEnd(engineRun.stdout) : [];
1861
+ let promising = !parkNow &&
1862
+ endedOnItsAnswer(engineRun) &&
1863
+ promisesLaterCheck(adapter.summarize(engineRun.stdout));
1111
1864
  const toContinue = adapter.resumesSessions
1112
1865
  ? (adapter.sessionId?.(engineRun.stdout) ?? null)
1113
1866
  : null;
@@ -1118,7 +1871,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1118
1871
  }
1119
1872
  else if ((open.length > 0 || promising) && toContinue) {
1120
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`);
1121
- inv = adapter.buildInvocation({
1874
+ inv = buildInvocation({
1122
1875
  ...ctx,
1123
1876
  prompt: continueToFinishBrief(open),
1124
1877
  resumeSessionId: toContinue,
@@ -1132,45 +1885,183 @@ export async function runJob(job, cfg, api, viewer, opts) {
1132
1885
  }
1133
1886
  openCommandAtEnd = open.length > 0;
1134
1887
  const unfinished = open.length > 0 || promising;
1135
- 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
+ }
1136
1937
  usage =
1137
1938
  attemptUsage(sessions, resumeCut ? { session: resumeCut.sessionId, baseline: resumeCut.usage } : undefined) ?? undefined;
1138
1939
  if (revising && kept?.attemptUsage) {
1139
1940
  usage = combineUsage([kept.attemptUsage, usage ?? null]) ?? usage;
1140
1941
  }
1942
+ if (parkStep && parkKept?.attemptUsage) {
1943
+ usage = combineUsage([parkKept.attemptUsage, usage ?? null]) ?? usage;
1944
+ }
1141
1945
  if (usage)
1142
1946
  log(`${engineName} spent: ${describeUsage(usage)}`);
1143
1947
  viewer?.end(job.runId, engineRun.code === 0 ? 'done' : 'failed');
1144
1948
  if (printer)
1145
1949
  log(`── end ${engineName} session ──`);
1146
1950
  await activity.flush();
1951
+ activitySeen = activity.seen;
1147
1952
  log(`reported ${activity.sent} of ${activity.seen} step(s) to FireFunc — names and verbs only; the session stayed here`);
1148
1953
  mcp?.cleanup();
1149
1954
  const sessionLogPath = saveSessionLog(job.runId, engineRun.stdout, engineRun.stderr);
1955
+ if (checkpointTimer)
1956
+ clearInterval(checkpointTimer);
1957
+ if (checkpointing)
1958
+ await checkpointing;
1150
1959
  const summary = adapter.summarize(engineRun.stdout);
1151
1960
  if (sessionLogPath)
1152
1961
  log(`${engineName} session saved → ${sessionLogPath}`);
1153
1962
  if (summary)
1154
1963
  log(`${engineName} said: ${summary.replace(/\s+/g, ' ').slice(0, 500)}`);
1964
+ if (isStopped(job.runId))
1965
+ return await fail(stoppedByPersonSentence(engineName, 'engine'));
1966
+ const keepForNextRun = (reason) => {
1967
+ const sessionId = adapter.resumesSessions
1968
+ ? (adapter.sessionId?.(engineRun.stdout) ?? (resumeCut?.sessionId || null))
1969
+ : null;
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 },
2028
+ });
2029
+ }
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
+ }
1155
2042
  if (engineRun.code === 124) {
1156
- return fail(budget !== null && limitMinutes === budget
2043
+ const keptOnTimeout = keepForNextRun('timeout');
2044
+ const limitWords = budget !== null && limitMinutes === budget
1157
2045
  ? `${engineName} timed out after ${limitMinutes} min — the agent's time budget.`
1158
- : `${engineName} timed out after ${limitMinutes} min.`);
2046
+ : `${engineName} timed out after ${limitMinutes} min.`;
2047
+ return await fail(keptOnTimeout
2048
+ ? `${limitWords} Its work is kept on this machine for a day: Re-run continues it from where it stopped.`
2049
+ : limitWords);
1159
2050
  }
1160
- const limit = limitOf(engineRun.stdout);
2051
+ const limit = limitOf(engineRun.stdout, engineRun.stderr);
1161
2052
  if (limit) {
1162
2053
  opts?.limits?.set(adapter.id, limit);
1163
2054
  const cutSession = adapter.resumesSessions
1164
2055
  ? (adapter.sessionId?.(engineRun.stdout) ?? null)
1165
2056
  : null;
1166
2057
  let kept = false;
1167
- if (cutSession && worktree) {
2058
+ if (worktree) {
1168
2059
  const cutAt = now().getTime();
1169
2060
  kept = saveCut(rdir, {
1170
2061
  workItemId: job.workItemId,
1171
2062
  runId: job.runId,
1172
2063
  engine: adapter.id,
1173
- sessionId: cutSession,
2064
+ sessionId: cutSession ?? '',
1174
2065
  repo: job.repo ?? null,
1175
2066
  branch: toolsOnly ? '' : branch,
1176
2067
  base,
@@ -1191,10 +2082,14 @@ export async function runJob(job, cfg, api, viewer, opts) {
1191
2082
  keepWorktree = kept;
1192
2083
  log(`${engineName} was stopped by the plan's usage limit${limit.said ? ` ("${limit.said}")` : ''} — ` +
1193
2084
  (limit.resetsAt ? `it resets at ${limit.resetsAt}` : 'it did not say when it resets') +
1194
- (kept ? '; the session and its worktree are kept to continue after the reset' : ''));
1195
- 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({
1196
2091
  status: 'failed',
1197
- error: limitSentence(engineName, limit, kept),
2092
+ error: limitSentence(engineName, limit, kept ? (cutSession ? 'session' : 'worktree') : false),
1198
2093
  limit: { kind: 'plan', resetsAt: limit.resetsAt },
1199
2094
  });
1200
2095
  }
@@ -1204,6 +2099,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1204
2099
  log(`the model declined ${job.runId}: its safety system refused the session`);
1205
2100
  return { status: 'failed', error: modelDeclinedSentence(engineName) };
1206
2101
  };
2102
+ let authFailed = false;
1207
2103
  const scanHints = () => {
1208
2104
  const declined = declinedHint();
1209
2105
  if (declined)
@@ -1211,6 +2107,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
1211
2107
  const authMsg = adapter.authFailureHint(`${summary}\n${engineRun.stderr}`);
1212
2108
  if (authMsg) {
1213
2109
  log(`auth/billing failure for ${job.runId}: ${authMsg}`);
2110
+ authFailed = true;
1214
2111
  return { status: 'failed', error: authMsg };
1215
2112
  }
1216
2113
  const rateMsg = adapter.rateLimitHint(`${summary}\n${engineRun.stderr}`);
@@ -1220,24 +2117,86 @@ export async function runJob(job, cfg, api, viewer, opts) {
1220
2117
  }
1221
2118
  return null;
1222
2119
  };
2120
+ if (parkNow) {
2121
+ const head = (await execOut('git', ['-C', worktree, 'rev-parse', 'HEAD']).catch(() => '')).trim() ||
2122
+ '0'.repeat(40);
2123
+ const changedFiles = parkNow.kind === 'plan' && !toolsOnly ? await changedWhilePlanning(worktree) : null;
2124
+ const at = now();
2125
+ const saved = saveKept(rdir, {
2126
+ runId: job.runId,
2127
+ workItemId: job.workItemId,
2128
+ engine: adapter.id,
2129
+ sessionId: adapter.sessionId?.(engineRun.stdout) ?? (resumeCut?.sessionId || null),
2130
+ repo: job.repo ?? '',
2131
+ branch: toolsOnly ? '' : branch,
2132
+ base,
2133
+ worktree,
2134
+ repoPath: toolsOnly ? null : (repoPath ?? null),
2135
+ continuesBranch,
2136
+ ...(readHead ? { readHead } : {}),
2137
+ head,
2138
+ round: parkNow.seq,
2139
+ title: job.title ?? '',
2140
+ kind: 'fix',
2141
+ summary: summary ? reportedSummary(summary) : null,
2142
+ keptAt: at.toISOString(),
2143
+ keepUntil: keepUntilFrom(at.getTime()),
2144
+ writtenSkills,
2145
+ ...(usage ? { attemptUsage: usage } : {}),
2146
+ ...(lastReport ? { sessionReport: lastReport } : {}),
2147
+ park: { kind: parkNow.kind, seq: parkNow.seq, phase },
2148
+ activitySeq: activitySeen,
2149
+ review,
2150
+ toolsOnly,
2151
+ });
2152
+ if (!saved) {
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.`);
2154
+ }
2155
+ keepWorktree = true;
2156
+ log(parkedLine(job.runId, parkNow));
2157
+ return await report({
2158
+ status: 'parked',
2159
+ park: {
2160
+ kind: parkNow.kind,
2161
+ seq: parkNow.seq,
2162
+ ...(changedFiles !== null ? { changedFiles } : {}),
2163
+ },
2164
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
2165
+ });
2166
+ }
1223
2167
  if (engineRun.code !== 0) {
1224
2168
  const signal = endedBySignal(engineRun.code);
1225
2169
  if (signal) {
1226
2170
  log(`${engineName} was ended by ${signal} (exit ${engineRun.code}) for ${job.runId}`);
1227
- 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.'));
1228
2180
  }
1229
2181
  const hinted = scanHints();
1230
- if (hinted)
1231
- 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
+ }
1232
2191
  const why = summary ? null : errorLine(engineRun.stderr);
1233
- return fail(summary
2192
+ return await fail(summary
1234
2193
  ? `${engineName} exited abnormally (code ${engineRun.code}). Last message: ${oneLine(shareable(summary), 500)}`
1235
2194
  : `${engineName} exited abnormally (code ${engineRun.code})${why ? `: ${oneLine(stripWorktree(why, worktree), 200)}` : ''}. ` +
1236
2195
  `Its output stayed on the machine${sessionLogPath ? ` — the session log is logs/${basename(sessionLogPath)} in the runner’s folder` : ''}.`);
1237
2196
  }
1238
2197
  if (unfinished) {
1239
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'}`);
1240
- return fail(unfinishedSentence(engineName, open, !review && !toolsOnly, continuedOnce));
2199
+ return await fail(unfinishedSentence(engineName, open, !review && !toolsOnly, continuedOnce));
1241
2200
  }
1242
2201
  if (review) {
1243
2202
  const dirty = await exec('git', ['-C', worktree, 'status', '--porcelain']);
@@ -1247,9 +2206,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
1247
2206
  }
1248
2207
  const declinedReview = declinedHint();
1249
2208
  if (declinedReview)
1250
- return report(declinedReview);
2209
+ return await report(declinedReview);
1251
2210
  log(`review run ${job.runId} finished — reporting the agent's review`);
1252
- return report({
2211
+ return await report({
1253
2212
  status: 'no_pr',
1254
2213
  ...(summary
1255
2214
  ? { summary: reportedSummary(summary) }
@@ -1259,26 +2218,16 @@ export async function runJob(job, cfg, api, viewer, opts) {
1259
2218
  if (toolsOnly) {
1260
2219
  const declinedAnswer = declinedHint();
1261
2220
  if (declinedAnswer)
1262
- return report(declinedAnswer);
2221
+ return await report(declinedAnswer);
1263
2222
  log(`tools-only run ${job.runId} finished — reporting the agent's summary`);
1264
- return report({
2223
+ return await report({
1265
2224
  status: 'no_pr',
1266
2225
  ...(summary
1267
2226
  ? { summary: reportedSummary(summary) }
1268
2227
  : { error: `${engineName} finished without a summary of what it did.` }),
1269
2228
  });
1270
2229
  }
1271
- await exec('git', [
1272
- '-C',
1273
- worktree,
1274
- 'add',
1275
- '-A',
1276
- '--',
1277
- '.',
1278
- ':(exclude).env',
1279
- ':(exclude).claude/skills',
1280
- ...writtenSkills.pathspecs,
1281
- ]);
2230
+ await exec('git', stageArgs);
1282
2231
  const vsBase = await exec('git', [
1283
2232
  '-C',
1284
2233
  worktree,
@@ -1290,9 +2239,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
1290
2239
  if (vsBase.code === 0) {
1291
2240
  const hinted = scanHints();
1292
2241
  if (hinted)
1293
- return report(hinted);
2242
+ return await report(hinted);
1294
2243
  log(`no changes produced for ${job.runId} — reporting no_pr`);
1295
- return report({
2244
+ return await report({
1296
2245
  status: 'no_pr',
1297
2246
  error: summary
1298
2247
  ? `No code change made. ${engineName}: ${oneLine(shareable(summary), 800)}`
@@ -1311,11 +2260,25 @@ export async function runJob(job, cfg, api, viewer, opts) {
1311
2260
  continuesBranch ? `origin/${branch}` : `origin/${base}`,
1312
2261
  ], { timeoutMs: 60_000 }).catch(() => null);
1313
2262
  const kind = changeKind(touched?.code === 0 ? touched.stdout.split('\0').filter(Boolean) : null);
1314
- const title = pullRequestTitle(job, kind);
2263
+ const agentText = await readFile(join(worktree, AGENT_PR_FILE), 'utf8')
2264
+ .then((t) => parseAgentPullRequest(blankSecrets(t.slice(0, 70_000))))
2265
+ .catch(() => null);
2266
+ const title = agentText?.title ?? pullRequestTitle(job, kind);
2267
+ if (agentText)
2268
+ log(`the agent named the pull request in ${AGENT_PR_FILE}`);
1315
2269
  log(`${kind === 'test' ? 'the change touches tests only — ' : ''}titled "${title}"`);
1316
2270
  const uncommitted = await exec('git', ['-C', worktree, 'diff', '--cached', '--quiet', 'HEAD']);
1317
2271
  if (uncommitted.code !== 0) {
1318
- 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
+ ]);
1319
2282
  }
1320
2283
  else {
1321
2284
  log(`agent already committed its changes for ${job.runId} — reconciling to a PR`);
@@ -1328,6 +2291,8 @@ export async function runJob(job, cfg, api, viewer, opts) {
1328
2291
  kind,
1329
2292
  engineName,
1330
2293
  summary,
2294
+ agentText,
2295
+ keepOnPushFailure: () => keepForNextRun('push'),
1331
2296
  keep: askFirst
1332
2297
  ? {
1333
2298
  sessionId: adapter.sessionId?.(engineRun.stdout) ?? (resumeCut?.sessionId || null),
@@ -1339,16 +2304,22 @@ export async function runJob(job, cfg, api, viewer, opts) {
1339
2304
  }
1340
2305
  catch (err) {
1341
2306
  log(`job ${job.runId} errored: ${err.message}`);
1342
- return report({ status: 'failed', error: err.message.slice(0, 400) });
2307
+ return await report({ status: 'failed', error: err.message.slice(0, 400) });
1343
2308
  }
1344
2309
  finally {
2310
+ if (job.agentEnv?.length) {
2311
+ setTimeout(() => releaseSecretValues(job.runId), 15 * 60_000).unref();
2312
+ }
1345
2313
  mcp?.cleanup();
1346
2314
  viewer?.end(job.runId, 'failed');
1347
2315
  await Promise.all(bgProcs.map((p) => killProcessTree(p).catch(() => { })));
1348
2316
  const reviewCopies = worktree ? reviewCopiesOf(worktree) : [];
1349
- 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) {
1350
2321
  await killOrphans({
1351
- roots: [worktree, attachDir, ...reviewCopies].filter((p) => !!p),
2322
+ roots: [worktree, attachDir, runTemp, ...reviewCopies].filter((p) => !!p),
1352
2323
  ...(worktree ? { reviewCopiesOf: basename(worktree) } : {}),
1353
2324
  groups: engineGroups.map((g) => ({ ...g, leaderExited: true })),
1354
2325
  }, { log }).catch(() => { });
@@ -1370,6 +2341,8 @@ export async function runJob(job, cfg, api, viewer, opts) {
1370
2341
  dropCut(rdir, resumeCut.workItemId);
1371
2342
  if (kept && !keepWorktree)
1372
2343
  dropKept(rdir, job.runId);
2344
+ if (parkKept && !keepWorktree)
2345
+ dropKept(rdir, job.runId);
1373
2346
  if (!keepWorktree) {
1374
2347
  for (const copy of reviewCopies) {
1375
2348
  try {
@@ -1386,6 +2359,10 @@ export async function runJob(job, cfg, api, viewer, opts) {
1386
2359
  catch {
1387
2360
  }
1388
2361
  }
2362
+ if (!keepWorktree)
2363
+ removeRunTemp(runTemp);
2364
+ if (worktree)
2365
+ await reportWorktree(api, job.runId, worktree, endedState(worktree, keepWorktree));
1389
2366
  }
1390
2367
  }
1391
2368
  //# sourceMappingURL=job.js.map