@animastor/installer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +66 -0
  3. package/ai/install-manifests/audio/qwen-tts.json +445 -0
  4. package/ai/install-manifests/image/qwen-image.json +465 -0
  5. package/ai/install-manifests/video/ltx-2.3.json +892 -0
  6. package/package.json +42 -0
  7. package/src/installer/cli.js +1067 -0
  8. package/src/installer/compatibility-resolver.js +1287 -0
  9. package/src/installer/download-planner.js +172 -0
  10. package/src/installer/engine/comfyui.js +508 -0
  11. package/src/installer/engine/downloader.js +514 -0
  12. package/src/installer/engine/engine.js +1180 -0
  13. package/src/installer/engine/io.js +437 -0
  14. package/src/installer/engine/logger.js +75 -0
  15. package/src/installer/engine/nodes.js +146 -0
  16. package/src/installer/engine/prereq.js +399 -0
  17. package/src/installer/engine/probe.js +349 -0
  18. package/src/installer/engine/progress.js +350 -0
  19. package/src/installer/engine/state.js +170 -0
  20. package/src/installer/engine/term.js +298 -0
  21. package/src/installer/engine/worker.js +430 -0
  22. package/src/installer/engine/workflows.js +153 -0
  23. package/src/installer/index.js +40 -0
  24. package/src/installer/install-manifest.js +376 -0
  25. package/src/installer/install-plan.js +741 -0
  26. package/src/installer/management.js +489 -0
  27. package/src/installer/platform/deployment/docker.js +78 -0
  28. package/src/installer/platform/deployment/native.js +36 -0
  29. package/src/installer/platform/index.js +165 -0
  30. package/src/installer/platform/linux.js +341 -0
  31. package/src/installer/platform/windows.js +360 -0
  32. package/src/installer/safety-rules.js +156 -0
  33. package/src/installer/setup-contract.js +1401 -0
  34. package/src/installer/uninstaller.js +572 -0
  35. package/src/installer/verification-report.js +220 -0
  36. package/src/installer/worker-bundle-source.js +64 -0
  37. package/src/installer/workflow-artifacts.js +152 -0
@@ -0,0 +1,170 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Install state — Private Worker Installer Phase 2.
5
+ *
6
+ * A small JSON file (default: <stateDir>/install-state.json) recording what
7
+ * the engine has done, so an interrupted installation can be resumed:
8
+ *
9
+ * installer resume
10
+ *
11
+ * Artifact statuses: missing | partial | installed | verified | failed.
12
+ *
13
+ * Rules:
14
+ * - the state file is an OPTIMIZATION — truth is the disk (the engine
15
+ * always re-checks before doing);
16
+ * - NO secrets are ever written here (worker key, tokens);
17
+ * - writes are atomic (tmp file + rename).
18
+ */
19
+
20
+ const STATE_VERSION = 1;
21
+
22
+ const ARTIFACT_STATUSES = Object.freeze(['missing', 'partial', 'installed', 'verified', 'failed']);
23
+
24
+ /**
25
+ * Ownership registry kinds (uninstaller input). Each entry records a path the
26
+ * installer actually created — the uninstaller must never guess and never
27
+ * delete anything that is not registered here.
28
+ */
29
+ const COMPONENT_KINDS = Object.freeze(['custom_nodes', 'models', 'workflows', 'services']);
30
+
31
+ const { isSecretName } = require('../safety-rules');
32
+
33
+ /** Defensive scrub: never persist values under secret-looking names. */
34
+ function scrubSecrets(obj) {
35
+ if (!obj || typeof obj !== 'object') return obj;
36
+ for (const key of Object.keys(obj)) {
37
+ if (isSecretName(key)) {
38
+ delete obj[key];
39
+ } else if (typeof obj[key] === 'object') {
40
+ scrubSecrets(obj[key]);
41
+ }
42
+ }
43
+ return obj;
44
+ }
45
+
46
+ function emptyState({ mode = null, profiles = [], root = null } = {}) {
47
+ return {
48
+ state_version: STATE_VERSION,
49
+ created: null,
50
+ updated: null,
51
+ mode,
52
+ profiles,
53
+ root,
54
+ // hardware branch chosen by the installer: 'cuda' | 'cpu'
55
+ device: null,
56
+ // uid of the account that created the installation — the ownership
57
+ // guard blocks resume/install under a different uid (sudo mixing).
58
+ owner_uid: null,
59
+ // non-secret user decisions (comfyui_update, install_models, …).
60
+ // Recorded so `resume` continues without re-prompting.
61
+ decisions: {},
62
+ artifacts: {},
63
+ // Installation manifest for the uninstaller: what THIS installer run
64
+ // created (and therefore owns). `null` = not touched/unknown.
65
+ // comfyui: { owned, path, ref? } — owned=true only when the
66
+ // installer created the dir
67
+ // venv: { owned, path, created }
68
+ // worker: { owned, dir, files_installed[], files_kept[], env_created }
69
+ // custom_nodes/models/workflows/services: [{ id, path, created?, files? }]
70
+ components: {
71
+ comfyui: null,
72
+ venv: null,
73
+ worker: null,
74
+ custom_nodes: [],
75
+ models: [],
76
+ workflows: [],
77
+ services: [],
78
+ },
79
+ checkpoints: [],
80
+ };
81
+ }
82
+
83
+ /**
84
+ * Normalize a state loaded from disk (older states lack the components
85
+ * registry and the device field — additively restored, version stays 1).
86
+ */
87
+ function normalizeState(state) {
88
+ if (!state || typeof state !== 'object') return state;
89
+ if (state.device === undefined) state.device = null;
90
+ if (state.owner_uid === undefined) state.owner_uid = null;
91
+ const empty = emptyState();
92
+ state.components = { ...empty.components, ...(state.components || {}) };
93
+ // legacy cleanup: older builds could persist a literal "undefined" key
94
+ if (state.artifacts && state.artifacts.undefined) delete state.artifacts.undefined;
95
+ return state;
96
+ }
97
+
98
+ /**
99
+ * Register an installer-created component (idempotent per path).
100
+ * @param {string} kind one of COMPONENT_KINDS
101
+ * @param {object} entry { id, path, created?, files? }
102
+ */
103
+ function addOwnedComponent(state, kind, entry) {
104
+ if (!COMPONENT_KINDS.includes(kind)) {
105
+ throw new Error(`internal error: unknown component kind "${kind}"`);
106
+ }
107
+ if (!entry || !entry.path) return;
108
+ const list = state.components[kind];
109
+ if (list.some((e) => e.path === entry.path)) return;
110
+ list.push({ id: entry.id || null, path: entry.path, ...(entry.created !== undefined ? { created: entry.created } : {}), ...(entry.files ? { files: entry.files } : {}) });
111
+ }
112
+
113
+ function loadState(io, statePath) {
114
+ if (!io.fs.existsSync(statePath)) return null;
115
+ try {
116
+ const parsed = JSON.parse(io.fs.readFileSync(statePath, 'utf8'));
117
+ if (!parsed || parsed.state_version !== STATE_VERSION) return null;
118
+ return normalizeState(parsed);
119
+ } catch (_) {
120
+ return null; // corrupt state — start fresh, truth is the disk
121
+ }
122
+ }
123
+
124
+ function saveState(io, statePath, state, now) {
125
+ state.updated = new Date(now()).toISOString();
126
+ if (!state.created) state.created = state.updated;
127
+ scrubSecrets(state);
128
+ const dir = statePath.replace(/\/[^/]+$/, '');
129
+ if (dir && !io.fs.existsSync(dir)) io.fs.mkdirSync(dir, { recursive: true });
130
+ const tmp = `${statePath}.tmp`;
131
+ io.fs.writeFileSync(tmp, JSON.stringify(state, null, 2));
132
+ io.fs.renameSync(tmp, statePath);
133
+ }
134
+
135
+ function setArtifact(state, id, status, detail = {}) {
136
+ if (!id) return; // defensive: a missing id must never create an "undefined" key
137
+ if (!ARTIFACT_STATUSES.includes(status)) {
138
+ throw new Error(`internal error: unknown artifact status "${status}"`);
139
+ }
140
+ const prev = state.artifacts[id] || {};
141
+ state.artifacts[id] = {
142
+ status,
143
+ at: new Date(Date.now()).toISOString(),
144
+ attempts: (prev.attempts || 0) + (status === 'failed' ? 1 : 0),
145
+ detail: { ...prev.detail, ...detail },
146
+ };
147
+ }
148
+
149
+ function artifactStatus(state, id) {
150
+ return state.artifacts[id] ? state.artifacts[id].status : 'missing';
151
+ }
152
+
153
+ /** Record a rollback checkpoint (e.g. previous ComfyUI commit). */
154
+ function addCheckpoint(state, checkpoint) {
155
+ state.checkpoints.push({ at: new Date(Date.now()).toISOString(), ...checkpoint });
156
+ }
157
+
158
+ module.exports = {
159
+ STATE_VERSION,
160
+ ARTIFACT_STATUSES,
161
+ COMPONENT_KINDS,
162
+ emptyState,
163
+ normalizeState,
164
+ loadState,
165
+ saveState,
166
+ setArtifact,
167
+ artifactStatus,
168
+ addCheckpoint,
169
+ addOwnedComponent,
170
+ };
@@ -0,0 +1,298 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Terminal renderer — the SINGLE point through which the installer draws
5
+ * anything on the terminal: permanent lines (logger output, plan text,
6
+ * final download statuses), the one mutable "active status" line used by
7
+ * download progress, and the busy spinner for long subprocess steps.
8
+ *
9
+ * Why it exists: before this module the progress line was drawn directly
10
+ * on stderr while installer messages went to stdout — the two streams
11
+ * interleaved arbitrarily and the progress redraw was not throttled, so
12
+ * a long download painted hundreds of near-identical "Downloading …"
13
+ * lines over the installer status.
14
+ *
15
+ * Contract:
16
+ * - TTY → `status()` redraws ONE line in place (\r … ESC[K), time-
17
+ * throttled; `print()` first erases the active line, writes
18
+ * the permanent line, then re-renders the active line below
19
+ * it — installer messages, progress and the busy spinner
20
+ * never overwrite each other;
21
+ * - non-TTY → `status()` and the spinner are no-ops, `print()` is a
22
+ * plain line. ANSI escape sequences are NEVER emitted, so
23
+ * pipes/CI/logs stay clean;
24
+ * - all output goes through ONE stream (stdout by default), so ordering
25
+ * with logger output is deterministic;
26
+ * - ONE status line, ONE owner: the busy spinner yields it to the
27
+ * download progress line while that is on screen and takes
28
+ * it back when the progress line is cleared;
29
+ * - fully injectable (isTTY/write/now/delayFn/tickFn) for deterministic
30
+ * tests.
31
+ *
32
+ * Note on external tools: spawnSync/spawn output is already captured (io.js)
33
+ * and never streams to the terminal. Any future external downloader must be
34
+ * piped through this renderer too — external processes must never draw their
35
+ * own UI over the installer's terminal output.
36
+ */
37
+
38
+ const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
39
+ const SPINNER_FRAMES_ASCII = ['|', '/', '-', '\\'];
40
+
41
+ /** 64000 → "1m 04s", 12400 → "12s" */
42
+ function formatDuration(ms) {
43
+ const s = Math.max(0, Math.round(ms / 1000));
44
+ if (s < 60) return `${s}s`;
45
+ return `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, '0')}s`;
46
+ }
47
+
48
+ /**
49
+ * Create a terminal renderer.
50
+ *
51
+ * @param {object} opts { isTTY, write, now, minRedrawMs, ascii, delayFn, tickFn }
52
+ * @returns renderer with status/print/clear/startBusy/stopBusy/withBusy/
53
+ * withBusySync/nextSpinnerFrame/spinnerFrame/isTTY/active/busy
54
+ */
55
+ function createTermRenderer(opts = {}) {
56
+ const {
57
+ isTTY = false,
58
+ write = null,
59
+ now = () => Date.now(),
60
+ minRedrawMs = 120,
61
+ ascii = false,
62
+ delayFn = (ms, fn) => { const id = setTimeout(fn, ms); return () => clearTimeout(id); },
63
+ tickFn = (ms, fn) => { const id = setInterval(fn, ms); return () => clearInterval(id); },
64
+ } = opts;
65
+
66
+ const frames = ascii ? SPINNER_FRAMES_ASCII : SPINNER_FRAMES;
67
+
68
+ const out = write || ((s) => {
69
+ try {
70
+ if (typeof process !== 'undefined' && process.stdout) process.stdout.write(s);
71
+ } catch (_) { /* stream gone */ }
72
+ });
73
+
74
+ const raw = (s) => { try { out(s); } catch (_) { /* stream gone */ } };
75
+
76
+ const state = {
77
+ activeText: null, // text currently on the status line (or null)
78
+ drawnText: null, // text as last actually drawn (dedup)
79
+ lastRedrawAt: -Infinity,
80
+ spinnerIdx: 0,
81
+ owner: null, // who owns the status line: 'busy' | 'external' | null
82
+ };
83
+
84
+ let busy = null; // { label, startedAt, shown, cancelled, frame, keepalives, cancelShow, cancelTick, cancelKeep }
85
+
86
+ const erase = () => {
87
+ if (isTTY && state.activeText !== null) raw('\r\x1b[K');
88
+ };
89
+
90
+ const drawStatus = (text, owner) => {
91
+ state.activeText = text;
92
+ state.drawnText = text;
93
+ state.lastRedrawAt = now();
94
+ if (owner) state.owner = owner;
95
+ raw(`\r${text}\x1b[K`);
96
+ };
97
+
98
+ return {
99
+ isTTY: !!isTTY,
100
+
101
+ /** True while a status line is on screen. */
102
+ get active() { return state.activeText !== null; },
103
+
104
+ /** True while a busy spinner is running (visible or pending). */
105
+ get busy() { return busy !== null; },
106
+
107
+ /**
108
+ * Set/replace the active status line (throttled in time; identical
109
+ * consecutive texts are never redrawn). `force` bypasses throttle —
110
+ * used when the line changes meaningfully (file switch, first chunk).
111
+ * Passing null clears the line. A drawn line takes ownership of the
112
+ * status line, pausing the busy spinner until clear(). Non-TTY: no-op.
113
+ */
114
+ status(text, { force = false } = {}) {
115
+ if (!isTTY) return;
116
+ if (text === null || text === undefined) { this.clear(); return; }
117
+ const t = now();
118
+ if (!force && text === state.drawnText) return;
119
+ if (!force && t - state.lastRedrawAt < minRedrawMs) return;
120
+ drawStatus(text, 'external');
121
+ },
122
+
123
+ /** Advance and return the indeterminate-progress spinner frame. */
124
+ nextSpinnerFrame() {
125
+ state.spinnerIdx = (state.spinnerIdx + 1) % frames.length;
126
+ return frames[state.spinnerIdx];
127
+ },
128
+
129
+ /** Current spinner frame (no advance). */
130
+ spinnerFrame() { return frames[state.spinnerIdx]; },
131
+
132
+ /**
133
+ * Emit a PERMANENT line: erases the active status line first (so
134
+ * logger output never merges into it), writes the line, then re-
135
+ * renders the status line below it. Non-TTY: plain line, no ANSI.
136
+ */
137
+ print(line) {
138
+ const had = state.activeText;
139
+ erase();
140
+ state.drawnText = null;
141
+ raw(`${line}\n`);
142
+ if (isTTY && had !== null) drawStatus(had); // keep the live status below the permanent line
143
+ },
144
+
145
+ /** Remove the active status line from screen (no replacement). */
146
+ clear() {
147
+ erase();
148
+ state.activeText = null;
149
+ state.drawnText = null;
150
+ state.owner = null;
151
+ },
152
+
153
+ // -----------------------------------------------------------------
154
+ // Busy indicator — ONE shared spinner for long subprocess steps
155
+ // (pip install, npm install, git clone, waiting for ComfyUI, …).
156
+ // -----------------------------------------------------------------
157
+
158
+ /**
159
+ * Start the busy spinner for a long operation.
160
+ *
161
+ * TTY: the line `[⠋] {label}...` appears only after `minShowMs`
162
+ * (fast operations never flicker), then animates on `intervalMs`.
163
+ * While the download progress line owns the status line the spinner
164
+ * pauses; it resumes when that line is cleared.
165
+ *
166
+ * Non-TTY: no animation and no ANSI; a plain keepalive line
167
+ * `... {label} ({elapsed})` every `keepaliveMs` (0 = off).
168
+ *
169
+ * @param {string} label operation name, e.g. "Installing ComfyUI requirements"
170
+ * @param {object} [o] { immediate, minShowMs, intervalMs, keepaliveMs }
171
+ */
172
+ startBusy(label, o = {}) {
173
+ if (busy) this.stopBusy({ ok: true }); // one busy at a time
174
+ const {
175
+ immediate = false,
176
+ minShowMs = 400,
177
+ intervalMs = 120,
178
+ keepaliveMs = 30000,
179
+ } = o;
180
+ busy = {
181
+ label: String(label),
182
+ startedAt: now(),
183
+ shown: false,
184
+ cancelled: false,
185
+ frame: 0,
186
+ keepalives: 0,
187
+ cancelShow: null,
188
+ cancelTick: null,
189
+ cancelKeep: null,
190
+ };
191
+ const show = () => {
192
+ if (!busy || busy.cancelled) return;
193
+ busy.shown = true;
194
+ if (isTTY) this._drawBusy();
195
+ if (isTTY) busy.cancelTick = tickFn(intervalMs, () => this._busyTick());
196
+ };
197
+ if (immediate) show();
198
+ else busy.cancelShow = delayFn(minShowMs, show);
199
+ if (!isTTY && keepaliveMs > 0) {
200
+ busy.cancelKeep = tickFn(keepaliveMs, () => {
201
+ if (!busy || busy.cancelled) return;
202
+ busy.keepalives += 1;
203
+ raw(`... ${busy.label} (${formatDuration(now() - busy.startedAt)})\n`);
204
+ });
205
+ }
206
+ },
207
+
208
+ /** Internal: draw one busy frame (TTY). */
209
+ _drawBusy() {
210
+ if (!busy || !isTTY) return;
211
+ drawStatus(`${frames[busy.frame % frames.length]} ${busy.label}...`, 'busy');
212
+ },
213
+
214
+ /** Internal: animation tick — advances the frame unless the status
215
+ * line is owned by the download progress. */
216
+ _busyTick() {
217
+ if (!busy || !busy.shown || busy.cancelled || !isTTY) return;
218
+ if (state.owner === 'external' && state.activeText !== null) return; // progress line on screen — pause
219
+ busy.frame += 1;
220
+ this._drawBusy();
221
+ },
222
+
223
+ /**
224
+ * Stop the busy spinner. When the spinner (or a keepalive) ever
225
+ * became visible, ONE final line is emitted:
226
+ * `[✓] {label} (12s)` on success, `[✗] {label} FAILED (12s)` on
227
+ * failure with `detail` on the following line. A fast operation
228
+ * that never showed anything stays completely silent.
229
+ */
230
+ stopBusy({ ok = true, detail = null } = {}) {
231
+ const b = busy;
232
+ if (!b) return;
233
+ busy = null;
234
+ b.cancelled = true;
235
+ if (b.cancelShow) b.cancelShow();
236
+ if (b.cancelTick) b.cancelTick();
237
+ if (b.cancelKeep) b.cancelKeep();
238
+ const wasVisible = b.shown || b.keepalives > 0;
239
+ if (!wasVisible && ok !== false) return; // fast op — no flicker, nothing to close; failures are ALWAYS shown
240
+ const dur = formatDuration(now() - b.startedAt);
241
+ const mark = ok ? '[✓]' : '[✗]';
242
+ const head = `${mark} ${b.label}${ok ? '' : ' FAILED'} (${dur})`;
243
+ this.clear();
244
+ if (detail !== null && detail !== undefined && String(detail).trim() !== '') {
245
+ const safe = String(detail).replace(/\r/g, '');
246
+ this.print(head);
247
+ for (const line of safe.split('\n').slice(0, 20)) {
248
+ if (line.trim() !== '') this.print(` ${line}`);
249
+ }
250
+ } else {
251
+ this.print(head);
252
+ }
253
+ },
254
+
255
+ /**
256
+ * Run an (async) operation under the busy spinner: starts it, stops
257
+ * it with [✓]/[✗] and rethrows errors after closing the spinner.
258
+ * The value of `fn()` is returned. Use for async work (animated
259
+ * spinner) — for synchronous subprocess work use withBusySync.
260
+ */
261
+ async withBusy(label, fn, o) {
262
+ this.startBusy(label, o);
263
+ try {
264
+ const result = await fn();
265
+ this.stopBusy({ ok: true });
266
+ return result;
267
+ } catch (err) {
268
+ this.stopBusy({ ok: false, detail: err && err.message ? String(err.message) : String(err) });
269
+ throw err;
270
+ }
271
+ },
272
+
273
+ /**
274
+ * Synchronous variant: the static busy line is drawn IMMEDIATELY
275
+ * (no animation is possible while spawnSync blocks the event loop),
276
+ * then closed with one final [✓]/[✗] line. Use for long SYNC child
277
+ * processes (git clone via exec, npm install, tar).
278
+ */
279
+ withBusySync(label, fn) {
280
+ this.startBusy(label, { immediate: true });
281
+ try {
282
+ const result = fn();
283
+ this.stopBusy({ ok: true });
284
+ return result;
285
+ } catch (err) {
286
+ this.stopBusy({ ok: false, detail: err && err.message ? String(err.message) : String(err) });
287
+ throw err;
288
+ }
289
+ },
290
+ };
291
+ }
292
+
293
+ module.exports = {
294
+ SPINNER_FRAMES,
295
+ SPINNER_FRAMES_ASCII,
296
+ formatDuration,
297
+ createTermRenderer,
298
+ };