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