@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.
@@ -45,7 +45,65 @@ function findWorkerManifest(manifests, workerEntryId) {
45
45
  * already on disk and were kept (files_kept).
46
46
  * @returns {{ status, files, files_installed, files_kept, dir_created, reason? }}
47
47
  */
48
- function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleDir = null, hubUrl = null, httpFetchText = null, log = null }) {
48
+ function readPkgVersion(io, dir) {
49
+ try {
50
+ const pkg = JSON.parse(io.fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
51
+ return typeof pkg.version === 'string' ? pkg.version : null;
52
+ } catch (_) {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ /** Runtime dependencies declared by a bundle's package.json ({} when none). */
58
+ function declaredDependencies(io, dir) {
59
+ try {
60
+ const pkg = JSON.parse(io.fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
61
+ return pkg && pkg.dependencies && typeof pkg.dependencies === 'object' ? pkg.dependencies : {};
62
+ } catch (_) {
63
+ return {};
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Install the bundle's runtime dependencies with `npm ci` — ONLY when the
69
+ * bundle declares any. The canonical worker bundle is zero-dependency (Node
70
+ * 20 global fetch), so this is normally a no-op; it exists so a future
71
+ * bundle with dependencies can never be deployed half-installed. npm next to
72
+ * the chosen node binary is preferred (same runtime the worker runs with).
73
+ * Throws with the npm output tail on failure — never a silent warning.
74
+ * @returns {{ ran: boolean, deps: string[] }}
75
+ */
76
+ function ensureWorkerDependencies(io, { workerDir, nodeBin = null }) {
77
+ const deps = Object.keys(declaredDependencies(io, workerDir));
78
+ if (deps.length === 0) return { ran: false, deps };
79
+ const npmNextToNode = nodeBin && path.isAbsolute(nodeBin) ? path.join(path.dirname(nodeBin), 'npm') : null;
80
+ const npm = npmNextToNode && io.fs.existsSync(npmNextToNode) ? npmNextToNode : 'npm';
81
+ const args = io.fs.existsSync(path.join(workerDir, 'package-lock.json'))
82
+ ? ['ci', '--omit=dev', '--no-audit', '--no-fund']
83
+ : ['install', '--omit=dev', '--no-audit', '--no-fund'];
84
+ const r = io.exec(npm, args, { cwd: workerDir, timeout: 10 * 60 * 1000 });
85
+ if (r.code !== 0) {
86
+ throw new Error(`${npm} ${args[0]} in ${workerDir} failed: ${String(r.stderr || r.stdout || '').trim().slice(-300)}`);
87
+ }
88
+ return { ran: true, deps };
89
+ }
90
+
91
+ /**
92
+ * Deploy the worker bundle into workerDir.
93
+ * Source order (never invented): a repo checkout bundle first — canonical
94
+ * `packages/animastor-worker/worker/`, legacy `worker/worker/` (pre-
95
+ * relocation checkouts; see installer/worker-bundle-source.js) — then an
96
+ * explicit `bundleDir` (a verified hub worker-bundle tarball the engine
97
+ * extracted beforehand). If both fail, the install returns status 'failed'.
98
+ * A bundle whose version differs from the source is UPDATED (bundle files
99
+ * only — .env and logs are never touched) when `update` is true; otherwise
100
+ * present files are kept.
101
+ * Ownership details are returned for the uninstall manifest: dir_created,
102
+ * files the installer actually copied (files_installed) vs files that were
103
+ * already on disk and were kept (files_kept).
104
+ * @returns {{ status, files, files_installed, files_kept, dir_created, updated_from?, reason? }}
105
+ */
106
+ function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleDir = null, hubUrl = null, httpFetchText = null, log = null, update = true, nodeBin = null }) {
49
107
  const wb = manifest.worker_bundle || {};
50
108
  const files = wb.files || [];
51
109
  const dirCreated = !io.fs.existsSync(workerDir);
@@ -53,13 +111,17 @@ function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleD
53
111
 
54
112
  const repoBundleDir = resolveRepoBundleDir(io.fs, repoRoot);
55
113
  const fromRepo = !!repoBundleDir;
114
+ const sourceDir = fromRepo ? repoBundleDir : bundleDir;
115
+ const installedVersion = readPkgVersion(io, workerDir);
116
+ const sourceVersion = sourceDir ? readPkgVersion(io, sourceDir) : null;
117
+ const outdated = !dirCreated && update && !!installedVersion && !!sourceVersion && installedVersion !== sourceVersion;
56
118
  const installed = [];
57
119
  const kept = [];
58
120
  const failed = [];
59
121
 
60
122
  for (const f of files) {
61
123
  const dest = path.join(workerDir, f);
62
- if (io.fs.existsSync(dest)) { kept.push(f); continue; }
124
+ if (io.fs.existsSync(dest) && !outdated) { kept.push(f); continue; }
63
125
  if (fromRepo && io.fs.existsSync(path.join(repoBundleDir, f))) {
64
126
  io.fs.copyFileSync(path.join(repoBundleDir, f), dest);
65
127
  installed.push(f);
@@ -70,6 +132,7 @@ function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleD
70
132
  installed.push(f);
71
133
  continue;
72
134
  }
135
+ if (io.fs.existsSync(dest)) { kept.push(f); continue; }
73
136
  failed.push(f);
74
137
  }
75
138
 
@@ -77,16 +140,18 @@ function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleD
77
140
  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
141
  }
79
142
 
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
- }
143
+ const deps = ensureWorkerDependencies(io, { workerDir, nodeBin });
144
+ if (deps.ran && log) log.info(`worker dependencies installed (${deps.deps.join(', ')})`);
87
145
 
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 };
146
+ if (log) {
147
+ if (outdated) log.info(`worker bundle updated ${installedVersion} → ${sourceVersion} at ${workerDir} (.env kept)`);
148
+ else log.info(`worker bundle deployed at ${workerDir} (${installed.length} files)`);
149
+ }
150
+ return {
151
+ status: 'installed', files: installed, files_installed: installed, files_kept: kept, dir_created: dirCreated,
152
+ version: readPkgVersion(io, workerDir),
153
+ ...(outdated ? { updated_from: installedVersion } : {}),
154
+ };
90
155
  }
91
156
 
92
157
  /** Serialize KEY=value lines. Values are written as given — never logged. */
@@ -98,14 +163,20 @@ function renderEnvLines(values) {
98
163
  * Create or update `.env` with merge semantics:
99
164
  * - existing keys are preserved (a valid token is never overwritten);
100
165
  * - missing required keys are appended;
166
+ * - `overrides` REPLACE the value of existing non-secret keys (installer-
167
+ * owned wiring the user agreed to fix: WORKER_TYPE, COMFY_URL, NODE_BIN…)
168
+ * and are appended when absent. Secret keys are only overridden through
169
+ * an explicit `secretOverrides` (a new Worker Key typed by the user after
170
+ * the old one was rejected);
101
171
  * - chmod 600.
102
172
  * @param {object} opts { workerDir, manifest, values: {KEY: value} candidate
103
- * values for MISSING keys only, log }
104
- * @returns {{ status, missing_after: string[], preserved: string[] }}
173
+ * values for MISSING keys only, overrides, secretOverrides, log }
174
+ * @returns {{ status, missing_after: string[], preserved: string[], changed: string[] }}
105
175
  */
106
- function configureEnv(io, { workerDir, manifest, values = {}, log = null }) {
176
+ function configureEnv(io, { workerDir, manifest, values = {}, overrides = {}, secretOverrides = {}, log = null }) {
107
177
  const wb = manifest.worker_bundle || {};
108
178
  const required = (wb.env && wb.env.required) || [];
179
+ const secretKeys = (wb.env && wb.env.secrets) || ['ANIMASTOR_WORKER_TOKEN'];
109
180
  const envPath = path.join(workerDir, '.env');
110
181
 
111
182
  let existingText = '';
@@ -115,25 +186,55 @@ function configureEnv(io, { workerDir, manifest, values = {}, log = null }) {
115
186
  existingKeys = parseEnvKeys(existingText);
116
187
  }
117
188
 
118
- const preserved = [];
189
+ const replace = {};
190
+ for (const [k, v] of Object.entries(overrides || {})) {
191
+ if (v === undefined || v === null || secretKeys.includes(k)) continue;
192
+ replace[k] = String(v);
193
+ }
194
+ for (const [k, v] of Object.entries(secretOverrides || {})) {
195
+ if (v) replace[k] = String(v);
196
+ }
197
+
198
+ const changed = [];
199
+ let text = existingText;
200
+ if (Object.keys(replace).length > 0 && text) {
201
+ text = text.split('\n').map((line) => {
202
+ const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(line);
203
+ if (!m || replace[m[1]] === undefined) return line;
204
+ const current = m[2].trim().replace(/^["']|["']$/g, '');
205
+ if (current === replace[m[1]]) return line;
206
+ changed.push(m[1]);
207
+ return `${m[1]}=${replace[m[1]]}`;
208
+ }).join('\n');
209
+ }
210
+
211
+ // Merge semantics: EVERY key of the existing .env that this run did not
212
+ // change is preserved — the log line must show the real numbers (a re-run
213
+ // over a configured worker used to report "0 key(s) preserved" because
214
+ // only manifest-required keys were counted).
215
+ const preserved = existingKeys.filter((k) => !changed.includes(k));
119
216
  const additions = [];
217
+ const added = new Set();
218
+ const add = (key, val) => { if (!added.has(key)) { additions.push(`${key}=${val}`); added.add(key); } };
120
219
  for (const key of required) {
121
220
  if (existingKeys.includes(key)) {
122
- preserved.push(key); // merge semantics: never overwrite
221
+ // already preserved above (merge semantics: never overwrite)
222
+ } else if (replace[key] !== undefined) {
223
+ add(key, replace[key]);
123
224
  } else if (values[key] !== undefined) {
124
- additions.push(`${key}=${values[key]}`);
225
+ add(key, values[key]);
125
226
  }
126
227
  }
127
228
  for (const [key, val] of Object.entries(values)) {
128
- if (!required.includes(key) && !existingKeys.includes(key)) {
129
- additions.push(`${key}=${val}`);
130
- }
229
+ if (!required.includes(key) && !existingKeys.includes(key) && replace[key] === undefined) add(key, val);
230
+ }
231
+ for (const [key, val] of Object.entries(replace)) {
232
+ if (!existingKeys.includes(key)) add(key, val);
131
233
  }
132
234
 
133
- const missingAfter = required.filter((k) => !existingKeys.includes(k) && values[k] === undefined);
235
+ const missingAfter = required.filter((k) => !existingKeys.includes(k) && !added.has(k));
134
236
 
135
237
  const envCreated = !io.fs.existsSync(envPath);
136
- let text = existingText;
137
238
  if (additions.length > 0) {
138
239
  if (text && !text.endsWith('\n')) text += '\n';
139
240
  text += additions.join('\n') + '\n';
@@ -141,8 +242,41 @@ function configureEnv(io, { workerDir, manifest, values = {}, log = null }) {
141
242
  io.fs.writeFileSync(envPath, text);
142
243
  io.fs.chmodSync(envPath, 0o600);
143
244
 
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 };
245
+ if (log) log.info(`.env configured: ${preserved.length} key(s) preserved, ${additions.length} added, ${changed.length} updated${changed.length ? ` (${changed.join(', ')})` : ''}, ${missingAfter.length} still missing`);
246
+ return { status: missingAfter.length === 0 ? 'configured' : 'incomplete', missing_after: missingAfter, preserved, changed, added: Array.from(added), created: envCreated };
247
+ }
248
+
249
+ /**
250
+ * True when the worker .env already holds a NON-EMPTY value for `key`.
251
+ * Only a boolean is returned — the value itself is never read out of .env,
252
+ * so a Worker Key can never leak through this check (re-installs therefore
253
+ * never ask for a key that is already there).
254
+ */
255
+ function hasEnvKey(io, workerDir, key) {
256
+ try {
257
+ const text = String(io.fs.readFileSync(path.join(workerDir, '.env'), 'utf8'));
258
+ for (const raw of text.split('\n')) {
259
+ const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(raw);
260
+ if (!m || m[1] !== key) continue;
261
+ const value = m[2].trim().replace(/^["']|[\"']$/g, '');
262
+ if (value) return true;
263
+ }
264
+ } catch (_) { /* no .env */ }
265
+ return false;
266
+ }
267
+
268
+ /** Read non-secret KEY=value pairs from the worker .env (secret keys skipped). */
269
+ function readEnvValues(io, workerDir, { skip = ['ANIMASTOR_WORKER_TOKEN'] } = {}) {
270
+ const out = {};
271
+ try {
272
+ const text = io.fs.readFileSync(path.join(workerDir, '.env'), 'utf8');
273
+ for (const raw of text.split('\n')) {
274
+ const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(raw);
275
+ if (!m || skip.includes(m[1])) continue;
276
+ out[m[1]] = m[2].trim().replace(/^["']|["']$/g, '');
277
+ }
278
+ } catch (_) { /* no .env */ }
279
+ return out;
146
280
  }
147
281
 
148
282
  /** Derive the backend API base from HUB_URL (…/gpu → …/api/v1). */
@@ -188,18 +322,22 @@ async function verifyRegistration(io, { hubUrl, token, expectedType = null }) {
188
322
  }
189
323
 
190
324
  /**
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.)
325
+ * Local sanity check that the worker CAN start: syntax check with the node
326
+ * binary that will run it + resolution of the dependencies the bundle
327
+ * DECLARES (the canonical bundle declares none — the old hard-coded
328
+ * node-fetch probe made every zero-dependency install "unstartable").
194
329
  */
195
- function checkWorkerCanStart(io, { workerDir }) {
330
+ function checkWorkerCanStart(io, { workerDir, nodeBin = 'node' }) {
196
331
  const workerCjs = path.join(workerDir, 'worker.cjs');
197
332
  if (!io.fs.existsSync(workerCjs)) return { ok: false, reason: 'worker.cjs missing' };
198
- const syntax = io.exec('node', ['--check', workerCjs]);
333
+ const syntax = io.exec(nodeBin, ['--check', workerCjs]);
199
334
  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)' };
335
+ const deps = Object.keys(declaredDependencies(io, workerDir));
336
+ if (deps.length > 0) {
337
+ const r = io.exec(nodeBin, ['-e', 'for (const d of process.argv.slice(2)) require.resolve(d, { paths: [process.cwd()] })', ...deps], { cwd: workerDir });
338
+ if (r.code !== 0) {
339
+ return { ok: false, reason: `worker dependencies missing (${deps.join(', ')}) — run: cd ${workerDir} && npm ci --omit=dev` };
340
+ }
203
341
  }
204
342
  return { ok: true };
205
343
  }
@@ -278,7 +416,10 @@ function workerEnvIsNewer(io, { workerDir, pid, platformAdapter = null }) {
278
416
  try {
279
417
  const adapter = platformAdapter || adapterOf({});
280
418
  const envM = io.fs.statSync(path.join(workerDir, '.env')).mtimeMs;
281
- let procM = adapter.processStartMs(io, pid);
419
+ // Most reliable marker: logs/worker.pid written at start (by this
420
+ // installer and by start-worker.sh) — its mtime IS the start time.
421
+ let procM = pidFileStartMs(io, workerDir, pid);
422
+ if (procM == null) procM = adapter.processStartMs(io, pid);
282
423
  if (procM == null && typeof adapter.workerStartMarkerMs === 'function') {
283
424
  procM = adapter.workerStartMarkerMs(io, workerDir);
284
425
  }
@@ -289,22 +430,82 @@ function workerEnvIsNewer(io, { workerDir, pid, platformAdapter = null }) {
289
430
  }
290
431
  }
291
432
 
433
+ /** Default worker log: <install base>/logs/worker.log (same file start-worker.sh uses). */
434
+ function workerLogPath(workerDir) {
435
+ return path.join(path.dirname(workerDir), 'logs', 'worker.log');
436
+ }
437
+
438
+ /**
439
+ * Node binary for the worker: NODE_BIN from .env when it exists and is >= 20,
440
+ * else the node running this installer (>= 20, verified by the bootstrap).
441
+ */
442
+ function resolveWorkerNode(io, workerDir) {
443
+ const fromEnv = readEnvValues(io, workerDir).NODE_BIN || null;
444
+ if (fromEnv && io.fs.existsSync(fromEnv)) {
445
+ const r = io.exec(fromEnv, ['--version']);
446
+ const m = /^v?(\d+)/.exec(String(r.stdout || '').trim());
447
+ if (r.code === 0 && m && Number(m[1]) >= 20) return fromEnv;
448
+ }
449
+ return process.execPath;
450
+ }
451
+
452
+ /**
453
+ * Environment for the spawned worker: the installer's own environment minus
454
+ * the worker configuration keys — the worker reads them from its .env, and a
455
+ * stray exported WORKER_TYPE/HUB_URL/COMFY_PORT in the installer's shell must
456
+ * never override the configuration that was just written (real env wins
457
+ * over .env inside the worker).
458
+ */
459
+ const WORKER_ENV_KEYS = Object.freeze([
460
+ 'HUB_URL', 'WORKER_TYPE', 'WORKER_ID', 'COMFY_PORT', 'COMFY_URL', 'NOTEBOOK_PATH',
461
+ 'COMFY_INPUT_DIR', 'ANIMASTOR_WORKER_TOKEN', 'ANIMASTOR_API_URL', 'NODE_BIN',
462
+ ]);
463
+ function workerSpawnEnv(base = process.env) {
464
+ const env = { ...base };
465
+ for (const k of WORKER_ENV_KEYS) delete env[k];
466
+ return env;
467
+ }
468
+
469
+ /** <base>/logs/worker.pid — written on every worker start. */
470
+ function workerPidFile(workerDir) {
471
+ return path.join(path.dirname(workerDir), 'logs', 'worker.pid');
472
+ }
473
+
474
+ /** Start time (pid file mtime) when the pid file names `pid`, else null. */
475
+ function pidFileStartMs(io, workerDir, pid) {
476
+ try {
477
+ const f = workerPidFile(workerDir);
478
+ if (!io.fs.existsSync(f)) return null;
479
+ if (Number(String(io.fs.readFileSync(f, 'utf8')).trim()) !== Number(pid)) return null;
480
+ const st = io.fs.statSync(f);
481
+ return typeof st.mtimeMs === 'number' ? st.mtimeMs : null;
482
+ } catch (_) {
483
+ return null;
484
+ }
485
+ }
486
+
292
487
  /**
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
488
+ * Start the installed worker as a detached daemon (<NODE_BIN> worker.cjs).
489
+ * The worker loads its own .env (worker-env.cjs), so no secrets pass through
295
490
  * 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.
491
+ * after a short grace period, plus the log file and the byte offset where
492
+ * THIS start's output begins (readiness is judged from there).
493
+ * Idempotent: a worker already running for this directory is left alone
494
+ * (re-runs must never spawn a second instance) unless .env changed after it
495
+ * started. Platform specifics (kill/sleep/alive commands, pid marker) come
496
+ * from the platform adapter — the flow itself is universal.
300
497
  */
301
- function startWorker(io, { workerDir, logFile = null, graceMs = 3000, sleep = null, platformAdapter = null }) {
498
+ function startWorker(io, { workerDir, nodeBin = null, logFile = null, graceMs = 3000, sleep = null, platformAdapter = null, forceRestart = false }) {
302
499
  const adapter = platformAdapter || adapterOf({});
303
- const can = checkWorkerCanStart(io, { workerDir });
304
- if (!can.ok) return { started: false, alive: false, reason: can.reason };
500
+ const node = nodeBin || resolveWorkerNode(io, workerDir);
501
+ const log = logFile || workerLogPath(workerDir);
502
+ const can = checkWorkerCanStart(io, { workerDir, nodeBin: node });
503
+ if (!can.ok) return { started: false, alive: false, reason: can.reason, logFile: log };
305
504
  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 };
505
+ // forceRestart: the caller just changed .env/the bundle — a running worker
506
+ // holds the OLD configuration (process env is fixed at start).
507
+ if (existing && !forceRestart && !workerEnvIsNewer(io, { workerDir, pid: existing, platformAdapter: adapter })) {
508
+ return { started: true, already_running: true, pid: existing, alive: true, reason: null, logFile: log, logOffset: null };
308
509
  }
309
510
  if (existing) {
310
511
  // .env changed after this worker started — it is running on the OLD
@@ -314,14 +515,19 @@ function startWorker(io, { workerDir, logFile = null, graceMs = 3000, sleep = nu
314
515
  io.exec(kc.cmd, kc.args);
315
516
  runSleep(io, adapter, sleep, 1);
316
517
  }
317
- const pid = io.spawnDaemon('node', ['worker.cjs'], {
518
+ try { io.fs.mkdirSync(path.dirname(log), { recursive: true }); } catch (_) { /* exists */ }
519
+ let logOffset = 0;
520
+ try { logOffset = io.fs.existsSync(log) ? io.fs.statSync(log).size : 0; } catch (_) { logOffset = 0; }
521
+ const pid = io.spawnDaemon(node, ['worker.cjs'], {
318
522
  cwd: workerDir,
319
- logFile: logFile || path.join(workerDir, 'worker-installer.log'),
523
+ logFile: log,
524
+ env: workerSpawnEnv(),
320
525
  });
321
526
  // Platform post-start bookkeeping (Windows: write the managed pid marker)
322
527
  if (typeof adapter.onWorkerSpawned === 'function') {
323
528
  try { adapter.onWorkerSpawned(io, { workerDir, pid }); } catch (_) { /* best effort */ }
324
529
  }
530
+ try { io.fs.writeFileSync(workerPidFile(workerDir), `${pid}\n`); } catch (_) { /* best effort */ }
325
531
  // sync grace pause (installer is already a synchronous-step CLI)
326
532
  runSleep(io, adapter, sleep, Math.max(1, Math.ceil(graceMs / 1000)));
327
533
  let alive;
@@ -332,7 +538,122 @@ function startWorker(io, { workerDir, logFile = null, graceMs = 3000, sleep = nu
332
538
  const chk = io.exec(chkCmd.cmd, chkCmd.args);
333
539
  alive = chk.code === 0 && /worker\.cjs/.test(chk.stdout);
334
540
  }
335
- return { started: true, pid, alive, reason: alive ? null : 'worker exited immediately — see the log file' };
541
+ return { started: true, pid, alive, reason: alive ? null : `worker exited immediately — see ${log}`, logFile: log, logOffset };
542
+ }
543
+
544
+ /**
545
+ * Classify a worker log excerpt (the output of ONE worker start: everything
546
+ * after the last "Worker <type> started" line). Pure — shared by the
547
+ * installer, `animastor start/status/doctor` and tests.
548
+ * Markers (worker.cjs >= 2.2.0; "ComfyUI ready" exists in every version):
549
+ * comfy_ready — "ComfyUI ready"
550
+ * heartbeat — "Hub heartbeat accepted"
551
+ * auth_failed — "Worker authentication failed"
552
+ * @returns {{ comfy_ready, heartbeat, auth_failed, crashed, last_comfy_error, last_beacon_error, last_lines }}
553
+ */
554
+ function scanWorkerLog(text) {
555
+ const all = String(text || '').split('\n');
556
+ let start = 0;
557
+ all.forEach((l, i) => { if (/\] Worker \S+ started/.test(l)) start = i; });
558
+ const lines = all.slice(start);
559
+ const find = (re) => lines.some((l) => re.test(l));
560
+ const last = (re) => {
561
+ for (let i = lines.length - 1; i >= 0; i--) if (re.test(lines[i])) return lines[i];
562
+ return null;
563
+ };
564
+ const comfyErr = last(/ComfyUI not ready/);
565
+ const lastIdx = (re) => { for (let i = lines.length - 1; i >= 0; i--) if (re.test(lines[i])) return i; return -1; };
566
+ const beaconErrIdx = lastIdx(/Beacon failed/);
567
+ return {
568
+ comfy_ready: find(/ComfyUI ready/),
569
+ // ONLINE now = the latest heartbeat marker is newer than the latest
570
+ // beacon failure (the worker re-logs the marker after a recovery).
571
+ heartbeat: lastIdx(/Hub heartbeat accepted/) > beaconErrIdx,
572
+ auth_failed: find(/Worker authentication failed/),
573
+ crashed: find(/Worker crashed/),
574
+ last_comfy_error: comfyErr ? comfyErr.replace(/^\[[^\]]*\]\s*\[[^\]]*\]\s*/, '') : null,
575
+ last_beacon_error: beaconErrIdx >= 0 ? (lines[beaconErrIdx + 1] || lines[beaconErrIdx]).trim() : null,
576
+ last_lines: lines.filter(Boolean).slice(-8),
577
+ };
578
+ }
579
+
580
+ function readLogFrom(io, logFile, offset) {
581
+ try {
582
+ const text = String(io.fs.readFileSync(logFile, 'utf8'));
583
+ return offset ? Buffer.from(text).subarray(offset).toString('utf8') : text;
584
+ } catch (_) {
585
+ return '';
586
+ }
587
+ }
588
+
589
+ /**
590
+ * Wait until the worker proves it is serving, judged from ITS OWN log:
591
+ * 1. "ComfyUI ready" (worker reached the ComfyUI API) — within comfyTimeoutMs
592
+ * 2. "Hub heartbeat accepted" (the hub recorded the heartbeat → Animastor
593
+ * shows ONLINE) — within heartbeatTimeoutMs after 1
594
+ * Stops early when the process died or authentication failed.
595
+ * @returns {Promise<{ comfy_ready, heartbeat, auth_failed, exited, reason, logFile, scan }>}
596
+ */
597
+ async function waitForWorkerReady(io, { workerDir, pid = null, logFile = null, logOffset = 0, comfyTimeoutMs = 90000, heartbeatTimeoutMs = 45000, pollMs = 1000, requireHeartbeat = true, platformAdapter = null, comfyUp = null, comfyUpTimeoutMs = 0 }) {
598
+ const log = logFile || workerLogPath(workerDir);
599
+ const adapter = platformAdapter || adapterOf({});
600
+ const now = () => (io.now ? io.now() : Date.now());
601
+ const alive = () => {
602
+ if (!pid) return true;
603
+ try {
604
+ if (typeof adapter.checkDaemonAlive === 'function') return adapter.checkDaemonAlive(io, { pid, workerDir });
605
+ const chk = adapter.psCheckCommand(pid);
606
+ const r = io.exec(chk.cmd, chk.args);
607
+ return r.code === 0 && /worker\.cjs/.test(r.stdout);
608
+ } catch (_) { return false; }
609
+ };
610
+ let scan = scanWorkerLog(readLogFrom(io, log, logOffset));
611
+ let deadline = now() + comfyTimeoutMs;
612
+ let phase = scan.comfy_ready ? 'heartbeat' : 'comfy';
613
+ if (phase === 'heartbeat') deadline = now() + heartbeatTimeoutMs;
614
+ // comfyUp (installer 0.2.3): the comfyTimeoutMs window opens only once
615
+ // ComfyUI itself answers — up to comfyUpTimeoutMs are spent waiting for
616
+ // that first (0 = check once, then count as before).
617
+ if (phase === 'comfy' && typeof comfyUp === 'function') {
618
+ const upDeadline = now() + Math.max(0, comfyUpTimeoutMs);
619
+ for (;;) {
620
+ let up = false;
621
+ try { up = await comfyUp(); } catch (_) { up = false; }
622
+ if (up) break;
623
+ scan = scanWorkerLog(readLogFrom(io, log, logOffset));
624
+ if (scan.comfy_ready || scan.auth_failed || !alive() || now() >= upDeadline) break;
625
+ await new Promise((r) => setTimeout(r, pollMs));
626
+ }
627
+ deadline = now() + comfyTimeoutMs;
628
+ }
629
+ for (;;) {
630
+ scan = scanWorkerLog(readLogFrom(io, log, logOffset));
631
+ if (scan.auth_failed) {
632
+ return { ...flags(scan), exited: !alive(), reason: 'the Worker Key was rejected (Worker authentication failed)', logFile: log, scan };
633
+ }
634
+ if (phase === 'comfy' && scan.comfy_ready) {
635
+ if (!requireHeartbeat) return { ...flags(scan), exited: false, reason: null, logFile: log, scan };
636
+ phase = 'heartbeat';
637
+ deadline = now() + heartbeatTimeoutMs;
638
+ }
639
+ if (phase === 'heartbeat' && scan.heartbeat) {
640
+ return { ...flags(scan), exited: false, reason: null, logFile: log, scan };
641
+ }
642
+ if (!alive()) {
643
+ return { ...flags(scan), exited: true, reason: `worker process exited${scan.crashed ? ' (Worker crashed)' : ''} — see ${log}`, logFile: log, scan };
644
+ }
645
+ if (now() > deadline) {
646
+ const reason = phase === 'comfy'
647
+ ? `worker did not log "ComfyUI ready" within ${Math.round(comfyTimeoutMs / 1000)} s${scan.last_comfy_error ? ` (${scan.last_comfy_error})` : ''} — see ${log}`
648
+ : `the hub did not confirm a heartbeat within ${Math.round(heartbeatTimeoutMs / 1000)} s${scan.last_beacon_error ? ` (${scan.last_beacon_error})` : ''} — see ${log}`;
649
+ return { ...flags(scan), exited: false, reason, logFile: log, scan };
650
+ }
651
+ await new Promise((r) => setTimeout(r, pollMs));
652
+ }
653
+ }
654
+
655
+ function flags(scan) {
656
+ return { comfy_ready: scan.comfy_ready, heartbeat: scan.heartbeat, auth_failed: scan.auth_failed };
336
657
  }
337
658
 
338
659
  /** Grace sleep through the adapter (test-injectable `sleep` command wins). */
@@ -416,6 +737,17 @@ async function restartManagedWorker(io, { workerDir, log = null, stopTimeoutMs =
416
737
 
417
738
  module.exports = {
418
739
  installWorkerBundle,
740
+ ensureWorkerDependencies,
741
+ declaredDependencies,
742
+ readPkgVersion,
743
+ readEnvValues,
744
+ hasEnvKey,
745
+ resolveWorkerNode,
746
+ workerLogPath,
747
+ workerSpawnEnv,
748
+ scanWorkerLog,
749
+ readLogFrom,
750
+ waitForWorkerReady,
419
751
  fetchHubWorkerBundle,
420
752
  startWorker,
421
753
  stopManagedWorker,