@firefunc-agent/runner 0.9.36 → 0.9.37

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.
package/README.md CHANGED
@@ -646,6 +646,17 @@ A workspace can manage its machines from Settings → Machines (or the API):
646
646
  so its service starts the new version. It only does this as the installed service
647
647
  (`firefunc-runner install`) and not from npx's cache; otherwise it says why and keeps running.
648
648
  A failed install leaves the old version running and reports npm's last lines.
649
+ - **Update in one step.** `firefunc-runner update` installs the newest runner the way it was
650
+ installed and restarts into it once no run is held. It is the same in PowerShell, zsh and
651
+ bash. It prints the old and new version and "restarted", or says why it could not and the fix.
652
+ - **Updates install themselves.** A machine running as the installed service updates itself when
653
+ idle, within an hour of a new version on npm, unless the workspace (Admin › Policies ›
654
+ Machines) or the machine's own page turns it off. A failed update shows in the Bell with npm's
655
+ words.
656
+ - **A newer runner is out.** At start and once a day the runner asks npm for the newest version
657
+ (only the package name is sent). When one is newer, its log and `firefunc-runner status` say
658
+ so in one line, with `firefunc-runner update`. `FIREFUNC_RUNNER_NO_UPDATE_CHECK=1` turns the
659
+ check off.
649
660
  - **Token lifetime and rotation.** A workspace can give machine tokens a lifetime and a
650
661
  pairing window. The runner replaces its token on its own when a third of its life is left,
651
662
  or when a person asks; the old token works for one more hour. An expired token stops the
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "0.9.36",
3
- "builtAt": "2026-11-25T07:39:42.553Z"
2
+ "version": "0.9.37",
3
+ "builtAt": "2026-11-25T09:12:28.905Z"
4
4
  }
package/dist/cli.js CHANGED
@@ -2,6 +2,8 @@
2
2
  import { configPath, drainSetting, expandHome, isDraining, loadConfig, runnerDir, saveConfig, editorsAllowed, } from './config.js';
3
3
  import { startDaemon } from './daemon.js';
4
4
  import { restartWhenIdle } from './restart-idle.js';
5
+ import { installedRunnerVersion, runQuiet, unknownWords, updateRunner } from './update.js';
6
+ import { endLiveRunner, startRunner, stopRunner, versionGapWords, } from './live-runner.js';
5
7
  import { heldByLiveProcesses } from './held.js';
6
8
  import { runBrief } from './brief.js';
7
9
  import { runMcpList, runMcpLogin, runMcpLogout } from './mcp-login.js';
@@ -9,7 +11,8 @@ import { RUNNER_VERSION } from './version.js';
9
11
  import { availableEngines, getAdapter } from './engines/index.js';
10
12
  import { engineBlocks, unattendedContext } from './unattended.js';
11
13
  import { engineLoginBlock } from './engine-login.js';
12
- import { liveRunner, liveRunnerWords, readAlive } from './alive.js';
14
+ import { liveRunner, liveRunnerWords, pidAlive, readAlive } from './alive.js';
15
+ import { newerRunnerLine, readLatestRunner } from './newer-runner.js';
13
16
  import { setWorkDir, workDirFailure, workDirWords } from './work-dir.js';
14
17
  import { diskOf } from './resources.js';
15
18
  import { currentPlatform, defaultServiceDeps, EPHEMERAL_INSTALL_MESSAGE, installService, isEphemeralInstall, readLogTail, renderLaunchdPlist, renderSystemdUnit, renderWindowsLauncher, renderWindowsTaskXml, serviceStatus, serviceWords, servicePaths, startService, stopService, uninstallService, } from './service.js';
@@ -37,6 +40,8 @@ Usage:
37
40
  (the machine stays online); safe to update or
38
41
  restart once the log says "drained"
39
42
  firefunc-runner resume Take work again after a drain
43
+ firefunc-runner update Install the newest runner and restart into it
44
+ once no run is held (one step, any shell)
40
45
  firefunc-runner restart --when-idle Drain, wait until no run is held, restart the
41
46
  service, then take work again
42
47
  (--max-wait <minutes> gives up after that)
@@ -388,11 +393,52 @@ async function main() {
388
393
  : 'Resumed: the runner takes work again within a minute.\n');
389
394
  return;
390
395
  }
396
+ if (cmd === 'update') {
397
+ const unknown = unknownWords(rest, ['--max-wait']);
398
+ if (unknown) {
399
+ process.stderr.write(`firefunc-runner update did not understand "${unknown}". Run it on its own: firefunc-runner update\n`);
400
+ process.exitCode = 1;
401
+ return;
402
+ }
403
+ const os = currentPlatform();
404
+ const deps = defaultServiceDeps('', os);
405
+ const res = await updateRunner({
406
+ current: RUNNER_VERSION,
407
+ running: () => {
408
+ const rec = readAlive(runnerDir());
409
+ return rec && pidAlive(rec.pid) && rec.version ? rec.version : null;
410
+ },
411
+ latest: () => readLatestRunner(),
412
+ scriptPath: process.argv[1] ?? '',
413
+ service: {
414
+ installed: async () => (await serviceStatus(deps)).installed,
415
+ stop: async () => {
416
+ const r = await stopRunner(liveRunnerDeps(deps));
417
+ return r;
418
+ },
419
+ start: async (want) => startRunner(liveRunnerDeps(deps), want),
420
+ },
421
+ run: runQuiet,
422
+ installedVersion: installedRunnerVersion,
423
+ load: loadConfig,
424
+ save: saveConfig,
425
+ held: () => heldByLiveProcesses(runnerDir()),
426
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
427
+ now: () => Date.now(),
428
+ log: (line) => process.stdout.write(`${line}\n`),
429
+ });
430
+ (res.ok ? process.stdout : process.stderr).write(`${res.message}\n`);
431
+ if (!res.ok)
432
+ process.exitCode = 1;
433
+ return;
434
+ }
391
435
  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');
436
+ const unknown = unknownWords(rest, ['--when-idle', '--max-wait']);
437
+ if (unknown) {
438
+ process.stderr.write(`firefunc-runner restart did not understand "${unknown}".\n` +
439
+ ' To update and restart in one step: firefunc-runner update\n' +
440
+ ' To restart once no run is held: firefunc-runner restart --when-idle\n' +
441
+ ' To restart at once, cutting the runs in flight short: firefunc-runner start-service\n');
396
442
  process.exitCode = 1;
397
443
  return;
398
444
  }
@@ -413,10 +459,11 @@ async function main() {
413
459
  const installed = (await serviceStatus(deps)).installed;
414
460
  if (!installed)
415
461
  return { ok: false, installed, message: '' };
416
- const stopped = await stopService(deps);
462
+ const live = liveRunnerDeps(deps);
463
+ const stopped = await stopRunner(live);
417
464
  if (!stopped.ok)
418
465
  return { ...stopped, installed };
419
- return { ...(await startService(deps)), installed };
466
+ return { ...(await startRunner(live, RUNNER_VERSION)), installed };
420
467
  },
421
468
  sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
422
469
  now: () => Date.now(),
@@ -479,7 +526,15 @@ async function main() {
479
526
  const svc = await serviceStatus(deps);
480
527
  const live = liveRunner(readAlive(runnerDir()));
481
528
  process.stdout.write(`\n${liveRunnerWords(live, { logPath: svc.log, os })}`);
529
+ const gap = live.state === 'running' ? versionGapWords(RUNNER_VERSION, live.rec) : null;
530
+ if (gap)
531
+ process.stdout.write(gap);
482
532
  process.stdout.write(serviceWords(svc, os, live.state === 'running'));
533
+ const newer = newerRunnerLine(RUNNER_VERSION, process.env.FIREFUNC_RUNNER_NO_UPDATE_CHECK === '1'
534
+ ? null
535
+ : await readLatestRunner({ timeoutMs: 3_000 }), svc.installed);
536
+ if (newer)
537
+ process.stdout.write(`\n${newer}\n`);
483
538
  return;
484
539
  }
485
540
  if (cmd === 'cloud-boot') {
@@ -555,13 +610,18 @@ async function main() {
555
610
  return;
556
611
  }
557
612
  }
613
+ const live = liveRunnerDeps(deps);
558
614
  const res = cmd === 'install'
559
615
  ? await installService(deps)
560
616
  : cmd === 'uninstall'
561
- ? await uninstallService(deps)
617
+ ? await (async () => {
618
+ const r = await uninstallService(deps);
619
+ const ended = await endLiveRunner(live);
620
+ return ended.ok ? r : { ok: false, message: `${r.message}\n${ended.message}` };
621
+ })()
562
622
  : cmd === 'stop'
563
- ? await stopService(deps)
564
- : await startService(deps);
623
+ ? await stopRunner(live)
624
+ : await startRunner(live, RUNNER_VERSION);
565
625
  process.stdout.write(`${res.message}\n`);
566
626
  if (!res.ok)
567
627
  process.exitCode = 1;
@@ -570,5 +630,19 @@ async function main() {
570
630
  process.stderr.write(`Unknown command "${cmd}".\n\n${HELP}`);
571
631
  process.exitCode = 1;
572
632
  }
633
+ function liveRunnerDeps(svc) {
634
+ return {
635
+ os: currentPlatform(),
636
+ readAlive: () => readAlive(runnerDir()),
637
+ pidAlive,
638
+ exec: (cmd, args) => runQuiet(cmd, args).then((r) => ({ code: r.code, out: r.output })),
639
+ signal: (pid, sig) => {
640
+ process.kill(pid, sig);
641
+ },
642
+ service: { stop: () => stopService(svc), start: () => startService(svc) },
643
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
644
+ now: () => Date.now(),
645
+ };
646
+ }
573
647
  void main();
574
648
  //# sourceMappingURL=cli.js.map
package/dist/daemon.js CHANGED
@@ -1,4 +1,7 @@
1
1
  import { readEngineModels } from './engine-models.js';
2
+ import { windowsRestartLater } from './live-runner.js';
3
+ import { WINDOWS_TASK_NAME } from './service.js';
4
+ import { NEWER_RUNNER_CHECK_MS, newerRunnerLine, readLatestRunner } from './newer-runner.js';
2
5
  import { reportWorktree } from './worktree-report.js';
3
6
  import { createEditorSessions } from './editor/sessions.js';
4
7
  import { worktreeOfRun } from './editor/worktree-of.js';
@@ -176,6 +179,7 @@ export async function startDaemon(cfg) {
176
179
  hostname: hostname(),
177
180
  platform: platform(),
178
181
  viewerPort,
182
+ service: !!process.env.FIREFUNC_RUNNER_SERVICE,
179
183
  };
180
184
  let stopping = false;
181
185
  const viewer = cfg.viewerEnabled === false
@@ -402,7 +406,23 @@ export async function startDaemon(cfg) {
402
406
  resolve({ code: code ?? -1, output });
403
407
  });
404
408
  }),
405
- exit: (code) => process.exit(code),
409
+ exit: (code) => {
410
+ if (process.platform === 'win32' && process.env.FIREFUNC_RUNNER_SERVICE === '1') {
411
+ try {
412
+ const later = windowsRestartLater(WINDOWS_TASK_NAME);
413
+ spawn(later.cmd, later.args, {
414
+ detached: true,
415
+ stdio: 'ignore',
416
+ windowsHide: true,
417
+ }).unref();
418
+ log('asked Task Scheduler to start the new version in a few seconds');
419
+ }
420
+ catch (err) {
421
+ log(`could not ask Task Scheduler to restart it: ${err.message}`);
422
+ }
423
+ }
424
+ process.exit(code);
425
+ },
406
426
  log,
407
427
  });
408
428
  const onUpgrade = (cmd) => {
@@ -478,6 +498,17 @@ export async function startDaemon(cfg) {
478
498
  };
479
499
  readModels();
480
500
  setInterval(readModels, 60 * 60_000).unref();
501
+ const sayNewer = () => {
502
+ void readLatestRunner().then((latest) => {
503
+ const line = newerRunnerLine(RUNNER_VERSION, latest, alive.service);
504
+ if (line)
505
+ log(line);
506
+ });
507
+ };
508
+ if (process.env.FIREFUNC_RUNNER_NO_UPDATE_CHECK !== '1') {
509
+ sayNewer();
510
+ setInterval(sayNewer, NEWER_RUNNER_CHECK_MS).unref();
511
+ }
481
512
  try {
482
513
  const checkouts = Object.values(cfg.repos ?? {}).filter((p) => existsSync(p));
483
514
  const removed = await sweepLeftoverWorktrees(checkouts, {
@@ -32,7 +32,27 @@ export const machineCommands = [
32
32
  .map((e) => text(e.engine).replace(/_channel$/, ''))
33
33
  .join(','),
34
34
  },
35
+ {
36
+ head: 'RUNNER',
37
+ get: (m) => {
38
+ const r = (m.runner ?? null);
39
+ if (!r?.version)
40
+ return '-';
41
+ return r.behind ? `${text(r.version)} (${text(r.latest)} is out)` : text(r.version);
42
+ },
43
+ },
35
44
  ]);
45
+ const behind = rows.filter((m) => (m.runner ?? null)?.update);
46
+ if (behind.length) {
47
+ ctx.io.stdout.write('\nA newer runner is out:\n');
48
+ for (const m of behind) {
49
+ const u = m.runner.update;
50
+ ctx.io.stdout.write(` ${text(m.name)}: ${text(u.from)} -> ${text(u.to)}\n`);
51
+ if (u.notes)
52
+ ctx.io.stdout.write(` What changed: ${text(u.notes)}\n`);
53
+ ctx.io.stdout.write(` ${text(u.how)}\n`);
54
+ }
55
+ }
36
56
  },
37
57
  },
38
58
  {
@@ -0,0 +1,47 @@
1
+ import type { AliveRecord } from './alive.js';
2
+ export type LiveRunnerDeps = {
3
+ os: 'darwin' | 'linux' | 'win32' | null;
4
+ readAlive: () => AliveRecord | null;
5
+ pidAlive: (pid: number) => boolean;
6
+ exec: (cmd: string, args: string[]) => Promise<{
7
+ code: number;
8
+ out: string;
9
+ }>;
10
+ signal: (pid: number, sig: 'SIGTERM' | 'SIGKILL') => void;
11
+ service: {
12
+ stop: () => Promise<{
13
+ ok: boolean;
14
+ message: string;
15
+ }>;
16
+ start: () => Promise<{
17
+ ok: boolean;
18
+ message: string;
19
+ }>;
20
+ };
21
+ sleep: (ms: number) => Promise<void>;
22
+ now: () => number;
23
+ graceMs?: number;
24
+ startMs?: number;
25
+ pollMs?: number;
26
+ };
27
+ export type StopResult = {
28
+ ok: boolean;
29
+ message: string;
30
+ pid: number | null;
31
+ version: string | null;
32
+ };
33
+ export declare function endLiveRunner(d: LiveRunnerDeps): Promise<StopResult>;
34
+ export declare function stopRunner(d: LiveRunnerDeps): Promise<{
35
+ ok: boolean;
36
+ message: string;
37
+ }>;
38
+ export declare function startRunner(d: LiveRunnerDeps, want: string | null): Promise<{
39
+ ok: boolean;
40
+ message: string;
41
+ pid: number | null;
42
+ }>;
43
+ export declare function versionGapWords(installed: string, running: AliveRecord | null): string | null;
44
+ export declare function windowsRestartLater(taskName: string, delaySeconds?: number): {
45
+ cmd: string;
46
+ args: string[];
47
+ };
@@ -0,0 +1,109 @@
1
+ async function gone(d, pid, ms) {
2
+ const until = d.now() + ms;
3
+ for (;;) {
4
+ if (!d.pidAlive(pid))
5
+ return true;
6
+ if (d.now() >= until)
7
+ return false;
8
+ await d.sleep(d.pollMs ?? 500);
9
+ }
10
+ }
11
+ export async function endLiveRunner(d) {
12
+ const rec = d.readAlive();
13
+ if (!rec || !d.pidAlive(rec.pid))
14
+ return { ok: true, message: '', pid: null, version: null };
15
+ const { pid, version } = rec;
16
+ const grace = d.graceMs ?? 15_000;
17
+ if (d.os === 'win32') {
18
+ await d.exec('taskkill', ['/PID', String(pid), '/T']);
19
+ if (!(await gone(d, pid, grace))) {
20
+ await d.exec('taskkill', ['/PID', String(pid), '/T', '/F']);
21
+ }
22
+ }
23
+ else {
24
+ try {
25
+ d.signal(pid, 'SIGTERM');
26
+ }
27
+ catch {
28
+ }
29
+ if (!(await gone(d, pid, grace))) {
30
+ try {
31
+ d.signal(pid, 'SIGKILL');
32
+ }
33
+ catch {
34
+ }
35
+ }
36
+ }
37
+ if (await gone(d, pid, 5_000))
38
+ return { ok: true, message: '', pid, version };
39
+ return {
40
+ ok: false,
41
+ pid,
42
+ version,
43
+ message: d.os === 'win32'
44
+ ? `The runner (pid ${pid}, runner ${version || 'unknown'}) would not stop. Fix: in PowerShell run Stop-Process -Id ${pid} -Force, then firefunc-runner start-service.`
45
+ : `The runner (pid ${pid}, runner ${version || 'unknown'}) would not stop. Fix: kill -9 ${pid}, then firefunc-runner start-service.`,
46
+ };
47
+ }
48
+ export async function stopRunner(d) {
49
+ const svc = await d.service.stop();
50
+ if (!svc.ok)
51
+ return svc;
52
+ const ended = await endLiveRunner(d);
53
+ if (!ended.ok)
54
+ return { ok: false, message: ended.message };
55
+ return {
56
+ ok: true,
57
+ message: `Stopped${ended.pid ? ` (pid ${ended.pid}, runner ${ended.version || 'unknown'})` : ''}. Run "firefunc-runner start-service" to start it again.`,
58
+ };
59
+ }
60
+ export async function startRunner(d, want) {
61
+ const ended = await endLiveRunner(d);
62
+ if (!ended.ok)
63
+ return { ...ended, pid: ended.pid };
64
+ const old = ended.pid;
65
+ const svc = await d.service.start();
66
+ if (!svc.ok)
67
+ return { ok: false, message: svc.message, pid: null };
68
+ const until = d.now() + (d.startMs ?? 60_000);
69
+ let last = null;
70
+ for (;;) {
71
+ const rec = d.readAlive();
72
+ if (rec && rec.pid !== old && d.pidAlive(rec.pid)) {
73
+ last = rec;
74
+ if (!want || rec.version === want) {
75
+ return {
76
+ ok: true,
77
+ pid: rec.pid,
78
+ message: `Started runner ${rec.version} (pid ${rec.pid}).`,
79
+ };
80
+ }
81
+ }
82
+ if (d.now() >= until)
83
+ break;
84
+ await d.sleep(d.pollMs ?? 1_000);
85
+ }
86
+ const still = d.readAlive();
87
+ const running = still && d.pidAlive(still.pid)
88
+ ? `pid ${still.pid} runs runner ${still.version || 'unknown'}`
89
+ : 'no runner is running';
90
+ return {
91
+ ok: false,
92
+ pid: null,
93
+ message: last && want
94
+ ? `The service started runner ${last.version} (pid ${last.pid}), not ${want}. Fix: run firefunc-runner update, or reinstall: npm install -g @firefunc-agent/runner@latest, then firefunc-runner install.`
95
+ : `The service was asked to start, but no new runner${want ? ` on ${want}` : ''} came up within ${Math.round((d.startMs ?? 60_000) / 1000)} s; ${running}. Fix: run firefunc-runner logs to see why, then firefunc-runner start-service again.`,
96
+ };
97
+ }
98
+ export function versionGapWords(installed, running) {
99
+ if (!running?.version || running.version === installed)
100
+ return null;
101
+ return ` versions: installed ${installed}, running ${running.version}: restart needed — run firefunc-runner restart --when-idle\n`;
102
+ }
103
+ export function windowsRestartLater(taskName, delaySeconds = 5) {
104
+ return {
105
+ cmd: 'cmd.exe',
106
+ args: ['/d', '/c', `timeout /t ${delaySeconds} /nobreak >nul & schtasks /Run /TN ${taskName}`],
107
+ };
108
+ }
109
+ //# sourceMappingURL=live-runner.js.map
@@ -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
@@ -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>;
package/dist/update.js ADDED
@@ -0,0 +1,176 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { restartWhenIdle } from './restart-idle.js';
3
+ import { shellSafe } from './win-shell.js';
4
+ import { isNewer } from './newer-runner.js';
5
+ export const RUNNER_PACKAGE = '@firefunc-agent/runner';
6
+ export function installCommand(scriptPath, spec) {
7
+ if (/[\\/]pnpm[\\/]/i.test(scriptPath))
8
+ return { cmd: 'pnpm', args: ['add', '-g', spec] };
9
+ return { cmd: 'npm', args: ['install', '-g', spec] };
10
+ }
11
+ const tail = (s) => s.trim().split('\n').slice(-4).join(' ').slice(0, 400);
12
+ export async function updateRunner(d) {
13
+ const running = d.running?.() ?? null;
14
+ const from = running ?? d.current;
15
+ if (/[\\/]_npx[\\/]/.test(d.scriptPath)) {
16
+ return {
17
+ ok: false,
18
+ from,
19
+ to: null,
20
+ message: `This runner runs from npx’s temporary cache, so there is nothing installed to update. Install it once: npm install -g ${RUNNER_PACKAGE}@latest — then: firefunc-runner install`,
21
+ };
22
+ }
23
+ const latest = await d.latest();
24
+ if (!latest) {
25
+ return {
26
+ ok: false,
27
+ from,
28
+ to: null,
29
+ message: `Not updated: npm did not answer with the newest version (is this machine online, or behind a proxy npm cannot use?). Try again, or run: npm install -g ${RUNNER_PACKAGE}@latest`,
30
+ };
31
+ }
32
+ if (!isNewer(latest, d.current)) {
33
+ if (running && isNewer(d.current, running) && (await d.service.installed())) {
34
+ let failure = null;
35
+ const idle = await restartWhenIdle({
36
+ ...d,
37
+ restart: async () => {
38
+ const stopped = await d.service.stop();
39
+ if (!stopped.ok) {
40
+ failure = stopped.message;
41
+ return { ok: false, installed: true, message: stopped.message };
42
+ }
43
+ const started = await d.service.start(d.current);
44
+ if (!started.ok)
45
+ failure = started.message;
46
+ return { ok: started.ok, installed: true, message: started.message };
47
+ },
48
+ });
49
+ if (failure)
50
+ return { ok: false, from, to: null, message: `Not restarted: ${failure}` };
51
+ if (!idle.ok)
52
+ return { ok: false, from, to: null, message: `Not restarted. ${idle.message}` };
53
+ return {
54
+ ok: true,
55
+ from,
56
+ to: d.current,
57
+ message: `Updated ${from} → ${d.current}, restarted (${d.current} was installed; ${from} was still running).`,
58
+ };
59
+ }
60
+ return { ok: true, from, to: from, message: `Already on ${from}, the newest on npm.` };
61
+ }
62
+ const spec = `${RUNNER_PACKAGE}@${latest}`;
63
+ const how = installCommand(d.scriptPath, spec);
64
+ const install = async () => {
65
+ d.log(`installing ${spec}`);
66
+ return d.run(how.cmd, how.args).catch((err) => ({
67
+ code: -1,
68
+ output: err instanceof Error ? err.message : String(err),
69
+ }));
70
+ };
71
+ const failed = (res, after) => ({
72
+ ok: false,
73
+ from,
74
+ to: null,
75
+ message: `Not updated: ${how.cmd} ${how.args.join(' ')} failed (exit ${res.code})${tail(res.output) ? `: ${tail(res.output)}` : ''}. ${after} Fix what npm says (on Windows, run PowerShell as the account that installed the runner), then run firefunc-runner update again.`,
76
+ });
77
+ const checked = async (restarted) => {
78
+ const now = (await d.installedVersion()) ?? latest;
79
+ return {
80
+ ok: true,
81
+ from,
82
+ to: now,
83
+ message: restarted
84
+ ? `Updated ${from} → ${now}, restarted.`
85
+ : `Updated ${from} → ${now}. No service is installed, so restart the runner where it runs: stop it (Ctrl-C) and run firefunc-runner start.`,
86
+ };
87
+ };
88
+ if (!(await d.service.installed())) {
89
+ const res = await install();
90
+ if (res.code !== 0)
91
+ return failed(res, `It still runs ${from}.`);
92
+ return checked(false);
93
+ }
94
+ let result = null;
95
+ const idle = await restartWhenIdle({
96
+ ...d,
97
+ restart: async () => {
98
+ const stopped = await d.service.stop();
99
+ if (!stopped.ok) {
100
+ result = {
101
+ ok: false,
102
+ from,
103
+ to: null,
104
+ message: `Not updated: the service would not stop (${stopped.message}). Nothing was installed; the runner stays drained, so run firefunc-runner resume once it is stopped and started again.`,
105
+ };
106
+ return { ok: false, installed: true, message: result.message };
107
+ }
108
+ const res = await install();
109
+ const started = await d.service.start(latest);
110
+ if (res.code !== 0) {
111
+ result = failed(res, started.ok
112
+ ? `The service runs ${from} again.`
113
+ : `The service did not start again (${started.message}): run firefunc-runner start-service.`);
114
+ return { ok: started.ok, installed: true, message: result.message };
115
+ }
116
+ if (!started.ok) {
117
+ result = {
118
+ ok: false,
119
+ from,
120
+ to: latest,
121
+ message: `Installed ${latest}, but the service did not start (${started.message}). Run: firefunc-runner start-service — then firefunc-runner resume, as it stays drained.`,
122
+ };
123
+ return { ok: false, installed: true, message: result.message };
124
+ }
125
+ return { ok: true, installed: true, message: '' };
126
+ },
127
+ });
128
+ if (result)
129
+ return result;
130
+ if (!idle.ok)
131
+ return { ok: false, from, to: null, message: `Not updated. ${idle.message}` };
132
+ const done = await checked(true);
133
+ return /drained/.test(idle.message) && /stays drained/.test(idle.message)
134
+ ? {
135
+ ...done,
136
+ message: `${done.message} It was drained before, so it stays drained: run firefunc-runner resume to take work again.`,
137
+ }
138
+ : done;
139
+ }
140
+ export function unknownWords(args, known, withValue = ['--max-wait']) {
141
+ for (let i = 0; i < args.length; i += 1) {
142
+ const a = args[i];
143
+ if (!known.includes(a))
144
+ return a;
145
+ if (withValue.includes(a))
146
+ i += 1;
147
+ }
148
+ return null;
149
+ }
150
+ export function runQuiet(cmd, args) {
151
+ return new Promise((resolve) => {
152
+ const line = shellSafe(cmd, args, process.platform === 'win32');
153
+ const child = spawn(line.cmd, line.args, { shell: line.shell, windowsHide: true });
154
+ let output = '';
155
+ const keep = (b) => {
156
+ output = (output + b.toString('utf8')).slice(-4_000);
157
+ };
158
+ child.stdout?.on('data', keep);
159
+ child.stderr?.on('data', keep);
160
+ const timer = setTimeout(() => child.kill('SIGTERM'), 10 * 60_000);
161
+ child.on('error', (err) => {
162
+ clearTimeout(timer);
163
+ resolve({ code: -1, output: err.message });
164
+ });
165
+ child.on('close', (code) => {
166
+ clearTimeout(timer);
167
+ resolve({ code: code ?? -1, output });
168
+ });
169
+ });
170
+ }
171
+ export async function installedRunnerVersion() {
172
+ const res = await runQuiet('firefunc-runner', ['--version']);
173
+ const v = res.output.trim().split('\n').pop()?.trim() ?? '';
174
+ return res.code === 0 && /^\d+\.\d+\.\d+$/.test(v) ? v : null;
175
+ }
176
+ //# sourceMappingURL=update.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firefunc-agent/runner",
3
- "version": "0.9.36",
3
+ "version": "0.9.37",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "FireFunc self-hosted runner — an always-on daemon that runs YOUR local coding agent (Claude Code, Codex, Gemini CLI, Cursor CLI, Copilot CLI, Antigravity) on work FireFunc routes to it, opens pull requests, and reports back. Your machine, your subscriptions.",