@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,1067 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Animastor GPU Worker Installer CLI — Phase 2.
6
+ *
7
+ * Usage:
8
+ * animastor-installer detect [--root PATH] [--worker-dir PATH]
9
+ * animastor-installer plan --profile P[,P2] [--mode managed|existing|shared] [--root PATH]
10
+ * animastor-installer install --profile P[,P2] [--mode ...] [--root PATH] [--yes] [--dry-run] [--worker-dir PATH] [--hub-url URL]
11
+ * [--start-comfy] [--comfy-port N] [--start-worker]
12
+ * [--accept-reference-runtime]
13
+ * animastor-installer verify [--profile P[,P2]] [--root PATH] [--worker-dir PATH] [--hub-url URL]
14
+ * animastor-installer resume
15
+ * animastor-installer uninstall [--all] [--yes] [--dry-run] [--state PATH] [--home PATH]
16
+ *
17
+ * Flags:
18
+ * --profile P Generation profile id (repeatable or comma-separated)
19
+ * --mode MODE managed | existing | shared (default: infer from detection)
20
+ * --root PATH ComfyUI root directory (default: ~/ComfyUI)
21
+ * --worker-dir PATH Worker bundle directory (default: ~/animastor/worker)
22
+ * --hub-url URL GPU Hub base URL (default: https://animastor.in/gpu)
23
+ * --repo-root PATH Animastor repo root (default: derived from cli.js location)
24
+ * --state PATH Install state file path
25
+ * --yes Auto-confirm all prompts
26
+ * --dry-run Show plan only; never perform real changes
27
+ * --all uninstall: full uninstall (everything recorded in the manifest)
28
+ */
29
+
30
+ const fs = require('fs');
31
+ const path = require('path');
32
+ const readline = require('readline');
33
+
34
+ const { createRealIo, createDryRunIo } = require('./engine/io');
35
+ const { createLogger } = require('./engine/logger');
36
+ const { createTermRenderer } = require('./engine/term');
37
+ const platforms = require('./platform');
38
+ const { probeEnvironment, renderDetection } = require('./engine/probe');
39
+ const { runInstallation, loadResumableState, renderResumeSummary } = require('./engine/engine');
40
+ const prereq = require('./engine/prereq');
41
+ const stateStore = require('./engine/state');
42
+ const management = require('./management');
43
+ const resolver = require('./compatibility-resolver');
44
+ const { buildInstallPlan, renderPlanText } = require('./install-plan');
45
+ const manifest = require('./install-manifest');
46
+ const uninstaller = require('./uninstaller');
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // Paths (platform-specific defaults; the platform adapter owns them)
50
+ // ---------------------------------------------------------------------------
51
+
52
+ const CLI_ROOT = path.resolve(__dirname, '..', '..');
53
+ const REPO_ROOT = path.resolve(__dirname, '..', '..', '..', '..');
54
+
55
+ /**
56
+ * The platform adapter is auto-detected ONCE at CLI startup. An unsupported
57
+ * host (e.g. macOS) fails here — clearly, early, before any side effect —
58
+ * instead of somewhere inside a Linux-only code path.
59
+ * (Resolution is silent; support notices are printed by main().)
60
+ */
61
+ function bootPlatform() {
62
+ return platforms.resolveRuntime();
63
+ }
64
+
65
+ const PLATFORM_RUNTIME = bootPlatform();
66
+ const PLATFORM_ADAPTER = PLATFORM_RUNTIME.adapter;
67
+
68
+ /** Support notices: preview platform / experimental deployment. */
69
+ function printPlatformNotices() {
70
+ if (!PLATFORM_ADAPTER.productionReady) {
71
+ console.error('=========================================================================');
72
+ console.error(` PREVIEW PLATFORM: ${PLATFORM_ADAPTER.displayName}`);
73
+ console.error(` ${PLATFORM_ADAPTER.previewNotice || 'This platform is not production-supported yet.'}`);
74
+ console.error('=========================================================================');
75
+ }
76
+ if (PLATFORM_RUNTIME.deployment === 'docker' && !PLATFORM_RUNTIME.deploymentAdapter.productionReady) {
77
+ console.error(`[notice] docker deployment detected (${PLATFORM_RUNTIME.deploymentAdapter.displayName}) — experimental, NOT production-supported yet.`);
78
+ }
79
+ }
80
+
81
+ /** Home directory, respecting the platform's env variable. */
82
+ function homeDir() {
83
+ return process.env[PLATFORM_ADAPTER.HOME_ENV]
84
+ || require('os').homedir();
85
+ }
86
+
87
+ const DEFAULT_ROOT = PLATFORM_ADAPTER.defaultRoot(homeDir());
88
+ const DEFAULT_WORKER_DIR = PLATFORM_ADAPTER.defaultWorkerDir(homeDir());
89
+ const DEFAULT_HUB_URL = 'https://animastor.in/gpu';
90
+
91
+ // ---------------------------------------------------------------------------
92
+ // Argument parsing
93
+ // ---------------------------------------------------------------------------
94
+
95
+ function parseArgs(argv) {
96
+ const args = argv.slice(2);
97
+ const parsed = { command: null, profiles: [], flags: {} };
98
+ const positional = [];
99
+ for (let i = 0; i < args.length; i++) {
100
+ const a = args[i];
101
+ if (a.startsWith('--')) {
102
+ const key = a.slice(2);
103
+ if (['yes', 'dry-run', 'resume', 'start-comfy', 'start-worker', 'no-start-comfy', 'no-start-worker', 'all', 'accept-reference-runtime', 'accept-runtime-change', 'install-tools', 'no-tools'].includes(key)) {
104
+ parsed.flags[key] = true;
105
+ } else {
106
+ const val = args[++i];
107
+ parsed.flags[key] = val || '';
108
+ }
109
+ } else {
110
+ positional.push(a);
111
+ }
112
+ }
113
+ parsed.command = positional[0] || null;
114
+ const profileFlag = parsed.flags.profile || '';
115
+ if (profileFlag) {
116
+ parsed.profiles = profileFlag.split(',').map((s) => s.trim()).filter(Boolean);
117
+ }
118
+ // Normalize: every cmd* receives `flags` and reads flags.profiles
119
+ parsed.flags.profiles = parsed.profiles;
120
+ return parsed;
121
+ }
122
+
123
+ function resolveRoot(flags) {
124
+ return flags.root || DEFAULT_ROOT;
125
+ }
126
+
127
+ function resolveWorkerDir(flags) {
128
+ return flags['worker-dir'] || DEFAULT_WORKER_DIR;
129
+ }
130
+
131
+ function resolveHubUrl(flags) {
132
+ return flags['hub-url'] || DEFAULT_HUB_URL;
133
+ }
134
+
135
+ function resolveRepoRoot(flags) {
136
+ return flags['repo-root'] || REPO_ROOT;
137
+ }
138
+
139
+ function resolveStatePath(flags) {
140
+ return flags.state || path.join(resolveRoot(flags), '.animastor-installer', 'install-state.json');
141
+ }
142
+
143
+ /**
144
+ * Management tools install directory: next to the worker/runtime
145
+ * (<workerDir parent>/tools, e.g. ~/animastor/tools). Overridable.
146
+ */
147
+ function resolveToolsDir(flags) {
148
+ return flags['tools-dir'] || path.join(path.dirname(resolveWorkerDir(flags)), 'tools');
149
+ }
150
+
151
+ /**
152
+ * Resolve the management runtime targets for the tool subcommands
153
+ * (status / monitor / reboot-*). Explicit flags win over the install state;
154
+ * a missing worker dir falls back to the documented default layout.
155
+ */
156
+ function managementTargets(io, flags) {
157
+ const targets = management.resolveTargets(io, {
158
+ statePath: resolveStatePath(flags),
159
+ root: flags.root || null,
160
+ workerDir: flags['worker-dir'] || null,
161
+ port: flags.port ? Number(flags.port) : null,
162
+ });
163
+ if (!targets.workerDir) targets.workerDir = DEFAULT_WORKER_DIR;
164
+ return targets;
165
+ }
166
+
167
+ /**
168
+ * Shared ownership guard for every management command: blocks a sudo run
169
+ * against a user-owned installation and any cross-tenant access (same rules
170
+ * as the installer gates). Prints the violations and sets the exit code.
171
+ * @returns {boolean} true when access is allowed
172
+ */
173
+ function guardManagementAccess(io, targets) {
174
+ const access = management.checkAccess(io, targets);
175
+ if (!access.ok) {
176
+ console.error('Management tools stopped because of an ownership mismatch:');
177
+ for (const v of access.violations) console.error(` ${v.message}`);
178
+ process.exitCode = 1;
179
+ return false;
180
+ }
181
+ return true;
182
+ }
183
+
184
+ /**
185
+ * Management-tools decision: explicit flags win; a decision recorded by a
186
+ * previous run is kept (tools are part of the installation state and are
187
+ * refreshed idempotently); otherwise ask / default to Yes (interactive runs
188
+ * prompt "Install command-line management tools?").
189
+ */
190
+ async function resolveToolsDecision({ flags, prompt = null, prior = null }) {
191
+ if (flags['no-tools']) return false;
192
+ if (flags['install-tools']) return true;
193
+ if (prior === true || prior === false) return prior;
194
+ if (prompt) return prompt.confirm('Install command-line management tools?');
195
+ return true; // non-interactive default: tools are part of a normal installation
196
+ }
197
+
198
+ function priorToolsDecision(io, statePath) {
199
+ const st = statePath ? stateStore.loadState(io, statePath) : null;
200
+ return st && st.decisions && typeof st.decisions.install_management_tools === 'boolean'
201
+ ? st.decisions.install_management_tools
202
+ : null;
203
+ }
204
+
205
+ /**
206
+ * Host gates that run BEFORE any heavy change (plan execution, venv, clone,
207
+ * model downloads): Python venv/ensurepip/pip prerequisites and ownership
208
+ * mixing (sudo vs. normal user). On failure prints the exact remediation
209
+ * and exits — the installer never ploughs on into an unrecoverable state.
210
+ */
211
+ function runHostGates(realIo, { paths, dryRun = false, stateUid = null, deep = true, venvDir = null }) {
212
+ const uid = prereq.currentUid();
213
+ const ownership = prereq.checkOwnership(realIo, {
214
+ paths,
215
+ home: prereq.currentHome(),
216
+ currentUid: uid,
217
+ stateUid,
218
+ });
219
+ if (!ownership.ok) {
220
+ console.error('\nInstallation stopped because of an ownership mismatch:');
221
+ for (const v of ownership.violations) console.error(` ${v.message}`);
222
+ console.error('\nDo not mix sudo and normal-user installs in the same home directory.');
223
+ process.exit(1);
224
+ }
225
+ if (dryRun) return;
226
+ const gate = prereq.checkPythonPrerequisites(realIo, { python: 'python3', deep, existingVenvDir: venvDir });
227
+ if (!gate.ok) {
228
+ console.error('');
229
+ for (const line of prereq.renderRemediation(gate.failure)) console.error(line);
230
+ process.exit(1);
231
+ }
232
+ }
233
+
234
+ // ---------------------------------------------------------------------------
235
+ // Interactive prompts
236
+ // ---------------------------------------------------------------------------
237
+
238
+ function createPrompt() {
239
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
240
+ return {
241
+ async confirm(question) {
242
+ return new Promise((resolve) => {
243
+ rl.question(`${question} [Yes/No] `, (answer) => {
244
+ resolve(/^(y|yes)$/i.test(answer.trim()));
245
+ });
246
+ });
247
+ },
248
+ async select(question, options) {
249
+ return new Promise((resolve) => {
250
+ const text = `${question}\n${options.map((o, i) => ` [${i + 1}] ${o}`).join('\n')}\n> `;
251
+ rl.question(text, (answer) => {
252
+ const n = parseInt(answer, 10);
253
+ resolve(options[(n - 1) || 0] || options[0]);
254
+ });
255
+ });
256
+ },
257
+ async secret(question) {
258
+ // TTY: hidden raw-mode input (no echo). Non-TTY (piped input /
259
+ // automation): plain line input. In BOTH cases the value is never
260
+ // echoed to the output stream, never logged, never stored in
261
+ // state, never passed via argv.
262
+ if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') {
263
+ return new Promise((resolve) => {
264
+ process.stdout.write(`${question}: `);
265
+ let value = '';
266
+ process.stdin.setRawMode(true);
267
+ process.stdin.resume();
268
+ const onData = (ch) => {
269
+ const c = ch.toString();
270
+ if (c === '\n' || c === '\r') {
271
+ process.stdin.setRawMode(false);
272
+ process.stdin.pause();
273
+ process.stdin.removeListener('data', onData);
274
+ process.stdout.write('\n');
275
+ resolve(value || null);
276
+ } else if (c === '\u0003') { // Ctrl+C
277
+ process.stdin.setRawMode(false);
278
+ process.stdin.pause();
279
+ process.stdin.removeListener('data', onData);
280
+ resolve(null);
281
+ } else if (c === '\u007F' || c === '\b') {
282
+ if (value.length > 0) value = value.slice(0, -1);
283
+ } else {
284
+ value += c;
285
+ }
286
+ };
287
+ process.stdin.on('data', onData);
288
+ });
289
+ }
290
+ return new Promise((resolve) => {
291
+ rl.question(`${question}: `, (answer) => resolve(answer ? String(answer) : null));
292
+ });
293
+ },
294
+ close() { rl.close(); },
295
+ };
296
+ }
297
+
298
+ // ---------------------------------------------------------------------------
299
+ // Commands
300
+ // ---------------------------------------------------------------------------
301
+
302
+ /**
303
+ * Resolve the environment against the manifests and build the install plan —
304
+ * the ONLY call shape that produces a plan in the CLI. The plan is ALWAYS
305
+ * built from a freshly resolved report passed under the `report` key, so
306
+ * buildInstallPlan can never be invoked with a missing/undefined report.
307
+ * The plan is re-derived after the interactive prompts because decisions
308
+ * change it; the report is re-resolved at the same time (single source).
309
+ */
310
+ function resolveAndPlan({ manifests, env, mode, decisions }) {
311
+ const report = resolver.resolveInstallation({ manifests, environment: env, mode });
312
+ const plan = buildInstallPlan({ report, manifests, decisions });
313
+ return { report, plan };
314
+ }
315
+
316
+ /** Secret values collected interactively — memory-only, never persisted. */
317
+ function makeSecretProvider(secrets) {
318
+ if (!secrets || Object.keys(secrets).length === 0) return null;
319
+ return async (name) => (Object.prototype.hasOwnProperty.call(secrets, name) ? secrets[name] : null);
320
+ }
321
+
322
+ async function cmdDetect(flags) {
323
+ const root = resolveRoot(flags);
324
+ const workerDir = resolveWorkerDir(flags);
325
+ const io = createRealIo();
326
+ const env = probeEnvironment(io, { root, workerDir, crypto: require('crypto') });
327
+ console.log(renderDetection(env));
328
+ }
329
+ async function cmdPlan(flags) {
330
+ if (flags.profiles.length === 0) {
331
+ console.error('error: --profile is required');
332
+ process.exit(1);
333
+ }
334
+ const root = resolveRoot(flags);
335
+ const workerDir = resolveWorkerDir(flags);
336
+ const hubUrl = resolveHubUrl(flags);
337
+ const repoRoot = resolveRepoRoot(flags);
338
+ const io = createRealIo();
339
+ const crypto = require('crypto');
340
+ const env = probeEnvironment(io, { root, workerDir, crypto, workerType: null });
341
+
342
+ const loadedManifests = flags.profiles.map((p) => manifest.loadManifest(p));
343
+ const mode = flags.mode || (env.comfyui && env.comfyui.present ? 'existing' : 'managed');
344
+ const { plan } = resolveAndPlan({ manifests: loadedManifests, env, mode, decisions: {} });
345
+ console.log(plan.plan_text);
346
+ }
347
+
348
+ /**
349
+ * The shared terminal renderer for an install run: ONE stream for installer
350
+ * status (logger sink), the download progress line and the busy spinner, so
351
+ * log lines erase and redraw around the live status instead of overwriting
352
+ * it. Terminals with a non-UTF-8 locale get an ASCII spinner fallback.
353
+ */
354
+ function createScreen() {
355
+ const locale = String(process.env.LC_ALL || process.env.LANG || '');
356
+ const ascii = locale !== '' && !/utf-?8/i.test(locale);
357
+ return createTermRenderer({
358
+ isTTY: !!process.stdout.isTTY,
359
+ write: (s) => { process.stdout.write(s); },
360
+ ascii,
361
+ });
362
+ }
363
+
364
+ async function cmdInstall(flags) {
365
+ if (flags.profiles.length === 0) {
366
+ console.error('error: --profile is required');
367
+ process.exit(1);
368
+ }
369
+ const root = resolveRoot(flags);
370
+ const workerDir = resolveWorkerDir(flags);
371
+ const hubUrl = resolveHubUrl(flags);
372
+ const repoRoot = resolveRepoRoot(flags);
373
+ const statePath = resolveStatePath(flags);
374
+ const dryRun = flags['dry-run'] || false;
375
+ const yes = flags.yes || false;
376
+ const crypto = require('crypto');
377
+
378
+ // Probing is read-only and always runs against the REAL io. In dry-run
379
+ // mode the guarded io is used ONLY inside the engine, where every
380
+ // mutating operation would throw a "dry-run violation".
381
+ const realIo = createRealIo();
382
+ const screen = createScreen();
383
+ const logger = createLogger({ io: realIo, sink: (line) => screen.print(line) });
384
+ const loadedManifests = flags.profiles.map((p) => manifest.loadManifest(p));
385
+ const mode = flags.mode || 'managed';
386
+
387
+ const env = probeEnvironment(realIo, {
388
+ root, workerDir, crypto,
389
+ workerType: loadedManifests.length === 1 ? (loadedManifests[0].worker_bundle || {}).worker_type : null,
390
+ });
391
+
392
+ // Prerequisites & ownership BEFORE the plan/confirmation flow: a missing
393
+ // python3.X-venv must be reported up front, with the exact apt command,
394
+ // not after the user has answered every prompt.
395
+ runHostGates(realIo, {
396
+ paths: [root, workerDir, statePath, resolveToolsDir(flags)].filter(Boolean),
397
+ dryRun,
398
+ deep: true,
399
+ venvDir: path.join(root, 'venv'),
400
+ });
401
+
402
+ // The dry-run guard wraps everything handed to the engine so any
403
+ // accidental mutation throws "dry-run violation" instead of executing.
404
+ const io = dryRun ? createDryRunIo(realIo) : realIo;
405
+
406
+ const { plan } = resolveAndPlan({ manifests: loadedManifests, env, mode, decisions: {} });
407
+
408
+ console.log(plan.plan_text);
409
+
410
+ // CPU-only mode is always announced explicitly and confirmed before any
411
+ // change: the user must see that performance will be significantly lower.
412
+ const device = env.device || (env.gpu ? 'cuda' : 'cpu');
413
+ if (device === 'cpu' && !dryRun) {
414
+ console.log('\n=========================================================================');
415
+ console.log(' CPU-ONLY MODE: no supported GPU was detected.');
416
+ console.log(' A CPU build of PyTorch will be installed and ComfyUI will run');
417
+ console.log(' with --cpu. Performance will be SIGNIFICANTLY lower.');
418
+ console.log(' This mode is intended for the TTS/audio profile test scenario.');
419
+ console.log('=========================================================================');
420
+ if (!yes) {
421
+ const prompt = createPrompt();
422
+ const proceed = await prompt.confirm('Continue with the CPU-only installation?');
423
+ prompt.close();
424
+ if (!proceed) {
425
+ console.log('Aborted — nothing was changed.');
426
+ process.exit(0);
427
+ }
428
+ }
429
+ }
430
+
431
+ if (dryRun) {
432
+ console.log('\n[dry-run] zero mutations performed');
433
+ return;
434
+ }
435
+
436
+ if (plan.blocked.length > 0) {
437
+ console.error('\nInstallation blocked — see above for details');
438
+ process.exit(1);
439
+ }
440
+
441
+ if (plan.awaiting_decisions.length > 0 && !yes) {
442
+ const prompt = createPrompt();
443
+ const decisions = {};
444
+ // Management tools: a decision from a previous run is kept; otherwise
445
+ // ask (explicit flags still win).
446
+ decisions.install_management_tools = await resolveToolsDecision({
447
+ flags, prompt, prior: priorToolsDecision(realIo, statePath),
448
+ });
449
+ // Explicit consent flags apply to interactive runs exactly as they do
450
+ // to --yes runs (parity): without them a reference-grade ComfyUI
451
+ // source (manifest basis=unknown, D1) can never be accepted here.
452
+ if (flags['accept-reference-runtime']) decisions.accept_reference_runtime = true;
453
+ if (flags['accept-runtime-change']) decisions.accept_runtime_change = true;
454
+ // Secret VALUES live only in this closure — never in decisions, logs,
455
+ // state, or argv. The engine receives them via secretProvider.
456
+ const secrets = {};
457
+ for (const stepId of plan.awaiting_decisions) {
458
+ const step = plan.steps.find((s) => s.id === stepId);
459
+ if (!step || !step.prompt) continue;
460
+ if (stepId === 'worker-key' && decisions.worker_setup === false) {
461
+ // worker setup was declined — the key prompt is skipped too
462
+ decisions.worker_key_provided = false;
463
+ continue;
464
+ }
465
+ if (step.kind === 'secret-prompt') {
466
+ // Worker Key step: real hidden input (never a Yes/No confirm —
467
+ // a typed token must not be misread as an answer). Only the
468
+ // boolean fact "provided" enters the decisions; the value
469
+ // itself is handed to the engine through secretProvider.
470
+ let provided = false;
471
+ for (const key of step.secret_keys || []) {
472
+ const value = await prompt.secret(`Enter ${key} (hidden input)`);
473
+ if (value) {
474
+ secrets[key] = value;
475
+ logger.registerSecret(value); // redact from ALL further output
476
+ provided = true;
477
+ }
478
+ }
479
+ decisions.worker_key_provided = provided;
480
+ continue;
481
+ }
482
+ const answer = await prompt.confirm(step.prompt.question);
483
+ if (step.consent === 'accept_reference_runtime') {
484
+ decisions.accept_reference_runtime = answer;
485
+ continue;
486
+ }
487
+ if (stepId === 'comfyui-update') decisions.comfyui_update = answer ? 'yes' : 'no';
488
+ else if (stepId === 'custom-nodes') decisions.install_custom_nodes = answer;
489
+ else if (stepId === 'models') decisions.install_models = answer;
490
+ else if (stepId === 'workflows') decisions.workflows = answer ? 'all' : 'none';
491
+ else if (stepId === 'worker-setup') decisions.worker_setup = answer;
492
+ else if (stepId === 'worker-key') decisions.worker_key_provided = answer;
493
+ }
494
+ prompt.close();
495
+
496
+ // Re-resolve and rebuild the plan with the recorded decisions — one
497
+ // call shape, so the rebuilt plan always has a resolution report.
498
+ const { plan: plan2 } = resolveAndPlan({ manifests: loadedManifests, env, mode, decisions });
499
+
500
+ if (plan2.awaiting_decisions.length > 0) {
501
+ console.error('\nStill awaiting decisions after prompts — cannot proceed');
502
+ process.exit(1);
503
+ }
504
+ if (plan2.blocked.length > 0) {
505
+ console.error('\nInstallation blocked after decisions — see above');
506
+ process.exit(1);
507
+ }
508
+
509
+ const result = await runInstallation({
510
+ manifests: loadedManifests, mode, io,
511
+ roots: { comfyuiRoot: root, workerDir, statePath, repoRoot, hubUrl, toolsDir: resolveToolsDir(flags) },
512
+ decisions, secretProvider: makeSecretProvider(secrets),
513
+ logger, crypto, env, dryRun, options: { ...installOptions(flags), term: screen },
514
+ });
515
+ printResult(result);
516
+ } else {
517
+ // All decisions pre-set or no decisions needed
518
+ const decisions = {};
519
+ if (yes) {
520
+ decisions.comfyui_update = 'yes';
521
+ decisions.install_custom_nodes = true;
522
+ decisions.install_models = true;
523
+ decisions.workflows = 'all';
524
+ decisions.worker_setup = true;
525
+ decisions.worker_key_provided = true;
526
+ if (flags['accept-reference-runtime']) decisions.accept_reference_runtime = true;
527
+ if (flags['accept-runtime-change']) decisions.accept_runtime_change = true;
528
+ }
529
+ decisions.install_management_tools = await resolveToolsDecision({
530
+ flags, prompt: null, prior: priorToolsDecision(realIo, statePath),
531
+ });
532
+ const result = await runInstallation({
533
+ manifests: loadedManifests, mode, io,
534
+ roots: { comfyuiRoot: root, workerDir, statePath, repoRoot, hubUrl, toolsDir: resolveToolsDir(flags) },
535
+ decisions, logger, crypto, env, dryRun, options: { ...installOptions(flags), term: screen },
536
+ });
537
+ printResult(result);
538
+ }
539
+ }
540
+
541
+ function installOptions(flags) {
542
+ return {
543
+ // Managed mode starts services by default (engine); these flags only
544
+ // carry an explicit ON (--start-comfy) or OFF (--no-start-comfy).
545
+ startComfyui: flags['start-comfy'] === true ? true : flags['no-start-comfy'] === true ? false : undefined,
546
+ comfyPort: flags['comfy-port'] ? Number(flags['comfy-port']) : undefined,
547
+ verifyTimeoutMs: flags['verify-timeout-ms'] ? Number(flags['verify-timeout-ms']) : undefined,
548
+ // --start-worker: launch the installed worker (node worker.cjs) as a
549
+ // detached daemon after the bundle+.env steps and check it is alive
550
+ // during verification. Without it the worker stays stopped (the
551
+ // installer never starts background services unprompted).
552
+ startWorker: flags['start-worker'] === true ? true : flags['no-start-worker'] === true ? false : undefined,
553
+ };
554
+ }
555
+
556
+ /**
557
+ * resume — continue an interrupted installation from install-state.json.
558
+ *
559
+ * The state file is the source of "what has been attempted"; disk truth is
560
+ * re-verified for every artifact. If there is NO state file, resume does NOT
561
+ * silently start a new installation.
562
+ */
563
+ async function cmdResume(flags) {
564
+ const root = resolveRoot(flags);
565
+ const workerDir = resolveWorkerDir(flags);
566
+ const hubUrl = resolveHubUrl(flags);
567
+ const repoRoot = resolveRepoRoot(flags);
568
+ const statePath = resolveStatePath(flags);
569
+ const crypto = require('crypto');
570
+
571
+ const io = createRealIo();
572
+ const check = loadResumableState(io, statePath);
573
+ if (!check.ok) {
574
+ console.log('No resumable installation state found.');
575
+ if (check.reason === 'state-has-no-profiles') {
576
+ console.log(`(state file at ${statePath} exists but records no profiles — cannot resume)`);
577
+ }
578
+ process.exit(1);
579
+ }
580
+
581
+ const st = check.state;
582
+ console.log(`Resuming installation of ${st.profiles.join(' + ')}`);
583
+ for (const line of renderResumeSummary(st)) console.log(line);
584
+
585
+ // Resume/state semantics after a UID change: an installation created by
586
+ // another user must never be continued under the current one (that is
587
+ // how root-owned files end up inside a user's home).
588
+ runHostGates(io, {
589
+ paths: [root, statePath, workerDir, resolveToolsDir(flags)].filter(Boolean),
590
+ dryRun: false,
591
+ deep: true,
592
+ venvDir: path.join(root, 'venv'),
593
+ stateUid: st.owner_uid != null ? st.owner_uid : null,
594
+ });
595
+
596
+ let loadedManifests;
597
+ try {
598
+ loadedManifests = st.profiles.map((p) => manifest.loadManifest(p));
599
+ } catch (err) {
600
+ console.error(`fatal: cannot load profile manifests recorded in state: ${err.message}`);
601
+ process.exit(1);
602
+ }
603
+
604
+ const mode = st.mode || flags.mode || 'managed';
605
+ const screen = createScreen();
606
+ const logger = createLogger({ io, sink: (line) => screen.print(line) });
607
+ const env = probeEnvironment(io, {
608
+ root, workerDir, crypto,
609
+ workerType: loadedManifests.length === 1 ? (loadedManifests[0].worker_bundle || {}).worker_type : null,
610
+ });
611
+
612
+ // restored non-secret decisions from state; CLI --yes can still widen them.
613
+ // Explicit consent flags keep their parity with `install` on resume too —
614
+ // a blocked runtime/reference decision must be resolvable via resume.
615
+ const decisions = { ...(st.decisions || {}), ...(flags.yes ? yesDecisions() : {}) };
616
+ if (flags['accept-reference-runtime']) decisions.accept_reference_runtime = true;
617
+ if (flags['accept-runtime-change']) decisions.accept_runtime_change = true;
618
+ // --no-tools / --install-tools override a previously recorded decision on
619
+ // resume too; otherwise the recorded decision (or install default) applies.
620
+ decisions.install_management_tools = await resolveToolsDecision({
621
+ flags, prompt: null, prior: priorToolsDecision(io, statePath),
622
+ });
623
+
624
+ const result = await runInstallation({
625
+ manifests: loadedManifests, mode, io,
626
+ roots: { comfyuiRoot: root, workerDir, statePath, repoRoot, hubUrl, toolsDir: resolveToolsDir(flags) },
627
+ decisions,
628
+ secretProvider: null, // secrets are never persisted; enter them via a fresh `install` if truly required
629
+ logger, crypto, env, initialState: st,
630
+ options: { ...installOptions(flags), term: screen },
631
+ });
632
+ printResult(result);
633
+ }
634
+
635
+ function yesDecisions() {
636
+ return {
637
+ comfyui_update: 'yes',
638
+ install_custom_nodes: true,
639
+ install_models: true,
640
+ workflows: 'all',
641
+ worker_setup: true,
642
+ worker_key_provided: true,
643
+ };
644
+ }
645
+
646
+ /**
647
+ * uninstall — remove what the Animastor installer installed, guided by the
648
+ * installation state/manifest. Components that existed before the installer
649
+ * ran are recorded as not-owned and are never removed.
650
+ *
651
+ * Interactive: full-uninstall or per-group Да/Нет questions, with a summary
652
+ * of the exact deletion list shown before anything is removed.
653
+ */
654
+ async function cmdUninstall(flags) {
655
+ const io = createRealIo();
656
+ const statePath = resolveStatePath(flags);
657
+ const home = flags.home || homeDir() || null;
658
+ const dryRun = flags['dry-run'] || false;
659
+ const yes = flags.yes || false;
660
+ const full = flags.all || false;
661
+
662
+ const record = uninstaller.loadInstallRecord(io, statePath);
663
+ if (!record) {
664
+ console.log(`No Animastor installation state found at ${statePath}.`);
665
+ console.log('Without the install manifest the uninstaller cannot determine');
666
+ console.log('what was installed by Animastor — and will not guess or delete');
667
+ console.log('anything by name. Remove leftover directories manually if needed.');
668
+ process.exit(1);
669
+ }
670
+ if (record.corrupt) {
671
+ console.error(`Install state at ${statePath} is unreadable (${record.error}).`);
672
+ console.error('Refusing to uninstall without a valid manifest — nothing was removed.');
673
+ process.exit(1);
674
+ }
675
+
676
+ // Ownership note: an install created under sudo carries root-owned files.
677
+ // Removing those legitimately requires root — warn instead of blocking.
678
+ const uninstallUid = prereq.currentUid();
679
+ if (record.owner_uid != null && uninstallUid != null && record.owner_uid !== uninstallUid) {
680
+ const ownerDesc = record.owner_uid === 0 ? 'root' : `uid ${record.owner_uid}`;
681
+ console.warn(`Warning: this installation was created by ${ownerDesc}, but you are running as uid ${uninstallUid}.`);
682
+ console.warn('Removal of root-owned files will fail without elevated privileges (sudo).');
683
+ }
684
+
685
+ const plan = uninstaller.buildUninstallPlan(io, { state: record, statePath, home });
686
+ console.log(uninstaller.renderUninstallPlan(plan, { state: record }));
687
+ console.log('');
688
+
689
+ if (plan.removable_count === 0) {
690
+ console.log('Nothing recorded as installed by Animastor was found on disk — nothing to remove.');
691
+ process.exit(0);
692
+ }
693
+
694
+ const answers = {};
695
+ const prompt = createPrompt();
696
+ if (full || yes) {
697
+ for (const g of uninstaller.GROUPS) answers[g.key] = true;
698
+ console.log(full ? 'Mode: FULL uninstall — every removable component listed above will be deleted.' : 'Mode: auto-confirmed (--yes) — every removable component will be deleted.');
699
+ } else {
700
+ const mode = await prompt.select(
701
+ 'Choose uninstall mode:',
702
+ [
703
+ 'Full uninstall — remove EVERYTHING installed by Animastor',
704
+ 'Selective — decide per component',
705
+ ],
706
+ );
707
+ if (mode.startsWith('Full')) {
708
+ for (const g of uninstaller.GROUPS) answers[g.key] = true;
709
+ } else {
710
+ for (const g of uninstaller.GROUPS) {
711
+ // only ask about groups that actually have removable items
712
+ const group = plan.groups.find((x) => x.key === g.key);
713
+ if (!group || !group.items.some((i) => i.removable)) continue;
714
+ answers[g.key] = await prompt.confirm(`Remove ${g.title}?`);
715
+ }
716
+ }
717
+ }
718
+
719
+ // Final confirmation: show exactly what will be removed
720
+ const willRemove = [];
721
+ for (const g of plan.groups) {
722
+ if (answers[g.key] !== true) continue;
723
+ for (const it of g.items) {
724
+ if (it.removable) willRemove.push(it.path);
725
+ }
726
+ }
727
+ if (willRemove.length === 0) {
728
+ console.log('\nNothing selected for removal — exiting.');
729
+ prompt.close();
730
+ process.exit(0);
731
+ }
732
+ console.log('\nThe following paths will be REMOVED:');
733
+ for (const p of willRemove) console.log(` - ${p}`);
734
+ if (!yes) {
735
+ const proceed = await prompt.confirm('\nExecute the uninstall now?');
736
+ if (!proceed) {
737
+ console.log('Aborted — nothing was removed.');
738
+ prompt.close();
739
+ process.exit(0);
740
+ }
741
+ }
742
+ prompt.close();
743
+
744
+ const outcome = uninstaller.runUninstallation(io, {
745
+ plan, answers, statePath, dryRun,
746
+ log: createLogger({ io }),
747
+ });
748
+ console.log('');
749
+ console.log(uninstaller.renderUninstallResult(outcome));
750
+ process.exit(outcome.failed > 0 ? 1 : 0);
751
+ }
752
+
753
+ async function cmdVerify(flags) {
754
+ const root = resolveRoot(flags);
755
+ const workerDir = resolveWorkerDir(flags);
756
+ const hubUrl = resolveHubUrl(flags);
757
+ const crypto = require('crypto');
758
+ const io = createRealIo();
759
+
760
+ const loadedManifests = flags.profiles.length > 0
761
+ ? flags.profiles.map((p) => manifest.loadManifest(p))
762
+ : [manifest.loadManifest('image/qwen-image')]; // default
763
+
764
+ const env = probeEnvironment(io, { root, workerDir, crypto, workerType: loadedManifests[0].worker_bundle.worker_type });
765
+ const report = resolver.resolveInstallation({ manifests: loadedManifests, environment: env, mode: 'existing' });
766
+ const { buildVerificationReport } = require('./verification-report');
767
+ const ver = buildVerificationReport({ report, live: {} });
768
+ console.log(ver.text);
769
+ }
770
+
771
+ function printResult(result) {
772
+ if (result.verification) {
773
+ console.log(`\nRESULT: ${result.verification.status}`);
774
+ } else {
775
+ console.log(`\nRESULT: ${result.status.toUpperCase()}`);
776
+ }
777
+ if (result.warnings.length > 0) {
778
+ console.log('\nWarnings:');
779
+ for (const w of result.warnings) console.log(` ! ${w}`);
780
+ }
781
+ // A failed/blocked installation must be visible in the exit code so
782
+ // scripts (and the E2E smoke test) can react.
783
+ if (result.status === 'failed' || result.status === 'blocked') process.exitCode = 1;
784
+ if (result.remediation) {
785
+ console.log('\nRemediation:');
786
+ if (result.remediation.summary) console.log(` ${result.remediation.summary}`);
787
+ if (result.remediation.package) console.log(` Required host package: ${result.remediation.package}`);
788
+ if (result.remediation.command) console.log(` Install it with: ${result.remediation.command}`);
789
+ console.log(' Then re-run the installer.');
790
+ }
791
+ }
792
+
793
+ /**
794
+ * validate-manifests — check all manifests for completeness and readiness.
795
+ *
796
+ * Validates:
797
+ * - JSON schema compliance
798
+ * - All required dependencies have confirmed sources
799
+ * - Download planner reports READY for all required models
800
+ * - Auth requirements are documented
801
+ * - Checksums are present where possible
802
+ */
803
+ async function cmdValidateManifests(flags) {
804
+ const loadedManifests = manifest.loadAllManifests();
805
+ const profiles = Object.keys(loadedManifests);
806
+ let allReady = true;
807
+ const hasHfToken = !!(process.env.HF_TOKEN || process.env.HUGGINGFACE_HUB_TOKEN);
808
+
809
+ console.log('Installer Manifest Validation');
810
+ console.log(`Profiles found: ${profiles.length}`);
811
+ console.log(`System HF token: ${hasHfToken ? 'available' : 'not set'}`);
812
+ console.log('');
813
+
814
+ for (const profileId of profiles) {
815
+ const m = loadedManifests[profileId];
816
+ const validation = m._validation;
817
+ console.log(`${m.profile.id}`);
818
+ console.log(` Status: ${m.status}`);
819
+ console.log(` Revision: ${m.revision}`);
820
+
821
+ // Show validation errors/warnings
822
+ if (validation && validation.errors.length > 0) {
823
+ console.log(` ERRORS: ${validation.errors.length}`);
824
+ for (const e of validation.errors) console.log(` - ${e}`);
825
+ }
826
+ if (validation && validation.warnings.length > 0) {
827
+ console.log(` Warnings: ${validation.warnings.length}`);
828
+ for (const w of validation.warnings) console.log(` - ${w}`);
829
+ }
830
+
831
+ // Check dependencies
832
+ const deps = m.dependencies || [];
833
+ const requiredModels = deps.filter((d) => (d.kind === 'model' || d.kind === 'model_repo') && d.requirement === 'required');
834
+ const requiredNodes = deps.filter((d) => d.kind === 'custom_node' && d.requirement === 'required');
835
+
836
+ console.log(` Required models: ${requiredModels.length}`);
837
+ console.log(` Required nodes: ${requiredNodes.length}`);
838
+
839
+ // Check each model source
840
+ let profileReady = true;
841
+ for (const dep of requiredModels) {
842
+ const src = dep.source || {};
843
+ const hasRepo = !!src.repository;
844
+ const hasFilePath = !!src.file_path || dep.kind === 'model_repo';
845
+ const verified = src.verification === 'confirmed';
846
+ const hasChecksum = !!(dep.checksum && dep.checksum.value);
847
+ const gated = !!src.gated;
848
+
849
+ let status = 'READY';
850
+ if (!hasRepo || !verified) {
851
+ status = 'BLOCKED — source not verified';
852
+ profileReady = false;
853
+ } else if (gated && !hasHfToken) {
854
+ status = 'BLOCKED — gated model, no HF token';
855
+ profileReady = false;
856
+ }
857
+
858
+ const check = hasRepo ? '\u2713' : '\u2717';
859
+ const gatedMark = gated ? ' (gated)' : '';
860
+ const checksumMark = hasChecksum ? '' : ' [no sha256]';
861
+ console.log(` ${check} ${dep.id}${gatedMark}: ${status}${checksumMark}`);
862
+ }
863
+
864
+ // Check custom nodes
865
+ for (const dep of requiredNodes) {
866
+ const src = (dep.install || {}).source || {};
867
+ const hasRepo = !!src.repository;
868
+ const hasCommit = !!src.commit;
869
+ const verified = src.verification === 'confirmed';
870
+ let status = 'READY';
871
+ if (!hasRepo || !hasCommit || !verified) {
872
+ status = 'BLOCKED — commit not pinned';
873
+ profileReady = false;
874
+ }
875
+ const check = (hasRepo && hasCommit) ? '\u2713' : '\u2717';
876
+ console.log(` ${check} ${dep.id}: ${status}`);
877
+ }
878
+
879
+ // Check workflows
880
+ const workflows = (m.workflows || {}).artifacts || [];
881
+ console.log(` Workflows: ${workflows.length}`);
882
+ for (const wf of workflows) {
883
+ const check = wf.baseline_sha256 ? '\u2713' : '\u2717';
884
+ console.log(` ${check} ${wf.id}${wf.baseline_sha256 ? '' : ' [no sha256]'}`);
885
+ }
886
+
887
+ if (!profileReady) allReady = false;
888
+ console.log('');
889
+ }
890
+
891
+ console.log(`\nOVERALL: ${allReady ? 'READY' : 'BLOCKED'}`);
892
+ if (!allReady) {
893
+ console.log('Some profiles have unresolved dependencies. See above for details.');
894
+ process.exit(1);
895
+ }
896
+ }
897
+
898
+ // ---------------------------------------------------------------------------
899
+ // Management tools — status / monitor / reboot (shared runtime logic lives in
900
+ // management.js; these handlers only resolve targets, guard access, render
901
+ // through the shared terminal renderer and set exit codes)
902
+ // ---------------------------------------------------------------------------
903
+
904
+ /** Resolve targets for a tool command; exit 2 when no installation is found. */
905
+ function managementTargetsOrExit(io, flags, label) {
906
+ const targets = managementTargets(io, flags);
907
+ if (!targets.found) {
908
+ console.log(`${label}`);
909
+ console.log('');
910
+ console.log('✗ installation not found');
911
+ console.log(` (looked for state at ${targets.statePath || '—'}, root ${targets.comfyuiRoot || '—'}, worker ${targets.workerDir || '—'})`);
912
+ process.exitCode = 2;
913
+ return null;
914
+ }
915
+ return targets;
916
+ }
917
+
918
+ async function cmdStatus(flags) {
919
+ const io = createRealIo();
920
+ const targets = managementTargetsOrExit(io, flags, 'Animastor status');
921
+ if (!targets) return;
922
+ if (!guardManagementAccess(io, targets)) return;
923
+ const screen = createScreen();
924
+ const snapshot = await management.collectStatus(io, targets);
925
+ for (const line of management.renderStatus(snapshot).split('\n')) screen.print(line);
926
+ process.exitCode = management.statusExitCode(snapshot);
927
+ }
928
+
929
+ async function cmdMonitor(flags) {
930
+ const io = createRealIo();
931
+ const targets = managementTargetsOrExit(io, flags, 'Animastor ComfyUI Monitor');
932
+ if (!targets) return;
933
+ if (!guardManagementAccess(io, targets)) return;
934
+ const screen = createScreen();
935
+ const data = await management.collectMonitor(io, targets, {
936
+ historyMax: flags['history-max'] ? Number(flags['history-max']) : 24,
937
+ });
938
+ for (const line of management.renderMonitor(data).split('\n')) screen.print(line);
939
+ process.exitCode = data.api.ok ? 0 : 1;
940
+ }
941
+
942
+ async function cmdRebootWorker(flags) {
943
+ const io = createRealIo();
944
+ const targets = managementTargetsOrExit(io, flags, 'Animastor Worker restart');
945
+ if (!targets) return;
946
+ if (!guardManagementAccess(io, targets)) return;
947
+ const screen = createScreen();
948
+ let res;
949
+ try {
950
+ res = await management.restartWorker(io, targets, { term: screen });
951
+ } catch (err) {
952
+ screen.print(`[✗] Worker restart failed: ${err.message}`);
953
+ process.exitCode = 1;
954
+ return;
955
+ }
956
+ if (res.ok && res.healthy) {
957
+ screen.print('[✓] Worker is healthy');
958
+ process.exitCode = 0;
959
+ } else {
960
+ screen.print(`[✗] Worker restart failed: ${res.detail || 'unknown reason'}`);
961
+ process.exitCode = 1;
962
+ }
963
+ }
964
+
965
+ async function cmdRebootComfyUI(flags) {
966
+ const io = createRealIo();
967
+ const targets = managementTargetsOrExit(io, flags, 'Animastor ComfyUI restart');
968
+ if (!targets) return;
969
+ if (!guardManagementAccess(io, targets)) return;
970
+ const screen = createScreen();
971
+ let res;
972
+ try {
973
+ res = await management.restartComfyUI(io, targets, {
974
+ term: screen,
975
+ verifyTimeoutMs: flags['verify-timeout-ms'] ? Number(flags['verify-timeout-ms']) : 120000,
976
+ });
977
+ } catch (err) {
978
+ screen.print(`[✗] ComfyUI restart failed: ${err.message}`);
979
+ process.exitCode = 1;
980
+ return;
981
+ }
982
+ if (res.ok && res.up !== false) {
983
+ screen.print(`[✓] API ready on :${res.port}`);
984
+ process.exitCode = 0;
985
+ } else if (res.ok) {
986
+ screen.print(`[!] ComfyUI restarted but the API is not ready: ${res.detail || 'unknown reason'}`);
987
+ process.exitCode = 1;
988
+ } else {
989
+ screen.print(`[✗] ComfyUI restart failed: ${res.detail || 'unknown reason'}`);
990
+ process.exitCode = 1;
991
+ }
992
+ }
993
+
994
+ // ---------------------------------------------------------------------------
995
+ // Main
996
+ // ---------------------------------------------------------------------------
997
+
998
+ async function main() {
999
+ const args = parseArgs(process.argv);
1000
+ const pkg = require('../../package.json');
1001
+ console.log(`animastor-installer v${pkg.version} (platform: ${PLATFORM_RUNTIME.platform}, deployment: ${PLATFORM_RUNTIME.deployment})`);
1002
+ printPlatformNotices();
1003
+ switch (args.command) {
1004
+ case 'detect':
1005
+ await cmdDetect(args.flags);
1006
+ break;
1007
+ case 'plan':
1008
+ await cmdPlan(args.flags);
1009
+ break;
1010
+ case 'install':
1011
+ await cmdInstall(args.flags);
1012
+ break;
1013
+ case 'verify':
1014
+ await cmdVerify(args.flags);
1015
+ break;
1016
+ case 'validate':
1017
+ await cmdValidateManifests(args.flags);
1018
+ break;
1019
+ case 'resume':
1020
+ await cmdResume(args.flags);
1021
+ break;
1022
+ case 'uninstall':
1023
+ await cmdUninstall(args.flags);
1024
+ break;
1025
+ case 'status':
1026
+ await cmdStatus(args.flags);
1027
+ break;
1028
+ case 'monitor':
1029
+ await cmdMonitor(args.flags);
1030
+ break;
1031
+ case 'reboot-worker':
1032
+ await cmdRebootWorker(args.flags);
1033
+ break;
1034
+ case 'reboot-comfyui':
1035
+ await cmdRebootComfyUI(args.flags);
1036
+ break;
1037
+ default:
1038
+ console.error('Usage: animastor-installer <detect|plan|install|verify|validate|resume|uninstall|status|monitor|reboot-worker|reboot-comfyui> [options]');
1039
+ console.error(' --profile P[,P2] Generation profile id');
1040
+ console.error(' --mode MODE managed | existing | shared');
1041
+ console.error(' --root PATH ComfyUI root (default: ~/ComfyUI)');
1042
+ console.error(' --worker-dir PATH Worker bundle dir');
1043
+ console.error(' --hub-url URL GPU Hub URL');
1044
+ console.error(' --yes Auto-confirm all prompts');
1045
+ console.error(' --dry-run Show plan only; zero mutations');
1046
+ console.error(' managed mode starts ComfyUI + worker automatically and picks');
1047
+ console.error(' a free port when 8188 is taken; opt out:');
1048
+ console.error(' --no-start-comfy --no-start-worker --comfy-port N');
1049
+ console.error(' management tools (installed next to the worker, ~/animastor/tools):');
1050
+ console.error(' status | monitor | reboot-worker | reboot-comfyui');
1051
+ console.error(' (--state/--root/--worker-dir/--port override discovery)');
1052
+ console.error(' installer flags: --install-tools / --no-tools / --tools-dir PATH');
1053
+ console.error(' uninstall flags:');
1054
+ console.error(' --all Full uninstall (remove everything recorded as installed by Animastor)');
1055
+ console.error(' --state PATH Install state file path');
1056
+ process.exit(1);
1057
+ }
1058
+ }
1059
+
1060
+ if (require.main === module) {
1061
+ main().catch((err) => {
1062
+ console.error(`fatal: ${err.message}`);
1063
+ process.exit(1);
1064
+ });
1065
+ }
1066
+
1067
+ module.exports = { parseArgs, cmdDetect, cmdPlan, cmdInstall, cmdVerify, cmdValidateManifests, cmdResume, cmdUninstall, cmdStatus, cmdMonitor, cmdRebootWorker, cmdRebootComfyUI, resolveAndPlan, makeSecretProvider, resolveToolsDecision, resolveToolsDir, PLATFORM_RUNTIME, printPlatformNotices, homeDir };