@firefunc-agent/runner 0.9.0 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +90 -28
  2. package/dist/activity.d.ts +4 -1
  3. package/dist/activity.js +94 -8
  4. package/dist/api.d.ts +24 -0
  5. package/dist/api.js +74 -5
  6. package/dist/brief.d.ts +5 -0
  7. package/dist/brief.js +21 -0
  8. package/dist/build-info.json +2 -2
  9. package/dist/cli.js +10 -2
  10. package/dist/config.d.ts +2 -0
  11. package/dist/cut.d.ts +45 -0
  12. package/dist/cut.js +105 -0
  13. package/dist/daemon.d.ts +16 -0
  14. package/dist/daemon.js +156 -35
  15. package/dist/declined.d.ts +11 -0
  16. package/dist/declined.js +27 -0
  17. package/dist/engines/claude.js +129 -1
  18. package/dist/engines/types.d.ts +10 -0
  19. package/dist/exec.d.ts +3 -0
  20. package/dist/exec.js +48 -5
  21. package/dist/firefunc/agents.js +59 -7
  22. package/dist/firefunc/client.d.ts +1 -0
  23. package/dist/firefunc/client.js +3 -0
  24. package/dist/firefunc/configure.d.ts +6 -0
  25. package/dist/firefunc/configure.js +409 -0
  26. package/dist/firefunc/main.js +45 -7
  27. package/dist/firefunc/output.js +4 -1
  28. package/dist/firefunc/version.js +2 -17
  29. package/dist/held.d.ts +18 -0
  30. package/dist/held.js +95 -0
  31. package/dist/job.d.ts +3 -0
  32. package/dist/job.js +437 -76
  33. package/dist/keep-local.d.ts +6 -1
  34. package/dist/keep-local.js +171 -4
  35. package/dist/limit.d.ts +30 -0
  36. package/dist/limit.js +258 -0
  37. package/dist/locks.d.ts +14 -0
  38. package/dist/locks.js +164 -0
  39. package/dist/mcp-proxy.d.ts +21 -0
  40. package/dist/mcp-proxy.js +180 -0
  41. package/dist/mcp.d.ts +2 -0
  42. package/dist/mcp.js +31 -2
  43. package/dist/orphans.d.ts +40 -0
  44. package/dist/orphans.js +235 -0
  45. package/dist/pool.d.ts +7 -0
  46. package/dist/pool.js +57 -9
  47. package/dist/pr-title.d.ts +11 -0
  48. package/dist/pr-title.js +63 -0
  49. package/dist/recover.d.ts +10 -0
  50. package/dist/recover.js +104 -0
  51. package/dist/session-stream.d.ts +8 -1
  52. package/dist/session-stream.js +9 -1
  53. package/dist/skills.d.ts +11 -0
  54. package/dist/skills.js +164 -0
  55. package/dist/stopped.d.ts +3 -0
  56. package/dist/stopped.js +10 -0
  57. package/dist/usage.d.ts +49 -0
  58. package/dist/usage.js +389 -0
  59. package/dist/version.d.ts +1 -0
  60. package/dist/version.js +17 -0
  61. package/dist/worktrees.d.ts +15 -0
  62. package/dist/worktrees.js +96 -0
  63. package/package.json +1 -1
  64. package/skill/firefunc/SKILL.md +57 -8
package/dist/job.js CHANGED
@@ -1,20 +1,32 @@
1
1
  import { mkdtempSync, rmSync, existsSync, mkdirSync, writeFileSync, copyFileSync, appendFileSync, chmodSync, readdirSync, } from 'node:fs';
2
- import { tmpdir } from 'node:os';
2
+ import { homedir, tmpdir } from 'node:os';
3
3
  import { join, basename, dirname, relative, sep } from 'node:path';
4
- import { execSync } from 'node:child_process';
4
+ import {} from 'node:child_process';
5
5
  import { exec, execOut, spawnBackground, killProcessTree } from './exec.js';
6
+ import { REPORTED_SUMMARY_MAX, cutText } from './api.js';
6
7
  import { configPath, loadConfig, saveConfig } from './config.js';
7
8
  import { cloneRepo, openDraftPr, pushBranch, pushFlags, redact } from './git-auth.js';
8
9
  import { createActivityReporter, redact as oneLine, stripWorktree } from './activity.js';
9
- import { commandName, errorLine, pushRefusal, stripCode } from './keep-local.js';
10
+ import { errorLine, foldHome, promisesLaterCheck, pushRefusal, setupCommandName, setupReason, stripCode, } from './keep-local.js';
10
11
  import { FULL_SHA, changeReads, hardFirst, refusesPush, scanAddedLines, secretRefusal, uniqueHits, } from './secret-scan.js';
11
12
  import { isNetworkError, networkFailureHint, waitForNetwork, withNetworkRetry } from './network.js';
13
+ import { endedOnRefusal, modelDeclinedSentence } from './declined.js';
14
+ import { endedBySignal, stoppedSentence } from './stopped.js';
15
+ import { changeKind, pullRequestBody, pullRequestTitle } from './pr-title.js';
12
16
  import { savePendingResult } from './pending.js';
13
17
  import { runnerDir } from './config.js';
18
+ import { attemptUsage, describeUsage } from './usage.js';
14
19
  import { makeStreamJsonParser } from './session-stream.js';
15
- import { createKeyedMutex } from './locks.js';
20
+ import { writeSkills, writtenSkillPaths } from './skills.js';
21
+ import { createKeyedMutex, ensureHeavyScript, heavyLockDir, withHeavyLock } from './locks.js';
16
22
  import { getAdapter, stripForeignEngineCreds } from './engines/index.js';
17
23
  import { mcpFormatForEngine, prepareMcp } from './mcp.js';
24
+ import { continueToFinishBrief, engineRules } from './brief.js';
25
+ import { limitSentence } from './limit.js';
26
+ import { cutFor, dropCut, keepUntil, promptHash, resumeAfterResetBrief, saveCut, } from './cut.js';
27
+ import { liveWorktrees, updateHeld } from './held.js';
28
+ import { killOrphans, reviewCopiesOf, trackEngineGroup, untrackEngineGroup } from './orphans.js';
29
+ import { canonicalPath, removeRunnerWorktree, staleHolder } from './worktrees.js';
18
30
  function log(msg) {
19
31
  console.log(`[firefunc-runner] ${new Date().toISOString()} ${msg}`);
20
32
  }
@@ -138,46 +150,43 @@ async function autoInstallDeps(worktree, env, timeoutMs) {
138
150
  if (!installed && dirs[0] !== '')
139
151
  log('auto-install: no package.json found — skipping');
140
152
  }
141
- function writeSkills(worktree, job, log) {
142
- const skills = (job.skills ?? []).filter((s) => s && typeof s.slug === 'string' && typeof s.content === 'string');
143
- if (skills.length === 0)
144
- return;
145
- try {
146
- for (const s of skills) {
147
- const slug = s.slug.replace(/[^a-z0-9-]/gi, '-').toLowerCase();
148
- const dir = join(worktree, '.claude', 'skills', slug);
149
- mkdirSync(dir, { recursive: true });
150
- writeFileSync(join(dir, 'SKILL.md'), s.content);
151
- }
152
- try {
153
- const gitDir = execSync('git rev-parse --git-common-dir', {
154
- cwd: worktree,
155
- encoding: 'utf8',
156
- }).trim();
157
- if (gitDir) {
158
- const abs = gitDir.startsWith('/') ? gitDir : join(worktree, gitDir);
159
- mkdirSync(join(abs, 'info'), { recursive: true });
160
- appendFileSync(join(abs, 'info', 'exclude'), '\n# FireFunc: skills are written per run, never committed\n.claude/skills/\n');
161
- }
162
- }
163
- catch {
164
- }
165
- log(`wrote ${skills.length} skill(s) into .claude/skills: ${skills.map((s) => s.slug).join(', ')}`);
166
- }
167
- catch (e) {
168
- log(`could not write skills: ${e.message}`);
169
- }
153
+ function unfinishedSentence(engineName, open, changeRun, continued) {
154
+ const how = open.length === 0
155
+ ? 'on a promise to check a result later'
156
+ : open.length === 1
157
+ ? `while a command it had started (${open[0]}) was still running`
158
+ : `while commands it had started (${open.join(', ')}) were still running`;
159
+ return (`${engineName} ended its session ${how}` +
160
+ (continued ? ', and again after the runner continued it once to get the result' : '') +
161
+ ' — the result it was waiting for never came, so its closing words are not reported as its answer' +
162
+ (changeRun ? ' and the runner pushed nothing' : '') +
163
+ '. Re-run the task; if it happens again, look in the agent’s instruction and skills for anything that runs its checks in the background.');
170
164
  }
171
- function resumeBrief(prompt) {
172
- return ('Your previous session on this task was cut short by a network outage. The worktree ' +
165
+ function resumeBrief(prompt, why = 'network') {
166
+ const what = why === 'limit'
167
+ ? "was stopped by the plan's usage limit, which has now reset, and that session could not be continued"
168
+ : 'was cut short by a network outage';
169
+ return (`Your previous session on this task ${what}. The worktree ` +
173
170
  'still holds everything you did; look at `git status` and `git diff`, continue from ' +
174
171
  'there, and finish the task. The original brief follows.\n\n' +
175
172
  prompt);
176
173
  }
177
174
  export async function runJob(job, cfg, api, viewer, opts) {
175
+ const now = opts?.now ?? (() => new Date());
176
+ const rdir = runnerDir();
178
177
  let secretScan;
178
+ let usage;
179
+ let readHead;
180
+ let openCommandAtEnd = false;
179
181
  const report = async (reported) => {
180
- const payload = secretScan && !reported.secretScan ? { ...reported, secretScan } : reported;
182
+ let payload = secretScan && !reported.secretScan ? { ...reported, secretScan } : reported;
183
+ if (usage && !payload.usage)
184
+ payload = { ...payload, usage };
185
+ if (readHead && !payload.readHead)
186
+ payload = { ...payload, readHead };
187
+ if (openCommandAtEnd && !payload.openCommandAtEnd) {
188
+ payload = { ...payload, openCommandAtEnd: true };
189
+ }
181
190
  try {
182
191
  await withNetworkRetry(() => api.result(job.runId, payload), {
183
192
  label: `result for ${job.runId}`,
@@ -208,13 +217,12 @@ export async function runJob(job, cfg, api, viewer, opts) {
208
217
  }
209
218
  }
210
219
  const shareable = (text) => stripCode(worktree ? stripWorktree(text, worktree) : text);
211
- const reportedSummary = (text) => shareable(text)
220
+ const reportedSummary = (text) => cutText(shareable(text)
212
221
  .replace(/\r\n?/g, '\n')
213
222
  .replace(/[ \t]+/g, ' ')
214
223
  .replace(/ +$/gm, '')
215
224
  .replace(/\n{3,}/g, '\n\n')
216
- .trim()
217
- .slice(0, 4000);
225
+ .trim(), REPORTED_SUMMARY_MAX);
218
226
  const fail = (error) => {
219
227
  log(`job ${job.runId} FAILED — ${error.replace(/\s+/g, ' ').slice(0, 300)}`);
220
228
  return report({ status: 'failed', error });
@@ -222,6 +230,17 @@ export async function runJob(job, cfg, api, viewer, opts) {
222
230
  const toolsOnly = !job.repo;
223
231
  const continuesBranch = !toolsOnly && job.continuesBranch === true;
224
232
  const review = !toolsOnly && job.review === true;
233
+ const adapter = getAdapter(job.engine ?? cfg.engine);
234
+ const spent = opts?.limits?.isLimited(adapter.id) ?? null;
235
+ if (spent) {
236
+ const limit = { kind: 'plan', resetsAt: spent.resetsAt };
237
+ log(`${adapter.displayName}'s plan limit is spent until ${spent.until} — answering ${job.runId} without starting it`);
238
+ return report({
239
+ status: 'failed',
240
+ error: limitSentence(adapter.displayName, limit, false),
241
+ limit: { kind: 'plan', resetsAt: limit.resetsAt },
242
+ });
243
+ }
225
244
  let repoPath = toolsOnly ? null : resolveRepoPath(job.repo, cfg);
226
245
  if (!repoPath && job.repo) {
227
246
  const cred = await api.gitCredential(job.runId);
@@ -251,12 +270,52 @@ export async function runJob(job, cfg, api, viewer, opts) {
251
270
  `${job.repo} <path>\`, set --repos-dir, or connect GitHub in FireFunc.`,
252
271
  });
253
272
  }
254
- const adapter = getAdapter(job.engine ?? cfg.engine);
255
273
  const branch = job.branch ?? `${adapter.branchPrefix}/firefunc-${job.runId.slice(0, 8)}`;
256
- const timeoutMs = (cfg.jobTimeoutMinutes ?? 20) * 60_000;
274
+ const budget = typeof job.maxMinutes === 'number' && Number.isFinite(job.maxMinutes) && job.maxMinutes > 0
275
+ ? Math.ceil(job.maxMinutes)
276
+ : null;
277
+ const limitMinutes = budget !== null
278
+ ? cfg.jobTimeoutMinutes
279
+ ? Math.min(budget, cfg.jobTimeoutMinutes)
280
+ : budget
281
+ : (cfg.jobTimeoutMinutes ?? 20);
282
+ const timeoutMs = limitMinutes * 60_000;
283
+ const cutMatch = cutFor(rdir, {
284
+ workItemId: job.workItemId,
285
+ engine: adapter.id,
286
+ repo: job.repo ?? null,
287
+ branch: toolsOnly ? '' : branch,
288
+ review,
289
+ toolsOnly,
290
+ }, now().getTime());
291
+ let resumeCut = null;
292
+ if (cutMatch && 'resume' in cutMatch && adapter.resumesSessions) {
293
+ resumeCut = cutMatch.resume;
294
+ }
295
+ else if (cutMatch) {
296
+ const stale = 'resume' in cutMatch ? cutMatch.resume : cutMatch.discard;
297
+ log(`the session a plan limit cut for this task cannot be continued by ${job.runId} — removing it`);
298
+ if (stale.repoPath && existsSync(stale.repoPath)) {
299
+ const holder = stale.repoPath;
300
+ await gitMutex
301
+ .run(holder, () => removeRunnerWorktree(holder, stale.worktree, log))
302
+ .catch(() => { });
303
+ }
304
+ else {
305
+ try {
306
+ rmSync(stale.worktree, { recursive: true, force: true });
307
+ }
308
+ catch {
309
+ }
310
+ }
311
+ dropCut(rdir, stale.workItemId);
312
+ }
313
+ let keepWorktree = false;
314
+ const engineGroups = [];
257
315
  let worktree = null;
258
316
  let attachDir = null;
259
317
  let mcp = null;
318
+ let writtenSkills = { written: [], pathspecs: [] };
260
319
  const bgProcs = [];
261
320
  viewer?.begin(job.runId, {
262
321
  title: job.title ?? job.externalId ?? undefined,
@@ -264,9 +323,15 @@ export async function runJob(job, cfg, api, viewer, opts) {
264
323
  });
265
324
  let base = '';
266
325
  try {
267
- if (toolsOnly) {
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) {
268
332
  worktree = mkdtempSync(join(tmpdir(), 'firefunc-tools-'));
269
- writeSkills(worktree, job, log);
333
+ updateHeld(rdir, job.runId, { scratch: [worktree] });
334
+ writeSkills(worktree, job.skills, log);
270
335
  await exec('git', ['-C', worktree, 'init', '--quiet']);
271
336
  log(`no repository for ${job.runId} — the agent works through its tools in ${worktree}`);
272
337
  }
@@ -275,6 +340,26 @@ export async function runJob(job, cfg, api, viewer, opts) {
275
340
  const checkout = repoPath;
276
341
  const prep = await gitMutex.run(checkout, async () => {
277
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
+ }
278
363
  let b = job.baseBranch ?? cfg.baseBranch ?? '';
279
364
  if (!b) {
280
365
  const head = await execOut('git', ['-C', checkout, 'symbolic-ref', 'refs/remotes/origin/HEAD'], checkout);
@@ -291,19 +376,49 @@ export async function runJob(job, cfg, api, viewer, opts) {
291
376
  '--quiet',
292
377
  `refs/remotes/origin/${branch}`,
293
378
  ]);
294
- if (has.code !== 0)
295
- return { base: b, wt: '', add: has, branchMissing: true };
379
+ if (has.code !== 0) {
380
+ return { base: b, wt: '', add: has, branchMissing: true, startPoint };
381
+ }
296
382
  startPoint = `origin/${branch}`;
297
383
  }
298
384
  const wt = mkdtempSync(join(tmpdir(), 'firefunc-'));
299
- const result = await exec('git', ['-C', checkout, 'worktree', 'add', '--force', '-B', branch, wt, startPoint], { timeoutMs: 120_000 });
300
- return { base: b, wt, add: result, branchMissing: false };
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 };
301
399
  });
302
400
  base = prep.base;
303
401
  if (prep.branchMissing) {
304
- return fail(`The pull request's branch "${branch}" is not in ${job.repo}, so it cannot be continued from this checkout — a pull request from a fork lives in the fork. Nothing was changed.`);
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.`);
305
404
  }
306
405
  worktree = prep.wt;
406
+ updateHeld(rdir, job.runId, { worktree, repoPath: checkout });
407
+ if (resumeCut) {
408
+ readHead = resumeCut.readHead;
409
+ }
410
+ else if (prep.add.code === 0 && prep.startPoint) {
411
+ const sha = await execOut('git', [
412
+ '-C',
413
+ worktree,
414
+ 'rev-parse',
415
+ '--verify',
416
+ '--quiet',
417
+ `${prep.startPoint}^{commit}`,
418
+ ]).catch(() => '');
419
+ if (FULL_SHA.test(sha))
420
+ readHead = sha;
421
+ }
307
422
  if (prep.add.code !== 0) {
308
423
  log(`git worktree add output for ${job.runId} (kept on this machine):\n${prep.add.stderr}`);
309
424
  const said = pushRefusal(prep.add.stderr);
@@ -315,6 +430,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
315
430
  const attachPaths = [];
316
431
  if (job.attachments?.length) {
317
432
  attachDir = mkdtempSync(join(tmpdir(), 'firefunc-attach-'));
433
+ updateHeld(rdir, job.runId, { scratch: [attachDir] });
318
434
  mkdirSync(attachDir, { recursive: true });
319
435
  job.attachments.forEach((att, i) => {
320
436
  if (!att?.dataB64)
@@ -363,31 +479,52 @@ export async function runJob(job, cfg, api, viewer, opts) {
363
479
  log(`envFile copy failed (${cfg.envFile}): ${e.message}`);
364
480
  }
365
481
  }
366
- if (!toolsOnly)
367
- writeSkills(worktree, job, log);
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();
368
497
  const setupMs = (cfg.setupTimeoutMinutes ?? cfg.jobTimeoutMinutes ?? 20) * 60_000;
369
498
  if (toolsOnly) {
370
499
  }
371
500
  else if (cfg.setupCommands?.length) {
372
501
  for (const cmd of cfg.setupCommands) {
373
502
  log(`setup: ${cmd}`);
374
- const r = await exec(cmd, [], {
375
- cwd: worktree,
503
+ const setupCwd = worktree;
504
+ const r = await heavily(() => exec(cmd, [], {
505
+ cwd: setupCwd,
376
506
  env: runEnv,
377
507
  timeoutMs: setupMs,
378
508
  shell: true,
379
- });
509
+ }));
380
510
  if (r.code !== 0) {
381
- log(`setup output for ${job.runId} (kept on this machine):\n${r.stderr.slice(-4000)}`);
382
- const why = errorLine(r.stderr);
383
- return fail(`Setup command failed (exit ${r.code}): ${commandName(cmd)}` +
384
- `${why ? ` — ${oneLine(stripWorktree(why, worktree), 200)}` : ''}. ` +
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}` : ''}. ` +
385
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.');
386
520
  }
387
521
  }
388
522
  }
523
+ else if (resumeCut) {
524
+ }
389
525
  else if (cfg.autoInstall ?? true) {
390
- await autoInstallDeps(worktree, runEnv, setupMs);
526
+ const installIn = worktree;
527
+ await heavily(() => autoInstallDeps(installIn, runEnv, setupMs));
391
528
  }
392
529
  for (const cmd of toolsOnly ? [] : (cfg.backgroundCommands ?? [])) {
393
530
  log(`starting background: ${cmd}`);
@@ -399,7 +536,8 @@ export async function runJob(job, cfg, api, viewer, opts) {
399
536
  const effort = job.effort ?? cfg.effort ?? null;
400
537
  const ultracode = effort === 'ultracode';
401
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';
402
- const prompt = observeNote + attachNote + (ultracode ? `ultracode\n\n${job.prompt}` : job.prompt);
539
+ const rules = engineRules({ minutes: limitMinutes, heavy: heavyHelper !== null });
540
+ const prompt = rules + observeNote + attachNote + (ultracode ? `ultracode\n\n${job.prompt}` : job.prompt);
403
541
  const tools = cfg.allowedTools ??
404
542
  'Read Edit Write Bash Glob Grep WebFetch WebSearch Task TodoWrite NotebookEdit';
405
543
  const isWin = process.platform === 'win32';
@@ -413,6 +551,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
413
551
  runId: job.runId,
414
552
  api,
415
553
  log,
554
+ relay: cfg.mcpRelay !== false,
416
555
  });
417
556
  }
418
557
  log(mcp ? `mcp: ${mcp.logLine}` : 'mcp: no server was injected for this run');
@@ -428,13 +567,25 @@ export async function runJob(job, cfg, api, viewer, opts) {
428
567
  attachDir: attachDir ?? undefined,
429
568
  attachPaths,
430
569
  isWin,
431
- runEnv: stripForeignEngineCreds(runEnv, adapter.id),
570
+ runEnv: {
571
+ ...stripForeignEngineCreds(runEnv, adapter.id),
572
+ ...(heavyHelper && heavyLock
573
+ ? { FIREFUNC_HEAVY: heavyHelper, FIREFUNC_HEAVY_LOCK: heavyLock }
574
+ : {}),
575
+ },
432
576
  cfg,
433
577
  ...(mcp ? { mcp } : {}),
434
578
  };
579
+ const firstCtx = resumeCut
580
+ ? {
581
+ ...ctx,
582
+ resumeSessionId: resumeCut.sessionId,
583
+ prompt: resumeAfterResetBrief(prompt, promptHash(job.prompt) !== resumeCut.promptHash),
584
+ }
585
+ : ctx;
435
586
  let inv;
436
587
  try {
437
- inv = adapter.buildInvocation(ctx);
588
+ inv = adapter.buildInvocation(firstCtx);
438
589
  }
439
590
  catch (e) {
440
591
  return fail(`${adapter.displayName} cannot run on this machine: ${e.message}`);
@@ -446,8 +597,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
446
597
  const activity = createActivityReporter({
447
598
  worktree,
448
599
  post: (steps) => api.activity(job.runId, steps),
600
+ writeTools: new Set(mcp?.writeToolNames ?? []),
449
601
  });
450
- const activityParser = makeStreamJsonParser(activity.push);
602
+ const activityParser = makeStreamJsonParser(activity.push, { toolResults: true });
451
603
  const onStdout = (chunk) => {
452
604
  printer?.(chunk);
453
605
  viewer?.push(job.runId, chunk);
@@ -458,16 +610,76 @@ export async function runJob(job, cfg, api, viewer, opts) {
458
610
  }
459
611
  const heartbeat = setInterval(() => void api.event(job.runId, 'heartbeat'), 5 * 60_000);
460
612
  const engineCwd = worktree;
461
- const runEngine = () => exec(inv.bin, inv.args, {
462
- cwd: engineCwd,
463
- timeoutMs,
464
- env: inv.env,
465
- input: inv.stdinInput,
466
- shell: inv.shell,
467
- onStdout,
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,
468
667
  });
469
668
  let engineRun = await runEngine();
669
+ meter(engineRun.stdout, false);
670
+ if (resumeCut && engineRun.code !== 0 && !adapter.sessionId?.(engineRun.stdout)) {
671
+ log(`${engineName} could not continue the session a plan limit cut — starting a new session in the same worktree`);
672
+ inv = adapter.buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt, 'limit') });
673
+ engineRun = await runEngine();
674
+ meter(engineRun.stdout, false);
675
+ }
470
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;
471
683
  const why = networkFailureHint(`${adapter.summarize(engineRun.stdout)}\n${engineRun.stderr.slice(-2000)}`);
472
684
  if (!why)
473
685
  break;
@@ -484,8 +696,48 @@ export async function runJob(job, cfg, api, viewer, opts) {
484
696
  log(`the network is back — resuming ${engineName} in the same worktree`);
485
697
  inv = adapter.buildInvocation({ ...ctx, prompt: resumeBrief(ctx.prompt) });
486
698
  engineRun = await runEngine();
699
+ meter(engineRun.stdout, false);
700
+ }
701
+ const openAtEnd = (stdout) => {
702
+ try {
703
+ return adapter.openCommandsAtEnd?.(stdout) ?? [];
704
+ }
705
+ catch {
706
+ return [];
707
+ }
708
+ };
709
+ const endedOnItsAnswer = (r) => r.code === 0 && !limitOf(r.stdout) && !refused(r.stdout, r.stderr);
710
+ let open = endedOnItsAnswer(engineRun) ? openAtEnd(engineRun.stdout) : [];
711
+ let promising = endedOnItsAnswer(engineRun) && promisesLaterCheck(adapter.summarize(engineRun.stdout));
712
+ const toContinue = adapter.resumesSessions
713
+ ? (adapter.sessionId?.(engineRun.stdout) ?? null)
714
+ : null;
715
+ const timeLeft = timeoutMs - engineMs;
716
+ let continuedOnce = false;
717
+ if ((open.length > 0 || promising) && toContinue && timeLeft < 60_000) {
718
+ log(`${engineName}'s session ended before its result came, with under a minute of its time left — not continuing it`);
719
+ }
720
+ else if ((open.length > 0 || promising) && toContinue) {
721
+ log(`${engineName}'s session ended ${open.length > 0 ? `while its own ${open.join(', ')} was still running` : 'on a promise to check a result later'} — continuing the same session once to get the result`);
722
+ inv = adapter.buildInvocation({
723
+ ...ctx,
724
+ prompt: continueToFinishBrief(open),
725
+ resumeSessionId: toContinue,
726
+ });
727
+ engineRun = await runEngine(timeLeft);
728
+ meter(engineRun.stdout, true);
729
+ continuedOnce = true;
730
+ open = endedOnItsAnswer(engineRun) ? openAtEnd(engineRun.stdout) : [];
731
+ promising =
732
+ endedOnItsAnswer(engineRun) && promisesLaterCheck(adapter.summarize(engineRun.stdout));
487
733
  }
734
+ openCommandAtEnd = open.length > 0;
735
+ const unfinished = open.length > 0 || promising;
488
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)}`);
489
741
  viewer?.end(job.runId, engineRun.code === 0 ? 'done' : 'failed');
490
742
  if (printer)
491
743
  log(`── end ${engineName} session ──`);
@@ -499,9 +751,61 @@ export async function runJob(job, cfg, api, viewer, opts) {
499
751
  if (summary)
500
752
  log(`${engineName} said: ${summary.replace(/\s+/g, ' ').slice(0, 500)}`);
501
753
  if (engineRun.code === 124) {
502
- return fail(`${engineName} timed out after ${cfg.jobTimeoutMinutes ?? 20} min.`);
754
+ return fail(budget !== null && limitMinutes === budget
755
+ ? `${engineName} timed out after ${limitMinutes} min — the agent's time budget.`
756
+ : `${engineName} timed out after ${limitMinutes} min.`);
503
757
  }
758
+ const limit = limitOf(engineRun.stdout);
759
+ if (limit) {
760
+ opts?.limits?.set(adapter.id, limit);
761
+ const cutSession = adapter.resumesSessions
762
+ ? (adapter.sessionId?.(engineRun.stdout) ?? null)
763
+ : null;
764
+ let kept = false;
765
+ if (cutSession && worktree) {
766
+ const cutAt = now().getTime();
767
+ kept = saveCut(rdir, {
768
+ workItemId: job.workItemId,
769
+ runId: job.runId,
770
+ engine: adapter.id,
771
+ sessionId: cutSession,
772
+ repo: job.repo ?? null,
773
+ branch: toolsOnly ? '' : branch,
774
+ base,
775
+ worktree,
776
+ repoPath: toolsOnly ? null : repoPath,
777
+ ...(readHead ? { readHead } : {}),
778
+ resetsAt: limit.resetsAt,
779
+ cutAt: new Date(cutAt).toISOString(),
780
+ keepUntil: keepUntil(limit.resetsAt, cutAt),
781
+ promptHash: promptHash(job.prompt),
782
+ review,
783
+ toolsOnly,
784
+ continuesBranch,
785
+ ...(lastReport ? { usage: lastReport } : {}),
786
+ writtenSkills,
787
+ });
788
+ }
789
+ keepWorktree = kept;
790
+ log(`${engineName} was stopped by the plan's usage limit${limit.said ? ` ("${limit.said}")` : ''} — ` +
791
+ (limit.resetsAt ? `it resets at ${limit.resetsAt}` : 'it did not say when it resets') +
792
+ (kept ? '; the session and its worktree are kept to continue after the reset' : ''));
793
+ return report({
794
+ status: 'failed',
795
+ error: limitSentence(engineName, limit, kept),
796
+ limit: { kind: 'plan', resetsAt: limit.resetsAt },
797
+ });
798
+ }
799
+ const declinedHint = () => {
800
+ if (!refused(engineRun.stdout, engineRun.stderr))
801
+ return null;
802
+ log(`the model declined ${job.runId}: its safety system refused the session`);
803
+ return { status: 'failed', error: modelDeclinedSentence(engineName) };
804
+ };
504
805
  const scanHints = () => {
806
+ const declined = declinedHint();
807
+ if (declined)
808
+ return declined;
505
809
  const authMsg = adapter.authFailureHint(`${summary}\n${engineRun.stderr}`);
506
810
  if (authMsg) {
507
811
  log(`auth/billing failure for ${job.runId}: ${authMsg}`);
@@ -515,6 +819,11 @@ export async function runJob(job, cfg, api, viewer, opts) {
515
819
  return null;
516
820
  };
517
821
  if (engineRun.code !== 0) {
822
+ const signal = endedBySignal(engineRun.code);
823
+ if (signal) {
824
+ log(`${engineName} was ended by ${signal} (exit ${engineRun.code}) for ${job.runId}`);
825
+ return fail(stoppedSentence(engineName, engineRun.code, signal, sessionLogPath ? basename(sessionLogPath) : null));
826
+ }
518
827
  const hinted = scanHints();
519
828
  if (hinted)
520
829
  return report(hinted);
@@ -524,12 +833,19 @@ export async function runJob(job, cfg, api, viewer, opts) {
524
833
  : `${engineName} exited abnormally (code ${engineRun.code})${why ? `: ${oneLine(stripWorktree(why, worktree), 200)}` : ''}. ` +
525
834
  `Its output stayed on the machine${sessionLogPath ? ` — the session log is logs/${basename(sessionLogPath)} in the runner’s folder` : ''}.`);
526
835
  }
836
+ if (unfinished) {
837
+ log(`${engineName} ended its session ${openCommandAtEnd ? `while its own ${open.join(', ')} was still running` : 'on a promise to check a result later'} — not reporting it as an answer${review || toolsOnly ? '' : ', pushing nothing'}`);
838
+ return fail(unfinishedSentence(engineName, open, !review && !toolsOnly, continuedOnce));
839
+ }
527
840
  if (review) {
528
841
  const dirty = await exec('git', ['-C', worktree, 'status', '--porcelain']);
529
842
  const left = dirty.stdout.split('\n').filter((l) => l.trim()).length;
530
843
  if (left > 0) {
531
844
  log(`review run ${job.runId}: ${left} changed path(s) in the checkout are discarded — a review pushes nothing`);
532
845
  }
846
+ const declinedReview = declinedHint();
847
+ if (declinedReview)
848
+ return report(declinedReview);
533
849
  log(`review run ${job.runId} finished — reporting the agent's review`);
534
850
  return report({
535
851
  status: 'no_pr',
@@ -539,6 +855,9 @@ export async function runJob(job, cfg, api, viewer, opts) {
539
855
  });
540
856
  }
541
857
  if (toolsOnly) {
858
+ const declinedAnswer = declinedHint();
859
+ if (declinedAnswer)
860
+ return report(declinedAnswer);
542
861
  log(`tools-only run ${job.runId} finished — reporting the agent's summary`);
543
862
  return report({
544
863
  status: 'no_pr',
@@ -547,7 +866,6 @@ export async function runJob(job, cfg, api, viewer, opts) {
547
866
  : { error: `${engineName} finished without a summary of what it did.` }),
548
867
  });
549
868
  }
550
- const title = job.title ? `fix: ${job.title}` : `fix: ${job.externalId ?? 'FireFunc auto-fix'}`;
551
869
  await exec('git', [
552
870
  '-C',
553
871
  worktree,
@@ -557,6 +875,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
557
875
  '.',
558
876
  ':(exclude).env',
559
877
  ':(exclude).claude/skills',
878
+ ...writtenSkills.pathspecs,
560
879
  ]);
561
880
  const vsBase = await exec('git', [
562
881
  '-C',
@@ -576,8 +895,22 @@ export async function runJob(job, cfg, api, viewer, opts) {
576
895
  error: summary
577
896
  ? `No code change made. ${engineName}: ${oneLine(shareable(summary), 800)}`
578
897
  : `${engineName} made no changes (could not reproduce or fix).`,
898
+ ...(summary ? { summary: reportedSummary(summary) } : {}),
579
899
  });
580
900
  }
901
+ const touched = await exec('git', [
902
+ '-C',
903
+ worktree,
904
+ 'diff',
905
+ '--cached',
906
+ '--name-only',
907
+ '--no-renames',
908
+ '-z',
909
+ continuesBranch ? `origin/${branch}` : `origin/${base}`,
910
+ ], { timeoutMs: 60_000 }).catch(() => null);
911
+ const kind = changeKind(touched?.code === 0 ? touched.stdout.split('\0').filter(Boolean) : null);
912
+ const title = pullRequestTitle(job, kind);
913
+ log(`${kind === 'test' ? 'the change touches tests only — ' : ''}titled "${title}"`);
581
914
  const uncommitted = await exec('git', ['-C', worktree, 'diff', '--cached', '--quiet', 'HEAD']);
582
915
  if (uncommitted.code !== 0) {
583
916
  await exec('git', ['-C', worktree, 'commit', '-m', title, '--quiet']);
@@ -692,14 +1025,23 @@ export async function runJob(job, cfg, api, viewer, opts) {
692
1025
  const mcpStaged = mcp?.configPath
693
1026
  ? relative(worktree, mcp.configPath).split(sep).join('/')
694
1027
  : null;
695
- const leaked = staged
1028
+ const stagedPaths = staged
696
1029
  .split('\n')
697
1030
  .map((l) => l.trim())
698
- .filter((l) => l === '.env' || l.endsWith('/.env') || (mcpStaged !== null && l === mcpStaged));
1031
+ .filter(Boolean);
1032
+ const leaked = stagedPaths.filter((l) => l === '.env' || l.endsWith('/.env') || (mcpStaged !== null && l === mcpStaged));
699
1033
  if (leaked.length > 0) {
700
1034
  return fail(`refusing to push: the commit contains ${leaked.join(', ')}, which can hold live credentials. ` +
701
1035
  `This is a FireFunc bug — please report it. Nothing was pushed.`);
702
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.`);
1044
+ }
703
1045
  const pushFrom = worktree;
704
1046
  const pushOnce = async () => gitCred
705
1047
  ? pushBranch(pushFrom, branch, gitCred.repo, gitCred, { force: !continuesBranch })
@@ -736,7 +1078,7 @@ export async function runJob(job, cfg, api, viewer, opts) {
736
1078
  else
737
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`);
738
1080
  }
739
- const body = `Automated fix by FireFunc (self-hosted ${engineName} runner) for ${job.externalId ?? 'a reported bug'}.\n\nReview before merging.`;
1081
+ const body = pullRequestBody(kind, engineName, job.externalId, { continuesBranch });
740
1082
  if (gitCred) {
741
1083
  const pr = await withNetworkRetry(() => openDraftPr({
742
1084
  repo: gitCred.repo,
@@ -848,19 +1190,38 @@ export async function runJob(job, cfg, api, viewer, opts) {
848
1190
  mcp?.cleanup();
849
1191
  viewer?.end(job.runId, 'failed');
850
1192
  await Promise.all(bgProcs.map((p) => killProcessTree(p).catch(() => { })));
851
- if (worktree && repoPath) {
1193
+ const reviewCopies = worktree ? reviewCopiesOf(worktree) : [];
1194
+ if (worktree || engineGroups.length > 0) {
1195
+ await killOrphans({
1196
+ roots: [worktree, attachDir, ...reviewCopies].filter((p) => !!p),
1197
+ ...(worktree ? { reviewCopiesOf: basename(worktree) } : {}),
1198
+ groups: engineGroups.map((g) => ({ ...g, leaderExited: true })),
1199
+ }, { log }).catch(() => { });
1200
+ }
1201
+ if (worktree && repoPath && !keepWorktree) {
852
1202
  const checkout = repoPath;
853
1203
  await gitMutex
854
1204
  .run(checkout, () => exec('git', ['-C', checkout, 'worktree', 'remove', '--force', worktree]))
855
1205
  .catch(() => { });
856
1206
  }
857
- if (worktree) {
1207
+ if (worktree && !keepWorktree) {
858
1208
  try {
859
1209
  rmSync(worktree, { recursive: true, force: true });
860
1210
  }
861
1211
  catch {
862
1212
  }
863
1213
  }
1214
+ if (resumeCut && !keepWorktree)
1215
+ dropCut(rdir, resumeCut.workItemId);
1216
+ if (!keepWorktree) {
1217
+ for (const copy of reviewCopies) {
1218
+ try {
1219
+ rmSync(copy, { recursive: true, force: true });
1220
+ }
1221
+ catch {
1222
+ }
1223
+ }
1224
+ }
864
1225
  if (attachDir) {
865
1226
  try {
866
1227
  rmSync(attachDir, { recursive: true, force: true });