@firefunc-agent/runner 0.7.1 → 0.9.0

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 (78) hide show
  1. package/LICENSE +7 -3
  2. package/README.md +233 -3
  3. package/dist/activity.d.ts +29 -0
  4. package/dist/activity.js +209 -0
  5. package/dist/api.d.ts +45 -1
  6. package/dist/api.js +44 -2
  7. package/dist/brief.d.ts +6 -0
  8. package/dist/brief.js +257 -0
  9. package/dist/build-info.json +4 -0
  10. package/dist/cli.js +49 -0
  11. package/dist/config.d.ts +5 -0
  12. package/dist/config.js +3 -0
  13. package/dist/daemon.js +70 -2
  14. package/dist/engines/antigravity.d.ts +2 -0
  15. package/dist/engines/antigravity.js +102 -0
  16. package/dist/engines/claude-budget.d.ts +1 -1
  17. package/dist/engines/claude-budget.js +2 -72
  18. package/dist/engines/claude.js +10 -1
  19. package/dist/engines/codex.js +10 -3
  20. package/dist/engines/copilot.d.ts +2 -0
  21. package/dist/engines/copilot.js +117 -0
  22. package/dist/engines/cursor.js +4 -0
  23. package/dist/engines/gemini.js +6 -1
  24. package/dist/engines/index.d.ts +2 -0
  25. package/dist/engines/index.js +22 -4
  26. package/dist/engines/types.d.ts +2 -1
  27. package/dist/firefunc/agents.d.ts +2 -0
  28. package/dist/firefunc/agents.js +291 -0
  29. package/dist/firefunc/args.d.ts +18 -0
  30. package/dist/firefunc/args.js +82 -0
  31. package/dist/firefunc/auth.d.ts +21 -0
  32. package/dist/firefunc/auth.js +129 -0
  33. package/dist/firefunc/catalog.d.ts +10 -0
  34. package/dist/firefunc/catalog.js +201 -0
  35. package/dist/firefunc/cli.d.ts +2 -0
  36. package/dist/firefunc/cli.js +24 -0
  37. package/dist/firefunc/client.d.ts +35 -0
  38. package/dist/firefunc/client.js +174 -0
  39. package/dist/firefunc/command.d.ts +28 -0
  40. package/dist/firefunc/command.js +35 -0
  41. package/dist/firefunc/config.d.ts +29 -0
  42. package/dist/firefunc/config.js +111 -0
  43. package/dist/firefunc/io.d.ts +25 -0
  44. package/dist/firefunc/io.js +14 -0
  45. package/dist/firefunc/main.d.ts +4 -0
  46. package/dist/firefunc/main.js +221 -0
  47. package/dist/firefunc/output.d.ts +29 -0
  48. package/dist/firefunc/output.js +128 -0
  49. package/dist/firefunc/prompt.d.ts +14 -0
  50. package/dist/firefunc/prompt.js +58 -0
  51. package/dist/firefunc/skill.d.ts +3 -0
  52. package/dist/firefunc/skill.js +80 -0
  53. package/dist/firefunc/tasks.d.ts +2 -0
  54. package/dist/firefunc/tasks.js +279 -0
  55. package/dist/firefunc/version.d.ts +2 -0
  56. package/dist/firefunc/version.js +23 -0
  57. package/dist/git-auth.d.ts +4 -1
  58. package/dist/git-auth.js +6 -2
  59. package/dist/job.js +439 -84
  60. package/dist/keep-local.d.ts +7 -0
  61. package/dist/keep-local.js +484 -0
  62. package/dist/machine-logins.d.ts +19 -0
  63. package/dist/machine-logins.js +187 -0
  64. package/dist/mcp-login.d.ts +24 -0
  65. package/dist/mcp-login.js +993 -0
  66. package/dist/mcp.d.ts +60 -0
  67. package/dist/mcp.js +582 -0
  68. package/dist/network.d.ts +20 -0
  69. package/dist/network.js +76 -0
  70. package/dist/pending.d.ts +14 -0
  71. package/dist/pending.js +56 -0
  72. package/dist/secret-scan.d.ts +19 -0
  73. package/dist/secret-scan.js +161 -0
  74. package/dist/session-stream.d.ts +1 -0
  75. package/dist/session-stream.js +11 -1
  76. package/dist/viewer.js +7 -1
  77. package/package.json +8 -5
  78. package/skill/firefunc/SKILL.md +173 -0
package/dist/job.js CHANGED
@@ -1,11 +1,20 @@
1
1
  import { mkdtempSync, rmSync, existsSync, mkdirSync, writeFileSync, copyFileSync, appendFileSync, chmodSync, readdirSync, } from 'node:fs';
2
2
  import { tmpdir } from 'node:os';
3
- import { join, basename, dirname } from 'node:path';
3
+ import { join, basename, dirname, relative, sep } from 'node:path';
4
+ import { execSync } from 'node:child_process';
4
5
  import { exec, execOut, spawnBackground, killProcessTree } from './exec.js';
5
6
  import { configPath, loadConfig, saveConfig } from './config.js';
6
- import { cloneRepo, openDraftPr, pushBranch, redact } from './git-auth.js';
7
+ import { cloneRepo, openDraftPr, pushBranch, pushFlags, redact } from './git-auth.js';
8
+ import { createActivityReporter, redact as oneLine, stripWorktree } from './activity.js';
9
+ import { commandName, errorLine, pushRefusal, stripCode } from './keep-local.js';
10
+ import { FULL_SHA, changeReads, hardFirst, refusesPush, scanAddedLines, secretRefusal, uniqueHits, } from './secret-scan.js';
11
+ import { isNetworkError, networkFailureHint, waitForNetwork, withNetworkRetry } from './network.js';
12
+ import { savePendingResult } from './pending.js';
13
+ import { runnerDir } from './config.js';
14
+ import { makeStreamJsonParser } from './session-stream.js';
7
15
  import { createKeyedMutex } from './locks.js';
8
16
  import { getAdapter, stripForeignEngineCreds } from './engines/index.js';
17
+ import { mcpFormatForEngine, prepareMcp } from './mcp.js';
9
18
  function log(msg) {
10
19
  console.log(`[firefunc-runner] ${new Date().toISOString()} ${msg}`);
11
20
  }
@@ -129,20 +138,91 @@ async function autoInstallDeps(worktree, env, timeoutMs) {
129
138
  if (!installed && dirs[0] !== '')
130
139
  log('auto-install: no package.json found — skipping');
131
140
  }
141
+ function writeSkills(worktree, job, log) {
142
+ const skills = (job.skills ?? []).filter((s) => s && typeof s.slug === 'string' && typeof s.content === 'string');
143
+ if (skills.length === 0)
144
+ return;
145
+ try {
146
+ for (const s of skills) {
147
+ const slug = s.slug.replace(/[^a-z0-9-]/gi, '-').toLowerCase();
148
+ const dir = join(worktree, '.claude', 'skills', slug);
149
+ mkdirSync(dir, { recursive: true });
150
+ writeFileSync(join(dir, 'SKILL.md'), s.content);
151
+ }
152
+ try {
153
+ const gitDir = execSync('git rev-parse --git-common-dir', {
154
+ cwd: worktree,
155
+ encoding: 'utf8',
156
+ }).trim();
157
+ if (gitDir) {
158
+ const abs = gitDir.startsWith('/') ? gitDir : join(worktree, gitDir);
159
+ mkdirSync(join(abs, 'info'), { recursive: true });
160
+ appendFileSync(join(abs, 'info', 'exclude'), '\n# FireFunc: skills are written per run, never committed\n.claude/skills/\n');
161
+ }
162
+ }
163
+ catch {
164
+ }
165
+ log(`wrote ${skills.length} skill(s) into .claude/skills: ${skills.map((s) => s.slug).join(', ')}`);
166
+ }
167
+ catch (e) {
168
+ log(`could not write skills: ${e.message}`);
169
+ }
170
+ }
171
+ function resumeBrief(prompt) {
172
+ return ('Your previous session on this task was cut short by a network outage. The worktree ' +
173
+ 'still holds everything you did; look at `git status` and `git diff`, continue from ' +
174
+ 'there, and finish the task. The original brief follows.\n\n' +
175
+ prompt);
176
+ }
132
177
  export async function runJob(job, cfg, api, viewer, opts) {
133
- const report = async (payload) => {
178
+ let secretScan;
179
+ const report = async (reported) => {
180
+ const payload = secretScan && !reported.secretScan ? { ...reported, secretScan } : reported;
134
181
  try {
135
- await api.result(job.runId, payload);
182
+ await withNetworkRetry(() => api.result(job.runId, payload), {
183
+ label: `result for ${job.runId}`,
184
+ maxWaitMs: 10 * 60_000,
185
+ probe: () => api.probe(),
186
+ log,
187
+ });
136
188
  }
137
189
  catch (err) {
138
- log(`failed to report result for ${job.runId}: ${err.message}`);
190
+ if (isNetworkError(err)) {
191
+ try {
192
+ const file = savePendingResult(runnerDir(), job.runId, payload);
193
+ log(`FireFunc is still unreachable — kept the result for ${job.runId} at ${file}; it is delivered when the network is back`);
194
+ }
195
+ catch (e) {
196
+ log(`failed to keep the result for ${job.runId}: ${e.message}`);
197
+ }
198
+ }
199
+ else {
200
+ log(`failed to report result for ${job.runId}: ${err.message}`);
201
+ }
139
202
  }
140
203
  };
204
+ class NetworkGoneError extends Error {
205
+ constructor(detail) {
206
+ super(`fetch failed: ${detail}`);
207
+ this.name = 'NetworkGoneError';
208
+ }
209
+ }
210
+ const shareable = (text) => stripCode(worktree ? stripWorktree(text, worktree) : text);
211
+ const reportedSummary = (text) => shareable(text)
212
+ .replace(/\r\n?/g, '\n')
213
+ .replace(/[ \t]+/g, ' ')
214
+ .replace(/ +$/gm, '')
215
+ .replace(/\n{3,}/g, '\n\n')
216
+ .trim()
217
+ .slice(0, 4000);
141
218
  const fail = (error) => {
142
219
  log(`job ${job.runId} FAILED — ${error.replace(/\s+/g, ' ').slice(0, 300)}`);
143
220
  return report({ status: 'failed', error });
144
221
  };
145
- let repoPath = resolveRepoPath(job.repo, cfg);
222
+ const toolsOnly = !job.repo;
223
+ const continuesBranch = !toolsOnly && job.continuesBranch === true;
224
+ const review = !toolsOnly && job.review === true;
225
+ let repoPath = toolsOnly ? null : resolveRepoPath(job.repo, cfg);
146
226
  if (!repoPath && job.repo) {
147
227
  const cred = await api.gitCredential(job.runId);
148
228
  const dest = cloneDestination(job.repo, cfg);
@@ -162,7 +242,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
162
242
  }
163
243
  }
164
244
  }
165
- if (!repoPath) {
245
+ if (!repoPath && !toolsOnly) {
166
246
  log(`no local checkout for ${job.repo} and no credential to clone with`);
167
247
  return report({
168
248
  status: 'failed',
@@ -176,29 +256,61 @@ export async function runJob(job, cfg, api, viewer, opts) {
176
256
  const timeoutMs = (cfg.jobTimeoutMinutes ?? 20) * 60_000;
177
257
  let worktree = null;
178
258
  let attachDir = null;
259
+ let mcp = null;
179
260
  const bgProcs = [];
180
261
  viewer?.begin(job.runId, {
181
262
  title: job.title ?? job.externalId ?? undefined,
182
263
  repo: job.repo ?? undefined,
183
264
  });
265
+ let base = '';
184
266
  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)}`);
267
+ if (toolsOnly) {
268
+ worktree = mkdtempSync(join(tmpdir(), 'firefunc-tools-'));
269
+ writeSkills(worktree, job, log);
270
+ await exec('git', ['-C', worktree, 'init', '--quiet']);
271
+ log(`no repository for ${job.runId} — the agent works through its tools in ${worktree}`);
272
+ }
273
+ else {
274
+ await api.event(job.runId, 'cloning', { repo: job.repo, branch });
275
+ const checkout = repoPath;
276
+ const prep = await gitMutex.run(checkout, async () => {
277
+ await exec('git', ['-C', checkout, 'fetch', 'origin', '--quiet'], { timeoutMs: 120_000 });
278
+ let b = job.baseBranch ?? cfg.baseBranch ?? '';
279
+ if (!b) {
280
+ const head = await execOut('git', ['-C', checkout, 'symbolic-ref', 'refs/remotes/origin/HEAD'], checkout);
281
+ b = head ? head.replace('refs/remotes/origin/', '') : 'main';
282
+ }
283
+ await exec('git', ['-C', checkout, 'worktree', 'prune']).catch(() => { });
284
+ let startPoint = `origin/${b}`;
285
+ if (continuesBranch) {
286
+ const has = await exec('git', [
287
+ '-C',
288
+ checkout,
289
+ 'rev-parse',
290
+ '--verify',
291
+ '--quiet',
292
+ `refs/remotes/origin/${branch}`,
293
+ ]);
294
+ if (has.code !== 0)
295
+ return { base: b, wt: '', add: has, branchMissing: true };
296
+ startPoint = `origin/${branch}`;
297
+ }
298
+ const wt = mkdtempSync(join(tmpdir(), 'firefunc-'));
299
+ const result = await exec('git', ['-C', checkout, 'worktree', 'add', '--force', '-B', branch, wt, startPoint], { timeoutMs: 120_000 });
300
+ return { base: b, wt, add: result, branchMissing: false };
301
+ });
302
+ base = prep.base;
303
+ if (prep.branchMissing) {
304
+ 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 lives in the fork. Nothing was changed.`);
305
+ }
306
+ worktree = prep.wt;
307
+ if (prep.add.code !== 0) {
308
+ log(`git worktree add output for ${job.runId} (kept on this machine):\n${prep.add.stderr}`);
309
+ const said = pushRefusal(prep.add.stderr);
310
+ return fail(said
311
+ ? `git worktree add failed: ${oneLine(said, 400)}`
312
+ : `git worktree add failed (exit ${prep.add.code}); its output stayed on the machine — the runner’s log shows it.`);
313
+ }
202
314
  }
203
315
  const attachPaths = [];
204
316
  if (job.attachments?.length) {
@@ -231,9 +343,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
231
343
  if (opts?.devServerPort && cfg.backgroundCommands?.length) {
232
344
  log(`session dev-server PORT=${opts.devServerPort} (parallel-safe)`);
233
345
  }
234
- if (cfg.envFile) {
346
+ if (cfg.envFile && !toolsOnly) {
235
347
  try {
236
- const gitDir = (await execOut('git', ['-C', worktree, 'rev-parse', '--git-dir'])).trim();
348
+ const gitDir = (await execOut('git', ['-C', worktree, 'rev-parse', '--git-common-dir'])).trim();
237
349
  if (gitDir) {
238
350
  const abs = gitDir.startsWith('/') ? gitDir : join(worktree, gitDir);
239
351
  mkdirSync(join(abs, 'info'), { recursive: true });
@@ -251,8 +363,12 @@ export async function runJob(job, cfg, api, viewer, opts) {
251
363
  log(`envFile copy failed (${cfg.envFile}): ${e.message}`);
252
364
  }
253
365
  }
366
+ if (!toolsOnly)
367
+ writeSkills(worktree, job, log);
254
368
  const setupMs = (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000;
255
- if (cfg.setupCommands?.length) {
369
+ if (toolsOnly) {
370
+ }
371
+ else if (cfg.setupCommands?.length) {
256
372
  for (const cmd of cfg.setupCommands) {
257
373
  log(`setup: ${cmd}`);
258
374
  const r = await exec(cmd, [], {
@@ -262,14 +378,18 @@ export async function runJob(job, cfg, api, viewer, opts) {
262
378
  shell: true,
263
379
  });
264
380
  if (r.code !== 0) {
265
- return fail(`Setup command failed (exit ${r.code}): ${cmd}\n${r.stderr.slice(0, 400)}`);
381
+ log(`setup output for ${job.runId} (kept on this machine):\n${r.stderr.slice(-4000)}`);
382
+ const why = errorLine(r.stderr);
383
+ return fail(`Setup command failed (exit ${r.code}): ${commandName(cmd)}` +
384
+ `${why ? ` — ${oneLine(stripWorktree(why, worktree), 200)}` : ''}. ` +
385
+ '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
386
  }
267
387
  }
268
388
  }
269
389
  else if (cfg.autoInstall ?? true) {
270
390
  await autoInstallDeps(worktree, runEnv, setupMs);
271
391
  }
272
- for (const cmd of cfg.backgroundCommands ?? []) {
392
+ for (const cmd of toolsOnly ? [] : (cfg.backgroundCommands ?? [])) {
273
393
  log(`starting background: ${cmd}`);
274
394
  bgProcs.push(spawnBackground(cmd, { cwd: worktree, env: runEnv }));
275
395
  }
@@ -283,51 +403,95 @@ export async function runJob(job, cfg, api, viewer, opts) {
283
403
  const tools = cfg.allowedTools ??
284
404
  'Read Edit Write Bash Glob Grep WebFetch WebSearch Task TodoWrite NotebookEdit';
285
405
  const isWin = process.platform === 'win32';
406
+ if (job.mcpConfig != null) {
407
+ const format = mcpFormatForEngine(adapter.id);
408
+ if (format) {
409
+ mcp = await prepareMcp({
410
+ raw: job.mcpConfig,
411
+ worktree,
412
+ format,
413
+ runId: job.runId,
414
+ api,
415
+ log,
416
+ });
417
+ }
418
+ log(mcp ? `mcp: ${mcp.logLine}` : 'mcp: no server was injected for this run');
419
+ }
420
+ const ctx = {
421
+ prompt,
422
+ model,
423
+ effort,
424
+ ultracode,
425
+ permissionMode: mode,
426
+ allowedTools: tools,
427
+ maxBudgetUsd: cfg.maxBudgetUsd,
428
+ attachDir: attachDir ?? undefined,
429
+ attachPaths,
430
+ isWin,
431
+ runEnv: stripForeignEngineCreds(runEnv, adapter.id),
432
+ cfg,
433
+ ...(mcp ? { mcp } : {}),
434
+ };
286
435
  let inv;
287
436
  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
- });
437
+ inv = adapter.buildInvocation(ctx);
302
438
  }
303
439
  catch (e) {
304
440
  return fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
305
441
  }
306
442
  const engineName = adapter.displayName;
307
- log(`running ${inv.bin} (${engineName}) on ${job.repo} (${branch}) — model=${model ?? 'default'} effort=${effort ?? 'default'} mode=${mode}`);
443
+ log(`running ${inv.bin} (${engineName}) on ${toolsOnly ? 'no repository — tools only' : `${job.repo} (${branch})`} — model=${model ?? 'default'} effort=${effort ?? 'default'} mode=${mode}`);
308
444
  log(`${engineName} auth: ${inv.authLogLine}`);
309
445
  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;
446
+ const activity = createActivityReporter({
447
+ worktree,
448
+ post: (steps) => api.activity(job.runId, steps),
449
+ });
450
+ const activityParser = makeStreamJsonParser(activity.push);
451
+ const onStdout = (chunk) => {
452
+ printer?.(chunk);
453
+ viewer?.push(job.runId, chunk);
454
+ activityParser(chunk);
455
+ };
316
456
  if (printer) {
317
457
  log(`── live ${engineName} session (shown here only — never sent to FireFunc) ──`);
318
458
  }
319
459
  const heartbeat = setInterval(() => void api.event(job.runId, 'heartbeat'), 5 * 60_000);
320
- const engineRun = await exec(inv.bin, inv.args, {
321
- cwd: worktree,
460
+ const engineCwd = worktree;
461
+ const runEngine = () => exec(inv.bin, inv.args, {
462
+ cwd: engineCwd,
322
463
  timeoutMs,
323
464
  env: inv.env,
324
465
  input: inv.stdinInput,
325
466
  shell: inv.shell,
326
467
  onStdout,
327
- }).finally(() => clearInterval(heartbeat));
468
+ });
469
+ let engineRun = await runEngine();
470
+ for (let resumes = 0; resumes < 2 && engineRun.code !== 0; resumes++) {
471
+ const why = networkFailureHint(`${adapter.summarize(engineRun.stdout)}\n${engineRun.stderr.slice(-2000)}`);
472
+ if (!why)
473
+ break;
474
+ log(`${engineName} stopped because ${why} — waiting for the network before resuming (resume ${resumes + 1} of 2)`);
475
+ const back = await waitForNetwork({
476
+ probe: () => api.probe(),
477
+ maxWaitMs: 20 * 60_000,
478
+ log,
479
+ });
480
+ if (!back) {
481
+ log('the network did not come back within 20 minutes — giving up on this attempt');
482
+ break;
483
+ }
484
+ log(`the network is back — resuming ${engineName} in the same worktree`);
485
+ inv = adapter.buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt) });
486
+ engineRun = await runEngine();
487
+ }
488
+ clearInterval(heartbeat);
328
489
  viewer?.end(job.runId, engineRun.code === 0 ? 'done' : 'failed');
329
490
  if (printer)
330
491
  log(`── end ${engineName} session ──`);
492
+ await activity.flush();
493
+ log(`reported ${activity.sent} of ${activity.seen} step(s) to FireFunc — names and verbs only; the session stayed here`);
494
+ mcp?.cleanup();
331
495
  const sessionLogPath = saveSessionLog(job.runId, engineRun.stdout, engineRun.stderr);
332
496
  const summary = adapter.summarize(engineRun.stdout);
333
497
  if (sessionLogPath)
@@ -354,12 +518,46 @@ export async function runJob(job, cfg, api, viewer, opts) {
354
518
  const hinted = scanHints();
355
519
  if (hinted)
356
520
  return report(hinted);
521
+ const why = summary ? null : errorLine(engineRun.stderr);
357
522
  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)}`);
523
+ ? `${engineName} exited abnormally (code ${engineRun.code}). Last message: ${oneLine(shareable(summary), 500)}`
524
+ : `${engineName} exited abnormally (code ${engineRun.code})${why ? `: ${oneLine(stripWorktree(why, worktree), 200)}` : ''}. ` +
525
+ `Its output stayed on the machine${sessionLogPath ? ` — the session log is logs/${basename(sessionLogPath)} in the runner’s folder` : ''}.`);
526
+ }
527
+ if (review) {
528
+ const dirty = await exec('git', ['-C', worktree, 'status', '--porcelain']);
529
+ const left = dirty.stdout.split('\n').filter((l) => l.trim()).length;
530
+ if (left > 0) {
531
+ log(`review run ${job.runId}: ${left} changed path(s) in the checkout are discarded — a review pushes nothing`);
532
+ }
533
+ log(`review run ${job.runId} finished — reporting the agent's review`);
534
+ return report({
535
+ status: 'no_pr',
536
+ ...(summary
537
+ ? { summary: reportedSummary(summary) }
538
+ : { error: `${engineName} finished without saying what it found.` }),
539
+ });
540
+ }
541
+ if (toolsOnly) {
542
+ log(`tools-only run ${job.runId} finished — reporting the agent's summary`);
543
+ return report({
544
+ status: 'no_pr',
545
+ ...(summary
546
+ ? { summary: reportedSummary(summary) }
547
+ : { error: `${engineName} finished without a summary of what it did.` }),
548
+ });
360
549
  }
361
550
  const title = job.title ? `fix: ${job.title}` : `fix: ${job.externalId ?? 'FireFunc auto-fix'}`;
362
- await exec('git', ['-C', worktree, 'add', '-A', '--', '.', ':(exclude).env']);
551
+ await exec('git', [
552
+ '-C',
553
+ worktree,
554
+ 'add',
555
+ '-A',
556
+ '--',
557
+ '.',
558
+ ':(exclude).env',
559
+ ':(exclude).claude/skills',
560
+ ]);
363
561
  const vsBase = await exec('git', [
364
562
  '-C',
365
563
  worktree,
@@ -376,7 +574,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
376
574
  return report({
377
575
  status: 'no_pr',
378
576
  error: summary
379
- ? `No code change made. ${engineName}: ${summary.replace(/\s+/g, ' ').slice(0, 800)}`
577
+ ? `No code change made. ${engineName}: ${oneLine(shareable(summary), 800)}`
380
578
  : `${engineName} made no changes (could not reproduce or fix).`,
381
579
  });
382
580
  }
@@ -387,41 +585,171 @@ export async function runJob(job, cfg, api, viewer, opts) {
387
585
  else {
388
586
  log(`agent already committed its changes for ${job.runId} — reconciling to a PR`);
389
587
  }
588
+ const scanIn = worktree;
589
+ const tipOf = async () => {
590
+ const r = await exec('git', ['-C', scanIn, 'rev-parse', '--verify', '--quiet', `refs/heads/${branch}^{commit}`], { timeoutMs: 30_000 }).catch(() => null);
591
+ const sha = r?.code === 0 ? r.stdout.trim() : '';
592
+ return FULL_SHA.test(sha) ? sha : null;
593
+ };
594
+ const scannedTip = await tipOf();
595
+ const readChange = (args, env) => exec('git', ['-C', scanIn, ...args], { timeoutMs: 120_000, env }).catch((e) => ({
596
+ code: 1,
597
+ stdout: '',
598
+ stderr: e.message,
599
+ }));
600
+ const scanSince = async (from) => {
601
+ const reads = changeReads(from, branch, scannedTip ?? undefined);
602
+ const whole = await readChange(reads.whole, reads.env);
603
+ const commits = whole.code === 0 ? await readChange(reads.commits, reads.env) : whole;
604
+ if (whole.code !== 0 || commits.code !== 0) {
605
+ const failed = whole.code !== 0 ? whole : commits;
606
+ return {
607
+ hits: null,
608
+ why: `git exit ${failed.code}: ${failed.stderr.trim().slice(0, 200)}`,
609
+ };
610
+ }
611
+ return {
612
+ hits: uniqueHits([...scanAddedLines(whole.stdout), ...scanAddedLines(commits.stdout)]),
613
+ };
614
+ };
615
+ const found = (hits, n = 5) => hits
616
+ .slice(0, n)
617
+ .map((h) => `${h.kind} at ${h.path}:${h.line}`)
618
+ .join(', ');
619
+ const asReported = (hits) => ({
620
+ scanned: true,
621
+ hits: hits.slice(0, 100).map((h) => ({ ...h, path: h.path.slice(0, 512) })),
622
+ });
623
+ let scanCoversPullRequest = false;
624
+ const own = await scanSince(continuesBranch ? `origin/${branch}` : `origin/${base}`);
625
+ if (own.hits) {
626
+ const added = hardFirst(own.hits);
627
+ secretScan = asReported(added);
628
+ if (added.some(refusesPush)) {
629
+ log(`secret scan for ${job.runId}: ${added.length} finding(s) — ${found(added)} — refusing to push`);
630
+ return fail(secretRefusal(added, branch));
631
+ }
632
+ if (added.length > 0) {
633
+ log(`secret scan for ${job.runId}: ${added.length} looser match(es) — ${found(added)} — pushing; ` +
634
+ 'the result reports them, and FireFunc does not auto-merge a pull request with a finding');
635
+ }
636
+ else {
637
+ log(`secret scan for ${job.runId}: nothing found in what this push adds`);
638
+ }
639
+ if (!continuesBranch) {
640
+ scanCoversPullRequest = true;
641
+ }
642
+ else {
643
+ const whole = await scanSince(`origin/${base}`);
644
+ if (whole.hits) {
645
+ const all = hardFirst(uniqueHits([...added, ...whole.hits]));
646
+ secretScan = asReported(all);
647
+ scanCoversPullRequest = true;
648
+ const before = all.length - added.length;
649
+ if (before > 0) {
650
+ log(`secret scan for ${job.runId}: the pull request already holds ${before} finding(s) from commits pushed before this run — ` +
651
+ 'they are on GitHub already, so the push goes on; the result reports them, and FireFunc does not auto-merge the pull request');
652
+ }
653
+ }
654
+ else {
655
+ log(`could not read the pull request from origin/${base} to scan it whole (${whole.why}) — ` +
656
+ 'the result reports what this run adds, without the commit it covers, so FireFunc does not auto-merge it');
657
+ }
658
+ }
659
+ }
660
+ else {
661
+ log(`could not read the change to scan it for secrets (${own.why}) — pushing without a scan, and the result reports none`);
662
+ }
390
663
  await api.event(job.runId, 'pushing', { branch });
391
664
  const gitCred = job.repo ? await api.gitCredential(job.runId) : null;
392
665
  if (gitCred)
393
666
  log(`using a FireFunc-issued git credential for ${gitCred.repo}`);
394
- const staged = await execOut('git', [
667
+ const pushedCommits = await execOut('git', [
395
668
  '-C',
396
669
  worktree,
397
- 'show',
670
+ '--no-replace-objects',
671
+ '-c',
672
+ 'core.quotepath=off',
673
+ 'log',
398
674
  '--name-only',
399
675
  '--format=',
400
- 'HEAD',
676
+ '--no-renames',
677
+ '--diff-filter=d',
678
+ `${continuesBranch ? `origin/${branch}` : `origin/${base}`}..${scannedTip ?? `refs/heads/${branch}`}`,
401
679
  ]);
680
+ const staged = [
681
+ await execOut('git', [
682
+ '-C',
683
+ worktree,
684
+ 'show',
685
+ '--name-only',
686
+ '--format=',
687
+ '--diff-filter=d',
688
+ 'HEAD',
689
+ ]),
690
+ pushedCommits,
691
+ ].join('\n');
692
+ const mcpStaged = mcp?.configPath
693
+ ? relative(worktree, mcp.configPath).split(sep).join('/')
694
+ : null;
402
695
  const leaked = staged
403
696
  .split('\n')
404
697
  .map((l) => l.trim())
405
- .filter((l) => l === '.env' || l.endsWith('/.env'));
698
+ .filter((l) => l === '.env' || l.endsWith('/.env') || (mcpStaged !== null && l === mcpStaged));
406
699
  if (leaked.length > 0) {
407
700
  return fail(`refusing to push: the commit contains ${leaked.join(', ')}, which can hold live credentials. ` +
408
701
  `This is a FireFunc bug — please report it. Nothing was pushed.`);
409
702
  }
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 });
703
+ const pushFrom = worktree;
704
+ const pushOnce = async () => gitCred
705
+ ? pushBranch(pushFrom, branch, gitCred.repo, gitCred, { force: !continuesBranch })
706
+ : exec('git', [
707
+ '-C',
708
+ pushFrom,
709
+ 'push',
710
+ ...pushFlags(!continuesBranch),
711
+ 'origin',
712
+ `${branch}:${branch}`,
713
+ ], {
714
+ timeoutMs: 120_000,
715
+ });
716
+ let push = await pushOnce();
717
+ for (let tries = 0; tries < 3 && push.code !== 0 && isNetworkError(push.stderr); tries++) {
718
+ log(`push failed because the network seems to be away — waiting for it (try ${tries + 1} of 3)`);
719
+ const back = await waitForNetwork({ probe: () => api.probe(), maxWaitMs: 10 * 60_000, log });
720
+ if (!back)
721
+ break;
722
+ push = await pushOnce();
723
+ }
413
724
  if (push.code !== 0) {
414
- return fail(`git push failed: ${redact(push.stderr, gitCred?.token).slice(0, 400)}`);
725
+ const said = redact(push.stderr, gitCred?.token);
726
+ log(`git push output for ${job.runId} (kept on this machine):\n${said.slice(-4000)}`);
727
+ const refused = pushRefusal(said);
728
+ return fail(refused
729
+ ? `git push failed: ${oneLine(refused, 400)}`
730
+ : `git push failed (exit ${push.code}); its output stayed on the machine — the runner’s log shows it.`);
731
+ }
732
+ if (secretScan && scannedTip && scanCoversPullRequest) {
733
+ const pushedTip = await tipOf();
734
+ if (pushedTip === scannedTip)
735
+ secretScan = { ...secretScan, head: scannedTip };
736
+ else
737
+ 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
738
  }
416
739
  const body = `Automated fix by FireFunc (self-hosted ${engineName} runner) for ${job.externalId ?? 'a reported bug'}.\n\nReview before merging.`;
417
740
  if (gitCred) {
418
- const pr = await openDraftPr({
741
+ const pr = await withNetworkRetry(() => openDraftPr({
419
742
  repo: gitCred.repo,
420
743
  head: branch,
421
744
  base,
422
745
  title,
423
746
  body,
424
747
  cred: gitCred,
748
+ }), {
749
+ label: `pull request for ${job.runId}`,
750
+ maxWaitMs: 10 * 60_000,
751
+ probe: () => api.probe(),
752
+ log,
425
753
  });
426
754
  if (!('error' in pr)) {
427
755
  await api.event(job.runId, 'pr_opened', { url: pr.url, branch });
@@ -435,6 +763,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
435
763
  branch,
436
764
  summary: title,
437
765
  },
766
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
438
767
  });
439
768
  }
440
769
  const why = redact(pr.error, gitCred.token);
@@ -442,19 +771,35 @@ export async function runJob(job, cfg, api, viewer, opts) {
442
771
  return fail(why);
443
772
  log(`could not open the PR as FireFunc (${why}); falling back to gh`);
444
773
  }
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 });
774
+ const createCwd = worktree;
775
+ const create = await withNetworkRetry(async () => {
776
+ const r = await exec('gh', [
777
+ 'pr',
778
+ 'create',
779
+ '--draft',
780
+ '--head',
781
+ branch,
782
+ '--base',
783
+ base,
784
+ '--title',
785
+ title,
786
+ '--body',
787
+ body,
788
+ ], { cwd: createCwd, timeoutMs: 60_000 });
789
+ if (r.code !== 0 && networkFailureHint(`${r.stdout}\n${r.stderr}`)) {
790
+ throw new NetworkGoneError(r.stderr.trim() || 'gh pr create failed');
791
+ }
792
+ return r;
793
+ }, {
794
+ label: `pull request for ${job.runId} (gh)`,
795
+ maxWaitMs: 10 * 60_000,
796
+ probe: () => api.probe(),
797
+ log,
798
+ }).catch((err) => ({
799
+ code: 1,
800
+ stdout: '',
801
+ stderr: err instanceof Error ? err.message : String(err),
802
+ }));
458
803
  const wt = worktree;
459
804
  const viewPr = async (b) => {
460
805
  const out = await execOut('gh', ['pr', 'view', b, '--json', 'url,number'], wt);
@@ -480,13 +825,19 @@ export async function runJob(job, cfg, api, viewer, opts) {
480
825
  if (m)
481
826
  resolved = { url: m[0], number: Number(m[1]) };
482
827
  }
483
- const url = resolved?.url ?? '';
484
- const number = resolved?.number;
828
+ if (!resolved) {
829
+ const why = (create.stderr || create.stdout).replace(/\s+/g, ' ').trim().slice(0, 400);
830
+ return fail(`The branch ${branch} was pushed, but the pull request could not be created${why ? `: ${why}` : ''}. ` +
831
+ `Open it from that branch on GitHub (FireFunc will link it to this task), or re-run.`);
832
+ }
833
+ const url = resolved.url;
834
+ const number = resolved.number;
485
835
  await api.event(job.runId, 'pr_opened', { url, branch });
486
- log(`opened PR for ${job.runId}: ${url || '(url unknown)'}`);
836
+ log(`opened PR for ${job.runId}: ${url}`);
487
837
  return report({
488
838
  status: 'pr_opened',
489
839
  pr: { repo: job.repo ?? undefined, number, url: url || undefined, branch, summary: title },
840
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
490
841
  });
491
842
  }
492
843
  catch (err) {
@@ -494,12 +845,16 @@ export async function runJob(job, cfg, api, viewer, opts) {
494
845
  return report({ status: 'failed', error: err.message.slice(0, 400) });
495
846
  }
496
847
  finally {
848
+ mcp?.cleanup();
497
849
  viewer?.end(job.runId, 'failed');
498
850
  await Promise.all(bgProcs.map((p) => killProcessTree(p).catch(() => { })));
499
- if (worktree) {
851
+ if (worktree && repoPath) {
852
+ const checkout = repoPath;
500
853
  await gitMutex
501
- .run(repoPath, () => exec('git', ['-C', repoPath, 'worktree', 'remove', '--force', worktree]))
854
+ .run(checkout, () => exec('git', ['-C', checkout, 'worktree', 'remove', '--force', worktree]))
502
855
  .catch(() => { });
856
+ }
857
+ if (worktree) {
503
858
  try {
504
859
  rmSync(worktree, { recursive: true, force: true });
505
860
  }