@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.
@@ -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 {
@@ -154,10 +183,18 @@ async function collectStatus(io, targets, opts = {}) {
154
183
  } catch (_) { /* queue is optional */ }
155
184
  }
156
185
  return {
157
- worker: { running: !!workerPid, pid: workerPid || null },
158
- comfyui: { running: comfyPids.length > 0, root_present: comfyRootPresent, port, pids: comfyPids },
186
+ // current job (installer 0.2.8): the running worker's task, from its own log.
187
+ worker: {
188
+ running: !!workerPid, pid: workerPid || null,
189
+ current_job: workerPid && targets.workerDir ? workerMod.currentJobLabel(io, { workerDir: targets.workerDir, pid: workerPid }) : 'none',
190
+ },
191
+ comfyui: {
192
+ running: comfyPids.length > 0, root_present: comfyRootPresent, port, pids: comfyPids, external, url: baseUrl,
193
+ started_by: startedBy, foreign_pid: foreign ? foreign.pid : null,
194
+ },
159
195
  api: { ok: !!stats },
160
196
  queue,
197
+ hub,
161
198
  };
162
199
  }
163
200
 
@@ -169,21 +206,38 @@ function renderStatus(snapshot) {
169
206
  lines.push('Animastor status');
170
207
  lines.push('');
171
208
  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`}`);
209
+ if (snapshot.comfyui.external) {
210
+ const c = snapshot.comfyui;
211
+ const state = snapshot.api.ok ? `${ok} RUNNING` : `${bad} UNREACHABLE`;
212
+ if (c.started_by === 'platform') {
213
+ const pid = c.foreign_pid ? `pid ${c.foreign_pid}` : 'no process running';
214
+ lines.push(`ComfyUI: ${state} — started by the platform (${pid})${c.url ? `, ${c.url}` : ''}`);
215
+ } else {
216
+ lines.push(`ComfyUI: ${state} (your own${c.url ? `, ${c.url}` : ''})`);
217
+ }
218
+ } else {
219
+ lines.push(`ComfyUI: ${snapshot.comfyui.running
220
+ ? `${ok} RUNNING${snapshot.comfyui.port ? ` :${snapshot.comfyui.port}` : ''}`
221
+ : `${bad} STOPPED`}`);
222
+ }
175
223
  lines.push(`API: ${snapshot.api.ok ? `${ok} OK` : `${bad} UNREACHABLE`}`);
176
224
  if (snapshot.queue) {
177
225
  lines.push(`Queue: ${snapshot.queue.running} running / ${snapshot.queue.pending} pending`);
178
226
  } else {
179
227
  lines.push('Queue: — (API unreachable)');
180
228
  }
229
+ lines.push(`current job: ${snapshot.worker.current_job || 'none'}`);
230
+ if (snapshot.hub) {
231
+ 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')}`}`);
232
+ }
181
233
  return lines.join('\n');
182
234
  }
183
235
 
184
236
  /** Exit code for a status snapshot: 0 healthy, 1 degraded. */
185
237
  function statusExitCode(snapshot) {
186
- return snapshot.worker.running && snapshot.comfyui.running && snapshot.api.ok ? 0 : 1;
238
+ const comfyOk = snapshot.comfyui.running || (snapshot.comfyui.external && snapshot.api.ok);
239
+ const hubOk = !snapshot.hub || snapshot.hub.heartbeat;
240
+ return snapshot.worker.running && comfyOk && snapshot.api.ok && hubOk ? 0 : 1;
187
241
  }
188
242
 
189
243
  // ---------------------------------------------------------------------------
@@ -447,28 +501,292 @@ function renderToolScript({ command, nodePath, cliPath, statePath, root, workerD
447
501
  return adapterOf({ platformAdapter }).renderToolScript({ command, nodePath, cliPath, statePath, root, workerDir });
448
502
  }
449
503
 
504
+ /**
505
+ * Where the `animastor` command is linked: ALWAYS ~/.local/bin (XDG user
506
+ * bin, created when missing) — root included. E2E nodes only keep /home
507
+ * across a reboot, so a /usr/local/bin link would vanish while the
508
+ * installation in $HOME survived; the command must survive with it.
509
+ * `uid` stays in the signature because callers/tests pass it.
510
+ */
511
+ function defaultLinkDir({ uid = prereq.currentUid(), home = prereq.currentHome() } = {}) {
512
+ if (!home) return null;
513
+ return path.join(home, '.local', 'bin');
514
+ }
515
+
516
+ // ---------------------------------------------------------------------------
517
+ // PATH persistence
518
+ // ---------------------------------------------------------------------------
519
+
520
+ /** Marker line of the PATH block this installer appends to shell rc files. */
521
+ const PATH_MARKER = '# animastor: PATH for the `animastor` command (added by animastor-installer)';
522
+
523
+ /**
524
+ * Make `dir` reachable in EVERY future login shell: append an idempotent
525
+ * PATH block to ~/.bashrc and ~/.profile when the directory is not there
526
+ * yet. The block keeps the current PATH intact and is added once — re-runs
527
+ * of the installer never duplicate it. Necessary because the link dir is
528
+ * ~/.local/bin (also for root) and many non-login shells skip it.
529
+ * @returns {{ dir: string|null, updated: string[], already: string[] }}
530
+ */
531
+ function ensurePathEntry(io, { dir, home = null, files = ['.bashrc', '.profile'] } = {}) {
532
+ if (!dir || !home) return { dir: dir || null, updated: [], already: [] };
533
+ const block = [
534
+ PATH_MARKER,
535
+ `case ":$PATH:" in *":${dir}:"*) ;; *) export PATH="${dir}:$PATH" ;; esac`,
536
+ '',
537
+ ].join('\n');
538
+ const updated = [];
539
+ const already = [];
540
+ for (const name of files) {
541
+ const file = path.join(home, name);
542
+ let text = '';
543
+ try { text = io.fs.existsSync(file) ? String(io.fs.readFileSync(file, 'utf8')) : ''; } catch (_) { text = ''; }
544
+ const present = text.includes(PATH_MARKER)
545
+ || text.split('\n').some((line) => line.includes(dir) && /\bPATH\b/.test(line));
546
+ if (present) { already.push(file); continue; }
547
+ try {
548
+ io.fs.mkdirSync(path.dirname(file), { recursive: true });
549
+ const prefix = text && !text.endsWith('\n') ? '\n' : '';
550
+ io.fs.writeFileSync(file, `${text}${prefix}${block}`);
551
+ updated.push(file);
552
+ } catch (_) { /* best effort — the hint below still tells the user */ }
553
+ }
554
+ return { dir, updated, already };
555
+ }
556
+
557
+ function shQuote(v) {
558
+ return `'${String(v).replace(/'/g, `'\\''`)}'`;
559
+ }
560
+
561
+ /**
562
+ * The `animastor` command (Linux): ONE entry point for the management
563
+ * subcommands — start | stop | status | logs | doctor (+ monitor,
564
+ * reboot-worker, reboot-comfyui). A thin shim: every behaviour lives in the
565
+ * persistent installer CLI; the recorded paths of THIS installation are
566
+ * injected so the command works from any directory.
567
+ */
568
+ function renderAnimastorCommand({ nodePath, cliPath, statePath, root, workerDir, hubUrl }) {
569
+ return [
570
+ '#!/bin/sh',
571
+ '# animastor — Animastor GPU worker management (generated by animastor-installer).',
572
+ '# Usage: animastor start | stop | status | logs [-f] | doctor [--new-key] | boot',
573
+ '# Do not edit: re-run the installer (or `animastor doctor`) to refresh.',
574
+ 'cmd="${1:-status}"',
575
+ '[ $# -gt 0 ] && shift',
576
+ 'case "$cmd" in',
577
+ ' -h|--help|help) echo "usage: animastor start | stop | status | logs [-f] | doctor [--new-key] | boot"; exit 0 ;;',
578
+ 'esac',
579
+ `exec ${shQuote(nodePath)} ${shQuote(cliPath)} "$cmd" \\`,
580
+ ` --state ${shQuote(statePath)} \\`,
581
+ ` --root ${shQuote(root || '')} \\`,
582
+ ` --worker-dir ${shQuote(workerDir || '')} \\`,
583
+ ` --hub-url ${shQuote(hubUrl || '')} "$@"`,
584
+ '',
585
+ ].join('\n');
586
+ }
587
+
588
+ /**
589
+ * Copy the installer package (src/, ai/, package.json, bundled workflows /
590
+ * worker files) to a persistent directory — the bootstrap unpacks it into a
591
+ * temp dir that is wiped on exit, and the tools must keep working. Idempotent:
592
+ * the destination is replaced as a whole (never merged with stale files).
593
+ * @returns {string} absolute path of the persistent cli.js
594
+ */
595
+ function persistInstaller(io, { srcRoot, destRoot }) {
596
+ const src = path.resolve(srcRoot);
597
+ const dest = path.resolve(destRoot);
598
+ if (src === dest) return path.join(dest, 'src', 'installer', 'cli.js');
599
+ const tmp = `${dest}.tmp-${process.pid}`;
600
+ if (io.fs.existsSync(tmp)) io.fs.rmSync(tmp, { recursive: true, force: true });
601
+ const copyDir = (from, to) => {
602
+ io.fs.mkdirSync(to, { recursive: true });
603
+ for (const name of io.fs.readdirSync(from)) {
604
+ if (name === 'node_modules' || name === '.git' || name === 'tests') continue;
605
+ const a = path.join(from, name);
606
+ const b = path.join(to, name);
607
+ if (io.fs.isDirectory(a)) copyDir(a, b);
608
+ else io.fs.copyFileSync(a, b);
609
+ }
610
+ };
611
+ copyDir(src, tmp);
612
+ if (io.fs.existsSync(dest)) io.fs.rmSync(dest, { recursive: true, force: true });
613
+ io.fs.renameSync(tmp, dest);
614
+ return path.join(dest, 'src', 'installer', 'cli.js');
615
+ }
616
+
617
+ /** True when `dir` is listed in PATH. */
618
+ function inPath(dir, envPath = process.env.PATH || '') {
619
+ return String(envPath).split(path.delimiter).some((p) => p && path.resolve(p) === path.resolve(dir));
620
+ }
621
+
622
+ /**
623
+ * Link <linkDir>/animastor → the generated command. An existing link is
624
+ * replaced only when it is a symlink to an `animastor` command generated by
625
+ * the installer (another installation of the same user); a foreign file is
626
+ * never overwritten.
627
+ * @returns {{ link: string|null, command: string, path_hint: string|null, reason?: string }}
628
+ */
629
+ function linkAnimastorCommand(io, { target, linkDir }) {
630
+ if (!linkDir || typeof io.fs.symlinkSync !== 'function') {
631
+ return { link: null, command: target, path_hint: null, reason: 'no link directory' };
632
+ }
633
+ const link = path.join(linkDir, 'animastor');
634
+ try {
635
+ io.fs.mkdirSync(linkDir, { recursive: true });
636
+ const existing = typeof io.fs.lstatSync === 'function' ? io.fs.lstatSync(link) : null;
637
+ if (existing) {
638
+ if (!existing.isSymbolicLink) {
639
+ return { link: null, command: target, path_hint: null, reason: `${link} exists and is not an installer link — left untouched` };
640
+ }
641
+ const current = io.fs.readlinkSync(link);
642
+ if (current !== target && !/[\\/]tools[\\/]animastor$/.test(current)) {
643
+ return { link: null, command: target, path_hint: null, reason: `${link} points to ${current} — left untouched` };
644
+ }
645
+ if (current !== target) io.fs.unlinkSync(link);
646
+ else return { link, command: inPath(linkDir) ? 'animastor' : link, path_hint: pathHint(linkDir) };
647
+ }
648
+ io.fs.symlinkSync(target, link);
649
+ return { link, command: inPath(linkDir) ? 'animastor' : link, path_hint: pathHint(linkDir) };
650
+ } catch (err) {
651
+ return { link: null, command: target, path_hint: null, reason: err.message };
652
+ }
653
+ }
654
+
655
+ function pathHint(linkDir) {
656
+ if (inPath(linkDir)) return null;
657
+ return `${linkDir} is not in PATH yet for this shell — open a new login shell, or run: export PATH="${linkDir}:$PATH"`;
658
+ }
659
+
660
+ /**
661
+ * Re-apply the PATH block on every run (installer, doctor AND `animastor
662
+ * start`): E2E nodes reset ~/.bashrc and ~/.profile on every boot, so the
663
+ * block added at install time disappears while the installation in $HOME
664
+ * survives. Idempotent — no duplicate blocks.
665
+ * @returns {{ dir, updated: string[], already: string[] }}
666
+ */
667
+ function restoreCommandPath(io, { linkDir = null, home = null } = {}) {
668
+ if (!linkDir) return { dir: null, updated: [], already: [] };
669
+ return ensurePathEntry(io, { dir: linkDir, home: home || (linkDir ? path.resolve(linkDir, '..', '..') : null) });
670
+ }
671
+
672
+ // ---------------------------------------------------------------------------
673
+ // Autostart wrapper (~/animastor/start-worker.sh)
674
+ // ---------------------------------------------------------------------------
675
+
676
+ /** Marker of the generated autostart wrapper (never re-backed-up). */
677
+ const WRAPPER_MARKER = '# animastor: generated autostart wrapper';
678
+
679
+ /** ~/animastor/start-worker.sh for <workerDir> = ~/animastor/worker. */
680
+ function startWorkerScriptPath(workerDir) {
681
+ if (!workerDir) return null;
682
+ return path.join(path.dirname(path.resolve(workerDir)), 'start-worker.sh');
683
+ }
684
+
685
+ /**
686
+ * The autostart wrapper. It delegates to the persistent `animastor` command:
687
+ * after a reboot the old script apt-installed Node 18 on every boot, waited
688
+ * for port 8188 and knew nothing about the platform's ComfyUI — the command
689
+ * handles PATH, the probed ComfyUI address, missing apt packages and the
690
+ * worker in one place (installer 0.2.2).
691
+ */
692
+ function renderStartWorkerWrapper(animastorPath) {
693
+ return [
694
+ '#!/bin/sh',
695
+ `${WRAPPER_MARKER} (installer 0.2.2) — do not edit; re-run: animastor doctor`,
696
+ '# The previous launcher is kept next to this file as start-worker.sh.bak.',
697
+ '# All logic (PATH block, ComfyUI address, apt prerequisites, worker) lives',
698
+ '# in the installer: `animastor start` (and `animastor doctor`).',
699
+ `exec ${shQuote(animastorPath)} start "$@"`,
700
+ '',
701
+ ].join('\n');
702
+ }
703
+
704
+ /**
705
+ * Replace <base>/start-worker.sh with the wrapper (the old script is backed
706
+ * up once). Idempotent: a second run rewrites the same bytes and creates no
707
+ * second backup. Never touches a foreign file without keeping a copy.
708
+ * @returns {{ path: string|null, status: 'created'|'replaced'|'unchanged'|'failed'|'skipped', backup: string|null, reason?: string }}
709
+ */
710
+ function ensureStartWorkerWrapper(io, { workerDir, animastorPath = null, backupSuffix = '.bak' } = {}) {
711
+ const file = startWorkerScriptPath(workerDir);
712
+ if (!file || !animastorPath) return { path: file, status: 'skipped', backup: null };
713
+ const wanted = renderStartWorkerWrapper(animastorPath);
714
+ let current = '';
715
+ try { current = io.fs.existsSync(file) ? String(io.fs.readFileSync(file, 'utf8')) : ''; } catch (_) { current = ''; }
716
+ if (current === wanted) return { path: file, status: 'unchanged', backup: null };
717
+ let backup = null;
718
+ if (current && !current.includes(WRAPPER_MARKER)) {
719
+ backup = `${file}${backupSuffix}`;
720
+ try {
721
+ // Keep the FIRST original: a second run must not overwrite the
722
+ // user's only copy with the already-generated wrapper.
723
+ if (!io.fs.existsSync(backup)) io.fs.copyFileSync(file, backup);
724
+ } catch (_) { backup = null; }
725
+ }
726
+ try {
727
+ io.fs.mkdirSync(path.dirname(file), { recursive: true });
728
+ io.fs.writeFileSync(file, wanted);
729
+ io.fs.chmodSync(file, 0o755);
730
+ } catch (err) {
731
+ return { path: file, status: 'failed', backup, reason: err.message };
732
+ }
733
+ return { path: file, status: current ? 'replaced' : 'created', backup };
734
+ }
735
+
450
736
  /**
451
737
  * Install (or idempotently refresh) the command-line management tools next
452
738
  * to the worker. Re-running the installer overwrites the same files —
453
739
  * no duplicates, no broken state. Script filenames/extensions and content
454
- * are platform-specific (platform adapter).
455
- * @returns {{ toolsDir, files: string[] }}
740
+ * are platform-specific (platform adapter). On Linux the `animastor` command
741
+ * (start|stop|status|logs|doctor) is generated too and linked into PATH.
742
+ * @returns {{ toolsDir, files: string[], command: string, link: string|null, installerDir: string|null, path_hint: string|null }}
456
743
  */
457
- function installManagementTools(io, { toolsDir, nodePath, cliPath, statePath, root, workerDir, log = null, platformAdapter = null }) {
744
+ function installManagementTools(io, { toolsDir, nodePath, cliPath, statePath, root, workerDir, hubUrl = null, installerSrcRoot = null, installerDestRoot = null, linkDir = null, home = null, log = null, platformAdapter = null }) {
458
745
  const adapter = adapterOf({ platformAdapter });
459
746
  io.fs.mkdirSync(toolsDir, { recursive: true });
747
+ let cli = cliPath;
748
+ let installerDir = null;
749
+ if (installerSrcRoot && installerDestRoot) {
750
+ cli = persistInstaller(io, { srcRoot: installerSrcRoot, destRoot: installerDestRoot });
751
+ installerDir = installerDestRoot;
752
+ }
460
753
  const files = [];
461
754
  for (const t of TOOL_SCRIPTS) {
462
755
  const p = path.join(toolsDir, adapter.toolScriptName(t.file));
463
756
  io.fs.writeFileSync(p, renderToolScript({
464
- command: t.command, nodePath, cliPath, statePath, root, workerDir,
757
+ command: t.command, nodePath, cliPath: cli, statePath, root, workerDir,
465
758
  platformAdapter: adapter,
466
759
  }));
467
760
  io.fs.chmodSync(p, adapter.TOOL_SCRIPT_MODE);
468
761
  files.push(p);
469
762
  }
470
- if (log && log.info) log.info(`management tools installed at ${toolsDir} (${files.length} commands)`);
471
- return { toolsDir, files };
763
+ let command = null;
764
+ let link = null;
765
+ let hint = null;
766
+ let pathEntry = null;
767
+ if (adapter.name === 'linux') {
768
+ const p = path.join(toolsDir, 'animastor');
769
+ io.fs.writeFileSync(p, renderAnimastorCommand({ nodePath, cliPath: cli, statePath, root, workerDir, hubUrl }));
770
+ io.fs.chmodSync(p, 0o755);
771
+ files.push(p);
772
+ const linked = linkAnimastorCommand(io, { target: p, linkDir });
773
+ command = linked.command;
774
+ link = linked.link;
775
+ hint = linked.path_hint;
776
+ if (linked.reason && log && log.warn) log.warn(`animastor command not linked into PATH: ${linked.reason} — use ${p}`);
777
+ if (link) {
778
+ // The command lives in ~/.local/bin (also for root) — persist the
779
+ // PATH entry so `animastor doctor` works after a node restart in a
780
+ // fresh shell, without re-installing anything.
781
+ const rcHome = home || (linkDir ? path.resolve(linkDir, '..', '..') : null);
782
+ pathEntry = ensurePathEntry(io, { dir: linkDir, home: rcHome });
783
+ if (log && log.info && pathEntry.updated.length > 0) {
784
+ log.info(`PATH updated for future shells: ${pathEntry.updated.join(', ')}`);
785
+ }
786
+ }
787
+ }
788
+ if (log && log.info) log.info(`management tools installed at ${toolsDir} (${files.length} commands${link ? `; ${link}` : ''})`);
789
+ return { toolsDir, files, command: command || null, link, installerDir, path_hint: hint, path_entry: pathEntry };
472
790
  }
473
791
 
474
792
  module.exports = {
@@ -485,5 +803,16 @@ module.exports = {
485
803
  renderMonitor,
486
804
  guessJobKind,
487
805
  renderToolScript,
806
+ renderAnimastorCommand,
807
+ persistInstaller,
808
+ linkAnimastorCommand,
809
+ defaultLinkDir,
810
+ ensurePathEntry,
811
+ restoreCommandPath,
812
+ ensureStartWorkerWrapper,
813
+ startWorkerScriptPath,
814
+ renderStartWorkerWrapper,
815
+ PATH_MARKER,
816
+ WRAPPER_MARKER,
488
817
  installManagementTools,
489
818
  };
@@ -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,