@animastor/installer 0.1.1 → 0.2.9

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.
@@ -13,10 +13,14 @@
13
13
  * animastor-installer verify [--profile P[,P2]] [--root PATH] [--worker-dir PATH] [--hub-url URL]
14
14
  * animastor-installer resume
15
15
  * animastor-installer uninstall [--all] [--yes] [--dry-run] [--state PATH] [--home PATH]
16
+ * animastor-installer start | stop | status | logs [-f] [--lines N] | doctor [--new-key] [--wait-job-ms N] [--force]
17
+ * animastor-installer boot (node startup script: detaches `doctor --yes`, exits 0 at once)
18
+ * (what the `animastor` command in PATH runs)
16
19
  *
17
20
  * Flags:
18
21
  * --profile P Generation profile id (repeatable or comma-separated)
19
- * --mode MODE managed | existing | shared (default: infer from detection)
22
+ * --mode MODE managed | existing | shared (default: existing when a ComfyUI
23
+ * is found — in ~/ComfyUI or as a running process — else managed)
20
24
  * --root PATH ComfyUI root directory (default: ~/ComfyUI)
21
25
  * --worker-dir PATH Worker bundle directory (default: ~/animastor/worker)
22
26
  * --hub-url URL GPU Hub base URL (default: https://animastor.org/gpu)
@@ -25,25 +29,42 @@
25
29
  * --yes Auto-confirm all prompts
26
30
  * --dry-run Show plan only; never perform real changes
27
31
  * --all uninstall: full uninstall (everything recorded in the manifest)
32
+ * --wait-job-ms N install/doctor: when the worker must be restarted (its .env or bundle
33
+ * changed) but is busy with a task, wait up to N ms for the task to
34
+ * finish (default 600000); still busy → FAILED, exit 1
35
+ * --force install/doctor: restart the worker for a changed configuration even
36
+ * when it is busy (the task's result is lost)
28
37
  */
29
38
 
30
39
  const fs = require('fs');
31
40
  const path = require('path');
32
- const readline = require('readline');
33
41
 
34
42
  const { createRealIo, createDryRunIo } = require('./engine/io');
35
43
  const { createLogger } = require('./engine/logger');
36
44
  const { createTermRenderer } = require('./engine/term');
37
45
  const platforms = require('./platform');
38
- const { probeEnvironment, renderDetection } = require('./engine/probe');
46
+ const probeMod = require('./engine/probe');
47
+ const { probeEnvironment, renderDetection } = probeMod;
39
48
  const { runInstallation, loadResumableState, renderResumeSummary } = require('./engine/engine');
40
49
  const prereq = require('./engine/prereq');
41
50
  const stateStore = require('./engine/state');
42
51
  const management = require('./management');
43
52
  const resolver = require('./compatibility-resolver');
44
- const { buildInstallPlan, renderPlanText } = require('./install-plan');
53
+ const { buildInstallPlan, renderPlanText, planNeedsPythonRuntime } = require('./install-plan');
45
54
  const manifest = require('./install-manifest');
46
55
  const uninstaller = require('./uninstaller');
56
+ const { createPrompt, NoTerminalError } = require('./engine/tty');
57
+ const { renderBanner, renderFinalSummary } = require('./engine/summary');
58
+ const fixes = require('./engine/fixes');
59
+ const workerMod = require('./engine/worker');
60
+ const comfyuiMod = require('./engine/comfyui');
61
+ const comfyOwner = require('./engine/comfy-owner');
62
+ const nodeDeps = require('./engine/node-deps');
63
+ const pydepsMod = require('./engine/pydeps');
64
+ const overridesMod = require('./engine/overrides');
65
+ const downloader = require('./engine/downloader');
66
+ const { resolveRepoBundleDir } = require('./worker-bundle-source');
67
+ const engineMod = require('./engine/engine');
47
68
 
48
69
  // ---------------------------------------------------------------------------
49
70
  // Paths (platform-specific defaults; the platform adapter owns them)
@@ -92,25 +113,74 @@ const DEFAULT_HUB_URL = 'https://animastor.org/gpu';
92
113
  // Argument parsing
93
114
  // ---------------------------------------------------------------------------
94
115
 
116
+ const BOOLEAN_FLAGS = ['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', 'new-key', 'follow', 'no-fix', 'restart-platform-comfy', 'no-restart-platform-comfy', 'accept-node-deps-overrides', 'force', 'help'];
117
+
118
+ /**
119
+ * Every option that takes a value. Installer 0.2.5: an option that is in
120
+ * neither list is an ERROR (exit 2) — installer 0.2.3 silently swallowed
121
+ * `doctor --restart-platform-comfy` (a flag it did not know) and ran a plain
122
+ * doctor, which printed the same fix again (live E2E 02.11).
123
+ */
124
+ const VALUE_FLAGS = ['profile', 'mode', 'root', 'worker-dir', 'hub-url', 'repo-root', 'state', 'tools-dir',
125
+ 'comfy-port', 'comfy-wait-ms', 'verify-timeout-ms', 'port', 'lines', 'history-max', 'home', 'boot-log', 'wait-job-ms'];
126
+
127
+ /** Commands main() dispatches. */
128
+ const COMMANDS = ['detect', 'plan', 'install', 'verify', 'validate', 'resume', 'uninstall', 'start', 'stop', 'status',
129
+ 'logs', 'doctor', 'boot', 'monitor', 'reboot-worker', 'reboot-comfyui'];
130
+
131
+ /** Exit code of a command line the CLI does not understand. */
132
+ const USAGE_EXIT = 2;
133
+
95
134
  function parseArgs(argv) {
96
135
  const args = argv.slice(2);
97
- const parsed = { command: null, profiles: [], flags: {} };
136
+ const parsed = { command: null, profiles: [], flags: {}, errors: [] };
98
137
  const positional = [];
99
138
  for (let i = 0; i < args.length; i++) {
100
139
  const a = args[i];
101
140
  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)) {
141
+ let key = a.slice(2);
142
+ let inline = null;
143
+ const eq = key.indexOf('=');
144
+ if (eq > 0) { inline = key.slice(eq + 1); key = key.slice(0, eq); }
145
+ if (BOOLEAN_FLAGS.includes(key)) {
146
+ if (inline !== null) parsed.errors.push(`option --${key} takes no value (got --${key}=${inline})`);
104
147
  parsed.flags[key] = true;
148
+ } else if (VALUE_FLAGS.includes(key)) {
149
+ let val = inline;
150
+ if (val === null) {
151
+ const next = args[i + 1];
152
+ if (next === undefined || (next.startsWith('--') && next.length > 2)) {
153
+ parsed.errors.push(`option --${key} needs a value`);
154
+ val = '';
155
+ } else {
156
+ val = next;
157
+ i += 1;
158
+ }
159
+ }
160
+ parsed.flags[key] = val;
105
161
  } else {
106
- const val = args[++i];
107
- parsed.flags[key] = val || '';
162
+ parsed.errors.push(`unknown option --${key}`);
108
163
  }
164
+ } else if (a === '-f') {
165
+ parsed.flags.follow = true;
166
+ } else if (a === '-y') {
167
+ parsed.flags.yes = true;
168
+ } else if (a === '-h') {
169
+ parsed.flags.help = true;
170
+ } else if (a.startsWith('-') && a.length > 1) {
171
+ parsed.errors.push(`unknown option ${a}`);
109
172
  } else {
110
173
  positional.push(a);
111
174
  }
112
175
  }
176
+ const wj = parsed.flags['wait-job-ms'];
177
+ if (wj !== undefined && wj !== '' && !(/^\d+$/.test(String(wj)))) {
178
+ parsed.errors.push(`option --wait-job-ms needs a number of milliseconds >= 0 (got ${wj})`);
179
+ }
113
180
  parsed.command = positional[0] || null;
181
+ if (positional.length > 1) parsed.errors.push(`unexpected argument(s): ${positional.slice(1).join(' ')}`);
182
+ // An unknown COMMAND keeps its old behaviour: usage + exit 1 (main()).
183
+ parsed.unknownCommand = parsed.command !== null && !COMMANDS.includes(parsed.command);
114
184
  const profileFlag = parsed.flags.profile || '';
115
185
  if (profileFlag) {
116
186
  parsed.profiles = profileFlag.split(',').map((s) => s.trim()).filter(Boolean);
@@ -132,8 +202,17 @@ function resolveHubUrl(flags) {
132
202
  return flags['hub-url'] || DEFAULT_HUB_URL;
133
203
  }
134
204
 
205
+ /**
206
+ * Root that holds the bundled worker files and workflows. In the hub
207
+ * installer tarball that is the unpacked `animastor-installer/` itself
208
+ * (worker/worker/, backend/ai/workflows/ next to src/); in a repo checkout
209
+ * it is the repository root. (The tarball case used to resolve OUTSIDE the
210
+ * unpacked bundle, so the bundled worker could never be found.)
211
+ */
135
212
  function resolveRepoRoot(flags) {
136
- return flags['repo-root'] || REPO_ROOT;
213
+ if (flags['repo-root']) return flags['repo-root'];
214
+ if (resolveRepoBundleDir(fs, CLI_ROOT)) return CLI_ROOT;
215
+ return REPO_ROOT;
137
216
  }
138
217
 
139
218
  function resolveStatePath(flags) {
@@ -208,7 +287,7 @@ function priorToolsDecision(io, statePath) {
208
287
  * mixing (sudo vs. normal user). On failure prints the exact remediation
209
288
  * and exits — the installer never ploughs on into an unrecoverable state.
210
289
  */
211
- function runHostGates(realIo, { paths, dryRun = false, stateUid = null, deep = true, venvDir = null }) {
290
+ async function runHostGates(realIo, { paths, dryRun = false, stateUid = null, venvDir = null, needVenv = true, prompt = null, yes = false, log = null }) {
212
291
  const uid = prereq.currentUid();
213
292
  const ownership = prereq.checkOwnership(realIo, {
214
293
  paths,
@@ -223,76 +302,27 @@ function runHostGates(realIo, { paths, dryRun = false, stateUid = null, deep = t
223
302
  process.exit(1);
224
303
  }
225
304
  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);
305
+ // Only what the plan will ACTUALLY use is checked: a working `existing`
306
+ // ComfyUI with every model/node present never touches a venv, so a
307
+ // missing python3.X-venv must not block (or be installed for) nothing.
308
+ if (!needVenv) return;
309
+ const gateOpts = { python: 'python3', deep: true, existingVenvDir: venvDir };
310
+ const gate = prereq.checkPythonPrerequisites(realIo, gateOpts);
311
+ if (gate.ok) return;
312
+ // root / passwordless sudo: install the package on consent and CONTINUE
313
+ // in this same run ("Install python3.12-venv now? [Y/n]"); --yes installs
314
+ // without asking. Without the privileges the exact command is printed.
315
+ const resolved = await prereq.resolveHostPrerequisite(realIo, {
316
+ failure: gate.failure, opts: gateOpts, prompt, yes, log,
317
+ });
318
+ if (resolved.ok) {
319
+ console.log(`✓ ${resolved.installed.packages.join(' ')} installed — continuing`);
320
+ return;
231
321
  }
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
- };
322
+ console.error('');
323
+ for (const line of prereq.renderRemediation(resolved.failure)) console.error(line);
324
+ if (resolved.install && resolved.install.message) console.error(resolved.install.message);
325
+ process.exit(1);
296
326
  }
297
327
 
298
328
  // ---------------------------------------------------------------------------
@@ -313,6 +343,760 @@ function resolveAndPlan({ manifests, env, mode, decisions }) {
313
343
  return { report, plan };
314
344
  }
315
345
 
346
+ /**
347
+ * Same as resolveAndPlan, plus the real download size of incomplete model
348
+ * repos (ModelScope listing) so the plan shows exactly what will be
349
+ * downloaded. Network failures leave the size unknown.
350
+ */
351
+ async function resolveAndPlanWithSizes({ io, manifests, env, mode, decisions }) {
352
+ const report = resolver.resolveInstallation({ manifests, environment: env, mode });
353
+ try { await downloader.annotateMissingModelSizes(io, report, manifests); } catch (_) { /* size unknown */ }
354
+ const plan = buildInstallPlan({ report, manifests, decisions });
355
+ return { report, plan };
356
+ }
357
+
358
+ /**
359
+ * The question asked for a plan step. Component lists are already printed
360
+ * in the plan (Missing/Actions) — list-type questions get one short line
361
+ * instead of a second copy of the menu; context questions (ComfyUI version
362
+ * decisions) are shown in full because the plan does not contain them.
363
+ */
364
+ function stepQuestion(step) {
365
+ switch (step.id) {
366
+ case 'custom-nodes': return 'Install the missing custom node(s) listed above?';
367
+ case 'models': return 'Download the missing model file(s) listed above?';
368
+ case 'workflows': return 'Install the optional profile workflows (not required for Animastor)?';
369
+ case 'worker-setup': return 'Install and configure the Animastor worker (listed above)?';
370
+ default: return String(step.prompt.question).replace(/\n\n+/g, '\n');
371
+ }
372
+ }
373
+
374
+ /** Versions shown in the banner. Hub/bootstrap versions come from the bootstrap env. */
375
+ function bannerVersions(manifests, flags, { hub = null } = {}) {
376
+ const pkg = require('../../package.json');
377
+ let worker = process.env.ANIMASTOR_WORKER_BUNDLE_VERSION || null;
378
+ if (!worker) {
379
+ const dir = resolveRepoBundleDir(fs, resolveRepoRoot(flags));
380
+ if (dir) worker = workerMod.readPkgVersion({ fs: { readFileSync: fs.readFileSync } }, dir);
381
+ }
382
+ return {
383
+ installer: pkg.version,
384
+ worker,
385
+ profile: manifests.map((m) => m.profile.id).join(' + '),
386
+ profileRevision: manifests.length === 1 ? manifests[0].revision : null,
387
+ hub: process.env.ANIMASTOR_HUB_VERSION || hub || null,
388
+ bootstrap: process.env.ANIMASTOR_BOOTSTRAP_VERSION || null,
389
+ platform: `${PLATFORM_RUNTIME.platform}/${PLATFORM_RUNTIME.deployment}`,
390
+ };
391
+ }
392
+
393
+ /** Absolute path of the `animastor` command of this installation. */
394
+ function toolCommandPath(flags) {
395
+ const linkDir = management.defaultLinkDir();
396
+ if (linkDir) {
397
+ const link = path.join(linkDir, 'animastor');
398
+ if (fs.existsSync(link)) return link;
399
+ }
400
+ return path.join(resolveToolsDir(flags), 'animastor');
401
+ }
402
+
403
+ /**
404
+ * Hub version for the banner. The bootstrap exports ANIMASTOR_HUB_VERSION;
405
+ * the install state remembers it; otherwise the hub is asked: GET
406
+ * <hub>/health (when it publishes a version) or the served installer script,
407
+ * whose `export ANIMASTOR_HUB_VERSION="…"` line is exactly what a fresh
408
+ * install receives. Never "hub unknown" while the hub is reachable.
409
+ */
410
+ async function detectHubVersion(io, hubUrl, { known = null } = {}) {
411
+ if (known) return String(known);
412
+ const base = String(hubUrl || '').replace(/\/$/, '');
413
+ if (!base || !io.http) return null;
414
+ try {
415
+ const health = await io.http.fetchJson(`${base}/health`);
416
+ if (health && health.status === 200 && health.json && health.json.version) return String(health.json.version);
417
+ } catch (_) { /* older hub without a version field */ }
418
+ try {
419
+ const res = await io.http.fetchText(`${base}/installer`);
420
+ const text = res && res.status === 200 ? String(res.text || res.body || '') : '';
421
+ const m = /ANIMASTOR_HUB_VERSION="?([0-9][^"\n]*)"?/.exec(text);
422
+ if (m) return m[1].trim();
423
+ } catch (_) { /* offline — the banner falls back to "unknown" */ }
424
+ return null;
425
+ }
426
+
427
+ /**
428
+ * Decisions of a previous run that are reused as the STARTING point of this
429
+ * one: a re-run does not ask again about steps the user already answered
430
+ * (optional workflows declined once stay declined — also for `doctor --yes`
431
+ * on every boot). Secret-related facts are never stored, so nothing leaked
432
+ * can be reused here.
433
+ */
434
+ const REUSED_DECISION_KEYS = ['comfyui_update', 'install_custom_nodes', 'install_models', 'workflows', 'worker_setup', 'accept_reference_runtime', 'accept_runtime_change'];
435
+ function priorReusableDecisions(state) {
436
+ const out = {};
437
+ const d = state && state.decisions;
438
+ if (!d) return out;
439
+ for (const k of REUSED_DECISION_KEYS) if (d[k] !== undefined) out[k] = d[k];
440
+ return out;
441
+ }
442
+
443
+ /**
444
+ * The boot script (`animastor doctor --yes`, no TTY): one line of output and
445
+ * an exit code, nothing else. `ANIMASTOR_BOOT=1` forces it on a TTY too.
446
+ */
447
+ function isBootRun(flags, doctor) {
448
+ if (!doctor || flags.yes !== true) return false;
449
+ if (process.env.ANIMASTOR_BOOT === '1') return true;
450
+ return !process.stdout.isTTY;
451
+ }
452
+
453
+ /** Host packages the boot path must restore when the image dropped them. */
454
+ function missingRequiredHostPackages(io) {
455
+ const out = [];
456
+ if (!probeMod.pickNodeBinary(io)) out.push('nodejs');
457
+ return out;
458
+ }
459
+
460
+ /**
461
+ * Should this run wait for the platform's ComfyUI before anything else?
462
+ * (installer 0.2.3) Yes when a wait is configured, no verified foreign
463
+ * instance answers yet, and either nothing runs at all or the recorded
464
+ * installation says the ComfyUI belongs to the platform (type A) — the
465
+ * latter holds even when some other main.py is visible, so the worker is
466
+ * never started before the platform's ComfyUI answers.
467
+ */
468
+ function shouldWaitForPlatformComfy({ waitMs, instance, state }) {
469
+ if (!(waitMs > 0) || !instance || instance.owner === 'foreign') return false;
470
+ // Type B (installer 0.2.4): the installer created this ComfyUI and starts
471
+ // it itself — there is no platform instance to wait for (with the 600 s
472
+ // default of `animastor boot` that would be ten idle minutes).
473
+ const owned = !!(state && state.components && state.components.comfyui && state.components.comfyui.owned);
474
+ if (owned && !comfyOwner.platformOwnedByRecord(state)) return false;
475
+ return instance.owner === 'none' || comfyOwner.platformOwnedByRecord(state);
476
+ }
477
+
478
+ /**
479
+ * The boot gate (installer 0.2.3): wait for the platform's ComfyUI when
480
+ * shouldWaitForPlatformComfy() says so — progress in the log every 30 s —
481
+ * and decide whether the run may continue.
482
+ * @returns {Promise<{ instance: object, waited: object|null, failed: boolean }>}
483
+ */
484
+ async function platformComfyGate(io, { state = null, root = null, waitMs = 0, instance = null, logger = null, sleep = null, intervalMs = 3000, progressMs = 30000 } = {}) {
485
+ let inst = instance || await comfyOwner.resolveComfyOwner(io, { state, root });
486
+ if (!shouldWaitForPlatformComfy({ waitMs, instance: inst, state })) return { instance: inst, waited: null, failed: false };
487
+ const info = (line) => { if (logger) logger.info(line); };
488
+ info(`waiting up to ${Math.round(waitMs / 1000)} s for the platform's ComfyUI (process + GET /system_stats)`);
489
+ const waited = await comfyOwner.waitForPlatformComfyUI(io, {
490
+ state, root, timeoutMs: waitMs, intervalMs, progressMs, sleep, onProgress: info,
491
+ });
492
+ inst = waited.instance;
493
+ if (waited.ok) {
494
+ info(`the platform's ComfyUI answers at ${inst.url} (pid ${inst.pid}, after ${Math.round(waited.waited_ms / 1000)} s)`);
495
+ return { instance: inst, waited, failed: false };
496
+ }
497
+ // Nobody will start a ComfyUI for this installation (type A / existing):
498
+ // stop here instead of wiring the worker to the previous boot's address.
499
+ const failed = comfyOwner.platformOwnedByRecord(state) || inst.mode === 'existing';
500
+ if (failed && logger) logger.error(comfyOwner.platformComfyMissingReason(waited.waited_ms, waited.last_seen));
501
+ return { instance: inst, waited, failed };
502
+ }
503
+
504
+ /**
505
+ * Type A, the platform's ComfyUI never came up within --comfy-wait-ms: the
506
+ * result is FAILED with one cause and one fix; the engine (worker start,
507
+ * .env rewrite) does not run, so the worker is never started against the
508
+ * address of a previous boot.
509
+ */
510
+ function platformComfyMissingResult({ waited, tool, mode }) {
511
+ const reason = comfyOwner.platformComfyMissingReason(waited.waited_ms, waited.last_seen);
512
+ return {
513
+ status: 'failed',
514
+ mode,
515
+ warnings: [],
516
+ blocked: [],
517
+ verification: null,
518
+ results: { comfy_owner: { owner: 'none', mode, url: null }, worker: [] },
519
+ e2e: engineMod.platformComfyMissingChecks({ reason, tool }),
520
+ };
521
+ }
522
+
523
+ /**
524
+ * May this run restart the PLATFORM's ComfyUI (installer 0.2.4)? An
525
+ * explicit flag wins, then the recorded answer (install-state
526
+ * installer_options.restartPlatformComfy), then the boot default: yes on
527
+ * type A — the node is unattended and nothing else brings the node classes
528
+ * back. An interactive run without a record asks (default Yes) and records
529
+ * the answer. A plain `--yes` is NOT consent to stop a process the installer
530
+ * does not own (installer 0.2.5 ADR): it needs the flag, a recorded yes, or
531
+ * the boot run.
532
+ * @returns {{ allowed: boolean|null, source: 'flag'|'state'|'boot'|'unset' }}
533
+ */
534
+ function restartPlatformComfyDecision(flags, state, { boot = false } = {}) {
535
+ if (flags['restart-platform-comfy']) return { allowed: true, source: 'flag' };
536
+ if (flags['no-restart-platform-comfy']) return { allowed: false, source: 'flag' };
537
+ const rec = state && state.installer_options ? state.installer_options.restartPlatformComfy : undefined;
538
+ if (rec === true || rec === false) return { allowed: rec, source: 'state' };
539
+ if (boot) return { allowed: true, source: 'boot' };
540
+ return { allowed: null, source: 'unset' };
541
+ }
542
+
543
+ const RESTART_PLATFORM_QUESTION = 'When the custom-node dependencies have to be (re)installed, may animastor (also `animastor boot`) restart the platform\'s ComfyUI with the same command line so the nodes load?';
544
+
545
+ /**
546
+ * The custom-node dependency gate for a ComfyUI that the PLATFORM runs
547
+ * (type A; installer 0.2.4, persistence + restart reworked in 0.2.5):
548
+ *
549
+ * 1. the pip requirements of every required profile node are checked in
550
+ * the Python of the running main.py — with the persistent overlay
551
+ * (~/animastor/pydeps, engine/pydeps.js) in front of sys.path, exactly
552
+ * as ComfyUI sees it after the generated prestartup script;
553
+ * 2. missing ones are installed (boot / --yes / --restart-platform-comfy:
554
+ * no question; interactive: one question that also records the restart
555
+ * option) INTO THE OVERLAY — it lives in /home and survives a node
556
+ * restart; only when the overlay is impossible (old ComfyUI without
557
+ * prestartup scripts, no venv module) into the platform Python as in
558
+ * 0.2.4 (lost with a restart — boot reinstalls them);
559
+ * 3. the running ComfyUI loads new packages only on a restart: when the
560
+ * node classes are not in its /object_info and restarting the
561
+ * platform's ComfyUI is allowed, it is restarted with the same command
562
+ * line, cwd and environment (node-deps restartForeignComfyUI).
563
+ * @returns {Promise<{ instance, checked: boolean, installed: string[], restarted: boolean, pid_changed: boolean, failed: boolean, reason: string|null, fix?: string, record: object, persistence: object|null, prestartup: object|null }>}
564
+ */
565
+ /**
566
+ * Compare the overlay with the platform Python and log every replacement
567
+ * (installer 0.2.6): "[i] <pkg> platform X → overlay Y (needed by <node>)",
568
+ * a major change as a warning. Null when the comparison itself failed.
569
+ * @returns {{ overrides: object[], conflicts: object[] }|null}
570
+ */
571
+ function overridesStep(io, { python, sitePackages, root, manifests = [], otherManifests = [], info, warn }) {
572
+ const all = [...(manifests || []), ...(otherManifests || [])];
573
+ const nodes = overridesMod.nodesOfProfiles(io, { root, manifests: all });
574
+ const raw = overridesMod.inspectOverlay(io, { python, sitePackages, root, nodes });
575
+ if (!raw.ok) {
576
+ warn(`overlay version comparison failed: ${raw.error}`);
577
+ return null;
578
+ }
579
+ const res = overridesMod.analyzeOverrides(raw, nodes, { profileCount: overridesMod.profileIds(all).length });
580
+ for (const o of res.overrides) {
581
+ const line = `node-deps overlay replaces a platform package: ${overridesMod.describeOverride(o)}`;
582
+ if (o.major) warn(`${line}${overridesMod.majorNote(o)}`);
583
+ else info(line);
584
+ }
585
+ return res;
586
+ }
587
+
588
+ /** Manifests of the profiles recorded on this ComfyUI that this run does not install (unknown ids are skipped). */
589
+ function otherProfileManifests(priorState, profiles, { load = manifest.loadManifest, logger = null } = {}) {
590
+ const ids = new Set();
591
+ for (const p of (priorState && Array.isArray(priorState.profiles) ? priorState.profiles : [])) ids.add(p);
592
+ const nd = priorState && priorState.installer_options && priorState.installer_options.nodeDeps;
593
+ for (const o of (nd && Array.isArray(nd.overrides) ? nd.overrides : [])) for (const p of o.profiles || []) ids.add(p);
594
+ const out = [];
595
+ for (const id of ids) {
596
+ if ((profiles || []).includes(id)) continue;
597
+ try { out.push(load(id)); } catch (err) {
598
+ if (logger) logger.warn(`profile ${id} recorded on this ComfyUI is unknown to this installer — not checked for version replacements (${err.message})`);
599
+ }
600
+ }
601
+ return out;
602
+ }
603
+
604
+ async function platformNodeDepsGate(io, {
605
+ instance, state = null, root, manifests, flags = {}, boot = false, yes = false, prompt = null,
606
+ waitMs = 600000, logger = null, statePath = null, sleep = null, intervalMs = 3000, progressMs = 30000,
607
+ workerDir = null, platformGraceMs = 30000, otherManifests = [], command = 'doctor',
608
+ } = {}) {
609
+ const out = {
610
+ instance, checked: false, installed: [], restarted: false, pid_changed: false, failed: false, reason: null, record: {},
611
+ persistence: null, prestartup: null, overrides: [], conflicts: [],
612
+ };
613
+ if (!instance || instance.owner !== 'foreign' || !instance.pid) return out;
614
+ const info = (line) => { if (logger) logger.info(line); };
615
+ const warn = (line) => { if (logger) logger.warn(line); };
616
+ const decision = restartPlatformComfyDecision(flags, state, { boot });
617
+ let restartAllowed = decision.allowed;
618
+ const interactive = !boot && !yes && !!(prompt && prompt.available);
619
+ const tool = toolCommandPath(flags);
620
+
621
+ const py = nodeDeps.pythonOfProcess(io, instance.pid);
622
+ if (!py.python) {
623
+ warn(`custom-node dependencies not checked: the Python of the ComfyUI process (pid ${instance.pid}) is unknown (${py.source})`);
624
+ return out;
625
+ }
626
+ const base = workerDir ? pydepsMod.overlayBase(workerDir) : null;
627
+ let persist = pydepsMod.planPersistence(io, { python: py.python, root, base, create: false });
628
+ const overlayReady = () => persist.kind === 'overlay' && persist.paths && io.fs.existsSync(persist.paths.cfg);
629
+ const extraPaths = () => (overlayReady() ? [persist.sitePackages] : []);
630
+ const ensurePrestartup = () => {
631
+ if (!overlayReady()) return null;
632
+ const r = pydepsMod.ensurePrestartupNode(io, { root, base });
633
+ if (r.status === 'created' || r.status === 'updated') info(`prestartup node ${r.dir}: ${r.status} — ComfyUI adds ${persist.sitePackages} before it imports the custom nodes`);
634
+ else if (r.status === 'foreign' || r.status === 'failed') warn(`prestartup node not written: ${r.reason}`);
635
+ return r;
636
+ };
637
+ out.prestartup = ensurePrestartup();
638
+
639
+ const check = nodeDeps.checkNodeDeps(io, { python: py.python, root, manifests, extraPaths: extraPaths() });
640
+ out.checked = true;
641
+ for (const e of check.errors) warn(`custom-node dependency check: ${e}`);
642
+ let needRestart = !!(out.prestartup && (out.prestartup.status === 'created' || out.prestartup.status === 'updated'));
643
+ let snapshotOf = null;
644
+ const dropSnap = () => { if (snapshotOf) overridesMod.dropSnapshot(io, snapshotOf); snapshotOf = null; };
645
+ if (check.nodes.length === 0) {
646
+ info(`custom-node dependencies satisfied in ${py.python}${overlayReady() ? ` (+ overlay ${persist.sitePackages})` : ''} (ComfyUI pid ${instance.pid})`);
647
+ if (interactive && restartAllowed === null) {
648
+ // Asked once and recorded: the unattended boot run must know it.
649
+ restartAllowed = await prompt.confirm(RESTART_PLATFORM_QUESTION, { defaultYes: true });
650
+ out.record.restartPlatformComfy = restartAllowed;
651
+ }
652
+ } else {
653
+ const what = nodeDeps.describeUnsatisfied(check.nodes);
654
+ info(`custom-node dependencies missing in ${py.python} (ComfyUI pid ${instance.pid}): ${what}`);
655
+ let install = boot || yes || !!flags['restart-platform-comfy'];
656
+ if (interactive && !install) {
657
+ const restartPart = restartAllowed === false ? '' : ` and restart the platform's ComfyUI (pid ${instance.pid}) so it loads them`;
658
+ install = await prompt.confirm(`Install the missing Python packages — ${what} — for ${py.python}${restartPart}?`, { defaultYes: true });
659
+ if (restartAllowed === null) {
660
+ restartAllowed = install;
661
+ out.record.restartPlatformComfy = install;
662
+ }
663
+ }
664
+ if (!install) {
665
+ out.failed = true;
666
+ out.reason = `custom-node dependencies missing in the ComfyUI Python ${py.python}: ${what}`;
667
+ out.fix = `${tool} doctor --yes --restart-platform-comfy`;
668
+ return out;
669
+ }
670
+ if (persist.kind === 'overlay') {
671
+ persist = pydepsMod.planPersistence(io, { python: py.python, root, base, create: true });
672
+ if (persist.kind === 'overlay') {
673
+ const pr = ensurePrestartup();
674
+ if (pr && (pr.status === 'foreign' || pr.status === 'failed')) {
675
+ persist = { ...persist, kind: 'system', reason: pr.reason };
676
+ } else if (pr && !out.prestartup) out.prestartup = pr;
677
+ }
678
+ }
679
+ if (persist.kind !== 'overlay') {
680
+ warn(`node dependencies go into ${py.python} itself (${persist.reason}) — they are lost with a node restart; \`${tool} boot\` reinstalls them`);
681
+ }
682
+ // Another profile on this ComfyUI (installer 0.2.6): a replacement it
683
+ // refuses must be undone — the overlay venv is copied aside first.
684
+ if (persist.kind === 'overlay' && overridesMod.profileIds([...(manifests || []), ...(otherManifests || [])]).length > 1) {
685
+ const snap = overridesMod.snapshotOverlay(io, persist.paths.dir);
686
+ if (snap.ok) snapshotOf = persist.paths.dir;
687
+ else warn(`overlay snapshot not taken (${snap.reason}) — a refused version replacement cannot be undone`);
688
+ }
689
+ const constraintsPath = statePath ? path.join(path.dirname(statePath), 'node-deps-constraints.txt') : null;
690
+ const inst = nodeDeps.installNodeDeps(io, {
691
+ python: py.python, nodes: check.nodes, torch: check.torch, constraintsPath, log: logger,
692
+ pipPython: persist.kind === 'overlay' ? persist.paths.python : null,
693
+ });
694
+ out.installed = inst.installed;
695
+ if (!inst.ok) {
696
+ dropSnap();
697
+ out.failed = true;
698
+ out.reason = inst.failed.map((f) => `${f.directory}: ${f.reason}`).join('; ');
699
+ out.fix = `fix the pip error above (network, disk space, a package conflict), then run: ${tool} doctor --yes --restart-platform-comfy`;
700
+ return out;
701
+ }
702
+ const again = nodeDeps.checkNodeDeps(io, { python: py.python, root, manifests, extraPaths: extraPaths() });
703
+ if (again.nodes.length > 0) {
704
+ dropSnap();
705
+ out.failed = true;
706
+ out.reason = `pip finished, but the requirements are still not satisfied in ${py.python}: ${nodeDeps.describeUnsatisfied(again.nodes)}`;
707
+ out.fix = `install them by hand: ${persist.kind === 'overlay' ? persist.paths.python : py.python} -m pip install -r <requirements.txt>, then run: ${tool} doctor --restart-platform-comfy`;
708
+ return out;
709
+ }
710
+ info(`custom-node dependencies installed: ${inst.installed.join(', ')} → ${persist.kind === 'overlay' ? persist.sitePackages : py.python}`);
711
+ needRestart = true;
712
+ }
713
+ out.persistence = { kind: persist.kind, base: persist.base, site_packages: persist.sitePackages || null, reason: persist.reason || null, python: py.python };
714
+ const prevDeps = (state && state.installer_options && state.installer_options.nodeDeps) || {};
715
+ let accepted = Array.isArray(prevDeps.accepted) ? prevDeps.accepted.slice() : [];
716
+ out.record.nodeDeps = { target: persist.kind, overlay: persist.sitePackages || null, python: py.python, overrides: [], accepted };
717
+ // Version replacements by the overlay (installer 0.2.6): logged, shown in
718
+ // RESULT, recorded; a replacement that touches another profile or the
719
+ // ComfyUI core needs consent.
720
+ if (overlayReady()) {
721
+ const ov = overridesStep(io, {
722
+ python: py.python, sitePackages: persist.sitePackages, root, manifests, otherManifests, info, warn,
723
+ });
724
+ if (ov) {
725
+ out.overrides = ov.overrides;
726
+ out.conflicts = ov.conflicts;
727
+ out.record.nodeDeps.overrides = ov.overrides.map(overridesMod.recordOf);
728
+ const pending = overridesMod.pendingConflicts(ov.conflicts, accepted);
729
+ if (pending.length > 0) {
730
+ const lines = pending.map(overridesMod.describeConflict);
731
+ for (const l of lines) warn(`version replacement affects another profile: ${l}`);
732
+ let consent = !!flags['accept-node-deps-overrides'];
733
+ if (!consent && interactive) {
734
+ consent = await prompt.confirm(`The node-deps overlay is first in sys.path of the whole ComfyUI. It replaces packages that another profile or ComfyUI itself uses:\n - ${lines.join('\n - ')}\nKeep these replacements (the other profile may stop working)?`, { defaultYes: false });
735
+ }
736
+ if (consent) {
737
+ const at = new Date(typeof io.now === 'function' ? io.now() : Date.now()).toISOString();
738
+ accepted = [...accepted, ...pending.map((c) => overridesMod.acceptedEntry(c, at))];
739
+ out.record.nodeDeps.accepted = accepted;
740
+ info(`version replacements accepted (${flags['accept-node-deps-overrides'] ? '--accept-node-deps-overrides' : 'answer'}): ${pending.map(overridesMod.conflictKey).join(', ')}`);
741
+ dropSnap();
742
+ } else {
743
+ let undone = '';
744
+ if (snapshotOf) {
745
+ const rs = overridesMod.restoreOverlay(io, snapshotOf);
746
+ snapshotOf = null;
747
+ if (rs.ok) {
748
+ undone = '; the overlay was restored to its state before this run';
749
+ info(`overlay ${persist.paths.dir} restored from the snapshot — the replacements were not kept`);
750
+ const back = overridesStep(io, { python: py.python, sitePackages: persist.sitePackages, root, manifests, otherManifests, info: () => {}, warn: () => {} });
751
+ out.record.nodeDeps.overrides = back ? back.overrides.map(overridesMod.recordOf) : [];
752
+ out.overrides = back ? back.overrides : [];
753
+ } else {
754
+ undone = `; restoring the overlay failed: ${rs.reason}`;
755
+ warn(rs.reason);
756
+ }
757
+ }
758
+ out.failed = true;
759
+ const why = boot ? 'boot never consents' : (interactive ? 'not accepted' : 'no consent (--yes is not consent; use --accept-node-deps-overrides)');
760
+ out.reason = `the node-deps overlay would replace packages another profile on this ComfyUI uses (${why}): ${lines.join('; ')}${undone}. One GPU node — one profile`;
761
+ const profileArg = command === 'install' && Array.isArray(flags.profiles) && flags.profiles.length > 0 ? ` --profile ${flags.profiles.join(',')}` : '';
762
+ out.fix = `install this profile on a separate GPU node, or accept the replacements: ${tool} ${command === 'install' ? 'install' : 'doctor'}${profileArg} --accept-node-deps-overrides`;
763
+ return out;
764
+ }
765
+ }
766
+ }
767
+ }
768
+ dropSnap();
769
+ // The running process imported the custom nodes at its start: the
770
+ // remedy for missing classes with the packages in place is a restart —
771
+ // decided by FACT (/object_info), not only by "installed just now":
772
+ // `doctor --restart-platform-comfy` must restart even when nothing was
773
+ // installed in this run (otherwise the printed fix loops).
774
+ const expectClasses = nodeDeps.profileNodeRequirements(io, { root, manifests }).flatMap((n) => n.classes);
775
+ if (expectClasses.length === 0) return out;
776
+ const have = instance.url ? await comfyuiMod.objectInfoClasses(io, instance.url) : null;
777
+ if (!have && !needRestart) return out; // not answering — the platform gate/verification reports it
778
+ const missingNow = have ? expectClasses.filter((c) => !have.has(c)) : expectClasses;
779
+ if (missingNow.length === 0) {
780
+ if (needRestart) info(`the running ComfyUI (pid ${instance.pid}) already has the node classes — no restart needed`);
781
+ return out;
782
+ }
783
+ if (!needRestart && decision.source !== 'flag') {
784
+ // A node that fails for another reason (syntax error, CUDA, …) is
785
+ // not fixed by restarting it on every boot: report the cause.
786
+ const diag = await nodeDeps.diagnoseMissingClasses(io, {
787
+ missingClasses: missingNow, manifests, root, url: instance.url, pid: instance.pid, python: py.python,
788
+ extraPaths: extraPaths(), logFiles: workerDir ? [path.join(path.dirname(path.resolve(workerDir)), 'logs', 'comfyui-restart.log')] : [],
789
+ });
790
+ if (diag.kind === 'import-failed') {
791
+ out.failed = true;
792
+ out.reason = `node classes missing: ${missingNow.join(', ')} — ${diag.detail}`;
793
+ out.fix = `fix the import error of the custom node (ComfyUI log: ${diag.log_source}), then run: ${tool} doctor --restart-platform-comfy`;
794
+ return out;
795
+ }
796
+ info(`node classes missing in the running ComfyUI (pid ${instance.pid}): ${missingNow.join(', ')} — ${diag.detail}`);
797
+ }
798
+ if (restartAllowed === null && interactive) {
799
+ restartAllowed = await prompt.confirm(`The running ComfyUI (pid ${instance.pid}) loaded the custom nodes before their dependencies were in place. Restart it now (same command line, working directory and environment)?`, { defaultYes: true });
800
+ out.record.restartPlatformComfy = restartAllowed;
801
+ }
802
+ if (restartAllowed !== true) {
803
+ // A ComfyUI that is not ours is never stopped without the option.
804
+ out.failed = true;
805
+ out.reason = `custom-node dependencies are in place, but the platform's ComfyUI (pid ${instance.pid}) imported the nodes before that and was not restarted (restart of the platform's ComfyUI is off): ${missingNow.join(', ')} missing`;
806
+ out.fix = `restart the ComfyUI from the platform console, or run: ${tool} doctor --restart-platform-comfy`;
807
+ return out;
808
+ }
809
+ const restartLog = workerDir ? path.join(path.dirname(path.resolve(workerDir)), 'logs', 'comfyui-restart.log') : null;
810
+ const rr = await nodeDeps.restartForeignComfyUI(io, {
811
+ pid: instance.pid, timeoutMs: waitMs, intervalMs, expectClasses: missingNow, sleep, log: logger, onProgress: info, progressMs,
812
+ platformGraceMs, logFile: restartLog,
813
+ });
814
+ out.restarted = rr.stopped;
815
+ out.restart = { started_by: rr.started_by, log_file: rr.log_file };
816
+ if (!rr.ok) {
817
+ out.failed = true;
818
+ out.reason = rr.reason;
819
+ out.fix = rr.stopped
820
+ ? `${rr.log_file ? `see ${rr.log_file}; ` : ''}when ComfyUI answers again, run: ${tool} doctor`
821
+ : `restart the ComfyUI from the platform console, then run: ${tool} doctor`;
822
+ if (rr.stopped) out.pid_changed = rr.pid != null;
823
+ if (rr.missing_classes && rr.missing_classes.length > 0 && rr.pid) {
824
+ const diag = await nodeDeps.diagnoseMissingClasses(io, {
825
+ missingClasses: rr.missing_classes, manifests, root, url: rr.url, pid: rr.pid, python: py.python,
826
+ extraPaths: extraPaths(), logFiles: [restartLog].filter(Boolean),
827
+ });
828
+ out.reason = `${rr.reason} — ${diag.detail}`;
829
+ if (diag.kind === 'import-failed') out.fix = `fix the import error of the custom node (log: ${diag.log_source}), then run: ${tool} doctor --restart-platform-comfy`;
830
+ }
831
+ return out;
832
+ }
833
+ const who = rr.started_by === 'installer' ? 'the installer started ComfyUI again (same command line, cwd and environment)' : 'the platform started ComfyUI again';
834
+ info(`${who}: pid ${rr.old_pid} → ${rr.pid} at ${rr.url} (after ${Math.round(rr.waited_ms / 1000)} s), node classes present`);
835
+ out.pid_changed = true;
836
+ out.instance = await comfyOwner.resolveComfyOwner(io, { state, root });
837
+ return out;
838
+ }
839
+
840
+ /** Owned paths created by the dependency gate (overlay venv base, prestartup node). */
841
+ function nodeDepsOwnedServices(gate) {
842
+ const out = [];
843
+ if (!gate || !gate.persistence || gate.persistence.kind !== 'overlay') return out;
844
+ if (gate.persistence.base) out.push({ id: 'node-deps-overlay', path: gate.persistence.base });
845
+ if (gate.prestartup && gate.prestartup.dir && gate.prestartup.status !== 'foreign' && gate.prestartup.status !== 'failed') {
846
+ out.push({ id: 'node-deps-prestartup-node', path: gate.prestartup.dir });
847
+ }
848
+ return out;
849
+ }
850
+
851
+ /** Register owned service paths in an existing install-state.json (no-op without one). */
852
+ function recordOwnedServices(io, statePath, entries) {
853
+ if (!entries || entries.length === 0) return false;
854
+ const st = stateStore.loadState(io, statePath);
855
+ if (!st) return false;
856
+ for (const e of entries) stateStore.addOwnedComponent(st, 'services', e);
857
+ stateStore.saveState(io, statePath, st, io.now);
858
+ return true;
859
+ }
860
+
861
+ /** FAILED result of the dependency gate (the engine — worker start — does not run). */
862
+ function nodeDepsFailedResult({ gate, mode }) {
863
+ return {
864
+ status: 'failed',
865
+ mode,
866
+ warnings: [],
867
+ blocked: [],
868
+ verification: null,
869
+ results: { comfy_owner: { owner: gate.instance && gate.instance.owner, mode, url: (gate.instance && gate.instance.url) || null }, worker: [] },
870
+ e2e: [
871
+ { id: 'node-deps', ok: false, label: 'Custom-node dependencies', detail: gate.reason, fix: gate.fix || null },
872
+ { id: 'worker', ok: null, label: 'Worker → ComfyUI', detail: 'not started — the ComfyUI has no node classes for this profile', fix: null },
873
+ ],
874
+ };
875
+ }
876
+
877
+ /**
878
+ * Register a file the installer wrote into the worker dir (uninstall removes
879
+ * it). Only for the recorded worker of THIS dir; no-op without a state.
880
+ */
881
+ function recordWorkerFile(io, statePath, workerDir, file) {
882
+ try {
883
+ const st = stateStore.loadState(io, statePath);
884
+ const w = st && st.components && st.components.worker;
885
+ if (!w || !w.dir || path.resolve(w.dir) !== path.resolve(workerDir)) return false;
886
+ const files = new Set(w.files_installed || []);
887
+ if (files.has(file)) return false;
888
+ files.add(file);
889
+ w.files_installed = Array.from(files);
890
+ stateStore.saveState(io, statePath, st, io.now);
891
+ return true;
892
+ } catch (_) { return false; }
893
+ }
894
+
895
+ /** Store one installer option in install-state.json (a recorded answer). */
896
+ function recordInstallerOption(io, statePath, key, value) {
897
+ const st = stateStore.loadState(io, statePath);
898
+ if (!st) return false;
899
+ st.installer_options = { ...(st.installer_options || {}), [key]: value };
900
+ stateStore.saveState(io, statePath, st, io.now);
901
+ return true;
902
+ }
903
+
904
+ /** ~/animastor/logs/bootstrap.log — the boot log next to the worker dir. */
905
+ function bootLogPath(flags) {
906
+ return flags['boot-log'] || path.join(path.dirname(resolveWorkerDir(flags)), 'logs', 'bootstrap.log');
907
+ }
908
+
909
+ /** System boot time from /proc/stat (btime) as ISO, or null. */
910
+ function systemBootTime(io) {
911
+ try {
912
+ const m = /^btime\s+(\d+)/m.exec(String(io.fs.readFileSync('/proc/stat', 'utf8')));
913
+ return m ? new Date(Number(m[1]) * 1000).toISOString() : null;
914
+ } catch (_) { return null; }
915
+ }
916
+
917
+ /** The argv of the detached `doctor --yes` that `animastor boot` starts. */
918
+ function bootChildArgs(flags, { cliPath = __filename, defaultWaitMs = 600000 } = {}) {
919
+ const args = [cliPath, 'doctor', '--yes'];
920
+ for (const [k, v] of Object.entries(flags)) {
921
+ if (k === 'profiles' || k === 'yes' || k === 'boot-log' || v === undefined || v === null || v === false) continue;
922
+ if (v === true) args.push(`--${k}`);
923
+ else args.push(`--${k}`, String(v));
924
+ }
925
+ if (flags['comfy-wait-ms'] === undefined || flags['comfy-wait-ms'] === '') {
926
+ if (!process.env.ANIMASTOR_COMFY_WAIT_MS) args.push('--comfy-wait-ms', String(defaultWaitMs));
927
+ }
928
+ return args;
929
+ }
930
+
931
+ /**
932
+ * `animastor boot` (installer 0.2.4) — the WHOLE node startup script. TIR
933
+ * starts its own ComfyUI only AFTER the startup script has finished, so any
934
+ * wait inside the script is a deadlock (live 31.10: doctor gave up 05:19:06,
935
+ * main.py started 05:19:35). boot therefore detaches at once — new session
936
+ * (setsid), stdin /dev/null, stdout/stderr appended to
937
+ * ~/animastor/logs/bootstrap.log under a header with the boot time — and
938
+ * exits 0; the detached `doctor --yes` waits (600 s by default), restores the
939
+ * node dependencies, restarts the platform's ComfyUI when needed and starts
940
+ * the worker.
941
+ */
942
+ function cmdBoot(flags, { io = createRealIo(), spawn = require('child_process').spawn, execPath = process.execPath, cliPath = __filename, now = () => new Date() } = {}) {
943
+ const logFile = bootLogPath(flags);
944
+ let fd = null;
945
+ try {
946
+ io.fs.mkdirSync(path.dirname(logFile), { recursive: true });
947
+ fd = fs.openSync(logFile, 'a');
948
+ const btime = systemBootTime(io);
949
+ fs.writeSync(fd, `\n===== animastor boot ${now().toISOString()} (system boot ${btime || 'unknown'}) =====\n`);
950
+ const args = bootChildArgs(flags, { cliPath });
951
+ const child = spawn(execPath, args, {
952
+ detached: true,
953
+ stdio: ['ignore', fd, fd],
954
+ cwd: homeDir(),
955
+ env: { ...process.env, ANIMASTOR_BOOT: '1' },
956
+ });
957
+ if (child && typeof child.unref === 'function') child.unref();
958
+ const pid = child && child.pid;
959
+ fs.writeSync(fd, `animastor boot: doctor --yes detached (pid ${pid || '?'}): ${args.slice(1).join(' ')}\n`);
960
+ console.log(`animastor boot: started in the background (pid ${pid || '?'}), log ${logFile}`);
961
+ process.exitCode = 0;
962
+ return { pid: pid || null, logFile, args };
963
+ } catch (err) {
964
+ console.error(`animastor boot: could not start the background run: ${err.message} (log ${logFile})`);
965
+ process.exitCode = 1;
966
+ return { pid: null, logFile, error: err.message };
967
+ } finally {
968
+ if (fd != null) { try { fs.closeSync(fd); } catch (_) { /* closed */ } }
969
+ }
970
+ }
971
+
972
+ /** This installer's version (package.json next to src/). */
973
+ function ownVersion() {
974
+ try { return require('../../package.json').version; } catch (_) { return null; }
975
+ }
976
+
977
+ /** Version of the persistent installer copy behind the `animastor` command (<base>/installer), or null. */
978
+ function installedToolsVersion(io, flags) {
979
+ const dir = path.join(path.dirname(resolveToolsDir(flags)), 'installer');
980
+ try { return JSON.parse(String(io.fs.readFileSync(path.join(dir, 'package.json'), 'utf8'))).version || null; } catch (_) { return null; }
981
+ }
982
+
983
+ /**
984
+ * Installer 0.2.5 — FIRST change of every install/doctor run, before any
985
+ * check that can end the run with ✗: the management tools (the `animastor`
986
+ * command and the persistent installer copy it runs) and an installed worker
987
+ * bundle are brought to THIS installer's version. Live E2E 02.11: 0.2.4
988
+ * stopped at the node-deps gate before its "install management tools" step,
989
+ * so ~/.local/bin/animastor stayed 0.2.3 (bundle 2.2.0) and the printed fix
990
+ * `animastor doctor --restart-platform-comfy` ran a version that did not
991
+ * know the flag. Every fix command printed afterwards names a command of
992
+ * THIS version — or the result says why it could not be updated.
993
+ * @returns {Promise<{ tools: object|null, tools_error: string|null, tools_skipped: string|null, bundle: object|null, version: string|null, tools_version: string|null }>}
994
+ */
995
+ async function preflightSelfUpdate(io, {
996
+ flags, statePath, root, workerDir, hubUrl, repoRoot, manifests = [], logger = null, dryRun = false,
997
+ nodeBin = null, home = homeDir(), linkDir = undefined, cliPath = __filename,
998
+ installerSrcRoot = path.resolve(__dirname, '..', '..'),
999
+ } = {}) {
1000
+ const out = { tools: null, tools_error: null, tools_skipped: null, bundle: null, version: ownVersion(), tools_version: null };
1001
+ if (dryRun) { out.tools_skipped = 'dry-run'; return out; }
1002
+ const toolsDirEarly = resolveToolsDir(flags);
1003
+ // Never write as the wrong user (sudo vs. normal user): the host gate
1004
+ // later stops such a run with the full explanation.
1005
+ const own = prereq.checkOwnership(io, {
1006
+ paths: [root, workerDir, statePath, toolsDirEarly].filter(Boolean), home: prereq.currentHome(), currentUid: prereq.currentUid(),
1007
+ });
1008
+ if (!own.ok) { out.tools_skipped = 'ownership mismatch'; return out; }
1009
+ const wantTools = await resolveToolsDecision({ flags, prompt: null, prior: priorToolsDecision(io, statePath) });
1010
+ const toolsDir = toolsDirEarly;
1011
+ if (!wantTools) {
1012
+ out.tools_skipped = 'management tools declined (--no-tools)';
1013
+ } else {
1014
+ try {
1015
+ out.tools = management.installManagementTools(io, {
1016
+ toolsDir,
1017
+ nodePath: nodeBin || process.execPath,
1018
+ cliPath,
1019
+ installerSrcRoot,
1020
+ installerDestRoot: path.join(path.dirname(toolsDir), 'installer'),
1021
+ linkDir: linkDir !== undefined ? linkDir : management.defaultLinkDir(),
1022
+ home,
1023
+ statePath,
1024
+ root,
1025
+ workerDir,
1026
+ hubUrl,
1027
+ log: logger,
1028
+ platformAdapter: PLATFORM_ADAPTER,
1029
+ });
1030
+ } catch (err) {
1031
+ out.tools_error = err.message;
1032
+ if (logger) logger.warn(`management tools could not be updated: ${err.message}`);
1033
+ }
1034
+ }
1035
+ out.tools_version = installedToolsVersion(io, flags);
1036
+ if (manifests.length > 0) {
1037
+ try {
1038
+ out.bundle = await engineMod.refreshInstalledWorkerBundle(io, {
1039
+ workerDir, manifest: manifests[0], repoRoot, hubUrl, log: logger, nodeBin,
1040
+ });
1041
+ } catch (err) {
1042
+ out.bundle = { status: 'failed', reason: err.message };
1043
+ }
1044
+ if (out.bundle && out.bundle.status === 'failed' && logger) logger.warn(`worker bundle ${out.bundle.have || '?'} could not be updated to ${out.bundle.want || '?'}: ${out.bundle.reason}`);
1045
+ // Installer 0.2.7: node-classes.json for the worker's readiness gate
1046
+ // — on install, bundle update, doctor and boot alike, so a node
1047
+ // installed by an older installer gets it on its next doctor/boot.
1048
+ try {
1049
+ out.node_classes = engineMod.writeNodeClasses(io, { workerDir, manifests, log: logger, version: ownVersion() });
1050
+ if (out.node_classes.status === 'written') recordWorkerFile(io, statePath, workerDir, 'node-classes.json');
1051
+ } catch (err) {
1052
+ out.node_classes = { status: 'failed', reason: err.message };
1053
+ }
1054
+ }
1055
+ return out;
1056
+ }
1057
+
1058
+ /**
1059
+ * Result lines for a preflight that could not bring the tools/bundle to
1060
+ * this version — the fix commands of the result would otherwise run an
1061
+ * older `animastor` (or the worker an older bundle) without saying so.
1062
+ */
1063
+ function preflightExtras(pre) {
1064
+ if (!pre) return [];
1065
+ const extra = [];
1066
+ if (!pre.tools_skipped && pre.version && pre.tools_version !== pre.version) {
1067
+ extra.push({
1068
+ ok: false,
1069
+ label: 'Management tools',
1070
+ detail: `the animastor command runs installer ${pre.tools_version || 'unknown'}, this installer is ${pre.version}${pre.tools_error ? ` — update failed: ${pre.tools_error}` : ''}; the fix commands of this result need ${pre.version}`,
1071
+ fix: 'run the install command from the Animastor setup page again',
1072
+ });
1073
+ }
1074
+ if (pre.bundle && pre.bundle.status === 'failed') {
1075
+ extra.push({
1076
+ ok: false,
1077
+ label: 'Worker bundle',
1078
+ detail: `installed ${pre.bundle.have || 'unknown'}, this installer ships ${pre.bundle.want || 'unknown'} — update failed: ${pre.bundle.reason}`,
1079
+ fix: 'run the install command from the Animastor setup page again',
1080
+ });
1081
+ }
1082
+ return extra;
1083
+ }
1084
+
1085
+ /** The one line for the node startup script (printed at the end of an install). */
1086
+ function startupScriptLine(flags) {
1087
+ const tool = toolCommandPath(flags);
1088
+ return `export PATH="$HOME/.local/bin:$PATH"; ${tool} boot`;
1089
+ }
1090
+
1091
+ /** The `animastor` command recorded for this installation (fix lines). */
1092
+ function toolCommand(flags) {
1093
+ const tool = path.join(resolveToolsDir(flags), 'animastor');
1094
+ const linked = path.join(management.defaultLinkDir() || '', 'animastor');
1095
+ if (fs.existsSync(linked) && String(process.env.PATH || '').split(path.delimiter).includes(path.dirname(linked))) return 'animastor';
1096
+ if (fs.existsSync(tool)) return tool;
1097
+ return 'animastor';
1098
+ }
1099
+
316
1100
  /** Secret values collected interactively — memory-only, never persisted. */
317
1101
  function makeSecretProvider(secrets) {
318
1102
  if (!secrets || Object.keys(secrets).length === 0) return null;
@@ -361,16 +1145,40 @@ function createScreen() {
361
1145
  });
362
1146
  }
363
1147
 
364
- async function cmdInstall(flags) {
1148
+ async function cmdInstall(flags, { doctor = false } = {}) {
1149
+ const realIo = createRealIo();
1150
+ // doctor = the same idempotent install for the RECORDED installation:
1151
+ // profiles come from install-state.json unless given explicitly. The
1152
+ // recorded MODE is not applied: the mode follows the machine (see
1153
+ // engine/comfy-owner.js) — a contradiction is shown and corrected.
1154
+ const statePathEarly = resolveStatePath(flags);
1155
+ let recorded = null;
1156
+ if (doctor) {
1157
+ recorded = stateStore.loadState(realIo, statePathEarly);
1158
+ if (!recorded || !Array.isArray(recorded.profiles) || recorded.profiles.length === 0) {
1159
+ console.error(`No Animastor installation found (state: ${statePathEarly}). Run the install command from the Animastor setup page first.`);
1160
+ process.exit(2);
1161
+ }
1162
+ if (flags.profiles.length === 0) flags.profiles = recorded.profiles.slice();
1163
+ }
365
1164
  if (flags.profiles.length === 0) {
366
1165
  console.error('error: --profile is required');
367
1166
  process.exit(1);
368
1167
  }
369
- const root = resolveRoot(flags);
1168
+ // Recorded facts reused as the starting point: previous non-secret
1169
+ // decisions (no repeated questions) and the hub version for the banner.
1170
+ const priorState = recorded || stateStore.loadState(realIo, statePathEarly);
1171
+ const boot = isBootRun(flags, doctor);
1172
+ // ComfyUI root: --root > ~/ComfyUI (when it holds a ComfyUI) > the root
1173
+ // of the user's running ComfyUI process > ~/ComfyUI (managed creates it).
1174
+ let runningComfy = probeMod.detectRunningComfyUI(realIo);
1175
+ const rootPick = probeMod.resolveComfyRoot(realIo, { explicit: flags.root || null, defaultRoot: DEFAULT_ROOT, running: runningComfy });
1176
+ flags.root = rootPick.root;
1177
+ const root = rootPick.root;
370
1178
  const workerDir = resolveWorkerDir(flags);
371
1179
  const hubUrl = resolveHubUrl(flags);
372
1180
  const repoRoot = resolveRepoRoot(flags);
373
- const statePath = resolveStatePath(flags);
1181
+ const statePath = statePathEarly;
374
1182
  const dryRun = flags['dry-run'] || false;
375
1183
  const yes = flags.yes || false;
376
1184
  const crypto = require('crypto');
@@ -378,167 +1186,391 @@ async function cmdInstall(flags) {
378
1186
  // Probing is read-only and always runs against the REAL io. In dry-run
379
1187
  // mode the guarded io is used ONLY inside the engine, where every
380
1188
  // mutating operation would throw a "dry-run violation".
381
- const realIo = createRealIo();
382
1189
  const screen = createScreen();
383
1190
  const logger = createLogger({ io: realIo, sink: (line) => screen.print(line) });
384
1191
  const loadedManifests = flags.profiles.map((p) => manifest.loadManifest(p));
385
- const mode = flags.mode || 'managed';
1192
+ const hubVersion = doctor
1193
+ ? await detectHubVersion(realIo, hubUrl, { known: process.env.ANIMASTOR_HUB_VERSION || (priorState && priorState.hub_version) || null })
1194
+ : (process.env.ANIMASTOR_HUB_VERSION || null);
1195
+
1196
+ if (!boot) {
1197
+ console.log(renderBanner(bannerVersions(loadedManifests, flags, { hub: hubVersion })));
1198
+ if (doctor) console.log('animastor doctor — re-checking the installation and fixing what can be fixed\n');
1199
+ }
1200
+
1201
+ // ONE prompt object for the whole run; every question reads /dev/tty
1202
+ // when stdin is the `curl | bash` pipe. Created BEFORE the ownership
1203
+ // questions below.
1204
+ const prompt = createPrompt();
1205
+
1206
+ // Restore the PATH block before anything else: the dotfiles are reset on
1207
+ // every node boot while ~/.local/bin/animastor survives.
1208
+ const pathEntry = management.restoreCommandPath(realIo, { linkDir: management.defaultLinkDir(), home: homeDir() });
1209
+ if (!boot && pathEntry.updated.length > 0) console.log(`PATH block restored: ${pathEntry.updated.join(', ')}`);
1210
+
1211
+ // Tools + bundle of THIS version before anything can stop the run (0.2.5).
1212
+ const preflight = await preflightSelfUpdate(realIo, {
1213
+ flags, statePath, root, workerDir, hubUrl, repoRoot, manifests: loadedManifests, logger, dryRun,
1214
+ nodeBin: (probeMod.pickNodeBinary(realIo) || {}).bin || null,
1215
+ });
1216
+ const withPre = (res) => ({ ...res, preflight });
1217
+
1218
+ // Host packages that disappeared with the image restart (boot path).
1219
+ if (doctor) {
1220
+ const missingPkgs = missingRequiredHostPackages(realIo);
1221
+ if (missingPkgs.length > 0) {
1222
+ const r = await prereq.installMissingHostPackages(realIo, {
1223
+ packages: missingPkgs, prompt: boot ? null : prompt, yes, log: logger,
1224
+ });
1225
+ if (r.installed.length > 0 && !boot) console.log(`✓ installed ${r.installed.join(' ')}`);
1226
+ else if (!r.ok && !boot) console.log(`! ${r.message}`);
1227
+ }
1228
+ }
1229
+
1230
+ // ComfyUI ownership BY FACT: a verified ComfyUI process the installer did
1231
+ // not start decides the mode (existing) and the worker address; the
1232
+ // installer never starts a second one next to it.
1233
+ let instance = await comfyOwner.resolveComfyOwner(realIo, { state: priorState, root });
1234
+ const comfyWaitMs = flags['comfy-wait-ms'] !== undefined && flags['comfy-wait-ms'] !== ''
1235
+ ? Number(flags['comfy-wait-ms'])
1236
+ : (Number(process.env.ANIMASTOR_COMFY_WAIT_MS) || (boot ? 180000 : 0));
1237
+ // Type A boot: the platform starts ComfyUI AFTER this script — wait for
1238
+ // it (process + /system_stats) before the address is recomputed into
1239
+ // .env and the worker is started; never start it against the address
1240
+ // of a previous boot.
1241
+ const windowStart = realIo.now();
1242
+ const gate = await platformComfyGate(realIo, { state: priorState, root, waitMs: comfyWaitMs, instance, logger });
1243
+ instance = gate.instance;
1244
+ if (gate.waited && gate.waited.ok) runningComfy = probeMod.detectRunningComfyUI(realIo);
1245
+ if (gate.failed) {
1246
+ printResult(withPre(platformComfyMissingResult({ waited: gate.waited, tool: toolCommandPath(flags), mode: 'existing' })), { flags, mode: 'existing', boot });
1247
+ process.exitCode = 1;
1248
+ prompt.close();
1249
+ return;
1250
+ }
1251
+
1252
+ // Type A (installer 0.2.4): the pip packages of the custom nodes live
1253
+ // outside /home and vanish with a node restart — check them in the Python
1254
+ // of the platform's main.py, reinstall, and (when allowed) let the
1255
+ // platform start its ComfyUI again so the node classes load.
1256
+ const recordedPid = priorState && priorState.comfy_owner ? priorState.comfy_owner.pid : null;
1257
+ const ownedServices = [];
1258
+ const depsGate = dryRun ? null : await platformNodeDepsGate(realIo, {
1259
+ instance, state: priorState, root, manifests: loadedManifests, flags, boot, yes, prompt,
1260
+ waitMs: Math.max(180000, comfyWaitMs - (realIo.now() - windowStart)), logger, statePath, workerDir,
1261
+ otherManifests: otherProfileManifests(priorState, flags.profiles, { logger }), command: doctor ? 'doctor' : 'install',
1262
+ });
1263
+ if (depsGate) {
1264
+ instance = depsGate.instance;
1265
+ if (depsGate.restarted) runningComfy = probeMod.detectRunningComfyUI(realIo);
1266
+ if (depsGate.record.restartPlatformComfy !== undefined) {
1267
+ recordInstallerOption(realIo, statePath, 'restartPlatformComfy', depsGate.record.restartPlatformComfy);
1268
+ }
1269
+ if (depsGate.record.nodeDeps) recordInstallerOption(realIo, statePath, 'nodeDeps', depsGate.record.nodeDeps);
1270
+ ownedServices.push(...nodeDepsOwnedServices(depsGate));
1271
+ recordOwnedServices(realIo, statePath, ownedServices);
1272
+ if (depsGate.failed) {
1273
+ printResult(withPre({ ...nodeDepsFailedResult({ gate: depsGate, mode: instance.mode }), node_deps_overrides: depsGate.overrides }), { flags, mode: instance.mode, boot });
1274
+ process.exitCode = 1;
1275
+ prompt.close();
1276
+ return;
1277
+ }
1278
+ }
1279
+ // Node classes are re-checked until the end of the window when the node
1280
+ // dependencies were just installed or the ComfyUI is a new process.
1281
+ const pidChanged = !!(depsGate && depsGate.pid_changed)
1282
+ || (recordedPid != null && instance.pid != null && Number(recordedPid) !== Number(instance.pid));
1283
+ const nodeClassesDeadline = (depsGate && depsGate.installed.length > 0) || pidChanged
1284
+ ? windowStart + Math.max(comfyWaitMs, 0)
1285
+ : null;
1286
+
1287
+ // The machine decides the mode. An explicit --mode that contradicts it is
1288
+ // reported, never silently applied: starting a second ComfyUI next to the
1289
+ // platform's is exactly the failure this release fixes.
1290
+ const mode = instance.mode;
1291
+ if (!boot) {
1292
+ if (flags.mode && flags.mode !== instance.mode) {
1293
+ console.log(`Mode: ${instance.mode} — ${instance.reason}; --mode ${flags.mode} ignored (the machine decides)`);
1294
+ } else {
1295
+ console.log(`Mode: ${instance.mode} — ${instance.reason}`);
1296
+ }
1297
+ }
1298
+ if (instance.conflicts.length > 0 && !boot) {
1299
+ console.log('\nThe recorded installation disagrees with this machine:');
1300
+ for (const c of instance.conflicts) console.log(` ! ${c.message}`);
1301
+ console.log(' → corrected for this run and stored in install-state.json');
1302
+ }
1303
+ if (instance.stop_offer) {
1304
+ const pid = instance.stop_offer.pid;
1305
+ const question = `Stop the installer's own ComfyUI (pid ${pid})? The platform instance ${instance.foreign.url} is the real one.`;
1306
+ let stopIt = false;
1307
+ if (yes) stopIt = true;
1308
+ else if (prompt.available) stopIt = await prompt.confirm(question, { defaultYes: true });
1309
+ else if (!boot) console.log(` · ${question} (non-interactive — left running; --yes stops it)`);
1310
+ if (stopIt) {
1311
+ const stopRes = comfyOwner.stopInstallerInstance(realIo, instance.ours);
1312
+ if (!boot) console.log(stopRes.stopped ? `✓ installer ComfyUI stopped (pid ${pid})` : `! ${stopRes.reason}`);
1313
+ }
1314
+ }
386
1315
 
387
1316
  const env = probeEnvironment(realIo, {
388
1317
  root, workerDir, crypto,
389
1318
  workerType: loadedManifests.length === 1 ? (loadedManifests[0].worker_bundle || {}).worker_type : null,
390
1319
  });
391
1320
 
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, {
1321
+ // The dry-run guard wraps everything handed to the engine so any
1322
+ // accidental mutation throws "dry-run violation" instead of executing.
1323
+ const io = dryRun ? createDryRunIo(realIo) : realIo;
1324
+
1325
+ // The plan comes FIRST: the prerequisite check must know whether the
1326
+ // Python runtime/venv is used at all (a working `existing` ComfyUI with
1327
+ // its models already in place needs none). Previously answered steps
1328
+ // (a declined optional workflow, a declined model download) are not
1329
+ // asked again.
1330
+ const priorDecisions = priorReusableDecisions(priorState);
1331
+ const { plan, report: planReport } = await resolveAndPlanWithSizes({ io: realIo, manifests: loadedManifests, env, mode, decisions: priorDecisions });
1332
+
1333
+ // Prerequisites & ownership BEFORE any prompt/change: a missing
1334
+ // python3.X-venv is reported/installed up front (when the plan uses the
1335
+ // runtime), not after the user has answered every question.
1336
+ await runHostGates(realIo, {
396
1337
  paths: [root, workerDir, statePath, resolveToolsDir(flags)].filter(Boolean),
397
1338
  dryRun,
398
- deep: true,
399
1339
  venvDir: path.join(root, 'venv'),
1340
+ needVenv: planNeedsPythonRuntime({ plan, report: planReport, mode }),
1341
+ prompt,
1342
+ yes,
1343
+ log: logger,
400
1344
  });
401
1345
 
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: {} });
1346
+ // Mode was printed above with its reason; the questions are asked below
1347
+ // one by one — neither is repeated in the plan text.
1348
+ if (!boot) {
1349
+ console.log(`Profile: ${plan.profiles.join(' + ')}\n`);
1350
+ console.log(renderPlanText(plan, planReport, { questions: false, header: false }));
1351
+ }
407
1352
 
408
- console.log(plan.plan_text);
1353
+ const needPrompt = () => {
1354
+ if (!prompt.available) {
1355
+ console.error('');
1356
+ console.error(require('./engine/tty').NO_TTY_MESSAGE);
1357
+ process.exit(3);
1358
+ }
1359
+ return prompt;
1360
+ };
409
1361
 
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);
1362
+ try {
1363
+ // CPU-only mode is always announced explicitly and confirmed before any
1364
+ // change: the user must see that performance will be significantly lower.
1365
+ const device = env.device || (env.gpu ? 'cuda' : 'cpu');
1366
+ if (device === 'cpu' && !dryRun) {
1367
+ console.log('\n=========================================================================');
1368
+ console.log(' CPU-ONLY MODE: no supported GPU was detected.');
1369
+ console.log(' A CPU build of PyTorch will be installed and ComfyUI will run');
1370
+ console.log(' with --cpu. Performance will be SIGNIFICANTLY lower.');
1371
+ console.log(' This mode is intended for the TTS/audio profile test scenario.');
1372
+ console.log('=========================================================================');
1373
+ if (!yes) {
1374
+ const proceed = await needPrompt().confirm('Continue with the CPU-only installation?');
1375
+ if (!proceed) {
1376
+ console.log('Aborted — nothing was changed.');
1377
+ process.exit(0);
1378
+ }
427
1379
  }
428
1380
  }
429
- }
430
1381
 
431
- if (dryRun) {
432
- console.log('\n[dry-run] zero mutations performed');
433
- return;
434
- }
1382
+ if (dryRun) {
1383
+ console.log('\n[dry-run] zero mutations performed');
1384
+ return;
1385
+ }
435
1386
 
436
- if (plan.blocked.length > 0) {
437
- console.error('\nInstallation blocked — see above for details');
438
- process.exit(1);
439
- }
1387
+ if (plan.blocked.length > 0) {
1388
+ printFinal({ blocked: plan.blocked, tool: toolCommand(flags), mode, preflight });
1389
+ process.exitCode = 1;
1390
+ return;
1391
+ }
440
1392
 
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).
1393
+ // Auto-fix: one list, one question — instead of warnings. The ComfyUI
1394
+ // address comes from the running process (comfy-owner), verified by
1395
+ // GET /system_stats, and is recomputed on EVERY run: port and notebook
1396
+ // prefix change between boots, so the remembered .env is not trusted.
1397
+ const nodePick = probeMod.pickNodeBinary(realIo);
1398
+ const port = flags['comfy-port'] ? Number(flags['comfy-port']) : (instance.port || null);
1399
+ let probedUrl = instance.url || null;
1400
+ if (!probedUrl && (port || mode !== 'managed')) {
1401
+ const envNow = workerMod.readEnvValues(realIo, workerDir);
1402
+ const pr = await probeMod.probeComfyUrl(realIo, {
1403
+ port: port || Number(envNow.COMFY_PORT) || 8188,
1404
+ prefixes: [envNow.NOTEBOOK_PATH, runningComfy && runningComfy.baseurl].filter(Boolean),
1405
+ });
1406
+ probedUrl = pr.url;
1407
+ }
1408
+ const desired = engineMod.desiredEnvWiring({
1409
+ manifests: loadedManifests,
1410
+ nodeBin: nodePick ? nodePick.bin : null,
1411
+ comfyUrl: probedUrl,
1412
+ comfyPort: port,
1413
+ hubUrl,
1414
+ hubUrlExplicit: !!flags['hub-url'],
1415
+ });
1416
+ const fixPlan = fixes.planFixes(realIo, {
1417
+ workerDir, desired,
1418
+ sourceBundleDir: resolveRepoBundleDir(fs, repoRoot),
1419
+ sourceVersion: process.env.ANIMASTOR_WORKER_BUNDLE_VERSION || null, // served by the hub (bootstrap)
1420
+ });
1421
+ let applyFixes = true;
1422
+ if (fixPlan.additions.length > 0 && !boot) {
1423
+ console.log(`\nWorker settings to add: ${fixPlan.additions.join(', ')}`);
1424
+ }
1425
+ if (fixPlan.items.length > 0) {
1426
+ if (!boot) {
1427
+ console.log('\nThe installer will fix:');
1428
+ fixPlan.items.forEach((f, i) => console.log(` ${i + 1}. ${f.title}`));
1429
+ }
1430
+ if (flags['no-fix']) applyFixes = false;
1431
+ else if (!yes) applyFixes = await needPrompt().confirm(`Fix ${fixPlan.items.length === 1 ? 'it' : `all ${fixPlan.items.length}`}?`, { defaultYes: true });
1432
+ if (!applyFixes && !boot) console.log('Not fixing — the remaining problems are listed in the result.');
1433
+ }
1434
+
1435
+ const decisions = { ...priorDecisions, apply_fixes: applyFixes };
1436
+ // Management tools (the `animastor` command): part of a normal
1437
+ // installation; --no-tools opts out, a recorded decision is kept.
446
1438
  decisions.install_management_tools = await resolveToolsDecision({
447
- flags, prompt, prior: priorToolsDecision(realIo, statePath),
1439
+ flags, prompt: null, prior: priorToolsDecision(realIo, statePath),
448
1440
  });
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
1441
  if (flags['accept-reference-runtime']) decisions.accept_reference_runtime = true;
453
1442
  if (flags['accept-runtime-change']) decisions.accept_runtime_change = true;
454
1443
  // Secret VALUES live only in this closure — never in decisions, logs,
455
1444
  // state, or argv. The engine receives them via secretProvider.
456
1445
  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;
1446
+
1447
+ if (yes) {
1448
+ // --yes answers everything EXCEPT steps the user already declined:
1449
+ // a "no" to the optional workflows (and to model/node downloads)
1450
+ // is remembered, so a boot-time `doctor --yes` never installs them
1451
+ // behind the user's back.
1452
+ const yd = yesDecisions();
1453
+ for (const k of ['workflows', 'install_models', 'install_custom_nodes']) {
1454
+ if (priorDecisions[k] !== undefined) yd[k] = priorDecisions[k];
464
1455
  }
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;
1456
+ Object.assign(decisions, yd);
1457
+ } else if (plan.awaiting_decisions.length > 0) {
1458
+ for (const stepId of plan.awaiting_decisions) {
1459
+ const step = plan.steps.find((s) => s.id === stepId);
1460
+ if (!step || !step.prompt) continue;
1461
+ if (stepId === 'worker-key' && decisions.worker_setup === false) {
1462
+ // worker setup was declined — the key prompt is skipped too
1463
+ decisions.worker_key_provided = false;
1464
+ continue;
1465
+ }
1466
+ if (step.kind === 'secret-prompt') {
1467
+ // Re-install over an already configured worker: the key is
1468
+ // in .env — never ask for it again (a key that the hub
1469
+ // REJECTED is replaced via --new-key, not by re-asking).
1470
+ if (stepId === 'worker-key' && !flags['new-key']
1471
+ && workerMod.hasEnvKey(realIo, workerDir, 'ANIMASTOR_WORKER_TOKEN')) {
1472
+ console.log(`Worker Key: kept from ${path.join(workerDir, '.env')} (already configured — not asked again; use --new-key to replace it)`);
1473
+ decisions.worker_key_provided = true;
1474
+ continue;
1475
+ }
1476
+ // Worker Key step: real hidden input (never a Yes/No confirm —
1477
+ // a typed token must not be misread as an answer). Only the
1478
+ // boolean fact "provided" enters the decisions; the value
1479
+ // itself is handed to the engine through secretProvider.
1480
+ let provided = false;
1481
+ for (const key of step.secret_keys || []) {
1482
+ const value = await needPrompt().secret(`Paste the Worker Key from the Animastor page (${key}, hidden input)`);
1483
+ if (value) {
1484
+ secrets[key] = value;
1485
+ logger.registerSecret(value); // redact from ALL further output
1486
+ provided = true;
1487
+ }
477
1488
  }
1489
+ decisions.worker_key_provided = provided;
1490
+ continue;
478
1491
  }
479
- decisions.worker_key_provided = provided;
480
- continue;
1492
+ // "Cannot be determined automatically — review": there is
1493
+ // nothing to choose; continue with the user's ComfyUI as is.
1494
+ if (stepId === 'comfyui-update' && (step.prompt.options || [])[0] === 'Review') {
1495
+ console.log(`${String(step.prompt.question).split('\n')[0]} — continuing with the installed ComfyUI as is.`);
1496
+ decisions.comfyui_update = 'yes';
1497
+ continue;
1498
+ }
1499
+ const answer = await needPrompt().confirm(stepQuestion(step), { defaultYes: true });
1500
+ if (step.consent === 'accept_reference_runtime') {
1501
+ decisions.accept_reference_runtime = answer;
1502
+ continue;
1503
+ }
1504
+ if (stepId === 'comfyui-update') decisions.comfyui_update = answer ? 'yes' : 'no';
1505
+ else if (stepId === 'custom-nodes') decisions.install_custom_nodes = answer;
1506
+ else if (stepId === 'models') decisions.install_models = answer;
1507
+ else if (stepId === 'workflows') decisions.workflows = answer ? 'all' : 'none';
1508
+ else if (stepId === 'worker-setup') decisions.worker_setup = answer;
1509
+ else if (stepId === 'worker-key') decisions.worker_key_provided = answer;
481
1510
  }
482
- const answer = await prompt.confirm(step.prompt.question);
483
- if (step.consent === 'accept_reference_runtime') {
484
- decisions.accept_reference_runtime = answer;
485
- continue;
1511
+ }
1512
+ if (decisions.worker_setup === undefined) decisions.worker_setup = true;
1513
+
1514
+ // doctor --new-key: the current key was rejected — ask for the new one.
1515
+ let replaceWorkerKey = false;
1516
+ if (flags['new-key']) {
1517
+ const value = await needPrompt().secret('Paste the NEW Worker Key from Animastor → Settings → Workers (hidden input)');
1518
+ if (value) {
1519
+ secrets.ANIMASTOR_WORKER_TOKEN = value;
1520
+ logger.registerSecret(value);
1521
+ replaceWorkerKey = true;
486
1522
  }
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
1523
  }
494
- prompt.close();
495
1524
 
496
1525
  // Re-resolve and rebuild the plan with the recorded decisions — one
497
1526
  // call shape, so the rebuilt plan always has a resolution report.
498
1527
  const { plan: plan2 } = resolveAndPlan({ manifests: loadedManifests, env, mode, decisions });
499
-
500
1528
  if (plan2.awaiting_decisions.length > 0) {
501
- console.error('\nStill awaiting decisions after prompts — cannot proceed');
1529
+ console.error(`\nStill awaiting decisions after prompts (${plan2.awaiting_decisions.join(', ')}) — cannot proceed`);
502
1530
  process.exit(1);
503
1531
  }
504
1532
  if (plan2.blocked.length > 0) {
505
- console.error('\nInstallation blocked after decisions — see above');
506
- process.exit(1);
1533
+ printFinal({ blocked: plan2.blocked, tool: toolCommand(flags), mode, preflight });
1534
+ process.exitCode = 1;
1535
+ return;
507
1536
  }
508
1537
 
509
1538
  const result = await runInstallation({
510
1539
  manifests: loadedManifests, mode, io,
511
1540
  roots: { comfyuiRoot: root, workerDir, statePath, repoRoot, hubUrl, toolsDir: resolveToolsDir(flags) },
512
1541
  decisions, secretProvider: makeSecretProvider(secrets),
513
- logger, crypto, env, dryRun, options: { ...installOptions(flags), term: screen },
1542
+ logger, crypto, env, dryRun,
1543
+ options: {
1544
+ ...installOptions(flags, { doctor }), term: screen,
1545
+ runningComfy: mode !== 'managed' ? runningComfy : null,
1546
+ hubUrlExplicit: !!flags['hub-url'],
1547
+ nodeBinary: nodePick,
1548
+ replaceWorkerKey,
1549
+ comfyOwner: instance,
1550
+ comfyWaitMs,
1551
+ nodeClassesDeadline,
1552
+ ownedServices,
1553
+ bundleRefreshedEarly: !!(preflight.bundle && preflight.bundle.status === 'updated'),
1554
+ restartPlatformComfy: restartPlatformComfyDecision(flags, priorState, { boot }).source === 'flag'
1555
+ ? !!flags['restart-platform-comfy']
1556
+ : (depsGate && depsGate.record.restartPlatformComfy !== undefined ? depsGate.record.restartPlatformComfy : undefined),
1557
+ hubVersion,
1558
+ },
514
1559
  });
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;
1560
+ printResult(withPre({ ...result, node_deps_overrides: depsGate ? depsGate.overrides : [] }), { flags, mode, boot, hubVersion });
1561
+ } catch (err) {
1562
+ if (err instanceof NoTerminalError) {
1563
+ console.error('');
1564
+ console.error(err.message);
1565
+ process.exit(3);
528
1566
  }
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);
1567
+ throw err;
1568
+ } finally {
1569
+ prompt.close();
538
1570
  }
539
1571
  }
540
1572
 
541
- function installOptions(flags) {
1573
+ function installOptions(flags, { doctor = false } = {}) {
542
1574
  return {
543
1575
  // Managed mode starts services by default (engine); these flags only
544
1576
  // carry an explicit ON (--start-comfy) or OFF (--no-start-comfy).
@@ -548,8 +1580,17 @@ function installOptions(flags) {
548
1580
  // --start-worker: launch the installed worker (node worker.cjs) as a
549
1581
  // detached daemon after the bundle+.env steps and check it is alive
550
1582
  // 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,
1583
+ // installer never starts background services unprompted) — EXCEPT in
1584
+ // `doctor`, whose job after a node reboot is to bring the worker back.
1585
+ startWorker: flags['start-worker'] === true ? true
1586
+ : flags['no-start-worker'] === true ? false
1587
+ : (doctor ? true : undefined),
1588
+ // Installer 0.2.8: a running worker is restarted only for a changed
1589
+ // .env/bundle and never in the middle of a task (engine/worker
1590
+ // ensureWorker); the boot path only starts a stopped worker.
1591
+ waitJobMs: flags['wait-job-ms'] !== undefined && flags['wait-job-ms'] !== '' ? Number(flags['wait-job-ms']) : undefined,
1592
+ forceWorkerRestart: !!flags.force,
1593
+ boot: isBootRun(flags, doctor),
553
1594
  };
554
1595
  }
555
1596
 
@@ -585,11 +1626,13 @@ async function cmdResume(flags) {
585
1626
  // Resume/state semantics after a UID change: an installation created by
586
1627
  // another user must never be continued under the current one (that is
587
1628
  // how root-owned files end up inside a user's home).
588
- runHostGates(io, {
1629
+ await runHostGates(io, {
589
1630
  paths: [root, statePath, workerDir, resolveToolsDir(flags)].filter(Boolean),
590
1631
  dryRun: false,
591
- deep: true,
592
1632
  venvDir: path.join(root, 'venv'),
1633
+ needVenv: true,
1634
+ prompt: createPrompt(),
1635
+ yes: !!flags.yes,
593
1636
  stateUid: st.owner_uid != null ? st.owner_uid : null,
594
1637
  });
595
1638
 
@@ -768,26 +1811,102 @@ async function cmdVerify(flags) {
768
1811
  console.log(ver.text);
769
1812
  }
770
1813
 
771
- function printResult(result) {
772
- if (result.verification) {
773
- console.log(`\nRESULT: ${result.verification.status}`);
774
- } else {
775
- console.log(`\nRESULT: ${result.status.toUpperCase()}`);
1814
+ /**
1815
+ * Final block of an install/doctor run: warnings, then ONE result section —
1816
+ * either every check ✓ and "Done", or one line of cause + one exact fix
1817
+ * command per ✗ (no "scroll up").
1818
+ */
1819
+ /** Blocked steps + host remediation as summary items (shared by both outputs). */
1820
+ function resultExtras(result, tool) {
1821
+ const extra = preflightExtras(result.preflight);
1822
+ // Version replacements of the node-deps overlay (installer 0.2.6).
1823
+ extra.push(...overridesMod.resultItems(result.node_deps_overrides));
1824
+ for (const b of result.blocked || []) {
1825
+ let fix = result.remediation && result.remediation.command ? `${result.remediation.command} && ${tool} doctor` : `${tool} doctor`;
1826
+ if (/accept_runtime_change/.test(b.reason || '')) fix = `if ComfyUI already works, this can be ignored; to let the installer replace the runtime run: ${tool} doctor --accept-runtime-change`;
1827
+ else if (/accept_reference_runtime/.test(b.reason || '')) fix = `${tool} doctor --accept-reference-runtime`;
1828
+ extra.push({ ok: false, label: `Step "${b.step}"`, detail: b.reason, fix });
1829
+ }
1830
+ if (result.remediation && (result.blocked || []).length === 0) {
1831
+ extra.push({
1832
+ ok: false,
1833
+ label: 'Host prerequisite',
1834
+ detail: `${result.remediation.summary || result.remediation.code}${result.remediation.package ? ` (package ${result.remediation.package})` : ''}`,
1835
+ fix: result.remediation.command ? `${result.remediation.command} && ${tool} doctor` : `${tool} doctor`,
1836
+ });
1837
+ }
1838
+ return extra;
1839
+ }
1840
+
1841
+ /**
1842
+ * Boot script output: EXACTLY one line plus the exit code — a node that
1843
+ * reboots must not need a human to read a 200-line plan, and the one line
1844
+ * must say whether the worker is back. `--yes` means zero questions.
1845
+ */
1846
+ function printOneLineSummary(result, { flags = {}, mode = null } = {}) {
1847
+ const tool = toolCommandPath(flags);
1848
+ const summary = renderFinalSummary({
1849
+ verification: result.verification, e2e: result.e2e || [],
1850
+ extra: resultExtras(result, tool), tool, mode: mode || result.mode,
1851
+ });
1852
+ const owner = result.results && result.results.comfy_owner;
1853
+ const worker = ((result.results && result.results.worker) || []).find((w) => w.id === 'worker-process');
1854
+ const what = [
1855
+ `mode ${mode || result.mode}`,
1856
+ owner && owner.url ? `ComfyUI ${owner.url}` : 'ComfyUI not reachable',
1857
+ worker && worker.started ? `worker pid ${worker.pid}${worker.action === 'left' ? ' (left as is)' : ''}` : 'worker not started',
1858
+ `current job: ${currentJobOf(result, flags)}`,
1859
+ ].join(', ');
1860
+ const head = summary.ok ? 'OK' : `FAILED — ${summary.failures.length} problem(s)`;
1861
+ console.log(`animastor doctor: ${head} — ${what} (${tool})`);
1862
+ if (!summary.ok) {
1863
+ for (const f of summary.failures) console.log(` ✗ ${f.label}: ${f.detail || ''}${f.fix ? ` — fix: ${f.fix}` : ''}`);
1864
+ process.exitCode = 1;
1865
+ }
1866
+ }
1867
+
1868
+ /** "none" | "<job_id>" | "unknown" — the worker's task at the end of the run (installer 0.2.8). */
1869
+ function currentJobOf(result, flags = {}) {
1870
+ const known = result && result.results && result.results.current_job;
1871
+ if (known) return known;
1872
+ // The engine did not run (e.g. the platform's ComfyUI never came up):
1873
+ // read the running worker's log directly.
1874
+ try {
1875
+ return workerMod.currentJobLabel(createRealIo(), { workerDir: resolveWorkerDir(flags), platformAdapter: PLATFORM_ADAPTER });
1876
+ } catch (_) {
1877
+ return 'unknown';
1878
+ }
1879
+ }
1880
+
1881
+ function printResult(result, { flags = {}, mode = null, boot = false } = {}) {
1882
+ if (boot) {
1883
+ printOneLineSummary(result, { flags, mode });
1884
+ return;
776
1885
  }
777
1886
  if (result.warnings.length > 0) {
778
1887
  console.log('\nWarnings:');
779
1888
  for (const w of result.warnings) console.log(` ! ${w}`);
780
1889
  }
1890
+ const tool = (result.results && result.results.management_tools && result.results.management_tools.command) || toolCommand(flags);
1891
+ const extra = resultExtras(result, tool);
1892
+ const summary = renderFinalSummary({ verification: result.verification, e2e: result.e2e || [], extra, tool, mode: mode || result.mode });
1893
+ console.log(summary.text);
1894
+ console.log(`current job: ${currentJobOf(result, flags)}`);
1895
+ // The full path is printed even when ~/.local/bin is already in PATH:
1896
+ // after a node reboot the PATH block is gone, and a copy-pasted relative
1897
+ // `animastor` must not be the only way to run the command.
1898
+ console.log(`\nAnimastor command: ${toolCommandPath(flags)}`);
1899
+ // The node startup script is this ONE line on both node types (0.2.4).
1900
+ console.log(`Node startup script (one line): ${startupScriptLine(flags)}`);
781
1901
  // A failed/blocked installation must be visible in the exit code so
782
1902
  // 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
- }
1903
+ if (!summary.ok || result.status === 'failed' || result.status === 'blocked') process.exitCode = 1;
1904
+ }
1905
+
1906
+ /** Result block for a plan that is blocked before anything ran. */
1907
+ function printFinal({ blocked = [], tool = 'animastor', mode = null, preflight = null }) {
1908
+ const extra = [...preflightExtras(preflight), ...blocked.map((b) => ({ ok: false, label: `Step "${b.step || b.id || 'plan'}"`, detail: b.reason, fix: `${tool} doctor` }))];
1909
+ console.log(renderFinalSummary({ extra, tool, mode }).text);
791
1910
  }
792
1911
 
793
1912
  /**
@@ -991,6 +2110,124 @@ async function cmdRebootComfyUI(flags) {
991
2110
  }
992
2111
  }
993
2112
 
2113
+ // ---------------------------------------------------------------------------
2114
+ // animastor start | stop | logs | doctor
2115
+ // ---------------------------------------------------------------------------
2116
+
2117
+ /** True when this installation owns its ComfyUI (managed mode). */
2118
+ function ownsComfyUI(targets) {
2119
+ const st = targets.state;
2120
+ return !!(st && ((st.components && st.components.comfyui && st.components.comfyui.owned) || st.mode === 'managed'));
2121
+ }
2122
+
2123
+ /**
2124
+ * animastor start — bring the installation up and PROVE it: the managed
2125
+ * ComfyUI (never the user's own), then the worker; READY only after the
2126
+ * worker logged "ComfyUI ready" and the hub confirmed the heartbeat.
2127
+ */
2128
+ async function cmdStart(flags) {
2129
+ const io = createRealIo();
2130
+ const targets = managementTargetsOrExit(io, flags, 'Animastor start');
2131
+ if (!targets) return;
2132
+ if (!guardManagementAccess(io, targets)) return;
2133
+ const screen = createScreen();
2134
+ // PATH is re-applied on EVERY start: E2E nodes reset ~/.bashrc and
2135
+ // ~/.profile on boot while ~/.local/bin/animastor survives.
2136
+ const pathEntry = management.restoreCommandPath(io, { linkDir: management.defaultLinkDir(), home: homeDir() });
2137
+ if (pathEntry.updated.length > 0) screen.print(`PATH block restored: ${pathEntry.updated.join(', ')}`);
2138
+ const envVals = workerMod.readEnvValues(io, targets.workerDir);
2139
+ // ComfyUI: mode and address come from the MACHINE (comfy-owner), not from
2140
+ // the remembered .env — the platform's port/prefix change between boots.
2141
+ const instance = await comfyOwner.resolveComfyOwner(io, { state: targets.state, root: targets.comfyuiRoot });
2142
+ const managed = instance.mode === 'managed';
2143
+ const port = instance.port || targets.port || Number(envVals.COMFY_PORT) || 8188;
2144
+ let comfyUrl = instance.url || envVals.COMFY_URL || `http://127.0.0.1:${port}`;
2145
+ let stats = instance.present ? await comfyuiMod.systemStats(io, comfyUrl) : null;
2146
+ if (!stats && managed && targets.comfyuiRoot && io.fs.existsSync(targets.comfyuiRoot)) {
2147
+ await screen.withBusy('Starting ComfyUI', async () => {
2148
+ comfyuiMod.startComfyUI(io, { root: targets.comfyuiRoot, port, device: targets.device });
2149
+ const up = await comfyuiMod.waitForApi(io, `http://127.0.0.1:${port}`, { timeoutMs: flags['verify-timeout-ms'] ? Number(flags['verify-timeout-ms']) : 120000 });
2150
+ if (up.ok) comfyUrl = `http://127.0.0.1:${port}`;
2151
+ });
2152
+ stats = await comfyuiMod.systemStats(io, comfyUrl);
2153
+ }
2154
+ if (!stats && instance.owner === 'foreign') {
2155
+ screen.print(`! the platform's ComfyUI (pid ${instance.pid}) does not answer at ${comfyUrl} yet`);
2156
+ }
2157
+ // Autostart entry kept in sync with the current command (old script → .bak).
2158
+ const wrap = management.ensureStartWorkerWrapper(io, { workerDir: targets.workerDir, animastorPath: toolCommandPath(flags) });
2159
+ if (wrap.status === 'replaced' || wrap.status === 'created') {
2160
+ screen.print(`autostart: ${wrap.path} → animastor start${wrap.backup ? ` (old script: ${wrap.backup})` : ''}`);
2161
+ }
2162
+ let start = null;
2163
+ let ready = null;
2164
+ if (stats) {
2165
+ start = workerMod.startWorker(io, { workerDir: targets.workerDir });
2166
+ if (start.started && start.alive) {
2167
+ if (start.already_running) {
2168
+ screen.print(start.busy_job
2169
+ ? `worker already running (pid ${start.pid}), busy with ${start.busy_job} — its .env changed, restart deferred until the task finishes (run \`${toolCommand(flags)} doctor\`)`
2170
+ : `worker already running (pid ${start.pid})`);
2171
+ }
2172
+ ready = await screen.withBusy('Waiting for the worker (ComfyUI ready → hub heartbeat)', () => workerMod.waitForWorkerReady(io, {
2173
+ workerDir: targets.workerDir, pid: start.pid, logFile: start.logFile, logOffset: start.logOffset || 0,
2174
+ }));
2175
+ }
2176
+ }
2177
+ const checks = await engineMod.endToEndChecks(io, {
2178
+ mode: managed ? 'managed' : 'existing', comfyUrl: stats ? comfyUrl : null, comfyPort: port,
2179
+ hubUrl: envVals.HUB_URL || resolveHubUrl(flags), workerWanted: !!stats, workerStart: start, workerReady: ready,
2180
+ tool: toolCommand(flags),
2181
+ });
2182
+ const summary = renderFinalSummary({ e2e: checks, tool: toolCommand(flags), mode: managed ? 'managed' : 'existing' });
2183
+ for (const line of summary.text.split('\n')) screen.print(line);
2184
+ screen.print(`\nAnimastor command: ${toolCommandPath(flags)}`);
2185
+ process.exitCode = summary.ok ? 0 : 1;
2186
+ }
2187
+
2188
+ /** animastor stop — stop this installation's worker (and its managed ComfyUI; never the user's own). */
2189
+ async function cmdStop(flags) {
2190
+ const io = createRealIo();
2191
+ const targets = managementTargetsOrExit(io, flags, 'Animastor stop');
2192
+ if (!targets) return;
2193
+ if (!guardManagementAccess(io, targets)) return;
2194
+ const w = await workerMod.stopManagedWorker(io, { workerDir: targets.workerDir });
2195
+ console.log(w.stopped ? `✓ worker stopped (pid ${w.pid})` : `· worker: ${w.reason}`);
2196
+ if (ownsComfyUI(targets) && targets.comfyuiRoot) {
2197
+ const pids = comfyuiMod.findManagedComfyUIPids(io, { root: targets.comfyuiRoot });
2198
+ for (const pid of pids) {
2199
+ try { process.kill(pid, 'SIGTERM'); console.log(`✓ ComfyUI stopped (pid ${pid})`); } catch (_) { /* gone */ }
2200
+ }
2201
+ if (pids.length === 0) console.log('· ComfyUI: not running');
2202
+ } else {
2203
+ console.log('· ComfyUI: not managed by Animastor — left running');
2204
+ }
2205
+ }
2206
+
2207
+ /** animastor logs [-f] [--lines N] — the worker log of this installation. */
2208
+ async function cmdLogs(flags) {
2209
+ const io = createRealIo();
2210
+ const targets = managementTargetsOrExit(io, flags, 'Animastor logs');
2211
+ if (!targets) return;
2212
+ const file = workerMod.workerLogPath(targets.workerDir);
2213
+ if (!fs.existsSync(file)) {
2214
+ console.log(`no worker log yet (${file}) — start the worker: ${toolCommand(flags)} start`);
2215
+ process.exitCode = 1;
2216
+ return;
2217
+ }
2218
+ const n = String(Number(flags.lines) > 0 ? Number(flags.lines) : 100);
2219
+ console.error(`==> ${file}`);
2220
+ const { spawn } = require('child_process');
2221
+ await new Promise((resolve) => {
2222
+ const child = spawn('tail', flags.follow ? ['-n', n, '-F', file] : ['-n', n, file], { stdio: 'inherit' });
2223
+ child.on('close', (code) => { process.exitCode = code || 0; resolve(); });
2224
+ });
2225
+ }
2226
+
2227
+ async function cmdDoctor(flags) {
2228
+ return cmdInstall(flags, { doctor: true });
2229
+ }
2230
+
994
2231
  // ---------------------------------------------------------------------------
995
2232
  // Main
996
2233
  // ---------------------------------------------------------------------------
@@ -998,9 +2235,35 @@ async function cmdRebootComfyUI(flags) {
998
2235
  async function main() {
999
2236
  const args = parseArgs(process.argv);
1000
2237
  const pkg = require('../../package.json');
1001
- console.log(`animastor-installer v${pkg.version} (platform: ${PLATFORM_RUNTIME.platform}, deployment: ${PLATFORM_RUNTIME.deployment})`);
2238
+ // A command line this version does not understand is never "best
2239
+ // effort": an ignored option silently changes what the run does.
2240
+ if (args.errors.length > 0) {
2241
+ for (const e of args.errors) console.error(`animastor-installer ${pkg.version}: ${e}`);
2242
+ console.error(`Run with --help for the list of commands and options (this is installer ${pkg.version}).`);
2243
+ process.exit(USAGE_EXIT);
2244
+ }
2245
+ if (args.flags.help) args.command = null;
2246
+ // install/doctor print the full banner; the everyday tool commands stay quiet.
2247
+ if (!['install', 'doctor', 'start', 'stop', 'logs', 'status', 'boot'].includes(args.command)) {
2248
+ console.log(`animastor-installer v${pkg.version} (platform: ${PLATFORM_RUNTIME.platform}, deployment: ${PLATFORM_RUNTIME.deployment})`);
2249
+ }
1002
2250
  printPlatformNotices();
1003
2251
  switch (args.command) {
2252
+ case 'start':
2253
+ await cmdStart(args.flags);
2254
+ break;
2255
+ case 'stop':
2256
+ await cmdStop(args.flags);
2257
+ break;
2258
+ case 'logs':
2259
+ await cmdLogs(args.flags);
2260
+ break;
2261
+ case 'doctor':
2262
+ await cmdDoctor(args.flags);
2263
+ break;
2264
+ case 'boot':
2265
+ cmdBoot(args.flags);
2266
+ break;
1004
2267
  case 'detect':
1005
2268
  await cmdDetect(args.flags);
1006
2269
  break;
@@ -1035,7 +2298,7 @@ async function main() {
1035
2298
  await cmdRebootComfyUI(args.flags);
1036
2299
  break;
1037
2300
  default:
1038
- console.error('Usage: animastor-installer <detect|plan|install|verify|validate|resume|uninstall|status|monitor|reboot-worker|reboot-comfyui> [options]');
2301
+ console.error('Usage: animastor-installer <detect|plan|install|verify|validate|resume|uninstall|start|stop|status|logs|doctor|boot|monitor|reboot-worker|reboot-comfyui> [options]');
1039
2302
  console.error(' --profile P[,P2] Generation profile id');
1040
2303
  console.error(' --mode MODE managed | existing | shared');
1041
2304
  console.error(' --root PATH ComfyUI root (default: ~/ComfyUI)');
@@ -1046,14 +2309,18 @@ async function main() {
1046
2309
  console.error(' managed mode starts ComfyUI + worker automatically and picks');
1047
2310
  console.error(' a free port when 8188 is taken; opt out:');
1048
2311
  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');
2312
+ console.error(' management (the `animastor` command in PATH):');
2313
+ console.error(' animastor start | stop | status | logs [-f] | doctor [--new-key] [--wait-job-ms N] [--force] | boot');
2314
+ console.error(' boot: node startup script — detaches `doctor --yes` (log ~/animastor/logs/bootstrap.log), exits 0');
2315
+ console.error(' --restart-platform-comfy / --no-restart-platform-comfy restart the platform ComfyUI after node deps');
2316
+ console.error(' --accept-node-deps-overrides consent: the node-deps overlay may replace a package another profile / ComfyUI core uses');
2317
+ console.error(' (also: monitor | reboot-worker | reboot-comfyui)');
1051
2318
  console.error(' (--state/--root/--worker-dir/--port override discovery)');
1052
2319
  console.error(' installer flags: --install-tools / --no-tools / --tools-dir PATH');
1053
2320
  console.error(' uninstall flags:');
1054
2321
  console.error(' --all Full uninstall (remove everything recorded as installed by Animastor)');
1055
2322
  console.error(' --state PATH Install state file path');
1056
- process.exit(1);
2323
+ process.exit(args.flags.help ? 0 : 1);
1057
2324
  }
1058
2325
  }
1059
2326
 
@@ -1064,4 +2331,16 @@ if (require.main === module) {
1064
2331
  });
1065
2332
  }
1066
2333
 
1067
- module.exports = { parseArgs, cmdDetect, cmdPlan, cmdInstall, cmdVerify, cmdValidateManifests, cmdResume, cmdUninstall, cmdStatus, cmdMonitor, cmdRebootWorker, cmdRebootComfyUI, resolveAndPlan, makeSecretProvider, resolveToolsDecision, resolveToolsDir, PLATFORM_RUNTIME, printPlatformNotices, homeDir };
2334
+ module.exports = {
2335
+ stepQuestion, parseArgs, BOOLEAN_FLAGS, VALUE_FLAGS, COMMANDS, USAGE_EXIT, cmdDetect, cmdPlan, cmdInstall, cmdStart, cmdStop, cmdLogs, cmdDoctor,
2336
+ printResult, printOneLineSummary, resultExtras, cmdVerify, cmdValidateManifests, cmdResume,
2337
+ cmdUninstall, cmdStatus, cmdMonitor, cmdRebootWorker, cmdRebootComfyUI, resolveAndPlan,
2338
+ makeSecretProvider, resolveToolsDecision, resolveToolsDir, installOptions, runHostGates,
2339
+ PLATFORM_RUNTIME, printPlatformNotices, homeDir,
2340
+ toolCommand, toolCommandPath, detectHubVersion, priorReusableDecisions, isBootRun,
2341
+ missingRequiredHostPackages, shouldWaitForPlatformComfy, platformComfyGate, platformComfyMissingResult,
2342
+ restartPlatformComfyDecision, platformNodeDepsGate, nodeDepsFailedResult, recordInstallerOption,
2343
+ cmdBoot, bootChildArgs, bootLogPath, startupScriptLine,
2344
+ preflightSelfUpdate, preflightExtras, installedToolsVersion, ownVersion,
2345
+ nodeDepsOwnedServices, recordOwnedServices, otherProfileManifests, overridesStep,
2346
+ };