@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,741 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Install Plan — Private Worker Installer Phase 1.5.
5
+ *
6
+ * Turns a resolver report into a sequential INTERACTIVE installation flow:
7
+ *
8
+ * 1 detect-gpu 7 custom-nodes (prompt)
9
+ * 2 detect-comfyui 8 models (prompt)
10
+ * 3 detect-runtime 9 workflows (selection prompt)
11
+ * 4 select-profiles 10 worker-setup
12
+ * 5 resolve-dependencies 11 worker-key (secret prompt, never logged)
13
+ * 6 comfyui-update 12 verify
14
+ *
15
+ * Profile workflows (step 9) are OPTIONAL demo/test artifacts: declining
16
+ * them never blocks the plan and never makes the installation incomplete —
17
+ * Animastor sends workflow JSON with each task via the ComfyUI API.
18
+ *
19
+ * The module is PURE: it builds the plan data structure and renders the
20
+ * human-readable plan text. It performs no I/O and no mutation. Steps that
21
+ * could disrupt the user's environment are gated:
22
+ * - the plan shows the user what will happen BEFORE anything changes;
23
+ * - prompts without a recorded decision leave the plan `awaiting_decision`;
24
+ * - destructive operations (ComfyUI update/downgrade, node checkout) are
25
+ * only admitted through safety-rules.confirmationGate with an explicit
26
+ * confirmation, and are never auto-executed;
27
+ * - the Worker Key is referenced by NAME only — its value never enters
28
+ * the plan, the rendered text, logs, or argv.
29
+ */
30
+
31
+ const { confirmationGate } = require('./safety-rules');
32
+ const { planWorkflowDownloads, summarizeWorkflowState } = require('./workflow-artifacts');
33
+ const { planModelDownloads, estimateMissingBytes } = require('./download-planner');
34
+ const { pickInstallSource } = require('./engine/comfyui');
35
+
36
+ function formatBytes(bytes) {
37
+ if (typeof bytes !== 'number' || bytes === 0) return '0 B';
38
+ const units = ['B', 'KB', 'MB', 'GB', 'TiB'];
39
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
40
+ return `${(bytes / (1024 ** i)).toFixed(i > 1 ? 1 : 0)} ${units[i]}`;
41
+ }
42
+
43
+ /** Canonical interactive flow step ids, in execution order. */
44
+ const FLOW_STEPS = Object.freeze([
45
+ 'detect-gpu',
46
+ 'detect-comfyui',
47
+ 'detect-runtime',
48
+ 'select-profiles',
49
+ 'resolve-dependencies',
50
+ 'comfyui-update',
51
+ 'custom-nodes',
52
+ 'models',
53
+ 'workflows',
54
+ 'worker-setup',
55
+ 'worker-key',
56
+ 'verify',
57
+ ]);
58
+
59
+ const RUNTIME_LABELS = Object.freeze({
60
+ comfyui: 'ComfyUI',
61
+ torch: 'Torch',
62
+ python: 'Python',
63
+ nodejs: 'Node.js',
64
+ });
65
+
66
+ function entryById(report, id) {
67
+ return report.entries.find((e) => e.id === id) || null;
68
+ }
69
+
70
+ function entryLabel(e) {
71
+ if (!e) return '?';
72
+ switch (e.kind) {
73
+ case 'runtime': return RUNTIME_LABELS[e.component] || e.component;
74
+ case 'workflow': return `${e.name || e.id} (optional profile workflow)`;
75
+ case 'worker': return `Animastor worker (${e.worker_type || 'unknown type'})`;
76
+ default: return e.name || e.id;
77
+ }
78
+ }
79
+
80
+ function actionLine(e) {
81
+ switch (e.kind) {
82
+ case 'custom_node': return `Install custom node ${e.name || e.id}`;
83
+ case 'model':
84
+ case 'model_repo': return `Download model ${e.name || e.id}`;
85
+ case 'workflow': return `Download optional profile workflow ${e.name || e.id}`;
86
+ case 'worker': return `Install Animastor worker bundle (${e.worker_type})`;
87
+ case 'runtime': return `Install ${RUNTIME_LABELS[e.component] || e.component}`;
88
+ default: return `Install ${e.id}`;
89
+ }
90
+ }
91
+
92
+ function foundLabel(e) {
93
+ if (!e || !e.found) return null;
94
+ if (e.kind === 'runtime' && e.component === 'comfyui') {
95
+ const f = e.found;
96
+ if (typeof f === 'string') return f;
97
+ return f.version || f.commit || 'present';
98
+ }
99
+ if (e.kind === 'runtime') {
100
+ return e.found.version || null;
101
+ }
102
+ return null;
103
+ }
104
+
105
+ // ---------------------------------------------------------------------------
106
+ // Step builders
107
+ // ---------------------------------------------------------------------------
108
+
109
+ function buildComfyuiStep(report, decisions, manifests = []) {
110
+ const comfy = entryById(report, 'runtime:comfyui');
111
+ const step = {
112
+ id: 'comfyui-update',
113
+ title: 'ComfyUI version policy',
114
+ kind: 'prompt',
115
+ entry: comfy ? comfy.id : null,
116
+ };
117
+ if (!comfy) {
118
+ step.kind = 'noop';
119
+ step.result = 'no ComfyUI entry in report';
120
+ return step;
121
+ }
122
+
123
+ if (comfy.status === 'installed') {
124
+ step.kind = 'noop';
125
+ step.result = `skip — ComfyUI ${foundLabel(comfy) || ''} accepted (${comfy.grade || 'canonical'})`.trim();
126
+ return step;
127
+ }
128
+
129
+ if (comfy.status === 'missing') {
130
+ // Managed install of the manifest source. When the manifest carries no
131
+ // canonical pin (decision D1 open) the only installable source is the
132
+ // known-working reference — and a reference is EVIDENCE, not a rule:
133
+ // it requires an explicit user decision (never silent, never automatic).
134
+ const src = manifests.length > 0 ? pickInstallSource(manifests[0]) : null;
135
+ if (src && src.needs_consent) {
136
+ const ref = src.source;
137
+ step.consent = 'accept_reference_runtime';
138
+ step.prompt = {
139
+ question: `The canonical ComfyUI version is not pinned yet (decision D1).\nThe known-working reference is ${ref.repository} @ ${ref.commit || ref.tag}.\nInstall this reference ComfyUI?`,
140
+ options: ['Yes', 'No'],
141
+ };
142
+ if (decisions.accept_reference_runtime === true) {
143
+ step.decision = 'yes';
144
+ step.action = { op: 'install_comfyui', destructive: false, requires_confirmation: false };
145
+ step.result = 'user accepted the known-working reference ComfyUI (recorded)';
146
+ } else if (decisions.accept_reference_runtime === false) {
147
+ step.decision = 'no';
148
+ step.abort = true;
149
+ step.abort_reason = 'user declined the reference ComfyUI — nothing can be installed (canonical pin is unknown, D1); nothing was changed';
150
+ step.result = 'keep the machine without ComfyUI; abort (fail-closed)';
151
+ } else {
152
+ step.awaiting_decision = true;
153
+ }
154
+ return step;
155
+ }
156
+ step.kind = 'action';
157
+ step.action = { op: 'install_comfyui', destructive: false, requires_confirmation: false };
158
+ step.result = 'ComfyUI absent — installer will clone the manifest version (managed environment)';
159
+ return step;
160
+ }
161
+
162
+ const found = foundLabel(comfy) || 'unknown version';
163
+ const expected = Array.isArray(comfy.expected) ? comfy.expected.join(' or ') : String(comfy.expected || 'the pinned version');
164
+
165
+ if (comfy.status === 'incompatible' && comfy.reason === 'below_minimum') {
166
+ step.prompt = {
167
+ question: `ComfyUI ${found} detected.\nRecommended version: ${expected}.\n\nUpdate?`,
168
+ options: ['Yes', 'No'],
169
+ };
170
+ if (decisions.comfyui_update === 'yes') {
171
+ const gate = confirmationGate('update_comfyui', { confirmed: true, op: 'update_comfyui', via: 'interactive-prompt' });
172
+ step.decision = 'yes';
173
+ step.action = { op: 'update_comfyui', destructive: true, requires_confirmation: true, allowed: gate.allowed };
174
+ step.result = 'user approved the ComfyUI update — checkpoint state before executing';
175
+ } else if (decisions.comfyui_update === 'no') {
176
+ step.decision = 'no';
177
+ step.abort = true;
178
+ step.abort_reason = 'user declined the required ComfyUI update — installation aborted; nothing was changed';
179
+ step.result = 'keep existing ComfyUI; abort (the profile cannot run on a below-minimum version)';
180
+ } else {
181
+ step.awaiting_decision = true;
182
+ }
183
+ return step;
184
+ }
185
+
186
+ if (comfy.status === 'incompatible' && comfy.reason === 'above_max_tested') {
187
+ step.prompt = {
188
+ question: `ComfyUI ${found} detected — newer than the tested maximum (${expected}).\nNEVER auto-downgraded. Keep it (continue at own risk) or downgrade to the pinned version?`,
189
+ options: ['Keep', 'Downgrade'],
190
+ };
191
+ if (decisions.comfyui_update === 'keep' || decisions.comfyui_update === 'no') {
192
+ step.decision = 'keep';
193
+ step.continue_at_own_risk = true;
194
+ step.result = 'user keeps the newer ComfyUI — recorded as continue-at-own-risk; nothing changed';
195
+ } else if (decisions.comfyui_update === 'downgrade' || decisions.comfyui_update === 'yes') {
196
+ const gate = confirmationGate('downgrade_comfyui', { confirmed: true, op: 'downgrade_comfyui', via: 'interactive-prompt' });
197
+ step.decision = 'downgrade';
198
+ step.action = { op: 'downgrade_comfyui', destructive: true, requires_confirmation: true, allowed: gate.allowed };
199
+ step.result = 'user approved the downgrade — checkpoint state before executing';
200
+ } else {
201
+ step.awaiting_decision = true;
202
+ }
203
+ return step;
204
+ }
205
+
206
+ // unknown / other incompatible — user must review, never automatic
207
+ step.prompt = {
208
+ question: `ComfyUI compatibility cannot be determined automatically (${comfy.reason || comfy.status}).\nReview and decide how to proceed.`,
209
+ options: ['Review'],
210
+ };
211
+ if (decisions.comfyui_update) {
212
+ step.decision = String(decisions.comfyui_update);
213
+ step.result = 'user decision recorded; manual review step';
214
+ } else {
215
+ step.awaiting_decision = true;
216
+ }
217
+ return step;
218
+ }
219
+
220
+ function buildArtifactStep({ id, title, report, kinds, decisionKey, decisions, manifests, stepExtra }) {
221
+ const missing = report.entries.filter((e) => kinds.includes(e.kind) && e.status === 'missing' && e.action === 'install');
222
+ const review = report.entries.filter((e) => kinds.includes(e.kind) && (e.status === 'incompatible' || (e.status === 'missing' && e.action === 'review')));
223
+ const step = {
224
+ id,
225
+ title,
226
+ kind: 'prompt',
227
+ missing: missing.map((e) => ({ id: e.id, label: entryLabel(e) })),
228
+ review: review.map((e) => ({ id: e.id, label: entryLabel(e), reason: e.reason || e.status, notes: e.notes || [] })),
229
+ ...(stepExtra || {}),
230
+ };
231
+ if (missing.length === 0) {
232
+ step.kind = 'noop';
233
+ step.result = review.length === 0 ? 'nothing to install' : 'nothing to install (review items listed)';
234
+ return step;
235
+ }
236
+
237
+ step.prompt = {
238
+ question: `${missing.length} component(s) missing. Install?\n${missing.map((e) => ` - ${entryLabel(e)}`).join('\n')}`,
239
+ options: ['Yes', 'No'],
240
+ };
241
+ const decision = decisions[decisionKey];
242
+ if (decision === true || decision === 'yes') {
243
+ step.decision = 'yes';
244
+ step.action = { op: `install_${id}`, items: missing.map((e) => e.id), destructive: false, requires_confirmation: true };
245
+ step.result = `user approved installing ${missing.length} component(s)`;
246
+ } else if (decision === false || decision === 'no') {
247
+ step.decision = 'no';
248
+ step.skipped_by_user = true;
249
+ step.result = 'user declined — components stay missing; worker may fail verification later';
250
+ } else {
251
+ step.awaiting_decision = true;
252
+ }
253
+ return step;
254
+ }
255
+
256
+ function buildWorkflowsStep({ report, manifests, decisions }) {
257
+ const missing = report.entries.filter((e) => e.kind === 'workflow' && e.status === 'missing' && e.action === 'install');
258
+ const customized = report.entries.filter((e) => e.kind === 'workflow' && e.grade === 'customized');
259
+ const installed = report.entries.filter((e) => e.kind === 'workflow' && e.status === 'installed' && e.grade !== 'customized');
260
+
261
+ const step = {
262
+ id: 'workflows',
263
+ // OPTIONAL component: Animastor sends workflow JSON with each task via
264
+ // the API, so local copies are demo/test material only. Declining this
265
+ // step leaves the installation complete.
266
+ title: 'Profile workflows (optional)',
267
+ kind: 'prompt',
268
+ available: report.entries.filter((e) => e.kind === 'workflow').map((e) => ({ id: e.id, name: e.name })),
269
+ installed: installed.map((e) => e.id),
270
+ customized: customized.map((e) => ({ id: e.id, note: 'customized by user — kept as-is, NEVER overwritten' })),
271
+ missing: missing.map((e) => ({ id: e.id, name: e.name, path: e.expected ? e.expected.path : null })),
272
+ };
273
+
274
+ if (missing.length === 0) {
275
+ step.kind = 'noop';
276
+ step.result = customized.length > 0
277
+ ? 'all optional profile workflows present; user-customized copies are kept untouched'
278
+ : 'all optional profile workflows present';
279
+ return step;
280
+ }
281
+
282
+ step.prompt = {
283
+ question: `Install optional profile workflows?\n${missing.map((e) => ` - ${e.name} [${e.id}]`).join('\n')}\n(Not required for Animastor — tasks are sent to ComfyUI via the API. Local copies are useful to test ComfyUI in its Web UI or as a starting point for your own workflows. Each one is an editable starting point you can customize freely.)`,
284
+ options: ['All', 'Select', 'None'],
285
+ };
286
+
287
+ const selection = decisions.workflows;
288
+ if (selection === 'none' || selection === false) {
289
+ step.decision = 'none';
290
+ step.skipped_by_user = true;
291
+ step.result = 'user declined optional profile workflows — nothing downloaded; the installation stays complete (workflows are optional)';
292
+ return step;
293
+ }
294
+ if (selection === 'all' || Array.isArray(selection)) {
295
+ step.decision = Array.isArray(selection) ? 'select' : 'all';
296
+ const downloads = [];
297
+ for (const m of manifests) {
298
+ downloads.push(...planWorkflowDownloads(m, { workflows: collectFoundWorkflows(report) }, selection, { restoreBaseline: decisions.restore_baseline === true }));
299
+ }
300
+ // only keep downloads for workflows the resolver actually reported missing
301
+ const missingIds = new Set(missing.map((e) => e.id));
302
+ const freshCopies = downloads.filter((d) => d.fresh_copy);
303
+ const selected = downloads.filter((d) => missingIds.has(d.id) || d.fresh_copy);
304
+ step.action = {
305
+ op: 'download_workflows',
306
+ items: selected.map((d) => ({ id: d.id, target_path: d.target_path, fresh_copy: d.fresh_copy })),
307
+ destructive: false,
308
+ requires_confirmation: true,
309
+ never_overwrites: true,
310
+ };
311
+ step.result = `user selected ${selected.length - freshCopies.length} optional profile workflow(s)${freshCopies.length ? ` + ${freshCopies.length} fresh copy(ies) of customized baselines (distinct paths)` : ''}`;
312
+ return step;
313
+ }
314
+ step.awaiting_decision = true;
315
+ return step;
316
+ }
317
+
318
+ function collectFoundWorkflows(report) {
319
+ // reconstruct the probed workflow files from report entries (found paths)
320
+ const workflows = [];
321
+ for (const e of report.entries) {
322
+ if (e.kind === 'workflow' && e.found && e.found.path) {
323
+ workflows.push({ path: e.found.path, sha256: e.found.sha256 || null });
324
+ }
325
+ }
326
+ return workflows;
327
+ }
328
+
329
+ function buildWorkerSteps({ report, manifests, decisions }) {
330
+ const workers = report.entries.filter((e) => e.kind === 'worker');
331
+ const setup = {
332
+ id: 'worker-setup',
333
+ title: 'Animastor Worker bundle',
334
+ kind: 'prompt',
335
+ workers: workers.map((e) => ({
336
+ id: e.id,
337
+ worker_type: e.worker_type,
338
+ status: e.status,
339
+ grade: e.grade || null,
340
+ env_missing: e.env ? e.env.missing_required : null,
341
+ })),
342
+ };
343
+
344
+ const toInstall = workers.filter((e) => e.status === 'missing' || (e.status === 'incompatible' && e.reason === 'incomplete_bundle'));
345
+ const toConfigure = workers.filter((e) => e.action === 'configure');
346
+
347
+ if (toInstall.length === 0 && toConfigure.length === 0) {
348
+ setup.kind = 'noop';
349
+ setup.result = workers.length > 0 ? 'worker bundle(s) installed and configured' : 'no worker entries';
350
+ return { setup, key: null };
351
+ }
352
+
353
+ // If the user declined worker setup, don't prompt for the key either.
354
+ if (decisions.worker_setup === false || decisions.worker_setup === 'no') {
355
+ setup.kind = 'noop';
356
+ setup.result = 'user skipped worker setup';
357
+ return { setup, key: null };
358
+ }
359
+
360
+ const actions = [];
361
+ if (toInstall.length > 0) actions.push(`install worker bundle: ${toInstall.map((e) => e.worker_type).join(', ')}`);
362
+ if (toConfigure.length > 0) actions.push(`create/update .env (merge semantics, chmod 600): ${toConfigure.map((e) => e.worker_type).join(', ')}`);
363
+ setup.prompt = { question: `Worker setup:\n${actions.map((a) => ` - ${a}`).join('\n')}\nContinue?`, options: ['Yes', 'No'] };
364
+
365
+ if (decisions.worker_setup === true || decisions.worker_setup === 'yes') {
366
+ setup.decision = 'yes';
367
+ setup.action = { op: 'worker_setup', items: workers.map((e) => e.id), destructive: false, requires_confirmation: true };
368
+ setup.result = 'user approved worker setup';
369
+ } else if (decisions.worker_setup === false || decisions.worker_setup === 'no') {
370
+ setup.decision = 'no';
371
+ setup.skipped_by_user = true;
372
+ setup.result = 'user skipped worker setup';
373
+ } else {
374
+ setup.awaiting_decision = true;
375
+ }
376
+
377
+ // Worker Key step — secret handling by NAME only.
378
+ // Needed whenever any worker still requires setup (fresh install implies
379
+ // a fresh .env) or explicit configuration.
380
+ const secretMissing = [];
381
+ const needsSetup = workers.filter((e) => e.status === 'missing' || e.action === 'configure'
382
+ || (e.status === 'incompatible' && e.reason === 'incomplete_bundle'));
383
+ for (const e of needsSetup) {
384
+ const manifest = manifests.find((m) => `worker:${m.profile.id}` === e.id);
385
+ const wbEnv = (manifest && manifest.worker_bundle && manifest.worker_bundle.env) || {};
386
+ const secrets = wbEnv.secrets || ['ANIMASTOR_WORKER_TOKEN'];
387
+ // for a missing bundle the whole .env is absent → every secret is missing
388
+ const missingHere = e.action === 'configure' && e.env ? e.env.missing_required : (wbEnv.required || secrets);
389
+ for (const k of missingHere) {
390
+ if (secrets.includes(k) && !secretMissing.includes(k)) secretMissing.push(k);
391
+ }
392
+ }
393
+
394
+ let key = null;
395
+ if (secretMissing.length > 0 || toConfigure.length > 0) {
396
+ key = {
397
+ id: 'worker-key',
398
+ title: 'Enter Worker Key securely',
399
+ kind: 'secret-prompt',
400
+ secret_keys: secretMissing,
401
+ prompt: {
402
+ question: `Enter ${secretMissing.join(', ') || 'Worker Key'} (hidden input)`,
403
+ options: ['Enter'],
404
+ },
405
+ rules: Object.freeze([
406
+ 'hidden interactive input only',
407
+ 'the VALUE is never printed to logs',
408
+ 'the VALUE is never passed via command-line arguments',
409
+ 'the VALUE is never stored in reports, plan objects, or state files',
410
+ 'an existing valid token is never overwritten (merge semantics)',
411
+ ]),
412
+ };
413
+ if (decisions.worker_key_provided === true) {
414
+ key.provided = true; // boolean flag ONLY — the value itself is never recorded
415
+ key.result = 'Worker Key entered interactively (value not recorded anywhere)';
416
+ } else {
417
+ key.provided = false;
418
+ key.awaiting_decision = true;
419
+ }
420
+ }
421
+ return { setup, key };
422
+ }
423
+
424
+ // ---------------------------------------------------------------------------
425
+ // Main entry point
426
+ // ---------------------------------------------------------------------------
427
+
428
+ /**
429
+ * Build the interactive installation plan from a resolution report.
430
+ *
431
+ * @param {object} args
432
+ * @param {object} args.report - resolver report (resolveInstallation output)
433
+ * @param {object[]} [args.manifests] - manifests used for the report
434
+ * (needed for workflow/model download planning and worker secret names)
435
+ * @param {object} [args.decisions] - recorded user decisions:
436
+ * comfyui_update: 'yes'|'no'|'keep'|'downgrade'|...
437
+ * accept_reference_runtime: true|false — consent to install the manifest's
438
+ * known-working reference ComfyUI when no canonical pin exists (D1)
439
+ * install_custom_nodes: true|false
440
+ * install_models: true|false
441
+ * workflows: 'all'|'none'|[ids]
442
+ * restore_baseline: true — additionally download fresh copies of customized baselines
443
+ * worker_setup: true|false
444
+ * worker_key_provided: true|false (flag only; the key value is NEVER passed here)
445
+ * @returns plan object with steps, rendered text, gates
446
+ */
447
+ function buildInstallPlan({ report, manifests = [], decisions = {} }) {
448
+ if (!report || !Array.isArray(report.entries)) {
449
+ throw new Error('buildInstallPlan requires a resolution report');
450
+ }
451
+
452
+ const steps = [];
453
+ const blocked = [];
454
+
455
+ // 1–3: detection
456
+ const hwDevice = report.hardware ? report.hardware.device : null;
457
+ steps.push({
458
+ id: 'detect-gpu',
459
+ title: 'Detect GPU',
460
+ kind: 'detect',
461
+ automatic: true,
462
+ result: {
463
+ gpu: report.hardware ? report.hardware.gpu : null,
464
+ device: hwDevice,
465
+ sufficient_vram: report.hardware ? report.hardware.sufficient_vram : null,
466
+ notes: report.hardware ? report.hardware.notes : [],
467
+ },
468
+ });
469
+
470
+ const comfy = entryById(report, 'runtime:comfyui');
471
+ steps.push({
472
+ id: 'detect-comfyui',
473
+ title: 'Detect existing ComfyUI',
474
+ kind: 'detect',
475
+ automatic: true,
476
+ result: comfy ? { status: comfy.status, grade: comfy.grade || null, found: comfy.found, expected: comfy.expected } : null,
477
+ });
478
+
479
+ steps.push({
480
+ id: 'detect-runtime',
481
+ title: 'Detect runtime (Python/Torch/CUDA/Node.js)',
482
+ kind: 'detect',
483
+ automatic: true,
484
+ result: ['python', 'torch', 'nodejs'].map((c) => {
485
+ const e = entryById(report, `runtime:${c}`);
486
+ return e ? { component: c, status: e.status, grade: e.grade || null, found: e.found } : null;
487
+ }).filter(Boolean),
488
+ });
489
+
490
+ // 4: profiles + sharing verdict
491
+ const selectStep = {
492
+ id: 'select-profiles',
493
+ title: 'Select profile(s)',
494
+ kind: 'select',
495
+ profiles: report.profiles,
496
+ };
497
+ if (report.sharing) {
498
+ selectStep.sharing = { verdict: report.sharing.verdict, message: report.sharing.message };
499
+ if (!report.sharing.can_share) {
500
+ const code = String(report.sharing.verdict || '').toUpperCase().replace(/-/g, '_')
501
+ || 'REQUIRES_ISOLATION';
502
+ blocked.push({
503
+ step: 'select-profiles',
504
+ code, // machine-readable verdict: REQUIRES_ISOLATION | SHARED_CONFLICT | UNKNOWN
505
+ reason: 'Profiles cannot safely share this ComfyUI runtime. Isolation recommended.',
506
+ detail: report.sharing.message,
507
+ });
508
+ }
509
+ }
510
+ steps.push(selectStep);
511
+
512
+ // 5: resolution summary
513
+ steps.push({
514
+ id: 'resolve-dependencies',
515
+ title: 'Resolve dependencies',
516
+ kind: 'resolve',
517
+ automatic: true,
518
+ result: report.summary,
519
+ });
520
+
521
+ // 6: ComfyUI update policy
522
+ const comfyStep = buildComfyuiStep(report, decisions, manifests);
523
+ steps.push(comfyStep);
524
+ if (comfyStep.abort) {
525
+ blocked.push({ step: 'comfyui-update', reason: comfyStep.abort_reason });
526
+ }
527
+
528
+ // 7: custom nodes
529
+ steps.push(buildArtifactStep({
530
+ id: 'custom-nodes',
531
+ title: 'Custom nodes',
532
+ report,
533
+ kinds: ['custom_node'],
534
+ decisionKey: 'install_custom_nodes',
535
+ decisions,
536
+ manifests,
537
+ }));
538
+
539
+ // 8: models (+ download specs with honesty blockers)
540
+ const missingModelIds = report.entries
541
+ .filter((e) => (e.kind === 'model' || e.kind === 'model_repo') && e.status === 'missing' && e.action === 'install')
542
+ .map((e) => e.id);
543
+ const downloadSpecs = manifests.flatMap((m) => planModelDownloads(m, missingModelIds));
544
+ const notReady = downloadSpecs.filter((s) => !s.ready);
545
+ const modelsStep = buildArtifactStep({
546
+ id: 'models',
547
+ title: 'Models',
548
+ report,
549
+ kinds: ['model', 'model_repo'],
550
+ decisionKey: 'install_models',
551
+ decisions,
552
+ manifests,
553
+ stepExtra: {
554
+ download_specs: downloadSpecs.map((s) => ({ id: s.id, ready: s.ready, resume: s.resume, blockers: s.blockers })),
555
+ estimated_bytes: estimateMissingBytes(downloadSpecs),
556
+ },
557
+ });
558
+ if (notReady.length > 0) {
559
+ modelsStep.blocked_downloads = notReady.map((s) => ({ id: s.id, blockers: s.blockers }));
560
+ modelsStep.notes = (modelsStep.notes || []).concat([
561
+ `${notReady.length} model download(s) are NOT ready: sources must be researched (D5) before the installer may download — URLs are never invented`,
562
+ ]);
563
+ }
564
+ steps.push(modelsStep);
565
+
566
+ // 9: baseline workflows
567
+ steps.push(buildWorkflowsStep({ report, manifests, decisions }));
568
+
569
+ // 10–11: worker + worker key
570
+ const { setup, key } = buildWorkerSteps({ report, manifests, decisions });
571
+ steps.push(setup);
572
+ if (key) steps.push(key);
573
+
574
+ // 12: verify
575
+ steps.push({
576
+ id: 'verify',
577
+ title: 'Verify installation',
578
+ kind: 'verify',
579
+ checks: ['GPU', 'ComfyUI', 'Runtime', 'Custom Nodes', 'Models', 'Profile workflows (optional)', 'Worker', 'GPU Hub registration'],
580
+ });
581
+
582
+ const awaiting = steps.filter((s) => s.awaiting_decision).map((s) => s.id);
583
+ const confirmedOperations = steps
584
+ .filter((s) => s.action && s.action.destructive && s.action.allowed)
585
+ .map((s) => ({ op: s.action.op, step: s.id, requires_confirmation: true }));
586
+
587
+ const plan = {
588
+ mode: report.mode,
589
+ profiles: report.profiles,
590
+ steps,
591
+ blocked,
592
+ awaiting_decisions: awaiting,
593
+ complete: awaiting.length === 0 && blocked.length === 0,
594
+ confirmed_operations: confirmedOperations,
595
+ destructive_operations: Object.freeze([]), // invariant: nothing destructive without explicit consent
596
+ safe_to_proceed: report.safe_to_proceed && blocked.length === 0,
597
+ };
598
+ plan.plan_text = renderPlanText(plan, report);
599
+ return plan;
600
+ }
601
+
602
+ // ---------------------------------------------------------------------------
603
+ // Rendering
604
+ // ---------------------------------------------------------------------------
605
+
606
+ function renderPlanText(plan, report) {
607
+ const lines = [];
608
+ lines.push(`Profile: ${plan.profiles.join(' + ')}`);
609
+ lines.push(`Mode: ${plan.mode}`);
610
+ lines.push('');
611
+
612
+ const hw = report.hardware || {};
613
+ if (hw.device === 'cpu') {
614
+ lines.push('=========================================================');
615
+ lines.push(' CPU-ONLY MODE DETECTED');
616
+ lines.push(' No supported GPU runtime was found on this machine.');
617
+ lines.push(' A CPU build of PyTorch will be installed and ComfyUI');
618
+ lines.push(' will run with --cpu. Performance will be SIGNIFICANTLY');
619
+ lines.push(' lower than GPU. This mode is intended for the');
620
+ lines.push(' TTS/audio profile — NOT for image/video generation.');
621
+ if (hw.gpu && hw.gpu.vendor === 'amd') {
622
+ lines.push(' Note: an AMD GPU was detected, but the installer');
623
+ lines.push(' provides no ROCm/accelerated runtime branch yet.');
624
+ }
625
+ lines.push('=========================================================');
626
+ lines.push('');
627
+ }
628
+ const detected = [];
629
+ if (hw.gpu && hw.gpu.name) {
630
+ detected.push(`\u2713 ${hw.gpu.name}${typeof hw.gpu.vram_mib === 'number' ? ` (${Math.round(hw.gpu.vram_mib / 1024)} GB VRAM)` : ''}`);
631
+ }
632
+ for (const e of report.entries) {
633
+ if (e.status !== 'installed') continue;
634
+ if (e.kind === 'runtime') {
635
+ const v = foundLabel(e);
636
+ detected.push(`\u2713 ${entryLabel(e)}${v ? ` (${v})` : ''}`);
637
+ } else if (e.kind === 'custom_node' || e.kind === 'workflow') {
638
+ detected.push(`\u2713 ${entryLabel(e)}${e.grade === 'customized' ? ' [customized by user — kept]' : ''}`);
639
+ } else if (e.kind === 'worker') {
640
+ detected.push(`\u2713 ${entryLabel(e)}`);
641
+ } else if (e.kind === 'model' || e.kind === 'model_repo') {
642
+ detected.push(`\u2713 ${entryLabel(e)}`);
643
+ }
644
+ }
645
+ if (detected.length > 0) {
646
+ lines.push('Detected:');
647
+ lines.push(...detected);
648
+ lines.push('');
649
+ }
650
+
651
+ // Optional profile workflows are deliberately NOT shown as ✗ Missing:
652
+ // they are demo/test artifacts, and their absence must never look like
653
+ // an incomplete or broken installation.
654
+ const missing = report.entries.filter((e) => e.status === 'missing' && e.kind !== 'workflow');
655
+ if (missing.length > 0) {
656
+ lines.push('Missing:');
657
+ for (const e of missing) lines.push(`\u2717 ${entryLabel(e)}`);
658
+ lines.push('');
659
+ }
660
+
661
+ const missingWorkflows = report.entries.filter((e) => e.status === 'missing' && e.kind === 'workflow');
662
+ if (missingWorkflows.length > 0) {
663
+ lines.push('Optional (not installed — NOT required):');
664
+ for (const e of missingWorkflows) {
665
+ lines.push(` - ${entryLabel(e)} — useful only to test ComfyUI locally in its Web UI or as a starting point for your own workflows`);
666
+ }
667
+ lines.push('');
668
+ }
669
+
670
+ const incompatible = report.entries.filter((e) => e.status === 'incompatible');
671
+ if (incompatible.length > 0) {
672
+ lines.push('Needs review:');
673
+ for (const e of incompatible) lines.push(`! ${entryLabel(e)} (${e.reason || 'incompatible'})`);
674
+ lines.push('');
675
+ }
676
+
677
+ const actions = report.entries.filter((e) => e.action === 'install').map(actionLine);
678
+ for (const e of report.entries) {
679
+ if (e.action === 'configure') actions.push(`Configure ${entryLabel(e)} (.env)`);
680
+ }
681
+ if (actions.length > 0) {
682
+ lines.push('Actions:');
683
+ for (const a of actions) lines.push(` ${a}`);
684
+ lines.push('');
685
+ }
686
+
687
+ // Download size summary
688
+ const modelsStep = plan.steps.find((s) => s.id === 'models');
689
+ if (modelsStep && modelsStep.estimated_bytes) {
690
+ const est = modelsStep.estimated_bytes;
691
+ if (est.total_bytes > 0 || est.unknown_count > 0) {
692
+ lines.push('Download size:');
693
+ if (est.total_bytes > 0) lines.push(` ${formatBytes(est.total_bytes)}`);
694
+ if (est.unknown_count > 0) lines.push(` + ${est.unknown_count} file(s) with unknown size`);
695
+ lines.push('');
696
+ }
697
+ }
698
+
699
+ // Auth requirements summary
700
+ const modelsStepEntry = plan.steps.find((s) => s.id === 'models');
701
+ if (modelsStepEntry && modelsStepEntry.download_specs) {
702
+ const authRequired = modelsStepEntry.download_specs.filter((s) => s.requires_auth);
703
+ if (authRequired.length > 0) {
704
+ const hasHfToken = !!(process.env.HF_TOKEN || process.env.HUGGINGFACE_HUB_TOKEN);
705
+ lines.push('Source: Hugging Face (gated models)');
706
+ if (hasHfToken) {
707
+ lines.push(' System HF token: available');
708
+ } else {
709
+ lines.push(' System HF token: UNAVAILABLE — set HF_TOKEN or HUGGINGFACE_HUB_TOKEN');
710
+ }
711
+ lines.push('');
712
+ }
713
+ }
714
+
715
+ if (plan.blocked.length > 0) {
716
+ lines.push('Blocked:');
717
+ for (const b of plan.blocked) lines.push(`- ${b.code ? `[${b.code}] ` : ''}${b.reason}`);
718
+ lines.push('');
719
+ }
720
+
721
+ const prompts = plan.steps.filter((s) => s.prompt && s.awaiting_decision);
722
+ if (prompts.length > 0) {
723
+ for (const p of prompts) {
724
+ lines.push(p.prompt.question);
725
+ lines.push(`[${p.prompt.options.join('] [')}]`);
726
+ lines.push('');
727
+ }
728
+ } else if (plan.blocked.length === 0) {
729
+ lines.push('Continue?');
730
+ lines.push('[Yes] [No]');
731
+ }
732
+
733
+ return lines.join('\n').trim();
734
+ }
735
+
736
+ module.exports = {
737
+ FLOW_STEPS,
738
+ buildInstallPlan,
739
+ renderPlanText,
740
+ entryLabel,
741
+ };