@firefunc-agent/runner 0.9.36 → 0.9.40

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 (77) hide show
  1. package/README.md +32 -0
  2. package/dist/activity.d.ts +2 -0
  3. package/dist/activity.js +3 -0
  4. package/dist/alive.d.ts +8 -0
  5. package/dist/alive.js +29 -0
  6. package/dist/api.d.ts +32 -0
  7. package/dist/api.js +18 -2
  8. package/dist/ask-replace.d.ts +6 -0
  9. package/dist/ask-replace.js +49 -0
  10. package/dist/awake-timer.d.ts +8 -0
  11. package/dist/awake-timer.js +30 -0
  12. package/dist/brief.js +2 -2
  13. package/dist/build-info.json +2 -2
  14. package/dist/clean-up.d.ts +29 -0
  15. package/dist/clean-up.js +131 -0
  16. package/dist/cli.js +141 -16
  17. package/dist/config.d.ts +7 -0
  18. package/dist/cut.d.ts +2 -0
  19. package/dist/cut.js +20 -3
  20. package/dist/daemon.js +147 -6
  21. package/dist/disk-reclaim.d.ts +40 -0
  22. package/dist/disk-reclaim.js +95 -0
  23. package/dist/drives.d.ts +29 -0
  24. package/dist/drives.js +270 -0
  25. package/dist/engine-account.d.ts +1 -1
  26. package/dist/engine-account.js +12 -1
  27. package/dist/engines/types.d.ts +1 -1
  28. package/dist/exec.js +5 -6
  29. package/dist/firefunc/automations.js +3 -3
  30. package/dist/firefunc/machines.js +20 -0
  31. package/dist/firefunc/main.js +1 -1
  32. package/dist/firefunc/oauth-login.js +1 -1
  33. package/dist/gh-repos.d.ts +41 -0
  34. package/dist/gh-repos.js +68 -0
  35. package/dist/git-auth.d.ts +1 -0
  36. package/dist/git-auth.js +1 -1
  37. package/dist/held.d.ts +4 -2
  38. package/dist/held.js +19 -5
  39. package/dist/job.d.ts +1 -0
  40. package/dist/job.js +148 -33
  41. package/dist/keep-local.d.ts +1 -0
  42. package/dist/keep-local.js +63 -0
  43. package/dist/live-runner.d.ts +47 -0
  44. package/dist/live-runner.js +109 -0
  45. package/dist/local-tools.d.ts +31 -0
  46. package/dist/local-tools.js +178 -0
  47. package/dist/machine-logins.d.ts +4 -0
  48. package/dist/machine-logins.js +31 -0
  49. package/dist/mcp-login.d.ts +3 -0
  50. package/dist/mcp-login.js +34 -4
  51. package/dist/mcp-tools.d.ts +23 -0
  52. package/dist/mcp-tools.js +122 -0
  53. package/dist/mcp.d.ts +8 -0
  54. package/dist/mcp.js +37 -3
  55. package/dist/newer-runner.d.ts +9 -0
  56. package/dist/newer-runner.js +38 -0
  57. package/dist/pool.d.ts +1 -0
  58. package/dist/pool.js +1 -0
  59. package/dist/pr-title.d.ts +1 -0
  60. package/dist/pr-title.js +7 -0
  61. package/dist/repo-path.d.ts +15 -0
  62. package/dist/repo-path.js +56 -0
  63. package/dist/resources.d.ts +38 -0
  64. package/dist/resources.js +47 -1
  65. package/dist/restart-idle.d.ts +1 -0
  66. package/dist/restart-idle.js +20 -5
  67. package/dist/run-folders.d.ts +25 -0
  68. package/dist/run-folders.js +89 -0
  69. package/dist/update.d.ts +41 -0
  70. package/dist/update.js +176 -0
  71. package/dist/viewer.d.ts +1 -1
  72. package/dist/viewer.js +3 -1
  73. package/dist/work-dir.d.ts +30 -0
  74. package/dist/work-dir.js +153 -22
  75. package/dist/worktrees.d.ts +7 -0
  76. package/dist/worktrees.js +26 -5
  77. package/package.json +1 -1
package/README.md CHANGED
@@ -621,6 +621,27 @@ and now says so: "[formatted text kept on the machine: read it in the run's sess
621
621
  To update: `npm install -g @firefunc-agent/runner@latest; firefunc-runner restart --when-idle`
622
622
  (PowerShell), or with `&&` in a POSIX shell.
623
623
 
624
+ ## Local tools on this machine (0.9.40)
625
+
626
+ An MCP server that lives on this machine, such as computer use, can be given to the runs of agents
627
+ granted it by name. Only you add one, here:
628
+
629
+ ```bash
630
+ firefunc-runner mcp add windows-mcp -- uvx windows-mcp serve
631
+ firefunc-runner mcp list
632
+ firefunc-runner mcp remove windows-mcp
633
+ ```
634
+
635
+ - **What leaves this machine:** only its name, on the heartbeat. The command, its arguments and any
636
+ `--env NAME=value` stay in this runner's config file (mode 0600).
637
+ - **When a run gets it:** only when its agent is granted that name in FireFunc. A granted name this
638
+ machine lacks is named in the run's brief.
639
+ - **Engine:** Claude Code runs only. The server is added to the run's `--mcp-config`, allowed whole.
640
+ - **What is recorded:** each call is a step on the run's trail by tool name, never its arguments or
641
+ its answer.
642
+
643
+ FireFunc cannot add, change or start one.
644
+
624
645
  ## Licence
625
646
 
626
647
  `@firefunc-agent/runner` is the **client** half of FireFunc, published so the machines
@@ -646,6 +667,17 @@ A workspace can manage its machines from Settings → Machines (or the API):
646
667
  so its service starts the new version. It only does this as the installed service
647
668
  (`firefunc-runner install`) and not from npx's cache; otherwise it says why and keeps running.
648
669
  A failed install leaves the old version running and reports npm's last lines.
670
+ - **Update in one step.** `firefunc-runner update` installs the newest runner the way it was
671
+ installed and restarts into it once no run is held. It is the same in PowerShell, zsh and
672
+ bash. It prints the old and new version and "restarted", or says why it could not and the fix.
673
+ - **Updates install themselves.** A machine running as the installed service updates itself when
674
+ idle, within an hour of a new version on npm, unless the workspace (Admin › Policies ›
675
+ Machines) or the machine's own page turns it off. A failed update shows in the Bell with npm's
676
+ words.
677
+ - **A newer runner is out.** At start and once a day the runner asks npm for the newest version
678
+ (only the package name is sent). When one is newer, its log and `firefunc-runner status` say
679
+ so in one line, with `firefunc-runner update`. `FIREFUNC_RUNNER_NO_UPDATE_CHECK=1` turns the
680
+ check off.
649
681
  - **Token lifetime and rotation.** A workspace can give machine tokens a lifetime and a
650
682
  pairing window. The runner replaces its token on its own when a third of its life is left,
651
683
  or when a person asks; the old token works for one more hour. An expired token stops the
@@ -15,6 +15,7 @@ export declare function stepOf(ev: SessionEvent, ctx: {
15
15
  seq: number;
16
16
  now: () => Date;
17
17
  writeTools?: ReadonlySet<string>;
18
+ localServers?: ReadonlySet<string>;
18
19
  }): ActivityStep | null;
19
20
  export declare function createActivityReporter(opts: {
20
21
  worktree: string;
@@ -23,6 +24,7 @@ export declare function createActivityReporter(opts: {
23
24
  cap?: number;
24
25
  now?: () => Date;
25
26
  writeTools?: ReadonlySet<string>;
27
+ localServers?: ReadonlySet<string>;
26
28
  holdMs?: number;
27
29
  seqStart?: number;
28
30
  }): {
package/dist/activity.js CHANGED
@@ -79,6 +79,7 @@ export function stepOf(ev, ctx) {
79
79
  const action = viaFireFunc ? viaFireFunc[2] : mcp.action;
80
80
  const server = TOOL_LABELS[tool] ?? tool;
81
81
  const write = ctx.writeTools?.has(name) === true;
82
+ const local = !viaFireFunc && ctx.localServers?.has(mcp.server) === true;
82
83
  return {
83
84
  ...base,
84
85
  kind: 'tool',
@@ -88,6 +89,7 @@ export function stepOf(ev, ctx) {
88
89
  action,
89
90
  ...(viaFireFunc ? { via: 'firefunc' } : {}),
90
91
  ...(write ? { write: true } : {}),
92
+ ...(local ? { local: true } : {}),
91
93
  },
92
94
  };
93
95
  }
@@ -216,6 +218,7 @@ export function createActivityReporter(opts) {
216
218
  seq: seq + 1,
217
219
  now,
218
220
  writeTools: opts.writeTools,
221
+ localServers: opts.localServers,
219
222
  });
220
223
  if (!step || !step.label.trim())
221
224
  return;
package/dist/alive.d.ts CHANGED
@@ -7,6 +7,7 @@ export type AliveRecord = {
7
7
  startedAt: string;
8
8
  seenAt: string;
9
9
  contactAt: string | null;
10
+ drainSeenAt?: string;
10
11
  transport?: {
11
12
  failingSince: string;
12
13
  failures: number;
@@ -38,3 +39,10 @@ export declare function liveRunnerWords(live: LiveRunner, opts: {
38
39
  logPath: string;
39
40
  os?: string | null;
40
41
  }): string;
42
+ export declare function otherRunnerWarning(rec: AliveRecord | null, opts?: {
43
+ selfPid?: number;
44
+ now?: number;
45
+ os?: string | null;
46
+ alive?: (pid: number) => boolean;
47
+ }): string[] | null;
48
+ export declare function viewerPortWords(port: number, message: string, other: AliveRecord | null, os: string | null): string;
package/dist/alive.js CHANGED
@@ -27,6 +27,7 @@ export function readAlive(runnerDir) {
27
27
  startedAt: typeof rec.startedAt === 'string' ? rec.startedAt : rec.seenAt,
28
28
  seenAt: rec.seenAt,
29
29
  contactAt: typeof rec.contactAt === 'string' ? rec.contactAt : null,
30
+ ...(typeof rec.drainSeenAt === 'string' ? { drainSeenAt: rec.drainSeenAt } : {}),
30
31
  ...(rec.transport &&
31
32
  typeof rec.transport.failingSince === 'string' &&
32
33
  Number.isInteger(rec.transport.failures) &&
@@ -135,4 +136,32 @@ export function liveRunnerWords(live, opts) {
135
136
  transportWords(r, now) +
136
137
  logs);
137
138
  }
139
+ export function otherRunnerWarning(rec, opts = {}) {
140
+ const now = opts.now ?? Date.now();
141
+ const live = liveRunner(rec, now, opts.alive);
142
+ if (live.state !== 'running' || live.rec.pid === (opts.selfPid ?? process.pid))
143
+ return null;
144
+ const r = live.rec;
145
+ const how = r.service ? 'started by the background service' : 'started by hand in a terminal';
146
+ const end = opts.os === 'win32' ? `taskkill /PID ${r.pid} /T /F` : `kill ${r.pid}`;
147
+ return [
148
+ `WARNING: another runner is already running on this machine — pid ${r.pid}` +
149
+ `${r.version ? `, runner ${r.version}` : ''}, ${how}${r.user ? ` as ${r.user}` : ''}, ` +
150
+ `since ${ago(r.startedAt, now)}.`,
151
+ 'Two runners on one machine take work side by side and the second cannot open the live viewer.',
152
+ `Keep one. To keep that one, stop this one (Ctrl+C, or end the service that started it). To keep this one, end the other: ${end}`,
153
+ ];
154
+ }
155
+ export function viewerPortWords(port, message, other, os) {
156
+ if (!/EADDRINUSE|address already in use/i.test(message)) {
157
+ return `session viewer could not start on :${port} (${message}) — set "viewerPort" or pass --no-viewer`;
158
+ }
159
+ if (other) {
160
+ return (`session viewer could not start: port ${port} is held by the other runner on this machine ` +
161
+ `(pid ${other.pid}). Keep one runner, or set "viewerPort" to another port.`);
162
+ }
163
+ const find = os === 'win32' ? `netstat -ano | findstr :${port}` : `lsof -i :${port}`;
164
+ return (`session viewer could not start: another program holds port ${port}. Find it with "${find}", ` +
165
+ `or set "viewerPort" to another port (or pass --no-viewer).`);
166
+ }
138
167
  //# sourceMappingURL=alive.js.map
package/dist/api.d.ts CHANGED
@@ -11,6 +11,7 @@ export type ClaimedJob = {
11
11
  prompt: string;
12
12
  repo: string | null;
13
13
  branch: string | null;
14
+ ticketKey?: string | null;
14
15
  toolsOnly?: boolean;
15
16
  checkpoint?: {
16
17
  ref: string;
@@ -37,7 +38,14 @@ export type ClaimedJob = {
37
38
  planApproved?: boolean;
38
39
  parkStep?: ParkStep;
39
40
  baseBranch?: string | null;
41
+ prDraft?: boolean;
42
+ localTools?: string[];
40
43
  externalId: string | null;
44
+ project?: {
45
+ id: string;
46
+ slug: string | null;
47
+ name: string | null;
48
+ } | null;
41
49
  title: string | null;
42
50
  type: string;
43
51
  engine?: string | null;
@@ -165,6 +173,11 @@ export type ResultPayload = ({
165
173
  usage?: RunUsage;
166
174
  limit?: PlanLimitReport | MachineLimitReport;
167
175
  readHead?: string;
176
+ session?: {
177
+ engine: string;
178
+ id: string | null;
179
+ continued: boolean;
180
+ };
168
181
  openCommandAtEnd?: true;
169
182
  lost?: true;
170
183
  release?: ReleaseReport;
@@ -206,6 +219,12 @@ export declare class RunnerApi {
206
219
  accountLabel: string | null;
207
220
  expiresAt: string | null;
208
221
  detail?: string;
222
+ tools?: Array<{
223
+ name: string;
224
+ readOnly: boolean | null;
225
+ destructive: boolean | null;
226
+ }>;
227
+ toolsListedAt?: string;
209
228
  }>;
210
229
  heldRuns?: string[];
211
230
  lostRuns?: string[];
@@ -256,13 +275,26 @@ export declare class RunnerApi {
256
275
  config(): Promise<{
257
276
  maxParallel: number;
258
277
  requiredCommands: string[] | null;
278
+ checkRepos: string[] | null;
259
279
  signInPrefs: SignInPrefs | null;
280
+ workRoot: string | null;
281
+ cleanUpRequestedAt: string | null;
260
282
  } | null>;
261
283
  gitCredential(runId: string): Promise<{
262
284
  token: string;
263
285
  expiresAt: string;
264
286
  repo: string;
265
287
  } | null>;
288
+ gitCredentialOrRefusal(runId: string): Promise<{
289
+ token: string;
290
+ expiresAt: string;
291
+ repo: string;
292
+ } | {
293
+ refused: {
294
+ reason: string;
295
+ fix: string;
296
+ };
297
+ } | null>;
266
298
  mcpCredential(runId: string, server: string): Promise<{
267
299
  token: string;
268
300
  expiresAt?: string;
package/dist/api.js CHANGED
@@ -265,7 +265,15 @@ export class RunnerApi {
265
265
  requiredCommands: Array.isArray(body.requiredCommands)
266
266
  ? body.requiredCommands.filter((c) => typeof c === 'string')
267
267
  : null,
268
+ checkRepos: Array.isArray(body.checkRepos)
269
+ ? body.checkRepos.filter((c) => typeof c === 'string')
270
+ : null,
268
271
  signInPrefs: parseSignInPrefs(body.signInPrefs),
272
+ workRoot: typeof body.workRoot === 'string' && body.workRoot.trim() ? body.workRoot.trim() : null,
273
+ cleanUpRequestedAt: typeof body.cleanUpRequestedAt === 'string' &&
274
+ Number.isFinite(Date.parse(body.cleanUpRequestedAt))
275
+ ? body.cleanUpRequestedAt
276
+ : null,
269
277
  };
270
278
  }
271
279
  catch {
@@ -273,14 +281,22 @@ export class RunnerApi {
273
281
  }
274
282
  }
275
283
  async gitCredential(runId) {
284
+ const got = await this.gitCredentialOrRefusal(runId);
285
+ return got && 'token' in got ? got : null;
286
+ }
287
+ async gitCredentialOrRefusal(runId) {
276
288
  try {
277
289
  const res = await fetch(`${this.apiUrl}/channel/runs/${runId}/git-credential`, {
278
290
  method: 'POST',
279
291
  headers: { ...this.headers(), 'content-type': 'application/json' },
280
292
  body: '{}',
281
293
  });
282
- if (!res.ok)
283
- return null;
294
+ if (!res.ok) {
295
+ const body = (await res.json().catch(() => null));
296
+ return typeof body?.reason === 'string' && typeof body.fix === 'string'
297
+ ? { refused: { reason: body.reason.slice(0, 400), fix: body.fix.slice(0, 400) } }
298
+ : null;
299
+ }
284
300
  const body = (await res.json());
285
301
  if (!body.ok || !body.token || !body.repo)
286
302
  return null;
@@ -0,0 +1,6 @@
1
+ import type { Readable } from 'node:stream';
2
+ export declare function askToReplace(question: string, opts?: {
3
+ input?: Readable;
4
+ isTTY?: boolean;
5
+ ttyPath?: string | null;
6
+ }): Promise<boolean>;
@@ -0,0 +1,49 @@
1
+ import { openSync, closeSync } from 'node:fs';
2
+ import { ReadStream } from 'node:tty';
3
+ import { createInterface } from 'node:readline';
4
+ export async function askToReplace(question, opts = {}) {
5
+ let input = opts.input ?? null;
6
+ let fd = null;
7
+ if (!input) {
8
+ if (opts.isTTY ?? process.stdin.isTTY)
9
+ input = process.stdin;
10
+ else {
11
+ const path = opts.ttyPath !== undefined
12
+ ? opts.ttyPath
13
+ : process.platform === 'win32' || !process.stderr.isTTY
14
+ ? null
15
+ : '/dev/tty';
16
+ if (!path)
17
+ return false;
18
+ try {
19
+ fd = openSync(path, 'r');
20
+ input = new ReadStream(fd);
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ }
26
+ }
27
+ const rl = createInterface({ input, output: process.stderr, terminal: false });
28
+ try {
29
+ const answer = await new Promise((resolve) => {
30
+ process.stderr.write(question);
31
+ rl.once('line', resolve);
32
+ rl.once('close', () => resolve(''));
33
+ });
34
+ return /^\s*y(es)?\s*$/i.test(answer);
35
+ }
36
+ finally {
37
+ rl.close();
38
+ if (fd !== null && input && input !== process.stdin)
39
+ input.destroy();
40
+ if (fd !== null) {
41
+ try {
42
+ closeSync(fd);
43
+ }
44
+ catch {
45
+ }
46
+ }
47
+ }
48
+ }
49
+ //# sourceMappingURL=ask-replace.js.map
@@ -0,0 +1,8 @@
1
+ export type AwakeTimer = {
2
+ cancel: () => void;
3
+ awakeMs: () => number;
4
+ };
5
+ export declare function awakeTimer(limitMs: number, onLimit: () => void, opts?: {
6
+ tickMs?: number;
7
+ now?: () => number;
8
+ }): AwakeTimer;
@@ -0,0 +1,30 @@
1
+ export function awakeTimer(limitMs, onLimit, opts = {}) {
2
+ const tickMs = opts.tickMs ?? 5_000;
3
+ const now = opts.now ?? Date.now;
4
+ let last = now();
5
+ let awake = 0;
6
+ let done = false;
7
+ const tick = () => {
8
+ if (done)
9
+ return;
10
+ const t = now();
11
+ const gap = t - last;
12
+ last = t;
13
+ awake += gap > tickMs * 3 ? tickMs : Math.max(0, gap);
14
+ if (awake >= limitMs) {
15
+ done = true;
16
+ clearInterval(handle);
17
+ onLimit();
18
+ }
19
+ };
20
+ const handle = setInterval(tick, tickMs);
21
+ handle.unref?.();
22
+ return {
23
+ cancel: () => {
24
+ done = true;
25
+ clearInterval(handle);
26
+ },
27
+ awakeMs: () => awake,
28
+ };
29
+ }
30
+ //# sourceMappingURL=awake-timer.js.map
package/dist/brief.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { mkdtempSync, rmSync, existsSync } from 'node:fs';
2
- import { setWorkDir, workRoot } from './work-dir.js';
2
+ import { scratchRoot, setWorkDir } from './work-dir.js';
3
3
  import { join } from 'node:path';
4
4
  import { exec, execOut } from './exec.js';
5
5
  import { resolveRepoPath } from './job.js';
@@ -102,7 +102,7 @@ export async function runBrief(repo, cfg) {
102
102
  base = head ? head.replace('refs/remotes/origin/', '') : 'main';
103
103
  }
104
104
  setWorkDir(cfg.workDir);
105
- worktree = mkdtempSync(join(workRoot(), 'firefunc-brief-'));
105
+ worktree = mkdtempSync(join(scratchRoot(), 'firefunc-brief-'));
106
106
  const add = await exec('git', ['-C', repoPath, 'worktree', 'add', '--force', '-B', branch, worktree, `origin/${base}`], { timeoutMs: 120_000 });
107
107
  if (add.code !== 0) {
108
108
  out(`git worktree add failed: ${add.stderr.slice(0, 300)}`);
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "0.9.36",
3
- "builtAt": "2026-11-25T07:39:42.553Z"
2
+ "version": "0.9.40",
3
+ "builtAt": "2026-11-27T20:54:51.815Z"
4
4
  }
@@ -0,0 +1,29 @@
1
+ export type CleanUpReport = {
2
+ at: string;
3
+ freedBytes: number;
4
+ };
5
+ export declare function lastCleanUp(): CleanUpReport | null;
6
+ export type RunFolder = {
7
+ path: string;
8
+ runId: string | null;
9
+ };
10
+ export declare function runFoldersIn(roots: readonly string[]): RunFolder[];
11
+ export type SweepDeps = {
12
+ roots?: readonly string[];
13
+ spare: ReadonlySet<string>;
14
+ liveRunIds: ReadonlySet<string>;
15
+ log?: (line: string) => void;
16
+ minAgeMs?: number;
17
+ now?: number;
18
+ size?: (dir: string) => Promise<number | null>;
19
+ };
20
+ export declare function sweepWorkRoot(deps: SweepDeps): Promise<{
21
+ removed: string[];
22
+ freedBytes: number;
23
+ }>;
24
+ export declare function cleanUpNow(deps: {
25
+ runnerDir: string;
26
+ checkouts: readonly string[];
27
+ holding?: Iterable<string>;
28
+ log?: (line: string) => void;
29
+ }): Promise<CleanUpReport>;
@@ -0,0 +1,131 @@
1
+ import { existsSync, readdirSync, rmdirSync, rmSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { keptWorktrees } from './cut.js';
4
+ import { dirBytes } from './drives.js';
5
+ import { heldByLiveProcesses, liveWorktrees } from './held.js';
6
+ import { RESERVED_FOLDERS, checkoutOfWorktree, runMarkerOf, GROUP_MARKER } from './run-folders.js';
7
+ import { removeRunTemp, staleRunTemps, tempRoot } from './run-temp.js';
8
+ import { runRoots, workRoots } from './work-dir.js';
9
+ import { canonicalPath, isLayoutRunFolder, removeRunnerWorktree, sweepLeftoverWorktrees, } from './worktrees.js';
10
+ let last = null;
11
+ export function lastCleanUp() {
12
+ return last;
13
+ }
14
+ export function runFoldersIn(roots) {
15
+ const out = [];
16
+ for (const root of new Set(roots)) {
17
+ for (const group of safeList(root)) {
18
+ if (!isGroup(group))
19
+ continue;
20
+ const g = join(root, group);
21
+ for (const name of safeList(g)) {
22
+ const p = join(g, name);
23
+ if (isLayoutRunFolder(p, { layoutRoots: [root] }))
24
+ out.push({ path: p, runId: runMarkerOf(p) });
25
+ }
26
+ }
27
+ }
28
+ return out;
29
+ }
30
+ const isGroup = (name) => !!name && !name.startsWith('.') && !RESERVED_FOLDERS.has(name.toLowerCase());
31
+ function safeList(dir) {
32
+ try {
33
+ return readdirSync(dir);
34
+ }
35
+ catch {
36
+ return [];
37
+ }
38
+ }
39
+ const isDir = (p) => {
40
+ try {
41
+ return statSync(p).isDirectory();
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ };
47
+ export async function sweepWorkRoot(deps) {
48
+ const roots = deps.roots ?? runRoots();
49
+ const spare = new Set([...deps.spare].map(canonicalPath));
50
+ const now = deps.now ?? Date.now();
51
+ const minAge = deps.minAgeMs ?? 2 * 60_000;
52
+ const size = deps.size ?? ((d) => dirBytes(d, 5_000));
53
+ const removed = [];
54
+ let freed = 0;
55
+ for (const f of runFoldersIn(roots)) {
56
+ try {
57
+ if (spare.has(canonicalPath(f.path)))
58
+ continue;
59
+ if (f.runId && deps.liveRunIds.has(f.runId))
60
+ continue;
61
+ if (now - statSync(f.path).mtimeMs < minAge)
62
+ continue;
63
+ const bytes = await size(f.path).catch(() => null);
64
+ const checkout = checkoutOfWorktree(f.path);
65
+ deps.log?.(`removing a run folder no run holds: ${f.path}`);
66
+ if (checkout && existsSync(checkout)) {
67
+ await removeRunnerWorktree(checkout, f.path, deps.log ?? (() => { }));
68
+ }
69
+ rmSync(f.path, { recursive: true, force: true });
70
+ if (!existsSync(f.path)) {
71
+ removed.push(f.path);
72
+ freed += bytes ?? 0;
73
+ }
74
+ }
75
+ catch {
76
+ }
77
+ }
78
+ for (const root of new Set(roots)) {
79
+ for (const group of safeList(root)) {
80
+ if (!isGroup(group))
81
+ continue;
82
+ const g = join(root, group);
83
+ const left = isDir(g) ? safeList(g) : null;
84
+ if (left && left.length === 1 && left[0] === GROUP_MARKER) {
85
+ try {
86
+ rmSync(join(g, GROUP_MARKER), { force: true });
87
+ rmdirSync(g);
88
+ }
89
+ catch {
90
+ }
91
+ }
92
+ }
93
+ const tmp = join(root, '_tmp');
94
+ for (const n of safeList(tmp)) {
95
+ const p = join(tmp, n);
96
+ if (isDir(p) && safeList(p).length === 0) {
97
+ try {
98
+ rmdirSync(p);
99
+ }
100
+ catch {
101
+ }
102
+ }
103
+ }
104
+ }
105
+ return { removed, freedBytes: freed };
106
+ }
107
+ export async function cleanUpNow(deps) {
108
+ const log = deps.log ?? (() => { });
109
+ let freed = 0;
110
+ try {
111
+ const live = liveWorktrees(deps.runnerDir);
112
+ const kept = keptWorktrees(deps.runnerDir);
113
+ const liveRunIds = new Set([...heldByLiveProcesses(deps.runnerDir), ...(deps.holding ?? [])]);
114
+ const r = await sweepWorkRoot({ spare: new Set([...live, ...kept]), liveRunIds, log });
115
+ freed += r.freedBytes;
116
+ if (r.removed.length)
117
+ log(`clean-up removed ${r.removed.length} run folder(s)`);
118
+ const checkouts = deps.checkouts.filter((p) => existsSync(p));
119
+ await sweepLeftoverWorktrees(checkouts, { live, keep: kept, log });
120
+ const stale = staleRunTemps([tempRoot(), ...workRoots()], live);
121
+ for (const dir of stale) {
122
+ freed += (await dirBytes(dir, 5_000).catch(() => null)) ?? 0;
123
+ removeRunTemp(dir);
124
+ }
125
+ }
126
+ catch {
127
+ }
128
+ last = { at: new Date().toISOString(), freedBytes: freed };
129
+ return last;
130
+ }
131
+ //# sourceMappingURL=clean-up.js.map