@animastor/installer 0.1.1 → 0.2.9

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,375 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Version replacements made by the persistent node-deps overlay
5
+ * (installer 0.2.6, ADR in animastor-docs INSTALLER_ARCHITECTURE
6
+ * §node deps → "One GPU node — one profile").
7
+ *
8
+ * E2E 02.11 (TIR, audio/qwen-tts): qwen-tts pins transformers==4.57.3, so pip
9
+ * put into ~/animastor/pydeps not only the missing packages but also
10
+ * transformers 4.57.3 (platform 5.0.0), huggingface_hub 0.36.2 (platform
11
+ * 1.3.5) and cryptography 50.0.2 (platform 3.4.8). The overlay is FIRST in
12
+ * sys.path of the whole ComfyUI (prestartup script), so these versions apply
13
+ * to ComfyUI itself and to every other custom node — silently.
14
+ *
15
+ * 1. after the deps are in place the overlay is compared with the platform
16
+ * Python (`python -I`, importlib.metadata, the overlay NOT on sys.path):
17
+ * every package present in both with different versions is a
18
+ * replacement; it is attributed to the node(s) that forced it — a node
19
+ * whose requirement closure (requirements.txt + Requires-Dist, as
20
+ * ComfyUI sees the packages: overlay first) excludes the platform
21
+ * version;
22
+ * 2. a replacement touching a package that ANOTHER profile on this ComfyUI
23
+ * uses (a node of that profile that did not force it), or — with more
24
+ * than one profile — a ComfyUI core requirement (<root>/requirements.txt)
25
+ * whose range excludes the overlay version, is a conflict: it needs
26
+ * consent (interactive question or --accept-node-deps-overrides); boot
27
+ * and --yes never consent.
28
+ */
29
+
30
+ const path = require('path');
31
+
32
+ /**
33
+ * Python run with `-I -c` in the PLATFORM interpreter:
34
+ * argv[1] overlay site-packages, argv[2] ComfyUI requirements.txt ('' = none),
35
+ * argv[3] JSON [{ key, req }] — requirements.txt of the custom nodes.
36
+ * Prints ONE JSON line:
37
+ * { overrides: [{ name, key, platform, overlay }],
38
+ * nodes: [{ key, uses: { <pkg key>: { specs, accepts_platform, accepts_overlay } } }],
39
+ * core: { <pkg key>: { spec, accepts_overlay } } }
40
+ */
41
+ const OVERRIDES_SCRIPT = [
42
+ 'import json, re, sys',
43
+ 'try:',
44
+ ' from packaging.requirements import Requirement',
45
+ ' from packaging.specifiers import SpecifierSet',
46
+ 'except Exception:',
47
+ ' from pip._vendor.packaging.requirements import Requirement',
48
+ ' from pip._vendor.packaging.specifiers import SpecifierSet',
49
+ 'try:',
50
+ ' from importlib import metadata as md',
51
+ 'except Exception:',
52
+ ' import importlib_metadata as md',
53
+ 'def canon(n):',
54
+ ' return re.sub(r"[-_.]+", "-", n).lower()',
55
+ 'overlay_sp = sys.argv[1]',
56
+ 'core_req = sys.argv[2]',
57
+ 'nodes = json.loads(sys.argv[3])',
58
+ 'platform_path = list(sys.path)',
59
+ 'def dists(paths):',
60
+ ' out = {}',
61
+ ' for d in md.distributions(path=paths):',
62
+ ' try:',
63
+ ' n = d.metadata["Name"]',
64
+ ' except Exception:',
65
+ ' n = None',
66
+ ' if n and canon(n) not in out:',
67
+ ' out[canon(n)] = d',
68
+ ' return out',
69
+ 'overlay = dists([overlay_sp])',
70
+ 'platform = dists(platform_path)',
71
+ 'both = dists([overlay_sp] + platform_path)',
72
+ 'overrides = []',
73
+ 'for k, d in sorted(overlay.items()):',
74
+ ' p = platform.get(k)',
75
+ ' if p is None or p.version == d.version:',
76
+ ' continue',
77
+ ' overrides.append({"name": d.metadata["Name"], "key": k, "platform": p.version, "overlay": d.version})',
78
+ 'ov = {o["key"]: o for o in overrides}',
79
+ 'def parse(path):',
80
+ ' out = []',
81
+ ' try:',
82
+ ' f = open(path, encoding="utf-8", errors="replace")',
83
+ ' except Exception:',
84
+ ' return out',
85
+ ' for raw in f:',
86
+ ' line = raw.split(" #")[0].strip()',
87
+ ' if not line or line.startswith("#") or line.startswith("-"):',
88
+ ' continue',
89
+ ' if "://" in line and "@" not in line:',
90
+ ' continue',
91
+ ' try:',
92
+ ' r = Requirement(line)',
93
+ ' except Exception:',
94
+ ' continue',
95
+ ' if r.marker is not None and not r.marker.evaluate():',
96
+ ' continue',
97
+ ' out.append(r)',
98
+ ' return out',
99
+ 'def marker_ok(r, extras):',
100
+ ' if r.marker is None:',
101
+ ' return True',
102
+ ' for e in ("",) + extras:',
103
+ ' try:',
104
+ ' if r.marker.evaluate({"extra": e}):',
105
+ ' return True',
106
+ ' except Exception:',
107
+ ' pass',
108
+ ' return False',
109
+ 'def closure(reqs):',
110
+ ' specs = {}',
111
+ ' seen = set()',
112
+ ' queue = list(reqs)',
113
+ ' while queue:',
114
+ ' r = queue.pop(0)',
115
+ ' k = canon(r.name)',
116
+ ' specs.setdefault(k, []).append(str(r.specifier))',
117
+ ' extras = tuple(sorted(r.extras))',
118
+ ' if (k, extras) in seen:',
119
+ ' continue',
120
+ ' seen.add((k, extras))',
121
+ ' d = both.get(k)',
122
+ ' if d is None:',
123
+ ' continue',
124
+ ' for s in (d.requires or []):',
125
+ ' try:',
126
+ ' rr = Requirement(s)',
127
+ ' except Exception:',
128
+ ' continue',
129
+ ' if marker_ok(rr, extras):',
130
+ ' queue.append(rr)',
131
+ ' return specs',
132
+ 'def accepts(specs, v):',
133
+ ' for s in specs:',
134
+ ' if s and not SpecifierSet(s).contains(v, prereleases=True):',
135
+ ' return False',
136
+ ' return True',
137
+ 'out_nodes = []',
138
+ 'for n in nodes:',
139
+ ' specs = closure(parse(n["req"])) if ov else {}',
140
+ ' uses = {}',
141
+ ' for k, o in ov.items():',
142
+ ' if k in specs:',
143
+ ' s = [x for x in specs[k] if x]',
144
+ ' uses[k] = {"specs": s, "accepts_platform": accepts(s, o["platform"]), "accepts_overlay": accepts(s, o["overlay"])}',
145
+ ' out_nodes.append({"key": n["key"], "uses": uses})',
146
+ 'core = {}',
147
+ 'if core_req and ov:',
148
+ ' for r in parse(core_req):',
149
+ ' k = canon(r.name)',
150
+ ' if k in ov:',
151
+ ' core[k] = {"spec": str(r.specifier), "accepts_overlay": accepts([str(r.specifier)], ov[k]["overlay"])}',
152
+ 'print(json.dumps({"overrides": overrides, "nodes": out_nodes, "core": core}))',
153
+ ].join('\n');
154
+
155
+ /**
156
+ * Required custom nodes with a requirements.txt of ALL profiles on this
157
+ * ComfyUI, one entry per directory with every profile that uses it.
158
+ * @returns {Array<{ directory, reqPath, profiles: string[] }>}
159
+ */
160
+ function nodesOfProfiles(io, { root, manifests }) {
161
+ const byDir = new Map();
162
+ for (const m of manifests || []) {
163
+ const profile = (m && m.profile && m.profile.id) || null;
164
+ for (const dep of (m && m.dependencies) || []) {
165
+ if (dep.kind !== 'custom_node' || dep.requirement !== 'required') continue;
166
+ const dir = (dep.install && dep.install.directory) || dep.name;
167
+ const reqPath = path.join(root, 'custom_nodes', dir, 'requirements.txt');
168
+ if (!io.fs.existsSync(reqPath)) continue;
169
+ const e = byDir.get(dir) || { directory: dir, reqPath, profiles: [] };
170
+ if (profile && !e.profiles.includes(profile)) e.profiles.push(profile);
171
+ byDir.set(dir, e);
172
+ }
173
+ }
174
+ return Array.from(byDir.values());
175
+ }
176
+
177
+ /** Distinct profile ids of the manifests. */
178
+ function profileIds(manifests) {
179
+ return Array.from(new Set((manifests || []).map((m) => m && m.profile && m.profile.id).filter(Boolean)));
180
+ }
181
+
182
+ function majorOf(v) {
183
+ const m = /^\s*v?(\d+)/.exec(String(v || ''));
184
+ return m ? Number(m[1]) : null;
185
+ }
186
+
187
+ /** 'up' | 'down' | null — change of the MAJOR version platform → overlay. */
188
+ function majorChange(platform, overlay) {
189
+ const a = majorOf(platform);
190
+ const b = majorOf(overlay);
191
+ if (a === null || b === null || a === b) return null;
192
+ return b > a ? 'up' : 'down';
193
+ }
194
+
195
+ /**
196
+ * Run the comparison in the platform Python.
197
+ * @returns {{ ok: boolean, error?: string, overrides: object[], nodes: object[], core: object }}
198
+ */
199
+ function inspectOverlay(io, { python, sitePackages, root, nodes }) {
200
+ const coreReq = root ? path.join(root, 'requirements.txt') : '';
201
+ const arg = JSON.stringify((nodes || []).map((n) => ({ key: n.directory, req: n.reqPath })));
202
+ let r = null;
203
+ try {
204
+ r = io.exec(python, ['-I', '-c', OVERRIDES_SCRIPT, sitePackages, coreReq && io.fs.existsSync(coreReq) ? coreReq : '', arg], { timeout: 120000 });
205
+ } catch (err) { r = { code: 1, stderr: err.message }; }
206
+ const empty = { overrides: [], nodes: [], core: {} };
207
+ if (!r || r.code !== 0) return { ok: false, error: String((r && (r.stderr || r.error)) || 'overlay comparison failed').trim().slice(-300), ...empty };
208
+ let parsed = null;
209
+ try { parsed = JSON.parse(String(r.stdout || '').trim().split('\n').pop()); } catch (_) { parsed = null; }
210
+ if (!parsed || !Array.isArray(parsed.overrides)) return { ok: false, error: 'unexpected output of the overlay comparison', ...empty };
211
+ return { ok: true, overrides: parsed.overrides, nodes: Array.isArray(parsed.nodes) ? parsed.nodes : [], core: parsed.core || {} };
212
+ }
213
+
214
+ /**
215
+ * Attribute the replacements and find the conflicts.
216
+ * @param {object} raw inspectOverlay() result
217
+ * @param {Array} nodes nodesOfProfiles() result
218
+ * @param {{ profileCount: number }} opts
219
+ * @returns {{ overrides: object[], conflicts: object[] }}
220
+ */
221
+ function analyzeOverrides(raw, nodes, { profileCount = 1 } = {}) {
222
+ const usesOf = new Map((raw.nodes || []).map((n) => [n.key, n.uses || {}]));
223
+ const overrides = [];
224
+ const conflicts = [];
225
+ for (const o of raw.overrides || []) {
226
+ const users = nodes.filter((n) => (usesOf.get(n.directory) || {})[o.key]);
227
+ const causes = users.filter((n) => usesOf.get(n.directory)[o.key].accepts_platform === false);
228
+ const neededBy = causes.length > 0 ? causes : users;
229
+ const causeProfiles = new Set(neededBy.flatMap((n) => n.profiles));
230
+ const entry = {
231
+ package: o.name,
232
+ key: o.key,
233
+ platform: o.platform,
234
+ overlay: o.overlay,
235
+ major: majorChange(o.platform, o.overlay),
236
+ needed_by: neededBy.map((n) => n.directory),
237
+ profiles: Array.from(causeProfiles),
238
+ };
239
+ overrides.push(entry);
240
+ if (causes.length > 0) {
241
+ for (const n of users) {
242
+ if (causes.includes(n)) continue;
243
+ const u = usesOf.get(n.directory)[o.key];
244
+ for (const p of n.profiles) {
245
+ if (causeProfiles.has(p)) continue;
246
+ conflicts.push({
247
+ kind: 'profile', package: o.name, key: o.key, platform: o.platform, overlay: o.overlay,
248
+ needed_by: entry.needed_by, cause_profiles: entry.profiles,
249
+ profile: p, node: n.directory, specs: u.specs || [], accepts_overlay: u.accepts_overlay !== false,
250
+ });
251
+ }
252
+ }
253
+ }
254
+ const core = (raw.core || {})[o.key];
255
+ if (profileCount > 1 && core && core.accepts_overlay === false) {
256
+ conflicts.push({
257
+ kind: 'core', package: o.name, key: o.key, platform: o.platform, overlay: o.overlay,
258
+ needed_by: entry.needed_by, cause_profiles: entry.profiles,
259
+ profile: null, node: 'ComfyUI', specs: core.spec ? [core.spec] : [], accepts_overlay: false,
260
+ });
261
+ }
262
+ }
263
+ return { overrides, conflicts };
264
+ }
265
+
266
+ /** "transformers platform 5.0.0 → overlay 4.57.3 (needed by qwen3-tts)" */
267
+ function describeOverride(o) {
268
+ const by = o.needed_by && o.needed_by.length > 0 ? o.needed_by.join(', ') : 'no node of the installed profiles';
269
+ return `${o.package} platform ${o.platform} → overlay ${o.overlay} (needed by ${by})`;
270
+ }
271
+
272
+ /** The warning part for a major change, or ''. */
273
+ function majorNote(o) {
274
+ if (!o.major) return '';
275
+ return ` — major version ${o.major === 'up' ? 'UP' : 'DOWN'} (${majorOf(o.platform)} → ${majorOf(o.overlay)}): ComfyUI and every other custom node import this version`;
276
+ }
277
+
278
+ /** One line for a conflict. */
279
+ function describeConflict(c) {
280
+ const head = `${c.package} platform ${c.platform} → overlay ${c.overlay} (needed by ${c.needed_by.join(', ') || '?'}${c.cause_profiles.length ? `, profile ${c.cause_profiles.join(', ')}` : ''})`;
281
+ if (c.kind === 'core') {
282
+ return `${head} is outside the range of the ComfyUI core requirement ${c.package}${c.specs[0] || ''} (<ComfyUI>/requirements.txt)`;
283
+ }
284
+ const range = c.specs.length > 0 ? `requires ${c.specs.join(', ')}; the overlay version is ${c.accepts_overlay ? 'inside' : 'OUTSIDE'} that range` : 'any version';
285
+ return `${head} also changes it for profile ${c.profile} (node ${c.node}, ${range})`;
286
+ }
287
+
288
+ /** Key of an accepted conflict in install-state (package@overlay-version:profile). */
289
+ function conflictKey(c) {
290
+ return `${c.key || String(c.package).toLowerCase()}@${c.overlay}:${c.profile || 'comfyui-core'}`;
291
+ }
292
+
293
+ /** Conflicts that are not in the recorded consent list. */
294
+ function pendingConflicts(conflicts, accepted = []) {
295
+ const ok = new Set((accepted || []).map((a) => (typeof a === 'string' ? a : a && a.key)).filter(Boolean));
296
+ return (conflicts || []).filter((c) => !ok.has(conflictKey(c)));
297
+ }
298
+
299
+ /** Record entry for an accepted conflict. */
300
+ function acceptedEntry(c, at) {
301
+ return { key: conflictKey(c), package: c.package, overlay: c.overlay, profile: c.profile || 'comfyui-core', at };
302
+ }
303
+
304
+ /** The install-state record of a replacement (installer_options.nodeDeps.overrides[]). */
305
+ function recordOf(o) {
306
+ return { package: o.package, platform: o.platform, overlay: o.overlay, major: o.major, needed_by: o.needed_by, profiles: o.profiles };
307
+ }
308
+
309
+ /** RESULT items: [i] for a replacement, ! for a major change. */
310
+ function resultItems(overrides) {
311
+ return (overrides || []).map((o) => ({ ok: o.major ? 'warn' : 'info', label: `${describeOverride(o)}${majorNote(o)}` }));
312
+ }
313
+
314
+ // ---------------------------------------------------------------------------
315
+ // Snapshot of the overlay venv (rollback of a refused replacement)
316
+ // ---------------------------------------------------------------------------
317
+
318
+ function snapshotDir(venvDir) {
319
+ return `${venvDir}.pre-install`;
320
+ }
321
+
322
+ /**
323
+ * Copy the overlay venv aside (`cp -a`) before pip changes it. A stale
324
+ * snapshot of an interrupted run is replaced.
325
+ * @returns {{ ok: boolean, dir: string, reason: string|null }}
326
+ */
327
+ function snapshotOverlay(io, venvDir) {
328
+ const dir = snapshotDir(venvDir);
329
+ try { if (io.fs.existsSync(dir)) io.fs.rmSync(dir, { recursive: true, force: true }); } catch (err) {
330
+ return { ok: false, dir, reason: `cannot remove the stale snapshot ${dir}: ${err.message}` };
331
+ }
332
+ let r = null;
333
+ try { r = io.exec('cp', ['-a', venvDir, dir], { timeout: 30 * 60 * 1000 }); } catch (err) { r = { code: 1, stderr: err.message }; }
334
+ if (!r || r.code !== 0) return { ok: false, dir, reason: `cp -a ${venvDir} ${dir} failed: ${String((r && (r.stderr || r.error)) || '').trim().slice(-200)}` };
335
+ return { ok: true, dir, reason: null };
336
+ }
337
+
338
+ /** Put the snapshot back in place of the overlay venv. */
339
+ function restoreOverlay(io, venvDir) {
340
+ const dir = snapshotDir(venvDir);
341
+ if (!io.fs.existsSync(dir)) return { ok: false, reason: `no snapshot ${dir}` };
342
+ try {
343
+ io.fs.rmSync(venvDir, { recursive: true, force: true });
344
+ io.fs.renameSync(dir, venvDir);
345
+ } catch (err) {
346
+ return { ok: false, reason: `restoring ${venvDir} from ${dir} failed: ${err.message}` };
347
+ }
348
+ return { ok: true, reason: null };
349
+ }
350
+
351
+ /** Remove the snapshot (the change was kept). */
352
+ function dropSnapshot(io, venvDir) {
353
+ try { io.fs.rmSync(snapshotDir(venvDir), { recursive: true, force: true }); } catch (_) { /* best effort */ }
354
+ }
355
+
356
+ module.exports = {
357
+ OVERRIDES_SCRIPT,
358
+ nodesOfProfiles,
359
+ profileIds,
360
+ majorChange,
361
+ inspectOverlay,
362
+ analyzeOverrides,
363
+ describeOverride,
364
+ majorNote,
365
+ describeConflict,
366
+ conflictKey,
367
+ pendingConflicts,
368
+ acceptedEntry,
369
+ recordOf,
370
+ resultItems,
371
+ snapshotDir,
372
+ snapshotOverlay,
373
+ restoreOverlay,
374
+ dropSnapshot,
375
+ };
@@ -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,