@camstack/kernel 0.1.1

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.
package/dist/index.js ADDED
@@ -0,0 +1,1833 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ AddonEngineManager: () => AddonEngineManager,
34
+ AddonInstaller: () => AddonInstaller,
35
+ AddonLoader: () => AddonLoader,
36
+ AddonWorkerHost: () => AddonWorkerHost,
37
+ CapabilityRegistry: () => CapabilityRegistry,
38
+ ConfigManager: () => ConfigManager,
39
+ DEFAULT_DATA_PATH: () => DEFAULT_DATA_PATH,
40
+ INFRA_CAPABILITIES: () => INFRA_CAPABILITIES,
41
+ RUNTIME_DEFAULTS: () => RUNTIME_DEFAULTS,
42
+ WorkerProcessManager: () => WorkerProcessManager,
43
+ bootstrapSchema: () => bootstrapSchema,
44
+ copyDirRecursive: () => copyDirRecursive,
45
+ copyExtraFileDirs: () => copyExtraFileDirs,
46
+ detectWorkspacePackagesDir: () => detectWorkspacePackagesDir,
47
+ ensureDir: () => ensureDir,
48
+ ensureLibraryBuilt: () => ensureLibraryBuilt,
49
+ installPackageFromNpmSync: () => installPackageFromNpmSync,
50
+ isInfraCapability: () => isInfraCapability,
51
+ isSourceNewer: () => isSourceNewer,
52
+ stripCamstackDeps: () => stripCamstackDeps,
53
+ symlinkAddonsToNodeModules: () => symlinkAddonsToNodeModules
54
+ });
55
+ module.exports = __toCommonJS(src_exports);
56
+
57
+ // src/addon-loader.ts
58
+ var fs = __toESM(require("fs"));
59
+ var path = __toESM(require("path"));
60
+ function resolveAddonClass(mod) {
61
+ let candidate = mod["default"] ?? mod[Object.keys(mod)[0]];
62
+ if (candidate && typeof candidate === "object" && "default" in candidate) {
63
+ candidate = candidate["default"];
64
+ }
65
+ return typeof candidate === "function" ? candidate : void 0;
66
+ }
67
+ var AddonLoader = class {
68
+ addons = /* @__PURE__ */ new Map();
69
+ /** Scan addons directory and load all addon packages.
70
+ * Supports scoped layout: addons/@scope/package-name/ */
71
+ async loadFromDirectory(addonsDir) {
72
+ if (!fs.existsSync(addonsDir)) return;
73
+ const entries = fs.readdirSync(addonsDir, { withFileTypes: true });
74
+ for (const entry of entries) {
75
+ if (!entry.isDirectory()) continue;
76
+ if (entry.name.startsWith("@")) {
77
+ const scopeDir = path.join(addonsDir, entry.name);
78
+ const scopeEntries = fs.readdirSync(scopeDir, { withFileTypes: true });
79
+ for (const scopeEntry of scopeEntries) {
80
+ if (!scopeEntry.isDirectory()) continue;
81
+ await this.tryLoadAddon(path.join(scopeDir, scopeEntry.name));
82
+ }
83
+ continue;
84
+ }
85
+ await this.tryLoadAddon(path.join(addonsDir, entry.name));
86
+ }
87
+ }
88
+ async tryLoadAddon(addonDir) {
89
+ const pkgJsonPath = path.join(addonDir, "package.json");
90
+ if (!fs.existsSync(pkgJsonPath)) return;
91
+ try {
92
+ await this.loadFromAddonDir(addonDir);
93
+ } catch (err) {
94
+ console.warn(`Failed to load addon from ${addonDir}: ${err}`);
95
+ }
96
+ }
97
+ /** Load addon from a specific directory (package.json + dist/) */
98
+ async loadFromAddonDir(addonDir) {
99
+ const pkgJsonPath = path.join(addonDir, "package.json");
100
+ const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
101
+ const packageName = pkgJson["name"];
102
+ const packageVersion = pkgJson["version"] ?? "0.0.0";
103
+ const manifest = pkgJson["camstack"];
104
+ if (!manifest?.addons?.length) return;
105
+ for (const declaration of manifest.addons) {
106
+ const entryFile = declaration.entry.replace(/^\.\//, "").replace(/^src\//, "dist/").replace(/\.ts$/, ".js");
107
+ let entryPath = path.resolve(addonDir, entryFile);
108
+ if (!fs.existsSync(entryPath)) {
109
+ const base = entryPath.replace(/\.(js|cjs|mjs)$/, "");
110
+ const alternatives = [
111
+ `${base}.cjs`,
112
+ `${base}.mjs`,
113
+ path.resolve(addonDir, "dist", "index.js"),
114
+ path.resolve(addonDir, "dist", "index.cjs"),
115
+ path.resolve(addonDir, "dist", "index.mjs"),
116
+ path.resolve(addonDir, declaration.entry)
117
+ ];
118
+ entryPath = alternatives.find((p) => fs.existsSync(p)) ?? entryPath;
119
+ }
120
+ if (!fs.existsSync(entryPath)) {
121
+ throw new Error(`Entry not found: ${entryPath}`);
122
+ }
123
+ const mod = await import(entryPath);
124
+ const AddonClass = resolveAddonClass(mod);
125
+ if (!AddonClass) {
126
+ throw new Error(`No addon class in ${entryPath}`);
127
+ }
128
+ this.addons.set(declaration.id, {
129
+ declaration,
130
+ packageName,
131
+ packageVersion,
132
+ addonClass: AddonClass
133
+ });
134
+ }
135
+ }
136
+ /** Load addon from a direct path (for development/testing) */
137
+ async loadFromPath(addonId, modulePath, packageName, declaration, packageVersion = "0.0.0") {
138
+ const mod = await import(modulePath);
139
+ const AddonClass = resolveAddonClass(mod);
140
+ if (!AddonClass) {
141
+ throw new Error(`Module ${modulePath} has no default export`);
142
+ }
143
+ this.addons.set(addonId, {
144
+ declaration: {
145
+ id: addonId,
146
+ entry: modulePath,
147
+ slot: "detector",
148
+ ...declaration
149
+ },
150
+ packageName,
151
+ packageVersion,
152
+ addonClass: AddonClass
153
+ });
154
+ }
155
+ /** Get a registered addon by ID */
156
+ getAddon(addonId) {
157
+ return this.addons.get(addonId);
158
+ }
159
+ /** List all registered addons */
160
+ listAddons() {
161
+ return [...this.addons.values()];
162
+ }
163
+ /** Check if an addon is registered */
164
+ hasAddon(addonId) {
165
+ return this.addons.has(addonId);
166
+ }
167
+ /** Create a new instance of an addon (not yet initialized) */
168
+ createInstance(addonId) {
169
+ const registered = this.addons.get(addonId);
170
+ if (!registered) {
171
+ throw new Error(`Addon "${addonId}" is not registered`);
172
+ }
173
+ return new registered.addonClass();
174
+ }
175
+ };
176
+
177
+ // src/addon-engine-manager.ts
178
+ var import_node_crypto = require("crypto");
179
+ var AddonEngineManager = class {
180
+ constructor(loader, baseContext) {
181
+ this.loader = loader;
182
+ this.baseContext = baseContext;
183
+ }
184
+ engines = /* @__PURE__ */ new Map();
185
+ /**
186
+ * Get or create an addon engine for the given effective config.
187
+ * Cameras with the same addonId + effective config share the same engine.
188
+ */
189
+ async getOrCreateEngine(addonId, globalConfig, cameraOverride) {
190
+ const effectiveConfig = { ...globalConfig, ...cameraOverride };
191
+ const configKey = `${addonId}:${this.hashConfig(effectiveConfig)}`;
192
+ const existing = this.engines.get(configKey);
193
+ if (existing) return existing;
194
+ const addon = this.loader.createInstance(addonId);
195
+ await addon.initialize({ ...this.baseContext, addonConfig: effectiveConfig });
196
+ this.engines.set(configKey, addon);
197
+ return addon;
198
+ }
199
+ /** Get all active engines */
200
+ getActiveEngines() {
201
+ return new Map(this.engines);
202
+ }
203
+ /** Shutdown a specific engine by its config key */
204
+ async shutdownEngine(configKey) {
205
+ const engine = this.engines.get(configKey);
206
+ if (engine) {
207
+ await engine.shutdown();
208
+ this.engines.delete(configKey);
209
+ }
210
+ }
211
+ /** Shutdown all engines */
212
+ async shutdownAll() {
213
+ for (const [, engine] of this.engines) {
214
+ await engine.shutdown();
215
+ }
216
+ this.engines.clear();
217
+ }
218
+ /** Compute a deterministic config key (visible for tests) */
219
+ computeConfigKey(addonId, effectiveConfig) {
220
+ return `${addonId}:${this.hashConfig(effectiveConfig)}`;
221
+ }
222
+ hashConfig(config) {
223
+ const sorted = JSON.stringify(config, Object.keys(config).sort());
224
+ return (0, import_node_crypto.createHash)("md5").update(sorted).digest("hex").slice(0, 12);
225
+ }
226
+ };
227
+
228
+ // src/addon-installer.ts
229
+ var import_node_child_process2 = require("child_process");
230
+ var import_node_util = require("util");
231
+ var fs3 = __toESM(require("fs"));
232
+ var path3 = __toESM(require("path"));
233
+ var os = __toESM(require("os"));
234
+
235
+ // src/fs-utils.ts
236
+ var import_node_child_process = require("child_process");
237
+ var fs2 = __toESM(require("fs"));
238
+ var path2 = __toESM(require("path"));
239
+ function ensureDir(dirPath) {
240
+ fs2.mkdirSync(dirPath, { recursive: true });
241
+ }
242
+ function copyDirRecursive(src, dest) {
243
+ ensureDir(dest);
244
+ const entries = fs2.readdirSync(src, { withFileTypes: true });
245
+ for (const entry of entries) {
246
+ const srcPath = path2.join(src, entry.name);
247
+ const destPath = path2.join(dest, entry.name);
248
+ if (entry.isDirectory()) {
249
+ copyDirRecursive(srcPath, destPath);
250
+ } else {
251
+ fs2.copyFileSync(srcPath, destPath);
252
+ }
253
+ }
254
+ }
255
+ function stripCamstackDeps(pkg) {
256
+ const result = { ...pkg };
257
+ for (const depType of ["dependencies", "peerDependencies", "devDependencies"]) {
258
+ const deps = result[depType];
259
+ if (deps) {
260
+ const filtered = {};
261
+ for (const [name, version] of Object.entries(deps)) {
262
+ if (!name.startsWith("@camstack/")) {
263
+ filtered[name] = version;
264
+ }
265
+ }
266
+ result[depType] = Object.keys(filtered).length > 0 ? filtered : void 0;
267
+ }
268
+ }
269
+ delete result.devDependencies;
270
+ return result;
271
+ }
272
+ function copyExtraFileDirs(pkgJson, sourceDir, destDir) {
273
+ const files = pkgJson.files;
274
+ if (!files) return;
275
+ for (const fileEntry of files) {
276
+ if (fileEntry === "dist" || fileEntry.includes("*")) continue;
277
+ const srcPath = path2.join(sourceDir, fileEntry);
278
+ if (!fs2.existsSync(srcPath)) continue;
279
+ const destPath = path2.join(destDir, fileEntry);
280
+ const stat = fs2.statSync(srcPath);
281
+ if (stat.isDirectory()) {
282
+ copyDirRecursive(srcPath, destPath);
283
+ } else if (stat.isFile()) {
284
+ ensureDir(path2.dirname(destPath));
285
+ fs2.copyFileSync(srcPath, destPath);
286
+ }
287
+ }
288
+ }
289
+ function symlinkAddonsToNodeModules(addonsDir, nodeModulesDir) {
290
+ const camstackDir = path2.join(nodeModulesDir, "@camstack");
291
+ ensureDir(camstackDir);
292
+ const packagesToLink = ["core"];
293
+ for (const pkg of packagesToLink) {
294
+ const addonDir = path2.join(addonsDir, "@camstack", pkg);
295
+ const linkPath = path2.join(camstackDir, pkg);
296
+ if (!fs2.existsSync(addonDir)) continue;
297
+ try {
298
+ const stat = fs2.lstatSync(linkPath);
299
+ if (stat.isSymbolicLink() || stat.isDirectory()) {
300
+ fs2.rmSync(linkPath, { recursive: true, force: true });
301
+ }
302
+ } catch {
303
+ }
304
+ fs2.symlinkSync(addonDir, linkPath, "dir");
305
+ console.log(`[symlink] node_modules/@camstack/${pkg} -> ${addonDir}`);
306
+ }
307
+ }
308
+ function isSourceNewer(packageDir) {
309
+ const srcDir = path2.join(packageDir, "src");
310
+ const distDir = path2.join(packageDir, "dist");
311
+ if (!fs2.existsSync(srcDir) || !fs2.existsSync(distDir)) return true;
312
+ try {
313
+ const distMtime = fs2.statSync(distDir).mtimeMs;
314
+ const entries = fs2.readdirSync(srcDir, { withFileTypes: true, recursive: true });
315
+ for (const entry of entries) {
316
+ if (!entry.isFile()) continue;
317
+ const filePath = path2.join(entry.parentPath ?? entry.path, entry.name);
318
+ if (fs2.statSync(filePath).mtimeMs > distMtime) return true;
319
+ }
320
+ return false;
321
+ } catch {
322
+ return true;
323
+ }
324
+ }
325
+ function ensureLibraryBuilt(packageName, packagesDir) {
326
+ const dirName = packageName.replace("@camstack/", "");
327
+ const sourceDir = path2.join(packagesDir, dirName);
328
+ if (!fs2.existsSync(sourceDir)) return;
329
+ const distDir = path2.join(sourceDir, "dist");
330
+ const hasIndex = fs2.existsSync(path2.join(distDir, "index.js")) || fs2.existsSync(path2.join(distDir, "index.mjs"));
331
+ if (hasIndex) return;
332
+ console.warn(`[ensureLibraryBuilt] ${packageName} has no dist/ \u2014 run 'npm run build' first`);
333
+ }
334
+ function installPackageFromNpmSync(packageName, targetDir) {
335
+ const os2 = require("os");
336
+ const tmpDir = fs2.mkdtempSync(path2.join(os2.tmpdir(), "camstack-install-"));
337
+ try {
338
+ const stdout = (0, import_node_child_process.execFileSync)("npm", ["pack", packageName, "--pack-destination", tmpDir], {
339
+ timeout: 12e4,
340
+ encoding: "utf-8"
341
+ });
342
+ const tgzFilename = stdout.trim().split("\n").pop()?.trim();
343
+ if (!tgzFilename) throw new Error("npm pack produced no output");
344
+ const tgzPath = path2.join(tmpDir, tgzFilename);
345
+ const extractDir = path2.join(tmpDir, "extracted");
346
+ ensureDir(extractDir);
347
+ (0, import_node_child_process.execFileSync)("tar", ["-xzf", tgzPath, "-C", extractDir], { timeout: 3e4 });
348
+ const packageSubDir = path2.join(extractDir, "package");
349
+ const srcPkgJsonDir = fs2.existsSync(path2.join(packageSubDir, "package.json")) ? packageSubDir : extractDir;
350
+ fs2.rmSync(targetDir, { recursive: true, force: true });
351
+ ensureDir(targetDir);
352
+ fs2.copyFileSync(path2.join(srcPkgJsonDir, "package.json"), path2.join(targetDir, "package.json"));
353
+ const distSrc = path2.join(srcPkgJsonDir, "dist");
354
+ if (fs2.existsSync(distSrc)) {
355
+ copyDirRecursive(distSrc, path2.join(targetDir, "dist"));
356
+ }
357
+ try {
358
+ const npmPkg = JSON.parse(fs2.readFileSync(path2.join(srcPkgJsonDir, "package.json"), "utf-8"));
359
+ copyExtraFileDirs(npmPkg, srcPkgJsonDir, targetDir);
360
+ } catch {
361
+ }
362
+ } finally {
363
+ fs2.rmSync(tmpDir, { recursive: true, force: true });
364
+ }
365
+ }
366
+
367
+ // src/addon-installer.ts
368
+ var execFileAsync = (0, import_node_util.promisify)(import_node_child_process2.execFile);
369
+ var AddonInstaller = class _AddonInstaller {
370
+ addonsDir;
371
+ registry;
372
+ workspacePackagesDir;
373
+ constructor(config) {
374
+ this.addonsDir = config.addonsDir;
375
+ this.registry = config.registry;
376
+ this.workspacePackagesDir = config.workspacePackagesDir;
377
+ }
378
+ /** Required addon packages that must be installed for the server to function */
379
+ static REQUIRED_PACKAGES = [
380
+ "@camstack/core",
381
+ "@camstack/addon-pipeline",
382
+ "@camstack/addon-vision",
383
+ "@camstack/addon-admin-ui",
384
+ "@camstack/addon-webrtc-adaptive",
385
+ "@camstack/addon-pipeline-analysis",
386
+ "@camstack/addon-scene-intelligence",
387
+ "@camstack/addon-advanced-notifier"
388
+ ];
389
+ /** Ensure the addons directory exists */
390
+ async initialize() {
391
+ ensureDir(this.addonsDir);
392
+ }
393
+ /**
394
+ * Ensure all required packages are installed in the addons directory.
395
+ * This replaces the standalone first-boot-installer.ts.
396
+ */
397
+ async ensureRequiredPackages() {
398
+ ensureDir(this.addonsDir);
399
+ if (this.workspacePackagesDir) {
400
+ console.log(`[AddonInstaller] Workspace detected: ${this.workspacePackagesDir}`);
401
+ ensureLibraryBuilt("@camstack/kernel", this.workspacePackagesDir);
402
+ ensureLibraryBuilt("@camstack/types", this.workspacePackagesDir);
403
+ }
404
+ for (const packageName of _AddonInstaller.REQUIRED_PACKAGES) {
405
+ const addonDir = path3.join(this.addonsDir, packageName);
406
+ const pkgJsonPath = path3.join(addonDir, "package.json");
407
+ if (fs3.existsSync(pkgJsonPath)) {
408
+ if (!this.workspacePackagesDir) {
409
+ continue;
410
+ }
411
+ const srcPkgDir = this.findWorkspacePackage(packageName);
412
+ if (srcPkgDir && !isSourceNewer(srcPkgDir)) {
413
+ continue;
414
+ }
415
+ }
416
+ try {
417
+ if (this.workspacePackagesDir) {
418
+ const pkgDir = this.findWorkspacePackage(packageName);
419
+ if (pkgDir) {
420
+ await this.installFromWorkspace(packageName);
421
+ continue;
422
+ }
423
+ }
424
+ await this.installFromNpm(packageName);
425
+ } catch (err) {
426
+ const msg = err instanceof Error ? err.message : String(err);
427
+ if (packageName === "@camstack/core") {
428
+ throw new Error(`Required package ${packageName} failed to install: ${msg}`);
429
+ }
430
+ console.error(`[AddonInstaller] Failed to install ${packageName}: ${msg}`);
431
+ }
432
+ }
433
+ }
434
+ findWorkspacePackage(packageName) {
435
+ if (!this.workspacePackagesDir) return null;
436
+ const shortName = packageName.replace("@camstack/", "");
437
+ for (const dirName of [shortName, `addon-${shortName}`, shortName.replace("addon-", "")]) {
438
+ const candidate = path3.join(this.workspacePackagesDir, dirName);
439
+ if (fs3.existsSync(path3.join(candidate, "package.json"))) {
440
+ try {
441
+ const pkg = JSON.parse(fs3.readFileSync(path3.join(candidate, "package.json"), "utf-8"));
442
+ if (pkg.name === packageName) return candidate;
443
+ } catch {
444
+ }
445
+ }
446
+ }
447
+ return null;
448
+ }
449
+ /** Install addon from a tgz file (uploaded or downloaded) */
450
+ async installFromTgz(tgzPath) {
451
+ const tmpDir = fs3.mkdtempSync(path3.join(os.tmpdir(), "camstack-addon-install-"));
452
+ try {
453
+ await execFileAsync("tar", ["-xzf", tgzPath, "-C", tmpDir], { timeout: 3e4 });
454
+ const extractedDir = path3.join(tmpDir, "package");
455
+ const pkgJsonPath = fs3.existsSync(path3.join(extractedDir, "package.json")) ? path3.join(extractedDir, "package.json") : path3.join(tmpDir, "package.json");
456
+ if (!fs3.existsSync(pkgJsonPath)) {
457
+ throw new Error("No package.json found in tgz archive");
458
+ }
459
+ const pkgJson = JSON.parse(fs3.readFileSync(pkgJsonPath, "utf-8"));
460
+ if (!pkgJson.camstack?.addons) {
461
+ throw new Error(`Package ${pkgJson.name} has no camstack.addons manifest`);
462
+ }
463
+ const targetDir = path3.join(this.addonsDir, pkgJson.name);
464
+ fs3.rmSync(targetDir, { recursive: true, force: true });
465
+ ensureDir(targetDir);
466
+ const sourceDir = path3.dirname(pkgJsonPath);
467
+ fs3.copyFileSync(pkgJsonPath, path3.join(targetDir, "package.json"));
468
+ const sourceDist = path3.join(sourceDir, "dist");
469
+ if (fs3.existsSync(sourceDist)) {
470
+ copyDirRecursive(sourceDist, path3.join(targetDir, "dist"));
471
+ }
472
+ copyExtraFileDirs(pkgJson, sourceDir, targetDir);
473
+ return { name: pkgJson.name, version: pkgJson.version };
474
+ } finally {
475
+ fs3.rmSync(tmpDir, { recursive: true, force: true });
476
+ }
477
+ }
478
+ /**
479
+ * Install addon — prefers workspace if available, falls back to npm.
480
+ * This ensures dev builds (with vite output, etc.) are used when in workspace mode.
481
+ */
482
+ async install(packageName, version) {
483
+ if (this.workspacePackagesDir) {
484
+ const workspaceDirName = packageName.replace("@camstack/", "");
485
+ const sourceDir = path3.join(this.workspacePackagesDir, workspaceDirName);
486
+ if (fs3.existsSync(path3.join(sourceDir, "package.json"))) {
487
+ return this.installFromWorkspace(packageName);
488
+ }
489
+ }
490
+ return this.installFromNpm(packageName, version);
491
+ }
492
+ /**
493
+ * Install addon from workspace by copying package.json + dist/ to addons dir.
494
+ * Does NOT build — expects dist/ to already exist (run `npm run build` separately).
495
+ */
496
+ async installFromWorkspace(packageName) {
497
+ if (!this.workspacePackagesDir) {
498
+ throw new Error("Workspace packages directory not configured");
499
+ }
500
+ const workspaceDirName = packageName.replace("@camstack/", "");
501
+ const sourceDir = path3.join(this.workspacePackagesDir, workspaceDirName);
502
+ const sourcePkgJson = path3.join(sourceDir, "package.json");
503
+ if (!fs3.existsSync(sourcePkgJson)) {
504
+ throw new Error(`Workspace package not found: ${sourceDir}`);
505
+ }
506
+ const distDir = path3.join(sourceDir, "dist");
507
+ if (!fs3.existsSync(distDir)) {
508
+ throw new Error(`${packageName} has no dist/ directory \u2014 run 'npm run build' first`);
509
+ }
510
+ const targetDir = path3.join(this.addonsDir, packageName);
511
+ fs3.rmSync(targetDir, { recursive: true, force: true });
512
+ ensureDir(targetDir);
513
+ const pkgData = JSON.parse(fs3.readFileSync(sourcePkgJson, "utf-8"));
514
+ const strippedPkg = stripCamstackDeps(pkgData);
515
+ fs3.writeFileSync(path3.join(targetDir, "package.json"), JSON.stringify(strippedPkg, null, 2));
516
+ copyDirRecursive(distDir, path3.join(targetDir, "dist"));
517
+ copyExtraFileDirs(pkgData, sourceDir, targetDir);
518
+ try {
519
+ await execFileAsync("npm", ["install", "--omit=dev", "--ignore-scripts=false"], {
520
+ cwd: targetDir,
521
+ timeout: 12e4
522
+ });
523
+ } catch {
524
+ }
525
+ return { name: pkgData.name, version: pkgData.version };
526
+ }
527
+ /** Install addon from npm (download tgz, then extract) */
528
+ async installFromNpm(packageName, version) {
529
+ const tmpDir = fs3.mkdtempSync(path3.join(os.tmpdir(), "camstack-addon-npm-"));
530
+ const packageSpec = version ? `${packageName}@${version}` : packageName;
531
+ const args = ["pack", packageSpec, "--pack-destination", tmpDir];
532
+ if (this.registry) {
533
+ args.push("--registry", this.registry);
534
+ }
535
+ try {
536
+ const { stdout } = await execFileAsync("npm", args, {
537
+ timeout: 12e4
538
+ });
539
+ const tgzFiles = fs3.readdirSync(tmpDir).filter((f) => f.endsWith(".tgz"));
540
+ if (tgzFiles.length === 0) {
541
+ throw new Error(`npm pack produced no tgz file for ${packageSpec}. stdout: ${stdout.trim()}`);
542
+ }
543
+ const tgzPath = path3.join(tmpDir, tgzFiles[0]);
544
+ const result = await this.installFromTgz(tgzPath);
545
+ return result;
546
+ } finally {
547
+ fs3.rmSync(tmpDir, { recursive: true, force: true });
548
+ }
549
+ }
550
+ /** Uninstall addon (delete directory) */
551
+ async uninstall(packageName) {
552
+ const addonDir = path3.join(this.addonsDir, packageName);
553
+ if (fs3.existsSync(addonDir)) {
554
+ fs3.rmSync(addonDir, { recursive: true, force: true });
555
+ return;
556
+ }
557
+ const legacyDir = path3.join(this.addonsDir, packageName.replace(/^@[^/]+\//, ""));
558
+ if (fs3.existsSync(legacyDir)) {
559
+ fs3.rmSync(legacyDir, { recursive: true, force: true });
560
+ }
561
+ }
562
+ /** List installed addons (directories with package.json containing camstack.addons) */
563
+ listInstalled() {
564
+ if (!fs3.existsSync(this.addonsDir)) return [];
565
+ return fs3.readdirSync(this.addonsDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => {
566
+ const pkgPath = path3.join(this.addonsDir, d.name, "package.json");
567
+ if (!fs3.existsSync(pkgPath)) return null;
568
+ try {
569
+ const pkg = JSON.parse(fs3.readFileSync(pkgPath, "utf-8"));
570
+ if (!pkg.camstack?.addons) return null;
571
+ return { name: pkg.name, version: pkg.version, dir: path3.join(this.addonsDir, d.name) };
572
+ } catch {
573
+ return null;
574
+ }
575
+ }).filter((item) => item !== null);
576
+ }
577
+ /** Check if an addon is installed */
578
+ isInstalled(packageName) {
579
+ if (fs3.existsSync(path3.join(this.addonsDir, packageName, "package.json"))) return true;
580
+ const legacy = packageName.replace(/^@[^/]+\//, "");
581
+ return fs3.existsSync(path3.join(this.addonsDir, legacy, "package.json"));
582
+ }
583
+ /** Get installed package info */
584
+ getInstalledPackage(packageName) {
585
+ let pkgPath = path3.join(this.addonsDir, packageName, "package.json");
586
+ if (!fs3.existsSync(pkgPath)) {
587
+ pkgPath = path3.join(this.addonsDir, packageName.replace(/^@[^/]+\//, ""), "package.json");
588
+ }
589
+ if (!fs3.existsSync(pkgPath)) return null;
590
+ try {
591
+ const pkg = JSON.parse(fs3.readFileSync(pkgPath, "utf-8"));
592
+ return { name: pkg.name, version: pkg.version, dir: path3.dirname(pkgPath) };
593
+ } catch {
594
+ return null;
595
+ }
596
+ }
597
+ };
598
+
599
+ // src/workspace-detect.ts
600
+ var fs4 = __toESM(require("fs"));
601
+ var path4 = __toESM(require("path"));
602
+ function detectWorkspacePackagesDir(startDir) {
603
+ let current = path4.resolve(startDir);
604
+ for (let i = 0; i < 6; i++) {
605
+ current = path4.dirname(current);
606
+ const packagesDir = path4.join(current, "packages");
607
+ const rootPkgJson = path4.join(current, "package.json");
608
+ if (fs4.existsSync(packagesDir) && fs4.existsSync(rootPkgJson)) {
609
+ try {
610
+ const rootPkg = JSON.parse(fs4.readFileSync(rootPkgJson, "utf-8"));
611
+ if (rootPkg.workspaces || rootPkg.name === "camstack-server" || rootPkg.name === "camstack") {
612
+ return packagesDir;
613
+ }
614
+ } catch {
615
+ }
616
+ }
617
+ }
618
+ return null;
619
+ }
620
+
621
+ // src/capability-registry.ts
622
+ var CapabilityRegistry = class {
623
+ constructor(logger, configReader) {
624
+ this.logger = logger;
625
+ this.configReader = configReader;
626
+ }
627
+ capabilities = /* @__PURE__ */ new Map();
628
+ /** Per-device singleton overrides: deviceId → (capability → addonId) */
629
+ deviceOverrides = /* @__PURE__ */ new Map();
630
+ /** Per-device collection filters: deviceId → (capability → addonIds[]) */
631
+ deviceCollectionFilters = /* @__PURE__ */ new Map();
632
+ /**
633
+ * Declare a capability (typically called when addon manifests are loaded).
634
+ * Must be called before registerProvider/registerConsumer for that capability.
635
+ */
636
+ declareCapability(declaration) {
637
+ if (this.capabilities.has(declaration.name)) {
638
+ this.logger.debug(`Capability "${declaration.name}" already declared, skipping`);
639
+ return;
640
+ }
641
+ this.capabilities.set(declaration.name, {
642
+ declaration,
643
+ available: /* @__PURE__ */ new Map(),
644
+ activeAddonId: null,
645
+ activeProvider: null,
646
+ activeCollection: [],
647
+ consumers: /* @__PURE__ */ new Set()
648
+ });
649
+ this.logger.debug(`Capability declared: ${declaration.name} (mode=${declaration.mode})`);
650
+ }
651
+ /**
652
+ * Register a capability provider (called by addon loader when addon is enabled).
653
+ * For singleton: auto-activates if user-preferred or first registered.
654
+ * For collection: adds to active set and notifies consumers.
655
+ */
656
+ registerProvider(capability, addonId, provider) {
657
+ const state = this.capabilities.get(capability);
658
+ if (!state) {
659
+ this.logger.warn(`Cannot register provider for undeclared capability "${capability}"`);
660
+ return;
661
+ }
662
+ state.available.set(addonId, provider);
663
+ this.logger.info(`Provider registered: ${addonId} \u2192 ${capability}`);
664
+ if (state.declaration.mode === "singleton") {
665
+ const userChoice = this.configReader(capability);
666
+ if (userChoice === addonId) {
667
+ this.activateSingleton(state, addonId, provider);
668
+ } else if (userChoice === void 0 && state.activeAddonId === null) {
669
+ this.activateSingleton(state, addonId, provider);
670
+ }
671
+ } else {
672
+ state.activeCollection.push({ addonId, provider });
673
+ for (const consumer of state.consumers) {
674
+ if (consumer.onAdded) {
675
+ try {
676
+ consumer.onAdded(provider);
677
+ } catch (error) {
678
+ const msg = error instanceof Error ? error.message : String(error);
679
+ this.logger.error(`Consumer onAdded failed for ${capability}: ${msg}`);
680
+ }
681
+ }
682
+ }
683
+ }
684
+ }
685
+ /**
686
+ * Unregister a provider (called when addon is disabled/uninstalled).
687
+ */
688
+ unregisterProvider(capability, addonId) {
689
+ const state = this.capabilities.get(capability);
690
+ if (!state) return;
691
+ const provider = state.available.get(addonId);
692
+ state.available.delete(addonId);
693
+ if (state.declaration.mode === "singleton") {
694
+ if (state.activeAddonId === addonId) {
695
+ state.activeAddonId = null;
696
+ state.activeProvider = null;
697
+ this.logger.info(`Singleton deactivated: ${capability} (was ${addonId})`);
698
+ }
699
+ } else {
700
+ const idx = state.activeCollection.findIndex((e) => e.addonId === addonId);
701
+ if (idx !== -1) {
702
+ state.activeCollection.splice(idx, 1);
703
+ for (const consumer of state.consumers) {
704
+ if (consumer.onRemoved && provider !== void 0) {
705
+ try {
706
+ consumer.onRemoved(provider);
707
+ } catch (error) {
708
+ const msg = error instanceof Error ? error.message : String(error);
709
+ this.logger.error(`Consumer onRemoved failed for ${capability}: ${msg}`);
710
+ }
711
+ }
712
+ }
713
+ }
714
+ }
715
+ }
716
+ /**
717
+ * Register a consumer that wants to be notified when providers change.
718
+ * If a provider is already active, the consumer is immediately notified.
719
+ * Returns a disposer function for cleanup.
720
+ */
721
+ registerConsumer(registration) {
722
+ const state = this.capabilities.get(registration.capability);
723
+ if (!state) {
724
+ this.logger.debug(`Consumer registered for undeclared capability "${registration.capability}" \u2014 auto-declaring`);
725
+ this.declareCapability({ name: registration.capability, mode: "singleton" });
726
+ return this.registerConsumer(registration);
727
+ }
728
+ const untypedReg = registration;
729
+ state.consumers.add(untypedReg);
730
+ if (state.declaration.mode === "singleton") {
731
+ if (state.activeProvider !== null && registration.onSet) {
732
+ try {
733
+ registration.onSet(state.activeProvider);
734
+ } catch (error) {
735
+ const msg = error instanceof Error ? error.message : String(error);
736
+ this.logger.error(`Consumer onSet (immediate) failed for ${registration.capability}: ${msg}`);
737
+ }
738
+ }
739
+ } else {
740
+ if (registration.onAdded) {
741
+ for (const entry of state.activeCollection) {
742
+ try {
743
+ registration.onAdded(entry.provider);
744
+ } catch (error) {
745
+ const msg = error instanceof Error ? error.message : String(error);
746
+ this.logger.error(`Consumer onAdded (immediate) failed for ${registration.capability}: ${msg}`);
747
+ }
748
+ }
749
+ }
750
+ }
751
+ return () => {
752
+ state.consumers.delete(untypedReg);
753
+ };
754
+ }
755
+ /**
756
+ * Get the active singleton provider for a capability.
757
+ * Returns null if none set.
758
+ */
759
+ getSingleton(capability) {
760
+ const state = this.capabilities.get(capability);
761
+ if (!state || state.declaration.mode !== "singleton") return null;
762
+ return state.activeProvider ?? null;
763
+ }
764
+ /**
765
+ * Get all active collection providers for a capability.
766
+ */
767
+ getCollection(capability) {
768
+ const state = this.capabilities.get(capability);
769
+ if (!state || state.declaration.mode !== "collection") return [];
770
+ return state.activeCollection.map((e) => e.provider);
771
+ }
772
+ /**
773
+ * Set which addon should be the active singleton for a capability.
774
+ * Call with `immediate: true` to also swap the runtime provider now
775
+ * (consumers' onSet will be awaited).
776
+ */
777
+ async setActiveSingleton(capability, addonId, immediate = false) {
778
+ const state = this.capabilities.get(capability);
779
+ if (!state) {
780
+ throw new Error(`Unknown capability: ${capability}`);
781
+ }
782
+ if (state.declaration.mode !== "singleton") {
783
+ throw new Error(`Capability "${capability}" is not a singleton`);
784
+ }
785
+ const provider = state.available.get(addonId);
786
+ if (!provider) {
787
+ throw new Error(`No provider "${addonId}" registered for capability "${capability}"`);
788
+ }
789
+ if (immediate) {
790
+ await this.activateSingletonAsync(state, addonId, provider);
791
+ }
792
+ this.logger.info(`Singleton preference set: ${capability} \u2192 ${addonId}`);
793
+ }
794
+ /**
795
+ * Get the mode declared for a capability.
796
+ */
797
+ getMode(capability) {
798
+ return this.capabilities.get(capability)?.declaration.mode;
799
+ }
800
+ /**
801
+ * List all registered capabilities with their providers.
802
+ */
803
+ listCapabilities() {
804
+ const result = [];
805
+ for (const [name, state] of this.capabilities) {
806
+ result.push({
807
+ name,
808
+ mode: state.declaration.mode,
809
+ providers: [...state.available.keys()],
810
+ activeProvider: state.activeAddonId
811
+ });
812
+ }
813
+ return result;
814
+ }
815
+ /**
816
+ * Check if all dependencies for a capability are satisfied (have active providers).
817
+ */
818
+ areDependenciesMet(declaration) {
819
+ if (!declaration.dependsOn?.length) return true;
820
+ return declaration.dependsOn.every((dep) => {
821
+ const state = this.capabilities.get(dep);
822
+ if (!state) return false;
823
+ if (state.declaration.mode === "singleton") {
824
+ return state.activeProvider !== null;
825
+ }
826
+ return state.activeCollection.length > 0;
827
+ });
828
+ }
829
+ /**
830
+ * Get the dependency-ordered list of capability names for boot sequencing.
831
+ * Returns capabilities sorted topologically by dependsOn.
832
+ * Throws if a cycle is detected.
833
+ */
834
+ getBootOrder() {
835
+ const visited = /* @__PURE__ */ new Set();
836
+ const visiting = /* @__PURE__ */ new Set();
837
+ const order = [];
838
+ const visit = (name) => {
839
+ if (visited.has(name)) return;
840
+ if (visiting.has(name)) {
841
+ throw new Error(`Circular dependency detected involving capability "${name}"`);
842
+ }
843
+ visiting.add(name);
844
+ const state = this.capabilities.get(name);
845
+ if (state?.declaration.dependsOn) {
846
+ for (const dep of state.declaration.dependsOn) {
847
+ visit(dep);
848
+ }
849
+ }
850
+ visiting.delete(name);
851
+ visited.add(name);
852
+ order.push(name);
853
+ };
854
+ for (const name of this.capabilities.keys()) {
855
+ visit(name);
856
+ }
857
+ return order;
858
+ }
859
+ // ---- Per-device overrides ----
860
+ /**
861
+ * Set a per-device singleton override. When resolveForDevice is called for
862
+ * this device + capability, the specified addon's provider is returned
863
+ * instead of the global singleton.
864
+ */
865
+ setDeviceOverride(deviceId, capability, addonId) {
866
+ const state = this.capabilities.get(capability);
867
+ if (!state) {
868
+ this.logger.warn(`Cannot set device override for undeclared capability "${capability}"`);
869
+ return;
870
+ }
871
+ if (!state.available.has(addonId)) {
872
+ this.logger.warn(`Cannot set device override: addon "${addonId}" not registered for "${capability}"`);
873
+ return;
874
+ }
875
+ let deviceMap = this.deviceOverrides.get(deviceId);
876
+ if (!deviceMap) {
877
+ deviceMap = /* @__PURE__ */ new Map();
878
+ this.deviceOverrides.set(deviceId, deviceMap);
879
+ }
880
+ deviceMap.set(capability, addonId);
881
+ this.logger.info(`Device override set: ${deviceId} \u2192 ${capability} = ${addonId}`);
882
+ }
883
+ /**
884
+ * Clear a per-device singleton override, reverting to the global singleton.
885
+ */
886
+ clearDeviceOverride(deviceId, capability) {
887
+ const deviceMap = this.deviceOverrides.get(deviceId);
888
+ if (!deviceMap) return;
889
+ deviceMap.delete(capability);
890
+ if (deviceMap.size === 0) {
891
+ this.deviceOverrides.delete(deviceId);
892
+ }
893
+ this.logger.info(`Device override cleared: ${deviceId} \u2192 ${capability}`);
894
+ }
895
+ /**
896
+ * Get all per-device singleton overrides for a device.
897
+ * Returns a Map of capability name to addon ID.
898
+ */
899
+ getDeviceOverrides(deviceId) {
900
+ return new Map(this.deviceOverrides.get(deviceId) ?? []);
901
+ }
902
+ /**
903
+ * Resolve a singleton provider for a specific device.
904
+ * 1. Check device override — return that addon's provider
905
+ * 2. Fallback to global singleton
906
+ */
907
+ resolveForDevice(capability, deviceId) {
908
+ const state = this.capabilities.get(capability);
909
+ if (!state || state.declaration.mode !== "singleton") return null;
910
+ const deviceMap = this.deviceOverrides.get(deviceId);
911
+ if (deviceMap) {
912
+ const overrideAddonId = deviceMap.get(capability);
913
+ if (overrideAddonId) {
914
+ const provider = state.available.get(overrideAddonId);
915
+ if (provider) return provider;
916
+ this.logger.warn(
917
+ `Device override for ${deviceId}/${capability} references unregistered addon "${overrideAddonId}" \u2014 falling back to global`
918
+ );
919
+ }
920
+ }
921
+ return state.activeProvider ?? null;
922
+ }
923
+ /**
924
+ * Set a per-device collection filter. When resolveCollectionForDevice is called
925
+ * for this device + capability, only providers from the specified addon IDs
926
+ * are returned instead of the full collection.
927
+ */
928
+ setDeviceCollectionFilter(deviceId, capability, addonIds) {
929
+ const state = this.capabilities.get(capability);
930
+ if (!state) {
931
+ this.logger.warn(`Cannot set device collection filter for undeclared capability "${capability}"`);
932
+ return;
933
+ }
934
+ let deviceMap = this.deviceCollectionFilters.get(deviceId);
935
+ if (!deviceMap) {
936
+ deviceMap = /* @__PURE__ */ new Map();
937
+ this.deviceCollectionFilters.set(deviceId, deviceMap);
938
+ }
939
+ deviceMap.set(capability, [...addonIds]);
940
+ this.logger.info(`Device collection filter set: ${deviceId} \u2192 ${capability} = [${addonIds.join(", ")}]`);
941
+ }
942
+ /**
943
+ * Clear a per-device collection filter, reverting to the full collection.
944
+ */
945
+ clearDeviceCollectionFilter(deviceId, capability) {
946
+ const deviceMap = this.deviceCollectionFilters.get(deviceId);
947
+ if (!deviceMap) return;
948
+ deviceMap.delete(capability);
949
+ if (deviceMap.size === 0) {
950
+ this.deviceCollectionFilters.delete(deviceId);
951
+ }
952
+ this.logger.info(`Device collection filter cleared: ${deviceId} \u2192 ${capability}`);
953
+ }
954
+ /**
955
+ * Resolve collection providers for a specific device.
956
+ * If a filter exists for the device + capability, only those addon's providers are returned.
957
+ * If no filter exists, the full collection is returned.
958
+ */
959
+ resolveCollectionForDevice(capability, deviceId) {
960
+ const state = this.capabilities.get(capability);
961
+ if (!state || state.declaration.mode !== "collection") return [];
962
+ const deviceMap = this.deviceCollectionFilters.get(deviceId);
963
+ if (deviceMap) {
964
+ const filterAddonIds = deviceMap.get(capability);
965
+ if (filterAddonIds) {
966
+ const filterSet = new Set(filterAddonIds);
967
+ return state.activeCollection.filter((e) => filterSet.has(e.addonId)).map((e) => e.provider);
968
+ }
969
+ }
970
+ return state.activeCollection.map((e) => e.provider);
971
+ }
972
+ /**
973
+ * Get a specific addon's provider by addon ID, regardless of whether it's the active singleton.
974
+ * Useful for per-device overrides that need to look up any registered provider.
975
+ */
976
+ getProviderByAddonId(capability, addonId) {
977
+ const state = this.capabilities.get(capability);
978
+ if (!state) return null;
979
+ const provider = state.available.get(addonId);
980
+ return provider ?? null;
981
+ }
982
+ activateSingleton(state, addonId, provider) {
983
+ state.activeAddonId = addonId;
984
+ state.activeProvider = provider;
985
+ this.logger.info(`Singleton activated: ${state.declaration.name} \u2192 ${addonId}`);
986
+ for (const consumer of state.consumers) {
987
+ if (consumer.onSet) {
988
+ try {
989
+ consumer.onSet(provider);
990
+ } catch (error) {
991
+ const msg = error instanceof Error ? error.message : String(error);
992
+ this.logger.error(`Consumer onSet failed for ${state.declaration.name}: ${msg}`);
993
+ }
994
+ }
995
+ }
996
+ }
997
+ async activateSingletonAsync(state, addonId, provider) {
998
+ state.activeAddonId = addonId;
999
+ state.activeProvider = provider;
1000
+ this.logger.info(`Singleton activated (async): ${state.declaration.name} \u2192 ${addonId}`);
1001
+ for (const consumer of state.consumers) {
1002
+ if (consumer.onSet) {
1003
+ try {
1004
+ await consumer.onSet(provider);
1005
+ } catch (error) {
1006
+ const msg = error instanceof Error ? error.message : String(error);
1007
+ this.logger.error(`Consumer onSet (async) failed for ${state.declaration.name}: ${msg}`);
1008
+ }
1009
+ }
1010
+ }
1011
+ }
1012
+ };
1013
+
1014
+ // src/infra-capabilities.ts
1015
+ var INFRA_CAPABILITIES = [
1016
+ { name: "storage", required: true },
1017
+ { name: "settings-store", required: true },
1018
+ { name: "log-destination", required: false }
1019
+ ];
1020
+ var infraNames = new Set(INFRA_CAPABILITIES.map((c) => c.name));
1021
+ function isInfraCapability(name) {
1022
+ return infraNames.has(name);
1023
+ }
1024
+
1025
+ // src/config-manager.ts
1026
+ var fs5 = __toESM(require("fs"));
1027
+ var yaml = __toESM(require("js-yaml"));
1028
+
1029
+ // src/config-schema.ts
1030
+ var import_zod = require("zod");
1031
+ var DEFAULT_DATA_PATH = "camstack-data";
1032
+ var bootstrapSchema = import_zod.z.object({
1033
+ /** Server mode: 'hub' (full server) or 'agent' (worker node) */
1034
+ mode: import_zod.z.enum(["hub", "agent"]).default("hub"),
1035
+ server: import_zod.z.object({
1036
+ port: import_zod.z.number().default(4443),
1037
+ host: import_zod.z.string().default("0.0.0.0"),
1038
+ dataPath: import_zod.z.string().default(DEFAULT_DATA_PATH)
1039
+ }).default({}),
1040
+ auth: import_zod.z.object({
1041
+ jwtSecret: import_zod.z.string().nullable().default(null),
1042
+ adminUsername: import_zod.z.string().default("admin"),
1043
+ adminPassword: import_zod.z.string().default(process.env.ADMIN_PASSWORD ?? "changeme")
1044
+ }).default({}),
1045
+ /** Hub connection config — only used when mode='agent' */
1046
+ hub: import_zod.z.object({
1047
+ url: import_zod.z.string().default("ws://localhost:4443/agent"),
1048
+ token: import_zod.z.string().default("")
1049
+ }).default({}),
1050
+ /** Agent-specific config — only used when mode='agent' */
1051
+ agent: import_zod.z.object({
1052
+ name: import_zod.z.string().default(""),
1053
+ /** Port for the agent status page (minimal HTML) */
1054
+ statusPort: import_zod.z.number().default(4444)
1055
+ }).default({}),
1056
+ /** TLS configuration */
1057
+ tls: import_zod.z.object({
1058
+ /** Enable HTTPS (default: true) */
1059
+ enabled: import_zod.z.boolean().default(true),
1060
+ /** Path to custom cert file (PEM). If not set, auto-generates self-signed. */
1061
+ certPath: import_zod.z.string().optional(),
1062
+ /** Path to custom key file (PEM). Required if certPath is set. */
1063
+ keyPath: import_zod.z.string().optional()
1064
+ }).default({})
1065
+ });
1066
+ var RUNTIME_DEFAULTS = {
1067
+ "features.streaming": true,
1068
+ "features.notifications": true,
1069
+ "features.objectDetection": false,
1070
+ "features.remoteAccess": true,
1071
+ "features.agentCluster": false,
1072
+ "features.smartHome": true,
1073
+ "features.recordings": true,
1074
+ "features.backup": true,
1075
+ "features.repl": true,
1076
+ "retention.detectionEventsDays": 30,
1077
+ "retention.audioLevelsDays": 7,
1078
+ "logging.level": "info",
1079
+ "logging.retentionDays": 30,
1080
+ "eventBus.ringBufferSize": 1e4,
1081
+ "storage.provider": "sqlite-storage",
1082
+ "storage.locations": {
1083
+ data: "camstack-data/data",
1084
+ media: "camstack-data/media",
1085
+ recordings: "camstack-data/recordings",
1086
+ cache: "/tmp/camstack-cache",
1087
+ logs: "camstack-data/logs",
1088
+ models: "camstack-data/models"
1089
+ },
1090
+ "providers": [],
1091
+ // Recording
1092
+ "recording.segmentDurationSeconds": 4,
1093
+ "recording.defaultRetentionDays": 30,
1094
+ // Streaming ports are addon-specific (go2rtc owns its defaults)
1095
+ // FFmpeg
1096
+ "ffmpeg.binaryPath": "ffmpeg",
1097
+ "ffmpeg.hwAccel": "auto",
1098
+ "ffmpeg.threadCount": 0,
1099
+ // Detection defaults
1100
+ "detection.defaultMotionFps": 2,
1101
+ "detection.defaultDetectionFps": 5,
1102
+ "detection.defaultCooldownSeconds": 10,
1103
+ "detection.defaultConfidenceThreshold": 0.4,
1104
+ "detection.trackerMaxAgeFrames": 30,
1105
+ "detection.trackerMinHits": 3,
1106
+ "detection.trackerIouThreshold": 0.3,
1107
+ // Backup retention is addon-specific (local-backup owns its default)
1108
+ // Auth (runtime)
1109
+ "auth.tokenExpiry": "24h"
1110
+ };
1111
+
1112
+ // src/config-manager.ts
1113
+ var ENV_VAR_MAP = {
1114
+ CAMSTACK_PORT: "server.port",
1115
+ CAMSTACK_HOST: "server.host",
1116
+ CAMSTACK_DATA: "server.dataPath",
1117
+ CAMSTACK_JWT_SECRET: "auth.jwtSecret",
1118
+ CAMSTACK_ADMIN_USER: "auth.adminUsername",
1119
+ CAMSTACK_ADMIN_PASS: "auth.adminPassword"
1120
+ };
1121
+ var ConfigManager = class _ConfigManager {
1122
+ constructor(configPath) {
1123
+ this.configPath = configPath;
1124
+ const rawYaml = this.loadYaml();
1125
+ const merged = this.applyEnvOverrides(rawYaml);
1126
+ this.bootstrapConfig = bootstrapSchema.parse(merged);
1127
+ this.warnDefaultCredentials();
1128
+ }
1129
+ // Non-readonly so update() can sync the in-memory view after a write.
1130
+ bootstrapConfig;
1131
+ settingsStore = null;
1132
+ /** Called by main.ts after the SQLite DB is ready (Phase 2). */
1133
+ setSettingsStore(store) {
1134
+ this.settingsStore = store;
1135
+ }
1136
+ /**
1137
+ * Get a config value by dot-notation path.
1138
+ * Priority: bootstrap config -> SQL system_settings -> RUNTIME_DEFAULTS fallback.
1139
+ */
1140
+ get(path5) {
1141
+ const bootstrapValue = this.getFromBootstrap(path5);
1142
+ if (bootstrapValue !== void 0) {
1143
+ return bootstrapValue;
1144
+ }
1145
+ if (this.settingsStore !== null) {
1146
+ const sqlValue = this.settingsStore.getSystem(path5);
1147
+ if (sqlValue !== void 0) {
1148
+ return sqlValue;
1149
+ }
1150
+ const sqlNested = this.getNestedFromSystemSettings(path5);
1151
+ if (sqlNested !== void 0) {
1152
+ return sqlNested;
1153
+ }
1154
+ }
1155
+ if (path5 in RUNTIME_DEFAULTS) {
1156
+ return RUNTIME_DEFAULTS[path5];
1157
+ }
1158
+ const nested = this.getFromRuntimeDefaults(path5);
1159
+ if (nested !== void 0) {
1160
+ return nested;
1161
+ }
1162
+ return void 0;
1163
+ }
1164
+ /**
1165
+ * Write a value to SQL system_settings.
1166
+ * Throws if the settings store is not yet wired.
1167
+ */
1168
+ set(key, value) {
1169
+ if (this.settingsStore === null) {
1170
+ throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
1171
+ }
1172
+ this.settingsStore.setSystem(key, value);
1173
+ }
1174
+ /**
1175
+ * Bulk-read all system_settings keys that belong to a logical section.
1176
+ * A "section" is the first segment of a dot-notation key (e.g. 'features', 'logging').
1177
+ */
1178
+ getSection(section) {
1179
+ if (this.settingsStore !== null) {
1180
+ const nested = this.getNestedFromSystemSettings(section);
1181
+ if (nested !== void 0) return nested;
1182
+ }
1183
+ const bootstrapValue = this.bootstrapConfig[section];
1184
+ if (bootstrapValue !== void 0 && bootstrapValue !== null && typeof bootstrapValue === "object") {
1185
+ return bootstrapValue;
1186
+ }
1187
+ return this.getFromRuntimeDefaults(section) ?? {};
1188
+ }
1189
+ /**
1190
+ * Bulk-write a section of runtime settings to SQL system_settings.
1191
+ * Each entry in `data` is stored as `section.key`.
1192
+ */
1193
+ setSection(section, data) {
1194
+ if (this.settingsStore === null) {
1195
+ throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
1196
+ }
1197
+ for (const [key, value] of Object.entries(data)) {
1198
+ this.settingsStore.setSystem(`${section}.${key}`, value);
1199
+ }
1200
+ }
1201
+ // ---------------------------------------------------------------------------
1202
+ // Addon / Provider / Device scoped config
1203
+ // ---------------------------------------------------------------------------
1204
+ /** Read all config for an addon from addon_settings. */
1205
+ getAddonConfig(addonId) {
1206
+ if (this.settingsStore !== null) {
1207
+ return this.settingsStore.getAllAddon(addonId);
1208
+ }
1209
+ return this.getFromBootstrap(`addons.${addonId}`) ?? {};
1210
+ }
1211
+ /** Write (bulk-replace) config for an addon to addon_settings. */
1212
+ setAddonConfig(addonId, config) {
1213
+ if (this.settingsStore === null) {
1214
+ throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
1215
+ }
1216
+ this.settingsStore.setAllAddon(addonId, config);
1217
+ }
1218
+ /** Read all config for a provider from provider_settings. */
1219
+ getProviderConfig(providerId) {
1220
+ if (this.settingsStore !== null) {
1221
+ return this.settingsStore.getAllProvider(providerId);
1222
+ }
1223
+ return {};
1224
+ }
1225
+ /** Write (upsert) a single key for a provider to provider_settings. */
1226
+ setProviderConfig(providerId, key, value) {
1227
+ if (this.settingsStore === null) {
1228
+ throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
1229
+ }
1230
+ this.settingsStore.setProvider(providerId, key, value);
1231
+ }
1232
+ /** Read all config for a device from device_settings. */
1233
+ getDeviceConfig(deviceId) {
1234
+ if (this.settingsStore !== null) {
1235
+ return this.settingsStore.getAllDevice(deviceId);
1236
+ }
1237
+ return {};
1238
+ }
1239
+ /** Write (upsert) a single key for a device to device_settings. */
1240
+ setDeviceConfig(deviceId, key, value) {
1241
+ if (this.settingsStore === null) {
1242
+ throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
1243
+ }
1244
+ this.settingsStore.setDevice(deviceId, key, value);
1245
+ }
1246
+ /** Get a value from the parsed bootstrap config */
1247
+ getBootstrap(path5) {
1248
+ return this.getFromBootstrap(path5);
1249
+ }
1250
+ /** Features accessor -- reads from SQL when available, falls back to RUNTIME_DEFAULTS */
1251
+ get features() {
1252
+ const g = (key) => this.get(`features.${key}`) ?? RUNTIME_DEFAULTS[`features.${key}`];
1253
+ return {
1254
+ streaming: g("streaming"),
1255
+ notifications: g("notifications"),
1256
+ objectDetection: g("objectDetection"),
1257
+ remoteAccess: g("remoteAccess"),
1258
+ agentCluster: g("agentCluster"),
1259
+ smartHome: g("smartHome"),
1260
+ recordings: g("recordings"),
1261
+ backup: g("backup"),
1262
+ repl: g("repl")
1263
+ };
1264
+ }
1265
+ /**
1266
+ * Returns a merged view of bootstrap config + runtime defaults for backward compat.
1267
+ */
1268
+ get raw() {
1269
+ const features = {
1270
+ streaming: RUNTIME_DEFAULTS["features.streaming"],
1271
+ notifications: RUNTIME_DEFAULTS["features.notifications"],
1272
+ objectDetection: RUNTIME_DEFAULTS["features.objectDetection"],
1273
+ remoteAccess: RUNTIME_DEFAULTS["features.remoteAccess"],
1274
+ agentCluster: RUNTIME_DEFAULTS["features.agentCluster"],
1275
+ smartHome: RUNTIME_DEFAULTS["features.smartHome"],
1276
+ recordings: RUNTIME_DEFAULTS["features.recordings"],
1277
+ backup: RUNTIME_DEFAULTS["features.backup"],
1278
+ repl: RUNTIME_DEFAULTS["features.repl"]
1279
+ };
1280
+ return {
1281
+ ...this.bootstrapConfig,
1282
+ features,
1283
+ storage: RUNTIME_DEFAULTS["storage.locations"] !== void 0 ? {
1284
+ provider: RUNTIME_DEFAULTS["storage.provider"],
1285
+ locations: RUNTIME_DEFAULTS["storage.locations"]
1286
+ } : { provider: "sqlite-storage", locations: {} },
1287
+ logging: {
1288
+ level: RUNTIME_DEFAULTS["logging.level"],
1289
+ retentionDays: RUNTIME_DEFAULTS["logging.retentionDays"]
1290
+ },
1291
+ eventBus: {
1292
+ ringBufferSize: RUNTIME_DEFAULTS["eventBus.ringBufferSize"]
1293
+ },
1294
+ retention: {
1295
+ detectionEventsDays: RUNTIME_DEFAULTS["retention.detectionEventsDays"],
1296
+ audioLevelsDays: RUNTIME_DEFAULTS["retention.audioLevelsDays"]
1297
+ },
1298
+ providers: RUNTIME_DEFAULTS["providers"]
1299
+ };
1300
+ }
1301
+ /** Sections that live in config.yaml. Everything else goes to SQL. */
1302
+ static BOOTSTRAP_SECTIONS = /* @__PURE__ */ new Set(["server", "auth", "mode"]);
1303
+ /**
1304
+ * Atomically update one top-level section of config.yaml and sync in-memory.
1305
+ * Only bootstrap sections (server, auth, mode) are written to YAML.
1306
+ * Runtime settings must use setSection() which writes to SQL.
1307
+ */
1308
+ update(section, data) {
1309
+ if (!_ConfigManager.BOOTSTRAP_SECTIONS.has(section)) {
1310
+ throw new Error(
1311
+ `[ConfigManager] Section "${section}" is a runtime setting \u2014 use setSection() to write to DB, not update() which writes to config.yaml`
1312
+ );
1313
+ }
1314
+ let raw = {};
1315
+ if (fs5.existsSync(this.configPath)) {
1316
+ raw = yaml.load(fs5.readFileSync(this.configPath, "utf-8")) ?? {};
1317
+ }
1318
+ const existing = raw[section] ?? {};
1319
+ raw[section] = { ...existing, ...data };
1320
+ const validation = bootstrapSchema.safeParse(raw);
1321
+ if (!validation.success) {
1322
+ throw new Error(`[ConfigManager] Invalid config update for section "${section}": ${validation.error.message}`);
1323
+ }
1324
+ const tmpPath = `${this.configPath}.tmp`;
1325
+ fs5.writeFileSync(tmpPath, yaml.dump(raw, { lineWidth: 120, indent: 2, quotingType: '"' }), "utf-8");
1326
+ fs5.renameSync(tmpPath, this.configPath);
1327
+ this.bootstrapConfig = validation.data;
1328
+ }
1329
+ /**
1330
+ * Deep-set a value in a nested plain object using a dot-notation path.
1331
+ * Returns a new object (immutable).
1332
+ */
1333
+ setNested(obj, path5, value) {
1334
+ const [head, ...rest] = path5.split(".");
1335
+ if (!head) return obj;
1336
+ if (rest.length === 0) {
1337
+ return { ...obj, [head]: value };
1338
+ }
1339
+ const child = obj[head] ?? {};
1340
+ return { ...obj, [head]: this.setNested(child, rest.join("."), value) };
1341
+ }
1342
+ /**
1343
+ * Apply env var overrides onto the raw YAML object.
1344
+ * Only bootstrap-level env vars are applied.
1345
+ */
1346
+ applyEnvOverrides(raw) {
1347
+ let result = { ...raw };
1348
+ for (const [envKey, configPath] of Object.entries(ENV_VAR_MAP)) {
1349
+ const envValue = process.env[envKey];
1350
+ if (envValue === void 0 || envValue === "") continue;
1351
+ const coerced = configPath === "server.port" ? Number(envValue) : envValue;
1352
+ result = this.setNested(result, configPath, coerced);
1353
+ console.log(`[ConfigManager] Env override applied: ${envKey} \u2192 ${configPath}`);
1354
+ }
1355
+ return result;
1356
+ }
1357
+ loadYaml() {
1358
+ if (!fs5.existsSync(this.configPath)) {
1359
+ console.warn(
1360
+ `[ConfigManager] Config file not found at: ${this.configPath}
1361
+ \u2192 Using built-in defaults. Set CONFIG_PATH env var or create the file.
1362
+ \u2192 Example path from project root: ./server/backend/data/config.yaml`
1363
+ );
1364
+ return {};
1365
+ }
1366
+ const content = fs5.readFileSync(this.configPath, "utf-8");
1367
+ const parsed = yaml.load(content) ?? {};
1368
+ console.log(`[ConfigManager] Loaded config from: ${this.configPath}`);
1369
+ return parsed;
1370
+ }
1371
+ warnDefaultCredentials() {
1372
+ if (this.bootstrapConfig.auth.adminPassword === "changeme") {
1373
+ console.warn(
1374
+ `[ConfigManager] Warning: Using default admin password "changeme". Set auth.adminPassword in your config.yaml or the ADMIN_PASSWORD env var.`
1375
+ );
1376
+ }
1377
+ }
1378
+ getFromBootstrap(path5) {
1379
+ const keys = path5.split(".");
1380
+ let current = this.bootstrapConfig;
1381
+ for (const key of keys) {
1382
+ if (current === null || current === void 0 || typeof current !== "object") {
1383
+ return void 0;
1384
+ }
1385
+ current = current[key];
1386
+ }
1387
+ return current;
1388
+ }
1389
+ getFromRuntimeDefaults(path5) {
1390
+ const prefix = path5 + ".";
1391
+ const result = {};
1392
+ let found = false;
1393
+ for (const [key, value] of Object.entries(RUNTIME_DEFAULTS)) {
1394
+ if (key.startsWith(prefix)) {
1395
+ const subKey = key.slice(prefix.length);
1396
+ result[subKey] = value;
1397
+ found = true;
1398
+ }
1399
+ }
1400
+ return found ? result : void 0;
1401
+ }
1402
+ /**
1403
+ * Perform a prefix-based nested lookup against SQL system_settings.
1404
+ * e.g. path='features' matches keys 'features.streaming', 'features.notifications', etc.
1405
+ * Returns an object keyed by the sub-key, or undefined if nothing is found.
1406
+ */
1407
+ getNestedFromSystemSettings(path5) {
1408
+ if (this.settingsStore === null) return void 0;
1409
+ const all = this.settingsStore.getAllSystem();
1410
+ const prefix = path5 + ".";
1411
+ const result = {};
1412
+ let found = false;
1413
+ for (const [key, value] of Object.entries(all)) {
1414
+ if (key.startsWith(prefix)) {
1415
+ result[key.slice(prefix.length)] = value;
1416
+ found = true;
1417
+ }
1418
+ }
1419
+ return found ? result : void 0;
1420
+ }
1421
+ };
1422
+
1423
+ // src/worker/addon-worker-host.ts
1424
+ var import_node_child_process3 = require("child_process");
1425
+ var INFRA_ADDON_IDS = /* @__PURE__ */ new Set([
1426
+ "filesystem-storage",
1427
+ "sqlite-settings",
1428
+ "winston-logging"
1429
+ ]);
1430
+ var AddonWorkerHost = class {
1431
+ workers = /* @__PURE__ */ new Map();
1432
+ options;
1433
+ heartbeatTimer = null;
1434
+ /** Set of addons that failed to fork and fell back to in-process */
1435
+ fallbackInProcess = /* @__PURE__ */ new Set();
1436
+ constructor(options) {
1437
+ this.options = {
1438
+ workerEntryPath: options.workerEntryPath,
1439
+ devMode: options.devMode ?? false,
1440
+ forceInProcess: options.forceInProcess ?? process.env.CAMSTACK_FORCE_INPROCESS === "true",
1441
+ heartbeatIntervalMs: options.heartbeatIntervalMs ?? 5e3,
1442
+ heartbeatTimeoutMs: options.heartbeatTimeoutMs ?? 3e4,
1443
+ maxCrashesInWindow: options.maxCrashesInWindow ?? 3,
1444
+ crashWindowMs: options.crashWindowMs ?? 6e4,
1445
+ shutdownTimeoutMs: options.shutdownTimeoutMs ?? 1e4,
1446
+ onWorkerLog: options.onWorkerLog
1447
+ };
1448
+ }
1449
+ /** Check if an addon is infrastructure (must stay in-process) */
1450
+ isInfraAddon(addonId) {
1451
+ return INFRA_ADDON_IDS.has(addonId);
1452
+ }
1453
+ /** Check if an addon fell back to in-process after fork failure */
1454
+ isFallbackInProcess(addonId) {
1455
+ return this.fallbackInProcess.has(addonId);
1456
+ }
1457
+ /** Mark an addon as fallen back to in-process */
1458
+ markFallbackInProcess(addonId) {
1459
+ this.fallbackInProcess.add(addonId);
1460
+ }
1461
+ /**
1462
+ * Determine if an addon should be forked.
1463
+ * Default: fork everything except infra addons.
1464
+ * Addons can opt out with `inProcess: true` in declaration.
1465
+ * Emergency fallback: CAMSTACK_FORCE_INPROCESS=true disables all forking.
1466
+ */
1467
+ shouldFork(addonId, declaration) {
1468
+ if (this.options.forceInProcess) return false;
1469
+ if (this.options.devMode) return false;
1470
+ if (this.isInfraAddon(addonId)) return false;
1471
+ if (this.fallbackInProcess.has(addonId)) return false;
1472
+ if (declaration?.inProcess === true) return false;
1473
+ if (declaration?.forkable !== true) return false;
1474
+ return true;
1475
+ }
1476
+ /** Fork a worker for an addon */
1477
+ async forkWorker(addonId, addonDir, config, storagePaths, dataDir, locationPaths, workerToken) {
1478
+ if (this.workers.has(addonId)) {
1479
+ throw new Error(`Worker for addon "${addonId}" already exists`);
1480
+ }
1481
+ const workerEnv = {
1482
+ PATH: process.env.PATH ?? "",
1483
+ HOME: process.env.HOME ?? "",
1484
+ NODE_ENV: process.env.NODE_ENV ?? "production",
1485
+ NODE_TLS_REJECT_UNAUTHORIZED: "0",
1486
+ // Accept self-signed cert
1487
+ CAMSTACK_WORKER_HUB_URL: `wss://localhost:${process.env.CAMSTACK_PORT ?? "4443"}/trpc`,
1488
+ CAMSTACK_WORKER_TOKEN: workerToken ?? "",
1489
+ CAMSTACK_ADDON_ID: addonId,
1490
+ CAMSTACK_ADDON_DIR: addonDir,
1491
+ CAMSTACK_ADDON_CONFIG: JSON.stringify(config),
1492
+ CAMSTACK_DATA_DIR: dataDir ?? `camstack-data/addons-data/${addonId}`,
1493
+ CAMSTACK_LOCATION_PATHS: JSON.stringify(locationPaths ?? storagePaths)
1494
+ };
1495
+ const forkOptions = {
1496
+ stdio: ["inherit", "inherit", "inherit", "ipc"],
1497
+ execArgv: [],
1498
+ env: workerEnv
1499
+ };
1500
+ const child = (0, import_node_child_process3.fork)(this.options.workerEntryPath, [], forkOptions);
1501
+ const worker = {
1502
+ addonId,
1503
+ process: child,
1504
+ state: "starting",
1505
+ startedAt: Date.now(),
1506
+ lastHeartbeat: Date.now(),
1507
+ restartCount: 0,
1508
+ crashTimestamps: [],
1509
+ cpuPercent: 0,
1510
+ memoryRss: 0,
1511
+ workerToken
1512
+ };
1513
+ this.workers.set(addonId, worker);
1514
+ child.on("message", (msg) => {
1515
+ if (msg.type === "LOG" && this.options.onWorkerLog) {
1516
+ this.options.onWorkerLog({
1517
+ addonId,
1518
+ level: msg.level,
1519
+ message: msg.message,
1520
+ scope: ["hub", addonId],
1521
+ meta: msg.context
1522
+ });
1523
+ } else if (msg.type === "STATS") {
1524
+ worker.cpuPercent = msg.cpu;
1525
+ worker.memoryRss = msg.memory;
1526
+ }
1527
+ });
1528
+ child.stdout?.on("data", (chunk) => {
1529
+ const lines = chunk.toString().trim();
1530
+ if (!lines) return;
1531
+ if (this.options.onWorkerLog) {
1532
+ this.options.onWorkerLog({
1533
+ addonId,
1534
+ level: "info",
1535
+ message: lines,
1536
+ scope: ["hub", addonId, "__stdout"]
1537
+ });
1538
+ } else {
1539
+ console.log(`[Worker:${addonId}] ${lines}`);
1540
+ }
1541
+ });
1542
+ child.stderr?.on("data", (chunk) => {
1543
+ const lines = chunk.toString().trim();
1544
+ if (!lines) return;
1545
+ if (this.options.onWorkerLog) {
1546
+ this.options.onWorkerLog({
1547
+ addonId,
1548
+ level: "error",
1549
+ message: lines,
1550
+ scope: ["hub", addonId, "__stderr"]
1551
+ });
1552
+ } else {
1553
+ console.error(`[Worker:${addonId}:ERR] ${lines}`);
1554
+ }
1555
+ });
1556
+ child.on("exit", (code) => {
1557
+ this.handleWorkerExit(addonId, code, addonDir, config, storagePaths, dataDir, locationPaths, workerToken);
1558
+ });
1559
+ child.on("error", (err) => {
1560
+ console.error(`[WorkerHost] Worker ${addonId} error:`, err.message);
1561
+ });
1562
+ await new Promise((resolve3, reject) => {
1563
+ const timeout = setTimeout(() => {
1564
+ reject(new Error(`Worker ${addonId} did not become ready within 30s`));
1565
+ }, 3e4);
1566
+ const readyCheck = (msg) => {
1567
+ if (msg.type === "READY") {
1568
+ clearTimeout(timeout);
1569
+ child.off("message", readyCheck);
1570
+ worker.state = "running";
1571
+ resolve3();
1572
+ }
1573
+ };
1574
+ child.on("message", readyCheck);
1575
+ });
1576
+ }
1577
+ /** List all workers with stats */
1578
+ listWorkers() {
1579
+ return [...this.workers.values()].map((w) => ({
1580
+ addonId: w.addonId,
1581
+ pid: w.process.pid ?? 0,
1582
+ state: w.state,
1583
+ cpuPercent: w.cpuPercent,
1584
+ memoryRss: w.memoryRss,
1585
+ uptimeSeconds: Math.round((Date.now() - w.startedAt) / 1e3),
1586
+ restartCount: w.restartCount,
1587
+ subProcesses: []
1588
+ }));
1589
+ }
1590
+ /** Gracefully shutdown a single worker by addon ID */
1591
+ async shutdownWorkerById(addonId) {
1592
+ const worker = this.workers.get(addonId);
1593
+ if (!worker) {
1594
+ throw new Error(`No worker found for addon "${addonId}"`);
1595
+ }
1596
+ await this.shutdownWorker(addonId, worker);
1597
+ this.workers.delete(addonId);
1598
+ }
1599
+ /** Gracefully shutdown all workers */
1600
+ async shutdownAll() {
1601
+ if (this.heartbeatTimer) {
1602
+ clearInterval(this.heartbeatTimer);
1603
+ this.heartbeatTimer = null;
1604
+ }
1605
+ const shutdowns = [...this.workers.entries()].map(
1606
+ ([addonId, worker]) => this.shutdownWorker(addonId, worker)
1607
+ );
1608
+ await Promise.allSettled(shutdowns);
1609
+ this.workers.clear();
1610
+ }
1611
+ /** Start heartbeat monitoring — workers now report heartbeat via tRPC, not IPC PING */
1612
+ startHeartbeatMonitoring() {
1613
+ this.heartbeatTimer = setInterval(() => {
1614
+ const now = Date.now();
1615
+ for (const [addonId, worker] of this.workers) {
1616
+ if (worker.state !== "running") continue;
1617
+ if (now - worker.lastHeartbeat > this.options.heartbeatTimeoutMs) {
1618
+ console.warn(`[WorkerHost] Worker ${addonId} heartbeat timeout \u2014 marking unresponsive`);
1619
+ worker.state = "crashed";
1620
+ worker.process.kill("SIGKILL");
1621
+ }
1622
+ }
1623
+ }, this.options.heartbeatIntervalMs);
1624
+ }
1625
+ /** Update heartbeat timestamp for a worker (called when agent.heartbeat arrives) */
1626
+ updateWorkerHeartbeat(addonId, cpuPercent, memoryRss) {
1627
+ const worker = this.workers.get(addonId);
1628
+ if (!worker) return;
1629
+ worker.lastHeartbeat = Date.now();
1630
+ if (cpuPercent !== void 0) worker.cpuPercent = cpuPercent;
1631
+ if (memoryRss !== void 0) worker.memoryRss = memoryRss;
1632
+ }
1633
+ handleWorkerExit(addonId, code, addonDir, config, storagePaths, dataDir, locationPaths, workerToken) {
1634
+ const worker = this.workers.get(addonId);
1635
+ if (!worker) return;
1636
+ if (worker.state === "stopping") {
1637
+ worker.state = "stopped";
1638
+ return;
1639
+ }
1640
+ worker.state = "crashed";
1641
+ console.error(`[WorkerHost] Worker ${addonId} exited with code ${code}`);
1642
+ const now = Date.now();
1643
+ worker.crashTimestamps.push(now);
1644
+ const recentCrashes = worker.crashTimestamps.filter(
1645
+ (t) => now - t < this.options.crashWindowMs
1646
+ );
1647
+ worker.crashTimestamps = recentCrashes;
1648
+ if (recentCrashes.length >= this.options.maxCrashesInWindow) {
1649
+ console.error(`[WorkerHost] Worker ${addonId} crashed ${recentCrashes.length} times in ${this.options.crashWindowMs}ms \u2014 not restarting`);
1650
+ return;
1651
+ }
1652
+ const backoff = Math.min(2e3 * (worker.restartCount + 1), 3e4);
1653
+ console.log(`[WorkerHost] Restarting worker ${addonId} in ${backoff}ms`);
1654
+ setTimeout(() => {
1655
+ worker.restartCount++;
1656
+ this.workers.delete(addonId);
1657
+ this.forkWorker(addonId, addonDir, config, storagePaths, dataDir, locationPaths, workerToken).catch((err) => {
1658
+ console.error(`[WorkerHost] Failed to restart worker ${addonId}:`, err);
1659
+ });
1660
+ }, backoff);
1661
+ }
1662
+ async shutdownWorker(addonId, worker) {
1663
+ worker.state = "stopping";
1664
+ worker.process.kill("SIGTERM");
1665
+ await new Promise((resolve3) => {
1666
+ const timeout = setTimeout(() => {
1667
+ console.warn(`[WorkerHost] Worker ${addonId} did not exit within ${this.options.shutdownTimeoutMs}ms \u2014 SIGKILL`);
1668
+ worker.process.kill("SIGKILL");
1669
+ resolve3();
1670
+ }, this.options.shutdownTimeoutMs);
1671
+ worker.process.on("exit", () => {
1672
+ clearTimeout(timeout);
1673
+ resolve3();
1674
+ });
1675
+ });
1676
+ }
1677
+ };
1678
+
1679
+ // src/worker/worker-process-manager.ts
1680
+ var import_node_child_process4 = require("child_process");
1681
+ var WorkerProcessManager = class {
1682
+ constructor(sendToMain) {
1683
+ this.sendToMain = sendToMain;
1684
+ }
1685
+ processes = /* @__PURE__ */ new Map();
1686
+ async spawn(config) {
1687
+ const child = (0, import_node_child_process4.spawn)(config.command, [...config.args ?? []], {
1688
+ cwd: config.cwd,
1689
+ env: config.env ? { ...process.env, ...config.env } : void 0,
1690
+ stdio: ["pipe", "pipe", "pipe"]
1691
+ });
1692
+ const managed = new ManagedProcess(child, config, this.sendToMain);
1693
+ this.processes.set(child.pid, managed);
1694
+ this.sendToMain({
1695
+ type: "SUB_PROCESS_SPAWNED",
1696
+ pid: child.pid,
1697
+ name: config.name,
1698
+ command: config.command
1699
+ });
1700
+ child.on("exit", (code) => {
1701
+ this.sendToMain({
1702
+ type: "SUB_PROCESS_EXITED",
1703
+ pid: child.pid,
1704
+ code
1705
+ });
1706
+ if (config.autoRestart && managed.restartCount < (config.maxRestarts ?? 3)) {
1707
+ managed.restartCount++;
1708
+ setTimeout(() => {
1709
+ this.spawn(config).catch(() => {
1710
+ });
1711
+ }, 2e3);
1712
+ }
1713
+ });
1714
+ return managed;
1715
+ }
1716
+ listProcesses() {
1717
+ return [...this.processes.values()].map((p) => p.toInfo());
1718
+ }
1719
+ getWorkerStats() {
1720
+ const mem = process.memoryUsage();
1721
+ const cpu = process.cpuUsage();
1722
+ return {
1723
+ pid: process.pid,
1724
+ cpuPercent: (cpu.user + cpu.system) / 1e6,
1725
+ memoryRss: mem.rss,
1726
+ heapUsed: mem.heapUsed,
1727
+ uptimeSeconds: Math.round(process.uptime()),
1728
+ restartCount: 0,
1729
+ state: "running"
1730
+ };
1731
+ }
1732
+ async killAll() {
1733
+ for (const [, proc] of this.processes) {
1734
+ proc.kill("SIGTERM");
1735
+ }
1736
+ this.processes.clear();
1737
+ }
1738
+ };
1739
+ var ManagedProcess = class {
1740
+ constructor(child, config, sendToMain) {
1741
+ this.child = child;
1742
+ this.config = config;
1743
+ this.sendToMain = sendToMain;
1744
+ this.pid = child.pid;
1745
+ this.name = config.name;
1746
+ child.on("exit", (code) => {
1747
+ for (const handler of this.exitHandlers) handler(code);
1748
+ });
1749
+ child.on("error", (err) => {
1750
+ for (const handler of this.errorHandlers) handler(err);
1751
+ });
1752
+ }
1753
+ pid;
1754
+ name;
1755
+ restartCount = 0;
1756
+ startedAt = Date.now();
1757
+ exitHandlers = [];
1758
+ errorHandlers = [];
1759
+ getStats() {
1760
+ return {
1761
+ pid: this.pid,
1762
+ cpuPercent: 0,
1763
+ memoryRss: 0,
1764
+ uptimeSeconds: Math.round((Date.now() - this.startedAt) / 1e3),
1765
+ restartCount: this.restartCount,
1766
+ state: this.child.exitCode !== null ? "stopped" : "running"
1767
+ };
1768
+ }
1769
+ write(data) {
1770
+ this.child.stdin?.write(data);
1771
+ }
1772
+ get stdout() {
1773
+ return this.child.stdout;
1774
+ }
1775
+ get stderr() {
1776
+ return this.child.stderr;
1777
+ }
1778
+ kill(signal = "SIGTERM") {
1779
+ this.child.kill(signal);
1780
+ }
1781
+ wait() {
1782
+ if (this.child.exitCode !== null) {
1783
+ return Promise.resolve({ code: this.child.exitCode, signal: null });
1784
+ }
1785
+ return new Promise((resolve3) => {
1786
+ this.child.on("exit", (code, signal) => {
1787
+ resolve3({ code, signal });
1788
+ });
1789
+ });
1790
+ }
1791
+ onExit(handler) {
1792
+ this.exitHandlers.push(handler);
1793
+ }
1794
+ onError(handler) {
1795
+ this.errorHandlers.push(handler);
1796
+ }
1797
+ toInfo() {
1798
+ return {
1799
+ pid: this.pid,
1800
+ name: this.name,
1801
+ command: this.config.command,
1802
+ state: this.child.exitCode !== null ? "stopped" : "running",
1803
+ cpuPercent: 0,
1804
+ memoryRss: 0,
1805
+ uptimeSeconds: Math.round((Date.now() - this.startedAt) / 1e3)
1806
+ };
1807
+ }
1808
+ };
1809
+ // Annotate the CommonJS export names for ESM import in node:
1810
+ 0 && (module.exports = {
1811
+ AddonEngineManager,
1812
+ AddonInstaller,
1813
+ AddonLoader,
1814
+ AddonWorkerHost,
1815
+ CapabilityRegistry,
1816
+ ConfigManager,
1817
+ DEFAULT_DATA_PATH,
1818
+ INFRA_CAPABILITIES,
1819
+ RUNTIME_DEFAULTS,
1820
+ WorkerProcessManager,
1821
+ bootstrapSchema,
1822
+ copyDirRecursive,
1823
+ copyExtraFileDirs,
1824
+ detectWorkspacePackagesDir,
1825
+ ensureDir,
1826
+ ensureLibraryBuilt,
1827
+ installPackageFromNpmSync,
1828
+ isInfraCapability,
1829
+ isSourceNewer,
1830
+ stripCamstackDeps,
1831
+ symlinkAddonsToNodeModules
1832
+ });
1833
+ //# sourceMappingURL=index.js.map