@firefunc-agent/runner 0.7.1 → 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 (114) hide show
  1. package/LICENSE +7 -3
  2. package/README.md +296 -4
  3. package/dist/activity.d.ts +32 -0
  4. package/dist/activity.js +295 -0
  5. package/dist/api.d.ts +69 -1
  6. package/dist/api.js +114 -3
  7. package/dist/brief.d.ts +11 -0
  8. package/dist/brief.js +278 -0
  9. package/dist/build-info.json +4 -0
  10. package/dist/cli.js +59 -2
  11. package/dist/config.d.ts +7 -0
  12. package/dist/config.js +3 -0
  13. package/dist/cut.d.ts +45 -0
  14. package/dist/cut.js +105 -0
  15. package/dist/daemon.d.ts +16 -0
  16. package/dist/daemon.js +196 -7
  17. package/dist/declined.d.ts +11 -0
  18. package/dist/declined.js +27 -0
  19. package/dist/engines/antigravity.d.ts +2 -0
  20. package/dist/engines/antigravity.js +102 -0
  21. package/dist/engines/claude-budget.d.ts +1 -1
  22. package/dist/engines/claude-budget.js +2 -72
  23. package/dist/engines/claude.js +139 -2
  24. package/dist/engines/codex.js +10 -3
  25. package/dist/engines/copilot.d.ts +2 -0
  26. package/dist/engines/copilot.js +117 -0
  27. package/dist/engines/cursor.js +4 -0
  28. package/dist/engines/gemini.js +6 -1
  29. package/dist/engines/index.d.ts +2 -0
  30. package/dist/engines/index.js +22 -4
  31. package/dist/engines/types.d.ts +12 -1
  32. package/dist/exec.d.ts +3 -0
  33. package/dist/exec.js +48 -5
  34. package/dist/firefunc/agents.d.ts +2 -0
  35. package/dist/firefunc/agents.js +343 -0
  36. package/dist/firefunc/args.d.ts +18 -0
  37. package/dist/firefunc/args.js +82 -0
  38. package/dist/firefunc/auth.d.ts +21 -0
  39. package/dist/firefunc/auth.js +129 -0
  40. package/dist/firefunc/catalog.d.ts +10 -0
  41. package/dist/firefunc/catalog.js +201 -0
  42. package/dist/firefunc/cli.d.ts +2 -0
  43. package/dist/firefunc/cli.js +24 -0
  44. package/dist/firefunc/client.d.ts +36 -0
  45. package/dist/firefunc/client.js +177 -0
  46. package/dist/firefunc/command.d.ts +28 -0
  47. package/dist/firefunc/command.js +35 -0
  48. package/dist/firefunc/config.d.ts +29 -0
  49. package/dist/firefunc/config.js +111 -0
  50. package/dist/firefunc/configure.d.ts +6 -0
  51. package/dist/firefunc/configure.js +409 -0
  52. package/dist/firefunc/io.d.ts +25 -0
  53. package/dist/firefunc/io.js +14 -0
  54. package/dist/firefunc/main.d.ts +4 -0
  55. package/dist/firefunc/main.js +259 -0
  56. package/dist/firefunc/output.d.ts +29 -0
  57. package/dist/firefunc/output.js +131 -0
  58. package/dist/firefunc/prompt.d.ts +14 -0
  59. package/dist/firefunc/prompt.js +58 -0
  60. package/dist/firefunc/skill.d.ts +3 -0
  61. package/dist/firefunc/skill.js +80 -0
  62. package/dist/firefunc/tasks.d.ts +2 -0
  63. package/dist/firefunc/tasks.js +279 -0
  64. package/dist/firefunc/version.d.ts +2 -0
  65. package/dist/firefunc/version.js +8 -0
  66. package/dist/git-auth.d.ts +4 -1
  67. package/dist/git-auth.js +6 -2
  68. package/dist/held.d.ts +18 -0
  69. package/dist/held.js +95 -0
  70. package/dist/job.d.ts +3 -0
  71. package/dist/job.js +818 -102
  72. package/dist/keep-local.d.ts +12 -0
  73. package/dist/keep-local.js +651 -0
  74. package/dist/limit.d.ts +30 -0
  75. package/dist/limit.js +258 -0
  76. package/dist/locks.d.ts +14 -0
  77. package/dist/locks.js +164 -0
  78. package/dist/machine-logins.d.ts +19 -0
  79. package/dist/machine-logins.js +187 -0
  80. package/dist/mcp-login.d.ts +24 -0
  81. package/dist/mcp-login.js +993 -0
  82. package/dist/mcp-proxy.d.ts +21 -0
  83. package/dist/mcp-proxy.js +180 -0
  84. package/dist/mcp.d.ts +62 -0
  85. package/dist/mcp.js +611 -0
  86. package/dist/network.d.ts +20 -0
  87. package/dist/network.js +76 -0
  88. package/dist/orphans.d.ts +40 -0
  89. package/dist/orphans.js +235 -0
  90. package/dist/pending.d.ts +14 -0
  91. package/dist/pending.js +56 -0
  92. package/dist/pool.d.ts +7 -0
  93. package/dist/pool.js +57 -9
  94. package/dist/pr-title.d.ts +11 -0
  95. package/dist/pr-title.js +63 -0
  96. package/dist/recover.d.ts +10 -0
  97. package/dist/recover.js +104 -0
  98. package/dist/secret-scan.d.ts +19 -0
  99. package/dist/secret-scan.js +161 -0
  100. package/dist/session-stream.d.ts +9 -1
  101. package/dist/session-stream.js +20 -2
  102. package/dist/skills.d.ts +11 -0
  103. package/dist/skills.js +164 -0
  104. package/dist/stopped.d.ts +3 -0
  105. package/dist/stopped.js +10 -0
  106. package/dist/usage.d.ts +49 -0
  107. package/dist/usage.js +389 -0
  108. package/dist/version.d.ts +1 -0
  109. package/dist/version.js +17 -0
  110. package/dist/viewer.js +7 -1
  111. package/dist/worktrees.d.ts +15 -0
  112. package/dist/worktrees.js +96 -0
  113. package/package.json +8 -5
  114. package/skill/firefunc/SKILL.md +222 -0
@@ -0,0 +1,279 @@
1
+ import { bool, positiveNumber, str, UsageError } from './args.js';
2
+ import { pick, listIn } from './catalog.js';
3
+ import { ApiRefusal, ApiUnreachable } from './client.js';
4
+ import { enc, readInputFile } from './command.js';
5
+ import { Refusal } from './io.js';
6
+ import { printJson, table, text } from './output.js';
7
+ const TASK_TYPES = ['task', 'feature', 'refactor', 'chore', 'bug'];
8
+ const STOPS_FOR_A_PERSON = [
9
+ 'resolved',
10
+ 'rejected',
11
+ 'false_positive',
12
+ 'pr_opened',
13
+ 'needs_human',
14
+ 'requires_human',
15
+ 'quota_exceeded',
16
+ 'dry_run_skipped',
17
+ ];
18
+ const isFailure = (state) => state.endsWith('_failed');
19
+ function printTask(ctx, t) {
20
+ const agent = t.agent;
21
+ const project = t.project;
22
+ const lines = [
23
+ `${text(t.title)}`,
24
+ ` id: ${text(t.id)}`,
25
+ ` state: ${text(t.state)}`,
26
+ ` type: ${text(t.type)}`,
27
+ ` agent: ${agent ? `${text(agent.name)}${agent.handle ? ` (@${String(agent.handle)})` : ''}` : text(t.workflowId)}`,
28
+ ` project: ${project ? text(project.name) : text(t.projectId)}`,
29
+ ];
30
+ if (t.error)
31
+ lines.push(` error: ${text(t.error)}`);
32
+ const prs = Array.isArray(t.pullRequests) ? t.pullRequests : [];
33
+ for (const pr of prs)
34
+ lines.push(` pull request: ${text(pr.url)} (${text(pr.state)})`);
35
+ if (t.externalUrl)
36
+ lines.push(` source: ${text(t.externalUrl)}`);
37
+ const runs = Array.isArray(t.runs) ? t.runs : [];
38
+ if (runs.length) {
39
+ lines.push(` runs: ${runs.length}`);
40
+ for (const r of runs.slice(0, 5)) {
41
+ lines.push(` ${text(r.id)} ${text(r.state)} ${text(r.engine)}${r.error ? ` ${text(r.error)}` : ''}`);
42
+ }
43
+ }
44
+ ctx.io.stdout.write(`${lines.join('\n')}\n`);
45
+ }
46
+ async function stopStates(api) {
47
+ const stops = new Set(STOPS_FOR_A_PERSON);
48
+ try {
49
+ const body = await api.get('/api/v1/task-states');
50
+ if (Array.isArray(body?.terminal))
51
+ for (const s of body.terminal)
52
+ if (typeof s === 'string')
53
+ stops.add(s);
54
+ }
55
+ catch (err) {
56
+ if (!(err instanceof ApiRefusal) && !(err instanceof ApiUnreachable))
57
+ throw err;
58
+ }
59
+ return stops;
60
+ }
61
+ const mmss = (ms) => {
62
+ const s = Math.max(0, Math.round(ms / 1000));
63
+ return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
64
+ };
65
+ async function watchTask(ctx, id, opts) {
66
+ const { io } = ctx;
67
+ const api = ctx.api();
68
+ const stops = await stopStates(api);
69
+ const started = io.now();
70
+ let last;
71
+ let lost = false;
72
+ let task;
73
+ if (!ctx.json) {
74
+ io.stdout.write(`Watching task ${id} every ${Math.round(opts.intervalMs / 1000)}s for up to ${Math.round(opts.timeoutMs / 60_000)} min.\n` +
75
+ 'Ctrl-C stops the watch, not the task.\n');
76
+ }
77
+ for (;;) {
78
+ try {
79
+ const body = await api.get(`/api/v1/tasks/${enc(id)}`);
80
+ task = body?.task ?? {};
81
+ if (lost && !ctx.json)
82
+ io.stderr.write('Back in contact.\n');
83
+ lost = false;
84
+ }
85
+ catch (err) {
86
+ const transient = err instanceof ApiUnreachable || (err instanceof ApiRefusal && err.status >= 500);
87
+ if (!transient)
88
+ throw err;
89
+ if (!lost && !ctx.json) {
90
+ io.stderr.write(`Lost contact with the API (${err.message}); still watching.\n`);
91
+ }
92
+ lost = true;
93
+ }
94
+ const state = typeof task?.state === 'string' ? task.state : undefined;
95
+ if (state && state !== last) {
96
+ if (!ctx.json)
97
+ io.stdout.write(`${mmss(io.now() - started)} ${state}\n`);
98
+ last = state;
99
+ }
100
+ if (state && (stops.has(state) || isFailure(state)))
101
+ break;
102
+ if (io.now() - started >= opts.timeoutMs) {
103
+ throw new Refusal(`Task ${id} is still ${state ?? 'unread'} after ${Math.round(opts.timeoutMs / 60_000)} min of watching` +
104
+ (lost ? ', and the API has not answered the last reads.' : '.'), `It carries on without the watch. Keep watching: firefunc tasks watch ${id}`, 'watch_timeout');
105
+ }
106
+ await io.sleep(opts.intervalMs);
107
+ }
108
+ const t = task;
109
+ const state = String(t.state);
110
+ if (ctx.json)
111
+ printJson(io, { task: t });
112
+ else {
113
+ io.stdout.write('\n');
114
+ printTask(ctx, t);
115
+ const prs = Array.isArray(t.pullRequests) ? t.pullRequests : [];
116
+ if (state === 'pr_opened' && prs.length) {
117
+ io.stdout.write('\nA pull request is open for review; the task resolves when it is merged.\n');
118
+ }
119
+ }
120
+ if (isFailure(state)) {
121
+ throw new Refusal(`Task ${id} ended ${state}${t.error ? `: ${text(t.error)}` : '.'}`, 'Read what happened on the task page in FireFunc, then run it again: firefunc run <agent> --title …', 'task_failed');
122
+ }
123
+ return 0;
124
+ }
125
+ function watchOpts(ctx) {
126
+ const interval = positiveNumber(ctx.args, 'interval', ctx.command, { min: 2, max: 300 }) ?? 5;
127
+ const timeout = positiveNumber(ctx.args, 'timeout', ctx.command, { min: 1, max: 24 * 60 }) ?? 60;
128
+ return { intervalMs: interval * 1000, timeoutMs: timeout * 60_000 };
129
+ }
130
+ const watchFlagHelp = [
131
+ ['--interval <seconds>', 'how often to read it (default 5, at least 2)'],
132
+ [
133
+ '--timeout <minutes>',
134
+ 'give up watching after this long (default 60); exit 1 says where it was',
135
+ ],
136
+ ];
137
+ export const taskCommands = [
138
+ {
139
+ path: ['run'],
140
+ summary: 'Start a task on an active agent (what "Run now" does)',
141
+ usage: 'run <agent id or @handle> --title <title> [--body <text> | --body-file <path>] [--type <type>] [--watch]',
142
+ details: 'The agent must be active; a draft is activated by a person first. Needs tasks:write.\n' +
143
+ `Types: ${TASK_TYPES.join(', ')} (default task).`,
144
+ flags: {
145
+ title: 'string',
146
+ body: 'string',
147
+ 'body-file': 'string',
148
+ type: 'string',
149
+ watch: 'boolean',
150
+ interval: 'string',
151
+ timeout: 'string',
152
+ },
153
+ flagHelp: [
154
+ ['--title <title>', 'what to do, in a line (required)'],
155
+ ['--body <text>', 'the detail'],
156
+ ['--body-file <path>', 'the detail from a file ("-" for stdin)'],
157
+ ['--type <type>', `${TASK_TYPES.join(' | ')}`],
158
+ ['--watch', 'then watch it until it stops (see "firefunc tasks watch --help")'],
159
+ ...watchFlagHelp,
160
+ ],
161
+ positional: { min: 1, max: 1 },
162
+ async run(ctx) {
163
+ const agent = ctx.args.positional[0];
164
+ const title = str(ctx.args, 'title');
165
+ if (!title?.trim())
166
+ throw new UsageError('Say what to do: --title "…"', ctx.command);
167
+ const bodyText = str(ctx.args, 'body');
168
+ const bodyFile = str(ctx.args, 'body-file');
169
+ if (bodyText !== undefined && bodyFile !== undefined) {
170
+ throw new UsageError('Pass --body or --body-file, not both.', ctx.command);
171
+ }
172
+ const type = str(ctx.args, 'type');
173
+ if (type !== undefined && !TASK_TYPES.includes(type)) {
174
+ throw new UsageError(`--type must be one of ${TASK_TYPES.join(', ')}.`, ctx.command);
175
+ }
176
+ const watch = bool(ctx.args, 'watch');
177
+ const opts = watch ? watchOpts(ctx) : undefined;
178
+ const detail = bodyFile !== undefined
179
+ ? (await readInputFile(ctx.io, bodyFile, 'body-file')).trim()
180
+ : bodyText;
181
+ const answer = await ctx.api().post('/api/v1/tasks', {
182
+ agent,
183
+ title: title.trim(),
184
+ ...(detail ? { body: detail } : {}),
185
+ ...(type ? { type } : {}),
186
+ });
187
+ const task = (answer?.task ?? {});
188
+ if (watch && typeof task.id === 'string') {
189
+ if (!ctx.json)
190
+ ctx.io.stdout.write(`Started task ${task.id}.\n`);
191
+ return watchTask(ctx, task.id, opts);
192
+ }
193
+ if (ctx.json)
194
+ return printJson(ctx.io, answer);
195
+ ctx.io.stdout.write('Started a task.\n\n');
196
+ printTask(ctx, task);
197
+ if (typeof task.id === 'string')
198
+ ctx.io.stdout.write(`\nFollow it: firefunc tasks watch ${task.id}\n`);
199
+ },
200
+ },
201
+ {
202
+ path: ['tasks', 'list'],
203
+ summary: 'Recent tasks, newest first',
204
+ usage: 'tasks list [--state <state>] [--agent <id or @handle>] [--limit <n>]',
205
+ flags: { state: 'string', agent: 'string', limit: 'string' },
206
+ flagHelp: [
207
+ ['--state <state>', 'only tasks in this state (firefunc tasks states)'],
208
+ ['--agent <id or @handle>', "only this agent's tasks"],
209
+ ['--limit <n>', 'how many (1-100, default 25)'],
210
+ ],
211
+ async run(ctx) {
212
+ const limit = positiveNumber(ctx.args, 'limit', ctx.command, { min: 1, max: 100 });
213
+ const body = await ctx.api().get('/api/v1/tasks', {
214
+ state: str(ctx.args, 'state'),
215
+ agent: str(ctx.args, 'agent'),
216
+ limit,
217
+ });
218
+ if (ctx.json)
219
+ return printJson(ctx.io, body);
220
+ const rows = listIn(body, 'tasks');
221
+ if (!rows.length) {
222
+ ctx.io.stdout.write('No tasks match.\n');
223
+ return;
224
+ }
225
+ table(ctx.io, rows, [
226
+ { head: 'ID', get: pick('id') },
227
+ { head: 'STATE', get: pick('state') },
228
+ { head: 'TYPE', get: pick('type') },
229
+ { head: 'CREATED', get: pick('createdAt') },
230
+ { head: 'TITLE', get: pick('title'), max: 70 },
231
+ ]);
232
+ },
233
+ },
234
+ {
235
+ path: ['tasks', 'get'],
236
+ summary: 'One task: its state, runs and pull requests',
237
+ usage: 'tasks get <task id>',
238
+ positional: { min: 1, max: 1 },
239
+ async run(ctx) {
240
+ const body = await ctx.api().get(`/api/v1/tasks/${enc(ctx.args.positional[0])}`);
241
+ if (ctx.json)
242
+ return printJson(ctx.io, body);
243
+ printTask(ctx, body?.task ?? {});
244
+ },
245
+ },
246
+ {
247
+ path: ['tasks', 'watch'],
248
+ summary: 'Follow a task until it stops',
249
+ usage: 'tasks watch <task id> [--interval <seconds>] [--timeout <minutes>]',
250
+ details: "Stops when the agent's part is over: resolved, a pull request open for review, parked\n" +
251
+ 'for a person (needs_human, requires_human, quota_exceeded), rejected, or failed.\n' +
252
+ 'Exit 0 when it stopped, 1 when it failed (the state ends in _failed) or the watch ran\n' +
253
+ 'out of time. Network loss is waited out; a refusal ends the watch.\n' +
254
+ 'Under --json, prints only the final { task } — nothing while it waits.',
255
+ flags: { interval: 'string', timeout: 'string' },
256
+ flagHelp: watchFlagHelp,
257
+ positional: { min: 1, max: 1 },
258
+ async run(ctx) {
259
+ return watchTask(ctx, ctx.args.positional[0], watchOpts(ctx));
260
+ },
261
+ },
262
+ {
263
+ path: ['tasks', 'states'],
264
+ summary: 'The states a task can be in, and which are final',
265
+ usage: 'tasks states',
266
+ async run(ctx) {
267
+ const body = await ctx
268
+ .api()
269
+ .get('/api/v1/task-states');
270
+ if (ctx.json)
271
+ return printJson(ctx.io, body);
272
+ const states = Array.isArray(body?.states) ? body.states.map(String) : [];
273
+ const terminal = new Set(Array.isArray(body?.terminal) ? body.terminal.map(String) : []);
274
+ for (const s of states)
275
+ ctx.io.stdout.write(`${s}${terminal.has(s) ? ' (final)' : ''}\n`);
276
+ },
277
+ },
278
+ ];
279
+ //# sourceMappingURL=tasks.js.map
@@ -0,0 +1,2 @@
1
+ export declare const CLI_VERSION: string;
2
+ export declare function packageRoot(): string;
@@ -0,0 +1,8 @@
1
+ import { dirname, join } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { RUNNER_VERSION } from '../version.js';
4
+ export const CLI_VERSION = RUNNER_VERSION;
5
+ export function packageRoot() {
6
+ return join(dirname(fileURLToPath(import.meta.url)), '..', '..');
7
+ }
8
+ //# sourceMappingURL=version.js.map
@@ -7,7 +7,10 @@ export type GitCredential = {
7
7
  export declare function redact(text: string, token?: string): string;
8
8
  export declare function gitAuthEnv(token: string, repo: string): NodeJS.ProcessEnv;
9
9
  export declare function cloneRepo(repo: string, dest: string, cred: GitCredential): Promise<ExecResult>;
10
- export declare function pushBranch(worktree: string, branch: string, repo: string, cred: GitCredential): Promise<ExecResult>;
10
+ export declare const pushFlags: (force: boolean) => string[];
11
+ export declare function pushBranch(worktree: string, branch: string, repo: string, cred: GitCredential, opts?: {
12
+ force: boolean;
13
+ }): Promise<ExecResult>;
11
14
  export declare function openDraftPr(args: {
12
15
  repo: string;
13
16
  head: string;
package/dist/git-auth.js CHANGED
@@ -35,8 +35,12 @@ export async function cloneRepo(repo, dest, cred) {
35
35
  });
36
36
  return { ...res, stderr: redact(res.stderr, cred.token), stdout: redact(res.stdout, cred.token) };
37
37
  }
38
- export async function pushBranch(worktree, branch, repo, cred) {
39
- const res = await exec('git', ['-C', worktree, 'push', '--force-with-lease', 'origin', `${branch}:${branch}`], { timeoutMs: 120_000, env: gitAuthEnv(cred.token, repo) });
38
+ export const pushFlags = (force) => (force ? ['--force-with-lease'] : []);
39
+ export async function pushBranch(worktree, branch, repo, cred, opts = { force: true }) {
40
+ const res = await exec('git', ['-C', worktree, 'push', ...pushFlags(opts.force), 'origin', `${branch}:${branch}`], {
41
+ timeoutMs: 120_000,
42
+ env: gitAuthEnv(cred.token, repo),
43
+ });
40
44
  return { ...res, stderr: redact(res.stderr, cred.token), stdout: redact(res.stdout, cred.token) };
41
45
  }
42
46
  export async function openDraftPr(args) {
package/dist/held.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ export type HeldRun = {
2
+ runId: string;
3
+ pid: number;
4
+ claimedAt: string;
5
+ worktree?: string;
6
+ repoPath?: string;
7
+ scratch?: string[];
8
+ engineGroup?: number;
9
+ engineStartedAt?: number;
10
+ };
11
+ export declare function heldDir(runnerDir: string): string;
12
+ export declare function recordHeld(runnerDir: string, runId: string, pid?: number): void;
13
+ export declare function updateHeld(runnerDir: string, runId: string, patch: Partial<Omit<HeldRun, 'runId' | 'pid' | 'claimedAt'>>): void;
14
+ export declare function releaseHeld(runnerDir: string, runId: string): void;
15
+ export declare function listHeld(runnerDir: string): HeldRun[];
16
+ export declare function heldByGoneProcesses(runnerDir: string, self?: number): HeldRun[];
17
+ export declare function heldByLiveProcesses(runnerDir: string, self?: number): string[];
18
+ export declare function liveWorktrees(runnerDir: string): Set<string>;
package/dist/held.js ADDED
@@ -0,0 +1,95 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { isAlive } from './orphans.js';
4
+ const RUN_ID = /^[A-Za-z0-9][A-Za-z0-9-]{3,79}$/;
5
+ export function heldDir(runnerDir) {
6
+ return join(runnerDir, 'held');
7
+ }
8
+ function fileFor(runnerDir, runId) {
9
+ return typeof runId === 'string' && RUN_ID.test(runId)
10
+ ? join(heldDir(runnerDir), `${runId}.json`)
11
+ : null;
12
+ }
13
+ function write(file, rec) {
14
+ const tmp = `${file}.${process.pid}.tmp`;
15
+ writeFileSync(tmp, `${JSON.stringify(rec, null, 2)}\n`, { mode: 0o600 });
16
+ renameSync(tmp, file);
17
+ }
18
+ export function recordHeld(runnerDir, runId, pid = process.pid) {
19
+ const file = fileFor(runnerDir, runId);
20
+ if (!file)
21
+ return;
22
+ try {
23
+ mkdirSync(heldDir(runnerDir), { recursive: true, mode: 0o700 });
24
+ write(file, { runId, pid, claimedAt: new Date().toISOString() });
25
+ }
26
+ catch {
27
+ }
28
+ }
29
+ export function updateHeld(runnerDir, runId, patch) {
30
+ const file = fileFor(runnerDir, runId);
31
+ if (!file || !existsSync(file))
32
+ return;
33
+ try {
34
+ const rec = JSON.parse(readFileSync(file, 'utf8'));
35
+ const scratch = patch.scratch
36
+ ? [...new Set([...(rec.scratch ?? []), ...patch.scratch])]
37
+ : rec.scratch;
38
+ write(file, { ...rec, ...patch, ...(scratch ? { scratch } : {}) });
39
+ }
40
+ catch {
41
+ }
42
+ }
43
+ export function releaseHeld(runnerDir, runId) {
44
+ const file = fileFor(runnerDir, runId);
45
+ if (!file)
46
+ return;
47
+ try {
48
+ unlinkSync(file);
49
+ }
50
+ catch {
51
+ }
52
+ }
53
+ export function listHeld(runnerDir) {
54
+ const dir = heldDir(runnerDir);
55
+ if (!existsSync(dir))
56
+ return [];
57
+ const out = [];
58
+ for (const name of readdirSync(dir)) {
59
+ if (!name.endsWith('.json'))
60
+ continue;
61
+ try {
62
+ const rec = JSON.parse(readFileSync(join(dir, name), 'utf8'));
63
+ if (rec &&
64
+ typeof rec.runId === 'string' &&
65
+ RUN_ID.test(rec.runId) &&
66
+ Number.isInteger(rec.pid)) {
67
+ out.push(rec);
68
+ }
69
+ }
70
+ catch {
71
+ }
72
+ }
73
+ return out.sort((a, b) => a.claimedAt.localeCompare(b.claimedAt));
74
+ }
75
+ export function heldByGoneProcesses(runnerDir, self = process.pid) {
76
+ return listHeld(runnerDir).filter((r) => r.pid !== self && !isAlive(r.pid));
77
+ }
78
+ export function heldByLiveProcesses(runnerDir, self = process.pid) {
79
+ return listHeld(runnerDir)
80
+ .filter((r) => r.pid === self || isAlive(r.pid))
81
+ .map((r) => r.runId);
82
+ }
83
+ export function liveWorktrees(runnerDir) {
84
+ const out = new Set();
85
+ for (const r of listHeld(runnerDir)) {
86
+ if (!isAlive(r.pid))
87
+ continue;
88
+ if (r.worktree)
89
+ out.add(r.worktree);
90
+ for (const s of r.scratch ?? [])
91
+ out.add(s);
92
+ }
93
+ return out;
94
+ }
95
+ //# sourceMappingURL=held.js.map
package/dist/job.d.ts CHANGED
@@ -1,10 +1,13 @@
1
1
  import type { RunnerApi, ClaimedJob } from './api.js';
2
2
  import { type RunnerConfig } from './config.js';
3
3
  import type { SessionViewer } from './viewer.js';
4
+ import { type LimitGate } from './limit.js';
4
5
  export declare function resolveRepoPath(repo: string | null | undefined, cfg: RunnerConfig): string | null;
5
6
  export declare function cloneDestination(repo: string, cfg: RunnerConfig): string | null;
6
7
  export declare function rememberRepoPath(repo: string, path: string, cfg: RunnerConfig): void;
7
8
  export declare function hasGh(cwd: string): Promise<boolean>;
8
9
  export declare function runJob(job: ClaimedJob, cfg: RunnerConfig, api: RunnerApi, viewer?: SessionViewer, opts?: {
9
10
  devServerPort?: number;
11
+ limits?: LimitGate;
12
+ now?: () => Date;
10
13
  }): Promise<void>;