@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,560 @@
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, argv[2..] = extra
34
+ * site dirs put IN FRONT of sys.path (the persistent overlay, installer
35
+ * 0.2.5 — exactly what the generated prestartup script does inside ComfyUI).
36
+ * Prints ONE JSON line:
37
+ * { torch: { name: version }, items: [{ line, name, status, have, want }] }
38
+ * status: ok | missing | mismatch | skipped (marker false) | unparsed.
39
+ */
40
+ const CHECK_SCRIPT = [
41
+ 'import json, sys',
42
+ 'try:',
43
+ ' from packaging.requirements import Requirement',
44
+ 'except Exception:',
45
+ ' from pip._vendor.packaging.requirements import Requirement',
46
+ 'try:',
47
+ ' from importlib import metadata as md',
48
+ 'except Exception:',
49
+ ' import importlib_metadata as md',
50
+ 'def ver(n):',
51
+ ' try:',
52
+ ' return md.version(n)',
53
+ ' except Exception:',
54
+ ' return None',
55
+ 'import site',
56
+ 'for _p in [p for p in sys.argv[2:] if p]:',
57
+ ' _before = list(sys.path)',
58
+ ' site.addsitedir(_p)',
59
+ ' _new = [x for x in sys.path if x not in _before]',
60
+ ' sys.path[:] = _new + [x for x in sys.path if x not in _new]',
61
+ 'items = []',
62
+ 'for raw in open(sys.argv[1], encoding="utf-8", errors="replace"):',
63
+ ' line = raw.split(" #")[0].strip()',
64
+ ' if not line or line.startswith("#"):',
65
+ ' continue',
66
+ ' if line.startswith("-") or "://" in line and "@" not in line:',
67
+ ' items.append({"line": line, "status": "unparsed"})',
68
+ ' continue',
69
+ ' try:',
70
+ ' r = Requirement(line)',
71
+ ' except Exception:',
72
+ ' items.append({"line": line, "status": "unparsed"})',
73
+ ' continue',
74
+ ' if r.marker is not None and not r.marker.evaluate():',
75
+ ' items.append({"line": line, "name": r.name, "status": "skipped"})',
76
+ ' continue',
77
+ ' have = ver(r.name)',
78
+ ' st = "missing" if have is None else ("ok" if not r.specifier or r.specifier.contains(have, prereleases=True) else "mismatch")',
79
+ ' items.append({"line": line, "name": r.name, "status": st, "have": have, "want": str(r.specifier) or None})',
80
+ 'torch = {n: ver(n) for n in ("torch", "torchvision", "torchaudio") if ver(n)}',
81
+ 'print(json.dumps({"torch": torch, "items": items}))',
82
+ ].join('\n');
83
+
84
+ function readProc(io, pid, name) {
85
+ try { return String(io.fs.readFileSync(`/proc/${pid}/${name}`, 'utf8')); } catch (_) { return null; }
86
+ }
87
+
88
+ function procEnv(io, pid) {
89
+ const raw = readProc(io, pid, 'environ');
90
+ const env = {};
91
+ if (!raw) return env;
92
+ for (const kv of raw.split('\0')) {
93
+ const i = kv.indexOf('=');
94
+ if (i > 0) env[kv.slice(0, i)] = kv.slice(i + 1);
95
+ }
96
+ return env;
97
+ }
98
+
99
+ /**
100
+ * The Python interpreter a running ComfyUI process uses, from /proc/<pid>.
101
+ * @returns {{ python: string|null, source: string }}
102
+ */
103
+ function pythonOfProcess(io, pid) {
104
+ const argv = String(readProc(io, pid, 'cmdline') || '').split('\0').filter(Boolean);
105
+ if (argv.length === 0) return { python: null, source: 'no /proc cmdline' };
106
+ const a0 = argv[0];
107
+ const env = procEnv(io, pid);
108
+ const cwd = (() => { try { return io.fs.readlinkSync(`/proc/${pid}/cwd`); } catch (_) { return null; } })();
109
+ if (path.isAbsolute(a0)) return { python: a0, source: 'argv[0]' };
110
+ if (/python/.test(path.basename(a0))) {
111
+ if (a0.includes('/') && cwd) return { python: path.resolve(cwd, a0), source: 'argv[0] (relative to cwd)' };
112
+ if (env.VIRTUAL_ENV) {
113
+ const cand = path.join(env.VIRTUAL_ENV, 'bin', a0);
114
+ if (io.fs.existsSync(cand)) return { python: cand, source: 'VIRTUAL_ENV of the process' };
115
+ }
116
+ for (const dir of String(env.PATH || '').split(':').filter(Boolean)) {
117
+ const cand = path.join(dir, a0);
118
+ if (io.fs.existsSync(cand)) return { python: cand, source: 'PATH of the process' };
119
+ }
120
+ }
121
+ try {
122
+ const exe = io.fs.readlinkSync(`/proc/${pid}/exe`);
123
+ if (exe) return { python: exe, source: '/proc/<pid>/exe' };
124
+ } catch (_) { /* not readable */ }
125
+ return { python: null, source: `cannot resolve ${a0}` };
126
+ }
127
+
128
+ /** Required custom nodes of the profiles that are on disk with a requirements.txt. */
129
+ function profileNodeRequirements(io, { root, manifests }) {
130
+ const out = [];
131
+ const seen = new Set();
132
+ for (const m of manifests || []) {
133
+ for (const dep of m.dependencies || []) {
134
+ if (dep.kind !== 'custom_node' || dep.requirement !== 'required' || seen.has(dep.id)) continue;
135
+ seen.add(dep.id);
136
+ const dir = (dep.install && dep.install.directory) || dep.name;
137
+ const reqPath = path.join(root, 'custom_nodes', dir, 'requirements.txt');
138
+ if (!io.fs.existsSync(reqPath)) continue;
139
+ out.push({ id: dep.id, directory: dir, reqPath, classes: dep.provides_classes || [] });
140
+ }
141
+ }
142
+ return out;
143
+ }
144
+
145
+ /** Run the check script for one requirements.txt in `python`. */
146
+ function checkRequirementsFile(io, { python, reqPath, extraPaths = [] }) {
147
+ let r = null;
148
+ try { r = io.exec(python, ['-I', '-c', CHECK_SCRIPT, reqPath, ...(extraPaths || []).filter(Boolean)], { timeout: 120000 }); } catch (err) { r = { code: 1, stderr: err.message }; }
149
+ if (!r || r.code !== 0) return { ok: false, error: String((r && (r.stderr || r.error)) || 'check failed').slice(-300), unsatisfied: [], torch: {} };
150
+ let parsed = null;
151
+ try { parsed = JSON.parse(String(r.stdout || '').trim().split('\n').pop()); } catch (_) { parsed = null; }
152
+ if (!parsed || !Array.isArray(parsed.items)) return { ok: false, error: 'unexpected check output', unsatisfied: [], torch: {} };
153
+ const unsatisfied = parsed.items.filter((i) => i.status === 'missing' || i.status === 'mismatch');
154
+ return { ok: true, unsatisfied, torch: parsed.torch || {}, items: parsed.items };
155
+ }
156
+
157
+ /**
158
+ * Which profile nodes have unsatisfied pip requirements in `python`.
159
+ * @returns {{ python, nodes: Array<{ id, directory, reqPath, classes, unsatisfied: object[] }>, torch: object, errors: string[] }}
160
+ */
161
+ function checkNodeDeps(io, { python, root, manifests, extraPaths = [] }) {
162
+ const nodes = [];
163
+ const errors = [];
164
+ let torch = {};
165
+ for (const n of profileNodeRequirements(io, { root, manifests })) {
166
+ const c = checkRequirementsFile(io, { python, reqPath: n.reqPath, extraPaths });
167
+ if (!c.ok) { errors.push(`${n.directory}: ${c.error}`); continue; }
168
+ torch = { ...torch, ...c.torch };
169
+ if (c.unsatisfied.length > 0) nodes.push({ ...n, unsatisfied: c.unsatisfied });
170
+ }
171
+ return { python, nodes, torch, errors };
172
+ }
173
+
174
+ /** "qwen3-tts (transformers missing, librosa>=0.10 has 0.9)" */
175
+ function describeUnsatisfied(nodes) {
176
+ return nodes.map((n) => `${n.directory} (${n.unsatisfied.map((u) => (u.status === 'missing'
177
+ ? `${u.name} missing`
178
+ : `${u.name}${u.want || ''} has ${u.have}`)).join(', ')})`).join('; ');
179
+ }
180
+
181
+ /**
182
+ * pip install -r for every node in `nodes` into `python`, with the installed
183
+ * torch family pinned. A permission error on a system interpreter retries
184
+ * with --user. With `pipPython` (the persistent overlay venv, installer
185
+ * 0.2.5) pip runs in the overlay: only what the platform Python lacks is
186
+ * written, under the installation in /home — no --user retry (as root the
187
+ * user site is /root/.local, outside /home, and is lost with a restart too).
188
+ * @returns {{ ok: boolean, installed: string[], failed: Array<{ directory, reason }>, target: string }}
189
+ */
190
+ function installNodeDeps(io, { python, nodes, torch = {}, constraintsPath = null, log = null, pipPython = null }) {
191
+ let constraint = null;
192
+ const pins = Object.entries(torch || {}).map(([n, v]) => `${n}==${v}`);
193
+ if (pins.length > 0 && constraintsPath) {
194
+ try {
195
+ io.fs.mkdirSync(path.dirname(constraintsPath), { recursive: true });
196
+ io.fs.writeFileSync(constraintsPath, `${pins.join('\n')}\n`);
197
+ constraint = constraintsPath;
198
+ } catch (_) { constraint = null; }
199
+ }
200
+ const installed = [];
201
+ const failed = [];
202
+ const pip = pipPython || python;
203
+ for (const n of nodes) {
204
+ const args = ['-m', 'pip', 'install', '-r', n.reqPath];
205
+ if (constraint) args.push('-c', constraint);
206
+ if (log) log.info(`installing the Python dependencies of ${n.directory} into ${pipPython ? `the persistent overlay ${path.dirname(path.dirname(pipPython))} (for ${python})` : python}`);
207
+ let r = io.exec(pip, args, { timeout: 60 * 60 * 1000 });
208
+ if (!pipPython && r.code !== 0 && /permission denied|not writeable|EnvironmentError: \[Errno 13\]/i.test(String(r.stderr || ''))) {
209
+ r = io.exec(python, [...args, '--user'], { timeout: 60 * 60 * 1000 });
210
+ }
211
+ if (r.code === 0) installed.push(n.directory);
212
+ else failed.push({ directory: n.directory, reason: `pip install -r ${n.reqPath} failed: ${String(r.stderr || r.error || '').slice(-300)}` });
213
+ }
214
+ return { ok: failed.length === 0, installed, failed, target: pipPython ? 'overlay' : 'system' };
215
+ }
216
+
217
+ function pidAlive(io, pid) {
218
+ if (typeof io.pidAlive === 'function') return io.pidAlive(pid);
219
+ if (!io.fs.existsSync(`/proc/${pid}`)) return false;
220
+ // A zombie (exited, not yet reaped by the platform's supervisor) is gone.
221
+ const stat = readProc(io, pid, 'stat');
222
+ const m = stat ? /\)\s+([A-Za-z])\s/.exec(stat) : null;
223
+ return !(m && (m[1] === 'Z' || m[1] === 'X'));
224
+ }
225
+
226
+ /**
227
+ * Everything needed to start the SAME ComfyUI again, read from /proc/<pid>
228
+ * BEFORE anything is stopped: argv (incl. --port/--listen/--baseurl), cwd,
229
+ * the full environment, the interpreter. A process whose environment cannot
230
+ * be read (another user, hardened /proc) is never stopped — it could not be
231
+ * started again faithfully.
232
+ * @returns {{ ok: boolean, reason: string|null, argv: string[], cwd: string|null, env: object|null, python: string|null, port: number, listen: string|null, baseurl: string|null, url: string|null }}
233
+ */
234
+ function snapshotProcess(io, pid) {
235
+ const argv = String(readProc(io, pid, 'cmdline') || '').split('\0').filter(Boolean);
236
+ const out = { ok: false, reason: null, argv, cwd: null, env: null, python: null, port: 8188, listen: null, baseurl: null, url: null };
237
+ if (!argv.some((a) => /(^|\/)main\.py$/.test(a))) {
238
+ out.reason = `pid ${pid} is no longer a ComfyUI main.py — nothing was stopped`;
239
+ return out;
240
+ }
241
+ try { out.cwd = io.fs.readlinkSync(`/proc/${pid}/cwd`); } catch (_) { out.cwd = null; }
242
+ if (!out.cwd) {
243
+ out.reason = `the working directory of the ComfyUI process (pid ${pid}) is not readable — it is not stopped, because it could not be started again the same way`;
244
+ return out;
245
+ }
246
+ const raw = readProc(io, pid, 'environ');
247
+ if (raw === null) {
248
+ out.reason = `the environment of the ComfyUI process (pid ${pid}) is not readable (another user?) — it is not stopped, because it could not be started again the same way`;
249
+ return out;
250
+ }
251
+ out.env = procEnv(io, pid);
252
+ const flag = (name) => {
253
+ const i = argv.indexOf(name);
254
+ if (i !== -1 && argv[i + 1]) return argv[i + 1];
255
+ const eq = argv.find((a) => a.startsWith(`${name}=`));
256
+ return eq ? eq.slice(name.length + 1) : null;
257
+ };
258
+ out.port = flag('--port') ? Number(flag('--port')) : 8188;
259
+ out.listen = flag('--listen');
260
+ out.baseurl = flag('--baseurl');
261
+ out.url = comfyOwner.comfyUrlFor({ port: out.port, baseurl: out.baseurl, listen: out.listen }).url;
262
+ const py = pythonOfProcess(io, pid);
263
+ out.python = py.python;
264
+ out.ok = true;
265
+ return out;
266
+ }
267
+
268
+ /** argv to start the snapshot again: an interpreter given by name is resolved like the original (pythonOfProcess). */
269
+ function relaunchArgv(snap) {
270
+ const argv = snap.argv.slice();
271
+ if (!path.isAbsolute(argv[0]) && /python/.test(path.basename(argv[0])) && snap.python) argv[0] = snap.python;
272
+ return argv;
273
+ }
274
+
275
+ /** Last lines of a log file (diagnostics), or ''. */
276
+ function tailFile(io, file, maxBytes = 4000) {
277
+ try {
278
+ const s = String(io.fs.readFileSync(file, 'utf8'));
279
+ return s.slice(-maxBytes);
280
+ } catch (_) { return ''; }
281
+ }
282
+
283
+ /**
284
+ * Restart a ComfyUI the installer did NOT start (the platform's — type A,
285
+ * installer 0.2.5). Live E2E 02.11: the platform (TIR) does NOT bring its
286
+ * ComfyUI back after it stops, so "SIGTERM and wait for the platform"
287
+ * (0.2.4) left the node without ComfyUI.
288
+ *
289
+ * 1. snapshot /proc/<pid>: argv, cwd, environment (nothing is stopped
290
+ * when any of it is unreadable);
291
+ * 2. SIGTERM exactly that pid (SIGKILL after stopTimeoutMs); a signal the
292
+ * kernel refuses (EPERM) stops here — nothing changed;
293
+ * 3. platform grace window (platformGraceMs): a NEW main.py appearing on its
294
+ * own means the platform supervises ComfyUI — it is used, the installer
295
+ * starts nothing;
296
+ * 4. otherwise the installer starts the same command line in the same cwd
297
+ * with the same environment, detached (own session), output appended to
298
+ * `logFile`;
299
+ * 5. wait for GET <url>/system_stats (url from --listen/--port/--baseurl of
300
+ * the original command line), then for every class of expectClasses in
301
+ * /object_info. A started process that exits is reported with the tail
302
+ * of its log at once.
303
+ * @returns {Promise<{ ok: boolean, stopped: boolean, started_by: 'platform'|'installer'|null, old_pid, pid: number|null, url: string|null, waited_ms: number, missing_classes: string[], reason: string|null, log_file: string|null }>}
304
+ */
305
+ async function restartForeignComfyUI(io, {
306
+ pid, timeoutMs = 600000, intervalMs = 3000, stopTimeoutMs = 15000, platformGraceMs = 30000, expectClasses = [],
307
+ logFile = null, sleep = null, log = null, onProgress = null, progressMs = 30000,
308
+ } = {}) {
309
+ const now = () => (typeof io.now === 'function' ? io.now() : Date.now());
310
+ const pause = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
311
+ const started = now();
312
+ const base = { stopped: false, started_by: null, old_pid: pid, pid: null, url: null, waited_ms: 0, missing_classes: [], log_file: null };
313
+ const snap = snapshotProcess(io, pid);
314
+ if (!snap.ok) return { ...base, ok: false, reason: snap.reason };
315
+ base.url = snap.url;
316
+ let killError = null;
317
+ const kill = (p, sig) => {
318
+ try {
319
+ if (typeof io.kill === 'function') io.kill(p, sig); else process.kill(p, sig);
320
+ } catch (err) {
321
+ if (err && err.code !== 'ESRCH') killError = err;
322
+ }
323
+ };
324
+ if (log) log.info(`stopping the platform's ComfyUI (pid ${pid}) to start it again with the node dependencies: ${snap.argv.join(' ')} (cwd ${snap.cwd})`);
325
+ kill(pid, 'SIGTERM');
326
+ if (killError) {
327
+ return { ...base, ok: false, reason: `cannot stop the ComfyUI process (pid ${pid}): ${killError.code || killError.message} — run the installer as the user that owns it, or restart ComfyUI from the platform console` };
328
+ }
329
+ base.stopped = true;
330
+ const stopDeadline = now() + stopTimeoutMs;
331
+ while (pidAlive(io, pid) && now() < stopDeadline) await pause(Math.min(500, intervalMs));
332
+ if (pidAlive(io, pid)) kill(pid, 'SIGKILL');
333
+ const otherProcs = () => probe.listRunningComfyUI(io).filter((p) => p.pid !== pid);
334
+
335
+ // 3. Does the platform supervise its ComfyUI? Give it the grace window.
336
+ let next = null;
337
+ const graceEnd = now() + platformGraceMs;
338
+ for (;;) {
339
+ next = otherProcs()[0] || null;
340
+ if (next || now() >= graceEnd) break;
341
+ await pause(Math.min(intervalMs, Math.max(1, graceEnd - now())));
342
+ }
343
+ let ownPid = null;
344
+ if (next) {
345
+ base.started_by = 'platform';
346
+ if (log) log.info(`the platform started ComfyUI again by itself (pid ${next.pid}) — the installer starts nothing`);
347
+ } else {
348
+ // 4. Nobody brought it back: start the same command line ourselves.
349
+ const argv = relaunchArgv(snap);
350
+ if (logFile) {
351
+ try { io.fs.mkdirSync(path.dirname(logFile), { recursive: true }); } catch (_) { /* spawn reports it */ }
352
+ }
353
+ try {
354
+ ownPid = io.spawnDaemon(argv[0], argv.slice(1), { cwd: snap.cwd, env: snap.env, logFile });
355
+ } catch (err) {
356
+ return { ...base, ok: false, waited_ms: now() - started, reason: `the platform did not start ComfyUI again and starting it failed: ${err.message} — start it from the platform console` };
357
+ }
358
+ base.started_by = 'installer';
359
+ base.log_file = logFile;
360
+ if (log) log.info(`the platform did not start ComfyUI again within ${Math.round(platformGraceMs / 1000)} s — started the same command line (pid ${ownPid}, cwd ${snap.cwd}${logFile ? `, log ${logFile}` : ''})`);
361
+ }
362
+
363
+ // 5. Wait for the API at the ORIGINAL address (prefix from --baseurl), then the classes.
364
+ let nextProgress = now() + progressMs;
365
+ let last = null;
366
+ for (;;) {
367
+ const waited = now() - started;
368
+ if (ownPid != null && !pidAlive(io, ownPid)) {
369
+ const tail = logFile ? tailFile(io, logFile, 1500).trim().split('\n').slice(-6).join(' | ') : '';
370
+ return { ...base, ok: false, pid: ownPid, waited_ms: waited, reason: `the restarted ComfyUI (pid ${ownPid}) exited${tail ? `: ${tail}` : ''}${logFile ? ` (log ${logFile})` : ''}` };
371
+ }
372
+ const candidates = ownPid != null
373
+ ? [{ pid: ownPid, url: snap.url }]
374
+ : otherProcs().map((p) => ({ pid: p.pid, url: comfyOwner.comfyUrlFor(p).url }));
375
+ for (const c of candidates) {
376
+ if (!(await comfyOwner.verifyComfyUrl(io, c.url))) { last = { pid: c.pid, url: c.url, why: 'does not answer GET /system_stats yet' }; continue; }
377
+ const classes = expectClasses.length > 0 ? await comfyui.objectInfoClasses(io, c.url) : new Set();
378
+ const missing = expectClasses.filter((x) => !classes || !classes.has(x));
379
+ if (missing.length === 0) return { ...base, ok: true, pid: c.pid, url: c.url, waited_ms: waited, reason: null };
380
+ last = { pid: c.pid, url: c.url, why: `answers, node classes missing: ${missing.join(', ')}`, missing };
381
+ }
382
+ if (waited >= timeoutMs) {
383
+ const secs = Math.round(timeoutMs / 1000);
384
+ const who = base.started_by === 'installer' ? 'the installer started ComfyUI again' : 'the platform started ComfyUI again';
385
+ const reason = last
386
+ ? `${who} (pid ${last.pid} at ${last.url}) but it ${last.why} after ${secs} s`
387
+ : `the platform did not start ComfyUI again within ${secs} s after it was stopped (old pid ${pid}) — start it from the platform console`;
388
+ return { ...base, ok: false, pid: last ? last.pid : ownPid, url: last ? last.url : base.url, waited_ms: waited, missing_classes: (last && last.missing) || [], reason };
389
+ }
390
+ if (onProgress && now() >= nextProgress) {
391
+ onProgress(`waiting for ComfyUI (${base.started_by === 'installer' ? `pid ${ownPid}, started by the installer` : 'started by the platform'}) — ${last ? `pid ${last.pid} ${last.why}` : 'no answer yet'} (${Math.round(waited / 1000)} s of ${Math.round(timeoutMs / 1000)} s)`);
392
+ nextProgress += progressMs;
393
+ }
394
+ await pause(Math.min(intervalMs, Math.max(1, timeoutMs - waited)));
395
+ }
396
+ }
397
+
398
+ /** 0.2.4 name, kept for callers: the platform ComfyUI restart is now restartForeignComfyUI. */
399
+ const restartPlatformComfyUI = restartForeignComfyUI;
400
+
401
+ // ---------------------------------------------------------------------------
402
+ // Why are node classes missing? (installer 0.2.5)
403
+ // ---------------------------------------------------------------------------
404
+
405
+ /**
406
+ * Custom-node import failures in a ComfyUI startup log:
407
+ * "Cannot import /x/custom_nodes/qwen3-tts module for custom nodes: No module named 'qwen_tts'"
408
+ * " 0.0 seconds (IMPORT FAILED): /x/custom_nodes/qwen3-tts"
409
+ * Only the LAST startup in the text counts (an appended log holds several).
410
+ * @returns {Array<{ dir: string, name: string, error: string|null }>}
411
+ */
412
+ function parseImportFailures(text) {
413
+ let s = String(text || '');
414
+ const marks = ['** ComfyUI startup time', 'Prestartup times for custom nodes'];
415
+ let cut = -1;
416
+ for (const m of marks) cut = Math.max(cut, s.lastIndexOf(m));
417
+ if (cut > 0) {
418
+ // keep from the start of that line
419
+ const lineStart = s.lastIndexOf('\n', cut);
420
+ s = s.slice(lineStart + 1);
421
+ }
422
+ const out = new Map();
423
+ for (const m of s.matchAll(/Cannot import (\S+) module for custom nodes: ([^\n]*)/g)) {
424
+ const dir = m[1].replace(/[\\/]+$/, '');
425
+ out.set(dir, { dir, name: path.basename(dir), error: m[2].trim() || null });
426
+ }
427
+ for (const m of s.matchAll(/\(IMPORT FAILED\):\s*(\S+)/g)) {
428
+ const dir = m[1].replace(/[\\/]+$/, '');
429
+ if (!out.has(dir)) out.set(dir, { dir, name: path.basename(dir), error: null });
430
+ }
431
+ return Array.from(out.values());
432
+ }
433
+
434
+ /**
435
+ * The startup log of a running ComfyUI, best source first:
436
+ * 1. GET <url>/internal/logs/raw | /internal/logs (ComfyUI's in-memory log);
437
+ * 2. the file behind /proc/<pid>/fd/1 or fd/2 (stdout redirected to a file);
438
+ * 3. `files` (the installer's restart log, <root>/comfyui-installer.log, …).
439
+ * @returns {Promise<{ text: string, source: string|null }>}
440
+ */
441
+ async function readComfyLog(io, { url = null, pid = null, files = [], maxBytes = 1024 * 1024 } = {}) {
442
+ if (url && io.http && typeof io.http.fetchJson === 'function') {
443
+ for (const ep of ['/internal/logs/raw', '/internal/logs']) {
444
+ try {
445
+ const r = await io.http.fetchJson(`${url}${ep}`);
446
+ if (r && r.status === 200 && r.json != null) {
447
+ const j = r.json;
448
+ let text = null;
449
+ if (typeof j === 'string') text = j;
450
+ else if (j && Array.isArray(j.entries)) text = j.entries.map((e) => String((e && e.m) || '')).join('');
451
+ if (text) return { text: text.slice(-maxBytes), source: `${url}${ep}` };
452
+ }
453
+ } catch (_) { /* older ComfyUI */ }
454
+ }
455
+ }
456
+ const candidates = [];
457
+ if (pid) {
458
+ for (const fd of [1, 2]) {
459
+ try {
460
+ const target = io.fs.readlinkSync(`/proc/${pid}/fd/${fd}`);
461
+ if (target && target.startsWith('/') && !target.startsWith('/dev/')) candidates.push(target);
462
+ } catch (_) { /* not readable */ }
463
+ }
464
+ }
465
+ for (const f of files || []) if (f) candidates.push(f);
466
+ for (const f of Array.from(new Set(candidates))) {
467
+ try {
468
+ if (!io.fs.existsSync(f)) continue;
469
+ const text = String(io.fs.readFileSync(f, 'utf8'));
470
+ if (text) return { text: text.slice(-maxBytes), source: f };
471
+ } catch (_) { /* unreadable */ }
472
+ }
473
+ return { text: '', source: null };
474
+ }
475
+
476
+ const IMPORT_ERROR_RE = /No module named|ModuleNotFoundError|ImportError|cannot import name/i;
477
+
478
+ /**
479
+ * The CAUSE of "ComfyUI node classes missing" — never just "run doctor"
480
+ * (live E2E 02.11: doctor printed "node classes missing" with the fix
481
+ * `animastor doctor`, which changed nothing → endless loop).
482
+ *
483
+ * Per required custom node that provides a missing class:
484
+ * deps-missing — its requirements are not satisfied in the ComfyUI Python
485
+ * (persistent overlay included);
486
+ * import-failed — the ComfyUI log has IMPORT FAILED for it with an error
487
+ * that is not a missing module;
488
+ * restart-needed — the packages are in place, but the running process
489
+ * failed to import the node at startup (missing module) or
490
+ * has no record of it: it predates the dependencies.
491
+ * @returns {Promise<{ kind: 'deps-missing'|'import-failed'|'restart-needed'|'unknown', detail: string, nodes: object[], log_source: string|null, python: string|null }>}
492
+ */
493
+ async function diagnoseMissingClasses(io, {
494
+ missingClasses = [], manifests = [], root, url = null, pid = null, python = null, extraPaths = [], logFiles = [],
495
+ } = {}) {
496
+ const missing = new Set(missingClasses);
497
+ const reqs = profileNodeRequirements(io, { root, manifests });
498
+ const affected = [];
499
+ for (const m of manifests || []) {
500
+ for (const dep of m.dependencies || []) {
501
+ if (dep.kind !== 'custom_node') continue;
502
+ const cls = (dep.provides_classes || []).filter((c) => missing.has(c));
503
+ if (cls.length === 0) continue;
504
+ const dir = (dep.install && dep.install.directory) || dep.name;
505
+ if (affected.some((a) => a.directory === dir)) continue;
506
+ affected.push({ id: dep.id, directory: dir, classes: cls, req: reqs.find((r) => r.directory === dir) || null });
507
+ }
508
+ }
509
+ let py = python;
510
+ if (!py && pid) py = pythonOfProcess(io, pid).python;
511
+ const logRes = await readComfyLog(io, { url, pid, files: logFiles });
512
+ const failures = parseImportFailures(logRes.text);
513
+ const nodes = [];
514
+ for (const a of affected) {
515
+ const n = { directory: a.directory, classes: a.classes, kind: 'unknown', detail: '' };
516
+ let unsatisfied = [];
517
+ let checked = false;
518
+ if (py && a.req) {
519
+ const c = checkRequirementsFile(io, { python: py, reqPath: a.req.reqPath, extraPaths });
520
+ if (c.ok) { checked = true; unsatisfied = c.unsatisfied; }
521
+ }
522
+ const fail = failures.find((f) => f.name === a.directory || f.dir.endsWith(`/custom_nodes/${a.directory}`));
523
+ if (unsatisfied.length > 0) {
524
+ n.kind = 'deps-missing';
525
+ n.detail = `${a.directory}: Python packages missing in ${py}: ${describeUnsatisfied([{ directory: a.directory, unsatisfied }]).replace(/^[^(]*\(|\)$/g, '')}`;
526
+ } else if (fail && fail.error && !IMPORT_ERROR_RE.test(fail.error)) {
527
+ n.kind = 'import-failed';
528
+ n.detail = `${a.directory}: IMPORT FAILED — ${fail.error} (${logRes.source})`;
529
+ } else if (fail) {
530
+ n.kind = 'restart-needed';
531
+ n.detail = `${a.directory}: the running ComfyUI${pid ? ` (pid ${pid})` : ''} failed to import it at startup${fail.error ? ` (${fail.error})` : ''}${checked ? '; the packages are installed now' : ''} — ComfyUI must be restarted`;
532
+ } else if (checked) {
533
+ n.kind = 'restart-needed';
534
+ n.detail = `${a.directory}: the packages are installed, but the running ComfyUI${pid ? ` (pid ${pid})` : ''} has not loaded the node${logRes.source ? '' : ' (no ComfyUI log available)'} — it was started before the node or its dependencies were in place; ComfyUI must be restarted`;
535
+ } else {
536
+ n.detail = `${a.directory}: not registered by ComfyUI${logRes.source ? '' : ' (no ComfyUI log available)'}`;
537
+ }
538
+ nodes.push(n);
539
+ }
540
+ const order = ['deps-missing', 'import-failed', 'restart-needed', 'unknown'];
541
+ const kind = nodes.length > 0 ? order.find((k) => nodes.some((n) => n.kind === k)) : 'unknown';
542
+ const detail = nodes.length > 0 ? nodes.map((n) => n.detail).join('; ') : 'no profile custom node provides them';
543
+ return { kind, detail, nodes, log_source: logRes.source, python: py || null };
544
+ }
545
+
546
+ module.exports = {
547
+ CHECK_SCRIPT,
548
+ pythonOfProcess,
549
+ profileNodeRequirements,
550
+ checkRequirementsFile,
551
+ checkNodeDeps,
552
+ describeUnsatisfied,
553
+ installNodeDeps,
554
+ snapshotProcess,
555
+ restartForeignComfyUI,
556
+ restartPlatformComfyUI,
557
+ parseImportFailures,
558
+ readComfyLog,
559
+ diagnoseMissingClasses,
560
+ };