@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/dist/mcp.js CHANGED
@@ -52,6 +52,8 @@ export function mcpFormatForEngine(engine) {
52
52
  function toolNamesFor(servers) {
53
53
  const names = new Set();
54
54
  for (const server of servers) {
55
+ if (server.local)
56
+ names.add(`mcp__${server.id}`);
55
57
  for (const tool of server.allowedTools)
56
58
  names.add(`mcp__${server.id}__${tool}`);
57
59
  }
@@ -340,7 +342,12 @@ function claudeBody(resolved) {
340
342
  for (const { spec, cred } of resolved) {
341
343
  servers[spec.id] =
342
344
  spec.transport === 'stdio'
343
- ? { type: 'stdio', command: spec.command, ...(spec.args ? { args: spec.args } : {}) }
345
+ ? {
346
+ type: 'stdio',
347
+ command: spec.command,
348
+ ...(spec.args?.length ? { args: spec.args } : {}),
349
+ ...(spec.env && Object.keys(spec.env).length ? { env: spec.env } : {}),
350
+ }
344
351
  : {
345
352
  type: spec.transport,
346
353
  url: spec.url,
@@ -453,8 +460,32 @@ export async function prepareMcp(opts) {
453
460
  catch {
454
461
  }
455
462
  };
456
- const config = parseRunConfig(opts.raw, log, (id) => drop(id, 'rejected'));
457
- if (!config || config.servers.length === 0)
463
+ const parsed = opts.raw == null ? null : parseRunConfig(opts.raw, log, (id) => drop(id, 'rejected'));
464
+ const locals = [];
465
+ for (const l of opts.local ?? []) {
466
+ if (opts.format !== 'claude') {
467
+ log(`mcp: skipping local tool ${l.id} on ${opts.format} — local tools reach Claude Code runs only. Fix: run this agent on Claude Code.`);
468
+ drop(l.id, 'unusable_on_engine');
469
+ continue;
470
+ }
471
+ if (parsed?.servers.some((s) => s.id === l.id) || !SERVER_ID_PATTERN.test(l.id)) {
472
+ log(`mcp: skipping local tool ${l.id} — FireFunc's own tools use that name. Fix: firefunc-runner mcp remove ${l.id}, then add it under another name.`);
473
+ drop(l.id, 'rejected');
474
+ continue;
475
+ }
476
+ locals.push({
477
+ id: l.id,
478
+ transport: 'stdio',
479
+ command: l.command,
480
+ ...(l.args.length ? { args: [...l.args] } : {}),
481
+ ...(Object.keys(l.env).length ? { env: { ...l.env } } : {}),
482
+ auth: 'none',
483
+ allowedTools: [],
484
+ local: true,
485
+ });
486
+ }
487
+ const config = parsed ?? (locals.length ? { servers: [], callBudget: null } : null);
488
+ if (!config || config.servers.length + locals.length === 0)
458
489
  return null;
459
490
  const usable = [];
460
491
  for (const spec of config.servers) {
@@ -466,6 +497,7 @@ export async function prepareMcp(opts) {
466
497
  }
467
498
  usable.push(spec);
468
499
  }
500
+ usable.push(...locals);
469
501
  if (!usable.length)
470
502
  return null;
471
503
  const relative = CONFIG_PATHS[opts.format];
@@ -649,6 +681,8 @@ export async function prepareMcp(opts) {
649
681
  : `call budget ${config.callBudget} (recorded — no CLI here can enforce it)`;
650
682
  const logLine = `${written.length} server(s) — ${written
651
683
  .map((s) => {
684
+ if (s.local)
685
+ return `${s.id} (local tool on this machine, all its tools)`;
652
686
  const total = s.allowedTools.length;
653
687
  const writes = s.writeTools?.length ?? 0;
654
688
  const tools = s.writeTools
@@ -0,0 +1,9 @@
1
+ export declare const RUNNER_REGISTRY_URL = "https://registry.npmjs.org/@firefunc-agent/runner";
2
+ export declare const NEWER_RUNNER_CHECK_MS: number;
3
+ export declare function isNewer(latest: string | null | undefined, version: string | null | undefined): boolean;
4
+ export declare const UPDATE_COMMAND = "firefunc-runner update";
5
+ export declare function newerRunnerLine(version: string, latest: string | null, service: boolean): string | null;
6
+ export declare function readLatestRunner(opts?: {
7
+ fetch?: typeof fetch;
8
+ timeoutMs?: number;
9
+ }): Promise<string | null>;
@@ -0,0 +1,38 @@
1
+ export const RUNNER_REGISTRY_URL = 'https://registry.npmjs.org/@firefunc-agent/runner';
2
+ export const NEWER_RUNNER_CHECK_MS = 24 * 60 * 60 * 1000;
3
+ const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/;
4
+ export function isNewer(latest, version) {
5
+ const a = SEMVER.exec(latest ?? '');
6
+ const b = SEMVER.exec(version ?? '');
7
+ if (!a || !b)
8
+ return false;
9
+ for (let i = 1; i <= 3; i += 1) {
10
+ const x = Number(a[i]);
11
+ const y = Number(b[i]);
12
+ if (x !== y)
13
+ return x > y;
14
+ }
15
+ return false;
16
+ }
17
+ export const UPDATE_COMMAND = 'firefunc-runner update';
18
+ export function newerRunnerLine(version, latest, service) {
19
+ if (!isNewer(latest, version))
20
+ return null;
21
+ return `A newer runner is out: ${latest} (this is ${version}). Update: ${UPDATE_COMMAND}${service ? ' — or it installs itself when idle, if the workspace keeps updates automatic' : ''}`;
22
+ }
23
+ export async function readLatestRunner(opts = {}) {
24
+ try {
25
+ const res = await (opts.fetch ?? fetch)(RUNNER_REGISTRY_URL, {
26
+ headers: { accept: 'application/vnd.npm.install-v1+json' },
27
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 10_000),
28
+ });
29
+ if (!res.ok)
30
+ return null;
31
+ const v = (await res.json())?.['dist-tags']?.latest;
32
+ return typeof v === 'string' && SEMVER.test(v) ? v : null;
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
38
+ //# sourceMappingURL=newer-runner.js.map
package/dist/pool.d.ts CHANGED
@@ -5,6 +5,7 @@ export type JobPoolDeps<J> = {
5
5
  claim: () => Promise<J | null>;
6
6
  run: (job: J) => Promise<void>;
7
7
  onClaimError?: (err: unknown) => Promise<'fatal' | 'retry'>;
8
+ onDrainSeen?: () => void;
8
9
  onStart?: (job: J, inFlight: number) => void;
9
10
  idleDelayMs?: number;
10
11
  maxIdleDelayMs?: number;
package/dist/pool.js CHANGED
@@ -75,6 +75,7 @@ export async function runJobPool(deps) {
75
75
  }
76
76
  const limit = cap();
77
77
  if (limit === 0) {
78
+ deps.onDrainSeen?.();
78
79
  if (active.size === 0 && !drainedTold) {
79
80
  drainedTold = true;
80
81
  deps.onDrained?.();
@@ -24,3 +24,4 @@ export declare function withProvenanceFooter(body: string, job: {
24
24
  prFooter?: string | null;
25
25
  } | null;
26
26
  }): string;
27
+ export declare function withTicketKey(title: string, key: string | null | undefined): string;
package/dist/pr-title.js CHANGED
@@ -93,4 +93,11 @@ export function withProvenanceFooter(body, job) {
93
93
  .slice(0, 500);
94
94
  return footer ? `${body.trimEnd()}\n\n${footer}` : body;
95
95
  }
96
+ export function withTicketKey(title, key) {
97
+ const k = (key ?? '').trim();
98
+ if (!k || title.toUpperCase().includes(k.toUpperCase()))
99
+ return title;
100
+ const m = /^([a-z]+(?:\([^)]*\))?!?:)\s*/.exec(title);
101
+ return m ? `${m[1]} ${k} ${title.slice(m[0].length)}` : `${k} ${title}`;
102
+ }
96
103
  //# sourceMappingURL=pr-title.js.map
@@ -0,0 +1,15 @@
1
+ export declare function expandPath(p: string, env?: NodeJS.ProcessEnv): string;
2
+ export type RepoPathCheck = {
3
+ ok: true;
4
+ path: string;
5
+ } | {
6
+ ok: false;
7
+ path: string;
8
+ reason: string;
9
+ fix: string;
10
+ };
11
+ export declare function repoOfRemote(url: string): string | null;
12
+ export declare function checkRepoPath(repo: string, typed: string, run?: (args: string[], cwd: string) => {
13
+ code: number;
14
+ out: string;
15
+ }): RepoPathCheck;
@@ -0,0 +1,56 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, statSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { expandHome } from './config.js';
5
+ export function expandPath(p, env = process.env) {
6
+ const out = p
7
+ .trim()
8
+ .replace(/^"(.*)"$/, '$1')
9
+ .replace(/%([A-Za-z_][A-Za-z0-9_]*)%/g, (m, n) => env[n] ?? env[n.toUpperCase()] ?? m)
10
+ .replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (m, n) => env[n] ?? m)
11
+ .replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g, (m, n) => env[n] ?? m);
12
+ return expandHome(out);
13
+ }
14
+ export function repoOfRemote(url) {
15
+ const m = /[:/]([^/:]+\/[^/]+?)(?:\.git)?\/?$/.exec(url.trim());
16
+ return m ? m[1] : null;
17
+ }
18
+ export function checkRepoPath(repo, typed, run = (args, cwd) => {
19
+ const r = spawnSync('git', args, { cwd, encoding: 'utf8' });
20
+ return { code: r.status ?? 1, out: `${r.stdout ?? ''}`.trim() };
21
+ }) {
22
+ const path = expandPath(typed);
23
+ const unexpanded = /%[A-Za-z_]+%|\$\{?[A-Za-z_]/.exec(path);
24
+ if (unexpanded)
25
+ return {
26
+ ok: false,
27
+ path,
28
+ reason: `${unexpanded[0]} in the path is not set on this machine.`,
29
+ fix: 'Type the full path instead, e.g. "C:\\Users\\you\\src\\repo".',
30
+ };
31
+ if (!existsSync(path) || !statSync(path).isDirectory())
32
+ return {
33
+ ok: false,
34
+ path,
35
+ reason: `No folder at ${path}.`,
36
+ fix: `Clone it there first (git clone https://github.com/${repo} "${path}"), or give the folder it is in.`,
37
+ };
38
+ if (!existsSync(join(path, '.git')))
39
+ return {
40
+ ok: false,
41
+ path,
42
+ reason: `${path} is not a git checkout.`,
43
+ fix: `Give the folder the repository was cloned into (it holds a .git folder).`,
44
+ };
45
+ const remote = run(['remote', 'get-url', 'origin'], path);
46
+ const named = remote.code === 0 ? repoOfRemote(remote.out) : null;
47
+ if (named && named.toLowerCase() !== repo.toLowerCase())
48
+ return {
49
+ ok: false,
50
+ path,
51
+ reason: `${path} is a checkout of ${named}, not ${repo}.`,
52
+ fix: `Give the folder that holds ${repo}, or map ${named} instead.`,
53
+ };
54
+ return { ok: true, path };
55
+ }
56
+ //# sourceMappingURL=repo-path.js.map
@@ -1,5 +1,9 @@
1
1
  import { type DeviceReport } from './device-lease.js';
2
2
  import { type MachineProfile } from './machine-profile.js';
3
+ import { type WorkRootSource } from './work-dir.js';
4
+ import { type DriveReport } from './drives.js';
5
+ import { type CleanUpReport } from './clean-up.js';
6
+ import { type ReclaimReport } from './disk-reclaim.js';
3
7
  export type ResourceReading = {
4
8
  freeBytes: number;
5
9
  totalBytes: number | null;
@@ -11,6 +15,11 @@ export type ResourcesReport = {
11
15
  timeLimitMinutes: number;
12
16
  devices?: DeviceReport;
13
17
  workDir?: WorkDirReport;
18
+ workRoot?: WorkRootReport;
19
+ drives?: DriveReport[];
20
+ localTools?: string[];
21
+ cleanUp?: CleanUpReport | null;
22
+ reclaim?: ReclaimReport | null;
14
23
  cpus?: number;
15
24
  load1PerCore?: number;
16
25
  maxHeavyRuns?: number;
@@ -28,6 +37,16 @@ export type WorkDirReport = {
28
37
  set: boolean;
29
38
  usable: boolean;
30
39
  };
40
+ export type WorkRootReport = {
41
+ path: string;
42
+ usable: boolean;
43
+ reason?: string;
44
+ fix?: string;
45
+ bytes: number | null;
46
+ freeBytes: number | null;
47
+ totalBytes: number | null;
48
+ source: WorkRootSource;
49
+ };
31
50
  export declare const DEFAULT_MIN_FREE_DISK_GB = 5;
32
51
  export declare const DEFAULT_MIN_FREE_MEMORY_GB = 1;
33
52
  export declare const DEFAULT_JOB_TIMEOUT_MINUTES = 20;
@@ -47,6 +66,7 @@ export declare function macAvailableFromVmStat(out: string): number | null;
47
66
  export declare function linuxAvailableFromMeminfo(text: string): number | null;
48
67
  export declare function availableMemory(os?: NodeJS.Platform): number;
49
68
  export type ResourceCfg = {
69
+ localTools?: Record<string, unknown>;
50
70
  workDir?: string;
51
71
  minFreeDiskGB?: number;
52
72
  minFreeMemoryGB?: number;
@@ -66,14 +86,32 @@ export declare function readResources(cfg: ResourceCfg, runnerDir: string, deps?
66
86
  memory?: () => number;
67
87
  totalMemory?: () => number;
68
88
  workDir?: () => WorkDirReport;
89
+ workRoot?: () => WorkRootReport;
90
+ drives?: () => DriveReport[];
91
+ cleanUp?: () => CleanUpReport | null;
69
92
  devices?: () => DeviceReport;
70
93
  processor?: () => {
71
94
  cpus: number;
72
95
  load1PerCore: number | null;
73
96
  };
74
97
  profile?: () => MachineProfile | null;
98
+ localTools?: () => string[];
75
99
  }): ResourcesReport;
76
100
  export declare function workDirReport(): WorkDirReport;
101
+ export declare function workRootReport(read?: {
102
+ check?: () => {
103
+ root: string;
104
+ usable: boolean;
105
+ reason?: string;
106
+ fix?: string;
107
+ };
108
+ source?: () => WorkRootSource;
109
+ disk?: (dir: string) => {
110
+ freeBytes: number;
111
+ totalBytes: number;
112
+ } | null;
113
+ bytes?: (dir: string) => number | null;
114
+ }): WorkRootReport;
77
115
  export declare function shortOf(r: ResourcesReport): Array<'disk' | 'memory'>;
78
116
  export declare function resourceWatch(deps: {
79
117
  read: () => ResourcesReport;
package/dist/resources.js CHANGED
@@ -5,7 +5,11 @@ import { deviceReport } from './device-lease.js';
5
5
  import { deviceLockDir } from './locks.js';
6
6
  import { commandOnPath, runPath } from './machine-commands.js';
7
7
  import { machineProfile } from './machine-profile.js';
8
- import { workDir, workDirFailure } from './work-dir.js';
8
+ import { workDir, workDirFailure, workRootCheck, workRootSource, } from './work-dir.js';
9
+ import { driveReport, rootBytes } from './drives.js';
10
+ import { localToolNames } from './local-tools.js';
11
+ import { lastCleanUp } from './clean-up.js';
12
+ import { lastReclaim } from './disk-reclaim.js';
9
13
  export function heavyRunBudget(setting, memBytes = totalmem()) {
10
14
  if (typeof setting === 'number' && Number.isInteger(setting) && setting >= 1) {
11
15
  return Math.min(16, setting);
@@ -101,9 +105,18 @@ export function hasDeviceTools(cfg, has = (n, p) => commandOnPath(n, p)) {
101
105
  return has('adb', runPath(cfg));
102
106
  }
103
107
  export function readResources(cfg, runnerDir, deps = {}) {
108
+ const root = (() => {
109
+ try {
110
+ return deps.workRoot ? deps.workRoot() : workRootReport();
111
+ }
112
+ catch {
113
+ return null;
114
+ }
115
+ })();
104
116
  const dirs = [
105
117
  tmpdir(),
106
118
  ...(cfg.workDir ? [cfg.workDir] : []),
119
+ ...(root?.usable ? [root.path] : []),
107
120
  runnerDir,
108
121
  ...Object.values(cfg.repos ?? {}),
109
122
  ];
@@ -144,6 +157,26 @@ export function readResources(cfg, runnerDir, deps = {}) {
144
157
  : null,
145
158
  timeLimitMinutes: Math.round(limit),
146
159
  workDir: deps.workDir ? deps.workDir() : workDirReport(),
160
+ ...(root ? { workRoot: root } : {}),
161
+ drives: (() => {
162
+ try {
163
+ return deps.drives ? deps.drives() : driveReport();
164
+ }
165
+ catch {
166
+ return [];
167
+ }
168
+ })(),
169
+ cleanUp: deps.cleanUp ? deps.cleanUp() : lastCleanUp(),
170
+ reclaim: lastReclaim(),
171
+ ...(() => {
172
+ try {
173
+ const names = deps.localTools ? deps.localTools() : localToolNames(cfg);
174
+ return names.length ? { localTools: names } : {};
175
+ }
176
+ catch {
177
+ return {};
178
+ }
179
+ })(),
147
180
  devices: (() => {
148
181
  try {
149
182
  if (deps.devices)
@@ -172,6 +205,19 @@ export function workDirReport() {
172
205
  const set = workDir() !== null;
173
206
  return { set, usable: !set || workDirFailure() === null };
174
207
  }
208
+ export function workRootReport(read = {}) {
209
+ const c = (read.check ?? (() => workRootCheck()))();
210
+ const d = c.usable ? (read.disk ?? diskOf)(c.root) : null;
211
+ return {
212
+ path: c.root,
213
+ usable: c.usable,
214
+ ...(c.usable ? {} : { reason: c.reason, fix: c.fix }),
215
+ bytes: c.usable ? (read.bytes ?? ((r) => rootBytes(r)))(c.root) : null,
216
+ freeBytes: d ? d.freeBytes : null,
217
+ totalBytes: d ? d.totalBytes : null,
218
+ source: (read.source ?? workRootSource)(),
219
+ };
220
+ }
175
221
  export function shortOf(r) {
176
222
  const out = [];
177
223
  if (r.disk && r.disk.floorBytes > 0 && r.disk.freeBytes < r.disk.floorBytes)
@@ -14,6 +14,7 @@ export type RestartIdleDeps = {
14
14
  settleMs?: number;
15
15
  pollMs?: number;
16
16
  maxWaitMs?: number | null;
17
+ drainSeen?: () => string | null;
17
18
  };
18
19
  export type RestartIdleResult = {
19
20
  ok: boolean;
@@ -19,11 +19,17 @@ export async function restartWhenIdle(d) {
19
19
  const started = d.now();
20
20
  d.log('Draining: the runner finishes the runs it holds and takes nothing new; it restarts once none is left.');
21
21
  let told = -1;
22
+ let toldSettle = -1;
22
23
  for (;;) {
23
24
  const held = d.held();
24
25
  const waited = d.now() - started;
25
- if (held.length === 0 && waited >= settle)
26
+ const seen = d.drainSeen?.() ?? null;
27
+ const confirmed = !!seen && (drainedBefore || Date.parse(seen) >= started - 1_000);
28
+ if (held.length === 0 && (confirmed || waited >= settle)) {
29
+ if (confirmed && waited < settle)
30
+ d.log('The runner confirmed it takes nothing new.');
26
31
  break;
32
+ }
27
33
  if (d.maxWaitMs != null && waited >= d.maxWaitMs) {
28
34
  lift();
29
35
  return {
@@ -35,11 +41,20 @@ export async function restartWhenIdle(d) {
35
41
  'Run "firefunc-runner restart --when-idle" again without --max-wait to wait for them.',
36
42
  };
37
43
  }
38
- if (held.length !== told) {
44
+ if (held.length > 0 && held.length !== told) {
39
45
  told = held.length;
40
- d.log(held.length > 0
41
- ? `waiting for ${held.length} run${held.length === 1 ? '' : 's'} to finish: ${held.join(', ')}`
42
- : 'no run held — waiting a moment for the runner to read the drain');
46
+ d.log(`waiting for ${held.length} run${held.length === 1 ? '' : 's'} to finish: ${held.join(', ')}`);
47
+ }
48
+ else if (held.length === 0) {
49
+ const left = Math.max(0, Math.ceil((settle - waited) / 1000));
50
+ const step = Math.floor(left / 10);
51
+ if (told !== 0 || step !== toldSettle) {
52
+ d.log(told !== 0
53
+ ? `No run held. Waiting up to ${left} s for the runner to confirm it takes nothing new, so a run being picked up right now cannot be cut short.`
54
+ : ` …up to ${left} s left`);
55
+ told = 0;
56
+ toldSettle = step;
57
+ }
43
58
  }
44
59
  await d.sleep(poll);
45
60
  }
@@ -0,0 +1,25 @@
1
+ export declare const RUN_MARKER = ".firefunc-run";
2
+ export declare const GROUP_MARKER = ".firefunc-project";
3
+ export declare const RESERVED_FOLDERS: Set<string>;
4
+ export declare const NO_PROJECT_FOLDER = "runs";
5
+ export type RunProject = {
6
+ id: string;
7
+ slug: string | null;
8
+ name: string | null;
9
+ } | null;
10
+ export declare function safeSegment(text: string | null | undefined, max?: number): string;
11
+ export declare function projectFolder(project: RunProject | undefined): string | null;
12
+ export declare function runFolderName(externalId: string | null | undefined, runId: string): string;
13
+ export declare function runFolderPath(root: string, job: {
14
+ runId: string;
15
+ externalId?: string | null;
16
+ project?: RunProject;
17
+ }): string;
18
+ export declare function makeRunFolder(root: string, job: {
19
+ runId: string;
20
+ externalId?: string | null;
21
+ project?: RunProject;
22
+ }): string;
23
+ export declare function writeRunMarker(folder: string, runId: string): boolean;
24
+ export declare function runMarkerOf(folder: string): string | null;
25
+ export declare function checkoutOfWorktree(folder: string): string | null;
@@ -0,0 +1,89 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ export const RUN_MARKER = '.firefunc-run';
4
+ export const GROUP_MARKER = '.firefunc-project';
5
+ export const RESERVED_FOLDERS = new Set(['_tmp', '_cache', 'kept', 'tmp']);
6
+ export const NO_PROJECT_FOLDER = 'runs';
7
+ export function safeSegment(text, max = 40) {
8
+ const s = (text ?? '')
9
+ .replace(/[^A-Za-z0-9._-]+/g, '-')
10
+ .replace(/-{2,}/g, '-')
11
+ .replace(/^[.-]+/, '')
12
+ .slice(0, max)
13
+ .replace(/[.-]+$/, '');
14
+ return s === '.' || s === '..' ? '' : s;
15
+ }
16
+ export function projectFolder(project) {
17
+ if (!project)
18
+ return null;
19
+ const seg = safeSegment(project.slug) || safeSegment(project.id, 8);
20
+ if (!seg)
21
+ return null;
22
+ const lower = seg.toLowerCase();
23
+ return RESERVED_FOLDERS.has(lower) || lower === NO_PROJECT_FOLDER ? `p-${seg}` : seg;
24
+ }
25
+ export function runFolderName(externalId, runId) {
26
+ const ref = safeSegment(externalId) || 'task';
27
+ const short = runId.replace(/[^A-Za-z0-9]/g, '').slice(0, 8) || 'run';
28
+ return `${ref}-${short}`;
29
+ }
30
+ export function runFolderPath(root, job) {
31
+ return join(root, projectFolder(job.project) ?? NO_PROJECT_FOLDER, runFolderName(job.externalId, job.runId));
32
+ }
33
+ export function makeRunFolder(root, job) {
34
+ const base = runFolderPath(root, job);
35
+ const group = join(base, '..');
36
+ mkdirSync(group, { recursive: true });
37
+ try {
38
+ writeFileSync(join(group, GROUP_MARKER), 'firefunc\n', { flag: 'wx' });
39
+ }
40
+ catch {
41
+ }
42
+ for (let n = 1; n < 1000; n++) {
43
+ const p = n === 1 ? base : `${base}-${n}`;
44
+ if (existsSync(p))
45
+ continue;
46
+ try {
47
+ mkdirSync(p);
48
+ return p;
49
+ }
50
+ catch (err) {
51
+ if (err.code === 'EEXIST')
52
+ continue;
53
+ throw err;
54
+ }
55
+ }
56
+ throw new Error(`could not find a free folder name for ${base}`);
57
+ }
58
+ export function writeRunMarker(folder, runId) {
59
+ try {
60
+ writeFileSync(join(folder, RUN_MARKER), `${JSON.stringify({ runId, at: new Date().toISOString() })}\n`);
61
+ return true;
62
+ }
63
+ catch {
64
+ return false;
65
+ }
66
+ }
67
+ export function runMarkerOf(folder) {
68
+ try {
69
+ const v = JSON.parse(readFileSync(join(folder, RUN_MARKER), 'utf8'));
70
+ return typeof v.runId === 'string' && v.runId ? v.runId : null;
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ }
76
+ export function checkoutOfWorktree(folder) {
77
+ try {
78
+ const text = readFileSync(join(folder, '.git'), 'utf8');
79
+ const gitdir = /^gitdir:\s*(.+)$/m.exec(text)?.[1]?.trim();
80
+ if (!gitdir)
81
+ return null;
82
+ const m = /^(.*)[\\/]\.git[\\/]worktrees[\\/][^\\/]+$/.exec(gitdir);
83
+ return m?.[1] ?? null;
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ }
89
+ //# sourceMappingURL=run-folders.js.map
@@ -0,0 +1,41 @@
1
+ import { type RestartIdleDeps } from './restart-idle.js';
2
+ export declare const RUNNER_PACKAGE = "@firefunc-agent/runner";
3
+ export type UpdateDeps = Omit<RestartIdleDeps, 'restart'> & {
4
+ current: string;
5
+ running?: () => string | null;
6
+ latest: () => Promise<string | null>;
7
+ scriptPath: string;
8
+ service: {
9
+ installed: () => Promise<boolean>;
10
+ stop: () => Promise<{
11
+ ok: boolean;
12
+ message: string;
13
+ }>;
14
+ start: (want: string) => Promise<{
15
+ ok: boolean;
16
+ message: string;
17
+ }>;
18
+ };
19
+ run: (cmd: string, args: string[]) => Promise<{
20
+ code: number;
21
+ output: string;
22
+ }>;
23
+ installedVersion: () => Promise<string | null>;
24
+ };
25
+ export type UpdateResult = {
26
+ ok: boolean;
27
+ message: string;
28
+ from: string;
29
+ to: string | null;
30
+ };
31
+ export declare function installCommand(scriptPath: string, spec: string): {
32
+ cmd: string;
33
+ args: string[];
34
+ };
35
+ export declare function updateRunner(d: UpdateDeps): Promise<UpdateResult>;
36
+ export declare function unknownWords(args: readonly string[], known: readonly string[], withValue?: readonly string[]): string | null;
37
+ export declare function runQuiet(cmd: string, args: string[]): Promise<{
38
+ code: number;
39
+ output: string;
40
+ }>;
41
+ export declare function installedRunnerVersion(): Promise<string | null>;