@animastor/installer 0.1.0

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.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +66 -0
  3. package/ai/install-manifests/audio/qwen-tts.json +445 -0
  4. package/ai/install-manifests/image/qwen-image.json +465 -0
  5. package/ai/install-manifests/video/ltx-2.3.json +892 -0
  6. package/package.json +42 -0
  7. package/src/installer/cli.js +1067 -0
  8. package/src/installer/compatibility-resolver.js +1287 -0
  9. package/src/installer/download-planner.js +172 -0
  10. package/src/installer/engine/comfyui.js +508 -0
  11. package/src/installer/engine/downloader.js +514 -0
  12. package/src/installer/engine/engine.js +1180 -0
  13. package/src/installer/engine/io.js +437 -0
  14. package/src/installer/engine/logger.js +75 -0
  15. package/src/installer/engine/nodes.js +146 -0
  16. package/src/installer/engine/prereq.js +399 -0
  17. package/src/installer/engine/probe.js +349 -0
  18. package/src/installer/engine/progress.js +350 -0
  19. package/src/installer/engine/state.js +170 -0
  20. package/src/installer/engine/term.js +298 -0
  21. package/src/installer/engine/worker.js +430 -0
  22. package/src/installer/engine/workflows.js +153 -0
  23. package/src/installer/index.js +40 -0
  24. package/src/installer/install-manifest.js +376 -0
  25. package/src/installer/install-plan.js +741 -0
  26. package/src/installer/management.js +489 -0
  27. package/src/installer/platform/deployment/docker.js +78 -0
  28. package/src/installer/platform/deployment/native.js +36 -0
  29. package/src/installer/platform/index.js +165 -0
  30. package/src/installer/platform/linux.js +341 -0
  31. package/src/installer/platform/windows.js +360 -0
  32. package/src/installer/safety-rules.js +156 -0
  33. package/src/installer/setup-contract.js +1401 -0
  34. package/src/installer/uninstaller.js +572 -0
  35. package/src/installer/verification-report.js +220 -0
  36. package/src/installer/worker-bundle-source.js +64 -0
  37. package/src/installer/workflow-artifacts.js +152 -0
@@ -0,0 +1,172 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Download Planner — Private Worker Installer Phase 3.2.
5
+ *
6
+ * Pure planning layer for model downloads. Given a manifest dependency
7
+ * (kind=model | model_repo), it produces a declarative download spec the
8
+ * future installer engine will execute. NO network access and NO invented
9
+ * URLs: if the manifest source is not researched yet (repository=null),
10
+ * the spec is marked `ready: false` with explicit blockers — the installer
11
+ * must refuse to guess.
12
+ *
13
+ * Supported source kinds (architecturally):
14
+ * - huggingface — single file from an HF repo (resolve endpoint, HTTP
15
+ * range resume);
16
+ * - modelscope — repo-style download (ModelScope snapshot); the
17
+ * installer preloads the repo (D2 closed: deterministic/offline).
18
+ *
19
+ * Auth logic:
20
+ * - public HF model → download without token;
21
+ * - gated/private HF model → use system HF_TOKEN;
22
+ * - system token unavailable → clear BLOCKED error (user is NOT asked to
23
+ * create their own HF account).
24
+ *
25
+ * Idempotency/resume contract for the engine:
26
+ * - download into `<target>.part`, rename on completion;
27
+ * - resume via HTTP Range when the source supports it;
28
+ * - skip entirely when the final file already verifies (checksum > size);
29
+ * - checksum mismatch ⇒ fail the step, never continue with a corrupt model.
30
+ */
31
+
32
+ const SUPPORTED_SOURCE_KINDS = Object.freeze(['huggingface', 'modelscope']);
33
+
34
+ function normPath(p) {
35
+ return String(p || '').replace(/\\/g, '/').replace(/^\/+/, '').replace(/\/+$/, '');
36
+ }
37
+
38
+ /**
39
+ * Build a download spec for one model/model_repo dependency.
40
+ *
41
+ * @param {object} dep manifest dependency entry
42
+ * @param {object} [opts] planner options
43
+ * @param {boolean} [opts.hasHfToken] whether the system HF token is available
44
+ * @returns {{
45
+ * id, kind, ready, url, target_path, part_path, resume, idempotent_skip,
46
+ * checksum, size_bytes_approx, requires_auth, blockers, notes
47
+ * }}
48
+ */
49
+ function planModelDownload(dep, opts = {}) {
50
+ const src = dep.source || {};
51
+ const blockers = [];
52
+ const notes = [];
53
+ const hasHfToken = opts.hasHfToken || false;
54
+
55
+ const targetPath = dep.kind === 'model_repo'
56
+ ? normPath(dep.target_dir)
57
+ : `${normPath(dep.target_dir)}/${dep.filename}`;
58
+
59
+ const spec = {
60
+ id: dep.id,
61
+ kind: src.kind || 'unknown',
62
+ ready: false,
63
+ url: null,
64
+ target_path: targetPath,
65
+ part_path: dep.kind === 'model_repo' ? null : `${targetPath}.part`,
66
+ resume: null,
67
+ idempotent_skip: true,
68
+ checksum: dep.checksum || null,
69
+ size_bytes_approx: dep.size_bytes_approx || null,
70
+ requires_auth: !!src.gated,
71
+ blockers,
72
+ notes,
73
+ };
74
+
75
+ if (!SUPPORTED_SOURCE_KINDS.includes(src.kind)) {
76
+ blockers.push(`source kind "${src.kind || 'unknown'}" is not supported yet (supported: ${SUPPORTED_SOURCE_KINDS.join(', ')})`);
77
+ return spec;
78
+ }
79
+
80
+ if (src.verification === 'unknown' || !src.repository) {
81
+ blockers.push('download source is not researched yet: repository/revision/sha256 must be confirmed by a human before the installer may download — URLs are never invented');
82
+ if (src.todo) notes.push(src.todo);
83
+ return spec;
84
+ }
85
+
86
+ if (src.kind === 'huggingface') {
87
+ if (!src.file_path && dep.kind === 'model') {
88
+ blockers.push('huggingface source needs file_path within the repository');
89
+ return spec;
90
+ }
91
+ const revision = src.revision || 'main';
92
+ spec.url = `https://huggingface.co/${src.repository}/resolve/${revision}/${src.file_path || dep.filename}`;
93
+ spec.resume = 'http-range';
94
+
95
+ if (src.gated) {
96
+ spec.requires_auth = true;
97
+ if (!hasHfToken) {
98
+ blockers.push('Required Hugging Face access is unavailable: set HF_TOKEN or HUGGINGFACE_HUB_TOKEN environment variable (gated model)');
99
+ return spec;
100
+ }
101
+ notes.push('gated repository — system HF token will be used for authentication');
102
+ }
103
+
104
+ spec.ready = true;
105
+ return spec;
106
+ }
107
+
108
+ // modelscope
109
+ if (dep.delivery && dep.delivery.mechanism === 'installer_preload') {
110
+ spec.resume = 'snapshot-restart';
111
+ const repoPath = normPath(src.repository);
112
+ spec.url = `https://modelscope.cn/models/${repoPath}`;
113
+ spec.repository = src.repository;
114
+ spec.revision = src.revision || 'master';
115
+ spec.ready = true;
116
+ notes.push('ModelScope repo pre-downloaded by installer (D2 closed: deterministic/offline)');
117
+ return spec;
118
+ }
119
+
120
+ if (dep.delivery && dep.delivery.mechanism === 'node_auto_download') {
121
+ spec.resume = 'node-managed';
122
+ notes.push('this repo can be auto-downloaded by the custom node on first run');
123
+ // ready stays false — the engine must decide
124
+ blockers.push('delivery mechanism is node_auto_download — installer preload not configured for this entry');
125
+ return spec;
126
+ }
127
+
128
+ spec.url = `https://modelscope.cn/models/${src.repository}`;
129
+ spec.resume = 'snapshot-restart';
130
+ spec.ready = true;
131
+ notes.push('ModelScope snapshot download; resumability depends on the client used by the engine');
132
+ return spec;
133
+ }
134
+
135
+ /**
136
+ * Plan downloads for all required model dependencies of a manifest that the
137
+ * resolver reported as missing. `missingIds` comes from the resolution
138
+ * report (entries with status=missing, action=install).
139
+ *
140
+ * @param {object} manifest install manifest
141
+ * @param {string[]} missingIds dependency IDs that need downloading
142
+ * @param {object} [opts] planner options
143
+ * @param {boolean} [opts.hasHfToken] whether the system HF token is available
144
+ */
145
+ function planModelDownloads(manifest, missingIds, opts = {}) {
146
+ const deps = (manifest.dependencies || []).filter(
147
+ (d) => (d.kind === 'model' || d.kind === 'model_repo') && missingIds.includes(d.id)
148
+ );
149
+ return deps.map((dep) => planModelDownload(dep, opts));
150
+ }
151
+
152
+ /**
153
+ * Disk preflight summary: total bytes the missing models will need.
154
+ * Returns { total_bytes, unknown_count } — unknown sizes are counted
155
+ * separately, never silently assumed zero.
156
+ */
157
+ function estimateMissingBytes(specs) {
158
+ let total = 0;
159
+ let unknown = 0;
160
+ for (const s of specs) {
161
+ if (typeof s.size_bytes_approx === 'number') total += s.size_bytes_approx;
162
+ else unknown += 1;
163
+ }
164
+ return { total_bytes: total, unknown_count: unknown };
165
+ }
166
+
167
+ module.exports = {
168
+ SUPPORTED_SOURCE_KINDS,
169
+ planModelDownload,
170
+ planModelDownloads,
171
+ estimateMissingBytes,
172
+ };
@@ -0,0 +1,508 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * ComfyUI operations — Private Worker Installer Phase 2.
5
+ *
6
+ * install / update / start / health for ComfyUI, driven by the manifest
7
+ * runtime_requirements. Safety invariants:
8
+ * - update/downgrade only with an explicit user confirmation (the plan
9
+ * carries it via safety-rules.confirmationGate);
10
+ * - a checkpoint (previous commit) is recorded before any version change;
11
+ * - custom_nodes/, models/ and user/ are untracked by git and survive a
12
+ * checkout — the engine never deletes them;
13
+ * - ComfyUI listens on 127.0.0.1 only.
14
+ */
15
+
16
+ const path = require('path');
17
+ const platforms = require('../platform');
18
+ const { PrerequisiteError, classifyVenvCreateFailure, classifyVenvDir, debianVenvPackage } = require('./prereq');
19
+
20
+ /** Platform adapter for one call (explicit override wins over auto-detect). */
21
+ function adapterOf(opts = {}) {
22
+ return (opts && opts.platformAdapter) || platforms.getPlatformAdapter();
23
+ }
24
+
25
+ /**
26
+ * Choose the install source for a clean install.
27
+ * Canonical pin wins; otherwise the known-working reference may be used,
28
+ * but ONLY with explicit consent (it is evidence, not a universal rule).
29
+ */
30
+ function pickInstallSource(manifest) {
31
+ const spec = (manifest.runtime_requirements || {}).comfyui || {};
32
+ if (spec.pin && (spec.pin.commit || spec.pin.tag)) {
33
+ return { source: spec.pin, grade: 'canonical', needs_consent: false };
34
+ }
35
+ const ref = spec.known_working_reference;
36
+ if (ref && (ref.commit || ref.tag)) {
37
+ return { source: ref, grade: 'reference', needs_consent: true };
38
+ }
39
+ return null;
40
+ }
41
+
42
+ /**
43
+ * Adopt an installer-created partial root in place: init+fetch+checkout
44
+ * without touching existing content (venv, models, custom_nodes). git
45
+ * refuses to overwrite untracked files, so a conflict fails loudly instead
46
+ * of destroying anything. Used when a previous run populated the root but
47
+ * ComfyUI itself was never cloned (state file present, main.py missing).
48
+ */
49
+ function adoptComfyUI(io, { root, source, log }) {
50
+ const repo = source.repository;
51
+ const ref = source.commit || source.tag;
52
+ let r = io.exec('git', ['-C', root, 'init']);
53
+ if (r.code !== 0) throw new Error(`git init failed: ${r.stderr || r.error}`);
54
+ r = io.exec('git', ['-C', root, 'remote', 'add', 'origin', repo]);
55
+ if (r.code !== 0) {
56
+ // remote already exists (previous adopt attempt) — idempotent update
57
+ r = io.exec('git', ['-C', root, 'remote', 'set-url', 'origin', repo]);
58
+ }
59
+ if (r.code !== 0) throw new Error(`git remote add failed: ${r.stderr || r.error}`);
60
+ r = io.exec('git', ['-C', root, 'fetch', '--tags', 'origin'], { timeout: 30 * 60 * 1000 });
61
+ if (r.code !== 0) throw new Error(`git fetch failed: ${r.stderr || r.error}`);
62
+ r = io.exec('git', ['-C', root, 'checkout', ref]);
63
+ if (r.code !== 0) throw new Error(`git checkout ${ref} failed: ${r.stderr || r.error}`);
64
+ // installer metadata is local-only: never tracked, never committed
65
+ try {
66
+ const exclude = path.join(root, '.git', 'info', 'exclude');
67
+ let text = io.fs.existsSync(exclude) ? io.fs.readFileSync(exclude, 'utf8') : '';
68
+ for (const entry of ['.animastor-installer/', 'comfyui-installer.log']) {
69
+ if (!text.split('\n').map((l) => l.trim()).includes(entry)) {
70
+ text += `${text && !text.endsWith('\n') ? '\n' : ''}${entry}\n`;
71
+ }
72
+ }
73
+ io.fs.writeFileSync(exclude, text);
74
+ } catch (_) { /* best effort */ }
75
+ if (log) log.info(`ComfyUI adopted in place at ${root} (${ref || 'HEAD'})`);
76
+ return { root, ref, adopted: true };
77
+ }
78
+
79
+ function installComfyUI(io, { root, source, log }) {
80
+ const repo = source.repository;
81
+ const ref = source.commit || source.tag;
82
+ if (!repo) throw new Error('ComfyUI install source has no repository');
83
+ const metaDir = path.join(root, '.animastor-installer');
84
+ const metaStash = `${root}.animastor-installer.stash-${Date.now()}`;
85
+ let stashed = false;
86
+ if (io.fs.existsSync(root)) {
87
+ // The engine writes its install state into <root>/.animastor-installer/
88
+ // BEFORE cloning (resume support). That directory is installer-owned
89
+ // metadata, not user content — it does not make the target "occupied".
90
+ const entries = io.fs.readdirSync(root).filter((n) => n !== '.animastor-installer');
91
+ if (entries.length > 0) {
92
+ // A non-empty root is normally refused. Exception: a partial
93
+ // install created by an earlier installer run (its state file is
94
+ // here, but ComfyUI itself is missing) is ADOPTED in place —
95
+ // re-cloning from scratch would throw away the already-installed
96
+ // venv/models/custom_nodes.
97
+ if (io.fs.existsSync(path.join(metaDir, 'install-state.json'))) {
98
+ return adoptComfyUI(io, { root, source, log });
99
+ }
100
+ throw new Error(`target root ${root} is not empty — refusing to touch it`);
101
+ }
102
+ // git clone still refuses ANY non-empty destination, so the metadata
103
+ // is stashed aside for the duration of the clone and restored after.
104
+ if (io.fs.existsSync(metaDir)) {
105
+ io.fs.renameSync(metaDir, metaStash);
106
+ io.fs.rmdirSync(root);
107
+ stashed = true;
108
+ }
109
+ }
110
+ const restoreMeta = () => {
111
+ if (!stashed) return;
112
+ stashed = false;
113
+ try {
114
+ if (!io.fs.existsSync(root)) io.fs.mkdirSync(root, { recursive: true });
115
+ io.fs.renameSync(metaStash, metaDir);
116
+ } catch (_) { /* stash stays beside the root; next save() rewrites state */ }
117
+ };
118
+ let r = io.exec('git', ['clone', repo, root]);
119
+ if (r.code !== 0) {
120
+ restoreMeta();
121
+ throw new Error(`git clone failed: ${r.stderr || r.error}`);
122
+ }
123
+ if (ref) {
124
+ r = io.exec('git', ['-C', root, 'checkout', ref]);
125
+ if (r.code !== 0) {
126
+ restoreMeta();
127
+ throw new Error(`git checkout ${ref} failed: ${r.stderr || r.error}`);
128
+ }
129
+ }
130
+ restoreMeta();
131
+ if (log) log.info(`ComfyUI installed at ${root} (${ref || 'HEAD'})`);
132
+ return { root, ref };
133
+ }
134
+
135
+ /**
136
+ * Update an existing ComfyUI to the target ref. The caller must have passed
137
+ * the confirmation gate already; this function records the checkpoint.
138
+ * @returns {{ previous_commit, target }}
139
+ */
140
+ function updateComfyUI(io, { root, target, state = null, log }) {
141
+ const git = io.exec('git', ['-C', root, 'rev-parse', 'HEAD']);
142
+ const previousCommit = git.code === 0 ? git.stdout.trim() : null;
143
+
144
+ let r = io.exec('git', ['-C', root, 'fetch', '--tags', 'origin']);
145
+ if (r.code !== 0) throw new Error(`git fetch failed: ${r.stderr || r.error}`);
146
+ const ref = target.commit || target.tag;
147
+ r = io.exec('git', ['-C', root, 'checkout', ref]);
148
+ if (r.code !== 0) throw new Error(`git checkout ${ref} failed: ${r.stderr || r.error}`);
149
+
150
+ if (state) {
151
+ const { addCheckpoint } = require('./state');
152
+ addCheckpoint(state, { kind: 'comfyui-version-change', root, previous_commit: previousCommit, target: ref });
153
+ }
154
+ if (log) log.info(`ComfyUI updated: ${previousCommit || '?'} → ${ref}`);
155
+ return { previous_commit: previousCommit, target: ref };
156
+ }
157
+
158
+ /**
159
+ * Move a broken/incomplete venv aside (never delete — the user may want to
160
+ * inspect it). Returns the quarantine path.
161
+ */
162
+ function quarantineBrokenVenv(io, venvDir, reason, log) {
163
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
164
+ const quarantine = `${venvDir}.broken-${stamp}`;
165
+ try {
166
+ io.fs.renameSync(venvDir, quarantine);
167
+ } catch (err) {
168
+ throw new Error(`existing venv at ${venvDir} is broken (${reason}) and could not be moved aside: ${err.message}`);
169
+ }
170
+ if (log) log.warn(`existing venv at ${venvDir} is broken (${reason}) — moved aside to ${quarantine}; a fresh venv will be created`);
171
+ return quarantine;
172
+ }
173
+
174
+ /**
175
+ * Long-running command runner for python runtime steps: prefers io.execAsync
176
+ * (event loop stays free — the terminal busy spinner keeps animating) and
177
+ * streams meaningful output lines (Collecting/Installing/Successfully…) to
178
+ * the terminal renderer, secret-scrubbed via the logger. Falls back to the
179
+ * synchronous io.exec for mock io in tests. Carriage-return progress-bar
180
+ * redraws are filtered out by execAsync; the full raw output is still
181
+ * captured and available for error messages.
182
+ */
183
+ function makeLongRunner(io, { term = null, log = null } = {}) {
184
+ const onLine = (term && log && typeof log.scrub === 'function')
185
+ ? (line) => term.print(log.scrub(line))
186
+ : null;
187
+ return (cmd, args, opts = {}) => (typeof io.execAsync === 'function'
188
+ ? io.execAsync(cmd, args, { ...opts, onLine })
189
+ : Promise.resolve(io.exec(cmd, args, opts)));
190
+ }
191
+
192
+ /** Install ComfyUI python requirements + torch pin into a venv. */
193
+ async function preparePythonRuntime(io, { root, torchSpec, pythonMinimum, log, term = null, platformAdapter = null }) {
194
+ const adapter = adapterOf({ platformAdapter });
195
+ const venvDir = path.join(root, 'venv');
196
+ const py = adapter.venvPythonBin(venvDir);
197
+ const execLong = makeLongRunner(io, { term, log });
198
+
199
+ let venvCreated = false;
200
+ let quarantined = null;
201
+
202
+ // A directory that LOOKS like a venv is not a working runtime: classify
203
+ // it first. A directory without a python interpreter is a broken/incomplete
204
+ // managed runtime — quarantine it and recreate instead of failing later
205
+ // (or worse, silently treating its presence as success).
206
+ const existing = classifyVenvDir(io, venvDir, adapter);
207
+ if (existing.state === 'incomplete') {
208
+ quarantined = quarantineBrokenVenv(io, venvDir, existing.reason, log);
209
+ }
210
+
211
+ if (!io.fs.existsSync(py)) {
212
+ const r = await execLong('python3', ['-m', 'venv', venvDir], { timeout: 15 * 60 * 1000 });
213
+ if (r.code !== 0) {
214
+ const versionRes = io.exec('python3', ['--version']);
215
+ const vMatch = /Python\s+([0-9][0-9.]*)/.exec(String(versionRes.stdout) + String(versionRes.stderr));
216
+ const failure = classifyVenvCreateFailure(String(r.stderr || r.stdout || ''), vMatch ? vMatch[1] : null, adapter);
217
+ throw new PrerequisiteError({
218
+ code: failure.code,
219
+ summary: failure.summary,
220
+ message: `python3 -m venv failed (code ${r.code}): ${String(r.stderr || r.stdout || r.error || 'no output').slice(-500)}`,
221
+ hostPackage: failure.hostPackage,
222
+ remediationCommand: failure.remediationCommand,
223
+ });
224
+ }
225
+ if (log) log.info(`venv created at ${venvDir}`);
226
+ venvCreated = true;
227
+ }
228
+
229
+ // Some distributions (notably Ubuntu/Debian VPS without python3-pip)
230
+ // create venvs WITHOUT pip — every later `python -m pip` would fail.
231
+ // The managed venv must have pip before torch/requirements installs.
232
+ const pipCheck = io.exec(py, ['-m', 'pip', '--version']);
233
+ if (pipCheck.code !== 0) {
234
+ const boot = await execLong(py, ['-m', 'ensurepip', '--upgrade'], { timeout: 15 * 60 * 1000 });
235
+ if (boot.code !== 0) {
236
+ const versionRes = io.exec(py, ['--version']);
237
+ const vMatch = /Python\s+([0-9][0-9.]*)/.exec(String(versionRes.stdout) + String(versionRes.stderr));
238
+ const pkg = debianVenvPackage(vMatch ? vMatch[1] : null);
239
+ throw new PrerequisiteError({
240
+ code: 'MISSING_ENSUREPIP',
241
+ summary: 'the Python venv prerequisite is missing (venv has neither pip nor a working ensurepip)',
242
+ message: `pip is unavailable in the venv and ensurepip failed (code ${boot.code}): ${String(boot.stderr || boot.stdout || '').slice(-500)}`,
243
+ hostPackage: pkg,
244
+ remediationCommand: adapter.hostPackageCommand(pkg),
245
+ });
246
+ }
247
+ if (log) log.info('pip bootstrapped into the venv via ensurepip');
248
+ }
249
+
250
+ // Torch is installed BEFORE requirements.txt: pip then sees the pinned
251
+ // (CUDA- or CPU-flavored) build as satisfied instead of pulling the
252
+ // default PyPI wheel first (a multi-GB CUDA download on CPU-only hosts).
253
+ if (torchSpec && torchSpec.pin) {
254
+ const pin = String(torchSpec.pin);
255
+ const version = pin.split('+')[0];
256
+ const args = ['-m', 'pip', 'install', `torch==${version}`];
257
+ if (torchSpec.index_url) args.push('--index-url', torchSpec.index_url);
258
+ const r = await execLong(py, args, { timeout: 60 * 60 * 1000 });
259
+ if (r.code !== 0) throw new Error(`pip install torch==${version} failed: ${String(r.stderr).slice(-500)}`);
260
+ if (log) log.info(`torch ${pin} installed${torchSpec.index_url ? ` (from ${torchSpec.index_url})` : ''}`);
261
+ }
262
+
263
+ const req = path.join(root, 'requirements.txt');
264
+ if (io.fs.existsSync(req)) {
265
+ const args = ['-m', 'pip', 'install', '-r', req];
266
+ if (torchSpec && torchSpec.pin) {
267
+ // requirements.txt typically carries UNPINNED torch/torchvision/
268
+ // torchaudio; without a constraint their dependency edges make pip
269
+ // REPLACE the pinned torch (e.g. with the latest CUDA build from
270
+ // PyPI). Constrain torch to the manifest pin and prefer the pin's
271
+ // index so matching torchvision/torchaudio builds are selected.
272
+ const constraintFile = path.join(root, 'venv', '.animastor-torch-constraints.txt');
273
+ io.fs.writeFileSync(constraintFile, `torch==${String(torchSpec.pin).split('+')[0]}\n`);
274
+ args.push('-c', constraintFile);
275
+ if (torchSpec.index_url) {
276
+ args.push('--index-url', torchSpec.index_url, '--extra-index-url', 'https://pypi.org/simple');
277
+ }
278
+ }
279
+ const r = await execLong(py, args, { timeout: 30 * 60 * 1000 });
280
+ if (r.code !== 0) throw new Error(`pip install -r requirements.txt failed: ${String(r.stderr).slice(-500)}`);
281
+ if (log) log.info('ComfyUI requirements installed');
282
+ }
283
+
284
+ return { venv: venvDir, python: py, venv_created: venvCreated, quarantined_broken_venv: quarantined };
285
+ }
286
+
287
+ /**
288
+ * Ensure ComfyUI's own requirements.txt dependencies are present in the venv
289
+ * WITHOUT breaking the pinned torch family. An ADOPTED ComfyUI (pre-existing
290
+ * venv with torch+python already working) skips the full runtime step — but
291
+ * the fork may carry extra deps the old venv never got (e.g. SQLAlchemy).
292
+ * requirements.txt typically lists UNPINNED torch/torchvision/torchaudio:
293
+ * without constraints pip pulls the latest PyPI builds, which are compiled
294
+ * against a DIFFERENT torch ABI ("operator torchvision::nms does not exist").
295
+ * The constraint pins the whole torch family to the installed version's
296
+ * minor; the CPU index supplies ABI-matched +cpu builds when available.
297
+ * pip skips satisfied deps in seconds, so this is safe on every run.
298
+ * @returns {{ skipped: boolean }}
299
+ */
300
+ async function syncComfyUIRequirements(io, { root, torchSpec = null, log = null, term = null, platformAdapter = null }) {
301
+ const py = adapterOf({ platformAdapter }).venvPythonBin(path.join(root, 'venv'));
302
+ const req = path.join(root, 'requirements.txt');
303
+ if (!io.fs.existsSync(py) || !io.fs.existsSync(req)) return { skipped: true };
304
+ const execLong = makeLongRunner(io, { term, log });
305
+
306
+ let args = ['-m', 'pip', 'install', '-r', req];
307
+ const pin = torchSpec && torchSpec.pin ? String(torchSpec.pin).split('+')[0] : null;
308
+ if (pin && /^\d+\.\d+\.\d+$/.test(pin)) {
309
+ // torch 2.N ↔ torchvision 0.(N+15) ↔ torchaudio 2.N (holds across 2.x;
310
+ // range-pins keep patch releases available, forbid minor drift)
311
+ const minor = Number(pin.split('.')[1]);
312
+ if (Number.isFinite(minor)) {
313
+ const constraints = [
314
+ `torch==${pin}`,
315
+ `torchvision>=0.${minor + 15},<0.${minor + 16}`,
316
+ `torchaudio>=${pin.split('.')[0]}.${minor},<${pin.split('.')[0]}.${minor + 1}`,
317
+ ].join('\n') + '\n';
318
+ const constraintFile = path.join(root, 'venv', '.animastor-torch-constraints.txt');
319
+ io.fs.writeFileSync(constraintFile, constraints);
320
+ args.push('-c', constraintFile);
321
+ }
322
+ if (torchSpec.index_url) {
323
+ args.push('--index-url', torchSpec.index_url, '--extra-index-url', 'https://pypi.org/simple');
324
+ }
325
+ }
326
+ const r = await execLong(py, args, { timeout: 30 * 60 * 1000 });
327
+ if (r.code !== 0) throw new Error(`pip install -r requirements.txt failed: ${String(r.stderr).slice(-500)}`);
328
+ if (log) log.info('ComfyUI requirements synced');
329
+
330
+ // Build provenance repair: a version range cannot distinguish a
331
+ // same-version wheel built for a DIFFERENT torch ABI (the generic PyPI
332
+ // torchvision 0.25.0 vs the ABI-matched 0.25.0+cpu) — the local version
333
+ // tag can. torch "2.10.0+cpu" + torchvision "0.25.0" (no local tag) means
334
+ // the generic build sneaked in ("operator torchvision::nms does not
335
+ // exist") → force the +cpu wheel from the torch pin's index.
336
+ const distVersion = (dist) => {
337
+ const q = io.exec(py, ['-c', `from importlib.metadata import version; print(version("${dist}"))`]);
338
+ return (q && q.code === 0 && q.stdout) ? String(q.stdout).trim() : null;
339
+ };
340
+ const torchVer = distVersion('torch');
341
+ const torchLocal = torchVer && torchVer.includes('+') ? torchVer.split('+')[1] : null;
342
+ if (torchLocal && torchSpec && torchSpec.index_url) {
343
+ for (const dist of ['torchvision', 'torchaudio']) {
344
+ const v = distVersion(dist);
345
+ if (v && !v.includes('+')) {
346
+ const fix = await execLong(py, ['-m', 'pip', 'install', '--force-reinstall', '--no-deps',
347
+ `${dist}==${v.split('+')[0]}`, '--index-url', torchSpec.index_url], { timeout: 30 * 60 * 1000 });
348
+ if (fix.code !== 0) throw new Error(`pip install --force-reinstall ${dist} failed: ${String(fix.stderr).slice(-500)}`);
349
+ if (log) log.info(`${dist} reinstalled from ${torchSpec.index_url} (ABI-matched ${torchLocal} build)`);
350
+ }
351
+ }
352
+ }
353
+ return { skipped: false };
354
+ }
355
+
356
+ /**
357
+ * Start ComfyUI. In CPU-only mode the `--cpu` flag forces the CPU execution
358
+ * path (ComfyUI's own device selector) — required on hosts without a GPU.
359
+ */
360
+ function startComfyUI(io, { root, port = 8188, logFile = null, device = null, platformAdapter = null }) {
361
+ const py = adapterOf({ platformAdapter }).venvPythonBin(path.join(root, 'venv'));
362
+ const python = io.fs.existsSync(py) ? py : 'python3';
363
+ const args = ['main.py', '--listen', '127.0.0.1', '--port', String(port)];
364
+ if (device === 'cpu') args.push('--cpu');
365
+ const pid = io.spawnDaemon(python, args, {
366
+ cwd: root,
367
+ logFile: logFile || path.join(root, 'comfyui-installer.log'),
368
+ });
369
+ return { pid, port, args };
370
+ }
371
+
372
+ async function waitForApi(io, baseUrl, { timeoutMs = 120000, intervalMs = 2000 } = {}) {
373
+ const deadline = io.now() + timeoutMs;
374
+ for (;;) {
375
+ try {
376
+ const { status, json } = await io.http.fetchJson(`${baseUrl}/system_stats`);
377
+ if (status === 200 && json) return { ok: true, system_stats: json };
378
+ } catch (_) { /* not up yet */ }
379
+ if (io.now() > deadline) return { ok: false, reason: `ComfyUI API not reachable at ${baseUrl} after ${timeoutMs} ms` };
380
+ await new Promise((r) => setTimeout(r, intervalMs));
381
+ }
382
+ }
383
+
384
+ async function systemStats(io, baseUrl) {
385
+ try {
386
+ const { status, json } = await io.http.fetchJson(`${baseUrl}/system_stats`);
387
+ if (status === 200 && json) return json;
388
+ } catch (_) { /* unreachable */ }
389
+ return null;
390
+ }
391
+
392
+ /**
393
+ * PIDs of ComfyUI processes running from `root` (managed-instance check), by
394
+ * default on `port`. Process discovery is a platform concern (Linux: cwd
395
+ * check via /proc; Windows: venv python ExecutablePath under the root) —
396
+ * the platform adapter guarantees the installer only ever touches an
397
+ * instance it manages — a foreign ComfyUI (different root) is never signaled.
398
+ */
399
+ function findManagedComfyUIPids(io, { root, port = null, platformAdapter = null }) {
400
+ return adapterOf({ platformAdapter }).findComfyUIPids(io, { root, port });
401
+ }
402
+
403
+ /**
404
+ * Restart the managed ComfyUI instance: stop the processes running from
405
+ * `root`, start a fresh one, and wait for the API. Used after custom nodes
406
+ * changed — ComfyUI imports custom nodes ONLY at startup, so a node
407
+ * installed or repaired while it runs never appears in /object_info.
408
+ * `allowedUids` (opt-in, used by the management tools): when given, only
409
+ * processes owned by those uids are signaled — a foreign account's ComfyUI
410
+ * running from the same root (shared host) is left alone.
411
+ */
412
+ async function restartManagedComfyUI(io, { root, port, device = null, log = null, verifyTimeoutMs = 120000, pollIntervalMs = 2000, allowedUids = null, platformAdapter = null }) {
413
+ const adapter = adapterOf({ platformAdapter });
414
+ let pids = findManagedComfyUIPids(io, { root, port, platformAdapter: adapter });
415
+ if (allowedUids && pids.length > 0) {
416
+ pids = pids.filter((pid) => {
417
+ const uid = adapter.pidUid(io, pid);
418
+ return uid != null ? allowedUids.includes(uid) : true;
419
+ });
420
+ }
421
+ if (pids.length === 0) {
422
+ return { restarted: false, reason: 'no running ComfyUI process found for this installation root' };
423
+ }
424
+ const doKill = (pid, signal) => {
425
+ if (typeof io.kill === 'function') io.kill(pid, signal);
426
+ else process.kill(pid, signal);
427
+ };
428
+ for (const pid of pids) {
429
+ if (log) log.info(`stopping ComfyUI (pid ${pid}) so the new custom nodes are imported on startup`);
430
+ try { doKill(pid, 'SIGTERM'); } catch (_) { /* already gone */ }
431
+ }
432
+ const alive = () => pids.filter((pid) => { try { process.kill(pid, 0); return true; } catch (_) { return false; } });
433
+ const deadline = io.now() + 15000;
434
+ while (alive().length > 0 && io.now() < deadline) {
435
+ await new Promise((r) => setTimeout(r, 300));
436
+ }
437
+ for (const pid of alive()) {
438
+ try { doKill(pid, 'SIGKILL'); } catch (_) { /* gone */ }
439
+ }
440
+ const { pid } = startComfyUI(io, { root, port, device });
441
+ const up = await waitForApi(io, `http://127.0.0.1:${port}`, { timeoutMs: verifyTimeoutMs, intervalMs: pollIntervalMs });
442
+ if (!up.ok) return { restarted: true, pid, up: false, reason: up.reason };
443
+ return { restarted: true, pid, up: true };
444
+ }
445
+
446
+ /** Set of available node class_type names (for workflow validation). */
447
+ async function objectInfoClasses(io, baseUrl) {
448
+ try {
449
+ const { status, json } = await io.http.fetchJson(`${baseUrl}/object_info`);
450
+ if (status === 200 && json) return new Set(Object.keys(json));
451
+ } catch (_) { /* unreachable */ }
452
+ return null;
453
+ }
454
+
455
+ /**
456
+ * Validate a workflow JSON against a running ComfyUI WITHOUT running
457
+ * generation: parse → node classes exist → model file refs present on disk.
458
+ */
459
+ function validateWorkflowStatic(workflowJson, { availableClasses = null, modelPaths = null } = {}) {
460
+ const problems = { missing_classes: [], missing_models: [], parse_error: null };
461
+ let wf = workflowJson;
462
+ if (typeof wf === 'string') {
463
+ try { wf = JSON.parse(wf); } catch (err) {
464
+ problems.parse_error = err.message;
465
+ return problems;
466
+ }
467
+ }
468
+ if (!wf || typeof wf !== 'object') {
469
+ problems.parse_error = 'workflow is not a JSON object';
470
+ return problems;
471
+ }
472
+ const nodes = wf.nodes && Array.isArray(wf.nodes) ? wf.nodes : null;
473
+ const apiStyle = !nodes; // API format: { "<id>": { class_type, inputs } }
474
+ const items = apiStyle ? Object.values(wf) : nodes;
475
+
476
+ for (const node of items) {
477
+ if (!node || typeof node !== 'object') continue;
478
+ const cls = node.class_type || (node.type);
479
+ if (cls && availableClasses && !availableClasses.has(cls)) {
480
+ if (!problems.missing_classes.includes(cls)) problems.missing_classes.push(cls);
481
+ }
482
+ const inputs = node.inputs || (apiStyle ? node.inputs : null) || {};
483
+ for (const v of Object.values(inputs)) {
484
+ if (typeof v === 'string' && /\.(gguf|safetensors|ckpt|pt|bin|onnx)$/i.test(v)) {
485
+ if (modelPaths && !modelPaths.has(v)) {
486
+ if (!problems.missing_models.includes(v)) problems.missing_models.push(v);
487
+ }
488
+ }
489
+ }
490
+ }
491
+ return problems;
492
+ }
493
+
494
+ module.exports = {
495
+ pickInstallSource,
496
+ installComfyUI,
497
+ adoptComfyUI,
498
+ updateComfyUI,
499
+ preparePythonRuntime,
500
+ syncComfyUIRequirements,
501
+ startComfyUI,
502
+ waitForApi,
503
+ systemStats,
504
+ objectInfoClasses,
505
+ findManagedComfyUIPids,
506
+ restartManagedComfyUI,
507
+ validateWorkflowStatic,
508
+ };