@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/cli.js CHANGED
@@ -1,16 +1,24 @@
1
1
  #!/usr/bin/env node
2
+ import { checkRepoPath } from './repo-path.js';
2
3
  import { configPath, drainSetting, expandHome, isDraining, loadConfig, runnerDir, saveConfig, editorsAllowed, } from './config.js';
3
4
  import { startDaemon } from './daemon.js';
5
+ import { askToReplace } from './ask-replace.js';
4
6
  import { restartWhenIdle } from './restart-idle.js';
7
+ import { installedRunnerVersion, runQuiet, unknownWords, updateRunner } from './update.js';
8
+ import { endLiveRunner, startRunner, stopRunner, versionGapWords, } from './live-runner.js';
5
9
  import { heldByLiveProcesses } from './held.js';
6
10
  import { runBrief } from './brief.js';
7
11
  import { runMcpList, runMcpLogin, runMcpLogout } from './mcp-login.js';
12
+ import { localToolsListing, runMcpAdd, runMcpRemove } from './local-tools.js';
8
13
  import { RUNNER_VERSION } from './version.js';
9
14
  import { availableEngines, getAdapter } from './engines/index.js';
10
15
  import { engineBlocks, unattendedContext } from './unattended.js';
11
16
  import { engineLoginBlock } from './engine-login.js';
12
- import { liveRunner, liveRunnerWords, readAlive } from './alive.js';
13
- import { setWorkDir, workDirFailure, workDirWords } from './work-dir.js';
17
+ import { liveRunner, liveRunnerWords, pidAlive, readAlive } from './alive.js';
18
+ import { newerRunnerLine, readLatestRunner } from './newer-runner.js';
19
+ import { loadWorkspaceRoot, setWorkDir, setWorkspaceRoot, workDirFailure, workDirWords, workRootWords, } from './work-dir.js';
20
+ import { workRootReport } from './resources.js';
21
+ import { dirBytes } from './drives.js';
14
22
  import { diskOf } from './resources.js';
15
23
  import { currentPlatform, defaultServiceDeps, EPHEMERAL_INSTALL_MESSAGE, installService, isEphemeralInstall, readLogTail, renderLaunchdPlist, renderSystemdUnit, renderWindowsLauncher, renderWindowsTaskXml, serviceStatus, serviceWords, servicePaths, startService, stopService, uninstallService, } from './service.js';
16
24
  const HELP = `firefunc-runner — run YOUR local coding agent on work FireFunc routes to you.
@@ -37,6 +45,8 @@ Usage:
37
45
  (the machine stays online); safe to update or
38
46
  restart once the log says "drained"
39
47
  firefunc-runner resume Take work again after a drain
48
+ firefunc-runner update Install the newest runner and restart into it
49
+ once no run is held (one step, any shell)
40
50
  firefunc-runner restart --when-idle Drain, wait until no run is held, restart the
41
51
  service, then take work again
42
52
  (--max-wait <minutes> gives up after that)
@@ -146,6 +156,12 @@ this one, the newest event on the issue):
146
156
  rather than left waiting for a window that never opens.
147
157
  GitHub needs no login: FireFunc mints it a read-only, one-repo, one-hour token
148
158
  per run — narrower than any machine-wide sign-in could be.
159
+ mcp add <name> [--env NAME=value] -- <command…>
160
+ An MCP server that lives on THIS machine, such as computer use
161
+ (mcp add windows-mcp -- uvx windows-mcp serve). Only you can add it,
162
+ here; FireFunc sees its name and a run gets it only when its
163
+ agent is granted that name. Claude Code runs only.
164
+ mcp remove <name> Take a local tool away.
149
165
 
150
166
  Examples:
151
167
  firefunc-runner connect ffr_xxx --repos-dir ~/code
@@ -206,6 +222,14 @@ async function main() {
206
222
  claudeEnv[e.slice(0, i)] = e.slice(i + 1);
207
223
  }
208
224
  const existing = loadConfig();
225
+ if (existing &&
226
+ existing.token !== token &&
227
+ !f.force &&
228
+ (await askToReplace(`This machine is already paired${existing.name ? ` as "${existing.name}"` : ''} with another token.\n` +
229
+ `Replacing it pairs it with the new one; it keeps its repos and engine settings.\n` +
230
+ `Replace it? [y/N] `))) {
231
+ f.force = ['true'];
232
+ }
209
233
  if (existing && existing.token !== token && !f.force) {
210
234
  process.stderr.write(`This machine is already connected to FireFunc with a different runner token.\n\n` +
211
235
  `Connecting again would REPLACE that token, so this machine would stop\n` +
@@ -275,9 +299,15 @@ async function main() {
275
299
  process.exitCode = 1;
276
300
  return;
277
301
  }
278
- cfg.repos = { ...(cfg.repos ?? {}), [name]: expandHome(localPath) };
302
+ const checked = checkRepoPath(name, localPath);
303
+ if (!checked.ok) {
304
+ process.stderr.write(`Not mapped: ${checked.reason}\nFix: ${checked.fix}\n`);
305
+ process.exitCode = 1;
306
+ return;
307
+ }
308
+ cfg.repos = { ...(cfg.repos ?? {}), [name]: checked.path };
279
309
  saveConfig(cfg);
280
- process.stdout.write(`Mapped ${name} → ${localPath}\nRestart the runner to apply: firefunc-runner start\n`);
310
+ process.stdout.write(`Mapped ${name} → ${checked.path}\nThe runner uses it from its next job; no restart needed.\n`);
281
311
  return;
282
312
  }
283
313
  if (cmd === 'brief') {
@@ -304,6 +334,18 @@ async function main() {
304
334
  const tool = positional[1];
305
335
  if (sub === 'list') {
306
336
  runMcpList();
337
+ process.stdout.write(`\n${localToolsListing(loadConfig())}`);
338
+ return;
339
+ }
340
+ if (sub === 'add') {
341
+ const at = rest.indexOf('add');
342
+ if (!runMcpAdd(rest.slice(at + 1), (t) => process.stdout.write(t), (t) => process.stderr.write(t)))
343
+ process.exitCode = 1;
344
+ return;
345
+ }
346
+ if (sub === 'remove') {
347
+ if (!runMcpRemove(tool, (t) => process.stdout.write(t), (t) => process.stderr.write(t)))
348
+ process.exitCode = 1;
307
349
  return;
308
350
  }
309
351
  if (sub === 'login' || sub === 'logout') {
@@ -320,10 +362,12 @@ async function main() {
320
362
  await runMcpLogout(tool);
321
363
  return;
322
364
  }
323
- process.stderr.write(`Usage: firefunc-runner mcp <login|list|logout> [tool]\n` +
365
+ process.stderr.write(`Usage: firefunc-runner mcp <login|list|logout|add|remove> [tool]\n` +
324
366
  ` firefunc-runner mcp login jira sign THIS machine in to Jira's MCP server\n` +
325
- ` firefunc-runner mcp list what this machine is signed in to\n` +
326
- ` firefunc-runner mcp logout jira forget that sign-in\n`);
367
+ ` firefunc-runner mcp list what this machine is signed in to, and its local tools\n` +
368
+ ` firefunc-runner mcp logout jira forget that sign-in\n` +
369
+ ` firefunc-runner mcp add windows-mcp -- uvx windows-mcp a local MCP server granted agents may use\n` +
370
+ ` firefunc-runner mcp remove windows-mcp take it away\n`);
327
371
  process.exitCode = 1;
328
372
  return;
329
373
  }
@@ -388,11 +432,56 @@ async function main() {
388
432
  : 'Resumed: the runner takes work again within a minute.\n');
389
433
  return;
390
434
  }
435
+ if (cmd === 'update') {
436
+ const unknown = unknownWords(rest, ['--max-wait']);
437
+ if (unknown) {
438
+ process.stderr.write(`firefunc-runner update did not understand "${unknown}". Run it on its own: firefunc-runner update\n`);
439
+ process.exitCode = 1;
440
+ return;
441
+ }
442
+ const os = currentPlatform();
443
+ const deps = defaultServiceDeps('', os);
444
+ const res = await updateRunner({
445
+ current: RUNNER_VERSION,
446
+ running: () => {
447
+ const rec = readAlive(runnerDir());
448
+ return rec && pidAlive(rec.pid) && rec.version ? rec.version : null;
449
+ },
450
+ latest: () => readLatestRunner(),
451
+ scriptPath: process.argv[1] ?? '',
452
+ service: {
453
+ installed: async () => (await serviceStatus(deps)).installed,
454
+ stop: async () => {
455
+ const r = await stopRunner(liveRunnerDeps(deps));
456
+ return r;
457
+ },
458
+ start: async (want) => startRunner(liveRunnerDeps(deps), want),
459
+ },
460
+ run: runQuiet,
461
+ installedVersion: installedRunnerVersion,
462
+ load: loadConfig,
463
+ save: saveConfig,
464
+ held: () => heldByLiveProcesses(runnerDir()),
465
+ drainSeen: () => {
466
+ const rec = readAlive(runnerDir());
467
+ return rec && pidAlive(rec.pid) ? (rec.drainSeenAt ?? null) : null;
468
+ },
469
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
470
+ now: () => Date.now(),
471
+ log: (line) => process.stdout.write(`${line}\n`),
472
+ });
473
+ (res.ok ? process.stdout : process.stderr).write(`${res.message}\n`);
474
+ if (!res.ok)
475
+ process.exitCode = 1;
476
+ return;
477
+ }
391
478
  if (cmd === 'restart') {
392
- if (!rest.includes('--when-idle')) {
393
- process.stderr.write('Usage: firefunc-runner restart --when-idle [--max-wait <minutes>]\n' +
394
- ' Drains the runner, waits until it holds no run, restarts the service and takes work again.\n' +
395
- ' To restart at once, cutting the runs in flight short (their work is kept for the next run): firefunc-runner start-service\n');
479
+ const unknown = unknownWords(rest, ['--when-idle', '--max-wait']);
480
+ if (unknown) {
481
+ process.stderr.write(`firefunc-runner restart did not understand "${unknown}".\n` +
482
+ ' To update and restart in one step: firefunc-runner update\n' +
483
+ ' To restart once no run is held: firefunc-runner restart --when-idle\n' +
484
+ ' To restart at once, cutting the runs in flight short: firefunc-runner start-service\n');
396
485
  process.exitCode = 1;
397
486
  return;
398
487
  }
@@ -409,14 +498,19 @@ async function main() {
409
498
  load: loadConfig,
410
499
  save: saveConfig,
411
500
  held: () => heldByLiveProcesses(runnerDir()),
501
+ drainSeen: () => {
502
+ const rec = readAlive(runnerDir());
503
+ return rec && pidAlive(rec.pid) ? (rec.drainSeenAt ?? null) : null;
504
+ },
412
505
  restart: async () => {
413
506
  const installed = (await serviceStatus(deps)).installed;
414
507
  if (!installed)
415
508
  return { ok: false, installed, message: '' };
416
- const stopped = await stopService(deps);
509
+ const live = liveRunnerDeps(deps);
510
+ const stopped = await stopRunner(live);
417
511
  if (!stopped.ok)
418
512
  return { ...stopped, installed };
419
- return { ...(await startService(deps)), installed };
513
+ return { ...(await startRunner(live, RUNNER_VERSION)), installed };
420
514
  },
421
515
  sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
422
516
  now: () => Date.now(),
@@ -435,11 +529,15 @@ async function main() {
435
529
  return;
436
530
  }
437
531
  setWorkDir(cfg.workDir);
532
+ setWorkspaceRoot(loadWorkspaceRoot(runnerDir()));
438
533
  const workDirWhy = workDirFailure();
534
+ const rootSize = await dirBytes(workRootReport({ bytes: () => null }).path, 3_000).catch(() => null);
535
+ const rootLine = workRootWords(workRootReport({ bytes: () => rootSize }));
439
536
  process.stdout.write(`Connected to ${cfg.apiUrl}\n` +
440
537
  ` name: ${cfg.name ?? '(hostname)'}\n` +
441
538
  ` reposDir: ${cfg.reposDir ?? '(none)'}\n` +
442
539
  ` workDir: ${workDirWords(cfg.workDir, diskOf, workDirWhy)}\n` +
540
+ ` workRoot: ${rootLine}\n` +
443
541
  ` repos: ${cfg.repos ? Object.keys(cfg.repos).join(', ') : '(auto by name)'}\n` +
444
542
  ` engine: ${cfg.engine ?? 'claude_code'} (default; per-project setting wins)\n` +
445
543
  ` claudeBin: ${cfg.claudeBin ?? 'claude'}\n` +
@@ -479,7 +577,15 @@ async function main() {
479
577
  const svc = await serviceStatus(deps);
480
578
  const live = liveRunner(readAlive(runnerDir()));
481
579
  process.stdout.write(`\n${liveRunnerWords(live, { logPath: svc.log, os })}`);
580
+ const gap = live.state === 'running' ? versionGapWords(RUNNER_VERSION, live.rec) : null;
581
+ if (gap)
582
+ process.stdout.write(gap);
482
583
  process.stdout.write(serviceWords(svc, os, live.state === 'running'));
584
+ const newer = newerRunnerLine(RUNNER_VERSION, process.env.FIREFUNC_RUNNER_NO_UPDATE_CHECK === '1'
585
+ ? null
586
+ : await readLatestRunner({ timeoutMs: 3_000 }), svc.installed);
587
+ if (newer)
588
+ process.stdout.write(`\n${newer}\n`);
483
589
  return;
484
590
  }
485
591
  if (cmd === 'cloud-boot') {
@@ -555,13 +661,18 @@ async function main() {
555
661
  return;
556
662
  }
557
663
  }
664
+ const live = liveRunnerDeps(deps);
558
665
  const res = cmd === 'install'
559
666
  ? await installService(deps)
560
667
  : cmd === 'uninstall'
561
- ? await uninstallService(deps)
668
+ ? await (async () => {
669
+ const r = await uninstallService(deps);
670
+ const ended = await endLiveRunner(live);
671
+ return ended.ok ? r : { ok: false, message: `${r.message}\n${ended.message}` };
672
+ })()
562
673
  : cmd === 'stop'
563
- ? await stopService(deps)
564
- : await startService(deps);
674
+ ? await stopRunner(live)
675
+ : await startRunner(live, RUNNER_VERSION);
565
676
  process.stdout.write(`${res.message}\n`);
566
677
  if (!res.ok)
567
678
  process.exitCode = 1;
@@ -570,5 +681,19 @@ async function main() {
570
681
  process.stderr.write(`Unknown command "${cmd}".\n\n${HELP}`);
571
682
  process.exitCode = 1;
572
683
  }
684
+ function liveRunnerDeps(svc) {
685
+ return {
686
+ os: currentPlatform(),
687
+ readAlive: () => readAlive(runnerDir()),
688
+ pidAlive,
689
+ exec: (cmd, args) => runQuiet(cmd, args).then((r) => ({ code: r.code, out: r.output })),
690
+ signal: (pid, sig) => {
691
+ process.kill(pid, sig);
692
+ },
693
+ service: { stop: () => stopService(svc), start: () => startService(svc) },
694
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
695
+ now: () => Date.now(),
696
+ };
697
+ }
573
698
  void main();
574
699
  //# sourceMappingURL=cli.js.map
package/dist/config.d.ts CHANGED
@@ -80,6 +80,13 @@ export type RunnerConfig = {
80
80
  setupTimeoutMinutes?: number;
81
81
  envFile?: string;
82
82
  backgroundCommands?: string[];
83
+ localTools?: Record<string, LocalTool>;
84
+ };
85
+ export type LocalTool = {
86
+ command: string;
87
+ args?: string[];
88
+ env?: Record<string, string>;
89
+ addedAt?: string;
83
90
  };
84
91
  export declare function configPath(): string;
85
92
  export declare function loadConfig(): RunnerConfig | null;
package/dist/cut.d.ts CHANGED
@@ -21,6 +21,8 @@ export type CutSession = {
21
21
  usage?: RunUsage;
22
22
  writtenSkills?: WrittenSkills;
23
23
  reason?: 'plan_limit' | 'timeout' | 'network' | 'auth' | 'lost' | 'push';
24
+ sessions?: Record<string, string>;
25
+ handedFrom?: CutSession;
24
26
  };
25
27
  export declare function cutDir(runnerDir: string): string;
26
28
  export declare function promptHash(prompt: string): string;
package/dist/cut.js CHANGED
@@ -78,14 +78,31 @@ export function cutFor(runnerDir, key, now = Date.now()) {
78
78
  const cut = listCuts(runnerDir).find((c) => c.workItemId === key.workItemId);
79
79
  if (!cut)
80
80
  return null;
81
- const matches = cut.engine === key.engine &&
82
- (cut.repo ?? null) === (key.repo ?? null) &&
81
+ const sameWork = (cut.repo ?? null) === (key.repo ?? null) &&
83
82
  cut.branch === key.branch &&
84
83
  cut.review === key.review &&
85
84
  cut.toolsOnly === key.toolsOnly;
86
- if (!matches || Date.parse(cut.keepUntil) <= now || !existsSync(cut.worktree)) {
85
+ if (!sameWork || Date.parse(cut.keepUntil) <= now || !existsSync(cut.worktree)) {
87
86
  return { discard: cut };
88
87
  }
88
+ if (cut.engine !== key.engine) {
89
+ const { handedFrom: _was, ...plain } = cut;
90
+ const others = { ...(plain.sessions ?? {}) };
91
+ const own = others[key.engine] ?? '';
92
+ delete others[key.engine];
93
+ if (plain.sessionId)
94
+ others[plain.engine] = plain.sessionId;
95
+ return {
96
+ resume: {
97
+ ...plain,
98
+ engine: key.engine,
99
+ sessionId: own,
100
+ resetsAt: null,
101
+ sessions: others,
102
+ handedFrom: plain,
103
+ },
104
+ };
105
+ }
89
106
  const reset = cut.resetsAt ? Date.parse(cut.resetsAt) : Number.NaN;
90
107
  if (Number.isFinite(reset) && reset > now)
91
108
  return null;
package/dist/daemon.js CHANGED
@@ -1,4 +1,8 @@
1
+ import { localToolNames } from './local-tools.js';
1
2
  import { readEngineModels } from './engine-models.js';
3
+ import { windowsRestartLater } from './live-runner.js';
4
+ import { WINDOWS_TASK_NAME } from './service.js';
5
+ import { NEWER_RUNNER_CHECK_MS, newerRunnerLine, readLatestRunner } from './newer-runner.js';
2
6
  import { reportWorktree } from './worktree-report.js';
3
7
  import { createEditorSessions } from './editor/sessions.js';
4
8
  import { worktreeOfRun } from './editor/worktree-of.js';
@@ -38,13 +42,18 @@ import { engineBlocks, unattendedContext } from './unattended.js';
38
42
  import { claimPause, engineWatch } from './engine-watch.js';
39
43
  import { engineLoginBlock } from './engine-login.js';
40
44
  import { commandWatch, runPath } from './machine-commands.js';
45
+ import { ghRepoWatch } from './gh-repos.js';
41
46
  import { forgetRun, stopRun } from './run-stops.js';
42
- import { readResources, resourceWatch } from './resources.js';
43
- import { clearAlive, writeAlive } from './alive.js';
47
+ import { readResources, resourceWatch, shortOf } from './resources.js';
48
+ import { dirBytes } from './drives.js';
49
+ import { join } from 'node:path';
50
+ import { clearAlive, otherRunnerWarning, readAlive, viewerPortWords, writeAlive, } from './alive.js';
44
51
  import { backoffAfterFailure, describeTransportError, isTransportFailure, rebuildGlobalDispatcher, TRANSPORT_REBUILD_AFTER, TransportWatchdog, } from './transport.js';
45
- import { setWorkDir, workDirProblem, workRoots } from './work-dir.js';
52
+ import { loadWorkspaceRoot, saveWorkspaceRoot, setWorkDir, setWorkspaceRoot, workDirProblem, workRootProblem, workRoots, } from './work-dir.js';
53
+ import { cleanUpNow } from './clean-up.js';
46
54
  import { removeRunTemp, staleRunTemps, tempRoot } from './run-temp.js';
47
55
  import { shellSafe } from './win-shell.js';
56
+ import { noteReclaim, reclaimDisk, stillShortWords } from './disk-reclaim.js';
48
57
  function log(msg) {
49
58
  console.log(`[firefunc-runner] ${new Date().toISOString()} ${blankSecrets(msg)}`);
50
59
  }
@@ -64,12 +73,23 @@ export async function startDaemon(cfg) {
64
73
  const rdir = runnerDir();
65
74
  const machine = cfg.name ?? hostname();
66
75
  setWorkDir(cfg.workDir);
76
+ setWorkspaceRoot(loadWorkspaceRoot(rdir));
67
77
  if (cfg.workDir) {
68
78
  const problem = workDirProblem();
69
79
  log(problem
70
80
  ? `WARNING: ${problem}`
71
81
  : `runs work in ${cfg.workDir} (worktrees, setup's and the engine's temp folder)`);
72
82
  }
83
+ else {
84
+ const problem = workRootProblem();
85
+ if (problem)
86
+ log(`WARNING: ${problem}`);
87
+ }
88
+ const before = readAlive(rdir);
89
+ const otherWarning = otherRunnerWarning(before, { os: platform() });
90
+ const otherRunner = otherWarning ? before : null;
91
+ for (const line of otherWarning ?? [])
92
+ log(line);
73
93
  const alive = {
74
94
  pid: process.pid,
75
95
  user: (() => {
@@ -176,6 +196,7 @@ export async function startDaemon(cfg) {
176
196
  hostname: hostname(),
177
197
  platform: platform(),
178
198
  viewerPort,
199
+ service: !!process.env.FIREFUNC_RUNNER_SERVICE,
179
200
  };
180
201
  let stopping = false;
181
202
  const viewer = cfg.viewerEnabled === false
@@ -183,7 +204,7 @@ export async function startDaemon(cfg) {
183
204
  : createSessionViewer({
184
205
  port: cfg.viewerPort,
185
206
  onListen: (u) => log(`live session viewer → ${u} (local only — watch Claude work in a browser)`),
186
- onError: (m) => log(`${m} — set "viewerPort" or pass --no-viewer`),
207
+ onError: (m, port) => log(viewerPortWords(port, m, otherRunner, platform())),
187
208
  });
188
209
  const holding = new Set();
189
210
  const pendingIds = () => {
@@ -230,8 +251,57 @@ export async function startDaemon(cfg) {
230
251
  });
231
252
  let serverMax = 1;
232
253
  const commands = commandWatch({ path: () => runPath(cfg), log });
254
+ const ghRepos = ghRepoWatch({ log });
233
255
  let localSignIn = signInFieldsOf(cfg);
234
256
  let signInPrefs = null;
257
+ let lastCleanUpRequest = -Infinity;
258
+ let lastReclaimAt = -Infinity;
259
+ const diskNow = () => readResources(cfg, rdir).disk;
260
+ const reclaimNow = async () => {
261
+ const r = await reclaimDisk({
262
+ runnerDir: rdir,
263
+ short: () => {
264
+ const d = diskNow();
265
+ return !!d && d.floorBytes > 0 && d.freeBytes < d.floorBytes;
266
+ },
267
+ cleanUp: async () => (await cleanUpNow({
268
+ runnerDir: rdir,
269
+ checkouts: Object.values(cfg.repos ?? {}),
270
+ holding,
271
+ log,
272
+ }).catch(() => null))?.freedBytes ?? 0,
273
+ sizeOf: (p) => dirBytes(p),
274
+ log,
275
+ });
276
+ const own = await dirBytes(join(rdir, 'cargo-target')).catch(() => null);
277
+ noteReclaim({
278
+ at: new Date().toISOString(),
279
+ freedBytes: r.freedBytes,
280
+ stillShort: r.stillShort,
281
+ ownBytes: own,
282
+ });
283
+ if (r.stillShort) {
284
+ const d = diskNow();
285
+ if (d)
286
+ log(stillShortWords({
287
+ machine,
288
+ freeBytes: d.freeBytes,
289
+ floorBytes: d.floorBytes,
290
+ own: [{ label: 'build targets', bytes: own }],
291
+ }));
292
+ }
293
+ };
294
+ const runCleanUp = async (why) => {
295
+ const r = await cleanUpNow({
296
+ runnerDir: rdir,
297
+ checkouts: Object.values(cfg.repos ?? {}),
298
+ holding,
299
+ log,
300
+ }).catch(() => null);
301
+ if (r && r.freedBytes > 0) {
302
+ log(`clean-up (${why}) freed ${(r.freedBytes / 1024 ** 3).toFixed(2)} GB`);
303
+ }
304
+ };
235
305
  const refreshConfig = async () => {
236
306
  const saved = loadConfig();
237
307
  if (saved) {
@@ -260,12 +330,39 @@ export async function startDaemon(cfg) {
260
330
  serverMax = Math.max(1, Math.floor(c.maxParallel));
261
331
  if (c)
262
332
  commands.update(c.requiredCommands);
333
+ if (c)
334
+ ghRepos.update(c.checkRepos);
263
335
  if (c)
264
336
  signInPrefs = c.signInPrefs;
265
337
  Object.assign(cfg, applySignInPrefs(localSignIn, signInPrefs));
338
+ if (c && setWorkspaceRoot(c.workRoot)) {
339
+ saveWorkspaceRoot(rdir, c.workRoot);
340
+ const problem = cfg.workDir ? null : workRootProblem();
341
+ log(problem
342
+ ? `WARNING: ${problem}`
343
+ : c.workRoot
344
+ ? `the workspace's work folder is ${c.workRoot}${cfg.workDir ? ` (this machine's own ${cfg.workDir} wins)` : ''}`
345
+ : 'the workspace set no work folder');
346
+ }
347
+ if (c?.cleanUpRequestedAt && Date.parse(c.cleanUpRequestedAt) > lastCleanUpRequest) {
348
+ lastCleanUpRequest = Date.parse(c.cleanUpRequestedAt);
349
+ void runCleanUp('asked from FireFunc');
350
+ }
266
351
  };
267
352
  await refreshConfig().catch(() => { });
268
353
  const cfgTimer = setInterval(() => void refreshConfig().catch(() => { }), 60_000);
354
+ const drainTimer = setInterval(() => {
355
+ const saved = loadConfig();
356
+ if (!saved)
357
+ return;
358
+ cfg.drain = saved.drain;
359
+ cfg.maxParallel = saved.maxParallel;
360
+ if (!isDraining(cfg) && alive.drainSeenAt) {
361
+ delete alive.drainSeenAt;
362
+ touchAlive();
363
+ }
364
+ }, 2_000);
365
+ drainTimer.unref?.();
269
366
  const commandActivity = commandActivityWatch();
270
367
  const activityTimer = setInterval(() => {
271
368
  const mine = new Set(holding);
@@ -402,7 +499,23 @@ export async function startDaemon(cfg) {
402
499
  resolve({ code: code ?? -1, output });
403
500
  });
404
501
  }),
405
- exit: (code) => process.exit(code),
502
+ exit: (code) => {
503
+ if (process.platform === 'win32' && process.env.FIREFUNC_RUNNER_SERVICE === '1') {
504
+ try {
505
+ const later = windowsRestartLater(WINDOWS_TASK_NAME);
506
+ spawn(later.cmd, later.args, {
507
+ detached: true,
508
+ stdio: 'ignore',
509
+ windowsHide: true,
510
+ }).unref();
511
+ log('asked Task Scheduler to start the new version in a few seconds');
512
+ }
513
+ catch (err) {
514
+ log(`could not ask Task Scheduler to restart it: ${err.message}`);
515
+ }
516
+ }
517
+ process.exit(code);
518
+ },
406
519
  log,
407
520
  });
408
521
  const onUpgrade = (cmd) => {
@@ -478,6 +591,17 @@ export async function startDaemon(cfg) {
478
591
  };
479
592
  readModels();
480
593
  setInterval(readModels, 60 * 60_000).unref();
594
+ const sayNewer = () => {
595
+ void readLatestRunner().then((latest) => {
596
+ const line = newerRunnerLine(RUNNER_VERSION, latest, alive.service);
597
+ if (line)
598
+ log(line);
599
+ });
600
+ };
601
+ if (process.env.FIREFUNC_RUNNER_NO_UPDATE_CHECK !== '1') {
602
+ sayNewer();
603
+ setInterval(sayNewer, NEWER_RUNNER_CHECK_MS).unref();
604
+ }
481
605
  try {
482
606
  const checkouts = Object.values(cfg.repos ?? {}).filter((p) => existsSync(p));
483
607
  const removed = await sweepLeftoverWorktrees(checkouts, {
@@ -506,7 +630,10 @@ export async function startDaemon(cfg) {
506
630
  gate.waive = (engine) => engine === 'claude_code' && fallbackKey(cfg, rdir) !== null;
507
631
  const limitReports = () => gate.active().map((l) => ({ engine: l.engine, kind: 'plan', resetsAt: l.resetsAt }));
508
632
  const enginesPaused = claimPause({ watch: declared, isLimited: (e) => gate.isLimited(e), log });
509
- const room = resourceWatch({ read: () => readResources(cfg, rdir), log });
633
+ const room = resourceWatch({
634
+ read: () => readResources(cfg, rdir, { localTools: () => localToolNames(loadConfig() ?? cfg) }),
635
+ log,
636
+ });
510
637
  const paused = () => enginesPaused() || room.short();
511
638
  const heavyWaitReport = (runIds) => {
512
639
  const byTag = new Map(runIds.map((id) => [heavyTag(id), id]));
@@ -544,6 +671,7 @@ export async function startDaemon(cfg) {
544
671
  maxParallel: effectiveMax(),
545
672
  resources: room.report(),
546
673
  commands: commands.report(),
674
+ ...(ghRepos.report() ? { ghRepos: ghRepos.report() } : {}),
547
675
  budget: budgets,
548
676
  ...(Object.keys(engineVersions).length > 0 ? { engineVersions } : {}),
549
677
  ...(Object.keys(engineModels).length > 0 ? { engineModels } : {}),
@@ -555,6 +683,7 @@ export async function startDaemon(cfg) {
555
683
  accountLabel: l.accountLabel,
556
684
  expiresAt: l.expiresAt,
557
685
  ...(l.detail ? { detail: l.detail } : {}),
686
+ ...(l.tools ? { tools: l.tools, toolsListedAt: l.toolsListedAt } : {}),
558
687
  })),
559
688
  awaitingRuns: keptRunIds(rdir),
560
689
  heavyWaits: heavyWaitReport([...holding, ...heldByLiveProcesses(rdir)]),
@@ -622,10 +751,15 @@ export async function startDaemon(cfg) {
622
751
  }
623
752
  await flushPendingTrails(rdir, (runId, batch) => api.trail(runId, batch)).catch(() => null);
624
753
  declared.rescan();
754
+ if (shortOf(room.report()).includes('disk') && Date.now() - lastReclaimAt > 10 * 60_000) {
755
+ lastReclaimAt = Date.now();
756
+ await reclaimNow().catch(() => { });
757
+ }
625
758
  if (Date.now() - lastCutSweep > 10 * 60_000) {
626
759
  lastCutSweep = Date.now();
627
760
  await dropExpiredCuts().catch(() => { });
628
761
  sweepRunTemps();
762
+ await runCleanUp('every ten minutes');
629
763
  for (const k of expiredKept(rdir)) {
630
764
  await letGo(k, 'was not answered in time').catch(() => { });
631
765
  }
@@ -657,6 +791,12 @@ export async function startDaemon(cfg) {
657
791
  backoffMs = Math.min(backoffMs * 2, 60_000);
658
792
  return 'retry';
659
793
  },
794
+ onDrainSeen: () => {
795
+ if (alive.drainSeenAt)
796
+ return;
797
+ alive.drainSeenAt = new Date().toISOString();
798
+ touchAlive();
799
+ },
660
800
  onStart: (job, inFlight) => {
661
801
  holding.add(job.runId);
662
802
  recordHeld(rdir, job.runId);
@@ -702,6 +842,7 @@ export async function startDaemon(cfg) {
702
842
  await toolCalls.idle();
703
843
  await commandSteps.idle();
704
844
  clearInterval(cfgTimer);
845
+ clearInterval(drainTimer);
705
846
  clearInterval(activityTimer);
706
847
  clearInterval(budgetTimer);
707
848
  clearInterval(aliveTimer);
@@ -0,0 +1,40 @@
1
+ export declare const RECLAIM_IN_USE_MS: number;
2
+ export type Reclaimable = {
3
+ path: string;
4
+ label: string;
5
+ lastUsed: number;
6
+ };
7
+ export declare const gbWords: (b: number) => string;
8
+ export declare function reclaimables(runnerDir: string, now?: number): Reclaimable[];
9
+ export type ReclaimDeps = {
10
+ runnerDir: string;
11
+ short: () => boolean;
12
+ cleanUp: () => Promise<number>;
13
+ sizeOf: (path: string) => Promise<number | null>;
14
+ remove?: (path: string) => void;
15
+ log: (line: string) => void;
16
+ now?: () => number;
17
+ };
18
+ export type ReclaimResult = {
19
+ freedBytes: number;
20
+ removed: string[];
21
+ stillShort: boolean;
22
+ };
23
+ export type ReclaimReport = {
24
+ at: string;
25
+ freedBytes: number;
26
+ stillShort: boolean;
27
+ ownBytes: number | null;
28
+ };
29
+ export declare function lastReclaim(): ReclaimReport | null;
30
+ export declare function noteReclaim(r: ReclaimReport): void;
31
+ export declare function reclaimDisk(deps: ReclaimDeps): Promise<ReclaimResult>;
32
+ export declare function stillShortWords(input: {
33
+ machine: string;
34
+ freeBytes: number;
35
+ floorBytes: number;
36
+ own: ReadonlyArray<{
37
+ label: string;
38
+ bytes: number | null;
39
+ }>;
40
+ }): string;