@firefunc-agent/runner 0.9.14 → 0.9.35

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 (158) hide show
  1. package/README.md +184 -10
  2. package/dist/alive.d.ts +40 -0
  3. package/dist/alive.js +138 -0
  4. package/dist/api-fallback.d.ts +4 -2
  5. package/dist/api-fallback.js +26 -1
  6. package/dist/api.d.ts +66 -3
  7. package/dist/api.js +164 -3
  8. package/dist/brief-file.d.ts +15 -0
  9. package/dist/brief-file.js +36 -0
  10. package/dist/brief.d.ts +3 -0
  11. package/dist/brief.js +14 -4
  12. package/dist/build-caches.d.ts +7 -0
  13. package/dist/build-caches.js +63 -0
  14. package/dist/build-info.json +2 -2
  15. package/dist/checkpoint.d.ts +40 -0
  16. package/dist/checkpoint.js +98 -0
  17. package/dist/cli.js +184 -18
  18. package/dist/cloud-boot.d.ts +41 -0
  19. package/dist/cloud-boot.js +239 -0
  20. package/dist/command-activity.d.ts +23 -0
  21. package/dist/command-activity.js +89 -0
  22. package/dist/command-step.d.ts +58 -0
  23. package/dist/command-step.js +248 -0
  24. package/dist/config.d.ts +39 -0
  25. package/dist/config.js +23 -0
  26. package/dist/cut.d.ts +1 -1
  27. package/dist/cut.js +13 -3
  28. package/dist/daemon.js +364 -15
  29. package/dist/device-lease.d.ts +15 -0
  30. package/dist/device-lease.js +608 -0
  31. package/dist/editor/fs-server.d.ts +31 -0
  32. package/dist/editor/fs-server.js +159 -0
  33. package/dist/editor/relay-crypto.d.ts +68 -0
  34. package/dist/editor/relay-crypto.js +191 -0
  35. package/dist/editor/sessions.d.ts +50 -0
  36. package/dist/editor/sessions.js +279 -0
  37. package/dist/editor/worktree-of.d.ts +1 -0
  38. package/dist/editor/worktree-of.js +23 -0
  39. package/dist/editor/ws-client.d.ts +26 -0
  40. package/dist/editor/ws-client.js +227 -0
  41. package/dist/engine-account.d.ts +24 -0
  42. package/dist/engine-account.js +118 -0
  43. package/dist/engine-login.d.ts +12 -0
  44. package/dist/engine-login.js +88 -0
  45. package/dist/engine-models.d.ts +13 -0
  46. package/dist/engine-models.js +71 -0
  47. package/dist/engine-watch.d.ts +1 -0
  48. package/dist/engine-watch.js +22 -6
  49. package/dist/engines/antigravity.d.ts +2 -0
  50. package/dist/engines/antigravity.js +74 -4
  51. package/dist/engines/claude.js +22 -9
  52. package/dist/engines/codex.js +16 -2
  53. package/dist/engines/copilot.js +12 -0
  54. package/dist/engines/crush.d.ts +2 -0
  55. package/dist/engines/crush.js +58 -0
  56. package/dist/engines/cursor.js +12 -0
  57. package/dist/engines/gemini.js +14 -9
  58. package/dist/engines/index.d.ts +8 -0
  59. package/dist/engines/index.js +73 -1
  60. package/dist/engines/kilo.d.ts +2 -0
  61. package/dist/engines/kilo.js +63 -0
  62. package/dist/engines/opencode.d.ts +9 -0
  63. package/dist/engines/opencode.js +234 -0
  64. package/dist/engines/openhands.d.ts +10 -0
  65. package/dist/engines/openhands.js +271 -0
  66. package/dist/engines/pi.d.ts +10 -0
  67. package/dist/engines/pi.js +248 -0
  68. package/dist/engines/qwen.d.ts +8 -0
  69. package/dist/engines/qwen.js +153 -0
  70. package/dist/engines/sessions.d.ts +6 -0
  71. package/dist/engines/sessions.js +68 -0
  72. package/dist/engines/types.d.ts +3 -3
  73. package/dist/exec.d.ts +1 -0
  74. package/dist/exec.js +10 -4
  75. package/dist/firefunc/agents.d.ts +8 -1
  76. package/dist/firefunc/agents.js +53 -3
  77. package/dist/firefunc/auth.js +72 -19
  78. package/dist/firefunc/automations.d.ts +2 -0
  79. package/dist/firefunc/automations.js +290 -0
  80. package/dist/firefunc/cli.js +25 -0
  81. package/dist/firefunc/client.d.ts +5 -1
  82. package/dist/firefunc/client.js +12 -2
  83. package/dist/firefunc/config.d.ts +11 -1
  84. package/dist/firefunc/config.js +6 -4
  85. package/dist/firefunc/io.d.ts +1 -0
  86. package/dist/firefunc/main.js +34 -2
  87. package/dist/firefunc/oauth-login.d.ts +23 -0
  88. package/dist/firefunc/oauth-login.js +304 -0
  89. package/dist/firefunc/tasks.d.ts +4 -0
  90. package/dist/firefunc/tasks.js +89 -2
  91. package/dist/fleet-words.d.ts +2 -0
  92. package/dist/fleet-words.js +7 -0
  93. package/dist/git-auth.d.ts +15 -0
  94. package/dist/git-auth.js +39 -1
  95. package/dist/held.d.ts +3 -0
  96. package/dist/job.d.ts +26 -3
  97. package/dist/job.js +763 -152
  98. package/dist/keep-awake.d.ts +17 -0
  99. package/dist/keep-awake.js +90 -0
  100. package/dist/keep-local.d.ts +1 -1
  101. package/dist/keep-local.js +5 -3
  102. package/dist/limit.d.ts +9 -1
  103. package/dist/limit.js +260 -3
  104. package/dist/local-checks.d.ts +19 -0
  105. package/dist/local-checks.js +79 -0
  106. package/dist/locks.d.ts +18 -1
  107. package/dist/locks.js +249 -69
  108. package/dist/machine-commands.d.ts +21 -0
  109. package/dist/machine-commands.js +107 -0
  110. package/dist/machine-profile.d.ts +18 -0
  111. package/dist/machine-profile.js +69 -0
  112. package/dist/mcp-init.d.ts +2 -0
  113. package/dist/mcp-init.js +28 -0
  114. package/dist/mcp.d.ts +13 -1
  115. package/dist/mcp.js +48 -4
  116. package/dist/network.js +3 -2
  117. package/dist/openrouter.d.ts +15 -0
  118. package/dist/openrouter.js +39 -0
  119. package/dist/orphans.d.ts +4 -0
  120. package/dist/orphans.js +96 -4
  121. package/dist/pool.d.ts +1 -0
  122. package/dist/pool.js +25 -2
  123. package/dist/pr-title.d.ts +10 -0
  124. package/dist/pr-title.js +15 -0
  125. package/dist/recover.d.ts +3 -1
  126. package/dist/recover.js +27 -7
  127. package/dist/release-draft.d.ts +79 -0
  128. package/dist/release-draft.js +301 -0
  129. package/dist/resources.d.ts +86 -0
  130. package/dist/resources.js +217 -0
  131. package/dist/restart-idle.d.ts +23 -0
  132. package/dist/restart-idle.js +67 -0
  133. package/dist/run-attachments.d.ts +5 -0
  134. package/dist/run-attachments.js +14 -9
  135. package/dist/run-stops.d.ts +15 -0
  136. package/dist/run-stops.js +90 -0
  137. package/dist/run-temp.d.ts +12 -0
  138. package/dist/run-temp.js +57 -0
  139. package/dist/secret-scan.d.ts +5 -0
  140. package/dist/secret-scan.js +30 -0
  141. package/dist/self-upgrade.d.ts +36 -0
  142. package/dist/self-upgrade.js +78 -0
  143. package/dist/service.d.ts +7 -1
  144. package/dist/service.js +50 -7
  145. package/dist/sign-in.d.ts +42 -0
  146. package/dist/sign-in.js +243 -0
  147. package/dist/tool-call.d.ts +59 -0
  148. package/dist/tool-call.js +375 -0
  149. package/dist/transport.d.ts +26 -0
  150. package/dist/transport.js +118 -0
  151. package/dist/work-dir.d.ts +11 -0
  152. package/dist/work-dir.js +69 -0
  153. package/dist/worktree-report.d.ts +10 -0
  154. package/dist/worktree-report.js +17 -0
  155. package/dist/worktrees.d.ts +16 -1
  156. package/dist/worktrees.js +62 -17
  157. package/package.json +4 -4
  158. package/skill/firefunc/SKILL.md +22 -3
package/dist/mcp.js CHANGED
@@ -15,6 +15,8 @@ const CONFIG_PATHS = {
15
15
  gemini: '.gemini/settings.json',
16
16
  codex: null,
17
17
  copilot: '.firefunc-copilot-mcp.json',
18
+ opencode: '.firefunc-opencode.json',
19
+ antigravity: '.agents/plugins/firefunc-run/mcp_config.json',
18
20
  };
19
21
  export function mcpFormatForEngine(engine) {
20
22
  switch (engine) {
@@ -28,6 +30,10 @@ export function mcpFormatForEngine(engine) {
28
30
  return 'codex';
29
31
  case 'copilot_cli':
30
32
  return 'copilot';
33
+ case 'opencode':
34
+ return 'opencode';
35
+ case 'antigravity':
36
+ return 'antigravity';
31
37
  default:
32
38
  return null;
33
39
  }
@@ -258,7 +264,7 @@ function whyUnusable(spec, format) {
258
264
  if (spec.allowedTools.length === 0) {
259
265
  return 'no tools are declared for it, so it would connect and offer nothing';
260
266
  }
261
- const boundsTools = format !== 'cursor' && format !== 'codex';
267
+ const boundsTools = format !== 'cursor' && format !== 'codex' && format !== 'opencode';
262
268
  if (spec.writeTools?.length && !boundsTools) {
263
269
  return (`${format} has no per-tool allowlist, so every tool this server publishes would be callable — including the ${spec.writeTools.length} write tool(s) named in this spec, which is a mutation surface nothing here can bound. ` +
264
270
  BOUNDABLE_ENGINES_FIX);
@@ -342,6 +348,32 @@ function cursorBody(resolved) {
342
348
  }
343
349
  return `${JSON.stringify({ mcpServers: servers }, null, 2)}\n`;
344
350
  }
351
+ function opencodeBody(resolved) {
352
+ const servers = {};
353
+ for (const { spec, cred } of resolved) {
354
+ servers[spec.id] =
355
+ spec.transport === 'stdio'
356
+ ? { type: 'local', command: [spec.command, ...(spec.args ?? [])], enabled: true }
357
+ : {
358
+ type: 'remote',
359
+ url: spec.url,
360
+ headers: { ...spec.headers, ...credentialHeaders(cred) },
361
+ enabled: true,
362
+ };
363
+ }
364
+ return `${JSON.stringify({ $schema: 'https://opencode.ai/config.json', mcp: servers }, null, 2)}\n`;
365
+ }
366
+ function antigravityBody(resolved) {
367
+ const servers = {};
368
+ for (const { spec, cred } of resolved) {
369
+ const headers = { ...spec.headers, ...credentialHeaders(cred) };
370
+ servers[spec.id] =
371
+ spec.transport === 'stdio'
372
+ ? { command: spec.command, ...(spec.args ? { args: spec.args } : {}) }
373
+ : { serverUrl: spec.url, headers };
374
+ }
375
+ return `${JSON.stringify({ mcpServers: servers }, null, 2)}\n`;
376
+ }
345
377
  function geminiBody(resolved) {
346
378
  const servers = {};
347
379
  for (const { spec, cred } of resolved) {
@@ -423,7 +455,7 @@ export async function prepareMcp(opts) {
423
455
  `Fix: remove ${relative} from the repository, or run this project on an engine that reads a different path.`);
424
456
  return null;
425
457
  }
426
- const excluded = await excludeFromGit(opts.worktree, [`/${relative}`], log);
458
+ const excluded = await excludeFromGit(opts.worktree, opts.format === 'antigravity' ? [`/${dirname(relative)}/`] : [`/${relative}`], log);
427
459
  if (!excluded) {
428
460
  log('mcp: MCP is off for this run because the config could not be kept out of the commit. ' +
429
461
  'Fix: check that the runner can write .git/info/exclude in the repository checkout.');
@@ -540,8 +572,16 @@ export async function prepareMcp(opts) {
540
572
  ? claudeBody(resolved)
541
573
  : opts.format === 'cursor'
542
574
  ? cursorBody(resolved)
543
- : geminiBody(resolved);
575
+ : opts.format === 'opencode'
576
+ ? opencodeBody(resolved)
577
+ : opts.format === 'antigravity'
578
+ ? antigravityBody(resolved)
579
+ : geminiBody(resolved);
544
580
  writeFileSync(target, body, { mode: 0o600 });
581
+ if (opts.format === 'antigravity')
582
+ writeFileSync(join(dirname(target), 'plugin.json'), '{ "name": "firefunc-run" }\n', {
583
+ mode: 0o600,
584
+ });
545
585
  }
546
586
  catch (e) {
547
587
  log(`mcp: could not write ${relative} (${e.message}) — MCP is off for this run.`);
@@ -564,7 +604,10 @@ export async function prepareMcp(opts) {
564
604
  if (!writtenPath)
565
605
  return;
566
606
  try {
567
- rmSync(writtenPath, { force: true });
607
+ if (opts.format === 'antigravity')
608
+ rmSync(dirname(writtenPath), { recursive: true, force: true });
609
+ else
610
+ rmSync(writtenPath, { force: true });
568
611
  }
569
612
  catch {
570
613
  }
@@ -608,4 +651,5 @@ export function mcpFromContext(ctx, format) {
608
651
  return null;
609
652
  return raw;
610
653
  }
654
+ export { parseServer as parseMcpServerSpec, readCachedLogin as cachedMcpLogin };
611
655
  //# sourceMappingURL=mcp.js.map
package/dist/network.js CHANGED
@@ -13,7 +13,8 @@ const NETWORK_SIGNS = [
13
13
  /\bfailed to connect\b/i,
14
14
  /\bconnection (?:refused|reset|timed out|error)\b/i,
15
15
  /\bnetwork (?:error|is unreachable|unreachable)\b/i,
16
- /\bunable to (?:access|connect)\b/i,
16
+ /\bunable to (?:access|connect|reach)\b/i,
17
+ /\bcan(?:'|’|no)?t reach the (?:api|server)\b/i,
17
18
  /\bthe remote end hung up\b/i,
18
19
  /\bunexpected disconnect\b/i,
19
20
  /\bHTTP\/?[12](?:\.[01])? 50[234]\b/i,
@@ -31,7 +32,7 @@ export function isNetworkError(input) {
31
32
  export function networkFailureHint(text) {
32
33
  if (!isNetworkError(text))
33
34
  return null;
34
- const m = /(fetch failed|ECONNRESET|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|socket hang up|connection (?:refused|reset|timed out|error)|network (?:error|is unreachable)|TLS handshake|could not resolve host|50[234])/i.exec(text);
35
+ const m = /(fetch failed|ECONNRESET|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|socket hang up|connection (?:refused|reset|timed out|error)|network (?:error|is unreachable)|TLS handshake|could not resolve host|can(?:'|’|no)?t reach the (?:api|server)|50[234])/i.exec(text);
35
36
  return `the network went away (${m?.[1] ?? 'transport error'})`;
36
37
  }
37
38
  export const netDeps = {
@@ -0,0 +1,15 @@
1
+ import type { RunnerConfig } from './config.js';
2
+ export declare const OPENROUTER_BASE_URL = "https://openrouter.ai/api";
3
+ export declare const OPENROUTER_KEY_VAR = "OPENROUTER_API_KEY";
4
+ export declare function openRouterKeyOf(cfg: Pick<RunnerConfig, 'claudeEnv'>, env?: NodeJS.ProcessEnv): string | null;
5
+ export declare function openRouterClaudeEnv(runEnv: NodeJS.ProcessEnv, key: string): NodeJS.ProcessEnv;
6
+ export type JobEndpoint = {
7
+ ok: true;
8
+ cfg: RunnerConfig;
9
+ note: string | null;
10
+ } | {
11
+ ok: false;
12
+ reason: string;
13
+ fix: string;
14
+ };
15
+ export declare function jobClaudeEndpoint(engine: string, want: unknown, cfg: RunnerConfig, machine: string, env?: NodeJS.ProcessEnv): JobEndpoint;
@@ -0,0 +1,39 @@
1
+ export const OPENROUTER_BASE_URL = 'https://openrouter.ai/api';
2
+ export const OPENROUTER_KEY_VAR = 'OPENROUTER_API_KEY';
3
+ export function openRouterKeyOf(cfg, env = process.env) {
4
+ const v = (cfg.claudeEnv?.[OPENROUTER_KEY_VAR] ?? env[OPENROUTER_KEY_VAR] ?? '').trim();
5
+ return v ? v : null;
6
+ }
7
+ export function openRouterClaudeEnv(runEnv, key) {
8
+ return {
9
+ ...runEnv,
10
+ ANTHROPIC_BASE_URL: OPENROUTER_BASE_URL,
11
+ ANTHROPIC_AUTH_TOKEN: key,
12
+ ANTHROPIC_API_KEY: '',
13
+ CLAUDE_CODE_OAUTH_TOKEN: undefined,
14
+ };
15
+ }
16
+ export function jobClaudeEndpoint(engine, want, cfg, machine, env = process.env) {
17
+ if (want !== 'openrouter')
18
+ return { ok: true, cfg, note: null };
19
+ if (engine !== 'claude_code') {
20
+ return {
21
+ ok: false,
22
+ reason: `This job asks for the OpenRouter endpoint, a setting of Claude Code only, and it runs on ${engine}.`,
23
+ fix: 'Set the Claude Code endpoint back to Anthropic for this work in FireFunc, or run it on Claude Code.',
24
+ };
25
+ }
26
+ if (!openRouterKeyOf(cfg, env)) {
27
+ return {
28
+ ok: false,
29
+ reason: `This job's Claude Code sends its requests to OpenRouter, and ${OPENROUTER_KEY_VAR} is not set on ${machine}.`,
30
+ fix: `Set ${OPENROUTER_KEY_VAR} on this machine (in the environment the runner starts in, or in the runner config's claudeEnv), restart the runner, and run the task again — or set the Claude Code endpoint back to Anthropic. FireFunc never stores the key.`,
31
+ };
32
+ }
33
+ return {
34
+ ok: true,
35
+ cfg: { ...cfg, claudeEndpoint: 'openrouter' },
36
+ note: `OpenRouter (${OPENROUTER_KEY_VAR} from this machine)`,
37
+ };
38
+ }
39
+ //# sourceMappingURL=openrouter.js.map
package/dist/orphans.d.ts CHANGED
@@ -19,9 +19,12 @@ export type OrphanScope = {
19
19
  };
20
20
  export type SelectScope = Omit<OrphanScope, 'groups'> & {
21
21
  groups?: number[];
22
+ spareDevices?: boolean;
22
23
  };
23
24
  export declare function groupsStillOurs(groups: EngineGroup[], rows: ProcessRow[]): Promise<number[]>;
24
25
  export declare function selectOrphans(rows: ProcessRow[], cwds: Map<number, string>, scope: SelectScope): number[];
26
+ export declare function isDeviceProcess(command: string): boolean;
27
+ export declare function deviceProcesses(rows: ProcessRow[]): Set<number>;
25
28
  export declare function isAlive(pid: number): boolean;
26
29
  export type OrphanSweep = {
27
30
  stopped: Array<{
@@ -38,3 +41,4 @@ export declare function reviewCopiesOf(worktree: string): string[];
38
41
  export declare function trackEngineGroup(pgid: number): void;
39
42
  export declare function untrackEngineGroup(pgid: number): void;
40
43
  export declare function signalEngineGroups(sig: NodeJS.Signals): number;
44
+ export declare function signalGroupSparingDevices(pgid: number, sig: NodeJS.Signals): boolean;
package/dist/orphans.js CHANGED
@@ -1,5 +1,7 @@
1
+ import { execFileSync } from 'node:child_process';
1
2
  import { readlinkSync, readdirSync, realpathSync } from 'node:fs';
2
3
  import { tmpdir } from 'node:os';
4
+ import { workRoots } from './work-dir.js';
3
5
  import { basename, join } from 'node:path';
4
6
  import { exec } from './exec.js';
5
7
  export async function listProcesses() {
@@ -10,8 +12,11 @@ export async function listProcesses() {
10
12
  }).catch(() => null);
11
13
  if (!ps || ps.code !== 0)
12
14
  return [];
15
+ return parseProcesses(ps.stdout);
16
+ }
17
+ function parseProcesses(stdout) {
13
18
  const rows = [];
14
- for (const line of ps.stdout.split('\n')) {
19
+ for (const line of stdout.split('\n')) {
15
20
  const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/.exec(line);
16
21
  if (!m)
17
22
  continue;
@@ -96,6 +101,9 @@ export function selectOrphans(rows, cwds, scope) {
96
101
  for (let p = byPid.get(self)?.ppid; p && !protectedPids.has(p); p = byPid.get(p)?.ppid) {
97
102
  protectedPids.add(p);
98
103
  }
104
+ if (scope.spareDevices !== false)
105
+ for (const pid of deviceProcesses(rows))
106
+ protectedPids.add(pid);
99
107
  const roots = scope.roots.flatMap(spellings);
100
108
  const inRoot = roots.map((r) => new RegExp(`${escapeRe(r)}(?:/|\\s|$|['"])`));
101
109
  const review = scope.reviewCopiesOf
@@ -129,6 +137,40 @@ export function selectOrphans(rows, cwds, scope) {
129
137
  }
130
138
  return [...hit].sort((a, b) => a - b);
131
139
  }
140
+ const DEVICE_PROGRAMS = new Set(['emulator', 'netsimd', 'launchd_sim']);
141
+ export function isDeviceProcess(command) {
142
+ const program = command.trim().split(/\s+/)[0] ?? '';
143
+ const name = basename(program);
144
+ if (DEVICE_PROGRAMS.has(name))
145
+ return true;
146
+ if (/^(?:qemu-system-|emulator64-)/.test(name))
147
+ return true;
148
+ if (name === 'crashpad_handler' && /\/emulator\//.test(program))
149
+ return true;
150
+ if (name === 'adb' && /\s(?:fork-server|server|start-server)\b/.test(command))
151
+ return true;
152
+ return /\/CoreSimulator[./]|\/Simulator\.app\//.test(program);
153
+ }
154
+ export function deviceProcesses(rows) {
155
+ const spared = new Set(rows.filter((r) => isDeviceProcess(r.command)).map((r) => r.pid));
156
+ const children = new Map();
157
+ for (const r of rows) {
158
+ const list = children.get(r.ppid) ?? [];
159
+ list.push(r.pid);
160
+ children.set(r.ppid, list);
161
+ }
162
+ const queue = [...spared];
163
+ while (queue.length) {
164
+ const pid = queue.shift();
165
+ for (const child of children.get(pid) ?? []) {
166
+ if (spared.has(child))
167
+ continue;
168
+ spared.add(child);
169
+ queue.push(child);
170
+ }
171
+ }
172
+ return spared;
173
+ }
132
174
  export function isAlive(pid) {
133
175
  if (!Number.isInteger(pid) || pid <= 0)
134
176
  return false;
@@ -161,10 +203,19 @@ export async function killOrphans(scope, opts = {}) {
161
203
  return result;
162
204
  const groups = await groupsStillOurs(scope.groups ?? [], rows);
163
205
  const select = { ...scope, groups };
206
+ const devices = deviceProcesses(rows);
207
+ const holdsDevice = new Set(rows.filter((r) => devices.has(r.pid)).map((r) => r.pgid));
164
208
  for (const g of groups)
165
- signal(-g, 'SIGTERM');
209
+ if (!holdsDevice.has(g))
210
+ signal(-g, 'SIGTERM');
166
211
  const cwds = await workingDirs(rows.map((r) => r.pid));
167
212
  const pids = selectOrphans(rows, cwds, select);
213
+ const wouldStop = new Set(selectOrphans(rows, cwds, { ...select, spareDevices: false }));
214
+ const kept = rows.filter((r) => wouldStop.has(r.pid) && isDeviceProcess(r.command));
215
+ if (kept.length > 0) {
216
+ opts.log?.(`left ${kept.map((r) => `${programOf(r.command)} (${r.pid})`).join(', ')} running: ` +
217
+ 'a device belongs to the machine and other sessions may be using it, so a run never stops it');
218
+ }
168
219
  const byPid = new Map(rows.map((r) => [r.pid, r]));
169
220
  for (const pid of pids) {
170
221
  signal(pid, 'SIGTERM');
@@ -202,7 +253,7 @@ export async function killOrphans(scope, opts = {}) {
202
253
  export function reviewCopiesOf(worktree) {
203
254
  const base = basename(worktree);
204
255
  const out = new Set();
205
- for (const dir of new Set([tmpdir(), '/tmp'])) {
256
+ for (const dir of new Set([tmpdir(), '/tmp', ...workRoots()])) {
206
257
  let names;
207
258
  try {
208
259
  names = readdirSync(dir);
@@ -229,7 +280,48 @@ export function signalEngineGroups(sig) {
229
280
  if (process.platform === 'win32')
230
281
  return 0;
231
282
  for (const g of engineGroups)
232
- signal(-g, sig);
283
+ signalGroupSparingDevices(g, sig);
233
284
  return engineGroups.size;
234
285
  }
286
+ function listProcessesNow() {
287
+ try {
288
+ const out = execFileSync('ps', ['-A', '-ww', '-o', 'pid=,ppid=,pgid=,command='], {
289
+ encoding: 'utf8',
290
+ timeout: 10_000,
291
+ stdio: ['ignore', 'pipe', 'ignore'],
292
+ });
293
+ return parseProcesses(out);
294
+ }
295
+ catch {
296
+ return [];
297
+ }
298
+ }
299
+ export function signalGroupSparingDevices(pgid, sig) {
300
+ if (!(pgid > 1))
301
+ return false;
302
+ const rows = listProcessesNow();
303
+ const devices = deviceProcesses(rows);
304
+ const members = rows.filter((r) => r.pgid === pgid);
305
+ if (!members.some((r) => devices.has(r.pid))) {
306
+ try {
307
+ process.kill(-pgid, sig);
308
+ return true;
309
+ }
310
+ catch {
311
+ return false;
312
+ }
313
+ }
314
+ let any = false;
315
+ for (const r of members) {
316
+ if (devices.has(r.pid))
317
+ continue;
318
+ try {
319
+ process.kill(r.pid, sig);
320
+ any = true;
321
+ }
322
+ catch {
323
+ }
324
+ }
325
+ return any;
326
+ }
235
327
  //# sourceMappingURL=orphans.js.map
package/dist/pool.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export type JobPoolDeps<J> = {
2
2
  maxParallel: number | (() => number);
3
+ onDrained?: () => void;
3
4
  stopping: () => boolean;
4
5
  claim: () => Promise<J | null>;
5
6
  run: (job: J) => Promise<void>;
package/dist/pool.js CHANGED
@@ -5,7 +5,11 @@ export async function runJobPool(deps) {
5
5
  const maxIdleMs = Math.max(baseIdleMs, deps.maxIdleDelayMs ?? 8_000);
6
6
  let emptyClaims = 0;
7
7
  const idleDelay = () => Math.min(maxIdleMs, baseIdleMs * 2 ** Math.min(emptyClaims, 10));
8
- const cap = () => Math.max(1, Math.floor(typeof deps.maxParallel === 'function' ? deps.maxParallel() : deps.maxParallel));
8
+ const cap = () => {
9
+ const n = Math.floor(typeof deps.maxParallel === 'function' ? deps.maxParallel() : deps.maxParallel);
10
+ return Number.isFinite(n) ? Math.max(0, n) : 1;
11
+ };
12
+ let drainedTold = false;
9
13
  const active = new Set();
10
14
  const now = deps.now ?? (() => Date.now());
11
15
  const heartbeatMs = deps.heartbeatMs ?? 30_000;
@@ -58,7 +62,26 @@ export async function runJobPool(deps) {
58
62
  }
59
63
  continue;
60
64
  }
61
- if (active.size >= cap()) {
65
+ const limit = cap();
66
+ if (limit === 0) {
67
+ if (active.size === 0 && !drainedTold) {
68
+ drainedTold = true;
69
+ deps.onDrained?.();
70
+ }
71
+ if (deps.heartbeat) {
72
+ await beat({ draining: true, paused: false });
73
+ await napUntilBeat();
74
+ }
75
+ else if (active.size > 0) {
76
+ await Promise.race([...active, sleep(idleDelay())]);
77
+ }
78
+ else {
79
+ await sleep(idleDelay());
80
+ }
81
+ continue;
82
+ }
83
+ drainedTold = false;
84
+ if (active.size >= limit) {
62
85
  if (deps.heartbeat) {
63
86
  await beat({ draining: false, paused: false });
64
87
  await napUntilBeat();
@@ -14,3 +14,13 @@ export declare function parseAgentPullRequest(text: string): {
14
14
  title: string;
15
15
  body: string;
16
16
  } | null;
17
+ export declare function provenanceTrailers(job: {
18
+ provenance?: {
19
+ trailers?: string[];
20
+ } | null;
21
+ }): string | null;
22
+ export declare function withProvenanceFooter(body: string, job: {
23
+ provenance?: {
24
+ prFooter?: string | null;
25
+ } | null;
26
+ }): string;
package/dist/pr-title.js CHANGED
@@ -78,4 +78,19 @@ export function parseAgentPullRequest(text) {
78
78
  .slice(0, 60_000);
79
79
  return { title, body };
80
80
  }
81
+ export function provenanceTrailers(job) {
82
+ const lines = (job.provenance?.trailers ?? [])
83
+ .filter((t) => typeof t === 'string')
84
+ .map((t) => t.replace(/[\r\n]+/g, ' ').trim())
85
+ .filter((t) => /^[A-Za-z][\w-]{0,40}: \S.{0,300}$/.test(t))
86
+ .slice(0, 5);
87
+ return lines.length ? lines.join('\n') : null;
88
+ }
89
+ export function withProvenanceFooter(body, job) {
90
+ const footer = job.provenance?.prFooter
91
+ ?.replace(/[\r\n]+/g, ' ')
92
+ .trim()
93
+ .slice(0, 500);
94
+ return footer ? `${body.trimEnd()}\n\n${footer}` : body;
95
+ }
81
96
  //# sourceMappingURL=pr-title.js.map
package/dist/recover.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { RunnerApi } from './api.js';
2
- export declare function lostSentence(machine: string): string;
2
+ import { type HeldRun } from './held.js';
3
+ export declare function lostSentence(machine: string, kept?: boolean): string;
4
+ export declare function keepLostSession(runnerDir: string, rec: HeldRun, now?: number): boolean;
3
5
  export type RecoverDeps = {
4
6
  runnerDir: string;
5
7
  api: Pick<RunnerApi, 'result' | 'probe'>;
package/dist/recover.js CHANGED
@@ -1,20 +1,36 @@
1
1
  import { existsSync, rmSync } from 'node:fs';
2
2
  import { basename } from 'node:path';
3
- import { keptWorktrees } from './cut.js';
3
+ import { keepUntil, keptWorktrees, saveCut } from './cut.js';
4
4
  import { heldByGoneProcesses, releaseHeld } from './held.js';
5
5
  import { isNetworkError, withNetworkRetry } from './network.js';
6
6
  import { killOrphans, reviewCopiesOf } from './orphans.js';
7
7
  import { listPendingResults, savePendingResult } from './pending.js';
8
8
  import { canonicalPath, removeRunnerWorktree } from './worktrees.js';
9
- export function lostSentence(machine) {
9
+ export function lostSentence(machine, kept = false) {
10
10
  return (`The attempt did not finish: the runner on ${machine} stopped while it was running — ` +
11
11
  'the runner process was restarted, stopped or crashed — and the process that took over ' +
12
12
  'does not hold it, so nothing more will be reported for it. What it left running on the ' +
13
- 'machine was stopped and its worktree removed. Re-run the task.');
13
+ (kept
14
+ ? 'machine was stopped; its worktree and the engine’s session are kept on this machine for a day, so Re-run continues it from where it stopped.'
15
+ : 'machine was stopped and its worktree removed. Re-run the task.'));
14
16
  }
15
- async function clearUp(rec, keep, log) {
17
+ export function keepLostSession(runnerDir, rec, now = Date.now()) {
18
+ if (!rec.resume || !rec.worktree || !existsSync(rec.worktree))
19
+ return false;
20
+ const cutAt = now;
21
+ return saveCut(runnerDir, {
22
+ ...rec.resume,
23
+ runId: rec.runId,
24
+ worktree: rec.worktree,
25
+ resetsAt: null,
26
+ cutAt: new Date(cutAt).toISOString(),
27
+ keepUntil: keepUntil(null, cutAt),
28
+ reason: 'lost',
29
+ });
30
+ }
31
+ async function clearUp(rec, keep, log, keepSession) {
16
32
  const roots = [rec.worktree, ...(rec.scratch ?? [])].filter((p) => !!p);
17
- const kept = rec.worktree ? keep.has(canonicalPath(rec.worktree)) : false;
33
+ const kept = keepSession || (rec.worktree ? keep.has(canonicalPath(rec.worktree)) : false);
18
34
  const copies = rec.worktree ? reviewCopiesOf(rec.worktree) : [];
19
35
  await killOrphans({
20
36
  roots: [...roots, ...copies],
@@ -64,11 +80,15 @@ export async function recoverPreviousProcess(deps) {
64
80
  let offline = false;
65
81
  for (const rec of gone) {
66
82
  try {
67
- await clearUp(rec, keep, deps.log);
83
+ const keptSession = !pending.has(rec.runId) && keepLostSession(deps.runnerDir, rec);
84
+ if (keptSession) {
85
+ deps.log(`kept run ${rec.runId}'s worktree and session for the task's next run here (${rec.worktree})`);
86
+ }
87
+ await clearUp(rec, keep, deps.log, keptSession);
68
88
  if (!pending.has(rec.runId)) {
69
89
  const payload = {
70
90
  status: 'failed',
71
- error: lostSentence(deps.machine),
91
+ error: lostSentence(deps.machine, keptSession),
72
92
  lost: true,
73
93
  };
74
94
  try {
@@ -0,0 +1,79 @@
1
+ import type { GitCredential } from './git-auth.js';
2
+ import { type PreparedAttach } from './run-attachments.js';
3
+ export declare const RELEASE_FOLDER = ".firefunc/release";
4
+ export declare const RELEASE_MANIFEST = "release.json";
5
+ export declare const MAX_RELEASE_FILES = 20;
6
+ export declare const MAX_RELEASE_FILE_BYTES: number;
7
+ export declare const MAX_RELEASE_TOTAL_BYTES: number;
8
+ export type ReleaseOffer = {
9
+ folder?: string;
10
+ manifest?: string;
11
+ tag?: string | null;
12
+ name?: string | null;
13
+ prerelease?: boolean;
14
+ maxFiles?: number;
15
+ maxFileBytes?: number;
16
+ maxTotalBytes?: number;
17
+ };
18
+ export type ReleaseReport = {
19
+ draftId: number;
20
+ tag: string;
21
+ url: string | null;
22
+ files: Array<{
23
+ name: string;
24
+ size: number;
25
+ }>;
26
+ skipped: Array<{
27
+ name: string;
28
+ why: string;
29
+ }>;
30
+ } | {
31
+ staged: false;
32
+ why: string;
33
+ tag: string | null;
34
+ };
35
+ export declare function releaseRule(offer: ReleaseOffer): string;
36
+ export declare function releaseTagProblem(tag: unknown): string | null;
37
+ export declare function prepareReleaseFolder(worktree: string, log: (m: string) => void): PreparedAttach;
38
+ type Manifest = {
39
+ tag: string | null;
40
+ name: string | null;
41
+ notes: string | null;
42
+ prerelease: boolean | null;
43
+ };
44
+ export type ReleaseScan = {
45
+ manifest: Manifest | {
46
+ problem: string;
47
+ } | null;
48
+ files: Array<{
49
+ name: string;
50
+ path: string;
51
+ size: number;
52
+ }>;
53
+ skipped: Array<{
54
+ name: string;
55
+ why: string;
56
+ }>;
57
+ };
58
+ export declare function scanReleaseFolder(dir: string, offer?: ReleaseOffer): ReleaseScan;
59
+ export type AssetUploader = (opts: {
60
+ url: string;
61
+ token: string;
62
+ path: string;
63
+ size: number;
64
+ }) => Promise<{
65
+ status: number;
66
+ }>;
67
+ export declare function assetUrl(uploadUrl: string | undefined, name: string): string | null;
68
+ export declare function stageDraftRelease(opts: {
69
+ repo: string;
70
+ base: string | null;
71
+ offer: ReleaseOffer;
72
+ dir: string;
73
+ cred: Pick<GitCredential, 'token'>;
74
+ log: (m: string) => void;
75
+ fetcher?: typeof fetch;
76
+ upload?: AssetUploader;
77
+ apiBase?: string;
78
+ }): Promise<ReleaseReport>;
79
+ export {};