@firefunc-agent/runner 0.7.0 → 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 +476 -83
  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 +11 -1
  77. package/package.json +7 -4
  78. package/skill/firefunc/SKILL.md +173 -0
package/dist/job.js CHANGED
@@ -1,11 +1,20 @@
1
- import { mkdtempSync, rmSync, existsSync, mkdirSync, writeFileSync, copyFileSync } from 'node:fs';
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
  }
@@ -13,9 +22,20 @@ const gitMutex = createKeyedMutex();
13
22
  function saveSessionLog(runId, stdout, stderr) {
14
23
  try {
15
24
  const dir = join(dirname(configPath()), 'logs');
16
- mkdirSync(dir, { recursive: true });
25
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
26
+ try {
27
+ chmodSync(dir, 0o700);
28
+ for (const f of readdirSync(dir)) {
29
+ if (f.endsWith('.log'))
30
+ chmodSync(join(dir, f), 0o600);
31
+ }
32
+ }
33
+ catch {
34
+ }
17
35
  const p = join(dir, `${runId}.log`);
18
- writeFileSync(p, `=== agent stdout ===\n${stdout}\n\n=== agent stderr ===\n${stderr}\n`);
36
+ writeFileSync(p, redact(`=== agent stdout ===\n${stdout}\n\n=== agent stderr ===\n${stderr}\n`), {
37
+ mode: 0o600,
38
+ });
19
39
  return p;
20
40
  }
21
41
  catch {
@@ -118,20 +138,91 @@ async function autoInstallDeps(worktree, env, timeoutMs) {
118
138
  if (!installed && dirs[0] !== '')
119
139
  log('auto-install: no package.json found — skipping');
120
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
+ }
121
177
  export async function runJob(job, cfg, api, viewer, opts) {
122
- const report = async (payload) => {
178
+ let secretScan;
179
+ const report = async (reported) => {
180
+ const payload = secretScan && !reported.secretScan ? { ...reported, secretScan } : reported;
123
181
  try {
124
- 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
+ });
125
188
  }
126
189
  catch (err) {
127
- 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
+ }
128
202
  }
129
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);
130
218
  const fail = (error) => {
131
219
  log(`job ${job.runId} FAILED — ${error.replace(/\s+/g, ' ').slice(0, 300)}`);
132
220
  return report({ status: 'failed', error });
133
221
  };
134
- 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);
135
226
  if (!repoPath && job.repo) {
136
227
  const cred = await api.gitCredential(job.runId);
137
228
  const dest = cloneDestination(job.repo, cfg);
@@ -151,7 +242,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
151
242
  }
152
243
  }
153
244
  }
154
- if (!repoPath) {
245
+ if (!repoPath && !toolsOnly) {
155
246
  log(`no local checkout for ${job.repo} and no credential to clone with`);
156
247
  return report({
157
248
  status: 'failed',
@@ -165,29 +256,61 @@ export async function runJob(job, cfg, api, viewer, opts) {
165
256
  const timeoutMs = (cfg.jobTimeoutMinutes ?? 20) * 60_000;
166
257
  let worktree = null;
167
258
  let attachDir = null;
259
+ let mcp = null;
168
260
  const bgProcs = [];
169
261
  viewer?.begin(job.runId, {
170
262
  title: job.title ?? job.externalId ?? undefined,
171
263
  repo: job.repo ?? undefined,
172
264
  });
265
+ let base = '';
173
266
  try {
174
- await api.event(job.runId, 'cloning', { repo: job.repo, branch });
175
- const prep = await gitMutex.run(repoPath, async () => {
176
- await exec('git', ['-C', repoPath, 'fetch', 'origin', '--quiet'], { timeoutMs: 120_000 });
177
- let b = cfg.baseBranch ?? '';
178
- if (!b) {
179
- const head = await execOut('git', ['-C', repoPath, 'symbolic-ref', 'refs/remotes/origin/HEAD'], repoPath);
180
- b = head ? head.replace('refs/remotes/origin/', '') : 'main';
181
- }
182
- await exec('git', ['-C', repoPath, 'worktree', 'prune']).catch(() => { });
183
- const wt = mkdtempSync(join(tmpdir(), 'firefunc-'));
184
- const result = await exec('git', ['-C', repoPath, 'worktree', 'add', '--force', '-B', branch, wt, `origin/${b}`], { timeoutMs: 120_000 });
185
- return { base: b, wt, add: result };
186
- });
187
- const base = prep.base;
188
- worktree = prep.wt;
189
- if (prep.add.code !== 0) {
190
- 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
+ }
191
314
  }
192
315
  const attachPaths = [];
193
316
  if (job.attachments?.length) {
@@ -220,17 +343,32 @@ export async function runJob(job, cfg, api, viewer, opts) {
220
343
  if (opts?.devServerPort && cfg.backgroundCommands?.length) {
221
344
  log(`session dev-server PORT=${opts.devServerPort} (parallel-safe)`);
222
345
  }
223
- if (cfg.envFile) {
346
+ if (cfg.envFile && !toolsOnly) {
347
+ try {
348
+ const gitDir = (await execOut('git', ['-C', worktree, 'rev-parse', '--git-common-dir'])).trim();
349
+ if (gitDir) {
350
+ const abs = gitDir.startsWith('/') ? gitDir : join(worktree, gitDir);
351
+ mkdirSync(join(abs, 'info'), { recursive: true });
352
+ appendFileSync(join(abs, 'info', 'exclude'), '\n# FireFunc: never commit the injected env file\n.env\n');
353
+ }
354
+ }
355
+ catch (e) {
356
+ log(`could not write git exclude for .env: ${e.message}`);
357
+ }
224
358
  try {
225
359
  copyFileSync(cfg.envFile, join(worktree, '.env'));
226
- log(`copied ${cfg.envFile} → worktree/.env`);
360
+ log(`copied ${cfg.envFile} → worktree/.env (excluded from commits)`);
227
361
  }
228
362
  catch (e) {
229
363
  log(`envFile copy failed (${cfg.envFile}): ${e.message}`);
230
364
  }
231
365
  }
366
+ if (!toolsOnly)
367
+ writeSkills(worktree, job, log);
232
368
  const setupMs = (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000;
233
- if (cfg.setupCommands?.length) {
369
+ if (toolsOnly) {
370
+ }
371
+ else if (cfg.setupCommands?.length) {
234
372
  for (const cmd of cfg.setupCommands) {
235
373
  log(`setup: ${cmd}`);
236
374
  const r = await exec(cmd, [], {
@@ -240,14 +378,18 @@ export async function runJob(job, cfg, api, viewer, opts) {
240
378
  shell: true,
241
379
  });
242
380
  if (r.code !== 0) {
243
- 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.');
244
386
  }
245
387
  }
246
388
  }
247
389
  else if (cfg.autoInstall ?? true) {
248
390
  await autoInstallDeps(worktree, runEnv, setupMs);
249
391
  }
250
- for (const cmd of cfg.backgroundCommands ?? []) {
392
+ for (const cmd of toolsOnly ? [] : (cfg.backgroundCommands ?? [])) {
251
393
  log(`starting background: ${cmd}`);
252
394
  bgProcs.push(spawnBackground(cmd, { cwd: worktree, env: runEnv }));
253
395
  }
@@ -261,51 +403,95 @@ export async function runJob(job, cfg, api, viewer, opts) {
261
403
  const tools = cfg.allowedTools ??
262
404
  'Read Edit Write Bash Glob Grep WebFetch WebSearch Task TodoWrite NotebookEdit';
263
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
+ };
264
435
  let inv;
265
436
  try {
266
- inv = adapter.buildInvocation({
267
- prompt,
268
- model,
269
- effort,
270
- ultracode,
271
- permissionMode: mode,
272
- allowedTools: tools,
273
- maxBudgetUsd: cfg.maxBudgetUsd,
274
- attachDir: attachDir ?? undefined,
275
- attachPaths,
276
- isWin,
277
- runEnv: stripForeignEngineCreds(runEnv, adapter.id),
278
- cfg,
279
- });
437
+ inv = adapter.buildInvocation(ctx);
280
438
  }
281
439
  catch (e) {
282
440
  return fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
283
441
  }
284
442
  const engineName = adapter.displayName;
285
- 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}`);
286
444
  log(`${engineName} auth: ${inv.authLogLine}`);
287
445
  const printer = cfg.quiet ? undefined : adapter.makeStreamPrinter();
288
- const onStdout = printer || viewer
289
- ? (chunk) => {
290
- printer?.(chunk);
291
- viewer?.push(job.runId, chunk);
292
- }
293
- : 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
+ };
294
456
  if (printer) {
295
457
  log(`── live ${engineName} session (shown here only — never sent to FireFunc) ──`);
296
458
  }
297
459
  const heartbeat = setInterval(() => void api.event(job.runId, 'heartbeat'), 5 * 60_000);
298
- const engineRun = await exec(inv.bin, inv.args, {
299
- cwd: worktree,
460
+ const engineCwd = worktree;
461
+ const runEngine = () => exec(inv.bin, inv.args, {
462
+ cwd: engineCwd,
300
463
  timeoutMs,
301
464
  env: inv.env,
302
465
  input: inv.stdinInput,
303
466
  shell: inv.shell,
304
467
  onStdout,
305
- }).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);
306
489
  viewer?.end(job.runId, engineRun.code === 0 ? 'done' : 'failed');
307
490
  if (printer)
308
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();
309
495
  const sessionLogPath = saveSessionLog(job.runId, engineRun.stdout, engineRun.stderr);
310
496
  const summary = adapter.summarize(engineRun.stdout);
311
497
  if (sessionLogPath)
@@ -332,12 +518,46 @@ export async function runJob(job, cfg, api, viewer, opts) {
332
518
  const hinted = scanHints();
333
519
  if (hinted)
334
520
  return report(hinted);
521
+ const why = summary ? null : errorLine(engineRun.stderr);
335
522
  return fail(summary
336
- ? `${engineName} exited abnormally (code ${engineRun.code}). Last message: ${summary.replace(/\s+/g, ' ').slice(0, 500)}`
337
- : `${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
+ });
338
549
  }
339
550
  const title = job.title ? `fix: ${job.title}` : `fix: ${job.externalId ?? 'FireFunc auto-fix'}`;
340
- await exec('git', ['-C', worktree, 'add', '-A']);
551
+ await exec('git', [
552
+ '-C',
553
+ worktree,
554
+ 'add',
555
+ '-A',
556
+ '--',
557
+ '.',
558
+ ':(exclude).env',
559
+ ':(exclude).claude/skills',
560
+ ]);
341
561
  const vsBase = await exec('git', [
342
562
  '-C',
343
563
  worktree,
@@ -354,7 +574,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
354
574
  return report({
355
575
  status: 'no_pr',
356
576
  error: summary
357
- ? `No code change made. ${engineName}: ${summary.replace(/\s+/g, ' ').slice(0, 800)}`
577
+ ? `No code change made. ${engineName}: ${oneLine(shareable(summary), 800)}`
358
578
  : `${engineName} made no changes (could not reproduce or fix).`,
359
579
  });
360
580
  }
@@ -365,25 +585,171 @@ export async function runJob(job, cfg, api, viewer, opts) {
365
585
  else {
366
586
  log(`agent already committed its changes for ${job.runId} — reconciling to a PR`);
367
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
+ }
368
663
  await api.event(job.runId, 'pushing', { branch });
369
664
  const gitCred = job.repo ? await api.gitCredential(job.runId) : null;
370
665
  if (gitCred)
371
666
  log(`using a FireFunc-issued git credential for ${gitCred.repo}`);
372
- const push = gitCred
373
- ? await pushBranch(worktree, branch, gitCred.repo, gitCred)
374
- : await exec('git', ['-C', worktree, 'push', '--force-with-lease', 'origin', `${branch}:${branch}`], { timeoutMs: 120_000 });
667
+ const pushedCommits = await execOut('git', [
668
+ '-C',
669
+ worktree,
670
+ '--no-replace-objects',
671
+ '-c',
672
+ 'core.quotepath=off',
673
+ 'log',
674
+ '--name-only',
675
+ '--format=',
676
+ '--no-renames',
677
+ '--diff-filter=d',
678
+ `${continuesBranch ? `origin/${branch}` : `origin/${base}`}..${scannedTip ?? `refs/heads/${branch}`}`,
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;
695
+ const leaked = staged
696
+ .split('\n')
697
+ .map((l) => l.trim())
698
+ .filter((l) => l === '.env' || l.endsWith('/.env') || (mcpStaged !== null && l === mcpStaged));
699
+ if (leaked.length > 0) {
700
+ return fail(`refusing to push: the commit contains ${leaked.join(', ')}, which can hold live credentials. ` +
701
+ `This is a FireFunc bug — please report it. Nothing was pushed.`);
702
+ }
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
+ }
375
724
  if (push.code !== 0) {
376
- 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`);
377
738
  }
378
739
  const body = `Automated fix by FireFunc (self-hosted ${engineName} runner) for ${job.externalId ?? 'a reported bug'}.\n\nReview before merging.`;
379
740
  if (gitCred) {
380
- const pr = await openDraftPr({
741
+ const pr = await withNetworkRetry(() => openDraftPr({
381
742
  repo: gitCred.repo,
382
743
  head: branch,
383
744
  base,
384
745
  title,
385
746
  body,
386
747
  cred: gitCred,
748
+ }), {
749
+ label: `pull request for ${job.runId}`,
750
+ maxWaitMs: 10 * 60_000,
751
+ probe: () => api.probe(),
752
+ log,
387
753
  });
388
754
  if (!('error' in pr)) {
389
755
  await api.event(job.runId, 'pr_opened', { url: pr.url, branch });
@@ -397,6 +763,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
397
763
  branch,
398
764
  summary: title,
399
765
  },
766
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
400
767
  });
401
768
  }
402
769
  const why = redact(pr.error, gitCred.token);
@@ -404,19 +771,35 @@ export async function runJob(job, cfg, api, viewer, opts) {
404
771
  return fail(why);
405
772
  log(`could not open the PR as FireFunc (${why}); falling back to gh`);
406
773
  }
407
- const create = await exec('gh', [
408
- 'pr',
409
- 'create',
410
- '--draft',
411
- '--head',
412
- branch,
413
- '--base',
414
- base,
415
- '--title',
416
- title,
417
- '--body',
418
- body,
419
- ], { 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
+ }));
420
803
  const wt = worktree;
421
804
  const viewPr = async (b) => {
422
805
  const out = await execOut('gh', ['pr', 'view', b, '--json', 'url,number'], wt);
@@ -442,13 +825,19 @@ export async function runJob(job, cfg, api, viewer, opts) {
442
825
  if (m)
443
826
  resolved = { url: m[0], number: Number(m[1]) };
444
827
  }
445
- const url = resolved?.url ?? '';
446
- 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;
447
835
  await api.event(job.runId, 'pr_opened', { url, branch });
448
- log(`opened PR for ${job.runId}: ${url || '(url unknown)'}`);
836
+ log(`opened PR for ${job.runId}: ${url}`);
449
837
  return report({
450
838
  status: 'pr_opened',
451
839
  pr: { repo: job.repo ?? undefined, number, url: url || undefined, branch, summary: title },
840
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
452
841
  });
453
842
  }
454
843
  catch (err) {
@@ -456,12 +845,16 @@ export async function runJob(job, cfg, api, viewer, opts) {
456
845
  return report({ status: 'failed', error: err.message.slice(0, 400) });
457
846
  }
458
847
  finally {
848
+ mcp?.cleanup();
459
849
  viewer?.end(job.runId, 'failed');
460
850
  await Promise.all(bgProcs.map((p) => killProcessTree(p).catch(() => { })));
461
- if (worktree) {
851
+ if (worktree && repoPath) {
852
+ const checkout = repoPath;
462
853
  await gitMutex
463
- .run(repoPath, () => exec('git', ['-C', repoPath, 'worktree', 'remove', '--force', worktree]))
854
+ .run(checkout, () => exec('git', ['-C', checkout, 'worktree', 'remove', '--force', worktree]))
464
855
  .catch(() => { });
856
+ }
857
+ if (worktree) {
465
858
  try {
466
859
  rmSync(worktree, { recursive: true, force: true });
467
860
  }