@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,1401 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Private Worker Setup Contract — UI-safe projection (Phase 3).
5
+ *
6
+ * Projects the canonical installer metadata (install manifests, resolver,
7
+ * download planner) into a stable DTO surface consumed by BOTH frontends
8
+ * (Web and Android) through backend/src/routes/worker-setup-routes.cjs:
9
+ *
10
+ * profiles, installation methods, installer/uninstaller artifacts,
11
+ * worker bundle, workflow metadata, setup instructions, worker status,
12
+ * normalized capabilities, UI-safe installation plan.
13
+ *
14
+ * Hard rules:
15
+ * - the raw installer manifest NEVER leaves the backend; only the
16
+ * projections defined here are exposed;
17
+ * - no secrets: the Worker Key / token_hash / credentials never appear in
18
+ * any projection; instructions carry a placeholder only;
19
+ * - nothing is invented: unknown VRAM stays null, unresearched model
20
+ * sources become explicit blocks, unavailable artifacts stay
21
+ * available=false with status 'planned';
22
+ * - download URLs are ORIGIN-RELATIVE paths (e.g. "/gpu/worker-bundle");
23
+ * the frontend resolves them against its own origin. The frontend can
24
+ * never supply or alter a download URL.
25
+ */
26
+
27
+ const fs = require('fs');
28
+ const path = require('path');
29
+
30
+ const { loadManifest, loadAllManifests, MANIFEST_ROOT } = require('./install-manifest');
31
+ const resolver = require('./compatibility-resolver');
32
+ const { planModelDownload } = require('./download-planner');
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // Versions & registries (single source of truth for the contract)
36
+ // ---------------------------------------------------------------------------
37
+ // Versions are READ from canonical sources — never duplicated here:
38
+ // installer → packages/animastor-installer/package.json (getInstallerVersion)
39
+ // worker bundle → packages/animastor-worker/worker/package.json (hub probe
40
+ // first, repo fallback via getWorkerBundleVersion)
41
+ // workflows → manifest revision + baseline_sha256 (content-addressed)
42
+ // uninstaller → does not exist yet → version stays null, status 'planned'
43
+
44
+ /** Read the canonical installer version from the installer's package.json. */
45
+ function getInstallerVersion() {
46
+ try {
47
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8'));
48
+ return typeof pkg.version === 'string' && pkg.version ? pkg.version : null;
49
+ } catch (_) {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Read the canonical worker bundle version from the bundle's own
56
+ * package.json. Checks baked-in artifacts first (container), then
57
+ * repo checkout (development), then hub probe (network).
58
+ */
59
+ function getWorkerBundleVersion() {
60
+ // Priority: baked-in > repo checkout > null (hub probe is primary source)
61
+ const bakedIn = path.join('/app', 'artifacts', 'worker-bundle', 'package.json');
62
+ try {
63
+ const pkg = JSON.parse(fs.readFileSync(bakedIn, 'utf8'));
64
+ if (typeof pkg.version === 'string' && pkg.version) return pkg.version;
65
+ } catch (_) { /* not in container */ }
66
+ try {
67
+ // Canonical repo location (packages/animastor-worker/worker) with the
68
+ // legacy worker/worker fallback for pre-relocation checkouts — see
69
+ // installer/worker-bundle-source.js. Resolved against THIS module dir
70
+ // (packages/animastor-installer/src/installer → repo root): inside the
71
+ // monorepo that is the repo root; inside a distributed installer package
72
+ // it is the extraction parent, mirroring the repo layout.
73
+ const candidates = [
74
+ path.join(__dirname, '..', '..', '..', '..', 'packages', 'animastor-worker', 'worker', 'package.json'),
75
+ path.join(__dirname, '..', '..', '..', '..', 'worker', 'worker', 'package.json'),
76
+ ];
77
+ for (const file of candidates) {
78
+ try {
79
+ const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));
80
+ if (typeof pkg.version === 'string' && pkg.version) return pkg.version;
81
+ } catch (_) { /* try the next candidate */ }
82
+ }
83
+ return null;
84
+ } catch (_) {
85
+ return null;
86
+ }
87
+ }
88
+
89
+ const PLATFORMS = Object.freeze(['linux', 'windows', 'docker']);
90
+
91
+ /**
92
+ * OS platforms (installer/platform — Platform × Deployment are orthogonal:
93
+ * docker is a DEPLOYMENT of a platform, never an OS of its own). The legacy
94
+ * UI dimension 'docker' (PLATFORMS above) stays accepted everywhere and is
95
+ * normalized to platform=linux + deployment=docker.
96
+ */
97
+ const OS_PLATFORMS = Object.freeze(['linux', 'windows']);
98
+
99
+ /** Deployment targets exposed to the UI (installer/platform DEPLOYMENTS). */
100
+ const DEPLOYMENTS = Object.freeze(['native', 'docker']);
101
+
102
+ /** Availability levels of a platform+deployment combination. */
103
+ const AVAILABILITY_LEVELS = Object.freeze(['stable', 'preview', 'experimental']);
104
+
105
+ /**
106
+ * Canonical UI copy for non-stable combinations (informational, never
107
+ * blocking). The levels themselves are DERIVED from the real installer
108
+ * adapters (see deploymentCapabilities) — this map only carries the text.
109
+ */
110
+ const DEPLOYMENT_NOTICES = Object.freeze({
111
+ 'windows:native':
112
+ 'Windows support is currently in Preview. The installer is under active development and may have platform-specific issues.',
113
+ 'linux:docker':
114
+ 'Docker deployment is Experimental. GPU support and host-specific Docker configurations may require additional setup.',
115
+ });
116
+
117
+ /** Availability level of one combination, derived from the adapter flags. */
118
+ function availabilityLevel(platformAdapter, deploymentAdapter) {
119
+ if (platformAdapter.experimental || deploymentAdapter.experimental) return 'experimental';
120
+ if (!platformAdapter.productionReady || !deploymentAdapter.productionReady) return 'preview';
121
+ return 'stable';
122
+ }
123
+
124
+ /**
125
+ * The single capability model consumed by BOTH frontends: every allowed
126
+ * platform+deployment combination with its honest availability level.
127
+ *
128
+ * Derived from the REAL installer adapters (platform/linux.js, platform/
129
+ * windows.js, platform/deployment/*) — flipping an adapter flag is the only
130
+ * change needed to move a combination from experimental → preview → stable
131
+ * in the UI (no frontend change, ever).
132
+ *
133
+ * windows+docker is NOT allowed (docker is a linux deployment target —
134
+ * platform/index.js getDeploymentAdapter rejects it); it is still listed
135
+ * with allowed=false so the contract states the full matrix explicitly.
136
+ *
137
+ * @returns {Array<{platform: string, deployment: string, availability: ?string,
138
+ * allowed: boolean, reason: ?string, notice: ?string}>}
139
+ */
140
+ function deploymentCapabilities() {
141
+ const linux = require('./platform/linux');
142
+ const windows = require('./platform/windows');
143
+ const native = require('./platform/deployment/native');
144
+ const docker = require('./platform/deployment/docker');
145
+ const entry = (platform, platformAdapter, deployment, deploymentAdapter) => {
146
+ if (deployment === 'docker' && platform !== 'linux') {
147
+ return {
148
+ platform, deployment, availability: null, allowed: false,
149
+ reason: 'unsupported_combination',
150
+ notice: 'Docker deployment requires the linux platform; windows containers are not a supported target.',
151
+ };
152
+ }
153
+ const availability = availabilityLevel(platformAdapter, deploymentAdapter);
154
+ const key = `${platform}:${deployment}`;
155
+ return {
156
+ platform,
157
+ deployment,
158
+ availability,
159
+ allowed: true,
160
+ reason: null,
161
+ notice: availability === 'stable' ? null : (DEPLOYMENT_NOTICES[key] || null),
162
+ };
163
+ };
164
+ return Object.freeze([
165
+ entry('linux', linux, 'native', native),
166
+ entry('linux', linux, 'docker', docker),
167
+ entry('windows', windows, 'native', windows),
168
+ entry('windows', windows, 'docker', docker),
169
+ ]);
170
+ }
171
+
172
+ /**
173
+ * Validate + normalize a UI deployment selection. Accepts the legacy UI
174
+ * platform 'docker' (→ linux + docker). Throws coded errors: the route maps
175
+ * unsupported_platform → 404, invalid_deployment / unsupported_combination
176
+ * → 400.
177
+ * @returns {{platform: string, deployment: string, capability: object}}
178
+ */
179
+ function resolveDeploymentTarget({ platform = 'linux', deployment = 'native' } = {}) {
180
+ let p = platform;
181
+ let d = deployment;
182
+ if (p === 'docker') { p = 'linux'; d = 'docker'; } // legacy UI dimension
183
+ if (!OS_PLATFORMS.includes(p)) {
184
+ const err = new Error(`unsupported platform "${platform}" (expected one of ${[...OS_PLATFORMS, 'docker'].join(', ')})`);
185
+ err.code = 'unsupported_platform';
186
+ throw err;
187
+ }
188
+ if (!DEPLOYMENTS.includes(d)) {
189
+ const err = new Error(`unsupported deployment "${deployment}" (expected one of ${DEPLOYMENTS.join(', ')})`);
190
+ err.code = 'invalid_deployment';
191
+ throw err;
192
+ }
193
+ const capability = deploymentCapabilities().find((c) => c.platform === p && c.deployment === d);
194
+ if (!capability || !capability.allowed) {
195
+ const err = new Error(`the combination "${p} + ${d}" is not supported (docker deployment requires the linux platform)`);
196
+ err.code = 'unsupported_combination';
197
+ throw err;
198
+ }
199
+ return { platform: p, deployment: d, capability };
200
+ }
201
+
202
+ /** Install modes exposed to the UI (resolver RUNTIME_MODES minus none). */
203
+ const INSTALL_MODES = Object.freeze(['managed', 'existing', 'shared', 'isolated']);
204
+
205
+ /**
206
+ * Extended UI-safe worker status model. Superset of the existing
207
+ * ONLINE/OFFLINE/REVOKED — the legacy values keep their meaning; the extra
208
+ * states are derived (CONNECTING) or reserved for future signals
209
+ * (NOT_CONFIGURED is a frontend-level state, INSTALLING/ERROR await an
210
+ * installer check-in / worker error channel).
211
+ */
212
+ const SETUP_WORKER_STATUSES = Object.freeze([
213
+ 'NOT_CONFIGURED',
214
+ 'INSTALLING',
215
+ 'CONNECTING',
216
+ 'ONLINE',
217
+ 'OFFLINE',
218
+ 'ERROR',
219
+ 'REVOKED',
220
+ ]);
221
+
222
+ /** Machine-readable sharing verdicts (task §15 naming). */
223
+ const SHARING_VERDICT_MAP = Object.freeze({
224
+ 'shared-compatible': 'SHARED_COMPATIBLE',
225
+ 'shared-conflict': 'SHARED_CONFLICT',
226
+ 'requires-isolation': 'REQUIRES_ISOLATION',
227
+ unknown: 'UNKNOWN',
228
+ });
229
+
230
+ const ACRONYMS = Object.freeze({ tts: 'TTS', ltx: 'LTX', gpu: 'GPU' });
231
+
232
+ function displayNameFromSlug(slug) {
233
+ return String(slug)
234
+ .split(/[-_\s]+/)
235
+ .filter(Boolean)
236
+ .map((w) => (ACRONYMS[w.toLowerCase()] ? ACRONYMS[w.toLowerCase()] : w.charAt(0).toUpperCase() + w.slice(1)))
237
+ .join(' ');
238
+ }
239
+
240
+ // ---------------------------------------------------------------------------
241
+ // Manifest cache (manifests are mounted live — reload when the tree changes)
242
+ // ---------------------------------------------------------------------------
243
+
244
+ function manifestsFingerprint(root) {
245
+ if (!fs.existsSync(root)) return null;
246
+ const parts = [];
247
+ for (const type of fs.readdirSync(root).sort()) {
248
+ const typeDir = path.join(root, type);
249
+ if (!fs.statSync(typeDir).isDirectory()) continue;
250
+ for (const file of fs.readdirSync(typeDir).sort()) {
251
+ if (!file.endsWith('.json')) continue;
252
+ const st = fs.statSync(path.join(typeDir, file));
253
+ parts.push(`${type}/${file}:${st.size}:${st.mtimeMs}`);
254
+ }
255
+ }
256
+ return parts.join('|') || null;
257
+ }
258
+
259
+ function createManifestRegistry({ loadAll = loadAllManifests, root = MANIFEST_ROOT } = {}) {
260
+ const cache = { fingerprint: undefined, manifests: null };
261
+ return {
262
+ /** @returns {Object<string, object>} manifests keyed by profile id */
263
+ all() {
264
+ const fp = manifestsFingerprint(root);
265
+ if (fp === cache.fingerprint && cache.manifests) return cache.manifests;
266
+ cache.manifests = loadAll({ skipValidation: false });
267
+ cache.fingerprint = fp;
268
+ return cache.manifests;
269
+ },
270
+ /** @returns {object|null} one manifest or null when unknown */
271
+ get(profileId) {
272
+ if (typeof profileId !== 'string' || !profileId) return null;
273
+ const all = this.all();
274
+ return Object.prototype.hasOwnProperty.call(all, profileId) ? all[profileId] : null;
275
+ },
276
+ invalidate() { cache.fingerprint = undefined; cache.manifests = null; },
277
+ };
278
+ }
279
+
280
+ const defaultRegistry = createManifestRegistry();
281
+
282
+ /** The canonical (repo manifests) registry — used unless one is injected. */
283
+ function getManifestRegistry() {
284
+ return defaultRegistry;
285
+ }
286
+
287
+ /** Manifests that must never be exposed through the setup contract. */
288
+ function isHiddenManifest(manifest) {
289
+ const status = manifest && manifest.status;
290
+ return status === 'internal' || status === 'hidden';
291
+ }
292
+
293
+ // ---------------------------------------------------------------------------
294
+ // Profiles
295
+ // ---------------------------------------------------------------------------
296
+
297
+ function dependenciesSummary(manifest) {
298
+ const deps = manifest.dependencies || [];
299
+ const models = deps.filter((d) => d.kind === 'model' || d.kind === 'model_repo');
300
+ const customNodes = deps.filter((d) => d.kind === 'custom_node');
301
+ const requiredModels = models.filter((d) => d.requirement === 'required');
302
+ const approxBytes = requiredModels.reduce(
303
+ (sum, d) => sum + (typeof d.size_bytes_approx === 'number' ? d.size_bytes_approx : 0), 0
304
+ );
305
+ return {
306
+ custom_nodes: customNodes.filter((d) => d.requirement === 'required').length,
307
+ models: requiredModels.length,
308
+ approx_bytes: approxBytes > 0 ? approxBytes : null,
309
+ };
310
+ }
311
+
312
+ /**
313
+ * UI-safe profile projection. Deliberately NOT the raw manifest: internal
314
+ * source URLs, repository paths, checksums of models, provenance evidence
315
+ * and resolver details stay inside the backend.
316
+ */
317
+ function projectProfile(manifest) {
318
+ const profile = manifest.profile;
319
+ const hardware = manifest.hardware || {};
320
+ const wfArtifacts = (manifest.workflows && manifest.workflows.artifacts) || [];
321
+ return {
322
+ id: profile.id,
323
+ name: displayNameFromSlug(profile.name),
324
+ description: `${displayNameFromSlug(profile.name)} — private ${profile.type} generation via ComfyUI on your own GPU worker.`,
325
+ worker_type: profile.type,
326
+ status: manifest.status || 'draft',
327
+ supported_install_modes: INSTALL_MODES.slice(),
328
+ gpu: {
329
+ min_vram_gb: typeof hardware.gpu_min_vram_gb === 'number' ? hardware.gpu_min_vram_gb : null,
330
+ reference_gpu: hardware.reference_gpu || null,
331
+ },
332
+ disk_budget_bytes_approx: (manifest.disk_budget && manifest.disk_budget.models_bytes_approx) || null,
333
+ workflows: wfArtifacts.map((w) => String(w.id).replace(/^workflow:/, '')),
334
+ dependencies_summary: dependenciesSummary(manifest),
335
+ };
336
+ }
337
+
338
+ /**
339
+ * List UI-safe install profiles from canonical installer metadata.
340
+ * @param {{type?: string, registry?: object}} opts
341
+ */
342
+ function listSetupProfiles({ type = null, registry = defaultRegistry } = {}) {
343
+ const manifests = registry.all();
344
+ const profiles = [];
345
+ for (const id of Object.keys(manifests).sort()) {
346
+ const manifest = manifests[id];
347
+ if (isHiddenManifest(manifest)) continue;
348
+ if (type && manifest.profile.type !== type) continue;
349
+ profiles.push(projectProfile(manifest));
350
+ }
351
+ return profiles;
352
+ }
353
+
354
+ // ---------------------------------------------------------------------------
355
+ // Installation methods & artifacts
356
+ // ---------------------------------------------------------------------------
357
+
358
+ function strictestMinimum(manifests, component) {
359
+ let max = null;
360
+ for (const m of manifests) {
361
+ const spec = (m.runtime_requirements || {})[component] || {};
362
+ if (spec.minimum && (max === null || resolver.compareVersions(spec.minimum, max) === 1)) {
363
+ max = spec.minimum;
364
+ }
365
+ }
366
+ return max;
367
+ }
368
+
369
+ /**
370
+ * Probe the hub for the artifacts it actually serves (task Phase 3.1:
371
+ * available=true ONLY when the artifact genuinely exists). Each artifact's
372
+ * sha256 endpoint is the authority: reachable + 200 ⇒ available with the
373
+ * real version/sha256; anything else ⇒ unavailable (no fake download URLs).
374
+ *
375
+ * @returns {Promise<{worker_bundle: object, installer: object}>}
376
+ * each: { available, status, version, sha256, bytes, files? }
377
+ */
378
+ async function probeHubArtifacts({ hubUrl = null, fetchImpl = null, timeoutMs = 2500 } = {}) {
379
+ const unavailable = { available: false, status: 'unavailable', version: null, sha256: null, bytes: null };
380
+ const result = { worker_bundle: { ...unavailable }, installer: { ...unavailable } };
381
+ if (!hubUrl) return result;
382
+ const doFetch = fetchImpl || ((url, opts) => fetch(url, opts));
383
+ const targets = [
384
+ ['worker_bundle', `${String(hubUrl).replace(/\/$/, '')}/worker-bundle/sha256`],
385
+ ['installer', `${String(hubUrl).replace(/\/$/, '')}/installer/sha256`],
386
+ ];
387
+ await Promise.all(targets.map(async ([key, url]) => {
388
+ try {
389
+ const controller = new AbortController();
390
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
391
+ const res = await doFetch(url, { signal: controller.signal });
392
+ clearTimeout(timer);
393
+ if (!res || !res.ok) return;
394
+ const body = await res.json();
395
+ if (body && typeof body.sha256 === 'string') {
396
+ result[key] = {
397
+ available: true,
398
+ status: 'available',
399
+ sha256: body.sha256,
400
+ version: typeof body.version === 'string' ? body.version : null,
401
+ bytes: typeof body.bytes === 'number' ? body.bytes : null,
402
+ files: Array.isArray(body.files) ? body.files : undefined,
403
+ };
404
+ }
405
+ } catch (_) { /* hub unreachable — artifact stays unavailable */ }
406
+ }));
407
+ return result;
408
+ }
409
+
410
+ /**
411
+ * Installation methods metadata (task §4): which platform has which
412
+ * lifecycle artifacts. No file extensions, shells or commands here — pure
413
+ * availability metadata the UI renders.
414
+ *
415
+ * Availability is REAL (Phase 3.1): `probe` carries the hub probe result —
416
+ * an artifact is available=true only if the hub actually serves it. The
417
+ * version is taken from the probe (what the hub publishes); the canonical
418
+ * repo package.json is the fallback when the probe is unavailable.
419
+ * download_url is present ONLY for available artifacts — no fake URLs.
420
+ *
421
+ * `status` values: available | draft (implemented, E2E acceptance pending)
422
+ * | planned (not implemented) | unavailable (not served by this deployment).
423
+ */
424
+ function getInstallationMethods({ registry = defaultRegistry, probe = null } = {}) {
425
+ const manifests = Object.values(registry.all()).filter((m) => !isHiddenManifest(m));
426
+ const profileIds = manifests.map((m) => m.profile.id).sort();
427
+ const workerBundleFiles = manifests.length > 0 ? (manifests[0].worker_bundle.files || []).slice() : [];
428
+ const p = probe || {
429
+ worker_bundle: { available: false, status: 'unavailable', version: null, sha256: null },
430
+ installer: { available: false, status: 'unavailable', version: null, sha256: null },
431
+ };
432
+
433
+ const installerAvailable = !!(p.installer && p.installer.available);
434
+ const bundleAvailable = !!(p.worker_bundle && p.worker_bundle.available);
435
+
436
+ const linux = {
437
+ platform: 'linux',
438
+ architectures: ['x86_64'],
439
+ // Capability model: the platform is available when AT LEAST ONE
440
+ // lifecycle artifact is served. A missing installer must not block
441
+ // the Existing ComfyUI flow (worker bundle only) — the UI derives
442
+ // per-mode availability from the artifact flags below.
443
+ status: (installerAvailable || bundleAvailable) ? 'available' : 'unavailable',
444
+ installer: {
445
+ available: installerAvailable,
446
+ // Installer code exists and its tests pass, but E2E acceptance on
447
+ // real GPU hardware is still pending — honest draft marker.
448
+ status: installerAvailable ? 'draft' : 'unavailable',
449
+ version: (p.installer && p.installer.version) || getInstallerVersion(),
450
+ download_url: installerAvailable ? '/gpu/installer' : null,
451
+ sha256: (p.installer && p.installer.sha256) || null,
452
+ signature: null,
453
+ signature_algorithm: null,
454
+ },
455
+ uninstaller: {
456
+ // The Linux uninstaller does not exist yet (a separate lifecycle
457
+ // artifact with its own ownership model — never assumed to be
458
+ // "install --remove"). Schema-ready for available=true later.
459
+ available: false,
460
+ status: 'planned',
461
+ version: null,
462
+ download_url: null,
463
+ sha256: null,
464
+ signature: null,
465
+ signature_algorithm: null,
466
+ },
467
+ worker_bundle: {
468
+ available: bundleAvailable,
469
+ status: bundleAvailable ? 'available' : 'unavailable',
470
+ version: (p.worker_bundle && p.worker_bundle.version) || getWorkerBundleVersion(),
471
+ download_url: bundleAvailable ? '/gpu/worker-bundle' : null,
472
+ sha256: (p.worker_bundle && p.worker_bundle.sha256) || null,
473
+ files: workerBundleFiles,
474
+ },
475
+ supported_profiles: profileIds,
476
+ minimum_requirements: {
477
+ node: strictestMinimum(manifests, 'nodejs'),
478
+ python: strictestMinimum(manifests, 'python'),
479
+ gpu: 'NVIDIA GPU with a CUDA-capable driver (detected by the installer; never installed/upgraded by it)',
480
+ },
481
+ };
482
+
483
+ // Windows (native deployment): the installer bundle is platform-neutral
484
+ // and the hub serves a Windows bootstrap for it — availability mirrors
485
+ // the same hub probe as linux. The honest availability LEVEL lives in
486
+ // deploymentCapabilities (preview); here it is plain artifact metadata.
487
+ const windows = {
488
+ platform: 'windows',
489
+ architectures: ['x86_64'],
490
+ status: (installerAvailable || bundleAvailable) ? 'available' : 'unavailable',
491
+ installer: {
492
+ available: installerAvailable,
493
+ // Implemented and test-covered, production validation pending —
494
+ // the same honest draft marker as linux.
495
+ status: installerAvailable ? 'draft' : 'unavailable',
496
+ version: (p.installer && p.installer.version) || getInstallerVersion(),
497
+ download_url: installerAvailable ? '/gpu/installer' : null,
498
+ sha256: (p.installer && p.installer.sha256) || null,
499
+ signature: null,
500
+ signature_algorithm: null,
501
+ },
502
+ uninstaller: {
503
+ available: false, status: 'planned', version: null,
504
+ download_url: null, sha256: null, signature: null, signature_algorithm: null,
505
+ },
506
+ worker_bundle: {
507
+ available: bundleAvailable,
508
+ status: bundleAvailable ? 'available' : 'unavailable',
509
+ version: (p.worker_bundle && p.worker_bundle.version) || getWorkerBundleVersion(),
510
+ download_url: bundleAvailable ? '/gpu/worker-bundle' : null,
511
+ sha256: (p.worker_bundle && p.worker_bundle.sha256) || null,
512
+ files: workerBundleFiles,
513
+ },
514
+ supported_profiles: profileIds,
515
+ minimum_requirements: {
516
+ node: strictestMinimum(manifests, 'nodejs'),
517
+ python: strictestMinimum(manifests, 'python'),
518
+ gpu: 'NVIDIA GPU with a CUDA-capable driver (detected by the installer; never installed/upgraded by it)',
519
+ },
520
+ };
521
+
522
+ // Docker (legacy UI platform — in the capability model it is the docker
523
+ // DEPLOYMENT of linux). Artifacts mirror linux: the container fetches
524
+ // the installer bundle from the hub itself. The honest availability
525
+ // LEVEL lives in deploymentCapabilities (experimental).
526
+ const docker = {
527
+ platform: 'docker',
528
+ deployment_of: 'linux',
529
+ architectures: ['x86_64'],
530
+ status: (installerAvailable || bundleAvailable) ? 'available' : 'unavailable',
531
+ installer: {
532
+ available: installerAvailable,
533
+ status: installerAvailable ? 'draft' : 'unavailable',
534
+ version: (p.installer && p.installer.version) || getInstallerVersion(),
535
+ download_url: installerAvailable ? '/gpu/installer' : null,
536
+ sha256: (p.installer && p.installer.sha256) || null,
537
+ signature: null,
538
+ signature_algorithm: null,
539
+ },
540
+ uninstaller: {
541
+ available: false, status: 'planned', version: null,
542
+ download_url: null, sha256: null, signature: null, signature_algorithm: null,
543
+ },
544
+ worker_bundle: {
545
+ available: bundleAvailable,
546
+ status: bundleAvailable ? 'available' : 'unavailable',
547
+ version: (p.worker_bundle && p.worker_bundle.version) || getWorkerBundleVersion(),
548
+ download_url: bundleAvailable ? '/gpu/worker-bundle' : null,
549
+ sha256: (p.worker_bundle && p.worker_bundle.sha256) || null,
550
+ files: workerBundleFiles,
551
+ },
552
+ supported_profiles: profileIds,
553
+ minimum_requirements: null,
554
+ };
555
+
556
+ return { methods: [linux, windows, docker] };
557
+ }
558
+
559
+ /**
560
+ * Artifact summary for one platform (task §5/§6). Unknown platform → null
561
+ * (the route answers 404 unsupported_platform).
562
+ */
563
+ function getPlatformArtifacts({ platform = 'linux', registry = defaultRegistry, probe = null } = {}) {
564
+ if (!PLATFORMS.includes(platform)) return null;
565
+ const { methods } = getInstallationMethods({ registry, probe });
566
+ const method = methods.find((m) => m.platform === platform);
567
+ return {
568
+ platform: method.platform,
569
+ architecture: method.architectures[0] || null,
570
+ status: method.status,
571
+ installer: method.installer,
572
+ uninstaller: method.uninstaller,
573
+ worker_bundle: method.worker_bundle,
574
+ supported_profiles: method.supported_profiles,
575
+ };
576
+ }
577
+
578
+ // ---------------------------------------------------------------------------
579
+ // Workflows
580
+ // ---------------------------------------------------------------------------
581
+
582
+ /**
583
+ * Host-side canonical workflows root candidates (first existing wins).
584
+ * backend/ai/workflows is a SHARED HOST ASSET — it never ships inside this
585
+ * package (the backend runtime loads it at startup and the generation
586
+ * package resolves the same ids), so the projection resolves it relative to
587
+ * the package location:
588
+ * dev monorepo / repo-layout distribution — <repo>/backend/ai/workflows
589
+ * backend container (npm-installed package) — /app/ai/workflows
590
+ * legacy package-adjacent layout (MANIFEST_ROOT sibling) — last resort
591
+ */
592
+ const WORKFLOW_ROOT_CANDIDATES = [
593
+ path.join(__dirname, '..', '..', '..', '..', 'backend', 'ai', 'workflows'),
594
+ path.join(__dirname, '..', '..', '..', '..', '..', 'ai', 'workflows'),
595
+ path.join(MANIFEST_ROOT, '..', 'workflows'),
596
+ ];
597
+
598
+ /**
599
+ * UI-safe workflow metadata (task §8). Baseline workflows are EDITABLE
600
+ * starting points — never immutable. No resolver internals, no repository
601
+ * paths; download_url is the public hub endpoint.
602
+ *
603
+ * Phase 3.1 honesty: `baseline_available` is true ONLY when the canonical
604
+ * workflow file actually exists in the repo tree the hub serves; otherwise
605
+ * download_url/sha256 are null (no fake downloads). `revision` is the
606
+ * manifest revision — the canonical workflow artifact version.
607
+ */
608
+ function listWorkflowArtifacts({ profileId = null, registry = defaultRegistry, workflowsRoot = null } = {}) {
609
+ let root = workflowsRoot;
610
+ if (!root) {
611
+ root = WORKFLOW_ROOT_CANDIDATES.find((candidate) => {
612
+ try { return fs.existsSync(candidate); } catch (_) { return false; }
613
+ }) || WORKFLOW_ROOT_CANDIDATES[0];
614
+ }
615
+ const manifests = registry.all();
616
+ const out = [];
617
+ for (const id of Object.keys(manifests).sort()) {
618
+ const manifest = manifests[id];
619
+ if (isHiddenManifest(manifest)) continue;
620
+ if (profileId && manifest.profile.id !== profileId) continue;
621
+ const artifacts = (manifest.workflows && manifest.workflows.artifacts) || [];
622
+ for (const wf of artifacts) {
623
+ const wfId = String(wf.id).replace(/^workflow:/, '');
624
+ let available = false;
625
+ try {
626
+ available = fs.existsSync(path.join(root, wf.filename));
627
+ } catch (_) { available = false; }
628
+ out.push({
629
+ id: wfId,
630
+ name: wf.name,
631
+ profile_id: manifest.profile.id,
632
+ revision: manifest.revision || null,
633
+ baseline_available: available,
634
+ download_url: available ? `/gpu/workflow/${wfId}` : null,
635
+ sha256: available ? (wf.baseline_sha256 || null) : null,
636
+ editable: wf.editable !== false,
637
+ });
638
+ }
639
+ }
640
+ return out;
641
+ }
642
+
643
+ // ---------------------------------------------------------------------------
644
+ // Instructions (server-assembled; the frontend only renders)
645
+ // ---------------------------------------------------------------------------
646
+
647
+ function envTemplateBlock(manifests, { hubUrl = null } = {}) {
648
+ const wb = manifests[0] && manifests[0].worker_bundle;
649
+ const required = (wb && wb.env && wb.env.required) || ['HUB_URL', 'ANIMASTOR_WORKER_TOKEN', 'WORKER_TYPE', 'WORKER_ID'];
650
+ const secrets = (wb && wb.env && wb.env.secrets) || ['ANIMASTOR_WORKER_TOKEN'];
651
+ const types = new Set(manifests.map((m) => m.profile && m.profile.type).filter(Boolean));
652
+ const workerType = types.size === 1 ? [...types][0] : null;
653
+ const lines = required.map((key) => {
654
+ if (secrets.includes(key)) return `${key}=<your-worker-key>`;
655
+ if (key === 'HUB_URL') return hubUrl ? `HUB_URL=${hubUrl}` : `${key}=<hub-url>`;
656
+ if (key === 'WORKER_TYPE') return workerType ? `WORKER_TYPE=${workerType}` : `${key}=<worker-type>`;
657
+ if (key === 'WORKER_ID') return `${key}=<worker-id>`;
658
+ return `${key}=<value>`;
659
+ });
660
+ return lines.join('\n');
661
+ }
662
+
663
+ /**
664
+ * Docker deployment instruction steps — the canonical container flow
665
+ * (linux platform, E2E validated on a VPS: real API worker creation,
666
+ * interactive hidden Worker Key prompt inside the container, Online via
667
+ * beacon, real generation, crash recovery, container restart).
668
+ *
669
+ * The entrypoint (docker/worker/entrypoint.sh) fetches the installer bundle
670
+ * from the hub, verifies the hub-published sha256 and runs the universal
671
+ * installer inside the container. Profile/mode stay separate concepts —
672
+ * they travel as env (ANIMASTOR_PROFILE / ANIMASTOR_MODE), never mixed into
673
+ * the platform/deployment selection, and the Worker Key NEVER appears in
674
+ * any command (entered at the installer's hidden prompt).
675
+ *
676
+ * GPU drivers belong to the HOST environment — the container only sees the
677
+ * GPU through the runtime (--gpus all + NVIDIA Container Toolkit on the
678
+ * host); nothing NVIDIA-related is ever installed inside the container.
679
+ */
680
+ function dockerContainerSteps({ profileIds, mode, hubUrl }) {
681
+ const steps = [];
682
+ steps.push({
683
+ id: 'docker-prerequisites',
684
+ title: 'Docker — what the host needs',
685
+ body: 'The worker runs inside a Docker container on your Linux host.',
686
+ requirements: {
687
+ docker: 'Docker must be available on the host.',
688
+ gpu: 'For NVIDIA GPU workloads, the host must provide NVIDIA drivers and container GPU runtime support (NVIDIA Container Toolkit). GPU drivers belong to the host — never install them inside the container.',
689
+ },
690
+ });
691
+ steps.push({
692
+ id: 'docker-build',
693
+ title: 'Build the worker image',
694
+ body: 'Clone the Animastor repository and build the worker image from its canonical Dockerfile (the image runs the universal installer in docker deployment).',
695
+ code: 'git clone https://github.com/Animastor/animastor.git\ncd animastor\ndocker build -t animastor-worker -f docker/worker/Dockerfile docker/worker',
696
+ });
697
+ steps.push({
698
+ id: 'docker-install',
699
+ title: 'First run — install (interactive)',
700
+ body: 'Run the install container once per profile. The installer asks for the Worker Key (hidden input) inside the container — paste the key saved above. Profile and mode are passed as configuration, never typed.',
701
+ code: profileIds.map((p) => [
702
+ 'docker run -it --rm \\',
703
+ ' -v ~/animastor/data:/data/animastor \\',
704
+ ' --entrypoint /usr/local/bin/entrypoint.sh \\',
705
+ ' -e ANIMASTOR_EXIT_AFTER_INSTALL=1 \\',
706
+ ` -e ANIMASTOR_HUB_URL=${hubUrl || '<hub-url>'} \\`,
707
+ ` -e ANIMASTOR_PROFILE=${p} \\`,
708
+ ` -e ANIMASTOR_MODE=${mode} \\`,
709
+ ' animastor-worker install',
710
+ ].join('\n')).join('\n\n'),
711
+ });
712
+ steps.push({
713
+ id: 'docker-runtime',
714
+ title: 'Runtime container',
715
+ body: 'Start the persistent runtime container. On (re)start it resumes automatically (ComfyUI + worker) and stays alive as PID 1. For NVIDIA GPU hosts add --gpus all — the driver comes from the host.',
716
+ code: [
717
+ 'docker run -d --name animastor-worker \\',
718
+ ' --restart unless-stopped \\',
719
+ ' -v ~/animastor/data:/data/animastor \\',
720
+ ' animastor-worker',
721
+ '# NVIDIA GPU host: add --gpus all to the command above',
722
+ ].join('\n'),
723
+ });
724
+ steps.push({
725
+ id: 'verify',
726
+ title: 'Verify',
727
+ body: 'After the container finishes installing, the worker connects to Animastor automatically. Return to Settings → Private Workers: the status changes to ONLINE after the first heartbeat, usually within ~30 seconds.',
728
+ });
729
+ return steps;
730
+ }
731
+
732
+ /**
733
+ * Dynamic setup instructions (task §9, Phase 3.2 bootstrap flow). Nothing is
734
+ * hardcoded in the frontends: commands, versions and checksums come from
735
+ * canonical metadata. The Worker Key is referenced by placeholder ONLY — its
736
+ * value never enters this response (it is disclosed once by
737
+ * POST /api/v1/workers and entered on the GPU machine through the
738
+ * installer's hidden prompt).
739
+ *
740
+ * Logical model (the worker is ALREADY created when these instructions are
741
+ * rendered — no "create the worker" step exists here):
742
+ *
743
+ * 1. download the bootstrap script (profile/mode embedded in the URL —
744
+ * the user never types them);
745
+ * 2. run it — it downloads + checksum-verifies the installer bundle,
746
+ * unpacks it and runs the real installer, which asks for the Worker
747
+ * Key interactively (hidden input);
748
+ * 3. return to this page — the worker goes ONLINE after its first
749
+ * heartbeat (~30s). A terminal diagnostics command is provided as
750
+ * optional secondary info (verify_command), not as a required step.
751
+ *
752
+ * @param {{profileIds: string[], platform?: string, deployment?: string,
753
+ * mode?: string, origin?: string, registry?: object, probe?: object}} args
754
+ */
755
+ function buildInstructions({
756
+ profileIds,
757
+ platform = 'linux',
758
+ deployment = 'native',
759
+ mode = 'managed',
760
+ origin = '',
761
+ registry = defaultRegistry,
762
+ probe = null,
763
+ }) {
764
+ if (!Array.isArray(profileIds) || profileIds.length === 0) {
765
+ const err = new Error('profile_ids is required (non-empty array)');
766
+ err.code = 'invalid_profile';
767
+ throw err;
768
+ }
769
+ // Platform × Deployment capability validation (single backend authority):
770
+ // legacy UI platform 'docker' normalizes to linux + docker; windows +
771
+ // docker is rejected here — the frontend is never the only gate.
772
+ const target = resolveDeploymentTarget({ platform, deployment });
773
+ if (!INSTALL_MODES.includes(mode)) {
774
+ const err = new Error(`unsupported mode "${mode}" (expected one of ${INSTALL_MODES.join(', ')})`);
775
+ err.code = 'invalid_mode';
776
+ throw err;
777
+ }
778
+ const manifests = profileIds.map((id) => {
779
+ const m = registry.get(id);
780
+ if (!m || isHiddenManifest(m)) {
781
+ const err = new Error(`unknown profile "${id}"`);
782
+ err.code = 'invalid_profile';
783
+ throw err;
784
+ }
785
+ return m;
786
+ });
787
+
788
+ // Artifacts always come from the OS platform method (docker deploys linux).
789
+ const artifacts = getPlatformArtifacts({ platform: target.platform, registry, probe });
790
+ const base = String(origin || '').replace(/\/$/, '');
791
+ const hubUrl = base ? `${base}/gpu` : null;
792
+ const steps = [];
793
+
794
+ const response = {
795
+ platform: target.platform,
796
+ deployment: target.deployment,
797
+ // Honest availability level + informational notice (null when stable).
798
+ availability: target.capability.availability,
799
+ notice: target.capability.notice,
800
+ mode,
801
+ profile_ids: profileIds,
802
+ worker_key_policy: {
803
+ disclosed_once: true,
804
+ disclosed_by: 'POST /api/v1/workers (create) or POST /api/v1/workers/:id/rotate',
805
+ entered_on: 'GPU machine — the installer asks interactively (hidden input)',
806
+ never: ['setup contract responses', 'logs', 'argv', 'URLs', 'installer state files'],
807
+ },
808
+ env: {
809
+ required: (manifests[0].worker_bundle.env && manifests[0].worker_bundle.env.required) || [],
810
+ secrets: (manifests[0].worker_bundle.env && manifests[0].worker_bundle.env.secrets) || ['ANIMASTOR_WORKER_TOKEN'],
811
+ template_block: envTemplateBlock(manifests, { hubUrl }),
812
+ },
813
+ // Installer artifact metadata for the UI: version is the primary UX
814
+ // line; the sha256 belongs in a collapsed/secondary block (shown ONCE).
815
+ installer: null,
816
+ steps,
817
+ // Optional terminal diagnostics — never a required step: the page
818
+ // itself shows the worker status (ONLINE after the first heartbeat).
819
+ verify_command: null,
820
+ };
821
+
822
+ const installerAvailable = !!(artifacts && artifacts.installer.available);
823
+ const bundle = artifacts && artifacts.worker_bundle;
824
+ const bundleAvailable = !!(bundle && bundle.available);
825
+
826
+ if (!installerAvailable) {
827
+ if (target.deployment === 'docker') {
828
+ // The container fetches the installer bundle itself — without
829
+ // the hub-served bundle the deployment cannot start. No fake
830
+ // commands (the host bundle flows do not apply to containers).
831
+ steps.push({
832
+ id: 'installer-unavailable',
833
+ title: 'Docker deployment temporarily unavailable',
834
+ body: 'The installer bundle is temporarily unavailable from this deployment, so the worker container cannot install. Please try again later.',
835
+ });
836
+ return response;
837
+ }
838
+ if (target.platform === 'windows' && mode === 'existing' && bundleAvailable) {
839
+ // The explicit bundle flow is a POSIX path — never rendered as
840
+ // Windows commands in Preview.
841
+ steps.push({
842
+ id: 'installer-unavailable',
843
+ title: 'Installer temporarily unavailable',
844
+ body: 'The Windows installer is temporarily unavailable. Please try again later.',
845
+ });
846
+ return response;
847
+ }
848
+ if (mode === 'existing' && bundleAvailable) {
849
+ // Existing ComfyUI without the installer: the worker runtime
850
+ // bundle alone is enough to connect an already installed ComfyUI.
851
+ // One bundle download — never manual per-file instructions.
852
+ steps.push({
853
+ id: 'prerequisites',
854
+ title: 'Existing ComfyUI — what you need',
855
+ body: 'Your ComfyUI stays untouched — the worker bundle only connects it to Animastor. Nothing is replaced, downgraded or removed.',
856
+ requirements: {
857
+ comfyui: 'installed and running (the worker finds it at http://127.0.0.1:8188; override with COMFY_PORT)',
858
+ node: `>= ${(artifacts.minimum_requirements && artifacts.minimum_requirements.node) || '20'} (for the worker runtime)`,
859
+ gpu: 'NVIDIA GPU with a CUDA-capable driver',
860
+ },
861
+ });
862
+ const bundleFile = `animastor-worker-${bundle.version || 'latest'}.tar.gz`;
863
+ steps.push({
864
+ id: 'download-bundle',
865
+ title: 'Download the worker runtime bundle',
866
+ body: `Download the worker runtime bundle (version ${bundle.version}). It contains the complete worker runtime — no manual per-file downloads.`,
867
+ code: `curl -fsSL -o ${bundleFile} ${base}${bundle.download_url}`,
868
+ checksum: bundle.sha256
869
+ ? { algorithm: 'sha256', value: bundle.sha256, verify_code: `echo "${bundle.sha256} ${bundleFile}" | sha256sum -c -` }
870
+ : null,
871
+ });
872
+ steps.push({
873
+ id: 'unpack-bundle',
874
+ title: 'Unpack the bundle',
875
+ body: 'Unpack the bundle on the GPU machine (e.g. next to your ComfyUI installation).',
876
+ code: `tar -xzf ${bundleFile} && cd animastor-worker`,
877
+ });
878
+ steps.push({
879
+ id: 'configure-worker',
880
+ title: 'Configure the worker',
881
+ body: 'Copy the environment template and fill in your Worker Key (shown once above) — the key value never passes through this contract. HUB_URL is this site address + /gpu.',
882
+ code: `cp .env.example .env\n# then edit .env:\n${envTemplateBlock(manifests, { hubUrl })}`,
883
+ });
884
+ steps.push({
885
+ id: 'start-worker',
886
+ title: 'Start the worker',
887
+ body: 'Start the worker and keep it running (e.g. in tmux/screen or as a systemd service). It verifies the credential, finds your ComfyUI and connects to the hub.',
888
+ code: 'node worker.cjs',
889
+ });
890
+ steps.push({
891
+ id: 'verify',
892
+ title: 'Verify',
893
+ body: 'Return to Settings → Private Workers: the worker status changes CONNECTING → ONLINE within ~30 seconds after the worker starts.',
894
+ });
895
+ return response;
896
+ }
897
+ if (bundleAvailable) {
898
+ // Installer missing but the bundle is served — do not block the
899
+ // whole platform: point at the Existing ComfyUI flow instead.
900
+ steps.push({
901
+ id: 'installer-unavailable',
902
+ title: 'Installer temporarily unavailable',
903
+ body: `The ${platform} installer is temporarily unavailable. Existing ComfyUI setup may still be available — choose the "Existing ComfyUI" mode: the worker runtime bundle is served by this deployment.`,
904
+ });
905
+ return response;
906
+ }
907
+ steps.push({
908
+ id: 'platform-planned',
909
+ title: 'Installation is not available on this platform yet',
910
+ body: `The ${platform} installer is planned but not published. The setup contract will expose it automatically (available=true) once it exists — no frontend change is needed.`,
911
+ });
912
+ return response;
913
+ }
914
+
915
+ // ── Bootstrap flow (installer artifact is served by the hub) ────────
916
+
917
+ const profileParam = encodeURIComponent(profileIds.join(','));
918
+ // platform is EXPLICIT in the bootstrap URL: the hub serves the matching
919
+ // launcher (bash for linux, PowerShell for windows) — no User-Agent
920
+ // sniffing dependency. Never a Worker Key here (credential gates in the
921
+ // bootstrap reject one even if someone tried).
922
+ const bootstrapUrl = `${base}/gpu/installer?profile=${profileParam}&mode=${mode}&platform=${target.platform}`;
923
+ response.installer = {
924
+ version: artifacts.installer.version,
925
+ sha256: artifacts.installer.sha256 || null,
926
+ status: artifacts.installer.status || 'available',
927
+ download_url: bootstrapUrl,
928
+ };
929
+ response.verify_command = '$HOME/animastor/tools/status.sh';
930
+
931
+ if (target.deployment === 'docker') {
932
+ // Docker deployment (linux platform) — the canonical container flow
933
+ // (E2E validated on a VPS). The entrypoint fetches + sha256-verifies
934
+ // the installer bundle from the hub and runs the real installer
935
+ // inside the container (deployment=docker auto-detected there); the
936
+ // Worker Key is asked interactively (hidden input) on first boot.
937
+ steps.push(...dockerContainerSteps({ profileIds, mode, hubUrl }));
938
+ response.installer = {
939
+ version: artifacts.installer.version,
940
+ sha256: artifacts.installer.sha256 || null,
941
+ status: artifacts.installer.status || 'available',
942
+ download_url: `${base}/gpu/installer/bundle`,
943
+ };
944
+ // No host-side verify command for containers — the page heartbeat
945
+ // below is the verification (nothing invented).
946
+ response.verify_command = null;
947
+ return response;
948
+ }
949
+
950
+ if (mode === 'existing') {
951
+ steps.push({
952
+ id: 'prerequisites',
953
+ title: 'Existing ComfyUI — what the installer expects',
954
+ body: 'The installer detects your ComfyUI, Python, Torch, CUDA, GPU, custom nodes, models and workflows itself, then proposes only what is missing. It never replaces, downgrades or removes your components automatically.',
955
+ requirements: {
956
+ comfyui: 'installed (any version — detected and compared, never auto-replaced)',
957
+ python: `>= ${artifacts.minimum_requirements && artifacts.minimum_requirements.python || '3.10'}`,
958
+ torch: 'installed with CUDA support (detected; never auto-replaced)',
959
+ gpu: 'NVIDIA GPU with a CUDA-capable driver',
960
+ node: `>= ${artifacts.minimum_requirements && artifacts.minimum_requirements.node || '20'} (for the installer runtime)`,
961
+ },
962
+ });
963
+ }
964
+
965
+ if (mode === 'isolated') {
966
+ if (target.platform === 'windows') {
967
+ // The explicit per-profile bundle flow is a POSIX path — no
968
+ // invented Windows commands while Windows is Preview.
969
+ steps.push({
970
+ id: 'isolated-unavailable',
971
+ title: 'Isolated mode is not available on Windows yet',
972
+ body: 'The per-profile isolated flow currently ships with Linux instructions only. Use the managed or existing mode for the Windows (Preview) installer.',
973
+ });
974
+ return response;
975
+ }
976
+ // Isolated mode = several independent ComfyUI environments — one
977
+ // installer run per profile into its own root. That is beyond what a
978
+ // single embedded-profile bootstrap run can express, so this
979
+ // power-user path keeps the explicit bundle flow (bootstrap is the
980
+ // canonical path for the wizard modes managed/existing).
981
+ const bundleUrl = `${base}/gpu/installer/bundle`;
982
+ const installerFile = `animastor-installer-${artifacts.installer.version}.tar.gz`;
983
+ response.installer = {
984
+ version: artifacts.installer.version,
985
+ sha256: artifacts.installer.sha256 || null,
986
+ status: artifacts.installer.status || 'available',
987
+ download_url: bundleUrl,
988
+ };
989
+ steps.push({
990
+ id: 'download-bootstrap',
991
+ title: 'Download the installer',
992
+ body: `Download the installer package (version ${artifacts.installer.version}).`,
993
+ code: `curl -fsSL -o ${installerFile} ${bundleUrl}`,
994
+ checksum: artifacts.installer.sha256
995
+ ? { algorithm: 'sha256', value: artifacts.installer.sha256, verify_code: `echo "${artifacts.installer.sha256} ${installerFile}" | sha256sum -c -` }
996
+ : null,
997
+ });
998
+ steps.push({
999
+ id: 'run-bootstrap',
1000
+ title: 'Run the installer (once per profile)',
1001
+ body: 'Isolated mode: run the installer once per profile, each into its own root directory. The Worker Key is asked interactively (hidden input) on each run.',
1002
+ code: profileIds
1003
+ .map((p) => `tar -xzf ${installerFile} && node animastor-installer/src/installer/cli.js install --profile ${p} --mode managed --root "$HOME/animastor/isolated/${p.split('/').pop()}"`)
1004
+ .join('\n'),
1005
+ });
1006
+ steps.push({
1007
+ id: 'verify',
1008
+ title: 'Verify',
1009
+ body: 'After the installer finishes the workers connect to Animastor automatically. Return to Settings → Private Workers: the status changes to ONLINE after the first heartbeat, usually within ~30 seconds.',
1010
+ });
1011
+ return response;
1012
+ }
1013
+
1014
+ if (target.platform === 'windows') {
1015
+ // Windows Native (Preview): the hub serves the PowerShell launcher
1016
+ // for this URL (platform=windows) — never Linux commands here.
1017
+ steps.push({
1018
+ id: 'download-bootstrap',
1019
+ title: 'Download the installer',
1020
+ body: `Download the bootstrap installer (installer version ${artifacts.installer.version}). The profile and connection mode you selected here are already embedded — nothing needs to be typed.`,
1021
+ code: `Invoke-WebRequest -UseBasicParsing -Uri "${bootstrapUrl}" -OutFile animastor-installer.ps1`,
1022
+ });
1023
+
1024
+ steps.push({
1025
+ id: 'run-bootstrap',
1026
+ title: 'Run the installer',
1027
+ body: 'The installer itself downloads and verifies all components (ComfyUI, models, worker), then asks for the Worker Key (hidden input) — paste the key saved above.',
1028
+ code: 'powershell -ExecutionPolicy Bypass -File .\\animastor-installer.ps1',
1029
+ });
1030
+ } else {
1031
+ steps.push({
1032
+ id: 'download-bootstrap',
1033
+ title: 'Download the installer',
1034
+ body: `Download the bootstrap installer (installer version ${artifacts.installer.version}). The profile and connection mode you selected here are already embedded — nothing needs to be typed.`,
1035
+ code: `curl -fsSL -o animastor-installer.sh ${bootstrapUrl}`,
1036
+ });
1037
+
1038
+ steps.push({
1039
+ id: 'run-bootstrap',
1040
+ title: 'Run the installer',
1041
+ body: 'The installer itself downloads and verifies all components (ComfyUI, models, worker), then asks for the Worker Key (hidden input) — paste the key saved above.',
1042
+ code: 'bash animastor-installer.sh',
1043
+ });
1044
+ }
1045
+
1046
+ steps.push({
1047
+ id: 'verify',
1048
+ title: 'Verify',
1049
+ body: 'After the installer finishes the worker connects to Animastor automatically. Return to Settings → Private Workers: the status changes to ONLINE after the first heartbeat, usually within ~30 seconds.',
1050
+ });
1051
+
1052
+ return response;
1053
+ }
1054
+
1055
+ // ---------------------------------------------------------------------------
1056
+ // Worker status adapter & capabilities normalization
1057
+ // ---------------------------------------------------------------------------
1058
+
1059
+ /**
1060
+ * Adapt the existing derived status (ONLINE/OFFLINE/REVOKED) to the
1061
+ * extended UI-safe model. A worker that was created but never seen has no
1062
+ * heartbeat yet — it is CONNECTING (installed-and-starting or still being
1063
+ * set up). NOT_CONFIGURED is frontend-level (no worker record); INSTALLING
1064
+ * and ERROR await future installer check-in / worker error signals.
1065
+ */
1066
+ function adaptSetupStatus({ status, last_seen = null }) {
1067
+ if (status === 'REVOKED') return 'REVOKED';
1068
+ if (status === 'ONLINE') return 'ONLINE';
1069
+ if (last_seen == null) return 'CONNECTING';
1070
+ return 'OFFLINE';
1071
+ }
1072
+
1073
+ /**
1074
+ * Normalize the free-form `capabilities` jsonb into the contract shape.
1075
+ * Passes through REAL data only — never invents fields.
1076
+ * @returns {{profiles?: string[], workflows?: string[], gpu?: {name: string|null, vram_gb: number|null}}|null}
1077
+ */
1078
+ function normalizeCapabilities(raw) {
1079
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
1080
+ const out = {};
1081
+ if (Array.isArray(raw.profiles)) {
1082
+ out.profiles = raw.profiles.filter((p) => typeof p === 'string');
1083
+ }
1084
+ if (Array.isArray(raw.workflows)) {
1085
+ out.workflows = raw.workflows.filter((w) => typeof w === 'string');
1086
+ }
1087
+ if (raw.gpu && typeof raw.gpu === 'object' && !Array.isArray(raw.gpu)) {
1088
+ let vramGb = null;
1089
+ if (typeof raw.gpu.vram_gb === 'number') vramGb = raw.gpu.vram_gb;
1090
+ else if (typeof raw.gpu.vram_mib === 'number') vramGb = Math.round((raw.gpu.vram_mib / 1024) * 10) / 10;
1091
+ out.gpu = {
1092
+ name: typeof raw.gpu.name === 'string' ? raw.gpu.name : null,
1093
+ vram_gb: vramGb,
1094
+ };
1095
+ }
1096
+ return Object.keys(out).length > 0 ? out : null;
1097
+ }
1098
+
1099
+ // ---------------------------------------------------------------------------
1100
+ // Installation plan (UI-safe; NO execution — task §16)
1101
+ // ---------------------------------------------------------------------------
1102
+
1103
+ const RUNTIME_LABELS = Object.freeze({
1104
+ comfyui: 'ComfyUI',
1105
+ torch: 'Torch',
1106
+ python: 'Python',
1107
+ nodejs: 'Node.js',
1108
+ nvidia_driver: 'NVIDIA driver',
1109
+ });
1110
+
1111
+ function mapEntryToAction(entry, { mode, downloadSpecs }) {
1112
+ const conditional = mode === 'existing' || mode === 'isolated';
1113
+ const base = {
1114
+ component: null,
1115
+ name: null,
1116
+ profiles: entry.profiles || [],
1117
+ conditional,
1118
+ };
1119
+ switch (entry.kind) {
1120
+ case 'runtime': {
1121
+ if (entry.component === 'nvidia_driver') return null; // detected only, never installed
1122
+ if (entry.status === 'installed') return { ...base, type: 'KEEP', component: 'runtime', name: RUNTIME_LABELS[entry.component] || entry.component };
1123
+ if (entry.status === 'missing' || entry.action === 'install') {
1124
+ return { ...base, type: 'INSTALL', component: 'runtime', name: RUNTIME_LABELS[entry.component] || entry.component };
1125
+ }
1126
+ return { ...base, type: 'REVIEW', component: 'runtime', name: RUNTIME_LABELS[entry.component] || entry.component };
1127
+ }
1128
+ case 'custom_node': {
1129
+ if (entry.status === 'installed') return { ...base, type: 'KEEP', component: 'custom-node', name: entry.name || entry.id };
1130
+ if (entry.requirement !== 'required') return null; // optional/unknown extras are never auto-installed
1131
+ return { ...base, type: 'INSTALL', component: 'custom-node', name: entry.name || entry.id };
1132
+ }
1133
+ case 'model':
1134
+ case 'model_repo': {
1135
+ if (entry.status === 'installed') return { ...base, type: 'KEEP', component: 'model', name: entry.name || entry.id };
1136
+ if (entry.requirement !== 'required') return null;
1137
+ const spec = downloadSpecs.get(entry.id);
1138
+ return {
1139
+ ...base,
1140
+ type: 'DOWNLOAD',
1141
+ component: 'model',
1142
+ name: entry.name || entry.id,
1143
+ blocked: spec ? !spec.ready : true,
1144
+ size_bytes_approx: spec ? spec.size_bytes_approx : null,
1145
+ };
1146
+ }
1147
+ case 'workflow': {
1148
+ if (entry.status === 'installed') return { ...base, type: 'KEEP', component: 'workflow', name: entry.name || entry.id, editable: true };
1149
+ return { ...base, type: 'DOWNLOAD', component: 'workflow', name: entry.name || entry.id, editable: true };
1150
+ }
1151
+ case 'worker': {
1152
+ if (entry.status === 'installed' && entry.action === 'skip') return { ...base, type: 'KEEP', component: 'worker-bundle', name: `Animastor worker (${entry.worker_type})` };
1153
+ if (entry.action === 'configure') {
1154
+ return { ...base, type: 'CONFIGURE', component: 'worker-env', name: 'Worker configuration (Worker Key entered on the GPU machine — never via this API)' };
1155
+ }
1156
+ return { ...base, type: 'INSTALL', component: 'worker-bundle', name: `Animastor worker (${entry.worker_type})` };
1157
+ }
1158
+ default:
1159
+ return null;
1160
+ }
1161
+ }
1162
+
1163
+ /**
1164
+ * Build a UI-safe installation plan preview (task §16). This is a PROPOSAL
1165
+ * computed from canonical manifests + resolver against a clean environment —
1166
+ * it never starts an installation and never touches any machine. On
1167
+ * mode=existing the real detection happens on the GPU machine; actions are
1168
+ * marked conditional.
1169
+ */
1170
+ function buildSetupPlan({ profileIds, mode, platform = 'linux', deployment = 'native', registry = defaultRegistry }) {
1171
+ if (!Array.isArray(profileIds) || profileIds.length === 0) {
1172
+ const err = new Error('profile_ids is required (non-empty array)');
1173
+ err.code = 'invalid_profile';
1174
+ throw err;
1175
+ }
1176
+ if (!INSTALL_MODES.includes(mode)) {
1177
+ const err = new Error(`unsupported mode "${mode}" (expected one of ${INSTALL_MODES.join(', ')})`);
1178
+ err.code = 'invalid_mode';
1179
+ throw err;
1180
+ }
1181
+ const target = (() => {
1182
+ try {
1183
+ return resolveDeploymentTarget({ platform: platform == null ? 'linux' : platform, deployment });
1184
+ } catch (e) {
1185
+ // The plan is a UI preview: an unsupported combination is an
1186
+ // honest BLOCKED result, not an exception.
1187
+ if (e.code === 'unsupported_combination') {
1188
+ return {
1189
+ platform: platform == null ? 'linux' : platform,
1190
+ deployment,
1191
+ capability: { allowed: false, availability: null, notice: e.message },
1192
+ };
1193
+ }
1194
+ throw e;
1195
+ }
1196
+ })();
1197
+ const manifests = profileIds.map((id) => {
1198
+ const m = registry.get(id);
1199
+ if (!m || isHiddenManifest(m)) {
1200
+ const err = new Error(`unknown profile "${id}"`);
1201
+ err.code = 'invalid_profile';
1202
+ throw err;
1203
+ }
1204
+ return m;
1205
+ });
1206
+ if (mode === 'shared' && manifests.length < 2) {
1207
+ const err = new Error("mode 'shared' requires at least two profiles");
1208
+ err.code = 'invalid_mode';
1209
+ throw err;
1210
+ }
1211
+
1212
+ const warnings = [];
1213
+ const blocks = [];
1214
+
1215
+ // Capability gate — the ONLY unsupported combination (windows + docker)
1216
+ // is honestly BLOCKED; everything else proceeds (validation is a backend
1217
+ // authority, never frontend-only).
1218
+ if (!target.capability.allowed) {
1219
+ return {
1220
+ result: 'BLOCKED',
1221
+ platform: target.platform,
1222
+ deployment: target.deployment,
1223
+ availability: null,
1224
+ mode,
1225
+ profiles: profileIds,
1226
+ actions: [],
1227
+ warnings,
1228
+ blocks: [{
1229
+ code: 'UNSUPPORTED_COMBINATION',
1230
+ message: target.capability.notice || 'This platform and deployment combination is not supported.',
1231
+ }],
1232
+ sharing: null,
1233
+ disk_budget_bytes_approx: null,
1234
+ };
1235
+ }
1236
+
1237
+ // Preview/Experimental combinations stay selectable — informational
1238
+ // warning, never a blocker (the installer prints the same notice).
1239
+ if (target.capability.availability !== 'stable') {
1240
+ warnings.push(target.capability.notice
1241
+ || `${target.platform} + ${target.deployment} is ${target.capability.availability} — production validation is pending`);
1242
+ }
1243
+
1244
+ // Sharing verdict (multi-profile) — machine-readable (task §15).
1245
+ let sharing = null;
1246
+ if (manifests.length > 1) {
1247
+ const shared = resolver.resolveSharedRuntime(manifests);
1248
+ sharing = {
1249
+ verdict: SHARING_VERDICT_MAP[shared.verdict] || 'UNKNOWN',
1250
+ can_share: shared.can_share,
1251
+ message: shared.message,
1252
+ };
1253
+ if (!shared.can_share) warnings.push(shared.message);
1254
+ }
1255
+
1256
+ // Isolated mode: each profile is planned in its own environment
1257
+ // (data model only — no multi-ComfyUI orchestration in Phase 3).
1258
+ const reports = [];
1259
+ if (mode === 'isolated') {
1260
+ for (const m of manifests) {
1261
+ reports.push(resolver.resolveInstallation({
1262
+ manifests: m,
1263
+ environment: resolver.createEmptyEnvironment(`isolated/${m.profile.id}`),
1264
+ mode: 'isolated',
1265
+ }));
1266
+ }
1267
+ if (manifests.length > 1 && !sharing) {
1268
+ sharing = {
1269
+ verdict: 'REQUIRES_ISOLATION',
1270
+ can_share: false,
1271
+ message: 'isolated mode: each profile gets its own ComfyUI environment by definition',
1272
+ };
1273
+ }
1274
+ } else {
1275
+ reports.push(resolver.resolveInstallation({
1276
+ manifests,
1277
+ environment: resolver.createEmptyEnvironment(),
1278
+ mode: mode === 'shared' ? 'shared' : mode,
1279
+ }));
1280
+ }
1281
+
1282
+ // Download specs for missing models — NEVER invent URLs: unresearched
1283
+ // sources become explicit blocks (installer would report BLOCKED too).
1284
+ const downloadSpecs = new Map();
1285
+ for (const report of reports) {
1286
+ for (const entry of report.entries) {
1287
+ if ((entry.kind === 'model' || entry.kind === 'model_repo')
1288
+ && entry.status === 'missing' && entry.requirement === 'required'
1289
+ && !downloadSpecs.has(entry.id)) {
1290
+ const dep = manifests.flatMap((m) => m.dependencies || []).find((d) => d.id === entry.id);
1291
+ if (dep) {
1292
+ const spec = planModelDownload(dep);
1293
+ downloadSpecs.set(entry.id, spec);
1294
+ if (!spec.ready) {
1295
+ blocks.push({
1296
+ code: 'MODEL_SOURCE_NOT_PUBLISHED',
1297
+ message: `${dep.name || dep.id}: download source is not researched yet — the installer refuses to guess URLs (manifest status: ${manifests.find((m) => (m.dependencies || []).some((d) => d.id === dep.id)).status || 'draft'})`,
1298
+ });
1299
+ }
1300
+ }
1301
+ }
1302
+ }
1303
+ }
1304
+
1305
+ const actions = [];
1306
+ const seen = new Set();
1307
+ for (const report of reports) {
1308
+ for (const entry of report.entries) {
1309
+ if (entry.id.startsWith('extra:')) continue; // extras are never part of a plan
1310
+ const action = mapEntryToAction(entry, { mode, downloadSpecs });
1311
+ if (!action) continue;
1312
+ const key = `${action.type}|${action.component}|${action.name}|${action.profiles.join(',')}`;
1313
+ if (seen.has(key)) continue;
1314
+ seen.add(key);
1315
+ actions.push(action);
1316
+ }
1317
+ for (const w of report.warnings) {
1318
+ if (!warnings.includes(w)) warnings.push(w);
1319
+ }
1320
+ }
1321
+
1322
+ // Worker Key configuration is always an interactive on-machine step.
1323
+ actions.push({
1324
+ type: 'CONFIGURE',
1325
+ component: 'worker-env',
1326
+ name: 'Worker configuration (Worker Key entered on the GPU machine — never via this API)',
1327
+ profiles: profileIds.slice(),
1328
+ conditional: false,
1329
+ });
1330
+ actions.push({
1331
+ type: 'VERIFY',
1332
+ component: 'verification',
1333
+ name: 'Post-install verification (resolver diff + registration check)',
1334
+ profiles: profileIds.slice(),
1335
+ conditional: false,
1336
+ });
1337
+
1338
+ for (const m of manifests) {
1339
+ if ((m.status || 'draft') !== 'stable') {
1340
+ warnings.push(`profile ${m.profile.id} is "${m.status || 'draft'}" — E2E acceptance on real GPU hardware is pending`);
1341
+ }
1342
+ if ((m.hardware || {}).gpu_min_vram_gb == null) {
1343
+ warnings.push(`profile ${m.profile.id}: minimum VRAM is unknown — preflight must measure, no automatic judgement`);
1344
+ }
1345
+ }
1346
+ if (mode === 'existing') {
1347
+ warnings.push('plan computed against a clean environment — on your machine the installer detects ComfyUI/Python/Torch/CUDA/nodes/models itself and installs only what is missing; user components are never replaced or removed automatically');
1348
+ }
1349
+
1350
+ const diskBudget = manifests.reduce(
1351
+ (sum, m) => sum + ((m.disk_budget && m.disk_budget.models_bytes_approx) || 0), 0
1352
+ );
1353
+
1354
+ let result = 'READY';
1355
+ if (blocks.length > 0) result = 'BLOCKED';
1356
+ else if (warnings.length > 0) result = 'READY_WITH_WARNINGS';
1357
+
1358
+ return {
1359
+ result,
1360
+ platform: target.platform,
1361
+ deployment: target.deployment,
1362
+ availability: target.capability.availability,
1363
+ mode,
1364
+ profiles: profileIds,
1365
+ actions,
1366
+ warnings,
1367
+ blocks,
1368
+ sharing,
1369
+ disk_budget_bytes_approx: diskBudget > 0 ? diskBudget : null,
1370
+ };
1371
+ }
1372
+
1373
+ module.exports = {
1374
+ PLATFORMS,
1375
+ OS_PLATFORMS,
1376
+ DEPLOYMENTS,
1377
+ AVAILABILITY_LEVELS,
1378
+ INSTALL_MODES,
1379
+ SETUP_WORKER_STATUSES,
1380
+ SHARING_VERDICT_MAP,
1381
+ getInstallerVersion,
1382
+ getWorkerBundleVersion,
1383
+ createManifestRegistry,
1384
+ getManifestRegistry,
1385
+ isHiddenManifest,
1386
+ listSetupProfiles,
1387
+ getInstallationMethods,
1388
+ getPlatformArtifacts,
1389
+ probeHubArtifacts,
1390
+ listWorkflowArtifacts,
1391
+ buildInstructions,
1392
+ adaptSetupStatus,
1393
+ normalizeCapabilities,
1394
+ buildSetupPlan,
1395
+ deploymentCapabilities,
1396
+ resolveDeploymentTarget,
1397
+ // exposed for tests
1398
+ projectProfile,
1399
+ displayNameFromSlug,
1400
+ loadManifest,
1401
+ };