@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,430 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Worker installation — Private Worker Installer Phase 2.
5
+ *
6
+ * Deploys the existing Animastor Worker bundle (the runtime contract is NOT
7
+ * changed), creates/updates `.env` with merge semantics, and verifies
8
+ * registration against GPU Hub.
9
+ *
10
+ * Worker Key safety:
11
+ * - the value is accepted only via an interactive secret provider;
12
+ * - it is never logged, never written to the plan/state/reports, never
13
+ * passed through argv;
14
+ * - an existing valid token in `.env` is never overwritten.
15
+ */
16
+
17
+ const path = require('path');
18
+ const platforms = require('../platform');
19
+ const { resolveRepoBundleDir } = require('../worker-bundle-source');
20
+ const { parseEnvKeys } = require('./probe');
21
+ const { currentUid } = require('./prereq');
22
+
23
+ /**
24
+ * Platform adapter resolution for one call. Explicit `platformAdapter` /
25
+ * `platform` wins; otherwise the running OS is auto-detected. Never called
26
+ * at module load so tests and callers stay free to inject.
27
+ */
28
+ function adapterOf(opts = {}) {
29
+ return opts.platformAdapter || platforms.getPlatformAdapter(opts.platform);
30
+ }
31
+
32
+ function findWorkerManifest(manifests, workerEntryId) {
33
+ return manifests.find((m) => `worker:${m.profile.id}` === workerEntryId) || null;
34
+ }
35
+
36
+ /**
37
+ * Deploy the worker bundle into workerDir.
38
+ * Source order (never invented): a repo checkout bundle first — canonical
39
+ * `packages/animastor-worker/worker/`, legacy `worker/worker/` (pre-
40
+ * relocation checkouts; see installer/worker-bundle-source.js) — then an
41
+ * explicit `bundleDir` (a verified hub worker-bundle tarball the engine
42
+ * extracted beforehand). If both fail, the install returns status 'failed'.
43
+ * Ownership details are returned for the uninstall manifest: dir_created,
44
+ * files the installer actually copied (files_installed) vs files that were
45
+ * already on disk and were kept (files_kept).
46
+ * @returns {{ status, files, files_installed, files_kept, dir_created, reason? }}
47
+ */
48
+ function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleDir = null, hubUrl = null, httpFetchText = null, log = null }) {
49
+ const wb = manifest.worker_bundle || {};
50
+ const files = wb.files || [];
51
+ const dirCreated = !io.fs.existsSync(workerDir);
52
+ if (dirCreated) io.fs.mkdirSync(workerDir, { recursive: true });
53
+
54
+ const repoBundleDir = resolveRepoBundleDir(io.fs, repoRoot);
55
+ const fromRepo = !!repoBundleDir;
56
+ const installed = [];
57
+ const kept = [];
58
+ const failed = [];
59
+
60
+ for (const f of files) {
61
+ const dest = path.join(workerDir, f);
62
+ if (io.fs.existsSync(dest)) { kept.push(f); continue; }
63
+ if (fromRepo && io.fs.existsSync(path.join(repoBundleDir, f))) {
64
+ io.fs.copyFileSync(path.join(repoBundleDir, f), dest);
65
+ installed.push(f);
66
+ continue;
67
+ }
68
+ if (bundleDir && io.fs.existsSync(path.join(bundleDir, f))) {
69
+ io.fs.copyFileSync(path.join(bundleDir, f), dest);
70
+ installed.push(f);
71
+ continue;
72
+ }
73
+ failed.push(f);
74
+ }
75
+
76
+ if (failed.length > 0) {
77
+ return { status: 'failed', files: installed, files_installed: installed, files_kept: kept, dir_created: dirCreated, reason: `could not obtain bundle files: ${failed.join(', ')} (no repo checkout, no hub bundle)` };
78
+ }
79
+
80
+ // npm dependencies (node-fetch etc.) — best effort, offline-tolerant
81
+ if (installed.includes('package.json')) {
82
+ const r = io.exec('npm', ['install', '--omit=dev', '--no-audit', '--no-fund'], { cwd: workerDir, timeout: 10 * 60 * 1000 });
83
+ if (r.code !== 0 && log) {
84
+ log.warn(`npm install in ${workerDir} failed (worker may still run if deps are cached): ${String(r.stderr).slice(-300)}`);
85
+ }
86
+ }
87
+
88
+ if (log) log.info(`worker bundle deployed at ${workerDir} (${installed.length} files)`);
89
+ return { status: 'installed', files: installed, files_installed: installed, files_kept: kept, dir_created: dirCreated };
90
+ }
91
+
92
+ /** Serialize KEY=value lines. Values are written as given — never logged. */
93
+ function renderEnvLines(values) {
94
+ return Object.entries(values).map(([k, v]) => `${k}=${v}`).join('\n');
95
+ }
96
+
97
+ /**
98
+ * Create or update `.env` with merge semantics:
99
+ * - existing keys are preserved (a valid token is never overwritten);
100
+ * - missing required keys are appended;
101
+ * - chmod 600.
102
+ * @param {object} opts { workerDir, manifest, values: {KEY: value} candidate
103
+ * values for MISSING keys only, log }
104
+ * @returns {{ status, missing_after: string[], preserved: string[] }}
105
+ */
106
+ function configureEnv(io, { workerDir, manifest, values = {}, log = null }) {
107
+ const wb = manifest.worker_bundle || {};
108
+ const required = (wb.env && wb.env.required) || [];
109
+ const envPath = path.join(workerDir, '.env');
110
+
111
+ let existingText = '';
112
+ let existingKeys = [];
113
+ if (io.fs.existsSync(envPath)) {
114
+ existingText = io.fs.readFileSync(envPath, 'utf8');
115
+ existingKeys = parseEnvKeys(existingText);
116
+ }
117
+
118
+ const preserved = [];
119
+ const additions = [];
120
+ for (const key of required) {
121
+ if (existingKeys.includes(key)) {
122
+ preserved.push(key); // merge semantics: never overwrite
123
+ } else if (values[key] !== undefined) {
124
+ additions.push(`${key}=${values[key]}`);
125
+ }
126
+ }
127
+ for (const [key, val] of Object.entries(values)) {
128
+ if (!required.includes(key) && !existingKeys.includes(key)) {
129
+ additions.push(`${key}=${val}`);
130
+ }
131
+ }
132
+
133
+ const missingAfter = required.filter((k) => !existingKeys.includes(k) && values[k] === undefined);
134
+
135
+ const envCreated = !io.fs.existsSync(envPath);
136
+ let text = existingText;
137
+ if (additions.length > 0) {
138
+ if (text && !text.endsWith('\n')) text += '\n';
139
+ text += additions.join('\n') + '\n';
140
+ }
141
+ io.fs.writeFileSync(envPath, text);
142
+ io.fs.chmodSync(envPath, 0o600);
143
+
144
+ if (log) log.info(`.env configured: ${preserved.length} key(s) preserved, ${additions.length} added, ${missingAfter.length} still missing`);
145
+ return { status: missingAfter.length === 0 ? 'configured' : 'incomplete', missing_after: missingAfter, preserved, created: envCreated };
146
+ }
147
+
148
+ /** Derive the backend API base from HUB_URL (…/gpu → …/api/v1). */
149
+ function apiBaseFromHubUrl(hubUrl) {
150
+ return String(hubUrl || '').replace(/\/gpu\/?$/, '') + '/api/v1';
151
+ }
152
+
153
+ /**
154
+ * Verify worker registration against GPU Hub:
155
+ * POST {api}/worker/verify with Authorization: Bearer <token>
156
+ * The token value is used in the request header ONLY.
157
+ * @returns {{ registered, worker_id?, worker_type?, mode?, status_code?, reason? }}
158
+ */
159
+ async function verifyRegistration(io, { hubUrl, token, expectedType = null }) {
160
+ if (!token) {
161
+ return { registered: false, reason: 'no Worker Key provided' };
162
+ }
163
+ const url = `${apiBaseFromHubUrl(hubUrl)}/worker/verify`;
164
+ let res;
165
+ try {
166
+ res = await io.http.fetchJson(url, {
167
+ method: 'POST',
168
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
169
+ body: '{}',
170
+ });
171
+ } catch (err) {
172
+ return { registered: false, reason: `hub unreachable: ${err.message}` };
173
+ }
174
+ if (res.status === 200 && res.json && res.json.verified === true) {
175
+ const typeOk = expectedType ? res.json.worker_type === expectedType : true;
176
+ return {
177
+ registered: true,
178
+ worker_id: res.json.worker_id,
179
+ worker_type: res.json.worker_type,
180
+ mode: res.json.mode,
181
+ type_matches: typeOk,
182
+ };
183
+ }
184
+ if (res.status === 401 || res.status === 403) {
185
+ return { registered: false, status_code: res.status, reason: 'credential rejected (fail-closed) — check the Worker Key; it is shown once at creation/rotation' };
186
+ }
187
+ return { registered: false, status_code: res.status, reason: `unexpected hub response (${res.status})` };
188
+ }
189
+
190
+ /**
191
+ * Local sanity check that the worker CAN start: syntax check + dependency
192
+ * resolution. (Actually starting the infinite worker loop is not part of
193
+ * installation; registration is verified via the hub endpoint.)
194
+ */
195
+ function checkWorkerCanStart(io, { workerDir }) {
196
+ const workerCjs = path.join(workerDir, 'worker.cjs');
197
+ if (!io.fs.existsSync(workerCjs)) return { ok: false, reason: 'worker.cjs missing' };
198
+ const syntax = io.exec('node', ['--check', workerCjs]);
199
+ if (syntax.code !== 0) return { ok: false, reason: `worker.cjs failed syntax check: ${String(syntax.stderr).slice(-200)}` };
200
+ const deps = io.exec('node', ['-e', "require.resolve('node-fetch', { paths: [process.argv[1]] })", workerDir]);
201
+ if (deps.code !== 0) {
202
+ return { ok: false, reason: 'worker npm dependencies missing (run npm install in the worker dir)' };
203
+ }
204
+ return { ok: true };
205
+ }
206
+
207
+ /**
208
+ * Download + verify + extract the hub's full worker bundle (GET
209
+ * /worker-bundle, sha256 published at /worker-bundle/sha256). Returns the
210
+ * extraction dir (`animastor-worker/`) as a copy source for
211
+ * installWorkerBundle — used when the installer runs without a repo
212
+ * checkout (the distributed installer package may not carry bundle files).
213
+ * The caller owns the returned tmpDir and must clean it up.
214
+ * @returns {{ bundleDir, tmpDir } | { bundleDir: null, reason }}
215
+ */
216
+ async function fetchHubWorkerBundle(io, { hubUrl, tmpRoot = null }) {
217
+ if (!hubUrl) return { bundleDir: null, reason: 'no hub URL' };
218
+ if (!io.http || !io.http.download || !io.http.fetchJson || !io.hashFile) {
219
+ return { bundleDir: null, reason: 'io layer cannot download the hub bundle' };
220
+ }
221
+ const base = hubUrl.replace(/\/$/, '');
222
+ const os = require('os');
223
+ const tmpDir = path.join(tmpRoot || os.tmpdir(), `animastor-worker-bundle-${Date.now()}`);
224
+ const tarPath = path.join(tmpDir, 'worker-bundle.tar.gz');
225
+ try {
226
+ const shaRes = await io.http.fetchJson(`${base}/worker-bundle/sha256`);
227
+ io.fs.mkdirSync(tmpDir, { recursive: true });
228
+ const dl = await io.http.download({ url: `${base}/worker-bundle`, dest: tarPath });
229
+ if (dl.status !== 200) {
230
+ return { bundleDir: null, reason: `worker-bundle download failed (HTTP ${dl.status})` };
231
+ }
232
+ if (shaRes.status === 200 && shaRes.json && shaRes.json.sha256) {
233
+ const actual = await io.hashFile(tarPath);
234
+ if (actual !== shaRes.json.sha256) {
235
+ return { bundleDir: null, reason: 'worker-bundle sha256 mismatch — download refused (integrity)' };
236
+ }
237
+ }
238
+ const r = io.exec('tar', ['-xzf', tarPath, '-C', tmpDir]);
239
+ if (r.code !== 0) {
240
+ return { bundleDir: null, reason: `tar extraction failed: ${String(r.stderr || r.error).slice(-200)}` };
241
+ }
242
+ const srcDir = path.join(tmpDir, 'animastor-worker');
243
+ if (!io.fs.isDirectory(srcDir)) {
244
+ return { bundleDir: null, reason: 'worker-bundle layout unexpected (animastor-worker/ missing)' };
245
+ }
246
+ return { bundleDir: srcDir, tmpDir };
247
+ } catch (err) {
248
+ return { bundleDir: null, reason: `worker-bundle fetch failed: ${err && err.message ? err.message : err}` };
249
+ } finally {
250
+ try { if (io.fs.existsSync(tarPath)) io.fs.unlinkSync(tarPath); } catch (_) { /* best effort */ }
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Find a RUNNING worker process for this exact workerDir. Discovery is a
256
+ * platform concern: on Linux `pgrep -f worker.cjs` matches every worker on
257
+ * the host (several users may run one), so the platform adapter confirms
258
+ * each candidate via /proc/<pid>/cwd — the worker always runs with
259
+ * cwd=workerDir. On Windows the managed marker is the pid file written at
260
+ * start (no /proc there). Foreign installations are never returned.
261
+ * @returns {number|null} pid of the running worker in this dir
262
+ */
263
+ function findRunningWorkerPid(io, workerDir, opts = {}) {
264
+ const adapter = adapterOf(opts);
265
+ const pids = adapter.findPidsByCmdlineAndCwd(io, { cmdPattern: 'worker\\.cjs', cwd: workerDir });
266
+ return pids.length > 0 ? pids[0] : null;
267
+ }
268
+
269
+ /**
270
+ * True when .env was modified AFTER the worker process started: the running
271
+ * worker loaded the OLD configuration (its process.env is fixed at startup)
272
+ * and would keep the stale wiring (e.g. the pre-COMFY_PORT default port)
273
+ * forever. Process start time comes from the platform adapter (/proc mtime
274
+ * on Linux, the pid marker on Windows); without any marker the check is
275
+ * inconclusive → false (never kill on a guess).
276
+ */
277
+ function workerEnvIsNewer(io, { workerDir, pid, platformAdapter = null }) {
278
+ try {
279
+ const adapter = platformAdapter || adapterOf({});
280
+ const envM = io.fs.statSync(path.join(workerDir, '.env')).mtimeMs;
281
+ let procM = adapter.processStartMs(io, pid);
282
+ if (procM == null && typeof adapter.workerStartMarkerMs === 'function') {
283
+ procM = adapter.workerStartMarkerMs(io, workerDir);
284
+ }
285
+ if (procM == null) return false;
286
+ return envM > procM + 1000; // 1s tolerance for same-second writes
287
+ } catch (_) {
288
+ return false;
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Start the installed worker as a detached daemon (node worker.cjs). The
294
+ * worker loads its own .env (worker-env.cjs), so no secrets pass through
295
+ * the environment or argv here. Returns whether the process is still alive
296
+ * after a short grace period. Idempotent: a worker already running for this
297
+ * directory is left alone (re-runs must never spawn a second instance).
298
+ * Platform specifics (kill/sleep/alive commands, pid marker) come from the
299
+ * platform adapter — the flow itself is universal.
300
+ */
301
+ function startWorker(io, { workerDir, logFile = null, graceMs = 3000, sleep = null, platformAdapter = null }) {
302
+ const adapter = platformAdapter || adapterOf({});
303
+ const can = checkWorkerCanStart(io, { workerDir });
304
+ if (!can.ok) return { started: false, alive: false, reason: can.reason };
305
+ const existing = findRunningWorkerPid(io, workerDir, { platformAdapter: adapter });
306
+ if (existing && !workerEnvIsNewer(io, { workerDir, pid: existing, platformAdapter: adapter })) {
307
+ return { started: true, already_running: true, pid: existing, alive: true, reason: null };
308
+ }
309
+ if (existing) {
310
+ // .env changed after this worker started — it is running on the OLD
311
+ // configuration (its env is fixed at process start). Restart it so
312
+ // re-runs with a new --comfy-port etc. actually take effect.
313
+ const kc = adapter.killCommand(existing);
314
+ io.exec(kc.cmd, kc.args);
315
+ runSleep(io, adapter, sleep, 1);
316
+ }
317
+ const pid = io.spawnDaemon('node', ['worker.cjs'], {
318
+ cwd: workerDir,
319
+ logFile: logFile || path.join(workerDir, 'worker-installer.log'),
320
+ });
321
+ // Platform post-start bookkeeping (Windows: write the managed pid marker)
322
+ if (typeof adapter.onWorkerSpawned === 'function') {
323
+ try { adapter.onWorkerSpawned(io, { workerDir, pid }); } catch (_) { /* best effort */ }
324
+ }
325
+ // sync grace pause (installer is already a synchronous-step CLI)
326
+ runSleep(io, adapter, sleep, Math.max(1, Math.ceil(graceMs / 1000)));
327
+ let alive;
328
+ if (typeof adapter.checkDaemonAlive === 'function') {
329
+ alive = adapter.checkDaemonAlive(io, { pid, workerDir });
330
+ } else {
331
+ const chkCmd = adapter.psCheckCommand(pid);
332
+ const chk = io.exec(chkCmd.cmd, chkCmd.args);
333
+ alive = chk.code === 0 && /worker\.cjs/.test(chk.stdout);
334
+ }
335
+ return { started: true, pid, alive, reason: alive ? null : 'worker exited immediately — see the log file' };
336
+ }
337
+
338
+ /** Grace sleep through the adapter (test-injectable `sleep` command wins). */
339
+ function runSleep(io, adapter, sleepOverride, seconds) {
340
+ if (sleepOverride) {
341
+ io.exec(sleepOverride, [String(seconds)]);
342
+ return;
343
+ }
344
+ const sc = adapter.sleepCommand(seconds);
345
+ io.exec(sc.cmd, sc.args);
346
+ }
347
+
348
+ /**
349
+ * Uid of a process (platform adapter: /proc stat on Linux, null on Windows)
350
+ * or null when unavailable.
351
+ */
352
+ function pidUid(io, pid, opts = {}) {
353
+ return adapterOf(opts).pidUid(io, pid);
354
+ }
355
+
356
+ /**
357
+ * Stop a RUNNING worker of THIS installation (pid from findRunningWorkerPid,
358
+ * i.e. cwd-verified) and wait for it to exit. Never uses pkill/killall: the
359
+ * pid is addressed directly, and a pid owned by a DIFFERENT account is
360
+ * refused (shared host with several Animastor installations).
361
+ * @returns {{ stopped: boolean, pid: number|null, reason: string|null }}
362
+ */
363
+ async function stopManagedWorker(io, { workerDir, stopTimeoutMs = 15000, pollMs = 300, log = null, platformAdapter = null }) {
364
+ const adapter = platformAdapter || adapterOf({});
365
+ const pid = findRunningWorkerPid(io, workerDir, { platformAdapter: adapter });
366
+ if (!pid) return { stopped: false, pid: null, reason: 'no running worker process found for this installation' };
367
+ const me = currentUid();
368
+ const owner = pidUid(io, pid, { platformAdapter: adapter });
369
+ if (me != null && owner != null && me !== 0 && owner !== me) {
370
+ return { stopped: false, pid, reason: `worker process ${pid} is owned by uid ${owner} — refusing to signal a foreign process` };
371
+ }
372
+ if (log) log.info(`stopping worker (pid ${pid})`);
373
+ try {
374
+ if (typeof io.kill === 'function') io.kill(pid, 'SIGTERM');
375
+ else process.kill(pid, 'SIGTERM');
376
+ } catch (_) {
377
+ return { stopped: true, pid, reason: null }; // already gone
378
+ }
379
+ const alive = () => { try { process.kill(pid, 0); return true; } catch (_) { return false; } };
380
+ const deadline = (io.now ? io.now() : Date.now()) + stopTimeoutMs;
381
+ while (alive() && (io.now ? io.now() : Date.now()) < deadline) {
382
+ await new Promise((r) => setTimeout(r, pollMs));
383
+ }
384
+ if (alive()) {
385
+ try { if (typeof io.kill === 'function') io.kill(pid, 'SIGKILL'); else process.kill(pid, 'SIGKILL'); } catch (_) { /* gone */ }
386
+ }
387
+ return { stopped: true, pid, reason: null };
388
+ }
389
+
390
+ /**
391
+ * Restart the managed worker of THIS installation: stop the running process
392
+ * (cwd-verified, uid-guarded — a foreign worker is never signaled), then
393
+ * start a fresh one via startWorker (which is idempotent, refuses a broken
394
+ * bundle, and reports liveness after a grace period). Also used when the
395
+ * worker is already stopped: the stop step is skipped and it is just started.
396
+ * @returns {{ restarted: boolean, previously_running: boolean, pid: number|null,
397
+ * alive: boolean, reason: string|null }}
398
+ */
399
+ async function restartManagedWorker(io, { workerDir, log = null, stopTimeoutMs = 15000, pollMs = 300, graceMs = 3000, platformAdapter = null }) {
400
+ const previouslyRunning = !!findRunningWorkerPid(io, workerDir, { platformAdapter });
401
+ if (previouslyRunning) {
402
+ const stop = await stopManagedWorker(io, { workerDir, stopTimeoutMs, pollMs, log, platformAdapter });
403
+ if (!stop.stopped) {
404
+ return { restarted: false, previously_running: true, pid: stop.pid, alive: false, reason: stop.reason };
405
+ }
406
+ }
407
+ const start = startWorker(io, { workerDir, graceMs, log, platformAdapter });
408
+ if (!start.started) {
409
+ return { restarted: true, previously_running: previouslyRunning, pid: null, alive: false, reason: start.reason };
410
+ }
411
+ if (start.already_running) {
412
+ return { restarted: false, previously_running: true, pid: start.pid, alive: true, reason: null };
413
+ }
414
+ return { restarted: true, previously_running: previouslyRunning, pid: start.pid, alive: start.alive, reason: start.reason };
415
+ }
416
+
417
+ module.exports = {
418
+ installWorkerBundle,
419
+ fetchHubWorkerBundle,
420
+ startWorker,
421
+ stopManagedWorker,
422
+ restartManagedWorker,
423
+ findRunningWorkerPid,
424
+ workerEnvIsNewer,
425
+ configureEnv,
426
+ apiBaseFromHubUrl,
427
+ verifyRegistration,
428
+ checkWorkerCanStart,
429
+ renderEnvLines,
430
+ };
@@ -0,0 +1,153 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Baseline workflow installation — Private Worker Installer Phase 2.
5
+ *
6
+ * A baseline workflow is an EDITABLE starting point:
7
+ * - downloaded only when absent at the baseline path;
8
+ * - an existing user file is NEVER overwritten (even if it differs);
9
+ * - a fresh official copy can be written to a distinct path
10
+ * (*.animastor-baseline.json) on explicit request;
11
+ * - after writing: JSON must parse, sha256 must match the manifest
12
+ * baseline_sha256, and the file must be at the expected path
13
+ * (tmp file + atomic rename).
14
+ *
15
+ * Sources (in order, never invented):
16
+ * 1. repository_path — when the installer runs from an Animastor repo
17
+ * checkout (the canonical production file);
18
+ * 2. endpoint — GET {HUB_URL}/workflow/<id>, if the hub provides it;
19
+ * otherwise BLOCKED.
20
+ */
21
+
22
+ const path = require('path');
23
+ const { baselineTargetPath, freshCopyPath, listProfileWorkflows } = require('../workflow-artifacts');
24
+
25
+ function findWorkflowArtifact(manifests, wfId) {
26
+ for (const m of manifests) {
27
+ const wf = listProfileWorkflows(m).find((w) => w.id === wfId);
28
+ if (wf) return wf;
29
+ }
30
+ return null;
31
+ }
32
+
33
+ async function readCanonicalContent(io, { wf, repoRoot, hubUrl, httpFetchText, log = null }) {
34
+ if (wf.source && wf.source.repository_path && repoRoot) {
35
+ // Two layouts carry the canonical workflows:
36
+ // dev checkout — <repoRoot>/backend/ai/workflows/...
37
+ // tarball — <repoRoot>/animastor-installer/backend/ai/workflows/...
38
+ // (REPO_ROOT resolves to the extraction PARENT when cli.js runs from
39
+ // <extract>/animastor-installer/src/installer — hence the second candidate)
40
+ for (const abs of [
41
+ path.join(repoRoot, wf.source.repository_path),
42
+ path.join(repoRoot, 'animastor-installer', wf.source.repository_path),
43
+ ]) {
44
+ if (io.fs.existsSync(abs)) {
45
+ return { content: io.fs.readFileSync(abs, 'utf8'), origin: `repository ${path.relative(repoRoot, abs)}` };
46
+ }
47
+ }
48
+ }
49
+ if (wf.source && wf.source.endpoint && hubUrl && httpFetchText) {
50
+ // Manifest endpoints carry an HTTP method prefix ("GET {HUB_URL}/workflow/x");
51
+ // fetch() needs the bare URL. Strip it, substitute {HUB_URL}, and never let a
52
+ // network failure crash the whole workflow step — fall through to "blocked".
53
+ let url = String(wf.source.endpoint).replace(/^[A-Za-z]+\s+/, '');
54
+ url = url.replace('{HUB_URL}', hubUrl.replace(/\/$/, ''));
55
+ try {
56
+ const res = await httpFetchText(url);
57
+ if (res && res.status === 200 && res.text) {
58
+ return { content: res.text, origin: url };
59
+ }
60
+ if (log) log.warn(`hub workflow endpoint ${url} returned status ${res ? res.status : 'no response'}`);
61
+ } catch (err) {
62
+ if (log) log.warn(`hub workflow endpoint ${url} unreachable: ${err.message}`);
63
+ }
64
+ }
65
+ return null;
66
+ }
67
+
68
+ /**
69
+ * Install baseline workflows per the plan step.
70
+ * @param {object} io
71
+ * @param {object} opts { root, manifests, planStep, repoRoot, hubUrl, crypto, log }
72
+ * @returns array of per-workflow results
73
+ */
74
+ async function installWorkflows(io, opts) {
75
+ const { root, manifests, planStep, repoRoot = null, hubUrl = null, crypto = null, log = null } = opts;
76
+ const results = [];
77
+ const items = (planStep.action && planStep.action.items) || [];
78
+
79
+ for (const item of items) {
80
+ const wf = findWorkflowArtifact(manifests, item.id);
81
+ if (!wf) {
82
+ results.push({ id: item.id, status: 'blocked', reason: 'workflow artifact not found in any manifest' });
83
+ continue;
84
+ }
85
+ const relTarget = item.target_path || (item.fresh_copy ? freshCopyPath(wf) : baselineTargetPath(wf));
86
+ const absTarget = path.join(root, relTarget);
87
+
88
+ if (io.fs.existsSync(absTarget)) {
89
+ results.push({
90
+ id: item.id,
91
+ status: 'kept',
92
+ target_path: relTarget,
93
+ reason: 'target already exists — never overwritten',
94
+ });
95
+ continue;
96
+ }
97
+
98
+ const canonical = await readCanonicalContent(io, { wf, repoRoot, hubUrl, httpFetchText: opts.httpFetchText, log });
99
+ if (!canonical) {
100
+ results.push({
101
+ id: item.id,
102
+ status: 'blocked',
103
+ reason: 'canonical workflow source is not available on this machine (no repo checkout, hub endpoint unreachable) — nothing was invented',
104
+ });
105
+ continue;
106
+ }
107
+
108
+ // validate BEFORE writing anything
109
+ let parsed;
110
+ try {
111
+ parsed = JSON.parse(canonical.content);
112
+ } catch (err) {
113
+ results.push({ id: item.id, status: 'failed', reason: `canonical workflow is not valid JSON: ${err.message}` });
114
+ continue;
115
+ }
116
+ if (!parsed || typeof parsed !== 'object') {
117
+ results.push({ id: item.id, status: 'failed', reason: 'canonical workflow JSON is empty' });
118
+ continue;
119
+ }
120
+
121
+ if (crypto && wf.baseline_sha256) {
122
+ const actual = crypto.createHash('sha256').update(Buffer.from(canonical.content)).digest('hex');
123
+ if (actual.toLowerCase() !== String(wf.baseline_sha256).toLowerCase()) {
124
+ results.push({
125
+ id: item.id,
126
+ status: 'failed',
127
+ reason: `canonical content sha256 ${actual.slice(0, 12)}… does not match manifest baseline ${String(wf.baseline_sha256).slice(0, 12)}… — manifest revision required`,
128
+ });
129
+ continue;
130
+ }
131
+ }
132
+
133
+ const dir = path.dirname(absTarget);
134
+ if (!io.fs.existsSync(dir)) io.fs.mkdirSync(dir, { recursive: true });
135
+ const tmp = `${absTarget}.tmp`;
136
+ io.fs.writeFileSync(tmp, canonical.content);
137
+ io.fs.renameSync(tmp, absTarget); // atomic publish
138
+
139
+ if (log) log.info(`baseline workflow installed: ${relTarget} (${canonical.origin})`);
140
+ results.push({
141
+ id: item.id,
142
+ status: item.fresh_copy ? 'fresh-copy-installed' : 'installed',
143
+ target_path: relTarget,
144
+ grade: 'sha256-verified',
145
+ });
146
+ }
147
+ return results;
148
+ }
149
+
150
+ module.exports = {
151
+ installWorkflows,
152
+ readCanonicalContent,
153
+ };
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Installer tooling index — Private Worker Installer Phase 1 / Phase 1.5.
5
+ *
6
+ * Read-only architecture foundation: canonical install manifests,
7
+ * compatibility resolver, workflow artifacts, download planner, interactive
8
+ * install plan, safety rules, and verification reporting.
9
+ *
10
+ * No installation is performed here; see
11
+ * docs/04-planning/private-worker-installer-phase15.md
12
+ *
13
+ * PUBLIC API of @animastor/installer — this is the ONLY supported entry
14
+ * point for host consumers (e.g. backend routes). Internal paths
15
+ * (src/installer/<module>) are not part of the package contract.
16
+ */
17
+
18
+ const manifest = require('./install-manifest');
19
+ const resolver = require('./compatibility-resolver');
20
+ const workflows = require('./workflow-artifacts');
21
+ const downloads = require('./download-planner');
22
+ const plan = require('./install-plan');
23
+ const safety = require('./safety-rules');
24
+ const verification = require('./verification-report');
25
+ const engine = require('./engine/engine');
26
+ const uninstaller = require('./uninstaller');
27
+ const setupContract = require('./setup-contract');
28
+
29
+ module.exports = {
30
+ manifest,
31
+ resolver,
32
+ workflows,
33
+ downloads,
34
+ plan,
35
+ safety,
36
+ verification,
37
+ engine,
38
+ uninstaller,
39
+ setupContract,
40
+ };