@animastor/installer 0.1.1 → 0.2.4

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.
@@ -77,11 +77,40 @@ function entryLabel(e) {
77
77
  }
78
78
  }
79
79
 
80
+ /** Human size (GiB/MiB) or null. */
81
+ function fmtBytes(n) {
82
+ if (typeof n !== 'number' || !(n > 0)) return null;
83
+ if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GiB`;
84
+ return `${Math.max(1, Math.round(n / 1024 ** 2))} MiB`;
85
+ }
86
+
87
+ /**
88
+ * Why a model is listed as missing and how much will be downloaded — the
89
+ * plan shows ONLY what is really absent (an incomplete repo names its
90
+ * missing files; files on disk are never re-downloaded).
91
+ */
92
+ function modelMissingDetail(e) {
93
+ const size = fmtBytes(e.missing_bytes_approx);
94
+ if (e.reason === 'incomplete' && Array.isArray(e.missing_files)) {
95
+ const files = e.missing_files.length > 3
96
+ ? `${e.missing_files.slice(0, 3).join(', ')} +${e.missing_files.length - 3} more`
97
+ : e.missing_files.join(', ');
98
+ return `incomplete — missing ${files}${size ? ` (≈ ${size})` : ' (size unknown)'}`;
99
+ }
100
+ return `not found${size ? ` (≈ ${size} download)` : ''}`;
101
+ }
102
+
80
103
  function actionLine(e) {
81
104
  switch (e.kind) {
82
105
  case 'custom_node': return `Install custom node ${e.name || e.id}`;
83
106
  case 'model':
84
- case 'model_repo': return `Download model ${e.name || e.id}`;
107
+ case 'model_repo': {
108
+ const size = fmtBytes(e.missing_bytes_approx);
109
+ if (e.reason === 'incomplete' && Array.isArray(e.missing_files)) {
110
+ return `Download ${e.missing_files.length} missing file(s) of ${e.name || e.id}${size ? ` (≈ ${size})` : ''}`;
111
+ }
112
+ return `Download model ${e.name || e.id}${size ? ` (≈ ${size})` : ''}`;
113
+ }
85
114
  case 'workflow': return `Download optional profile workflow ${e.name || e.id}`;
86
115
  case 'worker': return `Install Animastor worker bundle (${e.worker_type})`;
87
116
  case 'runtime': return `Install ${RUNTIME_LABELS[e.component] || e.component}`;
@@ -384,15 +413,21 @@ function buildWorkerSteps({ report, manifests, decisions }) {
384
413
  const manifest = manifests.find((m) => `worker:${m.profile.id}` === e.id);
385
414
  const wbEnv = (manifest && manifest.worker_bundle && manifest.worker_bundle.env) || {};
386
415
  const secrets = wbEnv.secrets || ['ANIMASTOR_WORKER_TOKEN'];
387
- // for a missing bundle the whole .env is absent → every secret is missing
388
- const missingHere = e.action === 'configure' && e.env ? e.env.missing_required : (wbEnv.required || secrets);
416
+ // The worker entry carries the REAL .env state (present / which keys
417
+ // are set) — "bundle missing" no longer implies ".env missing", which
418
+ // is what made a re-install ask for the Worker Key again.
419
+ const missingHere = e.env ? e.env.missing_required : (wbEnv.required || secrets);
389
420
  for (const k of missingHere) {
390
421
  if (secrets.includes(k) && !secretMissing.includes(k)) secretMissing.push(k);
391
422
  }
392
423
  }
393
424
 
425
+ // A Worker Key is asked for ONLY when it is genuinely missing from .env.
426
+ // A .env that merely needs extra (non-secret) keys is updated by
427
+ // configureEnv — a re-install over an already configured worker must
428
+ // never ask for the key again (E2E regression of 2026-10-30).
394
429
  let key = null;
395
- if (secretMissing.length > 0 || toConfigure.length > 0) {
430
+ if (secretMissing.length > 0) {
396
431
  key = {
397
432
  id: 'worker-key',
398
433
  title: 'Enter Worker Key securely',
@@ -603,11 +638,20 @@ function buildInstallPlan({ report, manifests = [], decisions = {} }) {
603
638
  // Rendering
604
639
  // ---------------------------------------------------------------------------
605
640
 
606
- function renderPlanText(plan, report) {
641
+ /**
642
+ * @param {object} [opts]
643
+ * @param {boolean} [opts.questions=true] render the pending questions at the
644
+ * end (the non-interactive `plan` command). The interactive installer asks
645
+ * them itself — printing them here too was the "double menu".
646
+ * @param {boolean} [opts.header=true] Profile/Mode header lines.
647
+ */
648
+ function renderPlanText(plan, report, { questions = true, header = true } = {}) {
607
649
  const lines = [];
608
- lines.push(`Profile: ${plan.profiles.join(' + ')}`);
609
- lines.push(`Mode: ${plan.mode}`);
610
- lines.push('');
650
+ if (header) {
651
+ lines.push(`Profile: ${plan.profiles.join(' + ')}`);
652
+ lines.push(`Mode: ${plan.mode}`);
653
+ lines.push('');
654
+ }
611
655
 
612
656
  const hw = report.hardware || {};
613
657
  if (hw.device === 'cpu') {
@@ -639,7 +683,8 @@ function renderPlanText(plan, report) {
639
683
  } else if (e.kind === 'worker') {
640
684
  detected.push(`\u2713 ${entryLabel(e)}`);
641
685
  } else if (e.kind === 'model' || e.kind === 'model_repo') {
642
- detected.push(`\u2713 ${entryLabel(e)}`);
686
+ const loc = e.found && e.found.location ? ` (${e.found.location.base}, extra_model_paths.yaml)` : '';
687
+ detected.push(`\u2713 ${entryLabel(e)}${loc}`);
643
688
  }
644
689
  }
645
690
  if (detected.length > 0) {
@@ -654,7 +699,10 @@ function renderPlanText(plan, report) {
654
699
  const missing = report.entries.filter((e) => e.status === 'missing' && e.kind !== 'workflow');
655
700
  if (missing.length > 0) {
656
701
  lines.push('Missing:');
657
- for (const e of missing) lines.push(`\u2717 ${entryLabel(e)}`);
702
+ for (const e of missing) {
703
+ const detail = (e.kind === 'model' || e.kind === 'model_repo') ? ` — ${modelMissingDetail(e)}` : '';
704
+ lines.push(`\u2717 ${entryLabel(e)}${detail}`);
705
+ }
658
706
  lines.push('');
659
707
  }
660
708
 
@@ -684,10 +732,14 @@ function renderPlanText(plan, report) {
684
732
  lines.push('');
685
733
  }
686
734
 
687
- // Download size summary
688
- const modelsStep = plan.steps.find((s) => s.id === 'models');
689
- if (modelsStep && modelsStep.estimated_bytes) {
690
- const est = modelsStep.estimated_bytes;
735
+ // Download size summary — what will REALLY be downloaded: the missing
736
+ // files of incomplete repos, the full size only for absent models.
737
+ const toDownload = report.entries.filter((e) => (e.kind === 'model' || e.kind === 'model_repo') && e.status === 'missing' && e.action === 'install');
738
+ if (toDownload.length > 0) {
739
+ const est = {
740
+ total_bytes: toDownload.reduce((a, e) => a + (typeof e.missing_bytes_approx === 'number' ? e.missing_bytes_approx : 0), 0),
741
+ unknown_count: toDownload.filter((e) => typeof e.missing_bytes_approx !== 'number').length,
742
+ };
691
743
  if (est.total_bytes > 0 || est.unknown_count > 0) {
692
744
  lines.push('Download size:');
693
745
  if (est.total_bytes > 0) lines.push(` ${formatBytes(est.total_bytes)}`);
@@ -719,7 +771,9 @@ function renderPlanText(plan, report) {
719
771
  }
720
772
 
721
773
  const prompts = plan.steps.filter((s) => s.prompt && s.awaiting_decision);
722
- if (prompts.length > 0) {
774
+ if (!questions) {
775
+ // the caller asks the questions interactively
776
+ } else if (prompts.length > 0) {
723
777
  for (const p of prompts) {
724
778
  lines.push(p.prompt.question);
725
779
  lines.push(`[${p.prompt.options.join('] [')}]`);
@@ -733,9 +787,39 @@ function renderPlanText(plan, report) {
733
787
  return lines.join('\n').trim();
734
788
  }
735
789
 
790
+ /**
791
+ * Does this plan ACTUALLY use the Python runtime (i.e. create/install into
792
+ * the ComfyUI venv)? Host prerequisites must only be checked — and missing
793
+ * apt packages only be required — when the plan needs them:
794
+ *
795
+ * - ComfyUI install/update/downgrade → venv + pip;
796
+ * - custom-node install → pip into the venv;
797
+ * - runtime:python / runtime:torch missing or
798
+ * incompatible (the engine prepares a venv) → venv + pip;
799
+ *
800
+ * In `existing` mode with the user's ComfyUI already working and every model
801
+ * and node present, no step touches Python — so a missing python3.X-venv
802
+ * must neither block nor be installed for nothing.
803
+ *
804
+ * Unknown shape (no plan) returns true: the historical, safe behaviour.
805
+ */
806
+ function planNeedsPythonRuntime({ plan, report = null } = {}) {
807
+ if (!plan || !Array.isArray(plan.steps)) return true;
808
+ const ops = new Set(plan.steps.map((s) => (s && s.action && s.action.op) || null).filter(Boolean));
809
+ if (ops.has('install_comfyui') || ops.has('update_comfyui') || ops.has('downgrade_comfyui')) return true;
810
+ if (ops.has('install_custom-nodes')) return true; // pip into the venv
811
+ if (report && Array.isArray(report.entries)) {
812
+ const runtime = ['runtime:python', 'runtime:torch']
813
+ .map((id) => report.entries.find((e) => e && e.id === id));
814
+ if (runtime.some((e) => e && (e.status === 'missing' || e.status === 'incompatible'))) return true;
815
+ }
816
+ return false;
817
+ }
818
+
736
819
  module.exports = {
737
820
  FLOW_STEPS,
738
821
  buildInstallPlan,
739
822
  renderPlanText,
823
+ planNeedsPythonRuntime,
740
824
  entryLabel,
741
825
  };
@@ -38,6 +38,7 @@ const comfyui = require('./engine/comfyui');
38
38
  const workerMod = require('./engine/worker');
39
39
  const stateMod = require('./engine/state');
40
40
  const prereq = require('./engine/prereq');
41
+ const comfyOwner = require('./engine/comfy-owner');
41
42
 
42
43
  /** Adapter for one call (explicit override wins over auto-detect). */
43
44
  function adapterOf(opts = {}) {
@@ -139,8 +140,36 @@ async function collectStatus(io, targets, opts = {}) {
139
140
  if (comfyPids.length > 0) {
140
141
  port = readPidPort(io, comfyPids[0], { platformAdapter: adapter }) || port;
141
142
  }
142
- const baseUrl = port ? `http://127.0.0.1:${port}` : null;
143
+ // existing/shared mode: the ComfyUI is the user's own (not discoverable
144
+ // as "ours") — its API is the COMFY_URL the installer probed into .env.
145
+ const external = !!(targets.state && targets.state.mode && targets.state.mode !== 'managed');
146
+ const envVals = targets.workerDir ? workerMod.readEnvValues(io, targets.workerDir) : {};
147
+ let baseUrl = port ? `http://127.0.0.1:${port}` : null;
148
+ if (external && envVals.COMFY_URL) baseUrl = envVals.COMFY_URL;
149
+ // Who started the ComfyUI (installer 0.2.3): a running main.py the
150
+ // installer did not start is the PLATFORM's — its address comes from its
151
+ // own cmdline (port/prefix change between boots), not from .env.
152
+ let foreign = null;
153
+ if (external) {
154
+ try {
155
+ const procs = await comfyOwner.inspectComfyInstances(io, { state: targets.state });
156
+ foreign = procs.find((p) => !p.ours && p.verified) || procs.find((p) => !p.ours) || null;
157
+ } catch (_) { foreign = null; }
158
+ if (foreign && foreign.verified) baseUrl = foreign.url;
159
+ }
160
+ const startedBy = !external ? 'installer'
161
+ : foreign ? 'platform'
162
+ : comfyOwner.platformOwnedByRecord(targets.state) && targets.state.comfy_owner ? 'platform' : 'user';
143
163
  const stats = baseUrl ? await comfyui.systemStats(io, baseUrl) : null;
164
+ // Hub heartbeat as the worker itself reports it (its log).
165
+ let hub = null;
166
+ if (workerPid && targets.workerDir) {
167
+ const logFile = workerMod.workerLogPath(targets.workerDir);
168
+ if (io.fs.existsSync(logFile)) {
169
+ const scan = workerMod.scanWorkerLog(String(io.fs.readFileSync(logFile, 'utf8')));
170
+ hub = { heartbeat: scan.heartbeat, comfy_ready: scan.comfy_ready, last_error: scan.last_beacon_error || scan.last_comfy_error || null };
171
+ }
172
+ }
144
173
  let queue = null;
145
174
  if (stats && baseUrl) {
146
175
  try {
@@ -155,9 +184,13 @@ async function collectStatus(io, targets, opts = {}) {
155
184
  }
156
185
  return {
157
186
  worker: { running: !!workerPid, pid: workerPid || null },
158
- comfyui: { running: comfyPids.length > 0, root_present: comfyRootPresent, port, pids: comfyPids },
187
+ comfyui: {
188
+ running: comfyPids.length > 0, root_present: comfyRootPresent, port, pids: comfyPids, external, url: baseUrl,
189
+ started_by: startedBy, foreign_pid: foreign ? foreign.pid : null,
190
+ },
159
191
  api: { ok: !!stats },
160
192
  queue,
193
+ hub,
161
194
  };
162
195
  }
163
196
 
@@ -169,21 +202,37 @@ function renderStatus(snapshot) {
169
202
  lines.push('Animastor status');
170
203
  lines.push('');
171
204
  lines.push(`Worker: ${snapshot.worker.running ? `${ok} RUNNING` : `${bad} STOPPED`}`);
172
- lines.push(`ComfyUI: ${snapshot.comfyui.running
173
- ? `${ok} RUNNING${snapshot.comfyui.port ? ` :${snapshot.comfyui.port}` : ''}`
174
- : `${bad} STOPPED`}`);
205
+ if (snapshot.comfyui.external) {
206
+ const c = snapshot.comfyui;
207
+ const state = snapshot.api.ok ? `${ok} RUNNING` : `${bad} UNREACHABLE`;
208
+ if (c.started_by === 'platform') {
209
+ const pid = c.foreign_pid ? `pid ${c.foreign_pid}` : 'no process running';
210
+ lines.push(`ComfyUI: ${state} — started by the platform (${pid})${c.url ? `, ${c.url}` : ''}`);
211
+ } else {
212
+ lines.push(`ComfyUI: ${state} (your own${c.url ? `, ${c.url}` : ''})`);
213
+ }
214
+ } else {
215
+ lines.push(`ComfyUI: ${snapshot.comfyui.running
216
+ ? `${ok} RUNNING${snapshot.comfyui.port ? ` :${snapshot.comfyui.port}` : ''}`
217
+ : `${bad} STOPPED`}`);
218
+ }
175
219
  lines.push(`API: ${snapshot.api.ok ? `${ok} OK` : `${bad} UNREACHABLE`}`);
176
220
  if (snapshot.queue) {
177
221
  lines.push(`Queue: ${snapshot.queue.running} running / ${snapshot.queue.pending} pending`);
178
222
  } else {
179
223
  lines.push('Queue: — (API unreachable)');
180
224
  }
225
+ if (snapshot.hub) {
226
+ lines.push(`Hub: ${snapshot.hub.heartbeat ? `${ok} ONLINE (heartbeat accepted)` : `${bad} no heartbeat${snapshot.hub.last_error ? ` — ${snapshot.hub.last_error}` : (snapshot.hub.comfy_ready ? '' : ' — worker has not reached ComfyUI')}`}`);
227
+ }
181
228
  return lines.join('\n');
182
229
  }
183
230
 
184
231
  /** Exit code for a status snapshot: 0 healthy, 1 degraded. */
185
232
  function statusExitCode(snapshot) {
186
- return snapshot.worker.running && snapshot.comfyui.running && snapshot.api.ok ? 0 : 1;
233
+ const comfyOk = snapshot.comfyui.running || (snapshot.comfyui.external && snapshot.api.ok);
234
+ const hubOk = !snapshot.hub || snapshot.hub.heartbeat;
235
+ return snapshot.worker.running && comfyOk && snapshot.api.ok && hubOk ? 0 : 1;
187
236
  }
188
237
 
189
238
  // ---------------------------------------------------------------------------
@@ -447,28 +496,292 @@ function renderToolScript({ command, nodePath, cliPath, statePath, root, workerD
447
496
  return adapterOf({ platformAdapter }).renderToolScript({ command, nodePath, cliPath, statePath, root, workerDir });
448
497
  }
449
498
 
499
+ /**
500
+ * Where the `animastor` command is linked: ALWAYS ~/.local/bin (XDG user
501
+ * bin, created when missing) — root included. E2E nodes only keep /home
502
+ * across a reboot, so a /usr/local/bin link would vanish while the
503
+ * installation in $HOME survived; the command must survive with it.
504
+ * `uid` stays in the signature because callers/tests pass it.
505
+ */
506
+ function defaultLinkDir({ uid = prereq.currentUid(), home = prereq.currentHome() } = {}) {
507
+ if (!home) return null;
508
+ return path.join(home, '.local', 'bin');
509
+ }
510
+
511
+ // ---------------------------------------------------------------------------
512
+ // PATH persistence
513
+ // ---------------------------------------------------------------------------
514
+
515
+ /** Marker line of the PATH block this installer appends to shell rc files. */
516
+ const PATH_MARKER = '# animastor: PATH for the `animastor` command (added by animastor-installer)';
517
+
518
+ /**
519
+ * Make `dir` reachable in EVERY future login shell: append an idempotent
520
+ * PATH block to ~/.bashrc and ~/.profile when the directory is not there
521
+ * yet. The block keeps the current PATH intact and is added once — re-runs
522
+ * of the installer never duplicate it. Necessary because the link dir is
523
+ * ~/.local/bin (also for root) and many non-login shells skip it.
524
+ * @returns {{ dir: string|null, updated: string[], already: string[] }}
525
+ */
526
+ function ensurePathEntry(io, { dir, home = null, files = ['.bashrc', '.profile'] } = {}) {
527
+ if (!dir || !home) return { dir: dir || null, updated: [], already: [] };
528
+ const block = [
529
+ PATH_MARKER,
530
+ `case ":$PATH:" in *":${dir}:"*) ;; *) export PATH="${dir}:$PATH" ;; esac`,
531
+ '',
532
+ ].join('\n');
533
+ const updated = [];
534
+ const already = [];
535
+ for (const name of files) {
536
+ const file = path.join(home, name);
537
+ let text = '';
538
+ try { text = io.fs.existsSync(file) ? String(io.fs.readFileSync(file, 'utf8')) : ''; } catch (_) { text = ''; }
539
+ const present = text.includes(PATH_MARKER)
540
+ || text.split('\n').some((line) => line.includes(dir) && /\bPATH\b/.test(line));
541
+ if (present) { already.push(file); continue; }
542
+ try {
543
+ io.fs.mkdirSync(path.dirname(file), { recursive: true });
544
+ const prefix = text && !text.endsWith('\n') ? '\n' : '';
545
+ io.fs.writeFileSync(file, `${text}${prefix}${block}`);
546
+ updated.push(file);
547
+ } catch (_) { /* best effort — the hint below still tells the user */ }
548
+ }
549
+ return { dir, updated, already };
550
+ }
551
+
552
+ function shQuote(v) {
553
+ return `'${String(v).replace(/'/g, `'\\''`)}'`;
554
+ }
555
+
556
+ /**
557
+ * The `animastor` command (Linux): ONE entry point for the management
558
+ * subcommands — start | stop | status | logs | doctor (+ monitor,
559
+ * reboot-worker, reboot-comfyui). A thin shim: every behaviour lives in the
560
+ * persistent installer CLI; the recorded paths of THIS installation are
561
+ * injected so the command works from any directory.
562
+ */
563
+ function renderAnimastorCommand({ nodePath, cliPath, statePath, root, workerDir, hubUrl }) {
564
+ return [
565
+ '#!/bin/sh',
566
+ '# animastor — Animastor GPU worker management (generated by animastor-installer).',
567
+ '# Usage: animastor start | stop | status | logs [-f] | doctor [--new-key] | boot',
568
+ '# Do not edit: re-run the installer (or `animastor doctor`) to refresh.',
569
+ 'cmd="${1:-status}"',
570
+ '[ $# -gt 0 ] && shift',
571
+ 'case "$cmd" in',
572
+ ' -h|--help|help) echo "usage: animastor start | stop | status | logs [-f] | doctor [--new-key] | boot"; exit 0 ;;',
573
+ 'esac',
574
+ `exec ${shQuote(nodePath)} ${shQuote(cliPath)} "$cmd" \\`,
575
+ ` --state ${shQuote(statePath)} \\`,
576
+ ` --root ${shQuote(root || '')} \\`,
577
+ ` --worker-dir ${shQuote(workerDir || '')} \\`,
578
+ ` --hub-url ${shQuote(hubUrl || '')} "$@"`,
579
+ '',
580
+ ].join('\n');
581
+ }
582
+
583
+ /**
584
+ * Copy the installer package (src/, ai/, package.json, bundled workflows /
585
+ * worker files) to a persistent directory — the bootstrap unpacks it into a
586
+ * temp dir that is wiped on exit, and the tools must keep working. Idempotent:
587
+ * the destination is replaced as a whole (never merged with stale files).
588
+ * @returns {string} absolute path of the persistent cli.js
589
+ */
590
+ function persistInstaller(io, { srcRoot, destRoot }) {
591
+ const src = path.resolve(srcRoot);
592
+ const dest = path.resolve(destRoot);
593
+ if (src === dest) return path.join(dest, 'src', 'installer', 'cli.js');
594
+ const tmp = `${dest}.tmp-${process.pid}`;
595
+ if (io.fs.existsSync(tmp)) io.fs.rmSync(tmp, { recursive: true, force: true });
596
+ const copyDir = (from, to) => {
597
+ io.fs.mkdirSync(to, { recursive: true });
598
+ for (const name of io.fs.readdirSync(from)) {
599
+ if (name === 'node_modules' || name === '.git' || name === 'tests') continue;
600
+ const a = path.join(from, name);
601
+ const b = path.join(to, name);
602
+ if (io.fs.isDirectory(a)) copyDir(a, b);
603
+ else io.fs.copyFileSync(a, b);
604
+ }
605
+ };
606
+ copyDir(src, tmp);
607
+ if (io.fs.existsSync(dest)) io.fs.rmSync(dest, { recursive: true, force: true });
608
+ io.fs.renameSync(tmp, dest);
609
+ return path.join(dest, 'src', 'installer', 'cli.js');
610
+ }
611
+
612
+ /** True when `dir` is listed in PATH. */
613
+ function inPath(dir, envPath = process.env.PATH || '') {
614
+ return String(envPath).split(path.delimiter).some((p) => p && path.resolve(p) === path.resolve(dir));
615
+ }
616
+
617
+ /**
618
+ * Link <linkDir>/animastor → the generated command. An existing link is
619
+ * replaced only when it is a symlink to an `animastor` command generated by
620
+ * the installer (another installation of the same user); a foreign file is
621
+ * never overwritten.
622
+ * @returns {{ link: string|null, command: string, path_hint: string|null, reason?: string }}
623
+ */
624
+ function linkAnimastorCommand(io, { target, linkDir }) {
625
+ if (!linkDir || typeof io.fs.symlinkSync !== 'function') {
626
+ return { link: null, command: target, path_hint: null, reason: 'no link directory' };
627
+ }
628
+ const link = path.join(linkDir, 'animastor');
629
+ try {
630
+ io.fs.mkdirSync(linkDir, { recursive: true });
631
+ const existing = typeof io.fs.lstatSync === 'function' ? io.fs.lstatSync(link) : null;
632
+ if (existing) {
633
+ if (!existing.isSymbolicLink) {
634
+ return { link: null, command: target, path_hint: null, reason: `${link} exists and is not an installer link — left untouched` };
635
+ }
636
+ const current = io.fs.readlinkSync(link);
637
+ if (current !== target && !/[\\/]tools[\\/]animastor$/.test(current)) {
638
+ return { link: null, command: target, path_hint: null, reason: `${link} points to ${current} — left untouched` };
639
+ }
640
+ if (current !== target) io.fs.unlinkSync(link);
641
+ else return { link, command: inPath(linkDir) ? 'animastor' : link, path_hint: pathHint(linkDir) };
642
+ }
643
+ io.fs.symlinkSync(target, link);
644
+ return { link, command: inPath(linkDir) ? 'animastor' : link, path_hint: pathHint(linkDir) };
645
+ } catch (err) {
646
+ return { link: null, command: target, path_hint: null, reason: err.message };
647
+ }
648
+ }
649
+
650
+ function pathHint(linkDir) {
651
+ if (inPath(linkDir)) return null;
652
+ return `${linkDir} is not in PATH yet for this shell — open a new login shell, or run: export PATH="${linkDir}:$PATH"`;
653
+ }
654
+
655
+ /**
656
+ * Re-apply the PATH block on every run (installer, doctor AND `animastor
657
+ * start`): E2E nodes reset ~/.bashrc and ~/.profile on every boot, so the
658
+ * block added at install time disappears while the installation in $HOME
659
+ * survives. Idempotent — no duplicate blocks.
660
+ * @returns {{ dir, updated: string[], already: string[] }}
661
+ */
662
+ function restoreCommandPath(io, { linkDir = null, home = null } = {}) {
663
+ if (!linkDir) return { dir: null, updated: [], already: [] };
664
+ return ensurePathEntry(io, { dir: linkDir, home: home || (linkDir ? path.resolve(linkDir, '..', '..') : null) });
665
+ }
666
+
667
+ // ---------------------------------------------------------------------------
668
+ // Autostart wrapper (~/animastor/start-worker.sh)
669
+ // ---------------------------------------------------------------------------
670
+
671
+ /** Marker of the generated autostart wrapper (never re-backed-up). */
672
+ const WRAPPER_MARKER = '# animastor: generated autostart wrapper';
673
+
674
+ /** ~/animastor/start-worker.sh for <workerDir> = ~/animastor/worker. */
675
+ function startWorkerScriptPath(workerDir) {
676
+ if (!workerDir) return null;
677
+ return path.join(path.dirname(path.resolve(workerDir)), 'start-worker.sh');
678
+ }
679
+
680
+ /**
681
+ * The autostart wrapper. It delegates to the persistent `animastor` command:
682
+ * after a reboot the old script apt-installed Node 18 on every boot, waited
683
+ * for port 8188 and knew nothing about the platform's ComfyUI — the command
684
+ * handles PATH, the probed ComfyUI address, missing apt packages and the
685
+ * worker in one place (installer 0.2.2).
686
+ */
687
+ function renderStartWorkerWrapper(animastorPath) {
688
+ return [
689
+ '#!/bin/sh',
690
+ `${WRAPPER_MARKER} (installer 0.2.2) — do not edit; re-run: animastor doctor`,
691
+ '# The previous launcher is kept next to this file as start-worker.sh.bak.',
692
+ '# All logic (PATH block, ComfyUI address, apt prerequisites, worker) lives',
693
+ '# in the installer: `animastor start` (and `animastor doctor`).',
694
+ `exec ${shQuote(animastorPath)} start "$@"`,
695
+ '',
696
+ ].join('\n');
697
+ }
698
+
699
+ /**
700
+ * Replace <base>/start-worker.sh with the wrapper (the old script is backed
701
+ * up once). Idempotent: a second run rewrites the same bytes and creates no
702
+ * second backup. Never touches a foreign file without keeping a copy.
703
+ * @returns {{ path: string|null, status: 'created'|'replaced'|'unchanged'|'failed'|'skipped', backup: string|null, reason?: string }}
704
+ */
705
+ function ensureStartWorkerWrapper(io, { workerDir, animastorPath = null, backupSuffix = '.bak' } = {}) {
706
+ const file = startWorkerScriptPath(workerDir);
707
+ if (!file || !animastorPath) return { path: file, status: 'skipped', backup: null };
708
+ const wanted = renderStartWorkerWrapper(animastorPath);
709
+ let current = '';
710
+ try { current = io.fs.existsSync(file) ? String(io.fs.readFileSync(file, 'utf8')) : ''; } catch (_) { current = ''; }
711
+ if (current === wanted) return { path: file, status: 'unchanged', backup: null };
712
+ let backup = null;
713
+ if (current && !current.includes(WRAPPER_MARKER)) {
714
+ backup = `${file}${backupSuffix}`;
715
+ try {
716
+ // Keep the FIRST original: a second run must not overwrite the
717
+ // user's only copy with the already-generated wrapper.
718
+ if (!io.fs.existsSync(backup)) io.fs.copyFileSync(file, backup);
719
+ } catch (_) { backup = null; }
720
+ }
721
+ try {
722
+ io.fs.mkdirSync(path.dirname(file), { recursive: true });
723
+ io.fs.writeFileSync(file, wanted);
724
+ io.fs.chmodSync(file, 0o755);
725
+ } catch (err) {
726
+ return { path: file, status: 'failed', backup, reason: err.message };
727
+ }
728
+ return { path: file, status: current ? 'replaced' : 'created', backup };
729
+ }
730
+
450
731
  /**
451
732
  * Install (or idempotently refresh) the command-line management tools next
452
733
  * to the worker. Re-running the installer overwrites the same files —
453
734
  * no duplicates, no broken state. Script filenames/extensions and content
454
- * are platform-specific (platform adapter).
455
- * @returns {{ toolsDir, files: string[] }}
735
+ * are platform-specific (platform adapter). On Linux the `animastor` command
736
+ * (start|stop|status|logs|doctor) is generated too and linked into PATH.
737
+ * @returns {{ toolsDir, files: string[], command: string, link: string|null, installerDir: string|null, path_hint: string|null }}
456
738
  */
457
- function installManagementTools(io, { toolsDir, nodePath, cliPath, statePath, root, workerDir, log = null, platformAdapter = null }) {
739
+ function installManagementTools(io, { toolsDir, nodePath, cliPath, statePath, root, workerDir, hubUrl = null, installerSrcRoot = null, installerDestRoot = null, linkDir = null, home = null, log = null, platformAdapter = null }) {
458
740
  const adapter = adapterOf({ platformAdapter });
459
741
  io.fs.mkdirSync(toolsDir, { recursive: true });
742
+ let cli = cliPath;
743
+ let installerDir = null;
744
+ if (installerSrcRoot && installerDestRoot) {
745
+ cli = persistInstaller(io, { srcRoot: installerSrcRoot, destRoot: installerDestRoot });
746
+ installerDir = installerDestRoot;
747
+ }
460
748
  const files = [];
461
749
  for (const t of TOOL_SCRIPTS) {
462
750
  const p = path.join(toolsDir, adapter.toolScriptName(t.file));
463
751
  io.fs.writeFileSync(p, renderToolScript({
464
- command: t.command, nodePath, cliPath, statePath, root, workerDir,
752
+ command: t.command, nodePath, cliPath: cli, statePath, root, workerDir,
465
753
  platformAdapter: adapter,
466
754
  }));
467
755
  io.fs.chmodSync(p, adapter.TOOL_SCRIPT_MODE);
468
756
  files.push(p);
469
757
  }
470
- if (log && log.info) log.info(`management tools installed at ${toolsDir} (${files.length} commands)`);
471
- return { toolsDir, files };
758
+ let command = null;
759
+ let link = null;
760
+ let hint = null;
761
+ let pathEntry = null;
762
+ if (adapter.name === 'linux') {
763
+ const p = path.join(toolsDir, 'animastor');
764
+ io.fs.writeFileSync(p, renderAnimastorCommand({ nodePath, cliPath: cli, statePath, root, workerDir, hubUrl }));
765
+ io.fs.chmodSync(p, 0o755);
766
+ files.push(p);
767
+ const linked = linkAnimastorCommand(io, { target: p, linkDir });
768
+ command = linked.command;
769
+ link = linked.link;
770
+ hint = linked.path_hint;
771
+ if (linked.reason && log && log.warn) log.warn(`animastor command not linked into PATH: ${linked.reason} — use ${p}`);
772
+ if (link) {
773
+ // The command lives in ~/.local/bin (also for root) — persist the
774
+ // PATH entry so `animastor doctor` works after a node restart in a
775
+ // fresh shell, without re-installing anything.
776
+ const rcHome = home || (linkDir ? path.resolve(linkDir, '..', '..') : null);
777
+ pathEntry = ensurePathEntry(io, { dir: linkDir, home: rcHome });
778
+ if (log && log.info && pathEntry.updated.length > 0) {
779
+ log.info(`PATH updated for future shells: ${pathEntry.updated.join(', ')}`);
780
+ }
781
+ }
782
+ }
783
+ if (log && log.info) log.info(`management tools installed at ${toolsDir} (${files.length} commands${link ? `; ${link}` : ''})`);
784
+ return { toolsDir, files, command: command || null, link, installerDir, path_hint: hint, path_entry: pathEntry };
472
785
  }
473
786
 
474
787
  module.exports = {
@@ -485,5 +798,16 @@ module.exports = {
485
798
  renderMonitor,
486
799
  guessJobKind,
487
800
  renderToolScript,
801
+ renderAnimastorCommand,
802
+ persistInstaller,
803
+ linkAnimastorCommand,
804
+ defaultLinkDir,
805
+ ensurePathEntry,
806
+ restoreCommandPath,
807
+ ensureStartWorkerWrapper,
808
+ startWorkerScriptPath,
809
+ renderStartWorkerWrapper,
810
+ PATH_MARKER,
811
+ WRAPPER_MARKER,
488
812
  installManagementTools,
489
813
  };
@@ -182,6 +182,21 @@ function hostPackagesCommand(pkgs) {
182
182
  return `sudo apt-get install -y ${pkgs}`;
183
183
  }
184
184
 
185
+ /** apt-get is the host package manager here — automatic installs are supported. */
186
+ const HOST_INSTALL_SUPPORTED = true;
187
+
188
+ /**
189
+ * The command that installs host packages (`apt-get install -y …`, or
190
+ * `apt-get update` when the index is stale). Elevation (root vs. `sudo -n`)
191
+ * is applied by the caller (engine/prereq.js), never hard-coded here.
192
+ * @returns {{ cmd: string, args: string[] }}
193
+ */
194
+ function hostInstallCommand({ packages = [], update = false } = {}) {
195
+ const pkgs = (Array.isArray(packages) ? packages : String(packages || '').split(/\s+/)).filter(Boolean);
196
+ if (update) return { cmd: 'apt-get', args: ['update'] };
197
+ return { cmd: 'apt-get', args: ['install', '-y', ...pkgs] };
198
+ }
199
+
185
200
  /**
186
201
  * C build-tool prerequisites (native Python extensions). Debian/Ubuntu
187
202
  * package names — a Linux-specific concern, so it lives in this adapter.
@@ -332,6 +347,8 @@ module.exports = {
332
347
 
333
348
  hostPackageCommand,
334
349
  hostPackagesCommand,
350
+ hostInstallCommand,
351
+ supportsHostInstall: HOST_INSTALL_SUPPORTED,
335
352
  checkBuildPrerequisites,
336
353
 
337
354
  toolScriptName,