@animastor/installer 0.1.0 → 0.2.4

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.
@@ -0,0 +1,96 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Auto-fix planning: everything wrong with an EXISTING worker installation
5
+ * that the installer can repair by itself, collected into one list so the
6
+ * user answers ONE question ("Fix all?") instead of reading warnings.
7
+ *
8
+ * Fixable (non-secret, installer-owned):
9
+ * - .env wiring that differs from this run: WORKER_TYPE (from the profile),
10
+ * NODE_BIN (Node.js >= 20), COMFY_URL (probed), COMFY_PORT, HUB_URL;
11
+ * - an outdated worker bundle (version differs from the bundled source);
12
+ * - bundle dependencies that are declared but not installed (npm ci).
13
+ * The Worker Key is never part of it (`doctor --new-key` asks explicitly).
14
+ */
15
+
16
+ const path = require('path');
17
+ const workerMod = require('./worker');
18
+ const probe = require('./probe');
19
+
20
+ /** Keys the installer owns in the worker .env (never secrets). */
21
+ const FIXABLE_ENV_KEYS = Object.freeze(['WORKER_TYPE', 'NODE_BIN', 'COMFY_URL', 'NOTEBOOK_PATH', 'COMFY_PORT', 'HUB_URL']);
22
+
23
+ const WHY = {
24
+ WORKER_TYPE: 'must match the profile',
25
+ NODE_BIN: 'the worker needs Node.js >= 20',
26
+ COMFY_URL: 'the address where ComfyUI actually answers',
27
+ NOTEBOOK_PATH: 'follows the probed ComfyUI address',
28
+ COMFY_PORT: 'the port of this installation\'s ComfyUI',
29
+ HUB_URL: 'the hub this installer was downloaded from',
30
+ };
31
+
32
+ /**
33
+ * Differences between the current .env values and the desired wiring.
34
+ * Pure. Missing keys are NOT fixes (they are always added).
35
+ * @returns {Array<{ id, key, from, to, title }>}
36
+ */
37
+ function planEnvFixes(current, desired) {
38
+ const out = [];
39
+ for (const key of FIXABLE_ENV_KEYS) {
40
+ if (desired[key] === undefined || desired[key] === null) continue;
41
+ if (current[key] === undefined) continue;
42
+ const from = String(current[key]);
43
+ const to = String(desired[key]);
44
+ if (from === to) continue;
45
+ out.push({ id: `env:${key}`, key, from, to, title: `${key}: ${from || '(empty)'} → ${to || '(empty)'} (${WHY[key]})` });
46
+ }
47
+ return out;
48
+ }
49
+
50
+ /**
51
+ * Collect the fix list for the installation at workerDir.
52
+ * @param {object} io
53
+ * @param {object} opts { workerDir, sourceBundleDir, desired: {KEY: value} }
54
+ * @returns {{ items: Array<{ id, title }>, additions: string[] }}
55
+ */
56
+ function planFixes(io, { workerDir, sourceBundleDir = null, sourceVersion = null, desired = {} }) {
57
+ const items = [];
58
+ const additions = [];
59
+ if (!workerDir || !io.fs.existsSync(path.join(workerDir, 'worker.cjs'))) return { items, additions };
60
+
61
+ const installed = workerMod.readPkgVersion(io, workerDir);
62
+ const source = (sourceBundleDir ? workerMod.readPkgVersion(io, sourceBundleDir) : null) || sourceVersion;
63
+ if (installed && source && installed !== source) {
64
+ items.push({ id: 'bundle', title: `worker bundle ${installed} → ${source} (worker files only; .env is kept)` });
65
+ }
66
+
67
+ const deps = Object.keys(workerMod.declaredDependencies(io, workerDir));
68
+ if (deps.length > 0 && !io.fs.existsSync(path.join(workerDir, 'node_modules'))) {
69
+ items.push({ id: 'deps', title: `install worker dependencies (${deps.join(', ')}): npm ci in ${workerDir}` });
70
+ }
71
+
72
+ if (io.fs.existsSync(path.join(workerDir, '.env'))) {
73
+ const current = workerMod.readEnvValues(io, workerDir);
74
+ for (const f of planEnvFixes(current, desired)) items.push(f);
75
+ for (const key of FIXABLE_ENV_KEYS) {
76
+ if (desired[key] !== undefined && desired[key] !== '' && current[key] === undefined) additions.push(`${key}=${desired[key]}`);
77
+ }
78
+ if (current.NODE_BIN && probe.nodeMajor(probe.nodeBinaryVersion(io, current.NODE_BIN)) < 20 && !items.some((i) => i.key === 'NODE_BIN') && desired.NODE_BIN) {
79
+ items.push({ id: 'env:NODE_BIN', key: 'NODE_BIN', from: current.NODE_BIN, to: desired.NODE_BIN, title: `NODE_BIN: ${current.NODE_BIN} is missing or older than Node.js 20 → ${desired.NODE_BIN}` });
80
+ }
81
+ }
82
+ // ONE entry per fix: two rules can describe the same key (a stale
83
+ // NODE_BIN and the generic env diff) — the list the user confirms and the
84
+ // list the engine applies must be the same, and neither may show a
85
+ // change that is not going to happen.
86
+ const seen = new Set();
87
+ const unique = items.filter((i) => {
88
+ const id = i.id || i.key;
89
+ if (seen.has(id)) return false;
90
+ seen.add(id);
91
+ return true;
92
+ });
93
+ return { items: unique, additions };
94
+ }
95
+
96
+ module.exports = { FIXABLE_ENV_KEYS, planEnvFixes, planFixes };
@@ -38,10 +38,20 @@ function createRealIo() {
38
38
  chmodSync: (p, mode) => fs.chmodSync(p, mode),
39
39
  statSync: (p) => {
40
40
  const s = fs.statSync(p);
41
- return { size: s.size, isFile: s.isFile(), isDirectory: s.isDirectory(), uid: s.uid, gid: s.gid };
41
+ return { size: s.size, isFile: s.isFile(), isDirectory: s.isDirectory(), uid: s.uid, gid: s.gid, mtimeMs: s.mtimeMs };
42
42
  },
43
43
  readdirSync: (p) => fs.readdirSync(p),
44
44
  readlinkSync: (p) => fs.readlinkSync(p),
45
+ symlinkSync: (target, p) => fs.symlinkSync(target, p),
46
+ /** lstat without following links; null when the path does not exist. */
47
+ lstatSync: (p) => {
48
+ try {
49
+ const s = fs.lstatSync(p);
50
+ return { isSymbolicLink: s.isSymbolicLink(), isFile: s.isFile(), isDirectory: s.isDirectory() };
51
+ } catch (_) {
52
+ return null;
53
+ }
54
+ },
45
55
  },
46
56
  /** Synchronous command execution (git, pip, npm, nvidia-smi…). */
47
57
  exec(command, args = [], opts = {}) {
@@ -243,6 +253,7 @@ function createRealIo() {
243
253
  function createMemoryFs(initial = {}) {
244
254
  const files = new Map(); // path -> { data: Buffer|string, mode }
245
255
  const dirs = new Set(['/']);
256
+ const links = new Map(); // path -> target (symlinks)
246
257
  for (const [p, data] of Object.entries(initial)) {
247
258
  files.set(norm(p), { data, mode: 0o644 });
248
259
  let d = path.dirname(norm(p));
@@ -288,7 +299,8 @@ function createMemoryFs(initial = {}) {
288
299
  if (opts && opts.recursive) {
289
300
  let d = target;
290
301
  const stack = [];
291
- while (d && d !== '/' && !dirs.has(d)) { stack.push(d); d = path.dirname(d); }
302
+ // guard: dirname('.') === '.' — the loop must always make progress
303
+ while (d && d !== '/' && !dirs.has(d) && d !== path.dirname(d)) { stack.push(d); d = path.dirname(d); }
292
304
  for (const dd of stack.reverse()) dirs.add(dd);
293
305
  return;
294
306
  }
@@ -327,6 +339,7 @@ function createMemoryFs(initial = {}) {
327
339
  throw Object.assign(new Error(`ENOENT: ${a}`), { code: 'ENOENT' });
328
340
  },
329
341
  unlinkSync: (p) => {
342
+ if (links.has(norm(p))) { links.delete(norm(p)); return; }
330
343
  if (!files.has(norm(p))) throw Object.assign(new Error(`ENOENT: ${p}`), { code: 'ENOENT' });
331
344
  files.delete(norm(p));
332
345
  },
@@ -387,6 +400,21 @@ function createMemoryFs(initial = {}) {
387
400
  }
388
401
  return Array.from(out).sort();
389
402
  },
403
+ symlinkSync: (target, p) => {
404
+ assertParent(p);
405
+ if (files.has(norm(p)) || links.has(norm(p))) throw Object.assign(new Error(`EEXIST: ${p}`), { code: 'EEXIST' });
406
+ links.set(norm(p), String(target));
407
+ },
408
+ readlinkSync: (p) => {
409
+ if (!links.has(norm(p))) throw Object.assign(new Error(`EINVAL: ${p}`), { code: 'EINVAL' });
410
+ return links.get(norm(p));
411
+ },
412
+ lstatSync: (p) => {
413
+ if (links.has(norm(p))) return { isSymbolicLink: true, isFile: false, isDirectory: false };
414
+ if (files.has(norm(p))) return { isSymbolicLink: false, isFile: true, isDirectory: false };
415
+ if (dirs.has(norm(p))) return { isSymbolicLink: false, isFile: false, isDirectory: true };
416
+ return null;
417
+ },
390
418
  };
391
419
  }
392
420
 
@@ -415,6 +443,9 @@ function createDryRunIo(io) {
415
443
  rmdirSync: guard('fs.rmdirSync'),
416
444
  copyFileSync: guard('fs.copyFileSync'),
417
445
  chmodSync: guard('fs.chmodSync'),
446
+ symlinkSync: guard('fs.symlinkSync'),
447
+ readlinkSync: io.fs.readlinkSync,
448
+ lstatSync: io.fs.lstatSync,
418
449
  },
419
450
  exec: guard('exec'),
420
451
  spawnDaemon: guard('spawnDaemon'),
@@ -0,0 +1,274 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Custom-node Python dependencies of the RUNNING ComfyUI (installer 0.2.4).
5
+ *
6
+ * Live TIR boots 2026-10-31 (type A): only /home survives a node restart, so
7
+ * the pip packages of a custom node (ComfyUI-Qwen3-TTS:
8
+ * custom_nodes/qwen3-tts/requirements.txt) disappear with the image while the
9
+ * node directory stays. The platform's ComfyUI then starts without the node
10
+ * classes and doctor reported "ComfyUI node classes missing: Qwen3TTS*".
11
+ *
12
+ * 1. the interpreter is taken from the main.py PROCESS (/proc/<pid>: its
13
+ * argv[0], VIRTUAL_ENV / PATH from its environ, then /proc/<pid>/exe) —
14
+ * never a guessed `python3`;
15
+ * 2. every required custom node of the profile that is on disk and ships a
16
+ * requirements.txt is checked IN THAT PYTHON (importlib.metadata +
17
+ * packaging; no network, nothing installed);
18
+ * 3. unsatisfied → `<python> -m pip install -r requirements.txt` with the
19
+ * installed torch family pinned as a constraint (pip must never swap the
20
+ * platform's torch build);
21
+ * 4. a platform ComfyUI is restarted only when allowed: SIGTERM to exactly
22
+ * the pid that was inspected (its /proc cmdline re-checked first), then
23
+ * wait until the PLATFORM starts a new main.py (new pid + GET
24
+ * /system_stats + the node classes in /object_info).
25
+ */
26
+
27
+ const path = require('path');
28
+ const probe = require('./probe');
29
+ const comfyui = require('./comfyui');
30
+ const comfyOwner = require('./comfy-owner');
31
+
32
+ /**
33
+ * Python run with `-I -c`: argv[1] = requirements.txt. Prints ONE JSON line:
34
+ * { torch: { name: version }, items: [{ line, name, status, have, want }] }
35
+ * status: ok | missing | mismatch | skipped (marker false) | unparsed.
36
+ */
37
+ const CHECK_SCRIPT = [
38
+ 'import json, sys',
39
+ 'try:',
40
+ ' from packaging.requirements import Requirement',
41
+ 'except Exception:',
42
+ ' from pip._vendor.packaging.requirements import Requirement',
43
+ 'try:',
44
+ ' from importlib import metadata as md',
45
+ 'except Exception:',
46
+ ' import importlib_metadata as md',
47
+ 'def ver(n):',
48
+ ' try:',
49
+ ' return md.version(n)',
50
+ ' except Exception:',
51
+ ' return None',
52
+ 'items = []',
53
+ 'for raw in open(sys.argv[1], encoding="utf-8", errors="replace"):',
54
+ ' line = raw.split(" #")[0].strip()',
55
+ ' if not line or line.startswith("#"):',
56
+ ' continue',
57
+ ' if line.startswith("-") or "://" in line and "@" not in line:',
58
+ ' items.append({"line": line, "status": "unparsed"})',
59
+ ' continue',
60
+ ' try:',
61
+ ' r = Requirement(line)',
62
+ ' except Exception:',
63
+ ' items.append({"line": line, "status": "unparsed"})',
64
+ ' continue',
65
+ ' if r.marker is not None and not r.marker.evaluate():',
66
+ ' items.append({"line": line, "name": r.name, "status": "skipped"})',
67
+ ' continue',
68
+ ' have = ver(r.name)',
69
+ ' st = "missing" if have is None else ("ok" if not r.specifier or r.specifier.contains(have, prereleases=True) else "mismatch")',
70
+ ' items.append({"line": line, "name": r.name, "status": st, "have": have, "want": str(r.specifier) or None})',
71
+ 'torch = {n: ver(n) for n in ("torch", "torchvision", "torchaudio") if ver(n)}',
72
+ 'print(json.dumps({"torch": torch, "items": items}))',
73
+ ].join('\n');
74
+
75
+ function readProc(io, pid, name) {
76
+ try { return String(io.fs.readFileSync(`/proc/${pid}/${name}`, 'utf8')); } catch (_) { return null; }
77
+ }
78
+
79
+ function procEnv(io, pid) {
80
+ const raw = readProc(io, pid, 'environ');
81
+ const env = {};
82
+ if (!raw) return env;
83
+ for (const kv of raw.split('\0')) {
84
+ const i = kv.indexOf('=');
85
+ if (i > 0) env[kv.slice(0, i)] = kv.slice(i + 1);
86
+ }
87
+ return env;
88
+ }
89
+
90
+ /**
91
+ * The Python interpreter a running ComfyUI process uses, from /proc/<pid>.
92
+ * @returns {{ python: string|null, source: string }}
93
+ */
94
+ function pythonOfProcess(io, pid) {
95
+ const argv = String(readProc(io, pid, 'cmdline') || '').split('\0').filter(Boolean);
96
+ if (argv.length === 0) return { python: null, source: 'no /proc cmdline' };
97
+ const a0 = argv[0];
98
+ const env = procEnv(io, pid);
99
+ const cwd = (() => { try { return io.fs.readlinkSync(`/proc/${pid}/cwd`); } catch (_) { return null; } })();
100
+ if (path.isAbsolute(a0)) return { python: a0, source: 'argv[0]' };
101
+ if (/python/.test(path.basename(a0))) {
102
+ if (a0.includes('/') && cwd) return { python: path.resolve(cwd, a0), source: 'argv[0] (relative to cwd)' };
103
+ if (env.VIRTUAL_ENV) {
104
+ const cand = path.join(env.VIRTUAL_ENV, 'bin', a0);
105
+ if (io.fs.existsSync(cand)) return { python: cand, source: 'VIRTUAL_ENV of the process' };
106
+ }
107
+ for (const dir of String(env.PATH || '').split(':').filter(Boolean)) {
108
+ const cand = path.join(dir, a0);
109
+ if (io.fs.existsSync(cand)) return { python: cand, source: 'PATH of the process' };
110
+ }
111
+ }
112
+ try {
113
+ const exe = io.fs.readlinkSync(`/proc/${pid}/exe`);
114
+ if (exe) return { python: exe, source: '/proc/<pid>/exe' };
115
+ } catch (_) { /* not readable */ }
116
+ return { python: null, source: `cannot resolve ${a0}` };
117
+ }
118
+
119
+ /** Required custom nodes of the profiles that are on disk with a requirements.txt. */
120
+ function profileNodeRequirements(io, { root, manifests }) {
121
+ const out = [];
122
+ const seen = new Set();
123
+ for (const m of manifests || []) {
124
+ for (const dep of m.dependencies || []) {
125
+ if (dep.kind !== 'custom_node' || dep.requirement !== 'required' || seen.has(dep.id)) continue;
126
+ seen.add(dep.id);
127
+ const dir = (dep.install && dep.install.directory) || dep.name;
128
+ const reqPath = path.join(root, 'custom_nodes', dir, 'requirements.txt');
129
+ if (!io.fs.existsSync(reqPath)) continue;
130
+ out.push({ id: dep.id, directory: dir, reqPath, classes: dep.provides_classes || [] });
131
+ }
132
+ }
133
+ return out;
134
+ }
135
+
136
+ /** Run the check script for one requirements.txt in `python`. */
137
+ function checkRequirementsFile(io, { python, reqPath }) {
138
+ let r = null;
139
+ try { r = io.exec(python, ['-I', '-c', CHECK_SCRIPT, reqPath], { timeout: 120000 }); } catch (err) { r = { code: 1, stderr: err.message }; }
140
+ if (!r || r.code !== 0) return { ok: false, error: String((r && (r.stderr || r.error)) || 'check failed').slice(-300), unsatisfied: [], torch: {} };
141
+ let parsed = null;
142
+ try { parsed = JSON.parse(String(r.stdout || '').trim().split('\n').pop()); } catch (_) { parsed = null; }
143
+ if (!parsed || !Array.isArray(parsed.items)) return { ok: false, error: 'unexpected check output', unsatisfied: [], torch: {} };
144
+ const unsatisfied = parsed.items.filter((i) => i.status === 'missing' || i.status === 'mismatch');
145
+ return { ok: true, unsatisfied, torch: parsed.torch || {}, items: parsed.items };
146
+ }
147
+
148
+ /**
149
+ * Which profile nodes have unsatisfied pip requirements in `python`.
150
+ * @returns {{ python, nodes: Array<{ id, directory, reqPath, classes, unsatisfied: object[] }>, torch: object, errors: string[] }}
151
+ */
152
+ function checkNodeDeps(io, { python, root, manifests }) {
153
+ const nodes = [];
154
+ const errors = [];
155
+ let torch = {};
156
+ for (const n of profileNodeRequirements(io, { root, manifests })) {
157
+ const c = checkRequirementsFile(io, { python, reqPath: n.reqPath });
158
+ if (!c.ok) { errors.push(`${n.directory}: ${c.error}`); continue; }
159
+ torch = { ...torch, ...c.torch };
160
+ if (c.unsatisfied.length > 0) nodes.push({ ...n, unsatisfied: c.unsatisfied });
161
+ }
162
+ return { python, nodes, torch, errors };
163
+ }
164
+
165
+ /** "qwen3-tts (transformers missing, librosa>=0.10 has 0.9)" */
166
+ function describeUnsatisfied(nodes) {
167
+ return nodes.map((n) => `${n.directory} (${n.unsatisfied.map((u) => (u.status === 'missing'
168
+ ? `${u.name} missing`
169
+ : `${u.name}${u.want || ''} has ${u.have}`)).join(', ')})`).join('; ');
170
+ }
171
+
172
+ /**
173
+ * pip install -r for every node in `nodes` into `python`, with the installed
174
+ * torch family pinned. A permission error on a system interpreter retries
175
+ * with --user (the account's site-packages live in /home and survive).
176
+ * @returns {{ ok: boolean, installed: string[], failed: Array<{ directory, reason }> }}
177
+ */
178
+ function installNodeDeps(io, { python, nodes, torch = {}, constraintsPath = null, log = null }) {
179
+ let constraint = null;
180
+ const pins = Object.entries(torch || {}).map(([n, v]) => `${n}==${v}`);
181
+ if (pins.length > 0 && constraintsPath) {
182
+ try {
183
+ io.fs.mkdirSync(path.dirname(constraintsPath), { recursive: true });
184
+ io.fs.writeFileSync(constraintsPath, `${pins.join('\n')}\n`);
185
+ constraint = constraintsPath;
186
+ } catch (_) { constraint = null; }
187
+ }
188
+ const installed = [];
189
+ const failed = [];
190
+ for (const n of nodes) {
191
+ const args = ['-m', 'pip', 'install', '-r', n.reqPath];
192
+ if (constraint) args.push('-c', constraint);
193
+ if (log) log.info(`installing the Python dependencies of ${n.directory} into ${python}`);
194
+ let r = io.exec(python, args, { timeout: 60 * 60 * 1000 });
195
+ if (r.code !== 0 && /permission denied|not writeable|EnvironmentError: \[Errno 13\]/i.test(String(r.stderr || ''))) {
196
+ r = io.exec(python, [...args, '--user'], { timeout: 60 * 60 * 1000 });
197
+ }
198
+ if (r.code === 0) installed.push(n.directory);
199
+ else failed.push({ directory: n.directory, reason: `pip install -r ${n.reqPath} failed: ${String(r.stderr || r.error || '').slice(-300)}` });
200
+ }
201
+ return { ok: failed.length === 0, installed, failed };
202
+ }
203
+
204
+ function pidAlive(io, pid) {
205
+ if (typeof io.pidAlive === 'function') return io.pidAlive(pid);
206
+ return io.fs.existsSync(`/proc/${pid}`);
207
+ }
208
+
209
+ /**
210
+ * Restart the PLATFORM's ComfyUI: stop exactly `pid` (its /proc cmdline is
211
+ * re-read and must still be a main.py — a recycled pid is never signaled),
212
+ * then wait until the platform starts a new one: another pid, GET
213
+ * /system_stats with a ComfyUI payload and every class of `expectClasses`
214
+ * in /object_info. The platform starts it — the installer never does.
215
+ * @returns {Promise<{ ok: boolean, stopped: boolean, old_pid, pid: number|null, url: string|null, waited_ms: number, missing_classes: string[], reason: string|null }>}
216
+ */
217
+ async function restartPlatformComfyUI(io, {
218
+ pid, timeoutMs = 600000, intervalMs = 3000, stopTimeoutMs = 15000, expectClasses = [],
219
+ sleep = null, log = null, onProgress = null, progressMs = 30000,
220
+ } = {}) {
221
+ const now = () => (typeof io.now === 'function' ? io.now() : Date.now());
222
+ const pause = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
223
+ const started = now();
224
+ const base = { stopped: false, old_pid: pid, pid: null, url: null, waited_ms: 0, missing_classes: [] };
225
+ const argv = String(readProc(io, pid, 'cmdline') || '').split('\0').filter(Boolean);
226
+ if (!argv.some((a) => /(^|\/)main\.py$/.test(a))) {
227
+ return { ...base, ok: false, reason: `pid ${pid} is no longer a ComfyUI main.py — nothing was stopped` };
228
+ }
229
+ const kill = (sig) => { try { if (typeof io.kill === 'function') io.kill(pid, sig); else process.kill(pid, sig); } catch (_) { /* gone */ } };
230
+ if (log) log.info(`stopping the platform's ComfyUI (pid ${pid}) so it is started again with the new node dependencies`);
231
+ kill('SIGTERM');
232
+ const stopDeadline = now() + stopTimeoutMs;
233
+ while (pidAlive(io, pid) && now() < stopDeadline) await pause(Math.min(500, intervalMs));
234
+ if (pidAlive(io, pid)) kill('SIGKILL');
235
+ let nextProgress = started + progressMs;
236
+ let last = null;
237
+ for (;;) {
238
+ const waited = now() - started;
239
+ const procs = probe.listRunningComfyUI(io).filter((p) => p.pid !== pid);
240
+ for (const p of procs) {
241
+ const { url } = comfyOwner.comfyUrlFor(p);
242
+ if (!(await comfyOwner.verifyComfyUrl(io, url))) { last = { pid: p.pid, url, why: 'does not answer GET /system_stats yet' }; continue; }
243
+ const classes = expectClasses.length > 0 ? await comfyui.objectInfoClasses(io, url) : new Set();
244
+ const missing = expectClasses.filter((c) => !classes || !classes.has(c));
245
+ if (missing.length === 0) {
246
+ return { ...base, ok: true, stopped: true, pid: p.pid, url, waited_ms: waited, reason: null };
247
+ }
248
+ last = { pid: p.pid, url, why: `answers, node classes missing: ${missing.join(', ')}`, missing };
249
+ }
250
+ if (waited >= timeoutMs) {
251
+ const secs = Math.round(timeoutMs / 1000);
252
+ const reason = last
253
+ ? `the platform started ComfyUI again (pid ${last.pid} at ${last.url}) but it ${last.why} after ${secs} s`
254
+ : `the platform did not start ComfyUI again within ${secs} s after it was stopped (old pid ${pid}) — start it from the platform console`;
255
+ return { ...base, ok: false, stopped: true, pid: last ? last.pid : null, url: last ? last.url : null, waited_ms: waited, missing_classes: (last && last.missing) || [], reason };
256
+ }
257
+ if (onProgress && now() >= nextProgress) {
258
+ onProgress(`waiting for the platform to start ComfyUI again — ${last ? `pid ${last.pid} ${last.why}` : 'no new main.py process yet'} (${Math.round(waited / 1000)} s of ${Math.round(timeoutMs / 1000)} s)`);
259
+ nextProgress += progressMs;
260
+ }
261
+ await pause(Math.min(intervalMs, Math.max(1, timeoutMs - waited)));
262
+ }
263
+ }
264
+
265
+ module.exports = {
266
+ CHECK_SCRIPT,
267
+ pythonOfProcess,
268
+ profileNodeRequirements,
269
+ checkRequirementsFile,
270
+ checkNodeDeps,
271
+ describeUnsatisfied,
272
+ installNodeDeps,
273
+ restartPlatformComfyUI,
274
+ };
@@ -249,6 +249,175 @@ function checkPythonPrerequisites(io, opts = {}) {
249
249
  return { ok: true, python_version: pythonVersion, deep_checked: true };
250
250
  }
251
251
 
252
+ // ---------------------------------------------------------------------------
253
+ // Host package installation (apt on Debian/Ubuntu) — with consent
254
+ // ---------------------------------------------------------------------------
255
+
256
+ /** dpkg/apt lock held by another process — a wait-and-retry situation, not a bug. */
257
+ const DPKG_LOCK_PATTERN = /Could not get lock|Unable to acquire the dpkg frontend lock|dpkg frontend lock|is another process using it|Could not open lock file/i;
258
+ /** apt's package index is stale — one `apt-get update` fixes it. */
259
+ const APT_STALE_INDEX_PATTERN = /Unable to locate package|has no installation candidate/i;
260
+
261
+ /** Normalize a package spec (string or array) into a list of names. */
262
+ function hostPackageList(packages) {
263
+ const list = Array.isArray(packages) ? packages : String(packages || '').split(/\s+/);
264
+ return list.map((p) => String(p).trim()).filter(Boolean);
265
+ }
266
+
267
+ /**
268
+ * Can this process install a host package WITHOUT an interactive password?
269
+ * root → yes (runs apt-get directly);
270
+ * user + `sudo -n true` ok → yes (runs `sudo -n apt-get …`);
271
+ * otherwise → no: the caller prints the remediation command.
272
+ * Platforms without a host package manager answer no (adapter flag).
273
+ * @returns {{ ok: boolean, via: 'root'|'sudo'|null, command_prefix: string[] }}
274
+ */
275
+ function canElevate(io, { platformAdapter = null, uid = currentUid() } = {}) {
276
+ const adapter = adapterOf({ platformAdapter });
277
+ if (adapter.supportsHostInstall !== true) return { ok: false, via: null, command_prefix: [] };
278
+ if (uid === 0) return { ok: true, via: 'root', command_prefix: [] };
279
+ if (uid === null || uid === undefined) return { ok: false, via: null, command_prefix: [] };
280
+ const probe = io.exec('sudo', ['-n', 'true']);
281
+ if (probe && probe.code === 0) return { ok: true, via: 'sudo', command_prefix: ['sudo', '-n'] };
282
+ return { ok: false, via: null, command_prefix: [] };
283
+ }
284
+
285
+ /**
286
+ * Install host packages (the missing `python3.X-venv` and friends) without a
287
+ * second installer run: runs `apt-get update` ONCE when apt reports a stale
288
+ * index, `apt-get install -y`, and turns a held dpkg lock into a clear
289
+ * message instead of an opaque exit code.
290
+ * @returns {{ ok, packages, updated, command, code, output, message }}
291
+ */
292
+ function installHostPackages(io, { packages, platformAdapter = null, elevated = null, log = null, timeoutMs = 10 * 60 * 1000 } = {}) {
293
+ const adapter = adapterOf({ platformAdapter });
294
+ const pkgs = hostPackageList(packages);
295
+ if (pkgs.length === 0) return { ok: true, packages: [], skipped: true, message: null };
296
+ if (adapter.supportsHostInstall !== true) {
297
+ return {
298
+ ok: false,
299
+ packages: pkgs,
300
+ reason: 'no-host-package-manager',
301
+ message: `The installer cannot install ${pkgs.join(', ')} automatically on this platform — install it with the system package manager and re-run.`,
302
+ };
303
+ }
304
+ const elev = elevated || canElevate(io, { platformAdapter: adapter });
305
+ if (!elev.ok) {
306
+ return {
307
+ ok: false,
308
+ packages: pkgs,
309
+ reason: 'no-privileges',
310
+ message: `Cannot install ${pkgs.join(', ')}: root or passwordless sudo is required.`,
311
+ };
312
+ }
313
+ const run = (update) => {
314
+ const c = adapter.hostInstallCommand({ packages: pkgs, update });
315
+ const res = elev.via === 'sudo'
316
+ ? io.exec('sudo', ['-n', c.cmd, ...c.args], { timeout: timeoutMs })
317
+ : io.exec(c.cmd, c.args, { timeout: timeoutMs });
318
+ return { res, command: `${elev.via === 'sudo' ? 'sudo -n ' : ''}${c.cmd} ${c.args.join(' ')}` };
319
+ };
320
+ const outputOf = (r) => String((r && (r.stderr || r.stdout || r.error)) || '');
321
+
322
+ let attempt = run(false);
323
+ let updated = false;
324
+ if (attempt.res.code !== 0 && APT_STALE_INDEX_PATTERN.test(outputOf(attempt.res))) {
325
+ const up = run(true);
326
+ updated = true;
327
+ // retry the install once, after the index refresh
328
+ attempt = up.res.code === 0 ? run(false) : up;
329
+ }
330
+ const text = outputOf(attempt.res);
331
+ const ok = attempt.res.code === 0;
332
+ let message = null;
333
+ if (!ok) {
334
+ message = DPKG_LOCK_PATTERN.test(text)
335
+ ? 'apt/dpkg is busy (another package manager process holds the lock) — wait for it to finish, then re-run the installer.'
336
+ : `Installing ${pkgs.join(', ')} failed (exit ${attempt.res.code}): ${text.trim().split('\n').filter(Boolean).slice(-3).join(' ')}`;
337
+ }
338
+ if (log) {
339
+ if (ok && log.info) log.info(`host package(s) installed: ${pkgs.join(', ')}${updated ? ' (apt-get update ran once)' : ''}`);
340
+ else if (!ok && log.warn) log.warn(message);
341
+ }
342
+ return { ok, packages: pkgs, updated, command: attempt.command, code: attempt.res.code, output: text, message };
343
+ }
344
+
345
+ /**
346
+ * Turn a failed prerequisite into a working one IN THE SAME RUN:
347
+ * ask "Install <pkg> now? [Y/n]" (or skip the question with --yes), install
348
+ * the host package, re-check the prerequisite and continue — no installer
349
+ * restart. Without root/passwordless sudo (or without a terminal and without
350
+ * --yes) nothing is installed and the caller prints the exact command.
351
+ * @returns {{ ok, failure, installed?, install?, elevatable?, declined?, reason? }}
352
+ */
353
+ /**
354
+ * True when a Debian/Ubuntu package is installed (dpkg-query status).
355
+ * Used by the boot path: `animastor doctor --yes` installs the packages that
356
+ * DISAPPEARED with the image restart instead of asking.
357
+ */
358
+ function hostPackageInstalled(io, pkg) {
359
+ const r = io.exec('dpkg-query', ['-W', '-f=${Status}', pkg]);
360
+ return !!(r && r.code === 0 && /install ok installed/.test(String(r.stdout || '')));
361
+ }
362
+
363
+ /**
364
+ * Install the host packages that are actually MISSING (one apt-get run),
365
+ * without asking when `yes` is set (boot script: no TTY). Without root or
366
+ * passwordless sudo nothing is installed and the exact command is returned.
367
+ * @returns {Promise<{ ok: boolean, installed: string[], missing: string[], message?: string, updated?: boolean }>}
368
+ */
369
+ async function installMissingHostPackages(io, { packages = [], prompt = null, yes = false, log = null, platformAdapter = null } = {}) {
370
+ const adapter = adapterOf({ platformAdapter });
371
+ if (!adapter || adapter.name !== 'linux' || adapter.HOST_INSTALL_SUPPORTED === false) {
372
+ return { ok: true, installed: [], missing: [], message: 'automatic host package installation is not supported on this platform' };
373
+ }
374
+ const wanted = [...new Set((packages || []).filter(Boolean))];
375
+ const missing = wanted.filter((pkg) => !hostPackageInstalled(io, pkg));
376
+ if (missing.length === 0) return { ok: true, installed: [], missing: [] };
377
+ const elevated = canElevate(io, { platformAdapter: adapter });
378
+ if (!elevated.ok) {
379
+ return {
380
+ ok: false, installed: [], missing,
381
+ message: `missing host package(s) ${missing.join(', ')} — install with: ${missing.map((p) => aptCommand(p, adapter.name)).join(' && ')}`,
382
+ };
383
+ }
384
+ if (!yes) {
385
+ if (!prompt || !prompt.available) {
386
+ return { ok: false, installed: [], missing, message: `missing host package(s) ${missing.join(', ')} (non-interactive — re-run with --yes)` };
387
+ }
388
+ const answer = await prompt.confirm(`Install ${missing.join(' ')} now?`, { defaultYes: true });
389
+ if (!answer) return { ok: false, installed: [], missing, message: `skipped by the user: ${missing.join(', ')}` };
390
+ }
391
+ if (log) log.info(`installing missing host package(s): ${missing.join(', ')}`);
392
+ const r = installHostPackages(io, { packages: missing, elevated, log });
393
+ return {
394
+ ok: r.ok,
395
+ installed: r.ok ? missing : [],
396
+ missing: r.ok ? [] : missing,
397
+ updated: r.updated,
398
+ message: r.message,
399
+ };
400
+ }
401
+
402
+ async function resolveHostPrerequisite(io, { failure, opts = {}, prompt = null, yes = false, log = null, platformAdapter = null } = {}) {
403
+ const pkg = (failure && ((failure.remediation && failure.remediation.package) || failure.hostPackage)) || null;
404
+ if (!pkg) return { ok: false, failure, reason: 'no-host-package' };
405
+ const adapter = adapterOf({ platformAdapter });
406
+ const elev = canElevate(io, { platformAdapter: adapter });
407
+ if (!elev.ok) return { ok: false, failure, elevatable: false, reason: 'no-privileges' };
408
+ if (!yes) {
409
+ if (!prompt || !prompt.available) return { ok: false, failure, elevatable: true, reason: 'no-tty' };
410
+ const accepted = await prompt.confirm(`Install ${pkg} now?`, { defaultYes: true });
411
+ if (!accepted) return { ok: false, failure, elevatable: true, declined: true, reason: 'declined' };
412
+ }
413
+ if (log && log.info) log.info(`installing host package ${pkg} (${elev.via})`);
414
+ const install = installHostPackages(io, { packages: pkg, platformAdapter: adapter, elevated: elev, log });
415
+ if (!install.ok) return { ok: false, failure, install, elevatable: true, reason: 'install-failed' };
416
+ const again = checkPythonPrerequisites(io, opts);
417
+ if (again.ok) return { ok: true, failure, installed: install };
418
+ return { ok: false, failure: again.failure, install, reason: 'still-missing' };
419
+ }
420
+
252
421
  // ---------------------------------------------------------------------------
253
422
  // Ownership guard — sudo vs. normal user mixing
254
423
  // ---------------------------------------------------------------------------
@@ -387,6 +556,13 @@ function checkBuildPrerequisites(io, { python = 'python3', log = null, platformA
387
556
  module.exports = {
388
557
  PrerequisiteError,
389
558
  debianVenvPackage,
559
+ canElevate,
560
+ installHostPackages,
561
+ resolveHostPrerequisite,
562
+ hostPackageList,
563
+ hostPackageInstalled,
564
+ installMissingHostPackages,
565
+ DPKG_LOCK_PATTERN,
390
566
  classifyVenvCreateFailure,
391
567
  classifyVenvDir,
392
568
  remediationPayload,