@firefunc-agent/runner 0.9.5 → 0.9.7

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.
package/dist/job.js CHANGED
@@ -15,7 +15,8 @@ import { endedBySignal, stoppedSentence } from './stopped.js';
15
15
  import { changeKind, pullRequestBody, pullRequestTitle } from './pr-title.js';
16
16
  import { savePendingResult } from './pending.js';
17
17
  import { runnerDir } from './config.js';
18
- import { attemptUsage, describeUsage } from './usage.js';
18
+ import { attemptUsage, combineUsage, describeUsage, } from './usage.js';
19
+ import { changesOf, dropKept, keepUntilFrom, keptDir, keptFor, reviseBrief, saveKept, } from './ask-first.js';
19
20
  import { makeStreamJsonParser } from './session-stream.js';
20
21
  import { writeSkills, writtenSkillPaths } from './skills.js';
21
22
  import { createKeyedMutex, ensureHeavyScript, heavyLockDir, withHeavyLock } from './locks.js';
@@ -23,6 +24,7 @@ import { getAdapter, stripForeignEngineCreds } from './engines/index.js';
23
24
  import { mcpFormatForEngine, prepareMcp } from './mcp.js';
24
25
  import { continueToFinishBrief, engineRules } from './brief.js';
25
26
  import { limitSentence } from './limit.js';
27
+ import { cannotRunUnattendedSentence, unattendedContext } from './unattended.js';
26
28
  import { cutFor, dropCut, keepUntil, promptHash, resumeAfterResetBrief, saveCut, } from './cut.js';
27
29
  import { liveWorktrees, updateHeld } from './held.js';
28
30
  import { killOrphans, reviewCopiesOf, trackEngineGroup, untrackEngineGroup } from './orphans.js';
@@ -230,6 +232,10 @@ export async function runJob(job, cfg, api, viewer, opts) {
230
232
  const toolsOnly = !job.repo;
231
233
  const continuesBranch = !toolsOnly && job.continuesBranch === true;
232
234
  const review = !toolsOnly && job.review === true;
235
+ const askFirst = !toolsOnly && !review && job.askFirst === true;
236
+ const step = askFirst ? (job.askFirstStep ?? null) : null;
237
+ const revising = step?.kind === 'revise' ? step : null;
238
+ const kept = step ? keptFor(rdir, job.runId) : null;
233
239
  const adapter = getAdapter(job.engine ?? cfg.engine);
234
240
  const spent = opts?.limits?.isLimited(adapter.id) ?? null;
235
241
  if (spent) {
@@ -241,6 +247,19 @@ export async function runJob(job, cfg, api, viewer, opts) {
241
247
  limit: { kind: 'plan', resetsAt: limit.resetsAt },
242
248
  });
243
249
  }
250
+ const unattended = adapter.unattendedBlock?.({
251
+ ...unattendedContext(cfg, job.permissionMode),
252
+ ...opts?.unattended,
253
+ });
254
+ if (unattended) {
255
+ const sentence = cannotRunUnattendedSentence(adapter.displayName, unattended);
256
+ log(`${job.runId}: ${sentence}`);
257
+ return report({
258
+ status: 'failed',
259
+ error: sentence,
260
+ limit: { kind: 'machine', detail: unattended.detail },
261
+ });
262
+ }
244
263
  let repoPath = toolsOnly ? null : resolveRepoPath(job.repo, cfg);
245
264
  if (!repoPath && job.repo) {
246
265
  const cred = await api.gitCredential(job.runId);
@@ -280,16 +299,41 @@ export async function runJob(job, cfg, api, viewer, opts) {
280
299
  : budget
281
300
  : (cfg.jobTimeoutMinutes ?? 20);
282
301
  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());
302
+ const cutMatch = step
303
+ ? null
304
+ : cutFor(rdir, {
305
+ workItemId: job.workItemId,
306
+ engine: adapter.id,
307
+ repo: job.repo ?? null,
308
+ branch: toolsOnly ? '' : branch,
309
+ review,
310
+ toolsOnly,
311
+ }, now().getTime());
291
312
  let resumeCut = null;
292
- if (cutMatch && 'resume' in cutMatch && adapter.resumesSessions) {
313
+ if (revising && kept) {
314
+ resumeCut = {
315
+ workItemId: kept.workItemId,
316
+ runId: kept.runId,
317
+ engine: kept.engine,
318
+ sessionId: kept.sessionId ?? '',
319
+ repo: kept.repo,
320
+ branch: kept.branch,
321
+ base: kept.base,
322
+ worktree: kept.worktree,
323
+ repoPath: kept.repoPath,
324
+ ...(kept.readHead ? { readHead: kept.readHead } : {}),
325
+ resetsAt: null,
326
+ cutAt: kept.keptAt,
327
+ keepUntil: kept.keepUntil,
328
+ promptHash: '',
329
+ review: false,
330
+ toolsOnly: false,
331
+ continuesBranch: kept.continuesBranch,
332
+ ...(kept.sessionReport ? { usage: kept.sessionReport } : {}),
333
+ ...(kept.writtenSkills ? { writtenSkills: kept.writtenSkills } : {}),
334
+ };
335
+ }
336
+ else if (cutMatch && 'resume' in cutMatch && adapter.resumesSessions) {
293
337
  resumeCut = cutMatch.resume;
294
338
  }
295
339
  else if (cutMatch) {
@@ -321,865 +365,976 @@ export async function runJob(job, cfg, api, viewer, opts) {
321
365
  title: job.title ?? job.externalId ?? undefined,
322
366
  repo: job.repo ?? undefined,
323
367
  });
324
- let base = '';
325
- try {
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.`);
368
+ const ship = async (s) => {
369
+ const { worktree, branch, base, title, kind, engineName, summary } = s;
370
+ const scanIn = worktree;
371
+ const tipOf = async () => {
372
+ const r = await exec('git', ['-C', scanIn, 'rev-parse', '--verify', '--quiet', `refs/heads/${branch}^{commit}`], { timeoutMs: 30_000 }).catch(() => null);
373
+ const sha = r?.code === 0 ? r.stdout.trim() : '';
374
+ return FULL_SHA.test(sha) ? sha : null;
375
+ };
376
+ const scannedTip = await tipOf();
377
+ const readChange = (args, env) => exec('git', ['-C', scanIn, ...args], { timeoutMs: 120_000, env }).catch((e) => ({
378
+ code: 1,
379
+ stdout: '',
380
+ stderr: e.message,
381
+ }));
382
+ const scanSince = async (from) => {
383
+ const reads = changeReads(from, branch, scannedTip ?? undefined);
384
+ const whole = await readChange(reads.whole, reads.env);
385
+ const commits = whole.code === 0 ? await readChange(reads.commits, reads.env) : whole;
386
+ if (whole.code !== 0 || commits.code !== 0) {
387
+ const failed = whole.code !== 0 ? whole : commits;
388
+ return {
389
+ hits: null,
390
+ why: `git exit ${failed.code}: ${failed.stderr.trim().slice(0, 200)}`,
391
+ };
404
392
  }
405
- worktree = prep.wt;
406
- updateHeld(rdir, job.runId, { worktree, repoPath: checkout });
407
- if (resumeCut) {
408
- readHead = resumeCut.readHead;
393
+ return {
394
+ hits: uniqueHits([...scanAddedLines(whole.stdout), ...scanAddedLines(commits.stdout)]),
395
+ };
396
+ };
397
+ const found = (hits, n = 5) => hits
398
+ .slice(0, n)
399
+ .map((h) => `${h.kind} at ${h.path}:${h.line}`)
400
+ .join(', ');
401
+ const asReported = (hits) => ({
402
+ scanned: true,
403
+ hits: hits.slice(0, 100).map((h) => ({ ...h, path: h.path.slice(0, 512) })),
404
+ });
405
+ let scanCoversPullRequest = false;
406
+ const own = await scanSince(continuesBranch ? `origin/${branch}` : `origin/${base}`);
407
+ if (own.hits) {
408
+ const added = hardFirst(own.hits);
409
+ secretScan = asReported(added);
410
+ if (added.some(refusesPush)) {
411
+ log(`secret scan for ${job.runId}: ${added.length} finding(s) — ${found(added)} — refusing to push`);
412
+ return fail(secretRefusal(added, branch));
409
413
  }
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;
414
+ if (added.length > 0) {
415
+ log(`secret scan for ${job.runId}: ${added.length} looser match(es) — ${found(added)} — pushing; ` +
416
+ 'the result reports them, and FireFunc does not auto-merge a pull request with a finding');
421
417
  }
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.`);
418
+ else {
419
+ log(`secret scan for ${job.runId}: nothing found in what this push adds`);
428
420
  }
429
- }
430
- const attachPaths = [];
431
- if (job.attachments?.length) {
432
- attachDir = mkdtempSync(join(tmpdir(), 'firefunc-attach-'));
433
- updateHeld(rdir, job.runId, { scratch: [attachDir] });
434
- mkdirSync(attachDir, { recursive: true });
435
- job.attachments.forEach((att, i) => {
436
- if (!att?.dataB64)
437
- return;
438
- try {
439
- const p = join(attachDir, safeAttachmentName(att.filename, i, att.contentType));
440
- writeFileSync(p, Buffer.from(att.dataB64, 'base64'));
441
- attachPaths.push(p);
421
+ if (!continuesBranch) {
422
+ scanCoversPullRequest = true;
423
+ }
424
+ else {
425
+ const whole = await scanSince(`origin/${base}`);
426
+ if (whole.hits) {
427
+ const all = hardFirst(uniqueHits([...added, ...whole.hits]));
428
+ secretScan = asReported(all);
429
+ scanCoversPullRequest = true;
430
+ const before = all.length - added.length;
431
+ if (before > 0) {
432
+ log(`secret scan for ${job.runId}: the pull request already holds ${before} finding(s) from commits pushed before this run — ` +
433
+ 'they are on GitHub already, so the push goes on; the result reports them, and FireFunc does not auto-merge the pull request');
434
+ }
442
435
  }
443
- catch {
436
+ else {
437
+ log(`could not read the pull request from origin/${base} to scan it whole (${whole.why}) — ` +
438
+ 'the result reports what this run adds, without the commit it covers, so FireFunc does not auto-merge it');
444
439
  }
445
- });
446
- if (attachPaths.length)
447
- log(`wrote ${attachPaths.length} attachment(s) for ${job.runId}`);
440
+ }
448
441
  }
449
- const attachNote = attachPaths.length
450
- ? `The reporter attached ${attachPaths.length} file(s). Read EACH one with the Read tool before forming your fix — they may be screenshots, designs, logs, stack traces, or repro data that show the bug or the intended result:\n${attachPaths
451
- .map((p) => `- ${p}`)
452
- .join('\n')}\n\n`
453
- : '';
454
- const runEnv = {
455
- ...cfg.claudeEnv,
456
- ...(cfg.claudeCodeOAuthToken ? { CLAUDE_CODE_OAUTH_TOKEN: cfg.claudeCodeOAuthToken } : {}),
457
- ...(opts?.devServerPort ? { PORT: String(opts.devServerPort) } : {}),
458
- };
459
- if (opts?.devServerPort && cfg.backgroundCommands?.length) {
460
- log(`session dev-server PORT=${opts.devServerPort} (parallel-safe)`);
442
+ else {
443
+ log(`could not read the change to scan it for secrets (${own.why}) — pushing without a scan, and the result reports none`);
461
444
  }
462
- if (cfg.envFile && !toolsOnly) {
463
- try {
464
- const gitDir = (await execOut('git', ['-C', worktree, 'rev-parse', '--git-common-dir'])).trim();
465
- if (gitDir) {
466
- const abs = gitDir.startsWith('/') ? gitDir : join(worktree, gitDir);
467
- mkdirSync(join(abs, 'info'), { recursive: true });
468
- appendFileSync(join(abs, 'info', 'exclude'), '\n# FireFunc: never commit the injected env file\n.env\n');
469
- }
470
- }
471
- catch (e) {
472
- log(`could not write git exclude for .env: ${e.message}`);
473
- }
474
- try {
475
- copyFileSync(cfg.envFile, join(worktree, '.env'));
476
- log(`copied ${cfg.envFile} → worktree/.env (excluded from commits)`);
445
+ if (s.keep) {
446
+ const changes = await changesOf(scanIn, continuesBranch ? `origin/${branch}` : `origin/${base}`, branch);
447
+ if (!changes || !scannedTip) {
448
+ return fail(`The change was made and committed on ${branch}, but the runner could not read what it holds to ask a person about it, so it was not kept. Nothing was pushed. Re-run the task.`);
477
449
  }
478
- catch (e) {
479
- log(`envFile copy failed (${cfg.envFile}): ${e.message}`);
450
+ const at = now();
451
+ const saved = saveKept(rdir, {
452
+ runId: job.runId,
453
+ workItemId: job.workItemId,
454
+ engine: adapter.id,
455
+ sessionId: s.keep.sessionId,
456
+ repo: job.repo ?? '',
457
+ branch,
458
+ base,
459
+ worktree,
460
+ repoPath: repoPath ?? null,
461
+ continuesBranch,
462
+ ...(readHead ? { readHead } : {}),
463
+ head: scannedTip,
464
+ round: s.keep.round,
465
+ title,
466
+ kind,
467
+ summary: summary ? reportedSummary(summary) : null,
468
+ keptAt: at.toISOString(),
469
+ keepUntil: keepUntilFrom(at.getTime()),
470
+ writtenSkills,
471
+ ...(usage ? { attemptUsage: usage } : {}),
472
+ ...(s.keep.sessionReport ? { sessionReport: s.keep.sessionReport } : {}),
473
+ });
474
+ if (!saved) {
475
+ return fail(`The change was made and committed on ${branch}, but the runner could not keep it for a person: it could not write ${keptDir(rdir)}. Nothing was pushed. Make that folder writable for the runner's user, then re-run the task.`);
480
476
  }
477
+ keepWorktree = true;
478
+ log(`Ask first: ${job.runId}'s change is committed on ${branch} and kept here — ${changes.filesChanged} file(s), +${changes.added} −${changes.removed}; nothing is pushed until a person approves it`);
479
+ return report({
480
+ status: 'awaiting_approval',
481
+ changes,
482
+ head: scannedTip,
483
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
484
+ });
481
485
  }
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();
497
- const setupMs = (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000;
498
- if (toolsOnly) {
499
- }
500
- else if (cfg.setupCommands?.length) {
501
- for (const cmd of cfg.setupCommands) {
502
- log(`setup: ${cmd}`);
503
- const setupCwd = worktree;
504
- const r = await heavily(() => exec(cmd, [], {
505
- cwd: setupCwd,
506
- env: runEnv,
507
- timeoutMs: setupMs,
508
- shell: true,
509
- }));
510
- if (r.code !== 0) {
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.');
520
- }
521
- }
522
- }
523
- else if (resumeCut) {
524
- }
525
- else if (cfg.autoInstall ?? true) {
526
- const installIn = worktree;
527
- await heavily(() => autoInstallDeps(installIn, runEnv, setupMs));
528
- }
529
- for (const cmd of toolsOnly ? [] : (cfg.backgroundCommands ?? [])) {
530
- log(`starting background: ${cmd}`);
531
- bgProcs.push(spawnBackground(cmd, { cwd: worktree, env: runEnv }));
532
- }
533
- await api.event(job.runId, 'fixing', { title: job.title });
534
- const mode = job.permissionMode ?? cfg.permissionMode ?? 'bypassPermissions';
535
- const model = job.model ?? cfg.model ?? null;
536
- const effort = job.effort ?? cfg.effort ?? null;
537
- const ultracode = effort === 'ultracode';
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';
539
- const rules = engineRules({ minutes: limitMinutes, heavy: heavyHelper !== null });
540
- const prompt = rules + observeNote + attachNote + (ultracode ? `ultracode\n\n${job.prompt}` : job.prompt);
541
- const tools = cfg.allowedTools ??
542
- 'Read Edit Write Bash Glob Grep WebFetch WebSearch Task TodoWrite NotebookEdit';
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');
486
+ await api.event(job.runId, 'pushing', { branch });
487
+ const gitCred = job.repo ? await api.gitCredential(job.runId) : null;
488
+ if (gitCred)
489
+ log(`using a FireFunc-issued git credential for ${gitCred.repo}`);
490
+ const pushedCommits = await execOut('git', [
491
+ '-C',
492
+ worktree,
493
+ '--no-replace-objects',
494
+ '-c',
495
+ 'core.quotepath=off',
496
+ 'log',
497
+ '--name-only',
498
+ '--format=',
499
+ '--no-renames',
500
+ '--diff-filter=d',
501
+ `${continuesBranch ? `origin/${branch}` : `origin/${base}`}..${scannedTip ?? `refs/heads/${branch}`}`,
502
+ ]);
503
+ const staged = [
504
+ await execOut('git', [
505
+ '-C',
506
+ worktree,
507
+ 'show',
508
+ '--name-only',
509
+ '--format=',
510
+ '--diff-filter=d',
511
+ 'HEAD',
512
+ ]),
513
+ pushedCommits,
514
+ ].join('\n');
515
+ const mcpStaged = mcp?.configPath
516
+ ? relative(worktree, mcp.configPath).split(sep).join('/')
517
+ : null;
518
+ const stagedPaths = staged
519
+ .split('\n')
520
+ .map((l) => l.trim())
521
+ .filter(Boolean);
522
+ const leaked = stagedPaths.filter((l) => l === '.env' || l.endsWith('/.env') || (mcpStaged !== null && l === mcpStaged));
523
+ if (leaked.length > 0) {
524
+ return fail(`refusing to push: the commit contains ${leaked.join(', ')}, which can hold live credentials. ` +
525
+ `This is a FireFunc bug — please report it. Nothing was pushed.`);
558
526
  }
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;
586
- let inv;
587
- try {
588
- inv = adapter.buildInvocation(firstCtx);
527
+ const skillLeaked = writtenSkillPaths(stagedPaths, writtenSkills);
528
+ if (skillLeaked.length > 0) {
529
+ return fail(`refusing to push: the agent added ${skillLeaked.join(', ')} to its commit — a skill ` +
530
+ `FireFunc writes into the checkout for this run only and never commits. Nothing was ` +
531
+ `pushed. Fix: tell the agent not to stage or commit anything under ` +
532
+ `${skillLeaked[0].split('/').slice(0, -1).join('/')} (check its instruction and ` +
533
+ `its skills for "git add -f" or "commit everything"), then re-run the task.`);
589
534
  }
590
- catch (e) {
591
- return fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
535
+ const pushFrom = worktree;
536
+ const pushOnce = async () => gitCred
537
+ ? pushBranch(pushFrom, branch, gitCred.repo, gitCred, { force: !continuesBranch })
538
+ : exec('git', [
539
+ '-C',
540
+ pushFrom,
541
+ 'push',
542
+ ...pushFlags(!continuesBranch),
543
+ 'origin',
544
+ `${branch}:${branch}`,
545
+ ], {
546
+ timeoutMs: 120_000,
547
+ });
548
+ let push = await pushOnce();
549
+ for (let tries = 0; tries < 3 && push.code !== 0 && isNetworkError(push.stderr); tries++) {
550
+ log(`push failed because the network seems to be away — waiting for it (try ${tries + 1} of 3)`);
551
+ const back = await waitForNetwork({ probe: () => api.probe(), maxWaitMs: 10 * 60_000, log });
552
+ if (!back)
553
+ break;
554
+ push = await pushOnce();
592
555
  }
593
- const engineName = adapter.displayName;
594
- log(`running ${inv.bin} (${engineName}) on ${toolsOnly ? 'no repository — tools only' : `${job.repo} (${branch})`} — model=${model ?? 'default'} effort=${effort ?? 'default'} mode=${mode}`);
595
- log(`${engineName} auth: ${inv.authLogLine}`);
596
- const printer = cfg.quiet ? undefined : adapter.makeStreamPrinter();
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
- };
608
- if (printer) {
609
- log(`── live ${engineName} session (shown here only — never sent to FireFunc) ──`);
556
+ if (push.code !== 0) {
557
+ const said = redact(push.stderr, gitCred?.token);
558
+ log(`git push output for ${job.runId} (kept on this machine):\n${said.slice(-4000)}`);
559
+ const refused = pushRefusal(said);
560
+ return fail(refused
561
+ ? `git push failed: ${oneLine(refused, 400)}`
562
+ : `git push failed (exit ${push.code}); its output stayed on the machine — the runner’s log shows it.`);
610
563
  }
611
- const heartbeat = setInterval(() => void api.event(job.runId, 'heartbeat'), 5 * 60_000);
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);
564
+ if (secretScan && scannedTip && scanCoversPullRequest) {
565
+ const pushedTip = await tipOf();
566
+ if (pushedTip === scannedTip)
567
+ secretScan = { ...secretScan, head: scannedTip };
568
+ else
569
+ 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`);
675
570
  }
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({
571
+ const body = pullRequestBody(kind, engineName, job.externalId, { continuesBranch });
572
+ if (gitCred) {
573
+ const pr = await withNetworkRetry(() => openDraftPr({
574
+ repo: gitCred.repo,
575
+ head: branch,
576
+ base,
577
+ title,
578
+ body,
579
+ cred: gitCred,
580
+ }), {
581
+ label: `pull request for ${job.runId}`,
582
+ maxWaitMs: 10 * 60_000,
688
583
  probe: () => api.probe(),
689
- maxWaitMs: 20 * 60_000,
690
584
  log,
691
585
  });
692
- if (!back) {
693
- log('the network did not come back within 20 minutes — giving up on this attempt');
694
- break;
586
+ if (!('error' in pr)) {
587
+ await api.event(job.runId, 'pr_opened', { url: pr.url, branch });
588
+ log(`opened PR for ${job.runId}: ${pr.url}`);
589
+ return report({
590
+ status: 'pr_opened',
591
+ pr: {
592
+ repo: job.repo ?? undefined,
593
+ number: pr.number,
594
+ url: pr.url,
595
+ branch,
596
+ summary: title,
597
+ },
598
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
599
+ });
695
600
  }
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);
601
+ const why = redact(pr.error, gitCred.token);
602
+ if (!(await hasGh(worktree)))
603
+ return fail(why);
604
+ log(`could not open the PR as FireFunc (${why}); falling back to gh`);
700
605
  }
701
- const openAtEnd = (stdout) => {
606
+ const createCwd = worktree;
607
+ const create = await withNetworkRetry(async () => {
608
+ const r = await exec('gh', [
609
+ 'pr',
610
+ 'create',
611
+ '--draft',
612
+ '--head',
613
+ branch,
614
+ '--base',
615
+ base,
616
+ '--title',
617
+ title,
618
+ '--body',
619
+ body,
620
+ ], { cwd: createCwd, timeoutMs: 60_000 });
621
+ if (r.code !== 0 && networkFailureHint(`${r.stdout}\n${r.stderr}`)) {
622
+ throw new NetworkGoneError(r.stderr.trim() || 'gh pr create failed');
623
+ }
624
+ return r;
625
+ }, {
626
+ label: `pull request for ${job.runId} (gh)`,
627
+ maxWaitMs: 10 * 60_000,
628
+ probe: () => api.probe(),
629
+ log,
630
+ }).catch((err) => ({
631
+ code: 1,
632
+ stdout: '',
633
+ stderr: err instanceof Error ? err.message : String(err),
634
+ }));
635
+ const wt = worktree;
636
+ const viewPr = async (b) => {
637
+ const out = await execOut('gh', ['pr', 'view', b, '--json', 'url,number'], wt);
702
638
  try {
703
- return adapter.openCommandsAtEnd?.(stdout) ?? [];
639
+ const j = JSON.parse(out);
640
+ if (typeof j.url === 'string' && /\/pull\/\d+/.test(j.url) && Number.isFinite(j.number)) {
641
+ return { url: j.url, number: Number(j.number) };
642
+ }
704
643
  }
705
644
  catch {
706
- return [];
707
645
  }
646
+ return null;
708
647
  };
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`);
648
+ const headBranch = (await execOut('git', ['rev-parse', '--abbrev-ref', 'HEAD'], wt)) || branch;
649
+ let resolved = null;
650
+ for (const b of [...new Set([headBranch, branch].filter(Boolean))]) {
651
+ resolved = await viewPr(b);
652
+ if (resolved)
653
+ break;
719
654
  }
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,
655
+ if (!resolved) {
656
+ const m = `${create.stdout}\n${create.stderr}`.match(/https?:\/\/\S*\/pull\/(\d+)/);
657
+ if (m)
658
+ resolved = { url: m[0], number: Number(m[1]) };
659
+ }
660
+ if (!resolved) {
661
+ const why = (create.stderr || create.stdout).replace(/\s+/g, ' ').trim().slice(0, 400);
662
+ return fail(`The branch ${branch} was pushed, but the pull request could not be created${why ? `: ${why}` : ''}. ` +
663
+ `Open it from that branch on GitHub (FireFunc will link it to this task), or re-run.`);
664
+ }
665
+ const url = resolved.url;
666
+ const number = resolved.number;
667
+ await api.event(job.runId, 'pr_opened', { url, branch });
668
+ log(`opened PR for ${job.runId}: ${url}`);
669
+ return report({
670
+ status: 'pr_opened',
671
+ pr: { repo: job.repo ?? undefined, number, url: url || undefined, branch, summary: title },
672
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
673
+ });
674
+ };
675
+ let base = '';
676
+ try {
677
+ if (step && (!kept || !existsSync(kept.worktree))) {
678
+ return fail('The change this attempt kept for approval is no longer on this machine (its kept folder was removed, or the runner was reinstalled), so it cannot be pushed. Re-run the task to make it again.');
679
+ }
680
+ if (step?.kind === 'publish' && kept) {
681
+ worktree = kept.worktree;
682
+ base = kept.base;
683
+ writtenSkills = kept.writtenSkills ?? { written: [], pathspecs: [] };
684
+ if (kept.readHead)
685
+ readHead = kept.readHead;
686
+ const tip = await execOut('git', [
687
+ '-C',
688
+ kept.worktree,
689
+ 'rev-parse',
690
+ '--verify',
691
+ '--quiet',
692
+ `refs/heads/${kept.branch}^{commit}`,
693
+ ]).catch(() => '');
694
+ if (tip.trim() !== kept.head) {
695
+ return fail(`The change kept for approval moved after it was approved: ${kept.branch} is at ${tip.trim().slice(0, 12) || 'nothing'}, not the approved ${kept.head.slice(0, 12)}. Nothing was pushed. Re-run the task.`);
696
+ }
697
+ log(`approved: pushing the change kept for ${job.runId} (${kept.branch}) and opening its pull request`);
698
+ return await ship({
699
+ worktree: kept.worktree,
700
+ branch: kept.branch,
701
+ base: kept.base,
702
+ title: kept.title,
703
+ kind: kept.kind,
704
+ engineName: adapter.displayName,
705
+ summary: kept.summary,
706
+ keep: null,
726
707
  });
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
708
  }
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)}`);
741
- viewer?.end(job.runId, engineRun.code === 0 ? 'done' : 'failed');
742
- if (printer)
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();
747
- const sessionLogPath = saveSessionLog(job.runId, engineRun.stdout, engineRun.stderr);
748
- const summary = adapter.summarize(engineRun.stdout);
749
- if (sessionLogPath)
750
- log(`${engineName} session saved → ${sessionLogPath}`);
751
- if (summary)
752
- log(`${engineName} said: ${summary.replace(/\s+/g, ' ').slice(0, 500)}`);
753
- if (engineRun.code === 124) {
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.`);
709
+ if (toolsOnly && resumeCut) {
710
+ worktree = resumeCut.worktree;
711
+ writtenSkills = { written: [], pathspecs: [] };
712
+ log(`continuing the session a plan limit cut for this task, in ${worktree}`);
757
713
  }
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,
714
+ else if (toolsOnly) {
715
+ worktree = mkdtempSync(join(tmpdir(), 'firefunc-tools-'));
716
+ updateHeld(rdir, job.runId, { scratch: [worktree] });
717
+ writeSkills(worktree, job.skills, log);
718
+ await exec('git', ['-C', worktree, 'init', '--quiet']);
719
+ log(`no repository for ${job.runId} — the agent works through its tools in ${worktree}`);
720
+ }
721
+ else {
722
+ await api.event(job.runId, 'cloning', { repo: job.repo, branch });
723
+ const checkout = repoPath;
724
+ const prep = await gitMutex.run(checkout, async () => {
725
+ await exec('git', ['-C', checkout, 'fetch', 'origin', '--quiet'], { timeoutMs: 120_000 });
726
+ if (resumeCut) {
727
+ const known = await exec('git', ['-C', resumeCut.worktree, 'rev-parse', '--git-dir']);
728
+ if (known.code === 0) {
729
+ return {
730
+ base: resumeCut.base,
731
+ wt: resumeCut.worktree,
732
+ add: { code: 0, stdout: '', stderr: '' },
733
+ branchMissing: false,
734
+ startPoint: '',
735
+ };
736
+ }
737
+ log(`the worktree the plan limit's cut session kept is no longer a worktree of ${job.repo} — starting over`);
738
+ dropCut(rdir, resumeCut.workItemId);
739
+ try {
740
+ rmSync(resumeCut.worktree, { recursive: true, force: true });
741
+ }
742
+ catch {
743
+ }
744
+ resumeCut = null;
745
+ }
746
+ let b = job.baseBranch ?? cfg.baseBranch ?? '';
747
+ if (!b) {
748
+ const head = await execOut('git', ['-C', checkout, 'symbolic-ref', 'refs/remotes/origin/HEAD'], checkout);
749
+ b = head ? head.replace('refs/remotes/origin/', '') : 'main';
750
+ }
751
+ await exec('git', ['-C', checkout, 'worktree', 'prune']).catch(() => { });
752
+ let startPoint = `origin/${b}`;
753
+ if (continuesBranch) {
754
+ const has = await exec('git', [
755
+ '-C',
756
+ checkout,
757
+ 'rev-parse',
758
+ '--verify',
759
+ '--quiet',
760
+ `refs/remotes/origin/${branch}`,
761
+ ]);
762
+ if (has.code !== 0) {
763
+ return { base: b, wt: '', add: has, branchMissing: true, startPoint };
764
+ }
765
+ startPoint = `origin/${branch}`;
766
+ }
767
+ const wt = mkdtempSync(join(tmpdir(), 'firefunc-'));
768
+ const add = () => exec('git', ['-C', checkout, 'worktree', 'add', '--force', '-B', branch, wt, startPoint], {
769
+ timeoutMs: 120_000,
787
770
  });
771
+ let result = await add();
772
+ const holder = result.code !== 0 ? staleHolder(result.stderr) : null;
773
+ if (holder) {
774
+ const live = new Set([...liveWorktrees(rdir)].map(canonicalPath));
775
+ if (!live.has(canonicalPath(holder))) {
776
+ log(`a worktree a stopped runner left holds ${branch} (${holder}) — removing it and trying again`);
777
+ await removeRunnerWorktree(checkout, holder, log);
778
+ result = await add();
779
+ }
780
+ }
781
+ return { base: b, wt, add: result, branchMissing: false, startPoint };
782
+ });
783
+ base = prep.base;
784
+ if (prep.branchMissing) {
785
+ return fail(`The pull request's branch "${branch}" is not in ${job.repo}, so it cannot be continued from this checkout — a pull request from a fork keeps its branch in the fork, and a merged or closed pull request's branch may have been deleted. Nothing was changed. ` +
786
+ `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.`);
788
787
  }
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 },
788
+ worktree = prep.wt;
789
+ updateHeld(rdir, job.runId, { worktree, repoPath: checkout });
790
+ if (resumeCut) {
791
+ readHead = resumeCut.readHead;
792
+ }
793
+ else if (prep.add.code === 0 && prep.startPoint) {
794
+ const sha = await execOut('git', [
795
+ '-C',
796
+ worktree,
797
+ 'rev-parse',
798
+ '--verify',
799
+ '--quiet',
800
+ `${prep.startPoint}^{commit}`,
801
+ ]).catch(() => '');
802
+ if (FULL_SHA.test(sha))
803
+ readHead = sha;
804
+ }
805
+ if (prep.add.code !== 0) {
806
+ log(`git worktree add output for ${job.runId} (kept on this machine):\n${prep.add.stderr}`);
807
+ const said = pushRefusal(prep.add.stderr);
808
+ return fail(said
809
+ ? `git worktree add failed: ${oneLine(said, 400)}`
810
+ : `git worktree add failed (exit ${prep.add.code}); its output stayed on the machine — the runner’s log shows it.`);
811
+ }
812
+ }
813
+ const attachPaths = [];
814
+ if (job.attachments?.length) {
815
+ attachDir = mkdtempSync(join(tmpdir(), 'firefunc-attach-'));
816
+ updateHeld(rdir, job.runId, { scratch: [attachDir] });
817
+ mkdirSync(attachDir, { recursive: true });
818
+ job.attachments.forEach((att, i) => {
819
+ if (!att?.dataB64)
820
+ return;
821
+ try {
822
+ const p = join(attachDir, safeAttachmentName(att.filename, i, att.contentType));
823
+ writeFileSync(p, Buffer.from(att.dataB64, 'base64'));
824
+ attachPaths.push(p);
825
+ }
826
+ catch {
827
+ }
797
828
  });
829
+ if (attachPaths.length)
830
+ log(`wrote ${attachPaths.length} attachment(s) for ${job.runId}`);
798
831
  }
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) };
832
+ const attachNote = attachPaths.length
833
+ ? `The reporter attached ${attachPaths.length} file(s). Read EACH one with the Read tool before forming your fix — they may be screenshots, designs, logs, stack traces, or repro data that show the bug or the intended result:\n${attachPaths
834
+ .map((p) => `- ${p}`)
835
+ .join('\n')}\n\n`
836
+ : '';
837
+ const runEnv = {
838
+ ...cfg.claudeEnv,
839
+ ...(cfg.claudeCodeOAuthToken ? { CLAUDE_CODE_OAUTH_TOKEN: cfg.claudeCodeOAuthToken } : {}),
840
+ ...(opts?.devServerPort ? { PORT: String(opts.devServerPort) } : {}),
804
841
  };
805
- const scanHints = () => {
806
- const declined = declinedHint();
807
- if (declined)
808
- return declined;
809
- const authMsg = adapter.authFailureHint(`${summary}\n${engineRun.stderr}`);
810
- if (authMsg) {
811
- log(`auth/billing failure for ${job.runId}: ${authMsg}`);
812
- return { status: 'failed', error: authMsg };
842
+ if (opts?.devServerPort && cfg.backgroundCommands?.length) {
843
+ log(`session dev-server PORT=${opts.devServerPort} (parallel-safe)`);
844
+ }
845
+ if (cfg.envFile && !toolsOnly) {
846
+ try {
847
+ const gitDir = (await execOut('git', ['-C', worktree, 'rev-parse', '--git-common-dir'])).trim();
848
+ if (gitDir) {
849
+ const abs = gitDir.startsWith('/') ? gitDir : join(worktree, gitDir);
850
+ mkdirSync(join(abs, 'info'), { recursive: true });
851
+ appendFileSync(join(abs, 'info', 'exclude'), '\n# FireFunc: never commit the injected env file\n.env\n');
852
+ }
813
853
  }
814
- const rateMsg = adapter.rateLimitHint(`${summary}\n${engineRun.stderr}`);
815
- if (rateMsg) {
816
- log(`rate limit for ${job.runId}: ${rateMsg}`);
817
- return { status: 'failed', error: rateMsg };
854
+ catch (e) {
855
+ log(`could not write git exclude for .env: ${e.message}`);
818
856
  }
819
- return null;
820
- };
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));
857
+ try {
858
+ copyFileSync(cfg.envFile, join(worktree, '.env'));
859
+ log(`copied ${cfg.envFile} → worktree/.env (excluded from commits)`);
860
+ }
861
+ catch (e) {
862
+ log(`envFile copy failed (${cfg.envFile}): ${e.message}`);
826
863
  }
827
- const hinted = scanHints();
828
- if (hinted)
829
- return report(hinted);
830
- const why = summary ? null : errorLine(engineRun.stderr);
831
- return fail(summary
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
864
  }
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));
865
+ if (resumeCut) {
866
+ writtenSkills = resumeCut.writtenSkills ?? { written: [], pathspecs: [] };
839
867
  }
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
- });
868
+ else if (!toolsOnly) {
869
+ writtenSkills = writeSkills(worktree, job.skills, log);
856
870
  }
871
+ const heavyLock = !toolsOnly && job.repo && cfg.heavyLock !== false ? heavyLockDir(rdir, job.repo) : null;
872
+ const heavyHelper = heavyLock ? ensureHeavyScript(rdir) : null;
873
+ const heavily = (fn) => heavyLock
874
+ ? withHeavyLock(heavyLock, fn, {
875
+ label: `setup of ${job.runId}`,
876
+ maxWaitMs: (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000,
877
+ onWait: (holder) => log(`another heavy command is running in ${job.repo}${holder ? ` (pid ${holder})` : ''} — setup waits for it`),
878
+ })
879
+ : fn();
880
+ const setupMs = (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000;
857
881
  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
882
  }
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
- ]);
880
- const vsBase = await exec('git', [
881
- '-C',
882
- worktree,
883
- 'diff',
884
- '--cached',
885
- '--quiet',
886
- `origin/${base}`,
887
- ]);
888
- if (vsBase.code === 0) {
889
- const hinted = scanHints();
890
- if (hinted)
891
- return report(hinted);
892
- log(`no changes produced for ${job.runId} — reporting no_pr`);
893
- return report({
894
- status: 'no_pr',
895
- error: summary
896
- ? `No code change made. ${engineName}: ${oneLine(shareable(summary), 800)}`
897
- : `${engineName} made no changes (could not reproduce or fix).`,
898
- ...(summary ? { summary: reportedSummary(summary) } : {}),
899
- });
883
+ else if (cfg.setupCommands?.length) {
884
+ for (const cmd of cfg.setupCommands) {
885
+ log(`setup: ${cmd}`);
886
+ const setupCwd = worktree;
887
+ const r = await heavily(() => exec(cmd, [], {
888
+ cwd: setupCwd,
889
+ env: runEnv,
890
+ timeoutMs: setupMs,
891
+ shell: true,
892
+ }));
893
+ if (r.code !== 0) {
894
+ log(`setup output for ${job.runId} (kept on this machine):\n${r.stderr.slice(-4000)}` +
895
+ `${r.stdout.trim() ? `\n--- stdout ---\n${r.stdout.slice(-2000)}` : ''}`);
896
+ const checkout = worktree;
897
+ const fold = (text) => foldHome(stripWorktree(text, checkout), homedir());
898
+ const why = setupReason(fold(r.stderr), fold(r.stdout));
899
+ const said = why ? oneLine(why, 200).replace(/[.\s]+$/, '') : '';
900
+ return fail(`Setup command failed (exit ${r.code}): ${setupCommandName(cmd)}` +
901
+ `${said ? ` — ${said}` : ''}. ` +
902
+ 'Its output stayed on the machine — the runner’s log shows it; fix the command or setupCommands in the runner config, then re-run.');
903
+ }
904
+ }
900
905
  }
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}"`);
914
- const uncommitted = await exec('git', ['-C', worktree, 'diff', '--cached', '--quiet', 'HEAD']);
915
- if (uncommitted.code !== 0) {
916
- await exec('git', ['-C', worktree, 'commit', '-m', title, '--quiet']);
906
+ else if (resumeCut) {
917
907
  }
918
- else {
919
- log(`agent already committed its changes for ${job.runId} — reconciling to a PR`);
908
+ else if (cfg.autoInstall ?? true) {
909
+ const installIn = worktree;
910
+ await heavily(() => autoInstallDeps(installIn, runEnv, setupMs));
920
911
  }
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
- };
912
+ for (const cmd of toolsOnly ? [] : (cfg.backgroundCommands ?? [])) {
913
+ log(`starting background: ${cmd}`);
914
+ bgProcs.push(spawnBackground(cmd, { cwd: worktree, env: runEnv }));
915
+ }
916
+ await api.event(job.runId, 'fixing', { title: job.title });
917
+ const mode = job.permissionMode ?? cfg.permissionMode ?? 'bypassPermissions';
918
+ const model = job.model ?? cfg.model ?? null;
919
+ const effort = job.effort ?? cfg.effort ?? null;
920
+ const ultracode = effort === 'ultracode';
921
+ const observeNote = 'Dev/observation tooling MAY be available here: the app may be runnable (setup ran), a dev server may be up, and AWS read creds / a staging URL / a test account may be in your environment. PREFER reproducing the reported symptom LIVE (run the app, curl the API, drive the UI) before reasoning statically, and re-observe after your change to confirm the fix. Treat any cloud/staging access as READ-ONLY.\n\n';
922
+ const rules = engineRules({ minutes: limitMinutes, heavy: heavyHelper !== null });
923
+ const prompt = rules + observeNote + attachNote + (ultracode ? `ultracode\n\n${job.prompt}` : job.prompt);
924
+ const tools = cfg.allowedTools ??
925
+ 'Read Edit Write Bash Glob Grep WebFetch WebSearch Task TodoWrite NotebookEdit';
926
+ const isWin = process.platform === 'win32';
927
+ if (job.mcpConfig != null) {
928
+ const format = mcpFormatForEngine(adapter.id);
929
+ if (format) {
930
+ mcp = await prepareMcp({
931
+ raw: job.mcpConfig,
932
+ worktree,
933
+ format,
934
+ runId: job.runId,
935
+ api,
936
+ log,
937
+ relay: cfg.mcpRelay !== false,
938
+ });
943
939
  }
944
- return {
945
- hits: uniqueHits([...scanAddedLines(whole.stdout), ...scanAddedLines(commits.stdout)]),
946
- };
940
+ log(mcp ? `mcp: ${mcp.logLine}` : 'mcp: no server was injected for this run');
941
+ }
942
+ const ctx = {
943
+ prompt,
944
+ model,
945
+ effort,
946
+ ultracode,
947
+ permissionMode: mode,
948
+ allowedTools: tools,
949
+ maxBudgetUsd: cfg.maxBudgetUsd,
950
+ attachDir: attachDir ?? undefined,
951
+ attachPaths,
952
+ isWin,
953
+ runEnv: {
954
+ ...stripForeignEngineCreds(runEnv, adapter.id),
955
+ ...(heavyHelper && heavyLock
956
+ ? { FIREFUNC_HEAVY: heavyHelper, FIREFUNC_HEAVY_LOCK: heavyLock }
957
+ : {}),
958
+ },
959
+ cfg,
960
+ ...(mcp ? { mcp } : {}),
947
961
  };
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) })),
962
+ const firstCtx = revising
963
+ ? resumeCut?.sessionId && adapter.resumesSessions
964
+ ? {
965
+ ...ctx,
966
+ resumeSessionId: resumeCut.sessionId,
967
+ prompt: reviseBrief(revising.note, revising.round),
968
+ }
969
+ : { ...ctx, prompt: `${reviseBrief(revising.note, revising.round)}\n\n${ctx.prompt}` }
970
+ : resumeCut
971
+ ? {
972
+ ...ctx,
973
+ resumeSessionId: resumeCut.sessionId,
974
+ prompt: resumeAfterResetBrief(prompt, promptHash(job.prompt) !== resumeCut.promptHash),
975
+ }
976
+ : ctx;
977
+ let inv;
978
+ try {
979
+ inv = adapter.buildInvocation(firstCtx);
980
+ }
981
+ catch (e) {
982
+ return fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
983
+ }
984
+ const engineName = adapter.displayName;
985
+ log(`running ${inv.bin} (${engineName}) on ${toolsOnly ? 'no repository — tools only' : `${job.repo} (${branch})`} — model=${model ?? 'default'} effort=${effort ?? 'default'} mode=${mode}`);
986
+ log(`${engineName} auth: ${inv.authLogLine}`);
987
+ const printer = cfg.quiet ? undefined : adapter.makeStreamPrinter();
988
+ const activity = createActivityReporter({
989
+ worktree,
990
+ post: (steps) => api.activity(job.runId, steps),
991
+ writeTools: new Set(mcp?.writeToolNames ?? []),
955
992
  });
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));
993
+ const activityParser = makeStreamJsonParser(activity.push, { toolResults: true });
994
+ const onStdout = (chunk) => {
995
+ printer?.(chunk);
996
+ viewer?.push(job.runId, chunk);
997
+ activityParser(chunk);
998
+ };
999
+ if (printer) {
1000
+ log(`── live ${engineName} session (shown here only — never sent to FireFunc) ──`);
1001
+ }
1002
+ const heartbeat = setInterval(() => void api.event(job.runId, 'heartbeat'), 5 * 60_000);
1003
+ const engineCwd = worktree;
1004
+ let engineMs = 0;
1005
+ const runEngine = async (limitMs = timeoutMs) => {
1006
+ let group = 0;
1007
+ const started = Date.now();
1008
+ try {
1009
+ return await exec(inv.bin, inv.args, {
1010
+ cwd: engineCwd,
1011
+ timeoutMs: limitMs,
1012
+ env: inv.env,
1013
+ input: inv.stdinInput,
1014
+ shell: inv.shell,
1015
+ onStdout,
1016
+ ownGroup: true,
1017
+ onSpawn: (pid) => {
1018
+ group = pid;
1019
+ engineGroups.push({ pgid: pid, startedAt: started });
1020
+ trackEngineGroup(pid);
1021
+ updateHeld(rdir, job.runId, { engineGroup: pid, engineStartedAt: started });
1022
+ },
1023
+ });
964
1024
  }
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');
1025
+ finally {
1026
+ if (group)
1027
+ untrackEngineGroup(group);
1028
+ engineMs += Date.now() - started;
968
1029
  }
969
- else {
970
- log(`secret scan for ${job.runId}: nothing found in what this push adds`);
1030
+ };
1031
+ const sessions = [];
1032
+ let lastReport = null;
1033
+ const meter = (stdout, continued = false) => {
1034
+ if (!adapter.meter)
1035
+ return;
1036
+ let u = null;
1037
+ try {
1038
+ u = adapter.meter(stdout);
971
1039
  }
972
- if (!continuesBranch) {
973
- scanCoversPullRequest = true;
1040
+ catch {
1041
+ u = null;
974
1042
  }
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
- }
1043
+ lastReport = u;
1044
+ sessions.push({ usage: u, session: adapter.sessionId?.(stdout) ?? null, continued });
1045
+ };
1046
+ const limitOf = (stdout) => {
1047
+ try {
1048
+ return adapter.planLimit?.(stdout, now()) ?? null;
991
1049
  }
1050
+ catch {
1051
+ return null;
1052
+ }
1053
+ };
1054
+ const refused = (stdout, stderr) => endedOnRefusal({
1055
+ ending: adapter.ending?.(stdout),
1056
+ summary: adapter.summarize(stdout),
1057
+ stderr,
1058
+ });
1059
+ let engineRun = await runEngine();
1060
+ meter(engineRun.stdout, false);
1061
+ if (resumeCut &&
1062
+ firstCtx.resumeSessionId &&
1063
+ engineRun.code !== 0 &&
1064
+ !adapter.sessionId?.(engineRun.stdout)) {
1065
+ log(`${engineName} could not continue the session a plan limit cut — starting a new session in the same worktree`);
1066
+ inv = adapter.buildInvocation({
1067
+ ...ctx,
1068
+ prompt: revising
1069
+ ? `${reviseBrief(revising.note, revising.round)}\n\n${ctx.prompt}`
1070
+ : resumeBrief(ctx.prompt, 'limit'),
1071
+ });
1072
+ engineRun = await runEngine();
1073
+ meter(engineRun.stdout, false);
992
1074
  }
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`);
1075
+ for (let resumes = 0; resumes < 2 && engineRun.code !== 0; resumes++) {
1076
+ if (limitOf(engineRun.stdout))
1077
+ break;
1078
+ if (refused(engineRun.stdout, engineRun.stderr))
1079
+ break;
1080
+ if (endedBySignal(engineRun.code))
1081
+ break;
1082
+ const why = networkFailureHint(`${adapter.summarize(engineRun.stdout)}\n${engineRun.stderr.slice(-2000)}`);
1083
+ if (!why)
1084
+ break;
1085
+ log(`${engineName} stopped because ${why} — waiting for the network before resuming (resume ${resumes + 1} of 2)`);
1086
+ const back = await waitForNetwork({
1087
+ probe: () => api.probe(),
1088
+ maxWaitMs: 20 * 60_000,
1089
+ log,
1090
+ });
1091
+ if (!back) {
1092
+ log('the network did not come back within 20 minutes — giving up on this attempt');
1093
+ break;
1094
+ }
1095
+ log(`the network is back — resuming ${engineName} in the same worktree`);
1096
+ inv = adapter.buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt) });
1097
+ engineRun = await runEngine();
1098
+ meter(engineRun.stdout, false);
995
1099
  }
996
- await api.event(job.runId, 'pushing', { branch });
997
- const gitCred = job.repo ? await api.gitCredential(job.runId) : null;
998
- if (gitCred)
999
- log(`using a FireFunc-issued git credential for ${gitCred.repo}`);
1000
- const pushedCommits = await execOut('git', [
1001
- '-C',
1002
- worktree,
1003
- '--no-replace-objects',
1004
- '-c',
1005
- 'core.quotepath=off',
1006
- 'log',
1007
- '--name-only',
1008
- '--format=',
1009
- '--no-renames',
1010
- '--diff-filter=d',
1011
- `${continuesBranch ? `origin/${branch}` : `origin/${base}`}..${scannedTip ?? `refs/heads/${branch}`}`,
1012
- ]);
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('/')
1100
+ const openAtEnd = (stdout) => {
1101
+ try {
1102
+ return adapter.openCommandsAtEnd?.(stdout) ?? [];
1103
+ }
1104
+ catch {
1105
+ return [];
1106
+ }
1107
+ };
1108
+ const endedOnItsAnswer = (r) => r.code === 0 && !limitOf(r.stdout) && !refused(r.stdout, r.stderr);
1109
+ let open = endedOnItsAnswer(engineRun) ? openAtEnd(engineRun.stdout) : [];
1110
+ let promising = endedOnItsAnswer(engineRun) && promisesLaterCheck(adapter.summarize(engineRun.stdout));
1111
+ const toContinue = adapter.resumesSessions
1112
+ ? (adapter.sessionId?.(engineRun.stdout) ?? null)
1027
1113
  : null;
1028
- const stagedPaths = staged
1029
- .split('\n')
1030
- .map((l) => l.trim())
1031
- .filter(Boolean);
1032
- const leaked = stagedPaths.filter((l) => l === '.env' || l.endsWith('/.env') || (mcpStaged !== null && l === mcpStaged));
1033
- if (leaked.length > 0) {
1034
- return fail(`refusing to push: the commit contains ${leaked.join(', ')}, which can hold live credentials. ` +
1035
- `This is a FireFunc bug — please report it. Nothing was pushed.`);
1036
- }
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.`);
1114
+ const timeLeft = timeoutMs - engineMs;
1115
+ let continuedOnce = false;
1116
+ if ((open.length > 0 || promising) && toContinue && timeLeft < 60_000) {
1117
+ log(`${engineName}'s session ended before its result came, with under a minute of its time left — not continuing it`);
1044
1118
  }
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,
1119
+ else if ((open.length > 0 || promising) && toContinue) {
1120
+ log(`${engineName}'s session ended ${open.length > 0 ? `while its own ${open.join(', ')} was still running` : 'on a promise to check a result later'} — continuing the same session once to get the result`);
1121
+ inv = adapter.buildInvocation({
1122
+ ...ctx,
1123
+ prompt: continueToFinishBrief(open),
1124
+ resumeSessionId: toContinue,
1057
1125
  });
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();
1126
+ engineRun = await runEngine(timeLeft);
1127
+ meter(engineRun.stdout, true);
1128
+ continuedOnce = true;
1129
+ open = endedOnItsAnswer(engineRun) ? openAtEnd(engineRun.stdout) : [];
1130
+ promising =
1131
+ endedOnItsAnswer(engineRun) && promisesLaterCheck(adapter.summarize(engineRun.stdout));
1065
1132
  }
1066
- if (push.code !== 0) {
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.`);
1133
+ openCommandAtEnd = open.length > 0;
1134
+ const unfinished = open.length > 0 || promising;
1135
+ clearInterval(heartbeat);
1136
+ usage =
1137
+ attemptUsage(sessions, resumeCut ? { session: resumeCut.sessionId, baseline: resumeCut.usage } : undefined) ?? undefined;
1138
+ if (revising && kept?.attemptUsage) {
1139
+ usage = combineUsage([kept.attemptUsage, usage ?? null]) ?? usage;
1073
1140
  }
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`);
1141
+ if (usage)
1142
+ log(`${engineName} spent: ${describeUsage(usage)}`);
1143
+ viewer?.end(job.runId, engineRun.code === 0 ? 'done' : 'failed');
1144
+ if (printer)
1145
+ log(`── end ${engineName} session ──`);
1146
+ await activity.flush();
1147
+ log(`reported ${activity.sent} of ${activity.seen} step(s) to FireFunc — names and verbs only; the session stayed here`);
1148
+ mcp?.cleanup();
1149
+ const sessionLogPath = saveSessionLog(job.runId, engineRun.stdout, engineRun.stderr);
1150
+ const summary = adapter.summarize(engineRun.stdout);
1151
+ if (sessionLogPath)
1152
+ log(`${engineName} session saved → ${sessionLogPath}`);
1153
+ if (summary)
1154
+ log(`${engineName} said: ${summary.replace(/\s+/g, ' ').slice(0, 500)}`);
1155
+ if (engineRun.code === 124) {
1156
+ return fail(budget !== null && limitMinutes === budget
1157
+ ? `${engineName} timed out after ${limitMinutes} min — the agent's time budget.`
1158
+ : `${engineName} timed out after ${limitMinutes} min.`);
1080
1159
  }
1081
- const body = pullRequestBody(kind, engineName, job.externalId, { continuesBranch });
1082
- if (gitCred) {
1083
- const pr = await withNetworkRetry(() => openDraftPr({
1084
- repo: gitCred.repo,
1085
- head: branch,
1086
- base,
1087
- title,
1088
- body,
1089
- cred: gitCred,
1090
- }), {
1091
- label: `pull request for ${job.runId}`,
1092
- maxWaitMs: 10 * 60_000,
1093
- probe: () => api.probe(),
1094
- log,
1095
- });
1096
- if (!('error' in pr)) {
1097
- await api.event(job.runId, 'pr_opened', { url: pr.url, branch });
1098
- log(`opened PR for ${job.runId}: ${pr.url}`);
1099
- return report({
1100
- status: 'pr_opened',
1101
- pr: {
1102
- repo: job.repo ?? undefined,
1103
- number: pr.number,
1104
- url: pr.url,
1105
- branch,
1106
- summary: title,
1107
- },
1108
- ...(summary ? { summary: reportedSummary(summary) } : {}),
1160
+ const limit = limitOf(engineRun.stdout);
1161
+ if (limit) {
1162
+ opts?.limits?.set(adapter.id, limit);
1163
+ const cutSession = adapter.resumesSessions
1164
+ ? (adapter.sessionId?.(engineRun.stdout) ?? null)
1165
+ : null;
1166
+ let kept = false;
1167
+ if (cutSession && worktree) {
1168
+ const cutAt = now().getTime();
1169
+ kept = saveCut(rdir, {
1170
+ workItemId: job.workItemId,
1171
+ runId: job.runId,
1172
+ engine: adapter.id,
1173
+ sessionId: cutSession,
1174
+ repo: job.repo ?? null,
1175
+ branch: toolsOnly ? '' : branch,
1176
+ base,
1177
+ worktree,
1178
+ repoPath: toolsOnly ? null : repoPath,
1179
+ ...(readHead ? { readHead } : {}),
1180
+ resetsAt: limit.resetsAt,
1181
+ cutAt: new Date(cutAt).toISOString(),
1182
+ keepUntil: keepUntil(limit.resetsAt, cutAt),
1183
+ promptHash: promptHash(job.prompt),
1184
+ review,
1185
+ toolsOnly,
1186
+ continuesBranch,
1187
+ ...(lastReport ? { usage: lastReport } : {}),
1188
+ writtenSkills,
1109
1189
  });
1110
1190
  }
1111
- const why = redact(pr.error, gitCred.token);
1112
- if (!(await hasGh(worktree)))
1113
- return fail(why);
1114
- log(`could not open the PR as FireFunc (${why}); falling back to gh`);
1191
+ keepWorktree = kept;
1192
+ log(`${engineName} was stopped by the plan's usage limit${limit.said ? ` ("${limit.said}")` : ''} — ` +
1193
+ (limit.resetsAt ? `it resets at ${limit.resetsAt}` : 'it did not say when it resets') +
1194
+ (kept ? '; the session and its worktree are kept to continue after the reset' : ''));
1195
+ return report({
1196
+ status: 'failed',
1197
+ error: limitSentence(engineName, limit, kept),
1198
+ limit: { kind: 'plan', resetsAt: limit.resetsAt },
1199
+ });
1115
1200
  }
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
- }));
1145
- const wt = worktree;
1146
- const viewPr = async (b) => {
1147
- const out = await execOut('gh', ['pr', 'view', b, '--json', 'url,number'], wt);
1148
- try {
1149
- const j = JSON.parse(out);
1150
- if (typeof j.url === 'string' && /\/pull\/\d+/.test(j.url) && Number.isFinite(j.number)) {
1151
- return { url: j.url, number: Number(j.number) };
1152
- }
1201
+ const declinedHint = () => {
1202
+ if (!refused(engineRun.stdout, engineRun.stderr))
1203
+ return null;
1204
+ log(`the model declined ${job.runId}: its safety system refused the session`);
1205
+ return { status: 'failed', error: modelDeclinedSentence(engineName) };
1206
+ };
1207
+ const scanHints = () => {
1208
+ const declined = declinedHint();
1209
+ if (declined)
1210
+ return declined;
1211
+ const authMsg = adapter.authFailureHint(`${summary}\n${engineRun.stderr}`);
1212
+ if (authMsg) {
1213
+ log(`auth/billing failure for ${job.runId}: ${authMsg}`);
1214
+ return { status: 'failed', error: authMsg };
1153
1215
  }
1154
- catch {
1216
+ const rateMsg = adapter.rateLimitHint(`${summary}\n${engineRun.stderr}`);
1217
+ if (rateMsg) {
1218
+ log(`rate limit for ${job.runId}: ${rateMsg}`);
1219
+ return { status: 'failed', error: rateMsg };
1155
1220
  }
1156
1221
  return null;
1157
1222
  };
1158
- const headBranch = (await execOut('git', ['rev-parse', '--abbrev-ref', 'HEAD'], wt)) || branch;
1159
- let resolved = null;
1160
- for (const b of [...new Set([headBranch, branch].filter(Boolean))]) {
1161
- resolved = await viewPr(b);
1162
- if (resolved)
1163
- break;
1223
+ if (engineRun.code !== 0) {
1224
+ const signal = endedBySignal(engineRun.code);
1225
+ if (signal) {
1226
+ log(`${engineName} was ended by ${signal} (exit ${engineRun.code}) for ${job.runId}`);
1227
+ return fail(stoppedSentence(engineName, engineRun.code, signal, sessionLogPath ? basename(sessionLogPath) : null));
1228
+ }
1229
+ const hinted = scanHints();
1230
+ if (hinted)
1231
+ return report(hinted);
1232
+ const why = summary ? null : errorLine(engineRun.stderr);
1233
+ return fail(summary
1234
+ ? `${engineName} exited abnormally (code ${engineRun.code}). Last message: ${oneLine(shareable(summary), 500)}`
1235
+ : `${engineName} exited abnormally (code ${engineRun.code})${why ? `: ${oneLine(stripWorktree(why, worktree), 200)}` : ''}. ` +
1236
+ `Its output stayed on the machine${sessionLogPath ? ` — the session log is logs/${basename(sessionLogPath)} in the runner’s folder` : ''}.`);
1164
1237
  }
1165
- if (!resolved) {
1166
- const m = `${create.stdout}\n${create.stderr}`.match(/https?:\/\/\S*\/pull\/(\d+)/);
1167
- if (m)
1168
- resolved = { url: m[0], number: Number(m[1]) };
1238
+ if (unfinished) {
1239
+ log(`${engineName} ended its session ${openCommandAtEnd ? `while its own ${open.join(', ')} was still running` : 'on a promise to check a result later'} — not reporting it as an answer${review || toolsOnly ? '' : ', pushing nothing'}`);
1240
+ return fail(unfinishedSentence(engineName, open, !review && !toolsOnly, continuedOnce));
1169
1241
  }
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.`);
1242
+ if (review) {
1243
+ const dirty = await exec('git', ['-C', worktree, 'status', '--porcelain']);
1244
+ const left = dirty.stdout.split('\n').filter((l) => l.trim()).length;
1245
+ if (left > 0) {
1246
+ log(`review run ${job.runId}: ${left} changed path(s) in the checkout are discarded — a review pushes nothing`);
1247
+ }
1248
+ const declinedReview = declinedHint();
1249
+ if (declinedReview)
1250
+ return report(declinedReview);
1251
+ log(`review run ${job.runId} finished — reporting the agent's review`);
1252
+ return report({
1253
+ status: 'no_pr',
1254
+ ...(summary
1255
+ ? { summary: reportedSummary(summary) }
1256
+ : { error: `${engineName} finished without saying what it found.` }),
1257
+ });
1174
1258
  }
1175
- const url = resolved.url;
1176
- const number = resolved.number;
1177
- await api.event(job.runId, 'pr_opened', { url, branch });
1178
- log(`opened PR for ${job.runId}: ${url}`);
1179
- return report({
1180
- status: 'pr_opened',
1181
- pr: { repo: job.repo ?? undefined, number, url: url || undefined, branch, summary: title },
1182
- ...(summary ? { summary: reportedSummary(summary) } : {}),
1259
+ if (toolsOnly) {
1260
+ const declinedAnswer = declinedHint();
1261
+ if (declinedAnswer)
1262
+ return report(declinedAnswer);
1263
+ log(`tools-only run ${job.runId} finished — reporting the agent's summary`);
1264
+ return report({
1265
+ status: 'no_pr',
1266
+ ...(summary
1267
+ ? { summary: reportedSummary(summary) }
1268
+ : { error: `${engineName} finished without a summary of what it did.` }),
1269
+ });
1270
+ }
1271
+ await exec('git', [
1272
+ '-C',
1273
+ worktree,
1274
+ 'add',
1275
+ '-A',
1276
+ '--',
1277
+ '.',
1278
+ ':(exclude).env',
1279
+ ':(exclude).claude/skills',
1280
+ ...writtenSkills.pathspecs,
1281
+ ]);
1282
+ const vsBase = await exec('git', [
1283
+ '-C',
1284
+ worktree,
1285
+ 'diff',
1286
+ '--cached',
1287
+ '--quiet',
1288
+ `origin/${base}`,
1289
+ ]);
1290
+ if (vsBase.code === 0) {
1291
+ const hinted = scanHints();
1292
+ if (hinted)
1293
+ return report(hinted);
1294
+ log(`no changes produced for ${job.runId} — reporting no_pr`);
1295
+ return report({
1296
+ status: 'no_pr',
1297
+ error: summary
1298
+ ? `No code change made. ${engineName}: ${oneLine(shareable(summary), 800)}`
1299
+ : `${engineName} made no changes (could not reproduce or fix).`,
1300
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
1301
+ });
1302
+ }
1303
+ const touched = await exec('git', [
1304
+ '-C',
1305
+ worktree,
1306
+ 'diff',
1307
+ '--cached',
1308
+ '--name-only',
1309
+ '--no-renames',
1310
+ '-z',
1311
+ continuesBranch ? `origin/${branch}` : `origin/${base}`,
1312
+ ], { timeoutMs: 60_000 }).catch(() => null);
1313
+ const kind = changeKind(touched?.code === 0 ? touched.stdout.split('\0').filter(Boolean) : null);
1314
+ const title = pullRequestTitle(job, kind);
1315
+ log(`${kind === 'test' ? 'the change touches tests only — ' : ''}titled "${title}"`);
1316
+ const uncommitted = await exec('git', ['-C', worktree, 'diff', '--cached', '--quiet', 'HEAD']);
1317
+ if (uncommitted.code !== 0) {
1318
+ await exec('git', ['-C', worktree, 'commit', '-m', title, '--quiet']);
1319
+ }
1320
+ else {
1321
+ log(`agent already committed its changes for ${job.runId} — reconciling to a PR`);
1322
+ }
1323
+ return await ship({
1324
+ worktree: worktree,
1325
+ branch,
1326
+ base,
1327
+ title,
1328
+ kind,
1329
+ engineName,
1330
+ summary,
1331
+ keep: askFirst
1332
+ ? {
1333
+ sessionId: adapter.sessionId?.(engineRun.stdout) ?? (resumeCut?.sessionId || null),
1334
+ ...(lastReport ? { sessionReport: lastReport } : {}),
1335
+ round: revising ? revising.round : 1,
1336
+ }
1337
+ : null,
1183
1338
  });
1184
1339
  }
1185
1340
  catch (err) {
@@ -1213,6 +1368,8 @@ export async function runJob(job, cfg, api, viewer, opts) {
1213
1368
  }
1214
1369
  if (resumeCut && !keepWorktree)
1215
1370
  dropCut(rdir, resumeCut.workItemId);
1371
+ if (kept && !keepWorktree)
1372
+ dropKept(rdir, job.runId);
1216
1373
  if (!keepWorktree) {
1217
1374
  for (const copy of reviewCopies) {
1218
1375
  try {