@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
@@ -0,0 +1,235 @@
1
+ import { readlinkSync, readdirSync, realpathSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { basename, join } from 'node:path';
4
+ import { exec } from './exec.js';
5
+ export async function listProcesses() {
6
+ if (process.platform === 'win32')
7
+ return [];
8
+ const ps = await exec('ps', ['-A', '-ww', '-o', 'pid=,ppid=,pgid=,command='], {
9
+ timeoutMs: 20_000,
10
+ }).catch(() => null);
11
+ if (!ps || ps.code !== 0)
12
+ return [];
13
+ const rows = [];
14
+ for (const line of ps.stdout.split('\n')) {
15
+ const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/.exec(line);
16
+ if (!m)
17
+ continue;
18
+ rows.push({ pid: Number(m[1]), ppid: Number(m[2]), pgid: Number(m[3]), command: m[4].trim() });
19
+ }
20
+ return rows;
21
+ }
22
+ export async function workingDirs(pids) {
23
+ const out = new Map();
24
+ if (process.platform === 'win32')
25
+ return out;
26
+ if (process.platform === 'linux') {
27
+ for (const pid of pids) {
28
+ try {
29
+ out.set(pid, readlinkSync(`/proc/${pid}/cwd`).replace(/ \(deleted\)$/, ''));
30
+ }
31
+ catch {
32
+ }
33
+ }
34
+ return out;
35
+ }
36
+ const uid = process.getuid?.();
37
+ const r = await exec('lsof', ['-a', '-d', 'cwd', ...(uid === undefined ? [] : ['-u', String(uid)]), '-Fpn'], { timeoutMs: 30_000 }).catch(() => null);
38
+ if (!r?.stdout)
39
+ return out;
40
+ let pid = 0;
41
+ for (const line of r.stdout.split('\n')) {
42
+ if (line.startsWith('p'))
43
+ pid = Number(line.slice(1));
44
+ else if (line.startsWith('n') && pid > 0)
45
+ out.set(pid, line.slice(1));
46
+ }
47
+ return out;
48
+ }
49
+ function spellings(path) {
50
+ const clean = path.replace(/\/+$/, '');
51
+ const out = new Set([clean]);
52
+ try {
53
+ out.add(realpathSync(clean));
54
+ }
55
+ catch {
56
+ }
57
+ for (const p of [...out]) {
58
+ if (p.startsWith('/private/'))
59
+ out.add(p.slice('/private'.length));
60
+ else if (p.startsWith('/var/') || p.startsWith('/tmp/'))
61
+ out.add(`/private${p}`);
62
+ }
63
+ return [...out].filter((p) => p.length > 1);
64
+ }
65
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
66
+ async function startedAtOf(pid) {
67
+ const r = await exec('ps', ['-o', 'etime=', '-p', String(pid)], { timeoutMs: 10_000 }).catch(() => null);
68
+ const m = /^\s*(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)\s*$/.exec(r?.stdout ?? '');
69
+ if (!r || r.code !== 0 || !m)
70
+ return null;
71
+ const secs = Number(m[1] ?? 0) * 86_400 + Number(m[2] ?? 0) * 3_600 + Number(m[3]) * 60 + Number(m[4]);
72
+ return Date.now() - secs * 1000;
73
+ }
74
+ export async function groupsStillOurs(groups, rows) {
75
+ const out = [];
76
+ for (const g of groups) {
77
+ if (!(g.pgid > 1))
78
+ continue;
79
+ const leader = rows.some((r) => r.pid === g.pgid);
80
+ if (!leader) {
81
+ out.push(g.pgid);
82
+ continue;
83
+ }
84
+ if (g.leaderExited)
85
+ continue;
86
+ const started = await startedAtOf(g.pgid);
87
+ if (started !== null && Math.abs(started - g.startedAt) < 15_000)
88
+ out.push(g.pgid);
89
+ }
90
+ return out;
91
+ }
92
+ export function selectOrphans(rows, cwds, scope) {
93
+ const self = scope.self ?? process.pid;
94
+ const byPid = new Map(rows.map((r) => [r.pid, r]));
95
+ const protectedPids = new Set([0, 1, self]);
96
+ for (let p = byPid.get(self)?.ppid; p && !protectedPids.has(p); p = byPid.get(p)?.ppid) {
97
+ protectedPids.add(p);
98
+ }
99
+ const roots = scope.roots.flatMap(spellings);
100
+ const inRoot = roots.map((r) => new RegExp(`${escapeRe(r)}(?:/|\\s|$|['"])`));
101
+ const review = scope.reviewCopiesOf
102
+ ? new RegExp(`/ff-review-[^/\\s]*-${escapeRe(scope.reviewCopiesOf)}(?:/|\\s|$|['"])`)
103
+ : null;
104
+ const groups = new Set((scope.groups ?? []).filter((g) => g > 1));
105
+ const matches = (text) => inRoot.some((re) => re.test(text)) || !!review?.test(text);
106
+ const hit = new Set();
107
+ for (const r of rows) {
108
+ if (protectedPids.has(r.pid))
109
+ continue;
110
+ const cwd = cwds.get(r.pid);
111
+ if (groups.has(r.pgid) || (cwd && matches(`${cwd}/`)) || matches(r.command))
112
+ hit.add(r.pid);
113
+ }
114
+ const children = new Map();
115
+ for (const r of rows) {
116
+ const list = children.get(r.ppid) ?? [];
117
+ list.push(r.pid);
118
+ children.set(r.ppid, list);
119
+ }
120
+ const queue = [...hit];
121
+ while (queue.length) {
122
+ const pid = queue.shift();
123
+ for (const child of children.get(pid) ?? []) {
124
+ if (hit.has(child) || protectedPids.has(child))
125
+ continue;
126
+ hit.add(child);
127
+ queue.push(child);
128
+ }
129
+ }
130
+ return [...hit].sort((a, b) => a - b);
131
+ }
132
+ export function isAlive(pid) {
133
+ if (!Number.isInteger(pid) || pid <= 0)
134
+ return false;
135
+ try {
136
+ process.kill(pid, 0);
137
+ return true;
138
+ }
139
+ catch (e) {
140
+ return e.code === 'EPERM';
141
+ }
142
+ }
143
+ function signal(pid, sig) {
144
+ try {
145
+ process.kill(pid, sig);
146
+ }
147
+ catch {
148
+ }
149
+ }
150
+ function programOf(command) {
151
+ const first = command.split(/\s+/)[0] ?? '';
152
+ return basename(first) || 'a process';
153
+ }
154
+ export async function killOrphans(scope, opts = {}) {
155
+ const result = { stopped: [], survivors: [] };
156
+ try {
157
+ if (process.platform === 'win32')
158
+ return result;
159
+ const rows = await listProcesses();
160
+ if (rows.length === 0)
161
+ return result;
162
+ const groups = await groupsStillOurs(scope.groups ?? [], rows);
163
+ const select = { ...scope, groups };
164
+ for (const g of groups)
165
+ signal(-g, 'SIGTERM');
166
+ const cwds = await workingDirs(rows.map((r) => r.pid));
167
+ const pids = selectOrphans(rows, cwds, select);
168
+ const byPid = new Map(rows.map((r) => [r.pid, r]));
169
+ for (const pid of pids) {
170
+ signal(pid, 'SIGTERM');
171
+ result.stopped.push({ pid, program: programOf(byPid.get(pid)?.command ?? '') });
172
+ }
173
+ if (pids.length === 0)
174
+ return result;
175
+ await new Promise((r) => setTimeout(r, opts.graceMs ?? 1500));
176
+ for (const pid of pids)
177
+ if (isAlive(pid))
178
+ signal(pid, 'SIGKILL');
179
+ await new Promise((r) => setTimeout(r, 200));
180
+ const again = await listProcesses();
181
+ const againCwds = await workingDirs(again.map((r) => r.pid));
182
+ result.survivors = selectOrphans(again, againCwds, { ...select, groups: [] });
183
+ for (const pid of result.survivors)
184
+ signal(pid, 'SIGKILL');
185
+ if (result.stopped.length > 0) {
186
+ opts.log?.(`stopped ${result.stopped.length} process(es) the session left running in its checkout: ` +
187
+ result.stopped
188
+ .slice(0, 8)
189
+ .map((p) => `${p.program} (${p.pid})`)
190
+ .join(', ') +
191
+ (result.stopped.length > 8 ? `, and ${result.stopped.length - 8} more` : ''));
192
+ }
193
+ if (result.survivors.length > 0) {
194
+ opts.log?.(`still running in the checkout after SIGKILL: ${result.survivors.join(', ')} — the directory is removed anyway`);
195
+ }
196
+ }
197
+ catch (e) {
198
+ opts.log?.(`could not look for processes left in the checkout: ${e.message}`);
199
+ }
200
+ return result;
201
+ }
202
+ export function reviewCopiesOf(worktree) {
203
+ const base = basename(worktree);
204
+ const out = new Set();
205
+ for (const dir of new Set([tmpdir(), '/tmp'])) {
206
+ let names;
207
+ try {
208
+ names = readdirSync(dir);
209
+ }
210
+ catch {
211
+ continue;
212
+ }
213
+ for (const n of names) {
214
+ if (n.startsWith('ff-review-') && n.endsWith(`-${base}`))
215
+ out.add(join(dir, n));
216
+ }
217
+ }
218
+ return [...out];
219
+ }
220
+ const engineGroups = new Set();
221
+ export function trackEngineGroup(pgid) {
222
+ if (pgid > 1)
223
+ engineGroups.add(pgid);
224
+ }
225
+ export function untrackEngineGroup(pgid) {
226
+ engineGroups.delete(pgid);
227
+ }
228
+ export function signalEngineGroups(sig) {
229
+ if (process.platform === 'win32')
230
+ return 0;
231
+ for (const g of engineGroups)
232
+ signal(-g, sig);
233
+ return engineGroups.size;
234
+ }
235
+ //# sourceMappingURL=orphans.js.map
package/dist/pool.d.ts CHANGED
@@ -8,5 +8,12 @@ export type JobPoolDeps<J> = {
8
8
  idleDelayMs?: number;
9
9
  maxIdleDelayMs?: number;
10
10
  sleep?: (ms: number) => Promise<void>;
11
+ paused?: () => boolean;
12
+ heartbeat?: (state: {
13
+ draining: boolean;
14
+ paused: boolean;
15
+ }) => Promise<J | null>;
16
+ heartbeatMs?: number;
17
+ now?: () => number;
11
18
  };
12
19
  export declare function runJobPool<J>(deps: JobPoolDeps<J>): Promise<void>;
package/dist/pool.js CHANGED
@@ -7,13 +7,67 @@ export async function runJobPool(deps) {
7
7
  const idleDelay = () => Math.min(maxIdleMs, baseIdleMs * 2 ** Math.min(emptyClaims, 10));
8
8
  const cap = () => Math.max(1, Math.floor(typeof deps.maxParallel === 'function' ? deps.maxParallel() : deps.maxParallel));
9
9
  const active = new Set();
10
- while (!deps.stopping()) {
10
+ const now = deps.now ?? (() => Date.now());
11
+ const heartbeatMs = deps.heartbeatMs ?? 30_000;
12
+ let lastContact = now();
13
+ const spawn = (job) => {
14
+ deps.onStart?.(job, active.size + 1);
15
+ const p = deps.run(job).finally(() => {
16
+ active.delete(p);
17
+ });
18
+ active.add(p);
19
+ };
20
+ const beat = async (state) => {
21
+ if (!deps.heartbeat || now() - lastContact < heartbeatMs)
22
+ return;
23
+ lastContact = now();
24
+ const job = await deps.heartbeat(state).catch(() => null);
25
+ if (job != null)
26
+ spawn(job);
27
+ };
28
+ const napUntilBeat = async () => {
29
+ const wait = Math.max(50, heartbeatMs - (now() - lastContact));
30
+ if (active.size > 0)
31
+ await Promise.race([...active, sleep(wait)]);
32
+ else
33
+ await sleep(wait);
34
+ };
35
+ for (;;) {
36
+ if (deps.stopping()) {
37
+ if (active.size === 0)
38
+ break;
39
+ if (!deps.heartbeat) {
40
+ await Promise.race(active);
41
+ continue;
42
+ }
43
+ await beat({ draining: true, paused: false });
44
+ if (active.size > 0)
45
+ await napUntilBeat();
46
+ continue;
47
+ }
48
+ if (deps.paused?.()) {
49
+ if (deps.heartbeat) {
50
+ await beat({ draining: false, paused: true });
51
+ await napUntilBeat();
52
+ }
53
+ else if (active.size > 0) {
54
+ await Promise.race([...active, sleep(idleDelay())]);
55
+ }
56
+ else {
57
+ await sleep(idleDelay());
58
+ }
59
+ continue;
60
+ }
11
61
  if (active.size >= cap()) {
12
- await Promise.race(active);
62
+ if (deps.heartbeat)
63
+ await Promise.race([...active, sleep(heartbeatMs)]);
64
+ else
65
+ await Promise.race(active);
13
66
  continue;
14
67
  }
15
68
  let job;
16
69
  try {
70
+ lastContact = now();
17
71
  job = await deps.claim();
18
72
  }
19
73
  catch (err) {
@@ -33,13 +87,7 @@ export async function runJobPool(deps) {
33
87
  continue;
34
88
  }
35
89
  emptyClaims = 0;
36
- if (deps.stopping())
37
- break;
38
- deps.onStart?.(job, active.size + 1);
39
- const p = deps.run(job).finally(() => {
40
- active.delete(p);
41
- });
42
- active.add(p);
90
+ spawn(job);
43
91
  }
44
92
  if (active.size > 0)
45
93
  await Promise.allSettled(active);
@@ -0,0 +1,11 @@
1
+ export type ChangeKind = 'fix' | 'test';
2
+ export declare function withoutConventionalPrefixes(title: string): string;
3
+ export declare function isTestPath(path: string): boolean;
4
+ export declare function changeKind(paths: string[] | null): ChangeKind;
5
+ export declare function pullRequestTitle(job: {
6
+ title: string | null;
7
+ externalId: string | null;
8
+ }, kind: ChangeKind): string;
9
+ export declare function pullRequestBody(kind: ChangeKind, engineName: string, externalId: string | null, opts?: {
10
+ continuesBranch?: boolean;
11
+ }): string;
@@ -0,0 +1,63 @@
1
+ const CONVENTIONAL_PREFIXES = /^(?:\s*(?:fix|feat|chore|refactor|docs|test)(?:\([^)]*\))?!?:\s*)+/i;
2
+ export function withoutConventionalPrefixes(title) {
3
+ return title.replace(CONVENTIONAL_PREFIXES, '').trim();
4
+ }
5
+ const TEST_DIRS = new Set([
6
+ 'test',
7
+ 'tests',
8
+ '__tests__',
9
+ '__test__',
10
+ 'e2e',
11
+ 'cypress',
12
+ 'testdata',
13
+ 'test-data',
14
+ 'test_data',
15
+ 'testfixtures',
16
+ '__snapshots__',
17
+ '__mocks__',
18
+ '__fixtures__',
19
+ 'androidtest',
20
+ 'integrationtest',
21
+ 'integration-tests',
22
+ 'integration_tests',
23
+ ]);
24
+ const SPEC_DIRS = new Set(['spec', 'specs']);
25
+ const CODE_FILE = /\.(?:[cm]?[jt]sx?|mts|cts|vue|svelte|py|rb|php|go|rs|java|kt|kts|groovy|scala|cs|fs|swift|dart|exs?|m|mm|c|cc|cpp|h|hpp|lua)$/i;
26
+ const TEST_FILES = [
27
+ /\.(?:test|spec|e2e|e2e-spec|cy)\.(?:[cm]?[jt]sx?|mts|cts|vue|svelte|py|rb|php|dart)$/i,
28
+ /_(?:unit)?test\.(?:go|py|rb|exs?|dart|c|cc|cpp|rs|[cm]?[jt]sx?)$/,
29
+ /^test_[^/]*\.py$|^tests?\.py$|_spec\.rb$/,
30
+ /[a-z0-9](?:Test|Tests|IT|Spec|Specs)\.(?:java|kt|kts|groovy|scala|cs|fs|swift|php|m|mm)$/,
31
+ /\.snap$/,
32
+ ];
33
+ const TEST_CONFIG = /^(?:(?:vitest|jest|playwright|cypress|ava|wdio)\.(?:config|setup|workspace)\.[cm]?[jt]s|karma\.conf\.[cm]?[jt]s|setupTests\.[cm]?[jt]sx?|conftest\.py|pytest\.ini|\.mocharc(?:\.[a-z]+)?)$/;
34
+ export function isTestPath(path) {
35
+ const parts = path.split('/').filter(Boolean);
36
+ const file = parts.pop();
37
+ if (!file)
38
+ return false;
39
+ if (parts.some((dir) => TEST_DIRS.has(dir.toLowerCase())))
40
+ return true;
41
+ if (parts.some((dir) => SPEC_DIRS.has(dir.toLowerCase())) && CODE_FILE.test(file))
42
+ return true;
43
+ return TEST_CONFIG.test(file) || TEST_FILES.some((re) => re.test(file));
44
+ }
45
+ export function changeKind(paths) {
46
+ return paths && paths.length > 0 && paths.every(isTestPath) ? 'test' : 'fix';
47
+ }
48
+ export function pullRequestTitle(job, kind) {
49
+ const words = withoutConventionalPrefixes(job.title ?? '') ||
50
+ job.externalId ||
51
+ (kind === 'test' ? 'tests by FireFunc' : 'FireFunc auto-fix');
52
+ return `${kind}: ${words}`;
53
+ }
54
+ export function pullRequestBody(kind, engineName, externalId, opts = {}) {
55
+ const tests = `Tests written by FireFunc (self-hosted ${engineName} runner) for ${externalId ?? 'this task'}.`;
56
+ const what = kind === 'test'
57
+ ? opts.continuesBranch
58
+ ? tests
59
+ : `${tests} When this pull request was opened, its change touched test files only.`
60
+ : `Automated fix by FireFunc (self-hosted ${engineName} runner) for ${externalId ?? 'a reported bug'}.`;
61
+ return `${what}\n\nReview before merging.`;
62
+ }
63
+ //# sourceMappingURL=pr-title.js.map
@@ -0,0 +1,10 @@
1
+ import type { RunnerApi } from './api.js';
2
+ export declare function lostSentence(machine: string): string;
3
+ export type RecoverDeps = {
4
+ runnerDir: string;
5
+ api: Pick<RunnerApi, 'result' | 'probe'>;
6
+ machine: string;
7
+ log: (line: string) => void;
8
+ maxWaitMs?: number;
9
+ };
10
+ export declare function recoverPreviousProcess(deps: RecoverDeps): Promise<string[]>;
@@ -0,0 +1,104 @@
1
+ import { existsSync, rmSync } from 'node:fs';
2
+ import { basename } from 'node:path';
3
+ import { keptWorktrees } from './cut.js';
4
+ import { heldByGoneProcesses, releaseHeld } from './held.js';
5
+ import { isNetworkError, withNetworkRetry } from './network.js';
6
+ import { killOrphans, reviewCopiesOf } from './orphans.js';
7
+ import { listPendingResults, savePendingResult } from './pending.js';
8
+ import { canonicalPath, removeRunnerWorktree } from './worktrees.js';
9
+ export function lostSentence(machine) {
10
+ return (`The attempt did not finish: the runner on ${machine} stopped while it was running — ` +
11
+ 'the runner process was restarted, stopped or crashed — and the process that took over ' +
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.');
14
+ }
15
+ async function clearUp(rec, keep, log) {
16
+ const roots = [rec.worktree, ...(rec.scratch ?? [])].filter((p) => !!p);
17
+ const kept = rec.worktree ? keep.has(canonicalPath(rec.worktree)) : false;
18
+ const copies = rec.worktree ? reviewCopiesOf(rec.worktree) : [];
19
+ await killOrphans({
20
+ roots: [...roots, ...copies],
21
+ ...(rec.worktree ? { reviewCopiesOf: basename(rec.worktree) } : {}),
22
+ ...(rec.engineGroup
23
+ ? {
24
+ groups: [
25
+ {
26
+ pgid: rec.engineGroup,
27
+ startedAt: rec.engineStartedAt ?? 0,
28
+ leaderExited: false,
29
+ },
30
+ ],
31
+ }
32
+ : {}),
33
+ }, { log });
34
+ if (rec.worktree && !kept) {
35
+ if (rec.repoPath && existsSync(rec.repoPath)) {
36
+ await removeRunnerWorktree(rec.repoPath, rec.worktree, log);
37
+ }
38
+ else {
39
+ rmSync(rec.worktree, { recursive: true, force: true });
40
+ }
41
+ }
42
+ for (const p of rec.scratch ?? []) {
43
+ try {
44
+ rmSync(p, { recursive: true, force: true });
45
+ }
46
+ catch {
47
+ }
48
+ }
49
+ }
50
+ export async function recoverPreviousProcess(deps) {
51
+ const lost = [];
52
+ let gone;
53
+ try {
54
+ gone = heldByGoneProcesses(deps.runnerDir);
55
+ }
56
+ catch {
57
+ return lost;
58
+ }
59
+ if (gone.length === 0)
60
+ return lost;
61
+ const pending = new Set(listPendingResults(deps.runnerDir).map((p) => p.runId));
62
+ const keep = new Set([...keptWorktrees(deps.runnerDir)].map(canonicalPath));
63
+ deps.log(`${gone.length} run(s) were held by a runner process that is no longer running — stopping what they left and reporting them`);
64
+ let offline = false;
65
+ for (const rec of gone) {
66
+ try {
67
+ await clearUp(rec, keep, deps.log);
68
+ if (!pending.has(rec.runId)) {
69
+ const payload = {
70
+ status: 'failed',
71
+ error: lostSentence(deps.machine),
72
+ lost: true,
73
+ };
74
+ try {
75
+ if (offline)
76
+ throw new Error('fetch failed: FireFunc was unreachable a moment ago');
77
+ await withNetworkRetry(() => deps.api.result(rec.runId, payload), {
78
+ label: `lost run ${rec.runId}`,
79
+ maxWaitMs: deps.maxWaitMs ?? 2 * 60_000,
80
+ probe: () => deps.api.probe(),
81
+ log: deps.log,
82
+ });
83
+ deps.log(`reported run ${rec.runId} as lost with the previous runner process`);
84
+ }
85
+ catch (err) {
86
+ if (isNetworkError(err)) {
87
+ offline = true;
88
+ savePendingResult(deps.runnerDir, rec.runId, payload);
89
+ deps.log(`FireFunc is unreachable — kept the lost report for ${rec.runId}; it is delivered when the network is back`);
90
+ }
91
+ else {
92
+ deps.log(`FireFunc did not take the lost report for ${rec.runId}: ${err.message}`);
93
+ }
94
+ }
95
+ lost.push(rec.runId);
96
+ }
97
+ }
98
+ finally {
99
+ releaseHeld(deps.runnerDir, rec.runId);
100
+ }
101
+ }
102
+ return lost;
103
+ }
104
+ //# sourceMappingURL=recover.js.map
@@ -6,8 +6,15 @@ export type SessionEvent = {
6
6
  name: string;
7
7
  arg?: string;
8
8
  path?: string;
9
+ id?: string;
9
10
  } | {
10
11
  kind: 'result';
11
12
  text: string;
13
+ } | {
14
+ kind: 'tool_result';
15
+ id: string;
16
+ isError: boolean;
12
17
  };
13
- export declare function makeStreamJsonParser(onEvent: (ev: SessionEvent) => void): (chunk: string) => void;
18
+ export declare function makeStreamJsonParser(onEvent: (ev: SessionEvent) => void, opts?: {
19
+ toolResults?: boolean;
20
+ }): (chunk: string) => void;
@@ -1,4 +1,4 @@
1
- export function makeStreamJsonParser(onEvent) {
1
+ export function makeStreamJsonParser(onEvent, opts = {}) {
2
2
  let buf = '';
3
3
  return (chunk) => {
4
4
  buf += chunk;
@@ -39,10 +39,18 @@ export function makeStreamJsonParser(onEvent) {
39
39
  name: c.name,
40
40
  ...(arg ? { arg } : {}),
41
41
  ...(path ? { path } : {}),
42
+ ...(opts.toolResults && typeof c.id === 'string' ? { id: c.id } : {}),
42
43
  });
43
44
  }
44
45
  }
45
46
  }
47
+ else if (opts.toolResults && ev.type === 'user' && Array.isArray(ev.message?.content)) {
48
+ for (const c of ev.message.content) {
49
+ if (c?.type === 'tool_result' && typeof c.tool_use_id === 'string') {
50
+ onEvent({ kind: 'tool_result', id: c.tool_use_id, isError: c.is_error === true });
51
+ }
52
+ }
53
+ }
46
54
  else if (ev.type === 'result' && typeof ev.result === 'string' && ev.result.trim()) {
47
55
  onEvent({ kind: 'result', text: ev.result });
48
56
  }
@@ -0,0 +1,11 @@
1
+ export interface SkillToWrite {
2
+ slug: string;
3
+ content: string;
4
+ }
5
+ export interface WrittenSkills {
6
+ written: string[];
7
+ pathspecs: string[];
8
+ ignoreCase?: boolean;
9
+ }
10
+ export declare function writtenSkillPaths(staged: readonly string[], w: WrittenSkills): string[];
11
+ export declare function writeSkills(worktree: string, skills: readonly SkillToWrite[] | null | undefined, log: (m: string) => void): WrittenSkills;