@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,1180 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Installation Engine — Private Worker Installer Phase 2.
5
+ *
6
+ * Execution layer. It receives the already-computed install plan (from the
7
+ * Phase 1.5 plan builder) and executes ONLY the operations the plan allows:
8
+ *
9
+ * Environment detection → Manifest → Compatibility Resolver → Install Plan
10
+ * → USER CONFIRMATION → Installation Engine → Verification
11
+ *
12
+ * The engine never invents dependencies, URLs, or versions — everything comes
13
+ * from the canonical manifests via resolver/plan. It is idempotent (re-run or
14
+ * `resume` continues where it stopped) and never destroys a user's working
15
+ * configuration on failure.
16
+ *
17
+ * Secrets: the Worker Key enters through `secretProvider` (interactive hidden
18
+ * input in the CLI), is registered for log redaction immediately, and is used
19
+ * only to write .env and to call the hub verify endpoint. It never appears in
20
+ * the plan, state, results, or logs.
21
+ */
22
+
23
+ const path = require('path');
24
+
25
+ const platforms = require('../platform');
26
+ const resolver = require('../compatibility-resolver');
27
+ const { buildInstallPlan } = require('../install-plan');
28
+ const { confirmationGate } = require('../safety-rules');
29
+ const { planModelDownloads } = require('../download-planner');
30
+ const state = require('./state');
31
+ const probe = require('./probe');
32
+ const comfyui = require('./comfyui');
33
+ const nodes = require('./nodes');
34
+ const workflowsInstall = require('./workflows');
35
+ const downloader = require('./downloader');
36
+ const worker = require('./worker');
37
+ const repoBundleSource = require('../worker-bundle-source');
38
+ const prereq = require('./prereq');
39
+ const management = require('../management');
40
+ const { createProgressReporter } = require('./progress');
41
+ const { buildVerificationReport } = require('../verification-report');
42
+
43
+ const CPU_TORCH_INDEX_URL = 'https://download.pytorch.org/whl/cpu';
44
+ const CPU_MODE_WARNING = 'CPU-only mode: no supported GPU runtime detected — a CPU build of PyTorch will be installed and ComfyUI will run with --cpu. Performance will be SIGNIFICANTLY lower; this mode is intended for the TTS/audio profile, not for image/video generation.';
45
+
46
+ function stepById(plan, id) {
47
+ return plan.steps.find((s) => s.id === id) || null;
48
+ }
49
+
50
+ /**
51
+ * Module-level registry of live SIGINT guards. A process runs at most ONE
52
+ * installation at a time; a still-registered handler from a previous
53
+ * crashed/abandoned run is stale and is unregistered when the next run
54
+ * installs its guard (self-healing, no signal-handler leaks).
55
+ */
56
+ const ACTIVE_INTERRUPT_HANDLERS = new Set();
57
+
58
+ function registerInterruptHandler(handler) {
59
+ for (const stale of ACTIVE_INTERRUPT_HANDLERS) {
60
+ process.removeListener('SIGINT', stale);
61
+ }
62
+ ACTIVE_INTERRUPT_HANDLERS.clear();
63
+ ACTIVE_INTERRUPT_HANDLERS.add(handler);
64
+ process.on('SIGINT', handler);
65
+ }
66
+
67
+ function unregisterInterruptHandler(handler) {
68
+ ACTIVE_INTERRUPT_HANDLERS.delete(handler);
69
+ process.removeListener('SIGINT', handler);
70
+ }
71
+
72
+ /**
73
+ * Ctrl+C guard for the installation run.
74
+ *
75
+ * On SIGINT: mark the state as interrupted, mark the in-flight artifact
76
+ * (e.g. a model whose download is mid-flight) as PARTIAL — never installed —
77
+ * persist the resumable state, tell the user, and exit 130. Partial
78
+ * downloads stay on disk as `<file>.part` and are resumed on the next run.
79
+ *
80
+ * Fully injectable (register/unregister/exit/state) for deterministic tests.
81
+ */
82
+ function createInterruptGuard({
83
+ state: installState, save, log = null,
84
+ getArtifactId = null,
85
+ exit = (code) => process.exit(code),
86
+ register = registerInterruptHandler,
87
+ unregister = unregisterInterruptHandler,
88
+ }) {
89
+ let triggered = false;
90
+ const handler = () => {
91
+ if (triggered) { exit(130); return; } // second Ctrl+C: force exit
92
+ triggered = true;
93
+ try {
94
+ installState.interrupted = true;
95
+ installState.interrupted_at = new Date().toISOString();
96
+ const id = getArtifactId ? getArtifactId() : null;
97
+ if (id) state.setArtifact(installState, id, 'partial', { reason: 'interrupted by user (Ctrl+C) — download is resumable' });
98
+ try { save(); } catch (_) { /* best effort */ }
99
+ if (log && log.error) log.error('Interrupted (Ctrl+C) — progress saved. Partial downloads are marked and will resume on the next run (`resume` or re-run `install`).');
100
+ } catch (_) { /* never throw from a signal handler */ }
101
+ exit(130);
102
+ };
103
+ register(handler);
104
+ return () => unregister(handler);
105
+ }
106
+
107
+ /**
108
+ * Pick the torch spec for the detected device branch.
109
+ * device='cuda' (default) — canonical pin, or known-working reference with
110
+ * explicit consent (unchanged Phase 2 behaviour).
111
+ * device='cpu' — the manifest's dedicated CPU build (spec.cpu) is a
112
+ * first-class branch; without one, a CPU spec is derived from the existing
113
+ * pin/reference by stripping the CUDA local tag (explicitly warned, never
114
+ * silent).
115
+ */
116
+ function pickTorchSpec(manifests, decisions, warnings, device = null) {
117
+ if (device === 'cpu') {
118
+ for (const m of manifests) {
119
+ const spec = (m.runtime_requirements || {}).torch || {};
120
+ if (spec.cpu && spec.cpu.pin) {
121
+ return {
122
+ spec: { pin: spec.cpu.pin, index_url: spec.cpu.index_url || CPU_TORCH_INDEX_URL },
123
+ grade: 'cpu-canonical',
124
+ };
125
+ }
126
+ }
127
+ for (const m of manifests) {
128
+ const spec = (m.runtime_requirements || {}).torch || {};
129
+ const raw = spec.pin
130
+ || (spec.known_working_reference && spec.known_working_reference.version)
131
+ || null;
132
+ if (raw) {
133
+ const base = String(raw).split('+')[0];
134
+ warnings.push(`manifest has no dedicated CPU torch build — deriving CPU spec from ${raw}: installing torch ${base} from ${CPU_TORCH_INDEX_URL}`);
135
+ return { spec: { pin: base, index_url: CPU_TORCH_INDEX_URL }, grade: 'cpu-derived' };
136
+ }
137
+ }
138
+ return null;
139
+ }
140
+ for (const m of manifests) {
141
+ const spec = (m.runtime_requirements || {}).torch || {};
142
+ if (spec.pin) return { spec, grade: 'canonical' };
143
+ }
144
+ for (const m of manifests) {
145
+ const spec = (m.runtime_requirements || {}).torch || {};
146
+ if (spec.known_working_reference && spec.known_working_reference.version) {
147
+ if (decisions.accept_reference_runtime === true) {
148
+ const ref = spec.known_working_reference;
149
+ return {
150
+ spec: { pin: ref.version, index_url: ref.index_url || null },
151
+ grade: 'reference',
152
+ };
153
+ }
154
+ warnings.push(`canonical torch pin is unknown (D1); known-working reference is ${spec.known_working_reference.version} — pass accept_reference_runtime to install it`);
155
+ return null;
156
+ }
157
+ }
158
+ return null;
159
+ }
160
+
161
+ /** Non-secret decision keys persisted to install-state.json for `resume`. */
162
+ const PERSISTED_DECISION_KEYS = Object.freeze([
163
+ 'comfyui_update', 'install_custom_nodes', 'install_models',
164
+ 'workflows', 'restore_baseline', 'worker_setup', 'worker_key_provided',
165
+ 'accept_reference_runtime', 'accept_runtime_change',
166
+ 'install_management_tools',
167
+ ]);
168
+
169
+ function sanitizeDecisions(decisions) {
170
+ const out = {};
171
+ for (const k of PERSISTED_DECISION_KEYS) {
172
+ if (decisions[k] !== undefined) out[k] = decisions[k];
173
+ }
174
+ return out;
175
+ }
176
+
177
+ /**
178
+ * Load resumable install state or produce a resumable-not-possible verdict.
179
+ * @returns {{ ok: true, state } | { ok: false, reason }}
180
+ */
181
+ function loadResumableState(io, statePath) {
182
+ const st = state.loadState(io, statePath);
183
+ if (!st) return { ok: false, reason: 'no-state-file' };
184
+ if (!st.profiles || !Array.isArray(st.profiles) || st.profiles.length === 0) {
185
+ return { ok: false, reason: 'state-has-no-profiles' };
186
+ }
187
+ return { ok: true, state: st };
188
+ }
189
+
190
+ /** Render prior-progress summary lines from a saved state. */
191
+ function renderResumeSummary(st) {
192
+ const ids = Object.keys(st.artifacts || {});
193
+ if (ids.length === 0) return ['Prior progress: nothing recorded yet'];
194
+ const marks = { verified: '✓', installed: '✓', failed: '✗', partial: '~', missing: '·' };
195
+ const lines = ['Prior progress (from install-state.json):'];
196
+ if (st.interrupted) {
197
+ lines.push(` Previous run was interrupted (Ctrl+C)${st.interrupted_at ? ` at ${st.interrupted_at}` : ''} — partial downloads will resume.`);
198
+ }
199
+ for (const id of ids.sort()) {
200
+ const a = st.artifacts[id];
201
+ lines.push(` ${marks[a.status] || '·'} ${id}: ${a.status}${a.attempts ? ` (${a.attempts} failed attempt(s))` : ''}`);
202
+ }
203
+ return lines;
204
+ }
205
+
206
+ /**
207
+ * Run the installation.
208
+ *
209
+ * @param {object} args
210
+ * @param {object[]} args.manifests - loaded canonical manifests
211
+ * @param {string} args.mode - managed | existing | shared
212
+ * @param {object} args.io - io adapter (real, mock, or dry-run guarded)
213
+ * @param {object} args.roots - { comfyuiRoot, workerDir, statePath, repoRoot, hubUrl }
214
+ * @param {object} [args.decisions] - recorded user decisions (never secret values)
215
+ * @param {Function} [args.secretProvider] - async (name) => value (hidden input)
216
+ * @param {object} [args.logger]
217
+ * @param {object} [args.crypto] - crypto module (hashing)
218
+ * @param {object} [args.env] - pre-probed environment (else probed here)
219
+ * @param {boolean} [args.dryRun]
220
+ * @param {object} [args.initialState] - pre-loaded install state (`resume`); when
221
+ * given, it is used as-is and never reset
222
+ * @param {object} [args.options] - { startComfyui, comfyPort, verifyTimeoutMs }
223
+ */
224
+ async function runInstallation(args) {
225
+ const {
226
+ manifests, mode, io, roots,
227
+ decisions = {}, secretProvider = null,
228
+ logger = null, crypto = null, env: preEnv = null,
229
+ dryRun = false, initialState = null, options = {},
230
+ platformAdapter: platformAdapterOpt = null,
231
+ } = args;
232
+
233
+ // Platform adapter (auto-detected unless injected): every OS-specific
234
+ // behaviour below (venv layout, process ops, build tools) goes through it.
235
+ const platformAdapter = platformAdapterOpt || platforms.getPlatformAdapter();
236
+
237
+ const log = logger || { info: () => {}, warn: () => {}, error: () => {}, output: () => {}, step: async (n, fn) => ({ ok: true, value: await fn() }), registerSecret: () => {} };
238
+ const {
239
+ comfyuiRoot, workerDir, statePath,
240
+ repoRoot = null, hubUrl = null, toolsDir = null,
241
+ } = roots;
242
+
243
+ // Busy indicator for long subprocess steps (pip/npm/git/waiting): ONE
244
+ // shared spinner through the terminal renderer. Without a term (tests,
245
+ // library use) it is a no-op passthrough.
246
+ const term = options.term || null;
247
+ const withBusy = (label, fn, o) => (term ? term.withBusy(label, fn, o) : fn());
248
+ const withBusySync = (label, fn) => (term ? term.withBusySync(label, fn) : fn());
249
+
250
+ const result = {
251
+ status: 'incomplete',
252
+ mode,
253
+ plan: null,
254
+ report: null,
255
+ results: {
256
+ comfyui: null, runtime: null, custom_nodes: [], models: [],
257
+ workflows: [], worker: [], registration: null,
258
+ },
259
+ blocked: [],
260
+ warnings: [],
261
+ verification: null,
262
+ remediation: null,
263
+ };
264
+
265
+ // ── 1. detect ─────────────────────────────────────────────────────────
266
+ // In dry-run mode, skip probing (io.exec is guarded) — use provided env or minimal.
267
+ const env = preEnv || (dryRun
268
+ ? { gpu: null, device: 'cpu', comfyui: null, python: null, torch: null, nodejs: null, custom_nodes: [], models: [], workflows: [], worker: null }
269
+ : probe.probeEnvironment(io, {
270
+ root: comfyuiRoot, workerDir, crypto,
271
+ workerType: manifests.length === 1 ? (manifests[0].worker_bundle || {}).worker_type : null,
272
+ })
273
+ );
274
+ const device = env.device || (env.gpu ? 'cuda' : 'cpu');
275
+ if (device === 'cpu') {
276
+ result.warnings.push(CPU_MODE_WARNING);
277
+ if (env.gpu && env.gpu.vendor === 'amd') {
278
+ result.warnings.push('AMD GPU detected, but the installer provides no ROCm/accelerated runtime branch yet — falling back to CPU-only mode.');
279
+ }
280
+ }
281
+
282
+ // ── 2. resolve ────────────────────────────────────────────────────────
283
+ const report = resolver.resolveInstallation({
284
+ manifests,
285
+ environment: env,
286
+ mode: mode === 'shared' ? 'shared' : mode,
287
+ });
288
+ result.report = report;
289
+
290
+ // ── 3. plan ───────────────────────────────────────────────────────────
291
+ const plan = buildInstallPlan({ report, manifests, decisions });
292
+ result.plan = plan;
293
+
294
+ if (plan.blocked.length > 0) {
295
+ result.status = 'blocked';
296
+ result.blocked = plan.blocked;
297
+ log.warn(`installation blocked: ${plan.blocked.map((b) => b.reason).join('; ')}`);
298
+ return result;
299
+ }
300
+ if (dryRun) {
301
+ result.status = 'dry_run';
302
+ return result;
303
+ }
304
+ if (plan.awaiting_decisions.length > 0) {
305
+ result.status = 'awaiting_decisions';
306
+ return result;
307
+ }
308
+
309
+ // ── 4. execute ────────────────────────────────────────────────────────
310
+ // State is an OPTIMIZATION; disk truth is always re-checked before doing.
311
+ const st = initialState
312
+ || state.loadState(io, statePath)
313
+ || state.emptyState({ mode, profiles: report.profiles, root: comfyuiRoot });
314
+ state.normalizeState(st);
315
+ st.profiles = report.profiles;
316
+ st.device = device;
317
+ if (!dryRun) {
318
+ // persist the (non-secret) decisions so `resume` does not re-prompt
319
+ st.decisions = { ...(st.decisions || {}), ...sanitizeDecisions(decisions) };
320
+ }
321
+ // Managed mode owns the whole stack: services start by default (opt out
322
+ // with --no-start-comfy / --no-start-worker), 'existing' mode leaves the
323
+ // user's own ComfyUI alone but still runs OUR worker. The flags are also
324
+ // remembered across re-runs — a bare re-run keeps the same wiring instead
325
+ // of silently reverting to defaults. Explicit CLI flags always win.
326
+ if (!dryRun) {
327
+ const saved = st.installer_options || {};
328
+ for (const k of ['comfyPort', 'startComfyui', 'startWorker']) {
329
+ if (options[k] === undefined && saved[k] !== undefined) {
330
+ options[k] = saved[k];
331
+ log.info(`reusing remembered setting: ${k}=${saved[k]}`);
332
+ }
333
+ }
334
+ if (options.startComfyui === undefined) options.startComfyui = (mode === 'managed');
335
+ if (options.startWorker === undefined) options.startWorker = (mode !== 'existing') && (decisions.worker_setup !== false);
336
+ // Never wire this install to a FOREIGN service on the default port.
337
+ if (options.comfyPort !== undefined) {
338
+ const ours = st.comfyui_runtime && st.comfyui_runtime.port === options.comfyPort;
339
+ const s = await comfyPortState(io, options.comfyPort);
340
+ if (s === 'foreign' && !ours) {
341
+ log.info(`remembered port ${options.comfyPort} is now used by another service — picking a new one`);
342
+ options.comfyPort = undefined;
343
+ }
344
+ }
345
+ if (options.comfyPort === undefined) {
346
+ options.comfyPort = await autoPickComfyPort(io, { st, mode, log });
347
+ }
348
+ st.installer_options = {
349
+ comfyPort: options.comfyPort ?? null,
350
+ startComfyui: !!options.startComfyui,
351
+ startWorker: !!options.startWorker,
352
+ };
353
+ }
354
+ const save = () => state.saveState(io, statePath, st, io.now);
355
+ if (initialState) {
356
+ for (const line of renderResumeSummary(st)) log.info(line);
357
+ }
358
+
359
+ // ── 4.0 host gates — BEFORE any mutation (state write, clone, venv,
360
+ // model downloads) ─────────────────────────────────────────────
361
+ // Ownership mixing: never let a sudo re-run lock a normal user out of
362
+ // their own home directory (or resume another uid's installation).
363
+ const currentUid = options.currentUid !== undefined ? options.currentUid : prereq.currentUid();
364
+ const home = options.home !== undefined ? options.home : prereq.currentHome();
365
+ const ownership = prereq.checkOwnership(io, {
366
+ paths: [comfyuiRoot, statePath, workerDir, toolsDir].filter(Boolean),
367
+ home,
368
+ currentUid,
369
+ stateUid: st.owner_uid != null ? st.owner_uid : null,
370
+ });
371
+ if (!ownership.ok) {
372
+ result.status = 'blocked';
373
+ for (const v of ownership.violations) {
374
+ result.blocked.push({ step: 'ownership', reason: v.message });
375
+ log.error(v.message);
376
+ }
377
+ return result;
378
+ }
379
+ if (st.owner_uid == null && currentUid != null) st.owner_uid = currentUid;
380
+
381
+ // Python runtime prerequisites (venv/ensurepip/pip) — must be verified
382
+ // before creating or modifying anything, let alone downloading models.
383
+ const torchEntryEarly = report.entries.find((e) => e.id === 'runtime:torch');
384
+ const pythonEntryEarly = report.entries.find((e) => e.id === 'runtime:python');
385
+ const needRuntimeEarly = [torchEntryEarly, pythonEntryEarly].some((e) => e && (e.status === 'missing' || e.status === 'incompatible'));
386
+ if (needRuntimeEarly) {
387
+ const gate = prereq.checkPythonPrerequisites(io, {
388
+ python: (env.python && env.python.binary) || 'python3',
389
+ tmpRoot: options.prereqTmpRoot || null,
390
+ deep: true,
391
+ existingVenvDir: path.join(comfyuiRoot, 'venv'),
392
+ });
393
+ if (!gate.ok) {
394
+ state.setArtifact(st, 'runtime', 'failed', { reason: gate.failure.code });
395
+ save();
396
+ result.status = 'failed';
397
+ result.remediation = prereq.remediationPayload(gate.failure);
398
+ result.blocked.push({ step: 'runtime', reason: gate.failure.message });
399
+ for (const line of prereq.renderRemediation(gate.failure)) log.error(line);
400
+ return result;
401
+ }
402
+ }
403
+
404
+ // Ctrl+C: mark interrupted state + partial artifact, save, exit 130.
405
+ let currentArtifactId = null;
406
+ let removeInterruptGuard = null;
407
+ if (options.interruptGuard !== false) {
408
+ removeInterruptGuard = createInterruptGuard({
409
+ state: st, save, log,
410
+ getArtifactId: () => currentArtifactId,
411
+ });
412
+ }
413
+
414
+ try {
415
+ save();
416
+
417
+ // 4.1 ComfyUI -----------------------------------------------------------
418
+ const comfyStep = stepById(plan, 'comfyui-update');
419
+ if (comfyStep && comfyStep.abort) {
420
+ result.status = 'aborted';
421
+ result.blocked.push({ step: 'comfyui-update', reason: comfyStep.abort_reason });
422
+ return result;
423
+ }
424
+ if (comfyStep && comfyStep.action) {
425
+ const op = comfyStep.action.op;
426
+ if (op === 'install_comfyui') {
427
+ const src = comfyui.pickInstallSource(manifests[0]);
428
+ if (!src) {
429
+ result.blocked.push({ step: 'comfyui-update', reason: 'no canonical ComfyUI pin and no known-working reference in the manifest — nothing to install (D1 research pending)' });
430
+ } else if (src.needs_consent && decisions.accept_reference_runtime !== true) {
431
+ result.blocked.push({
432
+ step: 'comfyui-update',
433
+ reason: `canonical ComfyUI pin is unknown (D1); the known-working reference is ${src.source.repository} @ ${src.source.commit || src.source.tag} — confirm accept_reference_runtime to install it`,
434
+ });
435
+ } else {
436
+ const r = await log.step('install ComfyUI', () => withBusySync('Cloning ComfyUI', () => comfyui.installComfyUI(io, { root: comfyuiRoot, source: src.source, log })));
437
+ result.results.comfyui = r.ok ? { op, grade: src.grade, ...r.value } : { op, failed: String(r.error && r.error.message) };
438
+ if (!r.ok) result.warnings.push(`ComfyUI install failed: ${r.error && r.error.message}`);
439
+ // installComfyUI refuses non-empty targets — success ⇒ the
440
+ // installer created this root and owns it.
441
+ st.components.comfyui = r.ok
442
+ ? { owned: true, path: comfyuiRoot, ref: src.source.commit || src.source.tag || null }
443
+ : st.components.comfyui;
444
+ state.setArtifact(st, 'comfyui', r.ok ? 'installed' : 'failed', { ref: src.source.commit || src.source.tag });
445
+ save();
446
+ }
447
+ } else if (op === 'update_comfyui' || op === 'downgrade_comfyui') {
448
+ const gate = confirmationGate(op, { confirmed: true, op, via: 'install-plan' });
449
+ if (!gate.allowed) {
450
+ result.blocked.push({ step: 'comfyui-update', reason: gate.reason });
451
+ } else {
452
+ const target = pickUpdateTarget(manifests[0]);
453
+ const busyLabel = op === 'downgrade_comfyui' ? 'Downgrading ComfyUI' : 'Updating ComfyUI';
454
+ const r = await log.step(`${op} ComfyUI`, () => withBusySync(busyLabel, () => comfyui.updateComfyUI(io, { root: comfyuiRoot, target, state: st, log })));
455
+ result.results.comfyui = r.ok ? { op, ...r.value } : { op, failed: String(r.error && r.error.message) };
456
+ // An updated/downgraded ComfyUI pre-existed — record ownership
457
+ // honestly so the uninstaller never removes it wholesale.
458
+ if (r.ok && !st.components.comfyui) {
459
+ st.components.comfyui = { owned: false, path: comfyuiRoot };
460
+ }
461
+ if (r.ok) save();
462
+ }
463
+ }
464
+ }
465
+ if (comfyStep && comfyStep.continue_at_own_risk) {
466
+ result.warnings.push('continuing with a ComfyUI newer than the tested maximum — at the user\'s own risk (recorded)');
467
+ }
468
+ if (!st.components.comfyui && env.comfyui && env.comfyui.present) {
469
+ st.components.comfyui = { owned: false, path: comfyuiRoot };
470
+ save();
471
+ }
472
+
473
+ // 4.2 Python runtime / torch (managed, or when missing) ------------------
474
+ // Never touch an EXISTING working Python/Torch/CUDA setup without an
475
+ // explicit user decision: `accept_runtime_change`. An incompatible
476
+ // runtime OUTSIDE the managed venv (system python) does not block: the
477
+ // installer creates an ISOLATED venv and never modifies the system
478
+ // runtime. Only replacing an already-present venv needs consent.
479
+ //
480
+ // Failure semantics: when the runtime cannot be prepared (no venv, no
481
+ // pip, broken venv that cannot be repaired) the installation is in an
482
+ // unrecoverable state — every dependent step (custom nodes, model
483
+ // downloads, ComfyUI start) is SKIPPED, never ploughed through.
484
+ let runtimeFatal = false;
485
+ const torchEntry = report.entries.find((e) => e.id === 'runtime:torch');
486
+ const pythonEntry = report.entries.find((e) => e.id === 'runtime:python');
487
+ const needRuntime = [torchEntry, pythonEntry].some((e) => e && (e.status === 'missing' || e.status === 'incompatible'));
488
+ if (needRuntime && io.fs.existsSync(comfyuiRoot)) {
489
+ const hasManagedVenv = io.fs.existsSync(platformAdapter.venvPythonBin(path.join(comfyuiRoot, 'venv')));
490
+ const presentRuntime = [torchEntry, pythonEntry].some((e) => e && e.status === 'incompatible');
491
+ if (presentRuntime && hasManagedVenv && decisions.accept_runtime_change !== true) {
492
+ result.blocked.push({
493
+ step: 'runtime',
494
+ reason: 'the managed venv runtime does not match the profile requirements. The installer will NOT replace it without an explicit accept_runtime_change decision.',
495
+ });
496
+ state.setArtifact(st, 'runtime', 'failed', { reason: 'runtime change not accepted' });
497
+ save();
498
+ } else {
499
+ if (presentRuntime && !hasManagedVenv) {
500
+ result.warnings.push(`the system Python/Torch runtime (outside the managed venv) does not match the profile requirement — the installer creates an isolated venv and does NOT modify the system runtime`);
501
+ }
502
+ const torchSpec = pickTorchSpec(manifests, decisions, result.warnings, device);
503
+ if (torchEntry && torchEntry.status === 'missing' && !torchSpec) {
504
+ result.blocked.push({ step: 'runtime', reason: 'torch requirement cannot be satisfied: no canonical pin and reference not accepted' });
505
+ } else {
506
+ const r = await log.step('prepare Python runtime', () => withBusy('Installing Python runtime', () => comfyui.preparePythonRuntime(io, {
507
+ root: comfyuiRoot,
508
+ torchSpec: torchSpec ? torchSpec.spec : null,
509
+ log,
510
+ term,
511
+ platformAdapter,
512
+ })));
513
+ result.results.runtime = r.ok ? { device, grade: torchSpec ? torchSpec.grade : null, ...r.value } : { failed: String(r.error && r.error.message) };
514
+ if (r.ok) {
515
+ // The venv under the ComfyUI root is created by this
516
+ // installer run — always ours (even inside a pre-existing
517
+ // root), so the uninstaller may remove it precisely.
518
+ st.components.venv = { owned: true, path: r.value.venv, created: r.value.venv_created };
519
+ if (torchSpec) st.torch = { device, grade: torchSpec.grade, pin: torchSpec.spec.pin };
520
+ if (r.value.quarantined_broken_venv) {
521
+ result.warnings.push(`a broken venv was found at ${r.value.venv} and moved aside to ${r.value.quarantined_broken_venv} — a fresh venv was created`);
522
+ }
523
+ } else {
524
+ runtimeFatal = true;
525
+ const err = r.error;
526
+ if (err && err.name === 'PrerequisiteError') {
527
+ result.remediation = {
528
+ code: err.code,
529
+ summary: err.summary,
530
+ package: err.hostPackage,
531
+ command: err.remediationCommand,
532
+ };
533
+ for (const line of prereq.renderRemediation(err)) log.error(line);
534
+ }
535
+ }
536
+ state.setArtifact(st, 'runtime', r.ok ? 'installed' : 'failed', {});
537
+ if (!r.ok) result.warnings.push(`python runtime preparation failed: ${r.error && r.error.message}`);
538
+ save();
539
+ }
540
+ }
541
+ } else if (!runtimeFatal && io.fs.existsSync(platformAdapter.venvPythonBin(path.join(comfyuiRoot, 'venv')))) {
542
+ // Runtime looks complete (torch+python already present — e.g. an
543
+ // ADOPTED ComfyUI), so the full prepare step was skipped. The fork's
544
+ // own requirements may still be missing from the old venv (the
545
+ // ComfyUI process crashes on import otherwise) — and unpinned
546
+ // torchvision/torchaudio edges must not drift off the installed
547
+ // torch ABI. Idempotent sync constrained to the torch family.
548
+ const torchSpec = pickTorchSpec(manifests, decisions, result.warnings, device);
549
+ const r = await log.step('sync ComfyUI requirements', () => withBusy('Installing ComfyUI requirements', () => comfyui.syncComfyUIRequirements(io, {
550
+ root: comfyuiRoot, torchSpec: torchSpec ? torchSpec.spec : null, log, term,
551
+ })));
552
+ if (!r.ok) result.warnings.push(`ComfyUI requirements sync failed: ${r.error && r.error.message}`);
553
+ }
554
+
555
+ // Dependent-step gating: a failed runtime stops everything that needs it.
556
+ if (runtimeFatal) {
557
+ const nodesStepG = stepById(plan, 'custom-nodes');
558
+ if (nodesStepG && nodesStepG.action && nodesStepG.decision === 'yes') {
559
+ log.warn('skipping "install custom nodes": Python runtime preparation failed');
560
+ result.blocked.push({ step: 'custom-nodes', reason: 'skipped — Python runtime preparation failed (fix the prerequisite above and re-run)' });
561
+ for (const item of nodesStepG.missing || []) {
562
+ state.setArtifact(st, item.id, 'missing', { reason: 'skipped — Python runtime preparation failed' });
563
+ }
564
+ save();
565
+ }
566
+ const modelsStepG = stepById(plan, 'models');
567
+ if (modelsStepG && modelsStepG.action && modelsStepG.decision === 'yes') {
568
+ log.warn('skipping model downloads: Python runtime preparation failed');
569
+ result.blocked.push({ step: 'models', reason: 'skipped — Python runtime preparation failed (no multi-GB downloads in a broken installation)' });
570
+ for (const item of modelsStepG.missing || []) {
571
+ state.setArtifact(st, item.id, 'missing', { reason: 'skipped — Python runtime preparation failed' });
572
+ }
573
+ save();
574
+ }
575
+ }
576
+
577
+ // 4.3 Custom nodes --------------------------------------------------------
578
+ const nodesStep = stepById(plan, 'custom-nodes');
579
+ // Nodes an earlier run left with "python dependencies incomplete" get
580
+ // an idempotent pip retry. This MUST also run when the plan step is a
581
+ // noop: the resolver keys node presence off the directory, so a
582
+ // present-but-broken node produces no install action and without this
583
+ // pass the broken state would never heal (ComfyUI logs IMPORT FAILED
584
+ // and /object_info lacks the node classes).
585
+ const retryDeps = Object.keys(st.artifacts || {}).filter((id) => {
586
+ const a = st.artifacts[id];
587
+ return !!(a && a.detail && /python dependencies incomplete/.test(a.detail.reason || ''));
588
+ });
589
+ const nodesApproved = !runtimeFatal && nodesStep && nodesStep.action && nodesStep.decision === 'yes';
590
+ if (!runtimeFatal && (nodesApproved || retryDeps.length > 0)) {
591
+ const python = platformAdapter.venvPythonBin(path.join(comfyuiRoot, 'venv'));
592
+ // Check for C build tools (gcc, python3-dev, libsndfile1-dev) that
593
+ // packages like funasr/soundfile need. Missing tools produce opaque
594
+ // metadata-generation-failed errors from pip — catch early and give
595
+ // a precise remediation command. (Which tools/packages to check is
596
+ // a platform concern — the adapter answers it.)
597
+ const buildCheck = platformAdapter.checkBuildPrerequisites(io, {
598
+ python: io.fs.existsSync(python) ? python : 'python3', log,
599
+ });
600
+ if (!buildCheck.ok) {
601
+ result.remediation = {
602
+ code: 'MISSING_BUILD_TOOLS',
603
+ summary: buildCheck.message,
604
+ package: buildCheck.remediation.package,
605
+ command: buildCheck.remediation.command,
606
+ };
607
+ }
608
+ const approvedIds = ((nodesStep && nodesStep.missing) || []).map((x) => x.id);
609
+ const repairOnlyIds = retryDeps.filter((id) => !approvedIds.includes(id));
610
+ const effectiveStep = nodesApproved
611
+ ? { ...nodesStep, missing: [...(nodesStep.missing || []), ...repairOnlyIds.map((id) => ({ id }))] }
612
+ : {
613
+ ...(nodesStep || { id: 'custom-nodes', title: 'Custom nodes' }),
614
+ missing: retryDeps.map((id) => ({ id })),
615
+ review: [],
616
+ };
617
+ const nodeTorchSpec = pickTorchSpec(manifests, decisions, result.warnings, device);
618
+ const r = await log.step('install custom nodes', () => withBusySync('Installing custom nodes', () => nodes.installCustomNodes(io, {
619
+ root: comfyuiRoot, manifests, planStep: effectiveStep,
620
+ python: io.fs.existsSync(python) ? python : null,
621
+ torchSpec: nodeTorchSpec ? nodeTorchSpec.spec : null,
622
+ retryDeps, log,
623
+ })));
624
+ result.results.custom_nodes = r.ok ? r.value : [{ status: 'failed', reason: String(r.error && r.error.message) }];
625
+ for (const item of result.results.custom_nodes) {
626
+ // Only directories the installer actually created are ours.
627
+ if (item.status === 'installed' && item.origin === 'installed' && item.directory) {
628
+ state.addOwnedComponent(st, 'custom_nodes', { id: item.id, path: path.join(comfyuiRoot, 'custom_nodes', item.directory) });
629
+ }
630
+ state.setArtifact(st, item.id, item.status === 'installed' ? 'installed' : item.status === 'failed' ? 'failed' : 'missing', { reason: item.reason || null });
631
+ }
632
+ save();
633
+ // ComfyUI imports custom nodes ONLY at startup. When this run
634
+ // actually changed a node (fresh clone or repaired deps — both
635
+ // report no reason), restart the managed instance so the live
636
+ // /object_info registry reflects the files on disk; otherwise
637
+ // verification below would check a stale process and fail.
638
+ const nodesChanged = result.results.custom_nodes.some((x) => x.status === 'installed' && !x.reason);
639
+ if (nodesChanged && options.startComfyui !== false) {
640
+ const port = options.comfyPort || 8188;
641
+ const rr = await log.step('restart ComfyUI', () => withBusy('Waiting for ComfyUI to restart', () => comfyui.restartManagedComfyUI(io, {
642
+ root: comfyuiRoot, port, device, log,
643
+ verifyTimeoutMs: options.verifyTimeoutMs || 120000,
644
+ pollIntervalMs: options.pollIntervalMs || 2000,
645
+ })));
646
+ const res = rr.ok ? rr.value : null;
647
+ if (res && res.restarted && res.up) {
648
+ st.comfyui_runtime = { port, pid: res.pid, started_at: io.now() };
649
+ log.info('ComfyUI restarted — custom node registry refreshed');
650
+ save();
651
+ } else if (res && res.restarted) {
652
+ log.warn(`ComfyUI restart did not come up cleanly: ${res.reason}`);
653
+ } else {
654
+ const why = res ? res.reason : String(rr.error && rr.error.message);
655
+ log.warn(`custom nodes changed but the managed ComfyUI was not restarted (${why}) — restart it manually so the new nodes are imported`);
656
+ }
657
+ }
658
+ }
659
+
660
+ // 4.4 Models ---------------------------------------------------------------
661
+ const modelsStep = stepById(plan, 'models');
662
+ if (!runtimeFatal && modelsStep && modelsStep.action && modelsStep.decision === 'yes') {
663
+ const getHeader = downloader.makeHeaderProvider(process.env);
664
+ const missingIds = (modelsStep.missing || []).map((x) => x.id);
665
+ const hasHfToken = !!(process.env.HF_TOKEN || process.env.HUGGINGFACE_HUB_TOKEN);
666
+ const specs = manifests.flatMap((m) => planModelDownloads(m, missingIds, { hasHfToken }));
667
+ // User-visible download progress: ONE in-place status line (file,
668
+ // bytes, %, speed, ETA, repo aggregate) on a TTY; throttled plain
669
+ // lines otherwise. `term` is the shared terminal renderer so the
670
+ // progress line and installer status share one stream and never
671
+ // overwrite each other. Inert until a download feeds it chunks.
672
+ const progress = createProgressReporter({
673
+ isTTY: options.progressIsTTY !== undefined ? !!options.progressIsTTY
674
+ : (typeof process !== 'undefined' && process.stdout ? !!process.stdout.isTTY : false),
675
+ log,
676
+ now: io.now,
677
+ term: options.term || null,
678
+ });
679
+ for (const spec of specs) {
680
+ const dep = findModelDep(manifests, spec.id);
681
+ const absTarget = path.join(comfyuiRoot, spec.target_path);
682
+ const existedBefore = io.fs.existsSync(absTarget);
683
+ currentArtifactId = spec.id; // SIGINT marks THIS artifact partial
684
+ if (dep && dep.kind === 'model_repo' && dep.source && dep.source.kind === 'modelscope') {
685
+ const strategy = downloader.modelscopeStrategy(dep);
686
+ if (strategy.mechanism === 'node_auto_download') {
687
+ result.results.models.push({ id: spec.id, status: 'deferred-to-node', reason: strategy.note });
688
+ state.setArtifact(st, spec.id, 'missing', { note: strategy.note });
689
+ } else if (strategy.mechanism === 'installer_preload') {
690
+ // D2 closed: installer pre-downloads ModelScope repos
691
+ // Use dedicated ModelScope snapshot download (not single-file downloadArtifact)
692
+ const expectedFiles = dep.expected_files || null;
693
+ const checksums = null; // ModelScope checksums not yet in manifest; verified by size
694
+ const r = await log.step(`download model ${spec.id} (ModelScope)`, async () => downloader.downloadModelScopeRepo(io, spec, {
695
+ root: comfyuiRoot,
696
+ getHeader,
697
+ retries: options.downloadRetries || 3,
698
+ retryDelayMs: options.retryDelayMs || 500,
699
+ log,
700
+ expectedFiles,
701
+ checksums,
702
+ progress,
703
+ }));
704
+ const res = r.ok ? r.value : { status: 'failed', reason: String(r.error && r.error.message) };
705
+ const status = res.status === 'failed' ? 'failed' : res.status === 'skipped' ? 'verified' : 'installed';
706
+ result.results.models.push({ id: spec.id, ...res });
707
+ if (status === 'installed') {
708
+ state.addOwnedComponent(st, 'models', {
709
+ id: spec.id,
710
+ path: absTarget,
711
+ created: !existedBefore,
712
+ files: (res.files || []).map((f) => f.path),
713
+ });
714
+ }
715
+ state.setArtifact(st, spec.id, status, { reason: res.reason });
716
+ save();
717
+ continue; // skip the generic downloadArtifact below
718
+ } else {
719
+ result.results.models.push({ id: spec.id, status: 'blocked', reason: strategy.note });
720
+ state.setArtifact(st, spec.id, 'missing', { note: strategy.note });
721
+ }
722
+ if (strategy.mechanism !== 'installer_preload') continue;
723
+ }
724
+ const singleLabel = spec.target_path || spec.id;
725
+ if (progress && progress.beginFile) progress.beginFile(singleLabel, spec.size_bytes_approx || null);
726
+ const r = await log.step(`download model ${spec.id}`, async () => downloader.downloadArtifact(io, spec, {
727
+ root: comfyuiRoot,
728
+ getHeader,
729
+ retries: options.downloadRetries || 3,
730
+ retryDelayMs: options.retryDelayMs || 500,
731
+ log,
732
+ onProgress: progress && progress.onChunk ? (e) => progress.onChunk(e) : null,
733
+ }));
734
+ if (progress && progress.endFile) progress.endFile({ status: r.ok ? r.value.status : 'failed' });
735
+ const res = r.ok ? r.value : { status: 'failed', reason: String(r.error && r.error.message) };
736
+ result.results.models.push({ id: spec.id, ...res });
737
+ if (res.status === 'downloaded' || res.status === 'resumed') {
738
+ state.addOwnedComponent(st, 'models', {
739
+ id: spec.id,
740
+ path: absTarget,
741
+ created: !existedBefore,
742
+ });
743
+ }
744
+ state.setArtifact(st, spec.id, res.status === 'failed' ? 'failed'
745
+ : res.status === 'blocked' ? 'missing'
746
+ : res.status === 'skipped' ? 'verified'
747
+ : 'installed', { grade: res.grade, reason: res.reason });
748
+ save();
749
+ currentArtifactId = null;
750
+ }
751
+ }
752
+
753
+ // 4.5 Baseline workflows ------------------------------------------------------
754
+ const wfStep = stepById(plan, 'workflows');
755
+ if (wfStep && wfStep.action && wfStep.action.items && wfStep.action.items.length > 0) {
756
+ const hubFetchText = hubUrl && io.http && io.http.fetchText
757
+ ? (url) => io.http.fetchText(url)
758
+ : null;
759
+ const r = await log.step('install baseline workflows', async () => workflowsInstall.installWorkflows(io, {
760
+ root: comfyuiRoot, manifests, planStep: wfStep,
761
+ repoRoot, hubUrl, crypto, log,
762
+ httpFetchText: hubFetchText,
763
+ }));
764
+ result.results.workflows = r.ok ? r.value : [{ status: 'failed', reason: String(r.error && r.error.message) }];
765
+ for (const item of result.results.workflows) {
766
+ // Fresh copies written by the installer are ours; 'kept' files are
767
+ // the user's — never registered, never removed.
768
+ if ((item.status === 'installed' || item.status === 'fresh-copy-installed') && item.target_path) {
769
+ state.addOwnedComponent(st, 'workflows', { id: item.id, path: path.join(comfyuiRoot, item.target_path) });
770
+ }
771
+ state.setArtifact(st, item.id, item.status === 'installed' || item.status === 'fresh-copy-installed' ? 'verified' : item.status === 'kept' ? 'verified' : 'missing', { path: item.target_path, reason: item.reason });
772
+ }
773
+ save();
774
+ }
775
+
776
+ // 4.6 Worker bundle + .env --------------------------------------------------
777
+ const workerStep = stepById(plan, 'worker-setup');
778
+ if (workerStep && workerStep.action && workerStep.decision === 'yes') {
779
+ for (const w of workerStep.workers || []) {
780
+ const manifest = manifests.find((m) => `worker:${m.profile.id}` === w.id) || manifests[0];
781
+ const bundleRes = await log.step(`install worker bundle (${w.worker_type})`, async () => {
782
+ // The distributed installer package may not carry the
783
+ // worker bundle files. When the repo checkout is missing
784
+ // any of them, fetch the hub's sha256-verified worker
785
+ // bundle (GET /worker-bundle) and use it as copy source.
786
+ const wbFiles = ((manifest.worker_bundle || {}).files) || [];
787
+ const repoBundleDir = repoBundleSource.resolveRepoBundleDir(io.fs, repoRoot);
788
+ const missingFromRepo = wbFiles.filter((f) => !(repoBundleDir && io.fs.existsSync(path.join(repoBundleDir, f))));
789
+ let bundleDir = null;
790
+ let bundleTmp = null;
791
+ if (missingFromRepo.length > 0 && hubUrl) {
792
+ const fetched = await worker.fetchHubWorkerBundle(io, { hubUrl });
793
+ if (fetched.bundleDir) {
794
+ bundleDir = fetched.bundleDir;
795
+ bundleTmp = fetched.tmpDir;
796
+ log.info(`worker bundle files missing from the installer package — fetched from ${hubUrl}/worker-bundle (${missingFromRepo.length} file(s))`);
797
+ } else {
798
+ log.warn(`worker bundle fetch failed: ${fetched.reason}`);
799
+ }
800
+ }
801
+ try {
802
+ return withBusySync('Installing worker bundle', () => worker.installWorkerBundle(io, {
803
+ workerDir, manifest, repoRoot, bundleDir, hubUrl,
804
+ httpFetchText: null, log,
805
+ }));
806
+ } finally {
807
+ if (bundleTmp) {
808
+ try { io.fs.rmSync(bundleTmp, { recursive: true, force: true }); } catch (_) { /* best effort */ }
809
+ }
810
+ }
811
+ });
812
+ result.results.worker.push({ id: w.id, bundle: bundleRes.ok ? bundleRes.value : { status: 'failed', reason: String(bundleRes.error && bundleRes.error.message) } });
813
+ if (bundleRes.ok && bundleRes.value.status === 'installed') {
814
+ // Ownership is per-file: a pre-existing worker dir keeps its
815
+ // own files; only what the installer copied is registered.
816
+ st.components.worker = {
817
+ owned: bundleRes.value.dir_created === true,
818
+ dir: workerDir,
819
+ files_installed: bundleRes.value.files_installed || [],
820
+ files_kept: bundleRes.value.files_kept || [],
821
+ env_created: null, // finalized by the .env step below
822
+ };
823
+ }
824
+ state.setArtifact(st, w.id, bundleRes.ok && bundleRes.value.status === 'installed' ? 'installed' : 'failed');
825
+ save();
826
+ }
827
+ }
828
+
829
+ // 4.7 Worker Key + .env configuration ----------------------------------------
830
+ // Runs on EVERY install where the worker is wanted — even full re-runs
831
+ // whose plan has no worker-key step (nothing left to ask). configureEnv
832
+ // merges (never overwrites), and runtime settings like COMFY_PORT must
833
+ // reach .env on every run: otherwise an already-running worker keeps
834
+ // its stale wiring forever.
835
+ const keyStep = stepById(plan, 'worker-key');
836
+ const workerWanted = decisions.worker_setup === true || decisions.worker_setup === 'yes'
837
+ || (keyStep && (keyStep.provided || decisions.worker_key_provided === true));
838
+ let tokenValue = null; // held in memory only; never stored on result/state
839
+ if (workerWanted) {
840
+ const manifest = manifests[0];
841
+ const required = ((manifest.worker_bundle || {}).env || {}).required || [];
842
+ const values = {};
843
+ for (const key of (keyStep && keyStep.secret_keys) || []) {
844
+ if (secretProvider) {
845
+ const value = await secretProvider(key);
846
+ if (value) {
847
+ log.registerSecret(value); // redact from ALL further output
848
+ values[key] = value;
849
+ if (key === 'ANIMASTOR_WORKER_TOKEN') tokenValue = value;
850
+ }
851
+ }
852
+ }
853
+ for (const key of required) {
854
+ if (values[key] === undefined && !key.includes('TOKEN')) {
855
+ values[key] = defaultEnvValue(key, { hubUrl, manifests });
856
+ }
857
+ }
858
+ // Point the worker at the ComfyUI port chosen for this install
859
+ // (--comfy-port). Shared hosts often run several ComfyUI
860
+ // instances; the default 8188 may belong to a different one.
861
+ if (options.comfyPort) values.COMFY_PORT = String(options.comfyPort);
862
+ const cfg = await log.step('configure worker .env', async () => worker.configureEnv(io, { workerDir, manifest, values, log }));
863
+ result.results.worker.push({ id: 'env', config: cfg.ok ? cfg.value : { status: 'failed', reason: String(cfg.error && cfg.error.message) } });
864
+ if (cfg.ok && st.components.worker) {
865
+ st.components.worker.env_created = cfg.value.created === true;
866
+ } else if (cfg.ok) {
867
+ st.components.worker = {
868
+ owned: false, dir: workerDir, files_installed: [], files_kept: [],
869
+ env_created: cfg.value.created === true,
870
+ };
871
+ }
872
+ state.setArtifact(st, 'env', cfg.ok && cfg.value.status === 'configured' ? 'installed' : 'partial', {});
873
+ save();
874
+ }
875
+
876
+ // 4.8 Worker start (managed-mode default / --start-worker) --------
877
+ // A fatal runtime failure leaves the install unrecoverable — every
878
+ // dependent step (including daemon starts) is SKIPPED, never ploughed
879
+ // through behind a broken ComfyUI.
880
+ let startedWorkerPid = null;
881
+ if (options.startWorker && workerDir && !runtimeFatal) {
882
+ const r = await log.step('start worker', async () => worker.startWorker(io, { workerDir }));
883
+ const res = r.ok ? r.value : { started: false, alive: false, reason: String(r.error && r.error.message) };
884
+ result.results.worker.push({ id: 'worker-process', ...res });
885
+ if (res.started && res.alive) {
886
+ startedWorkerPid = res.pid;
887
+ if (res.already_running) log.info(`worker already running (pid ${res.pid}) — not spawning a second instance`);
888
+ state.setArtifact(st, 'worker-process', 'installed', { pid: res.pid });
889
+ } else {
890
+ state.setArtifact(st, 'worker-process', 'failed', { reason: res.reason || null });
891
+ result.warnings.push(`worker did not start: ${res.reason || 'unknown reason'}`);
892
+ }
893
+ save();
894
+ }
895
+
896
+ // 4.9 Verification --------------------------------------------------------------
897
+ // A fatal runtime failure means ComfyUI cannot start — skip the live
898
+ // start step entirely (it would only spawn a doomed process).
899
+ const ver = await runVerification({
900
+ io, manifests, roots: { comfyuiRoot, workerDir, hubUrl },
901
+ options: { ...options, startComfyui: runtimeFatal ? false : options.startComfyui },
902
+ log, crypto,
903
+ tokenValue,
904
+ device,
905
+ workerPid: startedWorkerPid,
906
+ onEvent: (kind, value) => { result.results[kind] = value; },
907
+ });
908
+ result.verification = ver;
909
+ // Record the instance this installer started so future runs reuse its
910
+ // port instead of auto-picking a new one (the runVerification scope
911
+ // has no state — the start step reports via the comfyui_started event).
912
+ const startedEv = result.results.comfyui_started;
913
+ if (startedEv && startedEv.port) {
914
+ st.comfyui_runtime = { port: startedEv.port, pid: startedEv.pid, started_at: io.now() };
915
+ save();
916
+ }
917
+
918
+ // 4.10 Management tools ---------------------------------------------------
919
+ // Optional component (install decision install_management_tools). The
920
+ // tools are thin wrappers around this CLI's management commands — the
921
+ // runtime logic is shared (management.js), never duplicated. Installing
922
+ // is idempotent: a re-run overwrites the same files (no duplicates) and
923
+ // the files are registered as owned so the uninstaller removes them
924
+ // precisely. A tools failure must never fail the installation itself.
925
+ if (decisions.install_management_tools === true && toolsDir && !dryRun) {
926
+ try {
927
+ const r = await log.step('install management tools', async () => withBusySync('Installing management tools', () => management.installManagementTools(io, {
928
+ toolsDir,
929
+ nodePath: process.execPath,
930
+ cliPath: path.join(__dirname, '..', 'cli.js'),
931
+ statePath,
932
+ root: comfyuiRoot,
933
+ workerDir,
934
+ log,
935
+ platformAdapter,
936
+ })));
937
+ // log.step wraps the callback result in { ok, value, error } —
938
+ // the tools result itself is r.value (an unwrapped r.files here
939
+ // was a latent bug: tools were never installed by real runs).
940
+ if (r.ok && r.value) {
941
+ result.results.management_tools = r.value;
942
+ for (const f of r.value.files) {
943
+ state.addOwnedComponent(st, 'services', { id: 'management-tools', path: f });
944
+ }
945
+ state.setArtifact(st, 'management-tools', 'installed', { dir: r.value.toolsDir });
946
+ } else {
947
+ const reason = r.error && r.error.message ? r.error.message : 'unknown failure';
948
+ result.warnings.push(`management tools could not be installed: ${reason}`);
949
+ state.setArtifact(st, 'management-tools', 'failed', { reason });
950
+ }
951
+ save();
952
+ } catch (err) {
953
+ result.warnings.push(`management tools could not be installed: ${err.message}`);
954
+ state.setArtifact(st, 'management-tools', 'failed', { reason: err.message });
955
+ save();
956
+ }
957
+ }
958
+
959
+ if (runtimeFatal) {
960
+ result.status = 'failed';
961
+ } else {
962
+ const blockedCount = result.blocked.length + result.results.models.filter((m) => m.status === 'blocked').length;
963
+ if (result.blocked.length > 0 || blockedCount > 0) result.status = 'blocked';
964
+ else if (ver.status === 'FAIL') result.status = 'failed';
965
+ else if (ver.status === 'WARN') result.status = 'warn';
966
+ else result.status = 'ready';
967
+ }
968
+
969
+ if (removeInterruptGuard) removeInterruptGuard();
970
+ save();
971
+ return result;
972
+ } finally {
973
+ if (removeInterruptGuard) removeInterruptGuard();
974
+ }
975
+ }
976
+
977
+ function pickUpdateTarget(manifest) {
978
+ const spec = (manifest.runtime_requirements || {}).comfyui || {};
979
+ if (spec.pin && (spec.pin.commit || spec.pin.tag)) return spec.pin;
980
+ if (spec.known_working_reference) return spec.known_working_reference;
981
+ throw new Error('no update target in manifest');
982
+ }
983
+
984
+ function findModelDep(manifests, id) {
985
+ for (const m of manifests) {
986
+ const dep = (m.dependencies || []).find((d) => d.id === id);
987
+ if (dep) return dep;
988
+ }
989
+ return null;
990
+ }
991
+
992
+ function defaultEnvValue(key, { hubUrl, manifests }) {
993
+ if (key === 'HUB_URL') return hubUrl || 'https://animastor.in/gpu';
994
+ if (key === 'WORKER_TYPE') return (manifests[0].worker_bundle || {}).worker_type || 'image';
995
+ if (key === 'WORKER_ID') return `gpu-${Date.now().toString(36)}`;
996
+ return '';
997
+ }
998
+
999
+ // ---------------------------------------------------------------------------
1000
+ // Verification (live checks where possible)
1001
+ // ---------------------------------------------------------------------------
1002
+
1003
+ async function runVerification({ io, manifests, roots, options, log, crypto, tokenValue = null, device = null, workerPid = null, onEvent = null }) {
1004
+ const emit = (kind, value) => { if (onEvent) onEvent(kind, value); };
1005
+ const { comfyuiRoot, workerDir, hubUrl } = roots;
1006
+ const live = {};
1007
+
1008
+ // ComfyUI live check: use an already-running instance, or start one in
1009
+ // managed mode (files on disk are NOT sufficient verification).
1010
+ const port = options.comfyPort || 8188;
1011
+ const baseUrl = `http://127.0.0.1:${port}`;
1012
+ const withBusy = (label, fn, o) => (options.term ? options.term.withBusy(label, fn, o) : fn());
1013
+ let stats = await comfyui.systemStats(io, baseUrl);
1014
+ if (!stats && options.startComfyui && io.fs.existsSync(comfyuiRoot)) {
1015
+ const started = await log.step('start ComfyUI', () => withBusy('Starting ComfyUI', async () => {
1016
+ const { pid } = comfyui.startComfyUI(io, { root: comfyuiRoot, port, device });
1017
+ const up = await comfyui.waitForApi(io, baseUrl, { timeoutMs: options.verifyTimeoutMs || 120000, intervalMs: options.pollIntervalMs || 2000 });
1018
+ return { pid, up };
1019
+ }));
1020
+ if (started.ok && started.value.up.ok) {
1021
+ stats = started.value.up.system_stats;
1022
+ emit('comfyui_started', { pid: started.value.pid, port });
1023
+ } else {
1024
+ live.comfyui = { running: false, api_reachable: false };
1025
+ }
1026
+ }
1027
+ if (stats) {
1028
+ live.comfyui = { running: true, api_reachable: true };
1029
+ const classes = await comfyui.objectInfoClasses(io, baseUrl);
1030
+ if (classes) {
1031
+ const manifestClasses = new Set();
1032
+ for (const m of manifests) {
1033
+ for (const dep of m.dependencies || []) {
1034
+ for (const cls of dep.provides_classes || []) manifestClasses.add(cls);
1035
+ }
1036
+ }
1037
+ const missingClasses = Array.from(manifestClasses).filter((c) => !classes.has(c));
1038
+ if (missingClasses.length > 0) live.comfyui.missing_node_classes = missingClasses;
1039
+ }
1040
+ // workflow static validation (no generation) — only meaningful when
1041
+ // at least one OPTIONAL profile workflow copy is actually installed;
1042
+ // absent optional copies are never checked and never reported as a
1043
+ // problem (Animastor sends workflow JSON with each task via the API)
1044
+ if (crypto) {
1045
+ const wfProblems = [];
1046
+ let wfChecked = 0;
1047
+ for (const m of manifests) {
1048
+ for (const wf of (m.workflows && m.workflows.artifacts) || []) {
1049
+ const abs = path.join(comfyuiRoot, `${wf.target_dir}/${wf.filename}`);
1050
+ if (!io.fs.existsSync(abs)) continue;
1051
+ wfChecked += 1;
1052
+ try {
1053
+ const problems = comfyui.validateWorkflowStatic(io.fs.readFileSync(abs, 'utf8'), { availableClasses: null });
1054
+ if (problems.parse_error) wfProblems.push(`${wf.filename}: ${problems.parse_error}`);
1055
+ } catch (_) { /* unreadable */ }
1056
+ }
1057
+ }
1058
+ if (wfChecked > 0) live.workflow = { accepted: wfProblems.length === 0, problems: wfProblems };
1059
+ }
1060
+ } else if (!live.comfyui) {
1061
+ live.comfyui = { running: false, api_reachable: false };
1062
+ }
1063
+
1064
+ // Worker registration check
1065
+ const manifest = manifests[0];
1066
+ const expectedType = (manifest.worker_bundle || {}).worker_type || null;
1067
+ let token = tokenValue;
1068
+ if (!token && workerDir && io.fs.existsSync(path.join(workerDir, '.env'))) {
1069
+ token = readEnvValueLocal(io, workerDir, 'ANIMASTOR_WORKER_TOKEN');
1070
+ if (token && log.registerSecret) log.registerSecret(token);
1071
+ }
1072
+ if (hubUrl && token) {
1073
+ const reg = await worker.verifyRegistration(io, { hubUrl, token, expectedType });
1074
+ emit('registration', { registered: reg.registered, worker_id: reg.worker_id || null, worker_type: reg.worker_type || null, reason: reg.reason || null });
1075
+ live.worker = { process_alive: null, registered: reg.registered === true };
1076
+ live.hub = { connection: reg.reason ? reg.reason.indexOf('unreachable') === -1 : true, registration: reg.registered === true };
1077
+ if (!reg.registered) {
1078
+ log.warn('Installation completed locally, but Worker registration failed. The installed environment is intact — fix the credential/network and re-run `verify`.');
1079
+ }
1080
+ } else {
1081
+ const canStart = workerDir ? worker.checkWorkerCanStart(io, { workerDir }) : { ok: false, reason: 'worker dir missing' };
1082
+ live.worker = { process_alive: null, registered: null, can_start: canStart.ok };
1083
+ }
1084
+ // A worker started by this run is checked for real — a pid that died
1085
+ // before verification is a FAIL, never a silent pass.
1086
+ if (workerPid) {
1087
+ // Platform-appropriate liveness check (Linux: ps -o args= grep,
1088
+ // Windows: pid marker + tasklist).
1089
+ const adapter = platforms.getPlatformAdapter();
1090
+ const alive = typeof adapter.checkDaemonAlive === 'function'
1091
+ ? adapter.checkDaemonAlive(io, { pid: workerPid, workerDir })
1092
+ : (() => {
1093
+ const chkCmd = adapter.psCheckCommand(workerPid);
1094
+ const chk = io.exec(chkCmd.cmd, chkCmd.args);
1095
+ return chk.code === 0 && /worker\.cjs/.test(chk.stdout);
1096
+ })();
1097
+ live.worker = live.worker || {};
1098
+ live.worker.process_alive = alive;
1099
+ if (!alive) log.warn(`worker process (pid ${workerPid}) is not running — see the worker log`);
1100
+ }
1101
+
1102
+ // Re-probe disk state for the final report
1103
+ const envAfter = probe.probeEnvironment(io, { root: comfyuiRoot, workerDir, crypto, workerType: expectedType });
1104
+ const reportAfter = require('../compatibility-resolver').resolveInstallation({
1105
+ manifests, environment: envAfter, mode: manifests.length > 1 ? 'shared' : 'existing',
1106
+ });
1107
+ const ver = buildVerificationReport({ report: reportAfter, live });
1108
+ log.output(ver.text);
1109
+ return ver;
1110
+ }
1111
+
1112
+ /** Read one KEY value from the local .env (verification only; redacted). */
1113
+ function readEnvValueLocal(io, workerDir, key) {
1114
+ try {
1115
+ const text = io.fs.readFileSync(path.join(workerDir, '.env'), 'utf8');
1116
+ for (const line of text.split('\n')) {
1117
+ const m = new RegExp(`^${key}\\s*=\\s*(.*)$`).exec(line.trim());
1118
+ if (m) return m[1].trim() || null;
1119
+ }
1120
+ } catch (_) { /* no .env */ }
1121
+ return null;
1122
+ }
1123
+
1124
+ // ---------------------------------------------------------------------------
1125
+ // Service autostart + port selection (managed mode owns the whole stack)
1126
+ // ---------------------------------------------------------------------------
1127
+
1128
+ /**
1129
+ * Classify what listens on 127.0.0.1:<port>:
1130
+ * 'free' — nothing answers (connection refused / timeout)
1131
+ * 'comfyui' — a ComfyUI API (/system_stats → JSON with .system)
1132
+ * 'foreign' — something else answers
1133
+ * A FOREIGN service on the default port must never receive this install's
1134
+ * worker: shared hosts routinely run several users' ComfyUI instances.
1135
+ */
1136
+ async function comfyPortState(io, port) {
1137
+ try {
1138
+ const res = await io.http.fetchJson(`http://127.0.0.1:${port}/system_stats`, { signal: AbortSignal.timeout(2000) });
1139
+ if (res && res.status === 200 && res.json && res.json.system) return 'comfyui';
1140
+ return 'foreign';
1141
+ } catch (_) {
1142
+ return 'free';
1143
+ }
1144
+ }
1145
+
1146
+ /**
1147
+ * Pick the ComfyUI port for this install:
1148
+ * 1. a ComfyUI this installer started previously and still alive → keep it
1149
+ * 2. default 8188 when free → take it
1150
+ * 3. non-managed mode: the user's own ComfyUI on 8188 IS the target → use it
1151
+ * 4. otherwise the first free port in the managed range (8288+)
1152
+ */
1153
+ async function autoPickComfyPort(io, { st, mode, log }) {
1154
+ const rt = st.comfyui_runtime;
1155
+ if (rt && rt.port && await comfyPortState(io, rt.port) === 'comfyui') return rt.port;
1156
+ const s8188 = await comfyPortState(io, 8188);
1157
+ if (s8188 === 'free') return 8188;
1158
+ if (mode !== 'managed' && s8188 === 'comfyui') return 8188;
1159
+ for (const p of [8288, 8289, 8290, 8291]) {
1160
+ if (await comfyPortState(io, p) === 'free') {
1161
+ if (log) log.info(`port 8188 is occupied (${s8188}) — this install's ComfyUI will use port ${p}`);
1162
+ return p;
1163
+ }
1164
+ }
1165
+ return 8188;
1166
+ }
1167
+
1168
+ module.exports = {
1169
+ runInstallation,
1170
+ runVerification,
1171
+ pickTorchSpec,
1172
+ readEnvValueLocal,
1173
+ loadResumableState,
1174
+ renderResumeSummary,
1175
+ sanitizeDecisions,
1176
+ createInterruptGuard,
1177
+ comfyPortState,
1178
+ autoPickComfyPort,
1179
+ CPU_MODE_WARNING,
1180
+ };