@firefunc-agent/runner 0.7.1 → 0.9.3

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 (114) hide show
  1. package/LICENSE +7 -3
  2. package/README.md +296 -4
  3. package/dist/activity.d.ts +32 -0
  4. package/dist/activity.js +295 -0
  5. package/dist/api.d.ts +69 -1
  6. package/dist/api.js +114 -3
  7. package/dist/brief.d.ts +11 -0
  8. package/dist/brief.js +278 -0
  9. package/dist/build-info.json +4 -0
  10. package/dist/cli.js +59 -2
  11. package/dist/config.d.ts +7 -0
  12. package/dist/config.js +3 -0
  13. package/dist/cut.d.ts +45 -0
  14. package/dist/cut.js +105 -0
  15. package/dist/daemon.d.ts +16 -0
  16. package/dist/daemon.js +196 -7
  17. package/dist/declined.d.ts +11 -0
  18. package/dist/declined.js +27 -0
  19. package/dist/engines/antigravity.d.ts +2 -0
  20. package/dist/engines/antigravity.js +102 -0
  21. package/dist/engines/claude-budget.d.ts +1 -1
  22. package/dist/engines/claude-budget.js +2 -72
  23. package/dist/engines/claude.js +139 -2
  24. package/dist/engines/codex.js +10 -3
  25. package/dist/engines/copilot.d.ts +2 -0
  26. package/dist/engines/copilot.js +117 -0
  27. package/dist/engines/cursor.js +4 -0
  28. package/dist/engines/gemini.js +6 -1
  29. package/dist/engines/index.d.ts +2 -0
  30. package/dist/engines/index.js +22 -4
  31. package/dist/engines/types.d.ts +12 -1
  32. package/dist/exec.d.ts +3 -0
  33. package/dist/exec.js +48 -5
  34. package/dist/firefunc/agents.d.ts +2 -0
  35. package/dist/firefunc/agents.js +343 -0
  36. package/dist/firefunc/args.d.ts +18 -0
  37. package/dist/firefunc/args.js +82 -0
  38. package/dist/firefunc/auth.d.ts +21 -0
  39. package/dist/firefunc/auth.js +129 -0
  40. package/dist/firefunc/catalog.d.ts +10 -0
  41. package/dist/firefunc/catalog.js +201 -0
  42. package/dist/firefunc/cli.d.ts +2 -0
  43. package/dist/firefunc/cli.js +24 -0
  44. package/dist/firefunc/client.d.ts +36 -0
  45. package/dist/firefunc/client.js +177 -0
  46. package/dist/firefunc/command.d.ts +28 -0
  47. package/dist/firefunc/command.js +35 -0
  48. package/dist/firefunc/config.d.ts +29 -0
  49. package/dist/firefunc/config.js +111 -0
  50. package/dist/firefunc/configure.d.ts +6 -0
  51. package/dist/firefunc/configure.js +409 -0
  52. package/dist/firefunc/io.d.ts +25 -0
  53. package/dist/firefunc/io.js +14 -0
  54. package/dist/firefunc/main.d.ts +4 -0
  55. package/dist/firefunc/main.js +259 -0
  56. package/dist/firefunc/output.d.ts +29 -0
  57. package/dist/firefunc/output.js +131 -0
  58. package/dist/firefunc/prompt.d.ts +14 -0
  59. package/dist/firefunc/prompt.js +58 -0
  60. package/dist/firefunc/skill.d.ts +3 -0
  61. package/dist/firefunc/skill.js +80 -0
  62. package/dist/firefunc/tasks.d.ts +2 -0
  63. package/dist/firefunc/tasks.js +279 -0
  64. package/dist/firefunc/version.d.ts +2 -0
  65. package/dist/firefunc/version.js +8 -0
  66. package/dist/git-auth.d.ts +4 -1
  67. package/dist/git-auth.js +6 -2
  68. package/dist/held.d.ts +18 -0
  69. package/dist/held.js +95 -0
  70. package/dist/job.d.ts +3 -0
  71. package/dist/job.js +818 -102
  72. package/dist/keep-local.d.ts +12 -0
  73. package/dist/keep-local.js +651 -0
  74. package/dist/limit.d.ts +30 -0
  75. package/dist/limit.js +258 -0
  76. package/dist/locks.d.ts +14 -0
  77. package/dist/locks.js +164 -0
  78. package/dist/machine-logins.d.ts +19 -0
  79. package/dist/machine-logins.js +187 -0
  80. package/dist/mcp-login.d.ts +24 -0
  81. package/dist/mcp-login.js +993 -0
  82. package/dist/mcp-proxy.d.ts +21 -0
  83. package/dist/mcp-proxy.js +180 -0
  84. package/dist/mcp.d.ts +62 -0
  85. package/dist/mcp.js +611 -0
  86. package/dist/network.d.ts +20 -0
  87. package/dist/network.js +76 -0
  88. package/dist/orphans.d.ts +40 -0
  89. package/dist/orphans.js +235 -0
  90. package/dist/pending.d.ts +14 -0
  91. package/dist/pending.js +56 -0
  92. package/dist/pool.d.ts +7 -0
  93. package/dist/pool.js +57 -9
  94. package/dist/pr-title.d.ts +11 -0
  95. package/dist/pr-title.js +63 -0
  96. package/dist/recover.d.ts +10 -0
  97. package/dist/recover.js +104 -0
  98. package/dist/secret-scan.d.ts +19 -0
  99. package/dist/secret-scan.js +161 -0
  100. package/dist/session-stream.d.ts +9 -1
  101. package/dist/session-stream.js +20 -2
  102. package/dist/skills.d.ts +11 -0
  103. package/dist/skills.js +164 -0
  104. package/dist/stopped.d.ts +3 -0
  105. package/dist/stopped.js +10 -0
  106. package/dist/usage.d.ts +49 -0
  107. package/dist/usage.js +389 -0
  108. package/dist/version.d.ts +1 -0
  109. package/dist/version.js +17 -0
  110. package/dist/viewer.js +7 -1
  111. package/dist/worktrees.d.ts +15 -0
  112. package/dist/worktrees.js +96 -0
  113. package/package.json +8 -5
  114. package/skill/firefunc/SKILL.md +222 -0
package/dist/job.js CHANGED
@@ -1,11 +1,32 @@
1
1
  import { mkdtempSync, rmSync, existsSync, mkdirSync, writeFileSync, copyFileSync, appendFileSync, chmodSync, readdirSync, } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { join, basename, dirname } from 'node:path';
2
+ import { homedir, tmpdir } from 'node:os';
3
+ import { join, basename, dirname, relative, sep } from 'node:path';
4
+ import {} from 'node:child_process';
4
5
  import { exec, execOut, spawnBackground, killProcessTree } from './exec.js';
6
+ import { REPORTED_SUMMARY_MAX, cutText } from './api.js';
5
7
  import { configPath, loadConfig, saveConfig } from './config.js';
6
- import { cloneRepo, openDraftPr, pushBranch, redact } from './git-auth.js';
7
- import { createKeyedMutex } from './locks.js';
8
+ import { cloneRepo, openDraftPr, pushBranch, pushFlags, redact } from './git-auth.js';
9
+ import { createActivityReporter, redact as oneLine, stripWorktree } from './activity.js';
10
+ 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';
12
+ import { isNetworkError, networkFailureHint, waitForNetwork, withNetworkRetry } from './network.js';
13
+ import { endedOnRefusal, modelDeclinedSentence } from './declined.js';
14
+ import { endedBySignal, stoppedSentence } from './stopped.js';
15
+ import { changeKind, pullRequestBody, pullRequestTitle } from './pr-title.js';
16
+ import { savePendingResult } from './pending.js';
17
+ import { runnerDir } from './config.js';
18
+ import { attemptUsage, describeUsage } from './usage.js';
19
+ import { makeStreamJsonParser } from './session-stream.js';
20
+ import { writeSkills, writtenSkillPaths } from './skills.js';
21
+ import { createKeyedMutex, ensureHeavyScript, heavyLockDir, withHeavyLock } from './locks.js';
8
22
  import { getAdapter, stripForeignEngineCreds } from './engines/index.js';
23
+ import { mcpFormatForEngine, prepareMcp } from './mcp.js';
24
+ import { continueToFinishBrief, engineRules } from './brief.js';
25
+ import { limitSentence } from './limit.js';
26
+ import { cutFor, dropCut, keepUntil, promptHash, resumeAfterResetBrief, saveCut, } from './cut.js';
27
+ import { liveWorktrees, updateHeld } from './held.js';
28
+ import { killOrphans, reviewCopiesOf, trackEngineGroup, untrackEngineGroup } from './orphans.js';
29
+ import { canonicalPath, removeRunnerWorktree, staleHolder } from './worktrees.js';
9
30
  function log(msg) {
10
31
  console.log(`[firefunc-runner] ${new Date().toISOString()} ${msg}`);
11
32
  }
@@ -129,20 +150,98 @@ async function autoInstallDeps(worktree, env, timeoutMs) {
129
150
  if (!installed && dirs[0] !== '')
130
151
  log('auto-install: no package.json found — skipping');
131
152
  }
153
+ function unfinishedSentence(engineName, open, changeRun, continued) {
154
+ const how = open.length === 0
155
+ ? 'on a promise to check a result later'
156
+ : open.length === 1
157
+ ? `while a command it had started (${open[0]}) was still running`
158
+ : `while commands it had started (${open.join(', ')}) were still running`;
159
+ return (`${engineName} ended its session ${how}` +
160
+ (continued ? ', and again after the runner continued it once to get the result' : '') +
161
+ ' — the result it was waiting for never came, so its closing words are not reported as its answer' +
162
+ (changeRun ? ' and the runner pushed nothing' : '') +
163
+ '. 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.');
164
+ }
165
+ function resumeBrief(prompt, why = 'network') {
166
+ const what = why === 'limit'
167
+ ? "was stopped by the plan's usage limit, which has now reset, and that session could not be continued"
168
+ : 'was cut short by a network outage';
169
+ return (`Your previous session on this task ${what}. The worktree ` +
170
+ 'still holds everything you did; look at `git status` and `git diff`, continue from ' +
171
+ 'there, and finish the task. The original brief follows.\n\n' +
172
+ prompt);
173
+ }
132
174
  export async function runJob(job, cfg, api, viewer, opts) {
133
- const report = async (payload) => {
175
+ const now = opts?.now ?? (() => new Date());
176
+ const rdir = runnerDir();
177
+ let secretScan;
178
+ let usage;
179
+ let readHead;
180
+ let openCommandAtEnd = false;
181
+ const report = async (reported) => {
182
+ let payload = secretScan && !reported.secretScan ? { ...reported, secretScan } : reported;
183
+ if (usage && !payload.usage)
184
+ payload = { ...payload, usage };
185
+ if (readHead && !payload.readHead)
186
+ payload = { ...payload, readHead };
187
+ if (openCommandAtEnd && !payload.openCommandAtEnd) {
188
+ payload = { ...payload, openCommandAtEnd: true };
189
+ }
134
190
  try {
135
- await api.result(job.runId, payload);
191
+ await withNetworkRetry(() => api.result(job.runId, payload), {
192
+ label: `result for ${job.runId}`,
193
+ maxWaitMs: 10 * 60_000,
194
+ probe: () => api.probe(),
195
+ log,
196
+ });
136
197
  }
137
198
  catch (err) {
138
- log(`failed to report result for ${job.runId}: ${err.message}`);
199
+ if (isNetworkError(err)) {
200
+ try {
201
+ const file = savePendingResult(runnerDir(), job.runId, payload);
202
+ log(`FireFunc is still unreachable — kept the result for ${job.runId} at ${file}; it is delivered when the network is back`);
203
+ }
204
+ catch (e) {
205
+ log(`failed to keep the result for ${job.runId}: ${e.message}`);
206
+ }
207
+ }
208
+ else {
209
+ log(`failed to report result for ${job.runId}: ${err.message}`);
210
+ }
139
211
  }
140
212
  };
213
+ class NetworkGoneError extends Error {
214
+ constructor(detail) {
215
+ super(`fetch failed: ${detail}`);
216
+ this.name = 'NetworkGoneError';
217
+ }
218
+ }
219
+ const shareable = (text) => stripCode(worktree ? stripWorktree(text, worktree) : text);
220
+ const reportedSummary = (text) => cutText(shareable(text)
221
+ .replace(/\r\n?/g, '\n')
222
+ .replace(/[ \t]+/g, ' ')
223
+ .replace(/ +$/gm, '')
224
+ .replace(/\n{3,}/g, '\n\n')
225
+ .trim(), REPORTED_SUMMARY_MAX);
141
226
  const fail = (error) => {
142
227
  log(`job ${job.runId} FAILED — ${error.replace(/\s+/g, ' ').slice(0, 300)}`);
143
228
  return report({ status: 'failed', error });
144
229
  };
145
- let repoPath = resolveRepoPath(job.repo, cfg);
230
+ const toolsOnly = !job.repo;
231
+ const continuesBranch = !toolsOnly && job.continuesBranch === true;
232
+ const review = !toolsOnly && job.review === true;
233
+ const adapter = getAdapter(job.engine ?? cfg.engine);
234
+ const spent = opts?.limits?.isLimited(adapter.id) ?? null;
235
+ if (spent) {
236
+ const limit = { kind: 'plan', resetsAt: spent.resetsAt };
237
+ log(`${adapter.displayName}'s plan limit is spent until ${spent.until} — answering ${job.runId} without starting it`);
238
+ return report({
239
+ status: 'failed',
240
+ error: limitSentence(adapter.displayName, limit, false),
241
+ limit: { kind: 'plan', resetsAt: limit.resetsAt },
242
+ });
243
+ }
244
+ let repoPath = toolsOnly ? null : resolveRepoPath(job.repo, cfg);
146
245
  if (!repoPath && job.repo) {
147
246
  const cred = await api.gitCredential(job.runId);
148
247
  const dest = cloneDestination(job.repo, cfg);
@@ -162,7 +261,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
162
261
  }
163
262
  }
164
263
  }
165
- if (!repoPath) {
264
+ if (!repoPath && !toolsOnly) {
166
265
  log(`no local checkout for ${job.repo} and no credential to clone with`);
167
266
  return report({
168
267
  status: 'failed',
@@ -171,38 +270,167 @@ export async function runJob(job, cfg, api, viewer, opts) {
171
270
  `${job.repo} <path>\`, set --repos-dir, or connect GitHub in FireFunc.`,
172
271
  });
173
272
  }
174
- const adapter = getAdapter(job.engine ?? cfg.engine);
175
273
  const branch = job.branch ?? `${adapter.branchPrefix}/firefunc-${job.runId.slice(0, 8)}`;
176
- const timeoutMs = (cfg.jobTimeoutMinutes ?? 20) * 60_000;
274
+ const budget = typeof job.maxMinutes === 'number' && Number.isFinite(job.maxMinutes) && job.maxMinutes > 0
275
+ ? Math.ceil(job.maxMinutes)
276
+ : null;
277
+ const limitMinutes = budget !== null
278
+ ? cfg.jobTimeoutMinutes
279
+ ? Math.min(budget, cfg.jobTimeoutMinutes)
280
+ : budget
281
+ : (cfg.jobTimeoutMinutes ?? 20);
282
+ const timeoutMs = limitMinutes * 60_000;
283
+ const cutMatch = cutFor(rdir, {
284
+ workItemId: job.workItemId,
285
+ engine: adapter.id,
286
+ repo: job.repo ?? null,
287
+ branch: toolsOnly ? '' : branch,
288
+ review,
289
+ toolsOnly,
290
+ }, now().getTime());
291
+ let resumeCut = null;
292
+ if (cutMatch && 'resume' in cutMatch && adapter.resumesSessions) {
293
+ resumeCut = cutMatch.resume;
294
+ }
295
+ else if (cutMatch) {
296
+ const stale = 'resume' in cutMatch ? cutMatch.resume : cutMatch.discard;
297
+ log(`the session a plan limit cut for this task cannot be continued by ${job.runId} — removing it`);
298
+ if (stale.repoPath && existsSync(stale.repoPath)) {
299
+ const holder = stale.repoPath;
300
+ await gitMutex
301
+ .run(holder, () => removeRunnerWorktree(holder, stale.worktree, log))
302
+ .catch(() => { });
303
+ }
304
+ else {
305
+ try {
306
+ rmSync(stale.worktree, { recursive: true, force: true });
307
+ }
308
+ catch {
309
+ }
310
+ }
311
+ dropCut(rdir, stale.workItemId);
312
+ }
313
+ let keepWorktree = false;
314
+ const engineGroups = [];
177
315
  let worktree = null;
178
316
  let attachDir = null;
317
+ let mcp = null;
318
+ let writtenSkills = { written: [], pathspecs: [] };
179
319
  const bgProcs = [];
180
320
  viewer?.begin(job.runId, {
181
321
  title: job.title ?? job.externalId ?? undefined,
182
322
  repo: job.repo ?? undefined,
183
323
  });
324
+ let base = '';
184
325
  try {
185
- await api.event(job.runId, 'cloning', { repo: job.repo, branch });
186
- const prep = await gitMutex.run(repoPath, async () => {
187
- await exec('git', ['-C', repoPath, 'fetch', 'origin', '--quiet'], { timeoutMs: 120_000 });
188
- let b = cfg.baseBranch ?? '';
189
- if (!b) {
190
- const head = await execOut('git', ['-C', repoPath, 'symbolic-ref', 'refs/remotes/origin/HEAD'], repoPath);
191
- b = head ? head.replace('refs/remotes/origin/', '') : 'main';
192
- }
193
- await exec('git', ['-C', repoPath, 'worktree', 'prune']).catch(() => { });
194
- const wt = mkdtempSync(join(tmpdir(), 'firefunc-'));
195
- const result = await exec('git', ['-C', repoPath, 'worktree', 'add', '--force', '-B', branch, wt, `origin/${b}`], { timeoutMs: 120_000 });
196
- return { base: b, wt, add: result };
197
- });
198
- const base = prep.base;
199
- worktree = prep.wt;
200
- if (prep.add.code !== 0) {
201
- return fail(`git worktree add failed: ${prep.add.stderr.slice(0, 400)}`);
326
+ if (toolsOnly && resumeCut) {
327
+ worktree = resumeCut.worktree;
328
+ writtenSkills = { written: [], pathspecs: [] };
329
+ log(`continuing the session a plan limit cut for this task, in ${worktree}`);
330
+ }
331
+ else if (toolsOnly) {
332
+ worktree = mkdtempSync(join(tmpdir(), 'firefunc-tools-'));
333
+ updateHeld(rdir, job.runId, { scratch: [worktree] });
334
+ writeSkills(worktree, job.skills, log);
335
+ await exec('git', ['-C', worktree, 'init', '--quiet']);
336
+ log(`no repository for ${job.runId} — the agent works through its tools in ${worktree}`);
337
+ }
338
+ else {
339
+ await api.event(job.runId, 'cloning', { repo: job.repo, branch });
340
+ const checkout = repoPath;
341
+ const prep = await gitMutex.run(checkout, async () => {
342
+ await exec('git', ['-C', checkout, 'fetch', 'origin', '--quiet'], { timeoutMs: 120_000 });
343
+ if (resumeCut) {
344
+ const known = await exec('git', ['-C', resumeCut.worktree, 'rev-parse', '--git-dir']);
345
+ if (known.code === 0) {
346
+ return {
347
+ base: resumeCut.base,
348
+ wt: resumeCut.worktree,
349
+ add: { code: 0, stdout: '', stderr: '' },
350
+ branchMissing: false,
351
+ startPoint: '',
352
+ };
353
+ }
354
+ log(`the worktree the plan limit's cut session kept is no longer a worktree of ${job.repo} — starting over`);
355
+ dropCut(rdir, resumeCut.workItemId);
356
+ try {
357
+ rmSync(resumeCut.worktree, { recursive: true, force: true });
358
+ }
359
+ catch {
360
+ }
361
+ resumeCut = null;
362
+ }
363
+ let b = job.baseBranch ?? cfg.baseBranch ?? '';
364
+ if (!b) {
365
+ const head = await execOut('git', ['-C', checkout, 'symbolic-ref', 'refs/remotes/origin/HEAD'], checkout);
366
+ b = head ? head.replace('refs/remotes/origin/', '') : 'main';
367
+ }
368
+ await exec('git', ['-C', checkout, 'worktree', 'prune']).catch(() => { });
369
+ let startPoint = `origin/${b}`;
370
+ if (continuesBranch) {
371
+ const has = await exec('git', [
372
+ '-C',
373
+ checkout,
374
+ 'rev-parse',
375
+ '--verify',
376
+ '--quiet',
377
+ `refs/remotes/origin/${branch}`,
378
+ ]);
379
+ if (has.code !== 0) {
380
+ return { base: b, wt: '', add: has, branchMissing: true, startPoint };
381
+ }
382
+ startPoint = `origin/${branch}`;
383
+ }
384
+ const wt = mkdtempSync(join(tmpdir(), 'firefunc-'));
385
+ const add = () => exec('git', ['-C', checkout, 'worktree', 'add', '--force', '-B', branch, wt, startPoint], {
386
+ timeoutMs: 120_000,
387
+ });
388
+ let result = await add();
389
+ const holder = result.code !== 0 ? staleHolder(result.stderr) : null;
390
+ if (holder) {
391
+ const live = new Set([...liveWorktrees(rdir)].map(canonicalPath));
392
+ if (!live.has(canonicalPath(holder))) {
393
+ log(`a worktree a stopped runner left holds ${branch} (${holder}) — removing it and trying again`);
394
+ await removeRunnerWorktree(checkout, holder, log);
395
+ result = await add();
396
+ }
397
+ }
398
+ return { base: b, wt, add: result, branchMissing: false, startPoint };
399
+ });
400
+ base = prep.base;
401
+ if (prep.branchMissing) {
402
+ 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. ` +
403
+ `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.`);
404
+ }
405
+ worktree = prep.wt;
406
+ updateHeld(rdir, job.runId, { worktree, repoPath: checkout });
407
+ if (resumeCut) {
408
+ readHead = resumeCut.readHead;
409
+ }
410
+ else if (prep.add.code === 0 && prep.startPoint) {
411
+ const sha = await execOut('git', [
412
+ '-C',
413
+ worktree,
414
+ 'rev-parse',
415
+ '--verify',
416
+ '--quiet',
417
+ `${prep.startPoint}^{commit}`,
418
+ ]).catch(() => '');
419
+ if (FULL_SHA.test(sha))
420
+ readHead = sha;
421
+ }
422
+ if (prep.add.code !== 0) {
423
+ log(`git worktree add output for ${job.runId} (kept on this machine):\n${prep.add.stderr}`);
424
+ const said = pushRefusal(prep.add.stderr);
425
+ return fail(said
426
+ ? `git worktree add failed: ${oneLine(said, 400)}`
427
+ : `git worktree add failed (exit ${prep.add.code}); its output stayed on the machine — the runner’s log shows it.`);
428
+ }
202
429
  }
203
430
  const attachPaths = [];
204
431
  if (job.attachments?.length) {
205
432
  attachDir = mkdtempSync(join(tmpdir(), 'firefunc-attach-'));
433
+ updateHeld(rdir, job.runId, { scratch: [attachDir] });
206
434
  mkdirSync(attachDir, { recursive: true });
207
435
  job.attachments.forEach((att, i) => {
208
436
  if (!att?.dataB64)
@@ -231,9 +459,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
231
459
  if (opts?.devServerPort && cfg.backgroundCommands?.length) {
232
460
  log(`session dev-server PORT=${opts.devServerPort} (parallel-safe)`);
233
461
  }
234
- if (cfg.envFile) {
462
+ if (cfg.envFile && !toolsOnly) {
235
463
  try {
236
- const gitDir = (await execOut('git', ['-C', worktree, 'rev-parse', '--git-dir'])).trim();
464
+ const gitDir = (await execOut('git', ['-C', worktree, 'rev-parse', '--git-common-dir'])).trim();
237
465
  if (gitDir) {
238
466
  const abs = gitDir.startsWith('/') ? gitDir : join(worktree, gitDir);
239
467
  mkdirSync(join(abs, 'info'), { recursive: true });
@@ -251,25 +479,54 @@ export async function runJob(job, cfg, api, viewer, opts) {
251
479
  log(`envFile copy failed (${cfg.envFile}): ${e.message}`);
252
480
  }
253
481
  }
482
+ if (resumeCut) {
483
+ writtenSkills = resumeCut.writtenSkills ?? { written: [], pathspecs: [] };
484
+ }
485
+ else if (!toolsOnly) {
486
+ writtenSkills = writeSkills(worktree, job.skills, log);
487
+ }
488
+ const heavyLock = !toolsOnly && job.repo && cfg.heavyLock !== false ? heavyLockDir(rdir, job.repo) : null;
489
+ const heavyHelper = heavyLock ? ensureHeavyScript(rdir) : null;
490
+ const heavily = (fn) => heavyLock
491
+ ? withHeavyLock(heavyLock, fn, {
492
+ label: `setup of ${job.runId}`,
493
+ maxWaitMs: (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000,
494
+ onWait: (holder) => log(`another heavy command is running in ${job.repo}${holder ? ` (pid ${holder})` : ''} — setup waits for it`),
495
+ })
496
+ : fn();
254
497
  const setupMs = (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000;
255
- if (cfg.setupCommands?.length) {
498
+ if (toolsOnly) {
499
+ }
500
+ else if (cfg.setupCommands?.length) {
256
501
  for (const cmd of cfg.setupCommands) {
257
502
  log(`setup: ${cmd}`);
258
- const r = await exec(cmd, [], {
259
- cwd: worktree,
503
+ const setupCwd = worktree;
504
+ const r = await heavily(() => exec(cmd, [], {
505
+ cwd: setupCwd,
260
506
  env: runEnv,
261
507
  timeoutMs: setupMs,
262
508
  shell: true,
263
- });
509
+ }));
264
510
  if (r.code !== 0) {
265
- return fail(`Setup command failed (exit ${r.code}): ${cmd}\n${r.stderr.slice(0, 400)}`);
511
+ log(`setup output for ${job.runId} (kept on this machine):\n${r.stderr.slice(-4000)}` +
512
+ `${r.stdout.trim() ? `\n--- stdout ---\n${r.stdout.slice(-2000)}` : ''}`);
513
+ const checkout = worktree;
514
+ const fold = (text) => foldHome(stripWorktree(text, checkout), homedir());
515
+ const why = setupReason(fold(r.stderr), fold(r.stdout));
516
+ const said = why ? oneLine(why, 200).replace(/[.\s]+$/, '') : '';
517
+ return fail(`Setup command failed (exit ${r.code}): ${setupCommandName(cmd)}` +
518
+ `${said ? ` — ${said}` : ''}. ` +
519
+ 'Its output stayed on the machine — the runner’s log shows it; fix the command or setupCommands in the runner config, then re-run.');
266
520
  }
267
521
  }
268
522
  }
523
+ else if (resumeCut) {
524
+ }
269
525
  else if (cfg.autoInstall ?? true) {
270
- await autoInstallDeps(worktree, runEnv, setupMs);
526
+ const installIn = worktree;
527
+ await heavily(() => autoInstallDeps(installIn, runEnv, setupMs));
271
528
  }
272
- for (const cmd of cfg.backgroundCommands ?? []) {
529
+ for (const cmd of toolsOnly ? [] : (cfg.backgroundCommands ?? [])) {
273
530
  log(`starting background: ${cmd}`);
274
531
  bgProcs.push(spawnBackground(cmd, { cwd: worktree, env: runEnv }));
275
532
  }
@@ -279,55 +536,214 @@ export async function runJob(job, cfg, api, viewer, opts) {
279
536
  const effort = job.effort ?? cfg.effort ?? null;
280
537
  const ultracode = effort === 'ultracode';
281
538
  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';
282
- const prompt = observeNote + attachNote + (ultracode ? `ultracode\n\n${job.prompt}` : job.prompt);
539
+ const rules = engineRules({ minutes: limitMinutes, heavy: heavyHelper !== null });
540
+ const prompt = rules + observeNote + attachNote + (ultracode ? `ultracode\n\n${job.prompt}` : job.prompt);
283
541
  const tools = cfg.allowedTools ??
284
542
  'Read Edit Write Bash Glob Grep WebFetch WebSearch Task TodoWrite NotebookEdit';
285
543
  const isWin = process.platform === 'win32';
544
+ if (job.mcpConfig != null) {
545
+ const format = mcpFormatForEngine(adapter.id);
546
+ if (format) {
547
+ mcp = await prepareMcp({
548
+ raw: job.mcpConfig,
549
+ worktree,
550
+ format,
551
+ runId: job.runId,
552
+ api,
553
+ log,
554
+ relay: cfg.mcpRelay !== false,
555
+ });
556
+ }
557
+ log(mcp ? `mcp: ${mcp.logLine}` : 'mcp: no server was injected for this run');
558
+ }
559
+ const ctx = {
560
+ prompt,
561
+ model,
562
+ effort,
563
+ ultracode,
564
+ permissionMode: mode,
565
+ allowedTools: tools,
566
+ maxBudgetUsd: cfg.maxBudgetUsd,
567
+ attachDir: attachDir ?? undefined,
568
+ attachPaths,
569
+ isWin,
570
+ runEnv: {
571
+ ...stripForeignEngineCreds(runEnv, adapter.id),
572
+ ...(heavyHelper && heavyLock
573
+ ? { FIREFUNC_HEAVY: heavyHelper, FIREFUNC_HEAVY_LOCK: heavyLock }
574
+ : {}),
575
+ },
576
+ cfg,
577
+ ...(mcp ? { mcp } : {}),
578
+ };
579
+ const firstCtx = resumeCut
580
+ ? {
581
+ ...ctx,
582
+ resumeSessionId: resumeCut.sessionId,
583
+ prompt: resumeAfterResetBrief(prompt, promptHash(job.prompt) !== resumeCut.promptHash),
584
+ }
585
+ : ctx;
286
586
  let inv;
287
587
  try {
288
- inv = adapter.buildInvocation({
289
- prompt,
290
- model,
291
- effort,
292
- ultracode,
293
- permissionMode: mode,
294
- allowedTools: tools,
295
- maxBudgetUsd: cfg.maxBudgetUsd,
296
- attachDir: attachDir ?? undefined,
297
- attachPaths,
298
- isWin,
299
- runEnv: stripForeignEngineCreds(runEnv, adapter.id),
300
- cfg,
301
- });
588
+ inv = adapter.buildInvocation(firstCtx);
302
589
  }
303
590
  catch (e) {
304
591
  return fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
305
592
  }
306
593
  const engineName = adapter.displayName;
307
- log(`running ${inv.bin} (${engineName}) on ${job.repo} (${branch}) — model=${model ?? 'default'} effort=${effort ?? 'default'} mode=${mode}`);
594
+ log(`running ${inv.bin} (${engineName}) on ${toolsOnly ? 'no repository — tools only' : `${job.repo} (${branch})`} — model=${model ?? 'default'} effort=${effort ?? 'default'} mode=${mode}`);
308
595
  log(`${engineName} auth: ${inv.authLogLine}`);
309
596
  const printer = cfg.quiet ? undefined : adapter.makeStreamPrinter();
310
- const onStdout = printer || viewer
311
- ? (chunk) => {
312
- printer?.(chunk);
313
- viewer?.push(job.runId, chunk);
314
- }
315
- : undefined;
597
+ const activity = createActivityReporter({
598
+ worktree,
599
+ post: (steps) => api.activity(job.runId, steps),
600
+ writeTools: new Set(mcp?.writeToolNames ?? []),
601
+ });
602
+ const activityParser = makeStreamJsonParser(activity.push, { toolResults: true });
603
+ const onStdout = (chunk) => {
604
+ printer?.(chunk);
605
+ viewer?.push(job.runId, chunk);
606
+ activityParser(chunk);
607
+ };
316
608
  if (printer) {
317
609
  log(`── live ${engineName} session (shown here only — never sent to FireFunc) ──`);
318
610
  }
319
611
  const heartbeat = setInterval(() => void api.event(job.runId, 'heartbeat'), 5 * 60_000);
320
- const engineRun = await exec(inv.bin, inv.args, {
321
- cwd: worktree,
322
- timeoutMs,
323
- env: inv.env,
324
- input: inv.stdinInput,
325
- shell: inv.shell,
326
- onStdout,
327
- }).finally(() => clearInterval(heartbeat));
612
+ const engineCwd = worktree;
613
+ let engineMs = 0;
614
+ const runEngine = async (limitMs = timeoutMs) => {
615
+ let group = 0;
616
+ const started = Date.now();
617
+ try {
618
+ return await exec(inv.bin, inv.args, {
619
+ cwd: engineCwd,
620
+ timeoutMs: limitMs,
621
+ env: inv.env,
622
+ input: inv.stdinInput,
623
+ shell: inv.shell,
624
+ onStdout,
625
+ ownGroup: true,
626
+ onSpawn: (pid) => {
627
+ group = pid;
628
+ engineGroups.push({ pgid: pid, startedAt: started });
629
+ trackEngineGroup(pid);
630
+ updateHeld(rdir, job.runId, { engineGroup: pid, engineStartedAt: started });
631
+ },
632
+ });
633
+ }
634
+ finally {
635
+ if (group)
636
+ untrackEngineGroup(group);
637
+ engineMs += Date.now() - started;
638
+ }
639
+ };
640
+ const sessions = [];
641
+ let lastReport = null;
642
+ const meter = (stdout, continued = false) => {
643
+ if (!adapter.meter)
644
+ return;
645
+ let u = null;
646
+ try {
647
+ u = adapter.meter(stdout);
648
+ }
649
+ catch {
650
+ u = null;
651
+ }
652
+ lastReport = u;
653
+ sessions.push({ usage: u, session: adapter.sessionId?.(stdout) ?? null, continued });
654
+ };
655
+ const limitOf = (stdout) => {
656
+ try {
657
+ return adapter.planLimit?.(stdout, now()) ?? null;
658
+ }
659
+ catch {
660
+ return null;
661
+ }
662
+ };
663
+ const refused = (stdout, stderr) => endedOnRefusal({
664
+ ending: adapter.ending?.(stdout),
665
+ summary: adapter.summarize(stdout),
666
+ stderr,
667
+ });
668
+ let engineRun = await runEngine();
669
+ meter(engineRun.stdout, false);
670
+ if (resumeCut && engineRun.code !== 0 && !adapter.sessionId?.(engineRun.stdout)) {
671
+ log(`${engineName} could not continue the session a plan limit cut — starting a new session in the same worktree`);
672
+ inv = adapter.buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt, 'limit') });
673
+ engineRun = await runEngine();
674
+ meter(engineRun.stdout, false);
675
+ }
676
+ for (let resumes = 0; resumes < 2 && engineRun.code !== 0; resumes++) {
677
+ if (limitOf(engineRun.stdout))
678
+ break;
679
+ if (refused(engineRun.stdout, engineRun.stderr))
680
+ break;
681
+ if (endedBySignal(engineRun.code))
682
+ break;
683
+ const why = networkFailureHint(`${adapter.summarize(engineRun.stdout)}\n${engineRun.stderr.slice(-2000)}`);
684
+ if (!why)
685
+ break;
686
+ log(`${engineName} stopped because ${why} — waiting for the network before resuming (resume ${resumes + 1} of 2)`);
687
+ const back = await waitForNetwork({
688
+ probe: () => api.probe(),
689
+ maxWaitMs: 20 * 60_000,
690
+ log,
691
+ });
692
+ if (!back) {
693
+ log('the network did not come back within 20 minutes — giving up on this attempt');
694
+ break;
695
+ }
696
+ log(`the network is back — resuming ${engineName} in the same worktree`);
697
+ inv = adapter.buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt) });
698
+ engineRun = await runEngine();
699
+ meter(engineRun.stdout, false);
700
+ }
701
+ const openAtEnd = (stdout) => {
702
+ try {
703
+ return adapter.openCommandsAtEnd?.(stdout) ?? [];
704
+ }
705
+ catch {
706
+ return [];
707
+ }
708
+ };
709
+ const endedOnItsAnswer = (r) => r.code === 0 && !limitOf(r.stdout) && !refused(r.stdout, r.stderr);
710
+ let open = endedOnItsAnswer(engineRun) ? openAtEnd(engineRun.stdout) : [];
711
+ let promising = endedOnItsAnswer(engineRun) && promisesLaterCheck(adapter.summarize(engineRun.stdout));
712
+ const toContinue = adapter.resumesSessions
713
+ ? (adapter.sessionId?.(engineRun.stdout) ?? null)
714
+ : null;
715
+ const timeLeft = timeoutMs - engineMs;
716
+ let continuedOnce = false;
717
+ if ((open.length > 0 || promising) && toContinue && timeLeft < 60_000) {
718
+ log(`${engineName}'s session ended before its result came, with under a minute of its time left — not continuing it`);
719
+ }
720
+ else if ((open.length > 0 || promising) && toContinue) {
721
+ 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`);
722
+ inv = adapter.buildInvocation({
723
+ ...ctx,
724
+ prompt: continueToFinishBrief(open),
725
+ resumeSessionId: toContinue,
726
+ });
727
+ engineRun = await runEngine(timeLeft);
728
+ meter(engineRun.stdout, true);
729
+ continuedOnce = true;
730
+ open = endedOnItsAnswer(engineRun) ? openAtEnd(engineRun.stdout) : [];
731
+ promising =
732
+ endedOnItsAnswer(engineRun) && promisesLaterCheck(adapter.summarize(engineRun.stdout));
733
+ }
734
+ openCommandAtEnd = open.length > 0;
735
+ const unfinished = open.length > 0 || promising;
736
+ clearInterval(heartbeat);
737
+ usage =
738
+ attemptUsage(sessions, resumeCut ? { session: resumeCut.sessionId, baseline: resumeCut.usage } : undefined) ?? undefined;
739
+ if (usage)
740
+ log(`${engineName} spent: ${describeUsage(usage)}`);
328
741
  viewer?.end(job.runId, engineRun.code === 0 ? 'done' : 'failed');
329
742
  if (printer)
330
743
  log(`── end ${engineName} session ──`);
744
+ await activity.flush();
745
+ log(`reported ${activity.sent} of ${activity.seen} step(s) to FireFunc — names and verbs only; the session stayed here`);
746
+ mcp?.cleanup();
331
747
  const sessionLogPath = saveSessionLog(job.runId, engineRun.stdout, engineRun.stderr);
332
748
  const summary = adapter.summarize(engineRun.stdout);
333
749
  if (sessionLogPath)
@@ -335,9 +751,61 @@ export async function runJob(job, cfg, api, viewer, opts) {
335
751
  if (summary)
336
752
  log(`${engineName} said: ${summary.replace(/\s+/g, ' ').slice(0, 500)}`);
337
753
  if (engineRun.code === 124) {
338
- return fail(`${engineName} timed out after ${cfg.jobTimeoutMinutes ?? 20} min.`);
754
+ return fail(budget !== null && limitMinutes === budget
755
+ ? `${engineName} timed out after ${limitMinutes} min — the agent's time budget.`
756
+ : `${engineName} timed out after ${limitMinutes} min.`);
339
757
  }
758
+ const limit = limitOf(engineRun.stdout);
759
+ if (limit) {
760
+ opts?.limits?.set(adapter.id, limit);
761
+ const cutSession = adapter.resumesSessions
762
+ ? (adapter.sessionId?.(engineRun.stdout) ?? null)
763
+ : null;
764
+ let kept = false;
765
+ if (cutSession && worktree) {
766
+ const cutAt = now().getTime();
767
+ kept = saveCut(rdir, {
768
+ workItemId: job.workItemId,
769
+ runId: job.runId,
770
+ engine: adapter.id,
771
+ sessionId: cutSession,
772
+ repo: job.repo ?? null,
773
+ branch: toolsOnly ? '' : branch,
774
+ base,
775
+ worktree,
776
+ repoPath: toolsOnly ? null : repoPath,
777
+ ...(readHead ? { readHead } : {}),
778
+ resetsAt: limit.resetsAt,
779
+ cutAt: new Date(cutAt).toISOString(),
780
+ keepUntil: keepUntil(limit.resetsAt, cutAt),
781
+ promptHash: promptHash(job.prompt),
782
+ review,
783
+ toolsOnly,
784
+ continuesBranch,
785
+ ...(lastReport ? { usage: lastReport } : {}),
786
+ writtenSkills,
787
+ });
788
+ }
789
+ keepWorktree = kept;
790
+ log(`${engineName} was stopped by the plan's usage limit${limit.said ? ` ("${limit.said}")` : ''} — ` +
791
+ (limit.resetsAt ? `it resets at ${limit.resetsAt}` : 'it did not say when it resets') +
792
+ (kept ? '; the session and its worktree are kept to continue after the reset' : ''));
793
+ return report({
794
+ status: 'failed',
795
+ error: limitSentence(engineName, limit, kept),
796
+ limit: { kind: 'plan', resetsAt: limit.resetsAt },
797
+ });
798
+ }
799
+ const declinedHint = () => {
800
+ if (!refused(engineRun.stdout, engineRun.stderr))
801
+ return null;
802
+ log(`the model declined ${job.runId}: its safety system refused the session`);
803
+ return { status: 'failed', error: modelDeclinedSentence(engineName) };
804
+ };
340
805
  const scanHints = () => {
806
+ const declined = declinedHint();
807
+ if (declined)
808
+ return declined;
341
809
  const authMsg = adapter.authFailureHint(`${summary}\n${engineRun.stderr}`);
342
810
  if (authMsg) {
343
811
  log(`auth/billing failure for ${job.runId}: ${authMsg}`);
@@ -351,15 +819,64 @@ export async function runJob(job, cfg, api, viewer, opts) {
351
819
  return null;
352
820
  };
353
821
  if (engineRun.code !== 0) {
822
+ const signal = endedBySignal(engineRun.code);
823
+ if (signal) {
824
+ log(`${engineName} was ended by ${signal} (exit ${engineRun.code}) for ${job.runId}`);
825
+ return fail(stoppedSentence(engineName, engineRun.code, signal, sessionLogPath ? basename(sessionLogPath) : null));
826
+ }
354
827
  const hinted = scanHints();
355
828
  if (hinted)
356
829
  return report(hinted);
830
+ const why = summary ? null : errorLine(engineRun.stderr);
357
831
  return fail(summary
358
- ? `${engineName} exited abnormally (code ${engineRun.code}). Last message: ${summary.replace(/\s+/g, ' ').slice(0, 500)}`
359
- : `${engineName} exited abnormally (code ${engineRun.code}). ${engineRun.stderr.slice(0, 300)}`);
832
+ ? `${engineName} exited abnormally (code ${engineRun.code}). Last message: ${oneLine(shareable(summary), 500)}`
833
+ : `${engineName} exited abnormally (code ${engineRun.code})${why ? `: ${oneLine(stripWorktree(why, worktree), 200)}` : ''}. ` +
834
+ `Its output stayed on the machine${sessionLogPath ? ` — the session log is logs/${basename(sessionLogPath)} in the runner’s folder` : ''}.`);
835
+ }
836
+ if (unfinished) {
837
+ 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'}`);
838
+ return fail(unfinishedSentence(engineName, open, !review && !toolsOnly, continuedOnce));
839
+ }
840
+ if (review) {
841
+ const dirty = await exec('git', ['-C', worktree, 'status', '--porcelain']);
842
+ const left = dirty.stdout.split('\n').filter((l) => l.trim()).length;
843
+ if (left > 0) {
844
+ log(`review run ${job.runId}: ${left} changed path(s) in the checkout are discarded — a review pushes nothing`);
845
+ }
846
+ const declinedReview = declinedHint();
847
+ if (declinedReview)
848
+ return report(declinedReview);
849
+ log(`review run ${job.runId} finished — reporting the agent's review`);
850
+ return report({
851
+ status: 'no_pr',
852
+ ...(summary
853
+ ? { summary: reportedSummary(summary) }
854
+ : { error: `${engineName} finished without saying what it found.` }),
855
+ });
360
856
  }
361
- const title = job.title ? `fix: ${job.title}` : `fix: ${job.externalId ?? 'FireFunc auto-fix'}`;
362
- await exec('git', ['-C', worktree, 'add', '-A', '--', '.', ':(exclude).env']);
857
+ if (toolsOnly) {
858
+ const declinedAnswer = declinedHint();
859
+ if (declinedAnswer)
860
+ return report(declinedAnswer);
861
+ log(`tools-only run ${job.runId} finished — reporting the agent's summary`);
862
+ return report({
863
+ status: 'no_pr',
864
+ ...(summary
865
+ ? { summary: reportedSummary(summary) }
866
+ : { error: `${engineName} finished without a summary of what it did.` }),
867
+ });
868
+ }
869
+ await exec('git', [
870
+ '-C',
871
+ worktree,
872
+ 'add',
873
+ '-A',
874
+ '--',
875
+ '.',
876
+ ':(exclude).env',
877
+ ':(exclude).claude/skills',
878
+ ...writtenSkills.pathspecs,
879
+ ]);
363
880
  const vsBase = await exec('git', [
364
881
  '-C',
365
882
  worktree,
@@ -376,10 +893,24 @@ export async function runJob(job, cfg, api, viewer, opts) {
376
893
  return report({
377
894
  status: 'no_pr',
378
895
  error: summary
379
- ? `No code change made. ${engineName}: ${summary.replace(/\s+/g, ' ').slice(0, 800)}`
896
+ ? `No code change made. ${engineName}: ${oneLine(shareable(summary), 800)}`
380
897
  : `${engineName} made no changes (could not reproduce or fix).`,
898
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
381
899
  });
382
900
  }
901
+ const touched = await exec('git', [
902
+ '-C',
903
+ worktree,
904
+ 'diff',
905
+ '--cached',
906
+ '--name-only',
907
+ '--no-renames',
908
+ '-z',
909
+ continuesBranch ? `origin/${branch}` : `origin/${base}`,
910
+ ], { timeoutMs: 60_000 }).catch(() => null);
911
+ const kind = changeKind(touched?.code === 0 ? touched.stdout.split('\0').filter(Boolean) : null);
912
+ const title = pullRequestTitle(job, kind);
913
+ log(`${kind === 'test' ? 'the change touches tests only — ' : ''}titled "${title}"`);
383
914
  const uncommitted = await exec('git', ['-C', worktree, 'diff', '--cached', '--quiet', 'HEAD']);
384
915
  if (uncommitted.code !== 0) {
385
916
  await exec('git', ['-C', worktree, 'commit', '-m', title, '--quiet']);
@@ -387,41 +918,180 @@ export async function runJob(job, cfg, api, viewer, opts) {
387
918
  else {
388
919
  log(`agent already committed its changes for ${job.runId} — reconciling to a PR`);
389
920
  }
921
+ const scanIn = worktree;
922
+ const tipOf = async () => {
923
+ const r = await exec('git', ['-C', scanIn, 'rev-parse', '--verify', '--quiet', `refs/heads/${branch}^{commit}`], { timeoutMs: 30_000 }).catch(() => null);
924
+ const sha = r?.code === 0 ? r.stdout.trim() : '';
925
+ return FULL_SHA.test(sha) ? sha : null;
926
+ };
927
+ const scannedTip = await tipOf();
928
+ const readChange = (args, env) => exec('git', ['-C', scanIn, ...args], { timeoutMs: 120_000, env }).catch((e) => ({
929
+ code: 1,
930
+ stdout: '',
931
+ stderr: e.message,
932
+ }));
933
+ const scanSince = async (from) => {
934
+ const reads = changeReads(from, branch, scannedTip ?? undefined);
935
+ const whole = await readChange(reads.whole, reads.env);
936
+ const commits = whole.code === 0 ? await readChange(reads.commits, reads.env) : whole;
937
+ if (whole.code !== 0 || commits.code !== 0) {
938
+ const failed = whole.code !== 0 ? whole : commits;
939
+ return {
940
+ hits: null,
941
+ why: `git exit ${failed.code}: ${failed.stderr.trim().slice(0, 200)}`,
942
+ };
943
+ }
944
+ return {
945
+ hits: uniqueHits([...scanAddedLines(whole.stdout), ...scanAddedLines(commits.stdout)]),
946
+ };
947
+ };
948
+ const found = (hits, n = 5) => hits
949
+ .slice(0, n)
950
+ .map((h) => `${h.kind} at ${h.path}:${h.line}`)
951
+ .join(', ');
952
+ const asReported = (hits) => ({
953
+ scanned: true,
954
+ hits: hits.slice(0, 100).map((h) => ({ ...h, path: h.path.slice(0, 512) })),
955
+ });
956
+ let scanCoversPullRequest = false;
957
+ const own = await scanSince(continuesBranch ? `origin/${branch}` : `origin/${base}`);
958
+ if (own.hits) {
959
+ const added = hardFirst(own.hits);
960
+ secretScan = asReported(added);
961
+ if (added.some(refusesPush)) {
962
+ log(`secret scan for ${job.runId}: ${added.length} finding(s) — ${found(added)} — refusing to push`);
963
+ return fail(secretRefusal(added, branch));
964
+ }
965
+ if (added.length > 0) {
966
+ log(`secret scan for ${job.runId}: ${added.length} looser match(es) — ${found(added)} — pushing; ` +
967
+ 'the result reports them, and FireFunc does not auto-merge a pull request with a finding');
968
+ }
969
+ else {
970
+ log(`secret scan for ${job.runId}: nothing found in what this push adds`);
971
+ }
972
+ if (!continuesBranch) {
973
+ scanCoversPullRequest = true;
974
+ }
975
+ else {
976
+ const whole = await scanSince(`origin/${base}`);
977
+ if (whole.hits) {
978
+ const all = hardFirst(uniqueHits([...added, ...whole.hits]));
979
+ secretScan = asReported(all);
980
+ scanCoversPullRequest = true;
981
+ const before = all.length - added.length;
982
+ if (before > 0) {
983
+ log(`secret scan for ${job.runId}: the pull request already holds ${before} finding(s) from commits pushed before this run — ` +
984
+ 'they are on GitHub already, so the push goes on; the result reports them, and FireFunc does not auto-merge the pull request');
985
+ }
986
+ }
987
+ else {
988
+ log(`could not read the pull request from origin/${base} to scan it whole (${whole.why}) — ` +
989
+ 'the result reports what this run adds, without the commit it covers, so FireFunc does not auto-merge it');
990
+ }
991
+ }
992
+ }
993
+ else {
994
+ log(`could not read the change to scan it for secrets (${own.why}) — pushing without a scan, and the result reports none`);
995
+ }
390
996
  await api.event(job.runId, 'pushing', { branch });
391
997
  const gitCred = job.repo ? await api.gitCredential(job.runId) : null;
392
998
  if (gitCred)
393
999
  log(`using a FireFunc-issued git credential for ${gitCred.repo}`);
394
- const staged = await execOut('git', [
1000
+ const pushedCommits = await execOut('git', [
395
1001
  '-C',
396
1002
  worktree,
397
- 'show',
1003
+ '--no-replace-objects',
1004
+ '-c',
1005
+ 'core.quotepath=off',
1006
+ 'log',
398
1007
  '--name-only',
399
1008
  '--format=',
400
- 'HEAD',
1009
+ '--no-renames',
1010
+ '--diff-filter=d',
1011
+ `${continuesBranch ? `origin/${branch}` : `origin/${base}`}..${scannedTip ?? `refs/heads/${branch}`}`,
401
1012
  ]);
402
- const leaked = staged
1013
+ const staged = [
1014
+ await execOut('git', [
1015
+ '-C',
1016
+ worktree,
1017
+ 'show',
1018
+ '--name-only',
1019
+ '--format=',
1020
+ '--diff-filter=d',
1021
+ 'HEAD',
1022
+ ]),
1023
+ pushedCommits,
1024
+ ].join('\n');
1025
+ const mcpStaged = mcp?.configPath
1026
+ ? relative(worktree, mcp.configPath).split(sep).join('/')
1027
+ : null;
1028
+ const stagedPaths = staged
403
1029
  .split('\n')
404
1030
  .map((l) => l.trim())
405
- .filter((l) => l === '.env' || l.endsWith('/.env'));
1031
+ .filter(Boolean);
1032
+ const leaked = stagedPaths.filter((l) => l === '.env' || l.endsWith('/.env') || (mcpStaged !== null && l === mcpStaged));
406
1033
  if (leaked.length > 0) {
407
1034
  return fail(`refusing to push: the commit contains ${leaked.join(', ')}, which can hold live credentials. ` +
408
1035
  `This is a FireFunc bug — please report it. Nothing was pushed.`);
409
1036
  }
410
- const push = gitCred
411
- ? await pushBranch(worktree, branch, gitCred.repo, gitCred)
412
- : await exec('git', ['-C', worktree, 'push', '--force-with-lease', 'origin', `${branch}:${branch}`], { timeoutMs: 120_000 });
1037
+ const skillLeaked = writtenSkillPaths(stagedPaths, writtenSkills);
1038
+ if (skillLeaked.length > 0) {
1039
+ return fail(`refusing to push: the agent added ${skillLeaked.join(', ')} to its commit — a skill ` +
1040
+ `FireFunc writes into the checkout for this run only and never commits. Nothing was ` +
1041
+ `pushed. Fix: tell the agent not to stage or commit anything under ` +
1042
+ `${skillLeaked[0].split('/').slice(0, -1).join('/')} (check its instruction and ` +
1043
+ `its skills for "git add -f" or "commit everything"), then re-run the task.`);
1044
+ }
1045
+ const pushFrom = worktree;
1046
+ const pushOnce = async () => gitCred
1047
+ ? pushBranch(pushFrom, branch, gitCred.repo, gitCred, { force: !continuesBranch })
1048
+ : exec('git', [
1049
+ '-C',
1050
+ pushFrom,
1051
+ 'push',
1052
+ ...pushFlags(!continuesBranch),
1053
+ 'origin',
1054
+ `${branch}:${branch}`,
1055
+ ], {
1056
+ timeoutMs: 120_000,
1057
+ });
1058
+ let push = await pushOnce();
1059
+ for (let tries = 0; tries < 3 && push.code !== 0 && isNetworkError(push.stderr); tries++) {
1060
+ log(`push failed because the network seems to be away — waiting for it (try ${tries + 1} of 3)`);
1061
+ const back = await waitForNetwork({ probe: () => api.probe(), maxWaitMs: 10 * 60_000, log });
1062
+ if (!back)
1063
+ break;
1064
+ push = await pushOnce();
1065
+ }
413
1066
  if (push.code !== 0) {
414
- return fail(`git push failed: ${redact(push.stderr, gitCred?.token).slice(0, 400)}`);
1067
+ const said = redact(push.stderr, gitCred?.token);
1068
+ log(`git push output for ${job.runId} (kept on this machine):\n${said.slice(-4000)}`);
1069
+ const refused = pushRefusal(said);
1070
+ return fail(refused
1071
+ ? `git push failed: ${oneLine(refused, 400)}`
1072
+ : `git push failed (exit ${push.code}); its output stayed on the machine — the runner’s log shows it.`);
1073
+ }
1074
+ if (secretScan && scannedTip && scanCoversPullRequest) {
1075
+ const pushedTip = await tipOf();
1076
+ if (pushedTip === scannedTip)
1077
+ secretScan = { ...secretScan, head: scannedTip };
1078
+ else
1079
+ 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`);
415
1080
  }
416
- const body = `Automated fix by FireFunc (self-hosted ${engineName} runner) for ${job.externalId ?? 'a reported bug'}.\n\nReview before merging.`;
1081
+ const body = pullRequestBody(kind, engineName, job.externalId, { continuesBranch });
417
1082
  if (gitCred) {
418
- const pr = await openDraftPr({
1083
+ const pr = await withNetworkRetry(() => openDraftPr({
419
1084
  repo: gitCred.repo,
420
1085
  head: branch,
421
1086
  base,
422
1087
  title,
423
1088
  body,
424
1089
  cred: gitCred,
1090
+ }), {
1091
+ label: `pull request for ${job.runId}`,
1092
+ maxWaitMs: 10 * 60_000,
1093
+ probe: () => api.probe(),
1094
+ log,
425
1095
  });
426
1096
  if (!('error' in pr)) {
427
1097
  await api.event(job.runId, 'pr_opened', { url: pr.url, branch });
@@ -435,6 +1105,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
435
1105
  branch,
436
1106
  summary: title,
437
1107
  },
1108
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
438
1109
  });
439
1110
  }
440
1111
  const why = redact(pr.error, gitCred.token);
@@ -442,19 +1113,35 @@ export async function runJob(job, cfg, api, viewer, opts) {
442
1113
  return fail(why);
443
1114
  log(`could not open the PR as FireFunc (${why}); falling back to gh`);
444
1115
  }
445
- const create = await exec('gh', [
446
- 'pr',
447
- 'create',
448
- '--draft',
449
- '--head',
450
- branch,
451
- '--base',
452
- base,
453
- '--title',
454
- title,
455
- '--body',
456
- body,
457
- ], { cwd: worktree, timeoutMs: 60_000 });
1116
+ const createCwd = worktree;
1117
+ const create = await withNetworkRetry(async () => {
1118
+ const r = await exec('gh', [
1119
+ 'pr',
1120
+ 'create',
1121
+ '--draft',
1122
+ '--head',
1123
+ branch,
1124
+ '--base',
1125
+ base,
1126
+ '--title',
1127
+ title,
1128
+ '--body',
1129
+ body,
1130
+ ], { cwd: createCwd, timeoutMs: 60_000 });
1131
+ if (r.code !== 0 && networkFailureHint(`${r.stdout}\n${r.stderr}`)) {
1132
+ throw new NetworkGoneError(r.stderr.trim() || 'gh pr create failed');
1133
+ }
1134
+ return r;
1135
+ }, {
1136
+ label: `pull request for ${job.runId} (gh)`,
1137
+ maxWaitMs: 10 * 60_000,
1138
+ probe: () => api.probe(),
1139
+ log,
1140
+ }).catch((err) => ({
1141
+ code: 1,
1142
+ stdout: '',
1143
+ stderr: err instanceof Error ? err.message : String(err),
1144
+ }));
458
1145
  const wt = worktree;
459
1146
  const viewPr = async (b) => {
460
1147
  const out = await execOut('gh', ['pr', 'view', b, '--json', 'url,number'], wt);
@@ -480,13 +1167,19 @@ export async function runJob(job, cfg, api, viewer, opts) {
480
1167
  if (m)
481
1168
  resolved = { url: m[0], number: Number(m[1]) };
482
1169
  }
483
- const url = resolved?.url ?? '';
484
- const number = resolved?.number;
1170
+ if (!resolved) {
1171
+ const why = (create.stderr || create.stdout).replace(/\s+/g, ' ').trim().slice(0, 400);
1172
+ return fail(`The branch ${branch} was pushed, but the pull request could not be created${why ? `: ${why}` : ''}. ` +
1173
+ `Open it from that branch on GitHub (FireFunc will link it to this task), or re-run.`);
1174
+ }
1175
+ const url = resolved.url;
1176
+ const number = resolved.number;
485
1177
  await api.event(job.runId, 'pr_opened', { url, branch });
486
- log(`opened PR for ${job.runId}: ${url || '(url unknown)'}`);
1178
+ log(`opened PR for ${job.runId}: ${url}`);
487
1179
  return report({
488
1180
  status: 'pr_opened',
489
1181
  pr: { repo: job.repo ?? undefined, number, url: url || undefined, branch, summary: title },
1182
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
490
1183
  });
491
1184
  }
492
1185
  catch (err) {
@@ -494,18 +1187,41 @@ export async function runJob(job, cfg, api, viewer, opts) {
494
1187
  return report({ status: 'failed', error: err.message.slice(0, 400) });
495
1188
  }
496
1189
  finally {
1190
+ mcp?.cleanup();
497
1191
  viewer?.end(job.runId, 'failed');
498
1192
  await Promise.all(bgProcs.map((p) => killProcessTree(p).catch(() => { })));
499
- if (worktree) {
1193
+ const reviewCopies = worktree ? reviewCopiesOf(worktree) : [];
1194
+ if (worktree || engineGroups.length > 0) {
1195
+ await killOrphans({
1196
+ roots: [worktree, attachDir, ...reviewCopies].filter((p) => !!p),
1197
+ ...(worktree ? { reviewCopiesOf: basename(worktree) } : {}),
1198
+ groups: engineGroups.map((g) => ({ ...g, leaderExited: true })),
1199
+ }, { log }).catch(() => { });
1200
+ }
1201
+ if (worktree && repoPath && !keepWorktree) {
1202
+ const checkout = repoPath;
500
1203
  await gitMutex
501
- .run(repoPath, () => exec('git', ['-C', repoPath, 'worktree', 'remove', '--force', worktree]))
1204
+ .run(checkout, () => exec('git', ['-C', checkout, 'worktree', 'remove', '--force', worktree]))
502
1205
  .catch(() => { });
1206
+ }
1207
+ if (worktree && !keepWorktree) {
503
1208
  try {
504
1209
  rmSync(worktree, { recursive: true, force: true });
505
1210
  }
506
1211
  catch {
507
1212
  }
508
1213
  }
1214
+ if (resumeCut && !keepWorktree)
1215
+ dropCut(rdir, resumeCut.workItemId);
1216
+ if (!keepWorktree) {
1217
+ for (const copy of reviewCopies) {
1218
+ try {
1219
+ rmSync(copy, { recursive: true, force: true });
1220
+ }
1221
+ catch {
1222
+ }
1223
+ }
1224
+ }
509
1225
  if (attachDir) {
510
1226
  try {
511
1227
  rmSync(attachDir, { recursive: true, force: true });