@animastor/installer 0.2.15 → 0.2.17

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
@@ -121,6 +121,24 @@ it detaches at once (own session, stdin `/dev/null`, output appended to
121
121
  ComfyUI only after the startup script has finished, so waiting inside the
122
122
  script deadlocks.
123
123
 
124
+ `doctor` and `boot` update the INSTALLER ITSELF from the hub (0.2.16): the
125
+ first thing they do is compare the local installer, the installed worker
126
+ bundle and the loaded install manifests with the hub —
127
+ `GET <hub>/installer/sha256` and `GET <hub>/worker-bundle/sha256`. A newer hub
128
+ installer is downloaded (`GET <hub>/installer/bundle`), verified against the
129
+ published sha256, unpacked and put in place of the persistent copy
130
+ (`~/animastor/installer`, what the `animastor` command runs); `doctor` then
131
+ re-executes the same command line in that version, `boot` detaches
132
+ `doctor --yes` of that version. The manifests travel inside the hub bundle, so
133
+ their revision is compared there; the adopted bundle sha256 is recorded in
134
+ `install-state.json`, so a bundle rebuilt at the same version (changed
135
+ manifests) is picked up on the next run too. Offline (no network, a 5xx, a
136
+ missing endpoint) the local version runs and the log says so — before 0.2.16
137
+ a node kept 0.2.14 while the hub served 0.2.15, and only a repeated curl
138
+ bootstrap updated it. A local installer newer than the hub is never
139
+ downgraded. `--no-self-update` skips the check (the boot run gives it an 8 s
140
+ timeout so the platform's startup script is never stalled on the network).
141
+
124
142
  Custom-node Python dependencies on type A (0.2.5): the pip requirements of
125
143
  every required profile custom node are checked in the Python of the running
126
144
  `main.py` (taken from `/proc/<pid>`). Missing ones go into a persistent
@@ -201,8 +219,9 @@ otherwise the start is FAILED naming the file and the worker is not spawned.
201
219
  Every install/doctor run first brings the management tools (`animastor`,
202
220
  the persistent installer copy) and an installed worker bundle to its own
203
221
  version — before any check that can end the run — so every printed fix
204
- command exists in the installed `animastor`. Unknown options are an error
205
- (exit 2). When node classes are missing the result names the cause: missing
222
+ command exists in the installed `animastor`. For `doctor`/`boot` the hub
223
+ check above runs before this step, which then applies the ADOPTED version.
224
+ Unknown options are an error (exit 2). When node classes are missing the result names the cause: missing
206
225
  packages, an `IMPORT FAILED` line from the ComfyUI log (`/internal/logs`,
207
226
  the process stdout file, the restart log) or a needed restart.
208
227
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@animastor/installer",
3
- "version": "0.2.15",
3
+ "version": "0.2.17",
4
4
  "description": "Animastor Private GPU Worker installer — self-contained CLI and library for GPU worker setup, verification, and management.",
5
5
  "main": "src/installer/index.js",
6
6
  "exports": {
@@ -34,6 +34,8 @@
34
34
  * finish (default 600000); still busy → FAILED, exit 1
35
35
  * --force install/doctor: restart the worker for a changed configuration even
36
36
  * when it is busy (the task's result is lost)
37
+ * --no-self-update doctor/boot: skip the hub version check (an OFFLINE run does it
38
+ * automatically: it never waits for an unreachable hub)
37
39
  */
38
40
 
39
41
  const fs = require('fs');
@@ -65,6 +67,7 @@ const overridesMod = require('./engine/overrides');
65
67
  const downloader = require('./engine/downloader');
66
68
  const { resolveRepoBundleDir } = require('./worker-bundle-source');
67
69
  const engineMod = require('./engine/engine');
70
+ const hubSelfUpdateMod = require('./engine/hub-self-update');
68
71
 
69
72
  // ---------------------------------------------------------------------------
70
73
  // Paths (platform-specific defaults; the platform adapter owns them)
@@ -113,7 +116,7 @@ const DEFAULT_HUB_URL = 'https://animastor.org/gpu';
113
116
  // Argument parsing
114
117
  // ---------------------------------------------------------------------------
115
118
 
116
- const BOOLEAN_FLAGS = ['yes', 'dry-run', 'resume', 'start-comfy', 'start-worker', 'no-start-comfy', 'no-start-worker', 'all', 'accept-reference-runtime', 'accept-runtime-change', 'install-tools', 'no-tools', 'new-key', 'follow', 'no-fix', 'restart-platform-comfy', 'no-restart-platform-comfy', 'accept-node-deps-overrides', 'force', 'help'];
119
+ const BOOLEAN_FLAGS = ['yes', 'dry-run', 'resume', 'start-comfy', 'start-worker', 'no-start-comfy', 'no-start-worker', 'all', 'accept-reference-runtime', 'accept-runtime-change', 'install-tools', 'no-tools', 'new-key', 'follow', 'no-fix', 'restart-platform-comfy', 'no-restart-platform-comfy', 'accept-node-deps-overrides', 'force', 'no-self-update', 'help'];
117
120
 
118
121
  /**
119
122
  * Every option that takes a value. Installer 0.2.5: an option that is in
@@ -1013,7 +1016,7 @@ function bootChildArgs(flags, { cliPath = __filename, defaultWaitMs = 600000 } =
1013
1016
  * node dependencies, restarts the platform's ComfyUI when needed and starts
1014
1017
  * the worker.
1015
1018
  */
1016
- function cmdBoot(flags, { io = createRealIo(), spawn = require('child_process').spawn, execPath = process.execPath, cliPath = __filename, now = () => new Date() } = {}) {
1019
+ async function cmdBoot(flags, { io = createRealIo(), spawn = require('child_process').spawn, execPath = process.execPath, cliPath = __filename, now = () => new Date() } = {}) {
1017
1020
  const logFile = bootLogPath(flags);
1018
1021
  let fd = null;
1019
1022
  try {
@@ -1021,12 +1024,42 @@ function cmdBoot(flags, { io = createRealIo(), spawn = require('child_process').
1021
1024
  fd = fs.openSync(logFile, 'a');
1022
1025
  const btime = systemBootTime(io);
1023
1026
  fs.writeSync(fd, `\n===== animastor boot ${now().toISOString()} (system boot ${btime || 'unknown'}) =====\n`);
1024
- const args = bootChildArgs(flags, { cliPath });
1027
+ // Installer 0.2.16 — the hub version check runs BEFORE the detach: the
1028
+ // detached `doctor --yes` must be the adopted version, so a node that
1029
+ // boots after a hub release updates itself (live 05.12: boot detached
1030
+ // the local 0.2.14 doctor while the hub served 0.2.15).
1031
+ let childCli = cliPath;
1032
+ const selfUpdate = await preflightSelfUpdateFromHub(io, {
1033
+ flags,
1034
+ statePath: resolveStatePath(flags),
1035
+ workerDir: resolveWorkerDir(flags),
1036
+ hubUrl: resolveHubUrl(flags),
1037
+ manifests: recordedManifests(io, flags),
1038
+ boot: true,
1039
+ nodeBin: execPath,
1040
+ // the platform's startup script waits for this process: a
1041
+ // blackholed network must not stall it for the doctor timeout
1042
+ timeoutMs: 8000,
1043
+ });
1044
+ for (const n of selfUpdate.notes || []) {
1045
+ fs.writeSync(fd, `[${n.level === 'warn' ? '!' : 'i'}] ${n.text}\n`);
1046
+ }
1047
+ const adopted = selfUpdate.status === 'updated' && !!selfUpdate.cliPath;
1048
+ if (adopted) {
1049
+ childCli = selfUpdate.cliPath;
1050
+ fs.writeSync(fd, `animastor boot: installer ${selfUpdate.version || '?'} adopted — the detached doctor runs it\n`);
1051
+ }
1052
+ const args = bootChildArgs(flags, { cliPath: childCli });
1025
1053
  const child = spawn(execPath, args, {
1026
1054
  detached: true,
1027
1055
  stdio: ['ignore', fd, fd],
1028
1056
  cwd: homeDir(),
1029
- env: { ...process.env, ANIMASTOR_BOOT: '1' },
1057
+ // An ADOPTED version needs no second check in the detached doctor.
1058
+ // Anything else (offline, a failed download) is retried there —
1059
+ // the boot check never blocks the node startup script on it.
1060
+ env: adopted
1061
+ ? { ...process.env, ANIMASTOR_BOOT: '1', [hubSelfUpdateMod.SELF_UPDATE_ENV]: '1' }
1062
+ : { ...process.env, ANIMASTOR_BOOT: '1' },
1030
1063
  });
1031
1064
  if (child && typeof child.unref === 'function') child.unref();
1032
1065
  const pid = child && child.pid;
@@ -1054,6 +1087,108 @@ function installedToolsVersion(io, flags) {
1054
1087
  try { return JSON.parse(String(io.fs.readFileSync(path.join(dir, 'package.json'), 'utf8'))).version || null; } catch (_) { return null; }
1055
1088
  }
1056
1089
 
1090
+ /** The persistent installer copy the `animastor` command runs (<base>/installer). */
1091
+ function persistentInstallerDir(flags) {
1092
+ return path.join(path.dirname(resolveToolsDir(flags)), 'installer');
1093
+ }
1094
+
1095
+ /** Manifests of the profiles recorded in install-state (the boot path has no --profile). */
1096
+ function recordedManifests(io, flags) {
1097
+ const st = stateStore.loadState(io, resolveStatePath(flags));
1098
+ const profiles = st && Array.isArray(st.profiles) ? st.profiles : [];
1099
+ const out = [];
1100
+ for (const id of profiles) {
1101
+ try { out.push(manifest.loadManifest(id)); } catch (_) { /* a manifest removed by a release says nothing about the version */ }
1102
+ }
1103
+ return out;
1104
+ }
1105
+
1106
+ /**
1107
+ * Installer 0.2.16 — the FIRST step of `doctor` and `boot`: compare the local
1108
+ * installer / worker bundle / install manifests with the hub
1109
+ * (`/installer/sha256`, `/worker-bundle/sha256`) and adopt a newer hub
1110
+ * installer (verified bundle → persistent copy → re-exec by the caller).
1111
+ *
1112
+ * Offline (no network, a 5xx, a missing endpoint) is NOT an error: the run
1113
+ * continues with the local version and says so. So does a failed update — the
1114
+ * running version keeps working, the persistent copy is untouched.
1115
+ *
1116
+ * @returns {Promise<object>} hubSelfUpdate result ({ status, notes, cliPath, … })
1117
+ */
1118
+ async function preflightSelfUpdateFromHub(io, {
1119
+ flags = {}, statePath = null, workerDir = null, hubUrl = null, manifests = [], logger = null,
1120
+ boot = false, timeoutMs = undefined, nodeBin = process.execPath,
1121
+ } = {}) {
1122
+ const skip = (reason) => ({ status: 'skipped', reason, notes: [], hub: null, decision: null, cliPath: null, version: null });
1123
+ if (flags['no-self-update']) return skip('--no-self-update');
1124
+ if (process.env[hubSelfUpdateMod.SELF_UPDATE_ENV]) return skip(`already updated in this run (${hubSelfUpdateMod.SELF_UPDATE_ENV})`);
1125
+ let res;
1126
+ try {
1127
+ res = await hubSelfUpdateMod.hubSelfUpdate(io, {
1128
+ hubUrl,
1129
+ ownVersion: ownVersion(),
1130
+ bundleVersion: workerDir ? workerMod.readPkgVersion(io, workerDir) : null,
1131
+ manifests,
1132
+ statePath,
1133
+ persistentDir: persistentInstallerDir(flags),
1134
+ nodeBin: nodeBin || process.execPath,
1135
+ timeoutMs,
1136
+ });
1137
+ } catch (err) {
1138
+ // Installer 0.2.17 — the self-update is advisory: ANY error in it
1139
+ // (0.2.16 on 05.12: a ReferenceError here killed every doctor/boot)
1140
+ // leaves the run on the local version with a warning.
1141
+ const reason = (err && err.message) || String(err);
1142
+ res = {
1143
+ status: 'failed', reason, hub: null, decision: null, cliPath: null, version: null, manifest_revision: null,
1144
+ notes: [{ level: 'warn', text: `hub self-update failed: ${reason} — continuing with the local installer ${ownVersion() || 'unknown'}` }],
1145
+ };
1146
+ }
1147
+ // The boot path writes its own log lines (its stdout is bootstrap.log);
1148
+ // with a logger the lines go through the run's renderer.
1149
+ for (const n of res.notes || []) {
1150
+ if (logger) { if (n.level === 'warn') logger.warn(n.text); else logger.info(n.text); }
1151
+ else if (!boot) console.log(`[${n.level === 'warn' ? '!' : 'i'}] ${n.text}`);
1152
+ }
1153
+ return res;
1154
+ }
1155
+
1156
+ /**
1157
+ * Re-execute THIS command line in the just-adopted installer version. The
1158
+ * code of the running process cannot be replaced in place, and every fix
1159
+ * command of the result must belong to the version that produced it.
1160
+ * The child starts from the persistent copy (`<base>/installer`), gets the
1161
+ * same stdio and the SELF_UPDATE_ENV marker (no second check, no loop).
1162
+ * @returns {Promise<number|null>} null when the child could not be started
1163
+ */
1164
+ function reexecCli({
1165
+ cliPath, argv = process.argv, nodeBin = process.execPath, env = process.env,
1166
+ spawn = require('child_process').spawn, exit = (code) => process.exit(code),
1167
+ } = {}) {
1168
+ return new Promise((resolve) => {
1169
+ let done = false;
1170
+ const finish = (status) => { if (done) return; done = true; exit(status); resolve(status); };
1171
+ let child;
1172
+ try {
1173
+ child = spawn(nodeBin, [cliPath, ...argv.slice(2)], {
1174
+ stdio: 'inherit',
1175
+ env: { ...env, [hubSelfUpdateMod.SELF_UPDATE_ENV]: '1' },
1176
+ });
1177
+ } catch (err) {
1178
+ console.error(`animastor: could not start the updated installer ${cliPath}: ${err.message}`);
1179
+ process.exitCode = 1;
1180
+ resolve(null);
1181
+ return;
1182
+ }
1183
+ child.on('error', (err) => {
1184
+ console.error(`animastor: could not start the updated installer ${cliPath}: ${err.message}`);
1185
+ process.exitCode = 1;
1186
+ if (!done) { done = true; resolve(null); }
1187
+ });
1188
+ child.on('exit', (code, signal) => finish(signal ? 1 : (code == null ? 1 : code)));
1189
+ });
1190
+ }
1191
+
1057
1192
  /**
1058
1193
  * Installer 0.2.5 — FIRST change of every install/doctor run, before any
1059
1194
  * check that can end the run with ✗: the management tools (the `animastor`
@@ -1220,8 +1355,11 @@ function createScreen() {
1220
1355
  });
1221
1356
  }
1222
1357
 
1223
- async function cmdInstall(flags, { doctor = false } = {}) {
1224
- const realIo = createRealIo();
1358
+ async function cmdInstall(flags, { doctor = false, io: injectedIo = null, reexec = reexecCli, stopAfterHubPreflight = false } = {}) {
1359
+ // io / reexec / stopAfterHubPreflight: test seams (0.2.17) — the doctor
1360
+ // path up to and including the hub self-update runs for real against a
1361
+ // fake hub; nothing else of the run is reached when stopping there.
1362
+ const realIo = injectedIo || createRealIo();
1225
1363
  // doctor = the same idempotent install for the RECORDED installation:
1226
1364
  // profiles come from install-state.json unless given explicitly. The
1227
1365
  // recorded MODE is not applied: the mode follows the machine (see
@@ -1264,6 +1402,29 @@ async function cmdInstall(flags, { doctor = false } = {}) {
1264
1402
  const screen = createScreen();
1265
1403
  const logger = createLogger({ io: realIo, sink: (line) => screen.print(line) });
1266
1404
  const loadedManifests = flags.profiles.map((p) => manifest.loadManifest(p));
1405
+
1406
+ // Installer 0.2.16 — doctor/boot ask the HUB first (before the banner and
1407
+ // before any change): is this installer behind? A newer hub installer is
1408
+ // adopted and this command line is re-executed in that version; offline,
1409
+ // the local version runs and the result says so (live 05.12: doctor on a
1410
+ // node ran 0.2.14 while the hub served 0.2.15 — nothing was updated).
1411
+ // The node binary of this run: the hub preflight, the tools preflight and
1412
+ // the worker get the same one (0.2.17).
1413
+ const runNodeBin = (probeMod.pickNodeBinary(realIo) || {}).bin || null;
1414
+ if (doctor && !dryRun) {
1415
+ const selfUpdate = await preflightSelfUpdateFromHub(realIo, {
1416
+ flags, statePath, workerDir, hubUrl, manifests: loadedManifests, logger, boot,
1417
+ nodeBin: runNodeBin || process.execPath,
1418
+ });
1419
+ if (selfUpdate.status === 'updated' && selfUpdate.cliPath) {
1420
+ // The code of this process is already loaded: the adopted version
1421
+ // must run the command.
1422
+ await reexec({ cliPath: selfUpdate.cliPath });
1423
+ return { hubPreflight: selfUpdate, reexec: true };
1424
+ }
1425
+ if (stopAfterHubPreflight) return { hubPreflight: selfUpdate, reexec: false };
1426
+ }
1427
+
1267
1428
  const hubVersion = doctor
1268
1429
  ? await detectHubVersion(realIo, hubUrl, { known: process.env.ANIMASTOR_HUB_VERSION || (priorState && priorState.hub_version) || null })
1269
1430
  : (process.env.ANIMASTOR_HUB_VERSION || null);
@@ -1286,7 +1447,7 @@ async function cmdInstall(flags, { doctor = false } = {}) {
1286
1447
  // Tools + bundle of THIS version before anything can stop the run (0.2.5).
1287
1448
  const preflight = await preflightSelfUpdate(realIo, {
1288
1449
  flags, statePath, root, workerDir, hubUrl, repoRoot, manifests: loadedManifests, logger, dryRun,
1289
- nodeBin: (probeMod.pickNodeBinary(realIo) || {}).bin || null,
1450
+ nodeBin: runNodeBin,
1290
1451
  });
1291
1452
  const withPre = (res) => ({ ...res, preflight });
1292
1453
 
@@ -2323,8 +2484,8 @@ async function cmdLogs(flags) {
2323
2484
  });
2324
2485
  }
2325
2486
 
2326
- async function cmdDoctor(flags) {
2327
- return cmdInstall(flags, { doctor: true });
2487
+ async function cmdDoctor(flags, deps = {}) {
2488
+ return cmdInstall(flags, { ...deps, doctor: true });
2328
2489
  }
2329
2490
 
2330
2491
  // ---------------------------------------------------------------------------
@@ -2361,7 +2522,7 @@ async function main() {
2361
2522
  await cmdDoctor(args.flags);
2362
2523
  break;
2363
2524
  case 'boot':
2364
- cmdBoot(args.flags);
2525
+ await cmdBoot(args.flags);
2365
2526
  break;
2366
2527
  case 'detect':
2367
2528
  await cmdDetect(args.flags);
@@ -2412,6 +2573,7 @@ async function main() {
2412
2573
  console.error(' animastor start | stop | status | logs [-f] | doctor [--new-key] [--wait-job-ms N] [--force] | boot');
2413
2574
  console.error(' boot: node startup script — detaches `doctor --yes` (log ~/animastor/logs/bootstrap.log), exits 0');
2414
2575
  console.error(' --restart-platform-comfy / --no-restart-platform-comfy restart the platform ComfyUI after node deps (a process started outside the installer: its jobs are lost)');
2576
+ console.error(' --no-self-update doctor/boot: skip the hub installer version check (offline runs skip it themselves)');
2415
2577
  console.error(' --accept-node-deps-overrides consent: the node-deps overlay may replace a package another profile / ComfyUI core uses');
2416
2578
  console.error(' (also: monitor | reboot-worker | reboot-comfyui)');
2417
2579
  console.error(' (--state/--root/--worker-dir/--port override discovery)');
@@ -2441,5 +2603,6 @@ module.exports = {
2441
2603
  restartPlatformComfyDecision, platformNodeDepsGate, nodeDepsFailedResult, recordInstallerOption,
2442
2604
  cmdBoot, bootChildArgs, bootLogPath, teeToBootLog, startupScriptLine,
2443
2605
  preflightSelfUpdate, preflightExtras, installedToolsVersion, ownVersion,
2606
+ preflightSelfUpdateFromHub, reexecCli, persistentInstallerDir, recordedManifests,
2444
2607
  nodeDepsOwnedServices, recordOwnedServices, otherProfileManifests, overridesStep,
2445
2608
  };
@@ -0,0 +1,373 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Hub self-update (installer 0.2.16).
5
+ *
6
+ * Fact (05.12.2026): after hub v0.4.4 (installer 0.2.15, worker bundle 3.0.1)
7
+ * `animastor doctor --yes --restart-platform-comfy` on a node ran the LOCAL
8
+ * installer 0.2.14 with manifest 2026.11.12-r1 — the node stayed on 0.2.14 and
9
+ * only a repeated curl bootstrap brought 0.2.15, while every report told the
10
+ * user to run `animastor doctor` to update.
11
+ *
12
+ * `preflightSelfUpdate` (0.2.5) brings the management tools and the installed
13
+ * worker bundle to THIS installer's version; it never asks the hub whether THIS
14
+ * installer is old. That question is answered here, FIRST, for `doctor` and
15
+ * `boot`:
16
+ *
17
+ * GET <hub>/installer/sha256 { version, sha256, bytes }
18
+ * GET <hub>/worker-bundle/sha256 { version, sha256, bytes, files }
19
+ *
20
+ * and compared with the local installer, the installed worker bundle and the
21
+ * loaded install manifests. A newer hub installer → the hub bundle
22
+ * (`GET <hub>/installer/bundle`) is downloaded, verified against the published
23
+ * sha256, unpacked, and the persistent installer copy (`<base>/installer` —
24
+ * what the `animastor` command runs) is replaced; the caller then re-execs the
25
+ * run in the new version (`doctor`) or detaches the new version (`boot`).
26
+ *
27
+ * The install manifests travel INSIDE that bundle (ai/install-manifests), so
28
+ * their revision is compared there — the hub publishes no separate manifest
29
+ * revision. The hub bundle sha256 is recorded in install-state, so a bundle
30
+ * rebuilt at the SAME installer version (changed manifests) is still adopted on
31
+ * the next run.
32
+ *
33
+ * Honest failure modes (never a half-installed update):
34
+ * - offline / 5xx / missing endpoint → `offline`: doctor and boot continue
35
+ * with the local version and SAY SO;
36
+ * - a local installer NEWER than the hub → never downgraded;
37
+ * - a sha256 mismatch, an unexpected layout or an unwritable tools dir →
38
+ * `failed`: the running version continues, the persistent copy is untouched.
39
+ */
40
+
41
+ const os = require('os');
42
+ const path = require('path');
43
+
44
+ const management = require('../management');
45
+ const stateStore = require('./state');
46
+ const worker = require('./worker');
47
+ const { compareVersions } = require('../compatibility-resolver');
48
+
49
+ /** Endpoints the hub publishes versions/checksums at. */
50
+ const HUB_ROUTES = Object.freeze({
51
+ installer: '/installer/sha256',
52
+ installer_bundle: '/installer/bundle',
53
+ worker_bundle: '/worker-bundle/sha256',
54
+ });
55
+
56
+ /** Set for the re-executed run: its version was just adopted, no second check. */
57
+ const SELF_UPDATE_ENV = 'ANIMASTOR_SELF_UPDATE';
58
+
59
+ const TIMEOUT_MS = 15000;
60
+
61
+ /** The repo-checkout / bundled package root of a CLI file (…/src/installer/cli.js). */
62
+ function packageRootOf(cliPath) {
63
+ return path.resolve(path.dirname(cliPath || __filename), '..', '..');
64
+ }
65
+
66
+ function hubBase(hubUrl) {
67
+ return String(hubUrl || '').replace(/\/+$/, '');
68
+ }
69
+
70
+ /**
71
+ * What the hub publishes about its installer and worker bundle.
72
+ * A network error, a 5xx or a missing endpoint is `offline` — it says nothing
73
+ * about the versions, so nothing is updated from it.
74
+ * @returns {Promise<{ status: 'ok'|'partial'|'offline', hub_url: string|null,
75
+ * installer: {version: string, sha256: string|null, bytes: number|null}|null,
76
+ * worker_bundle: {version: string, sha256: string|null, bytes: number|null}|null,
77
+ * reason: string|null }>}
78
+ */
79
+ async function fetchHubVersions(io, { hubUrl, timeoutMs = TIMEOUT_MS } = {}) {
80
+ const base = hubBase(hubUrl);
81
+ const out = { status: 'offline', hub_url: base || null, installer: null, worker_bundle: null, reason: null };
82
+ if (!base) { out.reason = 'no hub URL'; return out; }
83
+ if (!io.http || typeof io.http.fetchJson !== 'function') {
84
+ out.reason = 'the io layer cannot reach the hub';
85
+ return out;
86
+ }
87
+ const fetchOne = async (route) => {
88
+ try {
89
+ const res = await io.http.fetchJson(`${base}${route}`, { signal: AbortSignal.timeout(timeoutMs) });
90
+ if (!res || res.status !== 200) return { ok: false, reason: `${route} answered HTTP ${res && res.status}` };
91
+ const json = res.json || {};
92
+ if (typeof json.version !== 'string' || !json.version) return { ok: false, reason: `${route} published no version` };
93
+ return {
94
+ ok: true,
95
+ version: json.version,
96
+ sha256: typeof json.sha256 === 'string' && /^[0-9a-f]{64}$/i.test(json.sha256) ? json.sha256.toLowerCase() : null,
97
+ bytes: typeof json.bytes === 'number' ? json.bytes : null,
98
+ };
99
+ } catch (err) {
100
+ return { ok: false, reason: `${route} is not reachable: ${err && err.message ? err.message : err}` };
101
+ }
102
+ };
103
+ const [installer, bundle] = await Promise.all([fetchOne(HUB_ROUTES.installer), fetchOne(HUB_ROUTES.worker_bundle)]);
104
+ if (installer.ok) out.installer = { version: installer.version, sha256: installer.sha256, bytes: installer.bytes };
105
+ if (bundle.ok) out.worker_bundle = { version: bundle.version, sha256: bundle.sha256, bytes: bundle.bytes };
106
+ const reasons = [installer.reason, bundle.reason].filter(Boolean);
107
+ if (installer.ok && bundle.ok) out.status = 'ok';
108
+ else if (installer.ok || bundle.ok) out.status = 'partial';
109
+ else { out.status = 'offline'; out.reason = reasons.join('; ') || 'the hub is not reachable'; }
110
+ return out;
111
+ }
112
+
113
+ /** Every `revision` of the manifests in <pkgDir>/ai/install-manifests (sorted, unique). */
114
+ function readManifestRevisions(io, pkgDir) {
115
+ const root = path.join(pkgDir, 'ai', 'install-manifests');
116
+ const revisions = [];
117
+ const walk = (dir) => {
118
+ let names = [];
119
+ try { names = io.fs.readdirSync(dir); } catch (_) { return; }
120
+ for (const name of names.sort()) {
121
+ const full = path.join(dir, name);
122
+ if (io.fs.isDirectory(full)) { walk(full); continue; }
123
+ if (!name.endsWith('.json')) continue;
124
+ try {
125
+ const json = JSON.parse(String(io.fs.readFileSync(full, 'utf8')));
126
+ if (json && typeof json.revision === 'string' && json.revision) revisions.push(json.revision);
127
+ } catch (_) { /* an unreadable manifest says nothing about the revision */ }
128
+ }
129
+ };
130
+ walk(root);
131
+ return Array.from(new Set(revisions)).sort();
132
+ }
133
+
134
+ /** Version + manifest revisions of an unpacked installer package. */
135
+ function readBundleInfo(io, pkgDir) {
136
+ let version = null;
137
+ try { version = JSON.parse(String(io.fs.readFileSync(path.join(pkgDir, 'package.json'), 'utf8'))).version || null; } catch (_) { version = null; }
138
+ const revisions = readManifestRevisions(io, pkgDir);
139
+ return { version, manifest_revisions: revisions, manifest_revision: revisions[0] || null };
140
+ }
141
+
142
+ /** Local manifests of this installation (revisions of the recorded profiles). */
143
+ function localManifestRevisions(manifests) {
144
+ return Array.from(new Set((manifests || []).map((m) => m && m.revision).filter(Boolean))).sort();
145
+ }
146
+
147
+ /** Recorded outcome of the last hub self-update (install-state `self_update`). */
148
+ function readRecordedSelfUpdate(io, statePath) {
149
+ if (!statePath) return null;
150
+ const st = stateStore.loadState(io, statePath);
151
+ return st && st.self_update && typeof st.self_update === 'object' ? st.self_update : null;
152
+ }
153
+
154
+ /** Remember which hub installer (version + sha256) this installation adopted. */
155
+ function recordSelfUpdate(io, statePath, info) {
156
+ if (!statePath) return false;
157
+ const st = stateStore.loadState(io, statePath);
158
+ if (!st) return false; // no recorded installation — doctor creates none
159
+ st.self_update = {
160
+ installer_version: info.installer_version || null,
161
+ installer_sha256: info.installer_sha256 || null,
162
+ manifest_revision: info.manifest_revision || null,
163
+ manifest_revisions: info.manifest_revisions || [],
164
+ worker_bundle_version: info.worker_bundle_version || null,
165
+ updated_at: new Date(io.now ? io.now() : Date.now()).toISOString(),
166
+ };
167
+ stateStore.saveState(io, statePath, st, io.now || Date.now);
168
+ return true;
169
+ }
170
+
171
+ /**
172
+ * Pure decision: is this installation behind the hub?
173
+ *
174
+ * installer — the hub publishes a NEWER installer version → adopt it;
175
+ * an OLDER hub version than the local one is never a downgrade;
176
+ * content — same version, but the hub bundle sha256 differs from the one
177
+ * this installation adopted → the hub rebuilt the bundle (its
178
+ * manifests changed) → adopt it;
179
+ * bundle — an installed worker bundle behind the hub is reported;
180
+ * it is refreshed by preflightSelfUpdate / the engine (the
181
+ * installer bundle carries the same files), not by a second
182
+ * installer download.
183
+ *
184
+ * @returns {{ needed: boolean, reasons: Array<{kind: string, have: *|null, want: *|null}>,
185
+ * warnings: string[], bundle_outdated: boolean }}
186
+ */
187
+ function decideHubSelfUpdate({ ownVersion = null, bundleVersion = null, manifestRevisions = [], recorded = null, hub = null } = {}) {
188
+ const out = { needed: false, reasons: [], warnings: [], bundle_outdated: false };
189
+ const hubInstaller = hub && hub.installer ? hub.installer : null;
190
+ if (!hubInstaller || !hubInstaller.version) {
191
+ out.warnings.push('the hub did not publish an installer version — nothing can be compared');
192
+ return out;
193
+ }
194
+ const cmp = ownVersion ? compareVersions(hubInstaller.version, ownVersion) : 1;
195
+ if (cmp > 0) {
196
+ out.needed = true;
197
+ out.reasons.push({ kind: 'installer', have: ownVersion, want: hubInstaller.version });
198
+ } else if (cmp < 0) {
199
+ out.warnings.push(`the local installer ${ownVersion} is newer than the hub's ${hubInstaller.version} — left as is (an installer is never downgraded)`);
200
+ } else if (recorded && recorded.installer_sha256 && hubInstaller.sha256
201
+ && String(recorded.installer_sha256) !== String(hubInstaller.sha256)) {
202
+ // same version, different bundle: rebuilt with other manifests
203
+ out.needed = true;
204
+ out.reasons.push({ kind: 'installer-content', have: String(recorded.installer_sha256).slice(0, 12), want: String(hubInstaller.sha256).slice(0, 12) });
205
+ }
206
+ const hubBundle = hub && hub.worker_bundle ? hub.worker_bundle : null;
207
+ if (hubBundle && hubBundle.version && bundleVersion && hubBundle.version !== bundleVersion) {
208
+ out.bundle_outdated = true;
209
+ }
210
+ return out;
211
+ }
212
+
213
+ /**
214
+ * Download the hub installer bundle, verify the published sha256, unpack it.
215
+ * The caller owns `tmpDir` (persist first, then remove it).
216
+ * @returns {Promise<{ ok: boolean, pkgDir?: string, tmpDir?: string, version?: string|null,
217
+ * manifest_revisions?: string[], manifest_revision?: string|null, sha256?: string, reason?: string }>}
218
+ */
219
+ async function applyHubSelfUpdate(io, { hubUrl, hub, tmpRoot = null } = {}) {
220
+ const base = hubBase(hubUrl);
221
+ const expected = hub && hub.installer ? hub.installer.sha256 : null;
222
+ if (!base) return { ok: false, reason: 'no hub URL' };
223
+ if (!expected) return { ok: false, reason: 'the hub published no installer sha256 — refusing an unverified installer' };
224
+ if (!io.http || typeof io.http.download !== 'function' || typeof io.hashFile !== 'function' || typeof io.exec !== 'function') {
225
+ return { ok: false, reason: 'the io layer cannot download and unpack the hub installer' };
226
+ }
227
+ const tmpDir = path.join(tmpRoot || os.tmpdir(), `animastor-installer-${process.pid}-${Date.now()}`);
228
+ const tarPath = path.join(tmpDir, 'installer-bundle.tar.gz');
229
+ try {
230
+ io.fs.mkdirSync(tmpDir, { recursive: true });
231
+ const dl = await io.http.download({ url: `${base}${HUB_ROUTES.installer_bundle}`, dest: tarPath });
232
+ if (!dl || dl.status !== 200) {
233
+ return { ok: false, tmpDir, reason: `installer bundle download failed (HTTP ${dl && dl.status})` };
234
+ }
235
+ const actual = await io.hashFile(tarPath);
236
+ if (String(actual).toLowerCase() !== String(expected).toLowerCase()) {
237
+ return { ok: false, tmpDir, reason: `installer bundle sha256 mismatch (expected ${String(expected).slice(0, 12)}…, got ${String(actual).slice(0, 12)}…) — the download was NOT used` };
238
+ }
239
+ const untar = io.exec('tar', ['-xzf', tarPath, '-C', tmpDir]);
240
+ if (!untar || untar.code !== 0) {
241
+ return { ok: false, tmpDir, reason: `installer bundle unpack failed: ${String((untar && (untar.stderr || untar.error)) || '').slice(-200)}` };
242
+ }
243
+ const pkgDir = path.join(tmpDir, 'animastor-installer');
244
+ const cli = path.join(pkgDir, 'src', 'installer', 'cli.js');
245
+ if (!io.fs.isDirectory(pkgDir) || !io.fs.existsSync(cli)) {
246
+ return { ok: false, tmpDir, reason: 'installer bundle layout unexpected (animastor-installer/src/installer/cli.js missing)' };
247
+ }
248
+ const info = readBundleInfo(io, pkgDir);
249
+ if (!info.version) return { ok: false, tmpDir, reason: 'installer bundle carries no package.json version' };
250
+ return { ok: true, pkgDir, tmpDir, version: info.version, manifest_revisions: info.manifest_revisions, manifest_revision: info.manifest_revision, sha256: String(actual).toLowerCase() };
251
+ } catch (err) {
252
+ return { ok: false, tmpDir, reason: `installer bundle fetch failed: ${err && err.message ? err.message : err}` };
253
+ } finally {
254
+ try { if (io.fs.existsSync(tarPath)) io.fs.unlinkSync(tarPath); } catch (_) { /* best effort */ }
255
+ }
256
+ }
257
+
258
+ /** Human line for the version comparison (doctor/boot prints it). */
259
+ function versionsLine({ ownVersion, bundleVersion, manifestRevisions = [], hub }) {
260
+ const hubInstaller = hub && hub.installer ? hub.installer.version : 'unknown';
261
+ const hubBundle = hub && hub.worker_bundle ? hub.worker_bundle.version : 'unknown';
262
+ const manifests = manifestRevisions.length > 0 ? manifestRevisions.join(', ') : 'unknown';
263
+ return `hub: installer ${hubInstaller}, worker bundle ${hubBundle}; local: installer ${ownVersion || 'unknown'}, worker bundle ${bundleVersion || 'unknown'}, manifests ${manifests}`;
264
+ }
265
+
266
+ /**
267
+ * The whole check: hub versions → decision → download/verify/unpack → replace
268
+ * the persistent installer copy → record the adopted sha256 in install-state.
269
+ * Never throws; never leaves a half-installed update behind.
270
+ *
271
+ * @returns {Promise<{ status: 'skipped'|'current'|'offline'|'updated'|'failed',
272
+ * reason: string|null, hub: object|null, decision: object|null,
273
+ * notes: Array<{level: 'info'|'warn', text: string}>,
274
+ * cliPath: string|null, version: string|null, manifest_revision: string|null }>}
275
+ */
276
+ async function hubSelfUpdate(io, {
277
+ hubUrl, ownVersion = null, bundleVersion = null, manifests = [], statePath = null,
278
+ persistentDir, timeoutMs = TIMEOUT_MS, tmpRoot = null, record = true,
279
+ } = {}) {
280
+ const notes = [];
281
+ const result = { status: 'skipped', reason: null, hub: null, decision: null, notes, cliPath: null, version: null, manifest_revision: null };
282
+ const manifestRevisions = localManifestRevisions(manifests);
283
+ if (!persistentDir) {
284
+ result.reason = 'no persistent installer directory';
285
+ notes.push({ level: 'warn', text: `hub self-update skipped: ${result.reason}` });
286
+ return result;
287
+ }
288
+ const hub = await fetchHubVersions(io, { hubUrl, timeoutMs });
289
+ result.hub = hub;
290
+ if (hub.status === 'offline') {
291
+ result.status = 'offline';
292
+ result.reason = hub.reason;
293
+ notes.push({ level: 'warn', text: `the hub ${hub.hub_url || ''} is not reachable (${hub.reason}) — continuing with the local installer ${ownVersion || 'unknown'} and worker bundle ${bundleVersion || 'unknown'}; nothing was updated` });
294
+ return result;
295
+ }
296
+ const recorded = readRecordedSelfUpdate(io, statePath);
297
+ const decision = decideHubSelfUpdate({ ownVersion, bundleVersion, manifestRevisions, recorded, hub });
298
+ result.decision = decision;
299
+ notes.push({ level: 'info', text: versionsLine({ ownVersion, bundleVersion, manifestRevisions, hub }) });
300
+ for (const w of decision.warnings) notes.push({ level: 'warn', text: w });
301
+ if (hub.status === 'partial' && !(hub.installer && hub.installer.version)) {
302
+ result.status = 'failed';
303
+ result.reason = hub.reason || 'the hub did not publish an installer version';
304
+ notes.push({ level: 'warn', text: `hub self-update skipped: ${result.reason} — continuing with the local installer ${ownVersion || 'unknown'}` });
305
+ return result;
306
+ }
307
+ if (decision.bundle_outdated) {
308
+ notes.push({ level: 'info', text: `worker bundle ${bundleVersion} → ${hub.worker_bundle.version} is updated by the install preflight (the hub installer bundle carries the same files)` });
309
+ }
310
+ if (!decision.needed) {
311
+ result.status = 'current';
312
+ result.reason = decision.warnings.length > 0 ? decision.warnings[0] : null;
313
+ return result;
314
+ }
315
+
316
+ const applied = await applyHubSelfUpdate(io, { hubUrl, hub, tmpRoot });
317
+ if (!applied.ok) {
318
+ if (applied.tmpDir) { try { io.fs.rmSync(applied.tmpDir, { recursive: true, force: true }); } catch (_) { /* best effort */ } }
319
+ result.status = 'failed';
320
+ result.reason = applied.reason;
321
+ notes.push({ level: 'warn', text: `hub self-update failed: ${applied.reason} — continuing with the local installer ${ownVersion || 'unknown'}` });
322
+ return result;
323
+ }
324
+ let cliPath = null;
325
+ try {
326
+ cliPath = management.persistInstaller(io, { srcRoot: applied.pkgDir, destRoot: persistentDir });
327
+ } catch (err) {
328
+ result.status = 'failed';
329
+ result.reason = `the persistent installer copy ${persistentDir} could not be replaced: ${err.message}`;
330
+ notes.push({ level: 'warn', text: `hub self-update failed: ${result.reason} — continuing with the local installer ${ownVersion || 'unknown'}` });
331
+ return result;
332
+ } finally {
333
+ try { io.fs.rmSync(applied.tmpDir, { recursive: true, force: true }); } catch (_) { /* best effort */ }
334
+ }
335
+ result.status = 'updated';
336
+ result.cliPath = cliPath;
337
+ result.version = applied.version;
338
+ result.manifest_revision = applied.manifest_revision;
339
+ if (record) {
340
+ recordSelfUpdate(io, statePath, {
341
+ installer_version: applied.version,
342
+ installer_sha256: applied.sha256,
343
+ manifest_revision: applied.manifest_revision,
344
+ manifest_revisions: applied.manifest_revisions,
345
+ worker_bundle_version: hub.worker_bundle ? hub.worker_bundle.version : null,
346
+ });
347
+ }
348
+ const why = decision.reasons.map((r) => (r.kind === 'installer'
349
+ ? `installer ${r.have || 'unknown'} → ${r.want}`
350
+ : `the hub rebuilt installer ${applied.version} (suite sha256 ${r.have}… → ${r.want}…, its manifests changed)`));
351
+ notes.push({ level: 'info', text: `installer updated: ${why.join('; ')}` });
352
+ if (applied.manifest_revision && !manifestRevisions.includes(applied.manifest_revision)) {
353
+ notes.push({ level: 'info', text: `install manifests ${manifestRevisions.join(', ') || 'unknown'} → ${applied.manifest_revisions.join(', ')}` });
354
+ }
355
+ return result;
356
+ }
357
+
358
+ module.exports = {
359
+ HUB_ROUTES,
360
+ SELF_UPDATE_ENV,
361
+ TIMEOUT_MS,
362
+ packageRootOf,
363
+ fetchHubVersions,
364
+ readManifestRevisions,
365
+ readBundleInfo,
366
+ localManifestRevisions,
367
+ readRecordedSelfUpdate,
368
+ recordSelfUpdate,
369
+ decideHubSelfUpdate,
370
+ applyHubSelfUpdate,
371
+ versionsLine,
372
+ hubSelfUpdate,
373
+ };