@camstack/system 1.2.69 → 1.2.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/addon-runner.js +6 -6
  2. package/dist/addon-runner.mjs +3 -3
  3. package/dist/addon-utils.js +11 -11
  4. package/dist/addon-utils.mjs +1 -1
  5. package/dist/auth/auth-manager.d.ts +13 -29
  6. package/dist/auth/scope-matcher.d.ts +6 -5
  7. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +3 -3
  8. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +2 -2
  9. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +3 -3
  10. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +2 -2
  11. package/dist/builtins/alerts/alerts.addon.js +1 -1
  12. package/dist/builtins/alerts/alerts.addon.mjs +1 -1
  13. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +8 -8
  14. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +6 -6
  15. package/dist/builtins/console-logging/index.js +1 -1
  16. package/dist/builtins/console-logging/index.mjs +1 -1
  17. package/dist/builtins/core-blocks/core-blocks.addon.js +3 -3
  18. package/dist/builtins/core-blocks/core-blocks.addon.mjs +2 -2
  19. package/dist/builtins/device-manager/device-manager.addon.js +2 -2
  20. package/dist/builtins/device-manager/device-manager.addon.mjs +2 -2
  21. package/dist/builtins/doorbell/virtual-doorbell.addon.js +1 -1
  22. package/dist/builtins/doorbell/virtual-doorbell.addon.mjs +1 -1
  23. package/dist/builtins/hub-forwarder/index.js +1 -1
  24. package/dist/builtins/hub-forwarder/index.mjs +1 -1
  25. package/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  26. package/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  27. package/dist/builtins/local-auth/index.d.ts +0 -1
  28. package/dist/builtins/local-auth/index.js +0 -1
  29. package/dist/builtins/local-auth/index.mjs +2 -2
  30. package/dist/builtins/local-auth/local-auth.addon.js +4878 -4883
  31. package/dist/builtins/local-auth/local-auth.addon.mjs +4879 -4883
  32. package/dist/builtins/local-auth/oauth-grants.d.ts +15 -0
  33. package/dist/builtins/local-network/local-network.addon.js +1 -1
  34. package/dist/builtins/local-network/local-network.addon.mjs +1 -1
  35. package/dist/builtins/loki-logging/index.js +1 -1
  36. package/dist/builtins/loki-logging/index.mjs +1 -1
  37. package/dist/builtins/native-metrics/native-metrics.addon.js +5 -5
  38. package/dist/builtins/native-metrics/native-metrics.addon.mjs +4 -4
  39. package/dist/builtins/platform-probe/index.js +4 -4
  40. package/dist/builtins/platform-probe/index.mjs +3 -3
  41. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  42. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  43. package/dist/builtins/snapshot/index.js +2 -2
  44. package/dist/builtins/snapshot/index.mjs +2 -2
  45. package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +4 -4
  46. package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +3 -3
  47. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +1 -1
  48. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +1 -1
  49. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +3 -3
  50. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +2 -2
  51. package/dist/builtins/system-config/system-config.addon.js +1 -1
  52. package/dist/builtins/system-config/system-config.addon.mjs +1 -1
  53. package/dist/builtins/winston-logging/index.js +1 -1
  54. package/dist/builtins/winston-logging/index.mjs +1 -1
  55. package/dist/{dist-C-QzFJ8v.mjs → dist-Daxx9CB0.mjs} +139 -5
  56. package/dist/{dist-D7wC-S4p.js → dist-I0WgqQQ-.js} +150 -10
  57. package/dist/{model-download-service-CTBHzORJ.mjs → file-data-plane-CuE_hBli.mjs} +848 -848
  58. package/dist/index.d.ts +73 -81
  59. package/dist/index.js +1302 -1278
  60. package/dist/index.mjs +1283 -1259
  61. package/dist/kernel/capability-registry.d.ts +26 -0
  62. package/dist/kernel/config-schema.d.ts +1 -1
  63. package/dist/kernel/transport/parent-unowned-call.d.ts +27 -0
  64. package/dist/{manifest-python-deps-Dz1ryHIN.mjs → manifest-python-deps-BdWxKNvu.mjs} +49 -47
  65. package/dist/{manifest-python-deps-BE6l8Y4W.js → manifest-python-deps-BqIpg0C7.js} +49 -47
  66. package/package.json +1 -4
  67. package/dist/builtins/local-auth/homeassistant-integration.d.ts +0 -7
  68. package/dist/{model-download-service-Caj1kaSi.js → file-data-plane-DUHPHa-Y.js} +847 -847
  69. package/dist/{resource-monitor-BkP504Vq.mjs → resource-monitor-BWmQ5i-o.mjs} +1 -1
  70. package/dist/{resource-monitor-DNNomR-i.js → resource-monitor-CdnzxBLP.js} +1 -1
package/dist/index.mjs CHANGED
@@ -1,48 +1,48 @@
1
1
  import { a as __toCommonJS, i as __require, n as __esmMin, o as __toESM$1, r as __exportAll, t as __commonJSMin$1 } from "./chunk-CNf5ZN-e.mjs";
2
- import { $ as objectInputDeclaresAddonId, B as isCollectionArrayMethod, Ct as asJsonObject$1, Dt as emitDownForOwnedCaps, Et as createEvent, Ft as readinessKey, G as lifecycleJobSchema, It as resolveCapMount, J as logLevelAtMost, L as extractNestedAddonId, Lt as scopeKey, Nt as parseJsonObject, Pt as parseJsonUnknown$1, Tt as asString$1, U as isVoidInput, V as isObjectInput, W as kebabToCamel, Y as looseSchema, bt as ReadinessRegistry, d as METHOD_ACCESS_MAP, f as RUNTIME_DEFAULTS, ft as errMsg$1, gt as DEVICE_STATUS_METHOD, ht as DEVICE_SETTINGS_CONTRIBUTION_METHODS, kt as expandCapMethods, mt as DATAPLANE_SECRET_HEADER$1, nt as procedureAuthKey, t as ALL_CAPABILITY_DEFINITIONS, v as addonSettingsCapability, wt as asNumber, xt as ReadinessTimeoutError, z as isArrayOutputSchema, zt as EventCategory$1 } from "./dist-C-QzFJ8v.mjs";
3
- import { a as downloadModel, c as getModelFilePath, d as contentTypeFor, f as createAuthenticatedFileServer, h as resolveFilePath, i as downloadFile, l as isModelDownloaded, m as parseTokenizedUrl, n as collectModelFiles, o as ensureModel, p as parseRangeHeader, r as deleteModelFromDisk, s as fetchJson, t as ModelDownloadService, u as createFileDataPlaneHandler } from "./model-download-service-CTBHzORJ.mjs";
4
- import { $ as buildNativeCapProxy, A as createHubCapForwardService, B as AGENT_CAP_FWD_ACTION, C as brokerTransportLink, Ct as resolveAddonClass, D as localProviderLink, E as ipcParentLink, F as createUdsLogger, G as callWithServiceDiscovery, H as CapRouteResolver, I as createUdsLoggerWithControl, J as UdsLocalTransportServer, K as createLocalTransport, L as LocalChildClient, M as createUdsEventBridge, N as createUdsEventBus, O as HUB_CAP_FWD_ACTION, P as udsChildLogToWorkerEntry, Q as encodeFrame, R as LocalChildRegistry, S as brokerCallForCap, St as runNpm, T as ipcChildLink, U as CapRouteError, V as AGENT_CAP_FWD_SERVICE, W as classifyCapRoute, X as localEndpointPath, Y as SocketChannel, Z as FrameDecoder, _ as createKernelHwAccel, _t as CapabilityHandle, a as getWorkerDeviceRegistry, b as __resetCapUsageRegistryForTests, bt as installManifestNativeDeps, c as setHubConnected, ct as NATIVE_PROVIDER_SERVICE_INFIX, d as getBrokerEventBus, dt as capBareAction, et as buildUdsNativeCapProxy, f as getMoleculerEventStats, ft as capServiceName, g as AddonDepsManager, gt as DeviceRegistry, h as subscribePassthrough, ht as serializeTypedArrays, i as createUdsAddonContext, it as mountNativeCapService, j as createParentUnownedCallHandler, k as HUB_CAP_FWD_SERVICE, l as EVENT_TOPIC_PREFIX, lt as capActionName, m as setNodeEventInterest, mt as deserializeTypedArrays, n as adaptBrokerToCluster, o as getOrInitReadinessRegistry, ot as createAddonService, p as registerEventBusService, pt as parseCapAction, q as UdsLocalTransportClient, r as createAddonContext, s as getOrInitReadinessRegistryForClient, st as validateProviderRegistrations, t as installManifestPythonDeps, tt as createBrokerDeviceManagerApi, u as clusterEventTopic, ut as capActionSuffix, v as resolveHwAccel, vt as CapabilityUnavailableError, w as buildLinkChain, wt as createAddonDataPlaneFacility, x as getCapUsageRegistry, xt as resolveNpmInvocation, y as CapUsageRegistry, yt as copyBundledNativeModules, z as UDS_NO_ROUTE_PREFIX } from "./manifest-python-deps-Dz1ryHIN.mjs";
5
- import { n as getSinglePidStats, t as getPidStats } from "./resource-monitor-BkP504Vq.mjs";
6
- import { FilesystemStorageAddon, t as FilesystemStorageProvider } from "./builtins/sqlite-storage/filesystem-storage.addon.mjs";
7
- import { SqliteSettingsAddon, o as SqliteSettingsBackend } from "./builtins/sqlite-storage/sqlite-settings.addon.mjs";
8
- import { ConfigStore, DeviceStore } from "./builtins/sqlite-storage/index.mjs";
2
+ import { At as expandCapMethods, B as isCollectionArrayMethod, Bt as EventCategory$1, Dt as createEvent, Et as asString$1, Ft as parseJsonUnknown$1, G as lifecycleJobSchema, It as readinessKey, J as logLevelAtMost, L as extractNestedAddonId, Lt as resolveCapMount, Ot as emitDownForOwnedCaps, Pt as parseJsonObject, Q as objectInputDeclaresAddonId, Rt as scopeKey, St as ReadinessTimeoutError, Tt as asNumber, U as isVoidInput, V as isObjectInput, W as kebabToCamel, Y as looseSchema, _t as DEVICE_STATUS_METHOD, d as METHOD_ACCESS_MAP, f as RUNTIME_DEFAULTS, gt as DEVICE_SETTINGS_CONTRIBUTION_METHODS, ht as DATAPLANE_SECRET_HEADER$1, nt as scopesAllowAddon, pt as errMsg$1, rt as scopesAllowDeviceCap, t as ALL_CAPABILITY_DEFINITIONS, tt as procedureAuthKey, v as addonSettingsCapability, wt as asJsonObject$1, xt as ReadinessRegistry, z as isArrayOutputSchema } from "./dist-Daxx9CB0.mjs";
3
+ import { AlertCenterAddon } from "./builtins/alerts/alerts.addon.mjs";
4
+ import "./builtins/alerts/index.mjs";
9
5
  import { t as formatLogLine } from "./formatter-B7qW8bPJ.mjs";
10
- import { WinstonDestination, WinstonLoggingAddon } from "./builtins/winston-logging/index.mjs";
11
6
  import { ConsoleDestination, ConsoleLoggingAddon } from "./builtins/console-logging/index.mjs";
12
- import { LokiDestination, LokiLoggingAddon } from "./builtins/loki-logging/index.mjs";
7
+ import { CoreBlocksAddon } from "./builtins/core-blocks/core-blocks.addon.mjs";
8
+ import "./builtins/core-blocks/index.mjs";
9
+ import { DeviceManagerAddon } from "./builtins/device-manager/device-manager.addon.mjs";
10
+ import "./builtins/device-manager/index.mjs";
13
11
  import { HubForwarderAddon, HubForwarderDestination } from "./builtins/hub-forwarder/index.mjs";
14
- import { StorageOrchestratorAddon, n as StorageOrchestratorService } from "./builtins/storage-orchestrator/storage-orchestrator.addon.mjs";
15
- import "./builtins/storage-orchestrator/index.mjs";
16
- import NativeMetricsAddon, { t as NativeMetricsProvider } from "./builtins/native-metrics/native-metrics.addon.mjs";
17
- import { AlertCenterAddon } from "./builtins/alerts/alerts.addon.mjs";
18
- import "./builtins/alerts/index.mjs";
19
12
  import { LivenessMonitorAddon } from "./builtins/liveness-monitor/liveness-monitor.addon.mjs";
20
13
  import "./builtins/liveness-monitor/index.mjs";
14
+ import { LocalAuthAddon, a as require_safe_buffer, i as require_ms, n as ScopedTokenManager, o as ApiKeyManager, r as AuthManager, t as UserManager } from "./builtins/local-auth/local-auth.addon.mjs";
15
+ import "./builtins/local-auth/index.mjs";
16
+ import { LokiDestination, LokiLoggingAddon } from "./builtins/loki-logging/index.mjs";
17
+ import NativeMetricsAddon, { t as NativeMetricsProvider } from "./builtins/native-metrics/native-metrics.addon.mjs";
18
+ import { FilesystemStorageAddon, t as FilesystemStorageProvider } from "./builtins/sqlite-storage/filesystem-storage.addon.mjs";
19
+ import { SqliteSettingsAddon, o as SqliteSettingsBackend } from "./builtins/sqlite-storage/sqlite-settings.addon.mjs";
20
+ import { ConfigStore, DeviceStore } from "./builtins/sqlite-storage/index.mjs";
21
+ import { StorageOrchestratorAddon, n as StorageOrchestratorService } from "./builtins/storage-orchestrator/storage-orchestrator.addon.mjs";
22
+ import "./builtins/storage-orchestrator/index.mjs";
21
23
  import { SystemConfigAddon } from "./builtins/system-config/system-config.addon.mjs";
22
24
  import "./builtins/system-config/index.mjs";
23
- import { CoreBlocksAddon } from "./builtins/core-blocks/core-blocks.addon.mjs";
24
- import "./builtins/core-blocks/index.mjs";
25
- import { LocalAuthAddon, a as require_safe_buffer, i as require_ms, n as ScopedTokenManager, o as ApiKeyManager, r as AuthManager, s as HOME_ASSISTANT_OAUTH_INTEGRATION, t as UserManager } from "./builtins/local-auth/local-auth.addon.mjs";
26
- import "./builtins/local-auth/index.mjs";
27
- import { DeviceManagerAddon } from "./builtins/device-manager/device-manager.addon.mjs";
28
- import "./builtins/device-manager/index.mjs";
25
+ import { WinstonDestination, WinstonLoggingAddon } from "./builtins/winston-logging/index.mjs";
26
+ import { a as parseTokenizedUrl, c as collectModelFiles, d as downloadModel, f as ensureModel, h as isModelDownloaded, i as parseRangeHeader, l as deleteModelFromDisk, m as getModelFilePath, n as contentTypeFor, o as resolveFilePath, p as fetchJson, r as createAuthenticatedFileServer, s as ModelDownloadService, t as createFileDataPlaneHandler, u as downloadFile } from "./file-data-plane-CuE_hBli.mjs";
27
+ import { $ as buildNativeCapProxy, A as createHubCapForwardService, B as AGENT_CAP_FWD_ACTION, C as brokerTransportLink, Ct as runNpm, D as localProviderLink, E as ipcParentLink, F as createUdsLogger, G as callWithServiceDiscovery, H as CapRouteResolver, I as createUdsLoggerWithControl, J as UdsLocalTransportServer, K as createLocalTransport, L as LocalChildClient, M as createUdsEventBridge, N as createUdsEventBus, O as HUB_CAP_FWD_ACTION, P as udsChildLogToWorkerEntry, Q as encodeFrame, R as LocalChildRegistry, S as brokerCallForCap, St as resolveNpmInvocation, T as ipcChildLink, U as CapRouteError, V as AGENT_CAP_FWD_SERVICE, W as classifyCapRoute, X as localEndpointPath, Y as SocketChannel, Z as FrameDecoder, _ as createKernelHwAccel, _t as CapabilityHandle, a as getWorkerDeviceRegistry, b as __resetCapUsageRegistryForTests, bt as installManifestNativeDeps, c as setHubConnected, ct as NATIVE_PROVIDER_SERVICE_INFIX, d as getBrokerEventBus, dt as capBareAction, et as buildUdsNativeCapProxy, f as getMoleculerEventStats, ft as capServiceName, g as AddonDepsManager, gt as DeviceRegistry, h as subscribePassthrough, ht as serializeTypedArrays, i as createUdsAddonContext, it as mountNativeCapService, j as createParentUnownedCallHandler, k as HUB_CAP_FWD_SERVICE, l as EVENT_TOPIC_PREFIX, lt as capActionName, m as setNodeEventInterest, mt as deserializeTypedArrays, n as adaptBrokerToCluster, o as getOrInitReadinessRegistry, ot as createAddonService, p as registerEventBusService, pt as parseCapAction, q as UdsLocalTransportClient, r as createAddonContext, s as getOrInitReadinessRegistryForClient, st as validateProviderRegistrations, t as installManifestPythonDeps, tt as createBrokerDeviceManagerApi, u as clusterEventTopic, ut as capActionSuffix, v as resolveHwAccel, vt as CapabilityUnavailableError, w as buildLinkChain, wt as createAddonDataPlaneFacility, x as getCapUsageRegistry, xt as resolveAddonClass, y as CapUsageRegistry, yt as copyBundledNativeModules, z as UDS_NO_ROUTE_PREFIX } from "./manifest-python-deps-BdWxKNvu.mjs";
28
+ import { n as getSinglePidStats, t as getPidStats } from "./resource-monitor-BWmQ5i-o.mjs";
29
29
  import { t as CustomActionRegistry } from "./custom-action-registry-F__gp_VX.mjs";
30
- import * as v8 from "node:v8";
31
- import * as vm from "node:vm";
32
- import { PYTHON_VERSION, buildBinaryPath, downloadBinary, ensureBinary, ensureFfmpeg, ensurePython, findInPath, getFfmpegDownloadUrl, getPlatformInfo, getPythonDownloadUrl, installPythonPackages, installPythonRequirements } from "@camstack/types/node";
33
30
  import { z } from "zod";
34
31
  import { X509Certificate, createHash, randomUUID, timingSafeEqual } from "node:crypto";
35
- import { request } from "node:http";
36
- import * as fs$17 from "node:fs";
37
- import { accessSync, constants, existsSync, mkdirSync, readFileSync } from "node:fs";
32
+ import { PYTHON_VERSION, buildBinaryPath, downloadBinary, ensureBinary, ensureFfmpeg, ensurePython, findInPath, getFfmpegDownloadUrl, getPlatformInfo, getPythonDownloadUrl, installPythonPackages, installPythonRequirements } from "@camstack/types/node";
33
+ import { lstat, readdir, readlink, realpath } from "node:fs/promises";
38
34
  import * as path$39 from "node:path";
39
35
  import { dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
36
+ import { execFile, spawn } from "node:child_process";
40
37
  import * as util$10 from "node:util";
41
38
  import { promisify } from "node:util";
42
- import { asJsonObject, errMsg, parseJsonUnknown } from "@camstack/types/addon";
43
- import { execFile, spawn } from "node:child_process";
44
39
  import * as os$18 from "node:os";
45
- import { lstat, readdir, readlink, realpath } from "node:fs/promises";
40
+ import * as fs$17 from "node:fs";
41
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync } from "node:fs";
42
+ import { request } from "node:http";
43
+ import * as v8 from "node:v8";
44
+ import * as vm from "node:vm";
45
+ import { asJsonObject, errMsg, parseJsonUnknown } from "@camstack/types/addon";
46
46
  import { fileURLToPath, pathToFileURL } from "node:url";
47
47
  import { EventEmitter } from "node:events";
48
48
  import As from "node:stream";
@@ -50,6 +50,371 @@ import { StringDecoder } from "node:string_decoder";
50
50
  import { lstatSync, readdir as readdir$1, readdirSync, readlinkSync, realpathSync } from "fs";
51
51
  import "path";
52
52
  import { createRequire } from "module";
53
+ //#region src/addon/addon-api-factory.ts
54
+ /**
55
+ * Wrap a raw tRPC caller (from `createCallerFactory`) in a proxy that
56
+ * exposes each leaf procedure as `{ query, mutate, subscribe }`, matching
57
+ * the shape of `CreateTRPCClient<AppRouter>`.
58
+ *
59
+ * The tricky part: tRPC v11 callers expose nested routers as callable
60
+ * no-op functions (e.g. `caller.greet` is `typeof === 'function'`), so
61
+ * we can't use `typeof` to tell namespace from leaf. Instead, we return
62
+ * a unified proxy that handles BOTH behaviours:
63
+ *
64
+ * - Accessing `.query` / `.mutate` treats the current node as a leaf
65
+ * procedure and invokes `caller(input)` when called.
66
+ * - Accessing `.subscribe` throws (not supported on direct caller).
67
+ * - Accessing any other property descends into `caller[prop]` and
68
+ * returns a nested proxy.
69
+ */
70
+ function wrapCallerAsClient(caller) {
71
+ return new Proxy(Object.create(null), { get(_target, prop) {
72
+ if (typeof prop !== "string") return void 0;
73
+ if (prop === "query" || prop === "mutate") {
74
+ if (typeof caller !== "function") throw new Error(`Cannot call .${prop}() — this tRPC node is not a procedure`);
75
+ const fn = caller;
76
+ return (input) => fn(input);
77
+ }
78
+ if (prop === "subscribe") return () => {
79
+ throw new Error(`subscribe() is not supported on direct caller — use the WSS client for subscriptions`);
80
+ };
81
+ const child = caller?.[prop];
82
+ if (child === void 0 || child === null) return void 0;
83
+ return wrapCallerAsClient(child);
84
+ } });
85
+ }
86
+ var AddonApiFactory = class {
87
+ /**
88
+ * Create a direct caller -- calls tRPC procedures directly in-process.
89
+ * Zero network overhead. Used for in-process addons and dev mode.
90
+ *
91
+ * Returns `AddonApi` — the same tRPC client surface that broker-routed
92
+ * callers get. Callers treat it uniformly as `context.api` regardless
93
+ * of the underlying transport.
94
+ */
95
+ async createDirectCaller(options) {
96
+ const { initTRPC } = await import("@trpc/server");
97
+ return wrapCallerAsClient(initTRPC.create().createCallerFactory(options.router)(options.context));
98
+ }
99
+ };
100
+ //#endregion
101
+ //#region src/addon-routes/addon-route-registry.ts
102
+ /**
103
+ * Registry for dynamic HTTP routes registered by addons.
104
+ * Framework-agnostic — the server HTTP layer queries this registry to dispatch requests.
105
+ */
106
+ var AddonRouteRegistry = class {
107
+ routes = /* @__PURE__ */ new Map();
108
+ /**
109
+ * Register all routes from an addon's route provider.
110
+ */
111
+ registerRoutes(addonId, provider) {
112
+ const registered = provider.getRoutes().map((route) => {
113
+ return {
114
+ addonId,
115
+ route,
116
+ fullPath: `/addon/${addonId}${route.path.startsWith("/") ? route.path : `/${route.path}`}`
117
+ };
118
+ });
119
+ this.routes.set(addonId, registered);
120
+ }
121
+ /**
122
+ * Unregister all routes for an addon.
123
+ */
124
+ unregisterRoutes(addonId) {
125
+ this.routes.delete(addonId);
126
+ }
127
+ /**
128
+ * Match an incoming request method + path to a registered route.
129
+ * Supports simple path parameters (e.g., /items/:id).
130
+ */
131
+ matchRoute(method, path) {
132
+ const normalizedMethod = method.toUpperCase();
133
+ for (const registeredRoutes of this.routes.values()) for (const entry of registeredRoutes) {
134
+ if (entry.route.method !== normalizedMethod) continue;
135
+ const params = matchPath(entry.fullPath, path);
136
+ if (params !== null) return {
137
+ route: entry.route,
138
+ addonId: entry.addonId,
139
+ params
140
+ };
141
+ }
142
+ return null;
143
+ }
144
+ /**
145
+ * List all registered routes across all addons.
146
+ */
147
+ listRoutes() {
148
+ const result = [];
149
+ for (const registeredRoutes of this.routes.values()) for (const entry of registeredRoutes) result.push({
150
+ addonId: entry.addonId,
151
+ method: entry.route.method,
152
+ path: entry.fullPath,
153
+ access: entry.route.access,
154
+ description: entry.route.description
155
+ });
156
+ return result;
157
+ }
158
+ };
159
+ /**
160
+ * Match a route pattern against an actual path.
161
+ * Supports :param segments (e.g., /addon/:addonId/items/:id).
162
+ * Returns extracted params or null if no match.
163
+ */
164
+ function matchPath(pattern, path) {
165
+ const patternParts = pattern.split("/").filter(Boolean);
166
+ const pathParts = path.split("/").filter(Boolean);
167
+ if (patternParts.length !== pathParts.length) return null;
168
+ const params = {};
169
+ for (let i = 0; i < patternParts.length; i++) {
170
+ const patternPart = patternParts[i];
171
+ const pathPart = pathParts[i];
172
+ if (patternPart.startsWith(":")) params[patternPart.slice(1)] = pathPart;
173
+ else if (patternPart !== pathPart) return null;
174
+ }
175
+ return params;
176
+ }
177
+ //#endregion
178
+ //#region src/events/event-bus.ts
179
+ var EventBus = class {
180
+ listeners = /* @__PURE__ */ new Map();
181
+ on(event, callback) {
182
+ if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
183
+ const set = this.listeners.get(event);
184
+ set.add(callback);
185
+ return () => set.delete(callback);
186
+ }
187
+ emit(event, data) {
188
+ const set = this.listeners.get(event);
189
+ if (!set) return;
190
+ for (const cb of set) try {
191
+ cb(data);
192
+ } catch {}
193
+ }
194
+ once(event, callback) {
195
+ const unsub = this.on(event, (data) => {
196
+ unsub();
197
+ callback(data);
198
+ });
199
+ return unsub;
200
+ }
201
+ removeAllListeners(event) {
202
+ if (event) this.listeners.delete(event);
203
+ else this.listeners.clear();
204
+ }
205
+ listenerCount(event) {
206
+ return this.listeners.get(event)?.size ?? 0;
207
+ }
208
+ };
209
+ //#endregion
210
+ //#region src/events/system-event-bus.ts
211
+ var EventRingBuffer = class {
212
+ capacity;
213
+ buffer;
214
+ head = 0;
215
+ count = 0;
216
+ constructor(capacity) {
217
+ this.capacity = capacity;
218
+ this.buffer = Array.from({ length: capacity });
219
+ }
220
+ push(event) {
221
+ this.buffer[this.head] = event;
222
+ this.head = (this.head + 1) % this.capacity;
223
+ if (this.count < this.capacity) this.count++;
224
+ }
225
+ getAll() {
226
+ const result = [];
227
+ for (let i = 0; i < this.count; i++) {
228
+ const index = (this.head - 1 - i + this.capacity) % this.capacity;
229
+ result.push(this.buffer[index]);
230
+ }
231
+ return result;
232
+ }
233
+ query(filter, limit) {
234
+ let result = [...this.getAll()];
235
+ if (filter) result = result.filter((event) => matchesFilter(event, filter));
236
+ if (limit !== void 0 && limit > 0) return result.slice(0, limit);
237
+ return result;
238
+ }
239
+ };
240
+ function matchesCategory(eventCategory, filterCategory) {
241
+ if (filterCategory.endsWith(".*")) {
242
+ const prefix = filterCategory.slice(0, -2);
243
+ return eventCategory.startsWith(prefix + ".") || eventCategory === prefix;
244
+ }
245
+ return eventCategory === filterCategory;
246
+ }
247
+ function matchesFilter(event, filter) {
248
+ if (filter.category) {
249
+ const raw = filter.category;
250
+ if (!(Array.isArray(raw) ? raw.map(String) : [String(raw)]).some((cat) => matchesCategory(event.category, cat))) return false;
251
+ }
252
+ if (filter.source) {
253
+ if (event.source.type !== filter.source.type || event.source.id !== filter.source.id) return false;
254
+ }
255
+ if (filter.agentId) {
256
+ const eventNodeId = event.source.nodeId;
257
+ if (!eventNodeId || !eventNodeId.startsWith(filter.agentId)) return false;
258
+ }
259
+ if (filter.addonId) {
260
+ if ((event.source.addonId ?? (event.source.type === "addon" ? String(event.source.id) : void 0)) !== filter.addonId) return false;
261
+ }
262
+ if (filter.deviceId !== void 0) {
263
+ if ((event.source.deviceId ?? (event.source.type === "device" ? Number(event.source.id) : void 0)) !== filter.deviceId) return false;
264
+ }
265
+ if (filter.since && event.timestamp < filter.since) return false;
266
+ return true;
267
+ }
268
+ var SystemEventBus = class {
269
+ ringBuffer;
270
+ subscribers = [];
271
+ constructor(bufferSize = 1e4) {
272
+ this.ringBuffer = new EventRingBuffer(bufferSize);
273
+ }
274
+ emit(event) {
275
+ this.ringBuffer.push(event);
276
+ for (const subscriber of this.subscribers) if (matchesFilter(event, subscriber.filter)) queueMicrotask(() => {
277
+ try {
278
+ subscriber.callback(event);
279
+ } catch (err) {
280
+ console.error(`[EventBus] Subscriber error for ${event.category}:`, err);
281
+ }
282
+ });
283
+ }
284
+ /**
285
+ * Subscribe to events matching a filter.
286
+ * When called with a typed category filter, the handler receives typed event data.
287
+ */
288
+ subscribe(filter, handler) {
289
+ const subscriber = {
290
+ filter,
291
+ callback: handler
292
+ };
293
+ this.subscribers.push(subscriber);
294
+ return () => {
295
+ const index = this.subscribers.indexOf(subscriber);
296
+ if (index !== -1) this.subscribers.splice(index, 1);
297
+ };
298
+ }
299
+ getRecent(filter, limit) {
300
+ return this.ringBuffer.query(filter, limit);
301
+ }
302
+ };
303
+ //#endregion
304
+ //#region src/feature/feature-manager.ts
305
+ var FeatureManager = class {
306
+ configReader;
307
+ constructor(configReader) {
308
+ this.configReader = configReader;
309
+ }
310
+ isEnabled(flag) {
311
+ return this.configReader.features[flag];
312
+ }
313
+ getManifest() {
314
+ return { ...this.configReader.features };
315
+ }
316
+ };
317
+ //#endregion
318
+ //#region src/http/data-plane-registry.ts
319
+ function trimSlashes(s) {
320
+ return s.replace(/^\/+/, "").replace(/\/+$/, "");
321
+ }
322
+ var DataPlaneRegistry = class {
323
+ byAddon = /* @__PURE__ */ new Map();
324
+ /** Replace ALL endpoints for an addon (idempotent re-mount). */
325
+ registerAddon(addonId, endpoints) {
326
+ if (endpoints.length === 0) {
327
+ this.byAddon.delete(addonId);
328
+ return;
329
+ }
330
+ this.byAddon.set(addonId, [...endpoints]);
331
+ }
332
+ /** Drop an addon's endpoints (stop / disconnect). */
333
+ unregisterAddon(addonId) {
334
+ this.byAddon.delete(addonId);
335
+ }
336
+ /** True when the addon has at least one data-plane registered. */
337
+ has(addonId) {
338
+ return this.byAddon.has(addonId);
339
+ }
340
+ /**
341
+ * Match `subPath` (the part after `/addon/<addonId>/`, with or without a
342
+ * leading slash, NO query string) against the addon's prefixes. Longest prefix
343
+ * wins. Returns the matched endpoint + the remaining path the addon handler sees.
344
+ */
345
+ match(addonId, subPath) {
346
+ const endpoints = this.byAddon.get(addonId);
347
+ if (!endpoints) return null;
348
+ const normalized = `/${trimSlashes(subPath)}`;
349
+ let best = null;
350
+ for (const endpoint of endpoints) {
351
+ const prefix = `/${trimSlashes(endpoint.prefix)}`;
352
+ if (normalized === prefix || normalized.startsWith(`${prefix}/`)) {
353
+ const rest = normalized.slice(prefix.length) || "/";
354
+ if (best === null || prefix.length > best.len) best = {
355
+ endpoint,
356
+ rest,
357
+ len: prefix.length
358
+ };
359
+ }
360
+ }
361
+ if (best === null) return null;
362
+ return {
363
+ addonId,
364
+ endpoint: best.endpoint,
365
+ rest: best.rest
366
+ };
367
+ }
368
+ };
369
+ //#endregion
370
+ //#region src/http/reverse-proxy.ts
371
+ /**
372
+ * Transport-agnostic reverse-proxy from the hub to an addon's `127.0.0.1`
373
+ * data-plane listener. Operates on RAW Node http objects (`request.raw` /
374
+ * `reply.raw`) so `@camstack/system` stays free of any HTTP-framework dependency.
375
+ *
376
+ * The hub authenticates first (its existing scoped-token / admin / cookie logic),
377
+ * then hands the raw request+response here. We forward method + headers (incl.
378
+ * `Range`) + body upstream — injecting the per-listener shared secret so the addon
379
+ * accepts the call — and pipe the upstream response straight back (status +
380
+ * headers + body), so `Content-Range`, backpressure and client-disconnect are all
381
+ * native. No bytes are buffered; nothing crosses the cap channel.
382
+ */
383
+ /** Reverse-proxy one request to an addon data-plane listener. Fire-and-forget:
384
+ * the caller must `reply.hijack()` (or otherwise stop the framework from also
385
+ * responding) before calling this, since we drive `clientRes` directly. */
386
+ function proxyToUpstream(opts) {
387
+ const { baseUrl, secret, upstreamPath, clientReq, clientRes } = opts;
388
+ const base = new URL(baseUrl);
389
+ const headers = { ...clientReq.headers };
390
+ delete headers.host;
391
+ delete headers.connection;
392
+ delete headers["content-length"];
393
+ headers[DATAPLANE_SECRET_HEADER$1] = secret;
394
+ const upstream = request({
395
+ protocol: base.protocol,
396
+ hostname: base.hostname,
397
+ port: base.port,
398
+ method: clientReq.method ?? "GET",
399
+ path: upstreamPath,
400
+ headers
401
+ }, (upRes) => {
402
+ clientRes.writeHead(upRes.statusCode ?? 502, upRes.headers);
403
+ upRes.pipe(clientRes);
404
+ });
405
+ upstream.on("error", (err) => {
406
+ if (!clientRes.headersSent) clientRes.writeHead(502, { "content-type": "application/json" });
407
+ clientRes.end(JSON.stringify({
408
+ error: "data-plane upstream error",
409
+ detail: String(err)
410
+ }));
411
+ });
412
+ clientRes.on("close", () => {
413
+ if (!clientRes.writableFinished && !upstream.destroyed) upstream.destroy();
414
+ });
415
+ clientReq.pipe(upstream);
416
+ }
417
+ //#endregion
53
418
  //#region src/kernel/heap-watch.ts
54
419
  /**
55
420
  * heap-watch — hub-main's own memory, on the record, and returned to the OS.
@@ -309,529 +674,11 @@ function startHeapWatch(label = "hub-main", sink = consoleSink, intervalMs = HEA
309
674
  tick();
310
675
  let stopped = false;
311
676
  return () => {
312
- if (stopped) return;
313
- stopped = true;
314
- clearInterval(timer);
315
- };
316
- }
317
- //#endregion
318
- //#region src/events/event-bus.ts
319
- var EventBus = class {
320
- listeners = /* @__PURE__ */ new Map();
321
- on(event, callback) {
322
- if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
323
- const set = this.listeners.get(event);
324
- set.add(callback);
325
- return () => set.delete(callback);
326
- }
327
- emit(event, data) {
328
- const set = this.listeners.get(event);
329
- if (!set) return;
330
- for (const cb of set) try {
331
- cb(data);
332
- } catch {}
333
- }
334
- once(event, callback) {
335
- const unsub = this.on(event, (data) => {
336
- unsub();
337
- callback(data);
338
- });
339
- return unsub;
340
- }
341
- removeAllListeners(event) {
342
- if (event) this.listeners.delete(event);
343
- else this.listeners.clear();
344
- }
345
- listenerCount(event) {
346
- return this.listeners.get(event)?.size ?? 0;
347
- }
348
- };
349
- //#endregion
350
- //#region src/http/data-plane-registry.ts
351
- function trimSlashes(s) {
352
- return s.replace(/^\/+/, "").replace(/\/+$/, "");
353
- }
354
- var DataPlaneRegistry = class {
355
- byAddon = /* @__PURE__ */ new Map();
356
- /** Replace ALL endpoints for an addon (idempotent re-mount). */
357
- registerAddon(addonId, endpoints) {
358
- if (endpoints.length === 0) {
359
- this.byAddon.delete(addonId);
360
- return;
361
- }
362
- this.byAddon.set(addonId, [...endpoints]);
363
- }
364
- /** Drop an addon's endpoints (stop / disconnect). */
365
- unregisterAddon(addonId) {
366
- this.byAddon.delete(addonId);
367
- }
368
- /** True when the addon has at least one data-plane registered. */
369
- has(addonId) {
370
- return this.byAddon.has(addonId);
371
- }
372
- /**
373
- * Match `subPath` (the part after `/addon/<addonId>/`, with or without a
374
- * leading slash, NO query string) against the addon's prefixes. Longest prefix
375
- * wins. Returns the matched endpoint + the remaining path the addon handler sees.
376
- */
377
- match(addonId, subPath) {
378
- const endpoints = this.byAddon.get(addonId);
379
- if (!endpoints) return null;
380
- const normalized = `/${trimSlashes(subPath)}`;
381
- let best = null;
382
- for (const endpoint of endpoints) {
383
- const prefix = `/${trimSlashes(endpoint.prefix)}`;
384
- if (normalized === prefix || normalized.startsWith(`${prefix}/`)) {
385
- const rest = normalized.slice(prefix.length) || "/";
386
- if (best === null || prefix.length > best.len) best = {
387
- endpoint,
388
- rest,
389
- len: prefix.length
390
- };
391
- }
392
- }
393
- if (best === null) return null;
394
- return {
395
- addonId,
396
- endpoint: best.endpoint,
397
- rest: best.rest
398
- };
399
- }
400
- };
401
- //#endregion
402
- //#region src/http/reverse-proxy.ts
403
- /**
404
- * Transport-agnostic reverse-proxy from the hub to an addon's `127.0.0.1`
405
- * data-plane listener. Operates on RAW Node http objects (`request.raw` /
406
- * `reply.raw`) so `@camstack/system` stays free of any HTTP-framework dependency.
407
- *
408
- * The hub authenticates first (its existing scoped-token / admin / cookie logic),
409
- * then hands the raw request+response here. We forward method + headers (incl.
410
- * `Range`) + body upstream — injecting the per-listener shared secret so the addon
411
- * accepts the call — and pipe the upstream response straight back (status +
412
- * headers + body), so `Content-Range`, backpressure and client-disconnect are all
413
- * native. No bytes are buffered; nothing crosses the cap channel.
414
- */
415
- /** Reverse-proxy one request to an addon data-plane listener. Fire-and-forget:
416
- * the caller must `reply.hijack()` (or otherwise stop the framework from also
417
- * responding) before calling this, since we drive `clientRes` directly. */
418
- function proxyToUpstream(opts) {
419
- const { baseUrl, secret, upstreamPath, clientReq, clientRes } = opts;
420
- const base = new URL(baseUrl);
421
- const headers = { ...clientReq.headers };
422
- delete headers.host;
423
- delete headers.connection;
424
- delete headers["content-length"];
425
- headers[DATAPLANE_SECRET_HEADER$1] = secret;
426
- const upstream = request({
427
- protocol: base.protocol,
428
- hostname: base.hostname,
429
- port: base.port,
430
- method: clientReq.method ?? "GET",
431
- path: upstreamPath,
432
- headers
433
- }, (upRes) => {
434
- clientRes.writeHead(upRes.statusCode ?? 502, upRes.headers);
435
- upRes.pipe(clientRes);
436
- });
437
- upstream.on("error", (err) => {
438
- if (!clientRes.headersSent) clientRes.writeHead(502, { "content-type": "application/json" });
439
- clientRes.end(JSON.stringify({
440
- error: "data-plane upstream error",
441
- detail: String(err)
442
- }));
443
- });
444
- clientRes.on("close", () => {
445
- if (!clientRes.writableFinished && !upstream.destroyed) upstream.destroy();
446
- });
447
- clientReq.pipe(upstream);
448
- }
449
- //#endregion
450
- //#region src/python/python-env-manager.ts
451
- var execFileAsync$4 = promisify(execFile);
452
- var PythonEnvManager = class {
453
- venvPath;
454
- cachedProbe = null;
455
- constructor(dataDir) {
456
- this.venvPath = path$39.join(dataDir, ".venv");
457
- }
458
- async probe() {
459
- if (this.cachedProbe) return this.cachedProbe;
460
- for (const cmd of ["python3", "python"]) try {
461
- const { stdout } = await execFileAsync$4(cmd, ["--version"]);
462
- const version = stdout.trim().replace("Python ", "");
463
- const major = parseInt(version.split(".")[0] ?? "0", 10);
464
- const minor = parseInt(version.split(".")[1] ?? "0", 10);
465
- if (major < 3 || major === 3 && minor < 10) continue;
466
- const { stdout: pathOut } = await execFileAsync$4(cmd, ["-c", "import sys; print(sys.executable)"]);
467
- this.cachedProbe = {
468
- available: true,
469
- version,
470
- path: pathOut.trim()
471
- };
472
- return this.cachedProbe;
473
- } catch {
474
- continue;
475
- }
476
- this.cachedProbe = { available: false };
477
- return this.cachedProbe;
478
- }
479
- async ensure(options) {
480
- const probe = await this.probe();
481
- if (!probe.available || !probe.path) throw new Error("Python 3.10+ is required but not found on this system");
482
- if (!fs$17.existsSync(path$39.join(this.venvPath, "bin", "python"))) await execFileAsync$4(probe.path, [
483
- "-m",
484
- "venv",
485
- this.venvPath
486
- ]);
487
- const venvPython = path$39.join(this.venvPath, "bin", "python");
488
- if (options.packages.length > 0) await execFileAsync$4(venvPython, [
489
- "-m",
490
- "pip",
491
- "install",
492
- "-q",
493
- ...options.packages
494
- ]);
495
- return {
496
- pythonPath: venvPython,
497
- venvPath: this.venvPath,
498
- spawn: (script, args) => {
499
- return spawn(venvPython, [script, ...args]);
500
- }
501
- };
502
- }
503
- spawn(script, args) {
504
- const venvPython = path$39.join(this.venvPath, "bin", "python");
505
- if (!fs$17.existsSync(venvPython)) throw new Error("Python venv not initialized. Call ensure() first.");
506
- return spawn(venvPython, [script, ...args]);
507
- }
508
- };
509
- //#endregion
510
- //#region src/pipeline/pipeline-validator.ts
511
- var PipelineValidator = class {
512
- stepExists;
513
- constructor(stepExists) {
514
- this.stepExists = stepExists;
515
- }
516
- validate(config) {
517
- const errors = [];
518
- const warnings = [];
519
- for (const node of config.video) this.validateNode(node, errors, warnings);
520
- if (config.audio) this.validateNode(config.audio, errors, warnings);
521
- return {
522
- valid: errors.length === 0,
523
- errors,
524
- warnings
525
- };
526
- }
527
- validateNode(node, errors, warnings) {
528
- if (!this.stepExists(node.addon)) {
529
- errors.push({
530
- step: node.step,
531
- addon: node.addon,
532
- message: `Step "${node.addon}" has no provider — the addon that provided it may have been removed`,
533
- severity: "error"
534
- });
535
- return;
536
- }
537
- if (node.children) for (const child of node.children) this.validateNode(child, errors, warnings);
538
- }
539
- };
540
- //#endregion
541
- //#region src/pipeline/pipeline-runner.ts
542
- var PipelineRunner = class {
543
- addonResolver;
544
- constructor(addonResolver) {
545
- this.addonResolver = addonResolver;
546
- }
547
- async run(frame, config) {
548
- const startTime = performance.now();
549
- const results = [];
550
- const timings = {};
551
- for (const rootNode of config.video) await this.executeNode(rootNode, frame, null, results, timings);
552
- if (config.audio) await this.executeNode(config.audio, frame, null, results, timings);
553
- return {
554
- results,
555
- totalMs: performance.now() - startTime,
556
- timings,
557
- frameTimestamp: frame.timestamp
558
- };
559
- }
560
- async executeNode(node, frame, parentDetection, results, timings) {
561
- const resultId = randomUUID();
562
- const stepStart = performance.now();
563
- try {
564
- const effectiveConfig = { ...node.configOverride };
565
- const caller = await this.addonResolver.resolve(node.addon, effectiveConfig);
566
- let output;
567
- if (parentDetection) {
568
- const cropInput = {
569
- frame,
570
- roi: parentDetection.det.bbox,
571
- parentDetection: parentDetection.det
572
- };
573
- output = await caller.process(cropInput);
574
- } else output = await caller.process(frame);
575
- const stepMs = performance.now() - stepStart;
576
- const slot = "detections" in output ? "detector" : "crops" in output ? "cropper" : "classifier";
577
- const stepResult = {
578
- addon: node.addon,
579
- slot,
580
- output,
581
- parentResultId: parentDetection?.resultId,
582
- resultId,
583
- inferenceMs: output.inferenceMs,
584
- preprocessMs: 0,
585
- totalMs: stepMs
586
- };
587
- results.push(stepResult);
588
- timings[node.step] = stepMs;
589
- if (node.children?.length) {
590
- const detections = "detections" in output ? output.detections : "crops" in output ? output.crops : [];
591
- await this.executeChildren(node.children, frame, detections, resultId, results, timings);
592
- }
593
- } catch (error) {
594
- const stepMs = performance.now() - stepStart;
595
- const message = errMsg$1(error);
596
- results.push({
597
- addon: node.addon,
598
- slot: "detector",
599
- output: {
600
- detections: [],
601
- inferenceMs: 0,
602
- modelId: ""
603
- },
604
- parentResultId: parentDetection?.resultId,
605
- resultId,
606
- inferenceMs: 0,
607
- preprocessMs: 0,
608
- totalMs: stepMs,
609
- error: {
610
- code: "ADDON_ERROR",
611
- message,
612
- childrenSkipped: true
613
- }
614
- });
615
- }
616
- }
617
- async executeChildren(children, frame, parentDetections, parentResultId, results, timings) {
618
- const promises = [];
619
- for (const detection of parentDetections) {
620
- if (detection.bbox.w < 1 || detection.bbox.h < 1) continue;
621
- for (const child of children) promises.push(this.executeNode(child, frame, {
622
- det: detection,
623
- resultId: parentResultId
624
- }, results, timings));
625
- }
626
- await Promise.allSettled(promises);
627
- }
628
- };
629
- //#endregion
630
- //#region src/pipeline/engine-manager-resolver.ts
631
- /**
632
- * Adapter that wraps an IEngineManager + addonConfigs as an IAddonResolver.
633
- *
634
- * Used for backwards compatibility — the in-process AddonEngineManager
635
- * still uses the old getOrCreateEngine(addonId, globalConfig, override) API.
636
- * This adapter bridges it to the new resolve(addonId, config) interface.
637
- */
638
- var EngineManagerResolver = class {
639
- engineManager;
640
- addonConfigs;
641
- constructor(engineManager, addonConfigs) {
642
- this.engineManager = engineManager;
643
- this.addonConfigs = addonConfigs;
644
- }
645
- async resolve(addonId, config) {
646
- const globalConfig = this.addonConfigs.get(addonId) ?? {};
647
- const engine = await this.engineManager.getOrCreateEngine(addonId, globalConfig, config);
648
- return { process: async (input) => {
649
- return engine.process(input);
650
- } };
651
- }
652
- async shutdownAll() {
653
- await this.engineManager.shutdownAll();
654
- }
655
- };
656
- //#endregion
657
- //#region src/network/network-quality.ts
658
- var NetworkQualityTracker = class NetworkQualityTracker {
659
- devices = /* @__PURE__ */ new Map();
660
- static MAX_SAMPLES = 30;
661
- reportStreamStats(deviceId, streamId, bitrateKbps, packetLoss) {
662
- const device = this.getOrCreateDevice(deviceId);
663
- let stream = device.streams.get(streamId);
664
- if (!stream) {
665
- stream = {
666
- nominalBitrateKbps: bitrateKbps,
667
- samples: [],
668
- peakBitrateKbps: 0,
669
- packetLossSamples: [],
670
- lastUpdated: 0
671
- };
672
- device.streams.set(streamId, stream);
673
- }
674
- stream.samples.push(bitrateKbps);
675
- if (stream.samples.length > NetworkQualityTracker.MAX_SAMPLES) stream.samples.shift();
676
- stream.peakBitrateKbps = Math.max(stream.peakBitrateKbps, bitrateKbps);
677
- if (packetLoss !== void 0) {
678
- stream.packetLossSamples.push(packetLoss);
679
- if (stream.packetLossSamples.length > NetworkQualityTracker.MAX_SAMPLES) stream.packetLossSamples.shift();
680
- }
681
- stream.lastUpdated = Date.now();
682
- }
683
- reportClientStats(deviceId, stats) {
684
- const device = this.getOrCreateDevice(deviceId);
685
- device.client = {
686
- ...stats,
687
- lastUpdated: Date.now()
688
- };
689
- }
690
- getDeviceStats(deviceId) {
691
- const device = this.devices.get(deviceId);
692
- if (!device) return null;
693
- const streams = {};
694
- for (const [streamId, s] of device.streams) {
695
- const avg = (arr) => arr.length === 0 ? 0 : arr.reduce((a, b) => a + b, 0) / arr.length;
696
- streams[streamId] = {
697
- nominalBitrateKbps: s.nominalBitrateKbps,
698
- observedBitrateKbps: Math.round(avg(s.samples)),
699
- peakBitrateKbps: s.peakBitrateKbps,
700
- packetLossPercent: Math.round(avg(s.packetLossSamples) * 10) / 10,
701
- lastUpdated: s.lastUpdated
702
- };
703
- }
704
- return {
705
- deviceId,
706
- streams,
707
- client: device.client ?? void 0
708
- };
709
- }
710
- getAllStats() {
711
- const results = [];
712
- for (const deviceId of this.devices.keys()) {
713
- const stats = this.getDeviceStats(deviceId);
714
- if (stats) results.push(stats);
715
- }
716
- return results;
717
- }
718
- getOrCreateDevice(deviceId) {
719
- let device = this.devices.get(deviceId);
720
- if (!device) {
721
- device = {
722
- streams: /* @__PURE__ */ new Map(),
723
- client: null
724
- };
725
- this.devices.set(deviceId, device);
726
- }
727
- return device;
728
- }
729
- };
730
- //#endregion
731
- //#region src/repl/repl-engine.ts
732
- var EXECUTION_TIMEOUT_MS = 5e3;
733
- var COMPLETION_TIMEOUT_MS = 1e3;
734
- var ReplEngine = class {
735
- contextProvider;
736
- constructor(contextProvider) {
737
- this.contextProvider = contextProvider;
738
- }
739
- async execute(code, context) {
740
- const start = Date.now();
741
- const sandbox = await this.buildSandbox(context);
742
- try {
743
- const vmContext = vm.createContext(sandbox);
744
- let result = new vm.Script(code).runInContext(vmContext, { timeout: EXECUTION_TIMEOUT_MS });
745
- if (result && typeof result === "object" && "then" in result && typeof result.then === "function") result = await Promise.race([result, new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("Async timeout (5s)")), EXECUTION_TIMEOUT_MS))]);
746
- const duration = Date.now() - start;
747
- if (result === void 0) return {
748
- output: "undefined",
749
- type: "void",
750
- duration
751
- };
752
- return {
753
- output: util$10.inspect(result, {
754
- depth: 4,
755
- colors: false,
756
- maxArrayLength: 50,
757
- maxStringLength: 1e3
758
- }),
759
- type: "value",
760
- duration
761
- };
762
- } catch (err) {
763
- return {
764
- output: err instanceof Error ? err.message : typeof err === "object" && err !== null && "message" in err ? String(err.message) : String(err),
765
- type: "error",
766
- duration: Date.now() - start
767
- };
768
- }
769
- }
770
- async getCompletions(partial, context) {
771
- const sandbox = await this.buildSandbox(context);
772
- const keys = Object.keys(sandbox);
773
- if (!partial) return keys;
774
- const lastDot = partial.lastIndexOf(".");
775
- if (lastDot === -1) return keys.filter((k) => k.startsWith(partial));
776
- const objPath = partial.substring(0, lastDot);
777
- const propPrefix = partial.substring(lastDot + 1);
778
- try {
779
- const vmContext = vm.createContext(sandbox);
780
- const obj = vm.runInContext(objPath, vmContext, { timeout: COMPLETION_TIMEOUT_MS });
781
- if (obj && typeof obj === "object") {
782
- const proto = Object.getPrototypeOf(obj);
783
- const objKeys = Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertyNames(proto ?? {})).filter((k) => k.startsWith(propPrefix));
784
- return [...new Set(objKeys)].map((k) => `${objPath}.${k}`);
785
- }
786
- } catch {}
787
- return [];
788
- }
789
- async buildSandbox(context) {
790
- const base = {
791
- console: {
792
- log: (...args) => util$10.inspect(args),
793
- warn: (...args) => util$10.inspect(args)
794
- },
795
- JSON,
796
- Math,
797
- Date,
798
- Array,
799
- Object,
800
- String,
801
- Number,
802
- Boolean,
803
- Map,
804
- Set,
805
- Promise,
806
- Buffer,
807
- setTimeout: void 0,
808
- setInterval: void 0,
809
- fetch: void 0,
810
- require: void 0,
811
- process: void 0,
812
- ...context.variables
813
- };
814
- switch (context.scope.type) {
815
- case "system": return {
816
- ...base,
817
- ...await this.contextProvider.getSystemSandbox()
818
- };
819
- case "device": return {
820
- ...base,
821
- ...await this.contextProvider.getDeviceSandbox(context.scope.deviceId)
822
- };
823
- case "provider": return {
824
- ...base,
825
- ...await this.contextProvider.getProviderSandbox(context.scope.providerId)
826
- };
827
- case "addon": return {
828
- ...base,
829
- ...await this.contextProvider.getAddonSandbox(context.scope.addonId)
830
- };
831
- default: return base;
832
- }
833
- }
834
- };
677
+ if (stopped) return;
678
+ stopped = true;
679
+ clearInterval(timer);
680
+ };
681
+ }
835
682
  //#endregion
836
683
  //#region src/lifecycle/lifecycle-state-machine.ts
837
684
  var VALID_TRANSITIONS = {
@@ -928,114 +775,6 @@ var LifecycleStateMachine = class {
928
775
  }
929
776
  };
930
777
  //#endregion
931
- //#region src/feature/feature-manager.ts
932
- var FeatureManager = class {
933
- configReader;
934
- constructor(configReader) {
935
- this.configReader = configReader;
936
- }
937
- isEnabled(flag) {
938
- return this.configReader.features[flag];
939
- }
940
- getManifest() {
941
- return { ...this.configReader.features };
942
- }
943
- };
944
- //#endregion
945
- //#region src/events/system-event-bus.ts
946
- var EventRingBuffer = class {
947
- capacity;
948
- buffer;
949
- head = 0;
950
- count = 0;
951
- constructor(capacity) {
952
- this.capacity = capacity;
953
- this.buffer = Array.from({ length: capacity });
954
- }
955
- push(event) {
956
- this.buffer[this.head] = event;
957
- this.head = (this.head + 1) % this.capacity;
958
- if (this.count < this.capacity) this.count++;
959
- }
960
- getAll() {
961
- const result = [];
962
- for (let i = 0; i < this.count; i++) {
963
- const index = (this.head - 1 - i + this.capacity) % this.capacity;
964
- result.push(this.buffer[index]);
965
- }
966
- return result;
967
- }
968
- query(filter, limit) {
969
- let result = [...this.getAll()];
970
- if (filter) result = result.filter((event) => matchesFilter(event, filter));
971
- if (limit !== void 0 && limit > 0) return result.slice(0, limit);
972
- return result;
973
- }
974
- };
975
- function matchesCategory(eventCategory, filterCategory) {
976
- if (filterCategory.endsWith(".*")) {
977
- const prefix = filterCategory.slice(0, -2);
978
- return eventCategory.startsWith(prefix + ".") || eventCategory === prefix;
979
- }
980
- return eventCategory === filterCategory;
981
- }
982
- function matchesFilter(event, filter) {
983
- if (filter.category) {
984
- const raw = filter.category;
985
- if (!(Array.isArray(raw) ? raw.map(String) : [String(raw)]).some((cat) => matchesCategory(event.category, cat))) return false;
986
- }
987
- if (filter.source) {
988
- if (event.source.type !== filter.source.type || event.source.id !== filter.source.id) return false;
989
- }
990
- if (filter.agentId) {
991
- const eventNodeId = event.source.nodeId;
992
- if (!eventNodeId || !eventNodeId.startsWith(filter.agentId)) return false;
993
- }
994
- if (filter.addonId) {
995
- if ((event.source.addonId ?? (event.source.type === "addon" ? String(event.source.id) : void 0)) !== filter.addonId) return false;
996
- }
997
- if (filter.deviceId !== void 0) {
998
- if ((event.source.deviceId ?? (event.source.type === "device" ? Number(event.source.id) : void 0)) !== filter.deviceId) return false;
999
- }
1000
- if (filter.since && event.timestamp < filter.since) return false;
1001
- return true;
1002
- }
1003
- var SystemEventBus = class {
1004
- ringBuffer;
1005
- subscribers = [];
1006
- constructor(bufferSize = 1e4) {
1007
- this.ringBuffer = new EventRingBuffer(bufferSize);
1008
- }
1009
- emit(event) {
1010
- this.ringBuffer.push(event);
1011
- for (const subscriber of this.subscribers) if (matchesFilter(event, subscriber.filter)) queueMicrotask(() => {
1012
- try {
1013
- subscriber.callback(event);
1014
- } catch (err) {
1015
- console.error(`[EventBus] Subscriber error for ${event.category}:`, err);
1016
- }
1017
- });
1018
- }
1019
- /**
1020
- * Subscribe to events matching a filter.
1021
- * When called with a typed category filter, the handler receives typed event data.
1022
- */
1023
- subscribe(filter, handler) {
1024
- const subscriber = {
1025
- filter,
1026
- callback: handler
1027
- };
1028
- this.subscribers.push(subscriber);
1029
- return () => {
1030
- const index = this.subscribers.indexOf(subscriber);
1031
- if (index !== -1) this.subscribers.splice(index, 1);
1032
- };
1033
- }
1034
- getRecent(filter, limit) {
1035
- return this.ringBuffer.query(filter, limit);
1036
- }
1037
- };
1038
- //#endregion
1039
778
  //#region src/logging/log-ring-buffer.ts
1040
779
  /**
1041
780
  * Per-tag filter matcher with semantic-aware comparisons:
@@ -1467,92 +1206,601 @@ var LogManager = class {
1467
1206
  } catch {}
1468
1207
  });
1469
1208
  }
1470
- enrichDeviceName(entry) {
1471
- if (!this.deviceNameLookup) return entry;
1472
- const tags = entry.tags;
1473
- if (!tags) return entry;
1474
- const deviceId = tags.deviceId;
1475
- if (typeof deviceId !== "number" || !Number.isFinite(deviceId)) return entry;
1476
- if (typeof tags.deviceName === "string") return entry;
1477
- const name = this.deviceNameLookup(deviceId);
1478
- if (!name) return entry;
1479
- return {
1480
- ...entry,
1481
- tags: {
1482
- ...tags,
1483
- deviceName: name
1484
- }
1485
- };
1209
+ enrichDeviceName(entry) {
1210
+ if (!this.deviceNameLookup) return entry;
1211
+ const tags = entry.tags;
1212
+ if (!tags) return entry;
1213
+ const deviceId = tags.deviceId;
1214
+ if (typeof deviceId !== "number" || !Number.isFinite(deviceId)) return entry;
1215
+ if (typeof tags.deviceName === "string") return entry;
1216
+ const name = this.deviceNameLookup(deviceId);
1217
+ if (!name) return entry;
1218
+ return {
1219
+ ...entry,
1220
+ tags: {
1221
+ ...tags,
1222
+ deviceName: name
1223
+ }
1224
+ };
1225
+ }
1226
+ /** Subscribe to live logs matching a filter. Returns an unsubscribe function. */
1227
+ subscribe(filter, callback) {
1228
+ const id = Math.random().toString(36).slice(2);
1229
+ this.subscribers.set(id, {
1230
+ filter,
1231
+ callback
1232
+ });
1233
+ return () => {
1234
+ this.subscribers.delete(id);
1235
+ };
1236
+ }
1237
+ matchesFilter(entry, filter) {
1238
+ if (filter.level) {
1239
+ const levels = [
1240
+ "debug",
1241
+ "info",
1242
+ "warn",
1243
+ "error"
1244
+ ];
1245
+ const minIdx = levels.indexOf(filter.level);
1246
+ if (levels.indexOf(entry.level) < minIdx) return false;
1247
+ }
1248
+ if (filter.tags) {
1249
+ if (!matchesLogTags(entry.tags, filter.tags)) return false;
1250
+ }
1251
+ return true;
1252
+ }
1253
+ /**
1254
+ * Register a log destination.
1255
+ *
1256
+ * @param opts.replay If true (default), replay every entry currently in
1257
+ * the ring buffer to the new destination before live
1258
+ * traffic starts. Lets a destination added mid-boot
1259
+ * still receive boot-time log entries.
1260
+ */
1261
+ /** Apply new in-memory buffer limits at runtime (see PartitionedLogBuffer). */
1262
+ reconfigureBuffer(options) {
1263
+ this.ringBuffer.reconfigure(options);
1264
+ }
1265
+ /** Set the per-destination enablement check (see {@link isDestinationEnabled}). */
1266
+ setDestinationEnabledCheck(check) {
1267
+ this.isDestinationEnabled = check ?? void 0;
1268
+ }
1269
+ addDestination(dest, opts = {}) {
1270
+ const replay = opts.replay ?? true;
1271
+ this.destinations.push(opts.addonId === void 0 ? { dest } : {
1272
+ dest,
1273
+ addonId: opts.addonId
1274
+ });
1275
+ if (replay) for (const entry of this.ringBuffer.query({})) try {
1276
+ dest.write(entry);
1277
+ } catch {}
1278
+ }
1279
+ removeDestination(dest) {
1280
+ const index = this.destinations.findIndex((d) => d.dest === dest);
1281
+ if (index !== -1) this.destinations.splice(index, 1);
1282
+ }
1283
+ query(filter) {
1284
+ return this.ringBuffer.query(filter);
1285
+ }
1286
+ /**
1287
+ * Drop ring-buffer entries matching `filter`. Returns the count
1288
+ * removed. Backs the UI's "Clear logs" admin action so an operator
1289
+ * can wipe the historical window for a scope (per-device, per-addon,
1290
+ * agent-level) without restarting the server. External destinations
1291
+ * (file, forwarder) are NOT touched — only the in-memory ring.
1292
+ */
1293
+ clear(filter = {}) {
1294
+ return this.ringBuffer.clear(filter);
1295
+ }
1296
+ };
1297
+ //#endregion
1298
+ //#region src/network/network-quality.ts
1299
+ var NetworkQualityTracker = class NetworkQualityTracker {
1300
+ devices = /* @__PURE__ */ new Map();
1301
+ static MAX_SAMPLES = 30;
1302
+ reportStreamStats(deviceId, streamId, bitrateKbps, packetLoss) {
1303
+ const device = this.getOrCreateDevice(deviceId);
1304
+ let stream = device.streams.get(streamId);
1305
+ if (!stream) {
1306
+ stream = {
1307
+ nominalBitrateKbps: bitrateKbps,
1308
+ samples: [],
1309
+ peakBitrateKbps: 0,
1310
+ packetLossSamples: [],
1311
+ lastUpdated: 0
1312
+ };
1313
+ device.streams.set(streamId, stream);
1314
+ }
1315
+ stream.samples.push(bitrateKbps);
1316
+ if (stream.samples.length > NetworkQualityTracker.MAX_SAMPLES) stream.samples.shift();
1317
+ stream.peakBitrateKbps = Math.max(stream.peakBitrateKbps, bitrateKbps);
1318
+ if (packetLoss !== void 0) {
1319
+ stream.packetLossSamples.push(packetLoss);
1320
+ if (stream.packetLossSamples.length > NetworkQualityTracker.MAX_SAMPLES) stream.packetLossSamples.shift();
1321
+ }
1322
+ stream.lastUpdated = Date.now();
1323
+ }
1324
+ reportClientStats(deviceId, stats) {
1325
+ const device = this.getOrCreateDevice(deviceId);
1326
+ device.client = {
1327
+ ...stats,
1328
+ lastUpdated: Date.now()
1329
+ };
1330
+ }
1331
+ getDeviceStats(deviceId) {
1332
+ const device = this.devices.get(deviceId);
1333
+ if (!device) return null;
1334
+ const streams = {};
1335
+ for (const [streamId, s] of device.streams) {
1336
+ const avg = (arr) => arr.length === 0 ? 0 : arr.reduce((a, b) => a + b, 0) / arr.length;
1337
+ streams[streamId] = {
1338
+ nominalBitrateKbps: s.nominalBitrateKbps,
1339
+ observedBitrateKbps: Math.round(avg(s.samples)),
1340
+ peakBitrateKbps: s.peakBitrateKbps,
1341
+ packetLossPercent: Math.round(avg(s.packetLossSamples) * 10) / 10,
1342
+ lastUpdated: s.lastUpdated
1343
+ };
1344
+ }
1345
+ return {
1346
+ deviceId,
1347
+ streams,
1348
+ client: device.client ?? void 0
1349
+ };
1350
+ }
1351
+ getAllStats() {
1352
+ const results = [];
1353
+ for (const deviceId of this.devices.keys()) {
1354
+ const stats = this.getDeviceStats(deviceId);
1355
+ if (stats) results.push(stats);
1356
+ }
1357
+ return results;
1358
+ }
1359
+ getOrCreateDevice(deviceId) {
1360
+ let device = this.devices.get(deviceId);
1361
+ if (!device) {
1362
+ device = {
1363
+ streams: /* @__PURE__ */ new Map(),
1364
+ client: null
1365
+ };
1366
+ this.devices.set(deviceId, device);
1367
+ }
1368
+ return device;
1369
+ }
1370
+ };
1371
+ //#endregion
1372
+ //#region src/notification/notification-service.ts
1373
+ /**
1374
+ * Central notification service that routes canonical notifications to
1375
+ * configured `(addonId, targetId)` targets. Framework-agnostic —
1376
+ * dependencies injected via constructor.
1377
+ *
1378
+ * Providers are resolved from the ICapabilityRegistry by `addonId` on each
1379
+ * call (proxy pattern). Falls back to a local map when no registry is
1380
+ * provided (tests / backward compat).
1381
+ */
1382
+ var NotificationService = class {
1383
+ logger;
1384
+ localProviders = /* @__PURE__ */ new Map();
1385
+ routing = /* @__PURE__ */ new Map();
1386
+ rateLimits = /* @__PURE__ */ new Map();
1387
+ lastSent = /* @__PURE__ */ new Map();
1388
+ registry = null;
1389
+ constructor(logger) {
1390
+ this.logger = logger;
1391
+ }
1392
+ /** Set the registry for live provider lookup. Called once during boot. */
1393
+ setRegistry(registry) {
1394
+ this.registry = registry;
1395
+ }
1396
+ /** Resolve the collection provider for an addon — registry first, then local map. */
1397
+ resolveProvider(addonId) {
1398
+ if (this.registry) return this.registry.getProviderByAddon("notification-output", addonId) ?? void 0;
1399
+ return this.localProviders.get(addonId);
1400
+ }
1401
+ /** Register a provider in the local fallback map (used when no registry is set). */
1402
+ registerLocalProvider(addonId, provider) {
1403
+ this.localProviders.set(addonId, provider);
1404
+ this.logger.info("Notification provider added", { meta: { addonId } });
1405
+ }
1406
+ /** Remove a provider from the local fallback map. */
1407
+ unregisterLocalProvider(addonId) {
1408
+ this.localProviders.delete(addonId);
1409
+ this.logger.info("Notification provider removed", { meta: { addonId } });
1410
+ }
1411
+ /** Route a category to a set of `(addonId, targetId)` targets. */
1412
+ setRouting(category, targets) {
1413
+ this.routing.set(category, [...targets]);
1414
+ }
1415
+ setRateLimit(category, minIntervalMs) {
1416
+ this.rateLimits.set(category, minIntervalMs);
1417
+ }
1418
+ async notify(notification) {
1419
+ const { category, deviceId } = notification;
1420
+ const rateLimitKey = deviceId ? `${category}:${deviceId}` : category;
1421
+ const minInterval = this.rateLimits.get(category) ?? 0;
1422
+ if (minInterval > 0) {
1423
+ const last = this.lastSent.get(rateLimitKey) ?? 0;
1424
+ if (notification.timestamp - last < minInterval) {
1425
+ this.logger.debug("Rate limited", { meta: { rateLimitKey } });
1426
+ return;
1427
+ }
1428
+ }
1429
+ const targets = this.routing.get(category) ?? this.routing.get("*") ?? [];
1430
+ if (targets.length === 0) {
1431
+ this.logger.debug("No routing configured for category", { meta: { category } });
1432
+ return;
1433
+ }
1434
+ this.lastSent.set(rateLimitKey, notification.timestamp);
1435
+ const { category: _category, timestamp: _timestamp, ...canonical } = notification;
1436
+ await Promise.allSettled(targets.map(async (ref) => {
1437
+ const provider = this.resolveProvider(ref.addonId);
1438
+ if (!provider) {
1439
+ this.logger.debug("No provider for target", { meta: { addonId: ref.addonId } });
1440
+ return;
1441
+ }
1442
+ try {
1443
+ await provider.send({
1444
+ targetId: ref.targetId,
1445
+ notification: canonical
1446
+ });
1447
+ } catch (err) {
1448
+ this.logger.error("Notification target failed", { meta: {
1449
+ addonId: ref.addonId,
1450
+ targetId: ref.targetId,
1451
+ error: errMsg$1(err)
1452
+ } });
1453
+ }
1454
+ }));
1455
+ }
1456
+ getRouting() {
1457
+ return this.routing;
1458
+ }
1459
+ };
1460
+ //#endregion
1461
+ //#region src/notification/toast-service.ts
1462
+ /**
1463
+ * Service for broadcasting toast notifications to connected UI clients.
1464
+ * Framework-agnostic — integrates with tRPC subscriptions via subscribe().
1465
+ */
1466
+ var ToastService = class {
1467
+ listeners = /* @__PURE__ */ new Map();
1468
+ /**
1469
+ * Subscribe to toast events for a specific user.
1470
+ * Returns an unsubscribe function.
1471
+ */
1472
+ subscribe(connectionId, userId, callback) {
1473
+ this.listeners.set(connectionId, {
1474
+ userId,
1475
+ callback
1476
+ });
1477
+ return () => {
1478
+ this.listeners.delete(connectionId);
1479
+ };
1480
+ }
1481
+ /**
1482
+ * Broadcast a toast to all connected clients.
1483
+ */
1484
+ broadcast(toast) {
1485
+ for (const entry of this.listeners.values()) entry.callback(toast);
1486
+ }
1487
+ /**
1488
+ * Send a toast to a specific user's connections only.
1489
+ */
1490
+ sendToUser(userId, toast) {
1491
+ for (const entry of this.listeners.values()) if (entry.userId === userId) entry.callback(toast);
1492
+ }
1493
+ };
1494
+ //#endregion
1495
+ //#region src/pipeline/engine-manager-resolver.ts
1496
+ /**
1497
+ * Adapter that wraps an IEngineManager + addonConfigs as an IAddonResolver.
1498
+ *
1499
+ * Used for backwards compatibility — the in-process AddonEngineManager
1500
+ * still uses the old getOrCreateEngine(addonId, globalConfig, override) API.
1501
+ * This adapter bridges it to the new resolve(addonId, config) interface.
1502
+ */
1503
+ var EngineManagerResolver = class {
1504
+ engineManager;
1505
+ addonConfigs;
1506
+ constructor(engineManager, addonConfigs) {
1507
+ this.engineManager = engineManager;
1508
+ this.addonConfigs = addonConfigs;
1509
+ }
1510
+ async resolve(addonId, config) {
1511
+ const globalConfig = this.addonConfigs.get(addonId) ?? {};
1512
+ const engine = await this.engineManager.getOrCreateEngine(addonId, globalConfig, config);
1513
+ return { process: async (input) => {
1514
+ return engine.process(input);
1515
+ } };
1516
+ }
1517
+ async shutdownAll() {
1518
+ await this.engineManager.shutdownAll();
1519
+ }
1520
+ };
1521
+ //#endregion
1522
+ //#region src/pipeline/pipeline-runner.ts
1523
+ var PipelineRunner = class {
1524
+ addonResolver;
1525
+ constructor(addonResolver) {
1526
+ this.addonResolver = addonResolver;
1527
+ }
1528
+ async run(frame, config) {
1529
+ const startTime = performance.now();
1530
+ const results = [];
1531
+ const timings = {};
1532
+ for (const rootNode of config.video) await this.executeNode(rootNode, frame, null, results, timings);
1533
+ if (config.audio) await this.executeNode(config.audio, frame, null, results, timings);
1534
+ return {
1535
+ results,
1536
+ totalMs: performance.now() - startTime,
1537
+ timings,
1538
+ frameTimestamp: frame.timestamp
1539
+ };
1540
+ }
1541
+ async executeNode(node, frame, parentDetection, results, timings) {
1542
+ const resultId = randomUUID();
1543
+ const stepStart = performance.now();
1544
+ try {
1545
+ const effectiveConfig = { ...node.configOverride };
1546
+ const caller = await this.addonResolver.resolve(node.addon, effectiveConfig);
1547
+ let output;
1548
+ if (parentDetection) {
1549
+ const cropInput = {
1550
+ frame,
1551
+ roi: parentDetection.det.bbox,
1552
+ parentDetection: parentDetection.det
1553
+ };
1554
+ output = await caller.process(cropInput);
1555
+ } else output = await caller.process(frame);
1556
+ const stepMs = performance.now() - stepStart;
1557
+ const slot = "detections" in output ? "detector" : "crops" in output ? "cropper" : "classifier";
1558
+ const stepResult = {
1559
+ addon: node.addon,
1560
+ slot,
1561
+ output,
1562
+ parentResultId: parentDetection?.resultId,
1563
+ resultId,
1564
+ inferenceMs: output.inferenceMs,
1565
+ preprocessMs: 0,
1566
+ totalMs: stepMs
1567
+ };
1568
+ results.push(stepResult);
1569
+ timings[node.step] = stepMs;
1570
+ if (node.children?.length) {
1571
+ const detections = "detections" in output ? output.detections : "crops" in output ? output.crops : [];
1572
+ await this.executeChildren(node.children, frame, detections, resultId, results, timings);
1573
+ }
1574
+ } catch (error) {
1575
+ const stepMs = performance.now() - stepStart;
1576
+ const message = errMsg$1(error);
1577
+ results.push({
1578
+ addon: node.addon,
1579
+ slot: "detector",
1580
+ output: {
1581
+ detections: [],
1582
+ inferenceMs: 0,
1583
+ modelId: ""
1584
+ },
1585
+ parentResultId: parentDetection?.resultId,
1586
+ resultId,
1587
+ inferenceMs: 0,
1588
+ preprocessMs: 0,
1589
+ totalMs: stepMs,
1590
+ error: {
1591
+ code: "ADDON_ERROR",
1592
+ message,
1593
+ childrenSkipped: true
1594
+ }
1595
+ });
1596
+ }
1597
+ }
1598
+ async executeChildren(children, frame, parentDetections, parentResultId, results, timings) {
1599
+ const promises = [];
1600
+ for (const detection of parentDetections) {
1601
+ if (detection.bbox.w < 1 || detection.bbox.h < 1) continue;
1602
+ for (const child of children) promises.push(this.executeNode(child, frame, {
1603
+ det: detection,
1604
+ resultId: parentResultId
1605
+ }, results, timings));
1606
+ }
1607
+ await Promise.allSettled(promises);
1608
+ }
1609
+ };
1610
+ //#endregion
1611
+ //#region src/pipeline/pipeline-validator.ts
1612
+ var PipelineValidator = class {
1613
+ stepExists;
1614
+ constructor(stepExists) {
1615
+ this.stepExists = stepExists;
1486
1616
  }
1487
- /** Subscribe to live logs matching a filter. Returns an unsubscribe function. */
1488
- subscribe(filter, callback) {
1489
- const id = Math.random().toString(36).slice(2);
1490
- this.subscribers.set(id, {
1491
- filter,
1492
- callback
1493
- });
1494
- return () => {
1495
- this.subscribers.delete(id);
1617
+ validate(config) {
1618
+ const errors = [];
1619
+ const warnings = [];
1620
+ for (const node of config.video) this.validateNode(node, errors, warnings);
1621
+ if (config.audio) this.validateNode(config.audio, errors, warnings);
1622
+ return {
1623
+ valid: errors.length === 0,
1624
+ errors,
1625
+ warnings
1496
1626
  };
1497
1627
  }
1498
- matchesFilter(entry, filter) {
1499
- if (filter.level) {
1500
- const levels = [
1501
- "debug",
1502
- "info",
1503
- "warn",
1504
- "error"
1505
- ];
1506
- const minIdx = levels.indexOf(filter.level);
1507
- if (levels.indexOf(entry.level) < minIdx) return false;
1628
+ validateNode(node, errors, warnings) {
1629
+ if (!this.stepExists(node.addon)) {
1630
+ errors.push({
1631
+ step: node.step,
1632
+ addon: node.addon,
1633
+ message: `Step "${node.addon}" has no provider — the addon that provided it may have been removed`,
1634
+ severity: "error"
1635
+ });
1636
+ return;
1508
1637
  }
1509
- if (filter.tags) {
1510
- if (!matchesLogTags(entry.tags, filter.tags)) return false;
1638
+ if (node.children) for (const child of node.children) this.validateNode(child, errors, warnings);
1639
+ }
1640
+ };
1641
+ //#endregion
1642
+ //#region src/python/python-env-manager.ts
1643
+ var execFileAsync$4 = promisify(execFile);
1644
+ var PythonEnvManager = class {
1645
+ venvPath;
1646
+ cachedProbe = null;
1647
+ constructor(dataDir) {
1648
+ this.venvPath = path$39.join(dataDir, ".venv");
1649
+ }
1650
+ async probe() {
1651
+ if (this.cachedProbe) return this.cachedProbe;
1652
+ for (const cmd of ["python3", "python"]) try {
1653
+ const { stdout } = await execFileAsync$4(cmd, ["--version"]);
1654
+ const version = stdout.trim().replace("Python ", "");
1655
+ const major = parseInt(version.split(".")[0] ?? "0", 10);
1656
+ const minor = parseInt(version.split(".")[1] ?? "0", 10);
1657
+ if (major < 3 || major === 3 && minor < 10) continue;
1658
+ const { stdout: pathOut } = await execFileAsync$4(cmd, ["-c", "import sys; print(sys.executable)"]);
1659
+ this.cachedProbe = {
1660
+ available: true,
1661
+ version,
1662
+ path: pathOut.trim()
1663
+ };
1664
+ return this.cachedProbe;
1665
+ } catch {
1666
+ continue;
1511
1667
  }
1512
- return true;
1668
+ this.cachedProbe = { available: false };
1669
+ return this.cachedProbe;
1513
1670
  }
1514
- /**
1515
- * Register a log destination.
1516
- *
1517
- * @param opts.replay If true (default), replay every entry currently in
1518
- * the ring buffer to the new destination before live
1519
- * traffic starts. Lets a destination added mid-boot
1520
- * still receive boot-time log entries.
1521
- */
1522
- /** Apply new in-memory buffer limits at runtime (see PartitionedLogBuffer). */
1523
- reconfigureBuffer(options) {
1524
- this.ringBuffer.reconfigure(options);
1671
+ async ensure(options) {
1672
+ const probe = await this.probe();
1673
+ if (!probe.available || !probe.path) throw new Error("Python 3.10+ is required but not found on this system");
1674
+ if (!fs$17.existsSync(path$39.join(this.venvPath, "bin", "python"))) await execFileAsync$4(probe.path, [
1675
+ "-m",
1676
+ "venv",
1677
+ this.venvPath
1678
+ ]);
1679
+ const venvPython = path$39.join(this.venvPath, "bin", "python");
1680
+ if (options.packages.length > 0) await execFileAsync$4(venvPython, [
1681
+ "-m",
1682
+ "pip",
1683
+ "install",
1684
+ "-q",
1685
+ ...options.packages
1686
+ ]);
1687
+ return {
1688
+ pythonPath: venvPython,
1689
+ venvPath: this.venvPath,
1690
+ spawn: (script, args) => {
1691
+ return spawn(venvPython, [script, ...args]);
1692
+ }
1693
+ };
1525
1694
  }
1526
- /** Set the per-destination enablement check (see {@link isDestinationEnabled}). */
1527
- setDestinationEnabledCheck(check) {
1528
- this.isDestinationEnabled = check ?? void 0;
1695
+ spawn(script, args) {
1696
+ const venvPython = path$39.join(this.venvPath, "bin", "python");
1697
+ if (!fs$17.existsSync(venvPython)) throw new Error("Python venv not initialized. Call ensure() first.");
1698
+ return spawn(venvPython, [script, ...args]);
1529
1699
  }
1530
- addDestination(dest, opts = {}) {
1531
- const replay = opts.replay ?? true;
1532
- this.destinations.push(opts.addonId === void 0 ? { dest } : {
1533
- dest,
1534
- addonId: opts.addonId
1535
- });
1536
- if (replay) for (const entry of this.ringBuffer.query({})) try {
1537
- dest.write(entry);
1538
- } catch {}
1700
+ };
1701
+ //#endregion
1702
+ //#region src/repl/repl-engine.ts
1703
+ var EXECUTION_TIMEOUT_MS = 5e3;
1704
+ var COMPLETION_TIMEOUT_MS = 1e3;
1705
+ var ReplEngine = class {
1706
+ contextProvider;
1707
+ constructor(contextProvider) {
1708
+ this.contextProvider = contextProvider;
1539
1709
  }
1540
- removeDestination(dest) {
1541
- const index = this.destinations.findIndex((d) => d.dest === dest);
1542
- if (index !== -1) this.destinations.splice(index, 1);
1710
+ async execute(code, context) {
1711
+ const start = Date.now();
1712
+ const sandbox = await this.buildSandbox(context);
1713
+ try {
1714
+ const vmContext = vm.createContext(sandbox);
1715
+ let result = new vm.Script(code).runInContext(vmContext, { timeout: EXECUTION_TIMEOUT_MS });
1716
+ if (result && typeof result === "object" && "then" in result && typeof result.then === "function") result = await Promise.race([result, new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("Async timeout (5s)")), EXECUTION_TIMEOUT_MS))]);
1717
+ const duration = Date.now() - start;
1718
+ if (result === void 0) return {
1719
+ output: "undefined",
1720
+ type: "void",
1721
+ duration
1722
+ };
1723
+ return {
1724
+ output: util$10.inspect(result, {
1725
+ depth: 4,
1726
+ colors: false,
1727
+ maxArrayLength: 50,
1728
+ maxStringLength: 1e3
1729
+ }),
1730
+ type: "value",
1731
+ duration
1732
+ };
1733
+ } catch (err) {
1734
+ return {
1735
+ output: err instanceof Error ? err.message : typeof err === "object" && err !== null && "message" in err ? String(err.message) : String(err),
1736
+ type: "error",
1737
+ duration: Date.now() - start
1738
+ };
1739
+ }
1543
1740
  }
1544
- query(filter) {
1545
- return this.ringBuffer.query(filter);
1741
+ async getCompletions(partial, context) {
1742
+ const sandbox = await this.buildSandbox(context);
1743
+ const keys = Object.keys(sandbox);
1744
+ if (!partial) return keys;
1745
+ const lastDot = partial.lastIndexOf(".");
1746
+ if (lastDot === -1) return keys.filter((k) => k.startsWith(partial));
1747
+ const objPath = partial.substring(0, lastDot);
1748
+ const propPrefix = partial.substring(lastDot + 1);
1749
+ try {
1750
+ const vmContext = vm.createContext(sandbox);
1751
+ const obj = vm.runInContext(objPath, vmContext, { timeout: COMPLETION_TIMEOUT_MS });
1752
+ if (obj && typeof obj === "object") {
1753
+ const proto = Object.getPrototypeOf(obj);
1754
+ const objKeys = Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertyNames(proto ?? {})).filter((k) => k.startsWith(propPrefix));
1755
+ return [...new Set(objKeys)].map((k) => `${objPath}.${k}`);
1756
+ }
1757
+ } catch {}
1758
+ return [];
1546
1759
  }
1547
- /**
1548
- * Drop ring-buffer entries matching `filter`. Returns the count
1549
- * removed. Backs the UI's "Clear logs" admin action so an operator
1550
- * can wipe the historical window for a scope (per-device, per-addon,
1551
- * agent-level) without restarting the server. External destinations
1552
- * (file, forwarder) are NOT touched — only the in-memory ring.
1553
- */
1554
- clear(filter = {}) {
1555
- return this.ringBuffer.clear(filter);
1760
+ async buildSandbox(context) {
1761
+ const base = {
1762
+ console: {
1763
+ log: (...args) => util$10.inspect(args),
1764
+ warn: (...args) => util$10.inspect(args)
1765
+ },
1766
+ JSON,
1767
+ Math,
1768
+ Date,
1769
+ Array,
1770
+ Object,
1771
+ String,
1772
+ Number,
1773
+ Boolean,
1774
+ Map,
1775
+ Set,
1776
+ Promise,
1777
+ Buffer,
1778
+ setTimeout: void 0,
1779
+ setInterval: void 0,
1780
+ fetch: void 0,
1781
+ require: void 0,
1782
+ process: void 0,
1783
+ ...context.variables
1784
+ };
1785
+ switch (context.scope.type) {
1786
+ case "system": return {
1787
+ ...base,
1788
+ ...await this.contextProvider.getSystemSandbox()
1789
+ };
1790
+ case "device": return {
1791
+ ...base,
1792
+ ...await this.contextProvider.getDeviceSandbox(context.scope.deviceId)
1793
+ };
1794
+ case "provider": return {
1795
+ ...base,
1796
+ ...await this.contextProvider.getProviderSandbox(context.scope.providerId)
1797
+ };
1798
+ case "addon": return {
1799
+ ...base,
1800
+ ...await this.contextProvider.getAddonSandbox(context.scope.addonId)
1801
+ };
1802
+ default: return base;
1803
+ }
1556
1804
  }
1557
1805
  };
1558
1806
  //#endregion
@@ -1894,216 +2142,6 @@ var StorageManager = class {
1894
2142
  }
1895
2143
  };
1896
2144
  //#endregion
1897
- //#region src/auth/scope-matcher.ts
1898
- /**
1899
- * True if the scope set grants `access` on device-scoped capabilities.
1900
- * A `category:device` grant covers every device cap (the broad grant).
1901
- * Mirrors the OR-semantics of the existing token scope matcher.
1902
- */
1903
- function scopesAllowDeviceCap(scopes, access) {
1904
- return scopes.some((s) => s.type === "category" && s.target === "device" && s.access.includes(access));
1905
- }
1906
- //#endregion
1907
- //#region src/notification/notification-service.ts
1908
- /**
1909
- * Central notification service that routes canonical notifications to
1910
- * configured `(addonId, targetId)` targets. Framework-agnostic —
1911
- * dependencies injected via constructor.
1912
- *
1913
- * Providers are resolved from the ICapabilityRegistry by `addonId` on each
1914
- * call (proxy pattern). Falls back to a local map when no registry is
1915
- * provided (tests / backward compat).
1916
- */
1917
- var NotificationService = class {
1918
- logger;
1919
- localProviders = /* @__PURE__ */ new Map();
1920
- routing = /* @__PURE__ */ new Map();
1921
- rateLimits = /* @__PURE__ */ new Map();
1922
- lastSent = /* @__PURE__ */ new Map();
1923
- registry = null;
1924
- constructor(logger) {
1925
- this.logger = logger;
1926
- }
1927
- /** Set the registry for live provider lookup. Called once during boot. */
1928
- setRegistry(registry) {
1929
- this.registry = registry;
1930
- }
1931
- /** Resolve the collection provider for an addon — registry first, then local map. */
1932
- resolveProvider(addonId) {
1933
- if (this.registry) return this.registry.getProviderByAddon("notification-output", addonId) ?? void 0;
1934
- return this.localProviders.get(addonId);
1935
- }
1936
- /** Register a provider in the local fallback map (used when no registry is set). */
1937
- registerLocalProvider(addonId, provider) {
1938
- this.localProviders.set(addonId, provider);
1939
- this.logger.info("Notification provider added", { meta: { addonId } });
1940
- }
1941
- /** Remove a provider from the local fallback map. */
1942
- unregisterLocalProvider(addonId) {
1943
- this.localProviders.delete(addonId);
1944
- this.logger.info("Notification provider removed", { meta: { addonId } });
1945
- }
1946
- /** Route a category to a set of `(addonId, targetId)` targets. */
1947
- setRouting(category, targets) {
1948
- this.routing.set(category, [...targets]);
1949
- }
1950
- setRateLimit(category, minIntervalMs) {
1951
- this.rateLimits.set(category, minIntervalMs);
1952
- }
1953
- async notify(notification) {
1954
- const { category, deviceId } = notification;
1955
- const rateLimitKey = deviceId ? `${category}:${deviceId}` : category;
1956
- const minInterval = this.rateLimits.get(category) ?? 0;
1957
- if (minInterval > 0) {
1958
- const last = this.lastSent.get(rateLimitKey) ?? 0;
1959
- if (notification.timestamp - last < minInterval) {
1960
- this.logger.debug("Rate limited", { meta: { rateLimitKey } });
1961
- return;
1962
- }
1963
- }
1964
- const targets = this.routing.get(category) ?? this.routing.get("*") ?? [];
1965
- if (targets.length === 0) {
1966
- this.logger.debug("No routing configured for category", { meta: { category } });
1967
- return;
1968
- }
1969
- this.lastSent.set(rateLimitKey, notification.timestamp);
1970
- const { category: _category, timestamp: _timestamp, ...canonical } = notification;
1971
- await Promise.allSettled(targets.map(async (ref) => {
1972
- const provider = this.resolveProvider(ref.addonId);
1973
- if (!provider) {
1974
- this.logger.debug("No provider for target", { meta: { addonId: ref.addonId } });
1975
- return;
1976
- }
1977
- try {
1978
- await provider.send({
1979
- targetId: ref.targetId,
1980
- notification: canonical
1981
- });
1982
- } catch (err) {
1983
- this.logger.error("Notification target failed", { meta: {
1984
- addonId: ref.addonId,
1985
- targetId: ref.targetId,
1986
- error: errMsg$1(err)
1987
- } });
1988
- }
1989
- }));
1990
- }
1991
- getRouting() {
1992
- return this.routing;
1993
- }
1994
- };
1995
- //#endregion
1996
- //#region src/notification/toast-service.ts
1997
- /**
1998
- * Service for broadcasting toast notifications to connected UI clients.
1999
- * Framework-agnostic — integrates with tRPC subscriptions via subscribe().
2000
- */
2001
- var ToastService = class {
2002
- listeners = /* @__PURE__ */ new Map();
2003
- /**
2004
- * Subscribe to toast events for a specific user.
2005
- * Returns an unsubscribe function.
2006
- */
2007
- subscribe(connectionId, userId, callback) {
2008
- this.listeners.set(connectionId, {
2009
- userId,
2010
- callback
2011
- });
2012
- return () => {
2013
- this.listeners.delete(connectionId);
2014
- };
2015
- }
2016
- /**
2017
- * Broadcast a toast to all connected clients.
2018
- */
2019
- broadcast(toast) {
2020
- for (const entry of this.listeners.values()) entry.callback(toast);
2021
- }
2022
- /**
2023
- * Send a toast to a specific user's connections only.
2024
- */
2025
- sendToUser(userId, toast) {
2026
- for (const entry of this.listeners.values()) if (entry.userId === userId) entry.callback(toast);
2027
- }
2028
- };
2029
- //#endregion
2030
- //#region src/addon-routes/addon-route-registry.ts
2031
- /**
2032
- * Registry for dynamic HTTP routes registered by addons.
2033
- * Framework-agnostic — the server HTTP layer queries this registry to dispatch requests.
2034
- */
2035
- var AddonRouteRegistry = class {
2036
- routes = /* @__PURE__ */ new Map();
2037
- /**
2038
- * Register all routes from an addon's route provider.
2039
- */
2040
- registerRoutes(addonId, provider) {
2041
- const registered = provider.getRoutes().map((route) => {
2042
- return {
2043
- addonId,
2044
- route,
2045
- fullPath: `/addon/${addonId}${route.path.startsWith("/") ? route.path : `/${route.path}`}`
2046
- };
2047
- });
2048
- this.routes.set(addonId, registered);
2049
- }
2050
- /**
2051
- * Unregister all routes for an addon.
2052
- */
2053
- unregisterRoutes(addonId) {
2054
- this.routes.delete(addonId);
2055
- }
2056
- /**
2057
- * Match an incoming request method + path to a registered route.
2058
- * Supports simple path parameters (e.g., /items/:id).
2059
- */
2060
- matchRoute(method, path) {
2061
- const normalizedMethod = method.toUpperCase();
2062
- for (const registeredRoutes of this.routes.values()) for (const entry of registeredRoutes) {
2063
- if (entry.route.method !== normalizedMethod) continue;
2064
- const params = matchPath(entry.fullPath, path);
2065
- if (params !== null) return {
2066
- route: entry.route,
2067
- addonId: entry.addonId,
2068
- params
2069
- };
2070
- }
2071
- return null;
2072
- }
2073
- /**
2074
- * List all registered routes across all addons.
2075
- */
2076
- listRoutes() {
2077
- const result = [];
2078
- for (const registeredRoutes of this.routes.values()) for (const entry of registeredRoutes) result.push({
2079
- addonId: entry.addonId,
2080
- method: entry.route.method,
2081
- path: entry.fullPath,
2082
- access: entry.route.access,
2083
- description: entry.route.description
2084
- });
2085
- return result;
2086
- }
2087
- };
2088
- /**
2089
- * Match a route pattern against an actual path.
2090
- * Supports :param segments (e.g., /addon/:addonId/items/:id).
2091
- * Returns extracted params or null if no match.
2092
- */
2093
- function matchPath(pattern, path) {
2094
- const patternParts = pattern.split("/").filter(Boolean);
2095
- const pathParts = path.split("/").filter(Boolean);
2096
- if (patternParts.length !== pathParts.length) return null;
2097
- const params = {};
2098
- for (let i = 0; i < patternParts.length; i++) {
2099
- const patternPart = patternParts[i];
2100
- const pathPart = pathParts[i];
2101
- if (patternPart.startsWith(":")) params[patternPart.slice(1)] = pathPart;
2102
- else if (patternPart !== pathPart) return null;
2103
- }
2104
- return params;
2105
- }
2106
- //#endregion
2107
2145
  //#region src/tls/cert-manager.ts
2108
2146
  var execFileAsync$3 = promisify(execFile);
2109
2147
  /**
@@ -2177,54 +2215,6 @@ function loadTlsCert(certPath, keyPath) {
2177
2215
  };
2178
2216
  }
2179
2217
  //#endregion
2180
- //#region src/addon/addon-api-factory.ts
2181
- /**
2182
- * Wrap a raw tRPC caller (from `createCallerFactory`) in a proxy that
2183
- * exposes each leaf procedure as `{ query, mutate, subscribe }`, matching
2184
- * the shape of `CreateTRPCClient<AppRouter>`.
2185
- *
2186
- * The tricky part: tRPC v11 callers expose nested routers as callable
2187
- * no-op functions (e.g. `caller.greet` is `typeof === 'function'`), so
2188
- * we can't use `typeof` to tell namespace from leaf. Instead, we return
2189
- * a unified proxy that handles BOTH behaviours:
2190
- *
2191
- * - Accessing `.query` / `.mutate` treats the current node as a leaf
2192
- * procedure and invokes `caller(input)` when called.
2193
- * - Accessing `.subscribe` throws (not supported on direct caller).
2194
- * - Accessing any other property descends into `caller[prop]` and
2195
- * returns a nested proxy.
2196
- */
2197
- function wrapCallerAsClient(caller) {
2198
- return new Proxy(Object.create(null), { get(_target, prop) {
2199
- if (typeof prop !== "string") return void 0;
2200
- if (prop === "query" || prop === "mutate") {
2201
- if (typeof caller !== "function") throw new Error(`Cannot call .${prop}() — this tRPC node is not a procedure`);
2202
- const fn = caller;
2203
- return (input) => fn(input);
2204
- }
2205
- if (prop === "subscribe") return () => {
2206
- throw new Error(`subscribe() is not supported on direct caller — use the WSS client for subscriptions`);
2207
- };
2208
- const child = caller?.[prop];
2209
- if (child === void 0 || child === null) return void 0;
2210
- return wrapCallerAsClient(child);
2211
- } });
2212
- }
2213
- var AddonApiFactory = class {
2214
- /**
2215
- * Create a direct caller -- calls tRPC procedures directly in-process.
2216
- * Zero network overhead. Used for in-process addons and dev mode.
2217
- *
2218
- * Returns `AddonApi` — the same tRPC client surface that broker-routed
2219
- * callers get. Callers treat it uniformly as `context.api` regardless
2220
- * of the underlying transport.
2221
- */
2222
- async createDirectCaller(options) {
2223
- const { initTRPC } = await import("@trpc/server");
2224
- return wrapCallerAsClient(initTRPC.create().createCallerFactory(options.router)(options.context));
2225
- }
2226
- };
2227
- //#endregion
2228
2218
  //#region src/builtins/sqlite-storage/integration-registry.ts
2229
2219
  function serializeSetting(value) {
2230
2220
  if (typeof value === "number") return {
@@ -2799,6 +2789,268 @@ var IntegrationRegistry = class IntegrationRegistry {
2799
2789
  }
2800
2790
  };
2801
2791
  //#endregion
2792
+ //#region src/kernel/deps/ensure-native-prebuilds.ts
2793
+ /**
2794
+ * `ensureNativePrebuilds` — the post-install native-prebuild ENSURE step the
2795
+ * shared `RootUpdateService` runs while staging a `@camstack/server` closure,
2796
+ * BEFORE its `findMissingNativePrebuilds` validator (in `@camstack/node-root`)
2797
+ * decides whether to arm the swap.
2798
+ *
2799
+ * Why this exists (Mac desktop incident, 2026-07-21): a runtime
2800
+ * `applyServerUpdate` on a packaged desktop stages the closure with
2801
+ * `npm install @camstack/server@X` under the app's BUNDLED bare Node. The one
2802
+ * TRADITIONAL (non-N-API) native, `better-sqlite3`, resolves its `.node` via
2803
+ * its `install` script `prebuild-install || node-gyp rebuild`. On a user's Mac
2804
+ * with no build toolchain (and where the auto `prebuild-install` does not
2805
+ * target the bundled Node's ABI/arch the way the DMG build's EXPLICIT
2806
+ * `prebuild-install --runtime node --target <bundled> --arch <arch>` call does)
2807
+ * that leaves the module SOURCE-ONLY → the closure has no `better-sqlite3`
2808
+ * `.node` → the validator refuses the swap ("staged closure missing native
2809
+ * prebuilds: better-sqlite3"). The docker image never hits this: its Node ABI
2810
+ * has a published prebuild the auto path fetches cleanly, and it carries a
2811
+ * build toolchain fallback.
2812
+ *
2813
+ * This mirrors the DMG build's explicit re-fetch (`scripts/stage-deps.mjs`)
2814
+ * into the runtime staging path: for each traditional native that is present
2815
+ * in the closure but missing its compiled `.node`, fetch the prebuild for the
2816
+ * RUNNING Node ABI/arch (the same Node that will load the swapped closure).
2817
+ *
2818
+ * N-API natives (`sharp`, `node-av`) are ABI-stable and ship their binaries as
2819
+ * platform SIBLING packages that npm fetches reliably with no compile step, so
2820
+ * they are not in scope here — a genuine miss there is a broken install the
2821
+ * validator should still reject, not something a prebuild re-fetch can heal.
2822
+ *
2823
+ * Injected into the update service from the construction site so the zero-dep
2824
+ * `@camstack/node-root` layer never depends on npm/@camstack/system, and the
2825
+ * fetch is unit-testable with a fake fetcher.
2826
+ */
2827
+ var execFileAsync$2 = promisify(execFile);
2828
+ /** Bounded recursive `.node` scan depth inside a module dir. */
2829
+ var NATIVE_SCAN_DEPTH = 4;
2830
+ /** Timeout for a single `prebuild-install` fetch. */
2831
+ var PREBUILD_FETCH_TIMEOUT_MS = 12e4;
2832
+ /**
2833
+ * Traditional (compile-or-prebuild) natives an installed closure must carry a
2834
+ * `.node` for. Only these are ENSURE-able by a prebuild re-fetch; N-API natives
2835
+ * are excluded (see file header).
2836
+ */
2837
+ var TRADITIONAL_NATIVE_PACKAGES = ["better-sqlite3"];
2838
+ /** Bounded recursive scan for ANY `*.node` file under `dir`. */
2839
+ function hasDotNode(dir, maxDepth) {
2840
+ let entries;
2841
+ try {
2842
+ entries = fs$17.readdirSync(dir, { withFileTypes: true });
2843
+ } catch {
2844
+ return false;
2845
+ }
2846
+ for (const entry of entries) if (entry.isFile() && entry.name.endsWith(".node")) return true;
2847
+ if (maxDepth <= 0) return false;
2848
+ for (const entry of entries) if (entry.isDirectory() && hasDotNode(path$39.join(dir, entry.name), maxDepth - 1)) return true;
2849
+ return false;
2850
+ }
2851
+ /** Locate the bundled `prebuild-install` bin.js inside the staged closure. */
2852
+ function resolvePrebuildInstallBin(closureDir, moduleDir) {
2853
+ return [path$39.join(moduleDir, "node_modules", "prebuild-install", "bin.js"), path$39.join(closureDir, "node_modules", "prebuild-install", "bin.js")].find((c) => fs$17.existsSync(c)) ?? null;
2854
+ }
2855
+ /**
2856
+ * Default fetcher: run the closure's own `prebuild-install` under the CURRENT
2857
+ * Node (`process.execPath`) — no reliance on `npx`/`npm` on PATH (a packaged
2858
+ * app ships a bare Node). Explicitly targets the running ABI/arch, mirroring
2859
+ * `scripts/stage-deps.mjs`.
2860
+ */
2861
+ function makeDefaultFetch(closureDir, logger) {
2862
+ return async (moduleDir, target) => {
2863
+ const bin = resolvePrebuildInstallBin(closureDir, moduleDir);
2864
+ if (bin === null) throw new Error(`prebuild-install not found in the staged closure for ${moduleDir}`);
2865
+ logger.info("fetching native prebuild via prebuild-install", { meta: {
2866
+ moduleDir,
2867
+ bin,
2868
+ nodeVersion: target.nodeVersion,
2869
+ arch: target.arch
2870
+ } });
2871
+ await execFileAsync$2(process.execPath, [
2872
+ bin,
2873
+ "--runtime",
2874
+ "node",
2875
+ "--target",
2876
+ target.nodeVersion,
2877
+ "--arch",
2878
+ target.arch
2879
+ ], {
2880
+ cwd: moduleDir,
2881
+ timeout: PREBUILD_FETCH_TIMEOUT_MS
2882
+ });
2883
+ };
2884
+ }
2885
+ /**
2886
+ * Ensure every traditional native in `<closureDir>/node_modules` carries its
2887
+ * compiled `.node`, fetching the prebuild for the running ABI when missing.
2888
+ *
2889
+ * A NO-OP when nothing is missing (docker / tests) and when a native package is
2890
+ * absent from the closure. Never throws for a single package's fetch failure —
2891
+ * it logs and continues so the downstream `findMissingNativePrebuilds`
2892
+ * validator makes the final swap/abort decision. Returns the packages whose
2893
+ * prebuild was successfully fetched (for logging/tests).
2894
+ */
2895
+ async function ensureNativePrebuilds(closureDir, options) {
2896
+ const nm = path$39.join(closureDir, "node_modules");
2897
+ const target = options.target ?? {
2898
+ nodeVersion: process.versions.node,
2899
+ arch: process.arch
2900
+ };
2901
+ const packages = options.packages ?? TRADITIONAL_NATIVE_PACKAGES;
2902
+ const fetchPrebuild = options.fetchPrebuild ?? makeDefaultFetch(closureDir, options.logger);
2903
+ const fetched = [];
2904
+ for (const pkg of packages) {
2905
+ const moduleDir = path$39.join(nm, pkg);
2906
+ if (!fs$17.existsSync(moduleDir)) continue;
2907
+ if (hasDotNode(moduleDir, 4)) continue;
2908
+ options.logger.warn("staged closure native prebuild missing — fetching for running ABI", { meta: {
2909
+ pkg,
2910
+ moduleDir,
2911
+ nodeVersion: target.nodeVersion,
2912
+ arch: target.arch
2913
+ } });
2914
+ try {
2915
+ await fetchPrebuild(moduleDir, target);
2916
+ } catch (err) {
2917
+ options.logger.error("native prebuild fetch failed (validator will decide)", { meta: {
2918
+ pkg,
2919
+ error: errMsg(err)
2920
+ } });
2921
+ continue;
2922
+ }
2923
+ if (hasDotNode(moduleDir, 4)) {
2924
+ fetched.push(pkg);
2925
+ options.logger.info("native prebuild fetched", { meta: { pkg } });
2926
+ } else options.logger.error("native prebuild still missing after fetch", { meta: { pkg } });
2927
+ }
2928
+ return fetched;
2929
+ }
2930
+ //#endregion
2931
+ //#region src/kernel/deps/ensure-addon-natives.ts
2932
+ /**
2933
+ * `ensureAddonNativePrebuilds` — the POST-install native-prebuild ENSURE pass an
2934
+ * addon install runs on the INSTALLED addon dir AFTER `npm install`.
2935
+ *
2936
+ * Why this exists (Mac desktop first-boot FATAL, 2026-07-21): `installCopy`
2937
+ * copies `dist/`, plants prebuilt natives from the bundled addon copy
2938
+ * (`copyBundledNativeModules`), then `npm install`s the addon's runtime deps.
2939
+ * On a TOOLCHAIN-LESS host that `npm install` RE-CREATES the traditional native
2940
+ * `better-sqlite3` SOURCE-ONLY — clobbering the good `.node` the pre-install
2941
+ * copy just planted — and the runner later dies at addon init with a cryptic
2942
+ * "Could not locate the bindings file". The copy-BEFORE-install fix was
2943
+ * empirically insufficient: npm's own install in the copied dir replaces the
2944
+ * satisfied dep without its binary.
2945
+ *
2946
+ * This pass runs LAST, so it always sees the final on-disk state npm left, and
2947
+ * per referenced traditional native still lacking its compiled `.node`:
2948
+ * 1. bundled-copy first — if the bundled addon copy carries the matching
2949
+ * `.node` (same machine → same platform/arch/ABI), re-plant it DIRECTLY.
2950
+ * Cheapest + offline-safe; runs BEFORE any network fetch.
2951
+ * 2. fetch fallback — otherwise fetch the prebuild for the running ABI via the
2952
+ * shared `ensureNativePrebuilds` pointed at the addon dir.
2953
+ * 3. FAIL LOUD — if the native is STILL source-only after both, log a clear
2954
+ * error naming module + addon and THROW so the install fails at install
2955
+ * time rather than at addon init.
2956
+ *
2957
+ * N-API natives (`sharp`, `node-av`) ship their binaries as ABI-stable platform
2958
+ * SIBLING packages npm fetches without a compile step, so they are excluded from
2959
+ * the default set — a miss there is a broken install, not something a prebuild
2960
+ * re-fetch heals (same rationale as `ensureNativePrebuilds`).
2961
+ */
2962
+ /**
2963
+ * Re-plant `<srcModuleDir>` → `<dstModuleDir>` when the source carries a `.node`.
2964
+ * Returns whether the destination ends up with a compiled binary.
2965
+ */
2966
+ function replantFromBundled(srcModuleDir, dstModuleDir, hasNative) {
2967
+ if (!hasNative(srcModuleDir)) return false;
2968
+ try {
2969
+ fs$17.rmSync(dstModuleDir, {
2970
+ recursive: true,
2971
+ force: true
2972
+ });
2973
+ fs$17.mkdirSync(path$39.dirname(dstModuleDir), { recursive: true });
2974
+ fs$17.cpSync(srcModuleDir, dstModuleDir, {
2975
+ recursive: true,
2976
+ dereference: true
2977
+ });
2978
+ } catch {
2979
+ return false;
2980
+ }
2981
+ return hasNative(dstModuleDir);
2982
+ }
2983
+ /**
2984
+ * Ensure every referenced traditional native in `<addonDir>/node_modules`
2985
+ * carries its compiled `.node` after the addon's `npm install`. Bundled-copy
2986
+ * first (offline), prebuild-fetch fallback, LOUD throw on a residual miss.
2987
+ *
2988
+ * SKIPS a native absent from the addon's own `node_modules` (it resolves via a
2989
+ * hoisted host copy — not this addon's concern). A NO-OP in docker / dev where
2990
+ * npm produced a working `.node` (already-present). Returns the per-native
2991
+ * outcomes for logging/tests.
2992
+ *
2993
+ * @throws if any required native is still source-only after copy + fetch.
2994
+ */
2995
+ async function ensureAddonNativePrebuilds(addonDir, options) {
2996
+ const packages = options.packages ?? TRADITIONAL_NATIVE_PACKAGES;
2997
+ const hasNative = options.hasNative ?? ((dir) => hasDotNode(dir, 4));
2998
+ const nm = path$39.join(addonDir, "node_modules");
2999
+ const results = [];
3000
+ const missing = [];
3001
+ for (const pkg of packages) {
3002
+ const moduleDir = path$39.join(nm, pkg);
3003
+ if (!fs$17.existsSync(moduleDir)) continue;
3004
+ if (hasNative(moduleDir)) {
3005
+ results.push({
3006
+ pkg,
3007
+ outcome: "already-present"
3008
+ });
3009
+ continue;
3010
+ }
3011
+ if (options.bundledSourceDir) {
3012
+ const src = path$39.join(options.bundledSourceDir, "node_modules", pkg);
3013
+ if (replantFromBundled(src, moduleDir, hasNative)) {
3014
+ options.logger.info("addon native prebuild re-planted from bundled copy (offline)", { meta: {
3015
+ addon: options.addonName,
3016
+ pkg,
3017
+ src,
3018
+ moduleDir
3019
+ } });
3020
+ results.push({
3021
+ pkg,
3022
+ outcome: "copied"
3023
+ });
3024
+ continue;
3025
+ }
3026
+ }
3027
+ if ((await ensureNativePrebuilds(addonDir, {
3028
+ logger: options.logger,
3029
+ packages: [pkg],
3030
+ ...options.target ? { target: options.target } : {},
3031
+ ...options.fetchPrebuild ? { fetchPrebuild: options.fetchPrebuild } : {}
3032
+ })).includes(pkg)) {
3033
+ results.push({
3034
+ pkg,
3035
+ outcome: "fetched"
3036
+ });
3037
+ continue;
3038
+ }
3039
+ options.logger.error("addon native prebuild MISSING after ensure — module has no compiled .node", { meta: {
3040
+ addon: options.addonName,
3041
+ pkg,
3042
+ moduleDir
3043
+ } });
3044
+ results.push({
3045
+ pkg,
3046
+ outcome: "missing"
3047
+ });
3048
+ missing.push(pkg);
3049
+ }
3050
+ if (missing.length > 0) throw new Error(`${options.addonName} — required native module(s) missing a compiled .node after install (bundled-copy + prebuild-fetch both failed): ${missing.join(", ")}`);
3051
+ return results;
3052
+ }
3053
+ //#endregion
2802
3054
  //#region src/kernel/addon-loader.ts
2803
3055
  function isRecord$1(value) {
2804
3056
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -3160,7 +3412,7 @@ var AddonEngineManager = class {
3160
3412
  };
3161
3413
  //#endregion
3162
3414
  //#region src/kernel/fs-utils.ts
3163
- var execFileAsync$2 = promisify(execFile);
3415
+ var execFileAsync$1 = promisify(execFile);
3164
3416
  /**
3165
3417
  * Ensure a directory exists (recursive).
3166
3418
  * Single source of truth — replaces scattered mkdirSync calls.
@@ -3349,7 +3601,7 @@ function ensureLibraryBuilt(packageName, packagesDir) {
3349
3601
  async function installPackageFromNpm(packageName, targetDir) {
3350
3602
  const tmpDir = await fs$17.promises.mkdtemp(path$39.join(os$18.tmpdir(), "camstack-install-"));
3351
3603
  try {
3352
- const { stdout } = await execFileAsync$2("npm", [
3604
+ const { stdout } = await execFileAsync$1("npm", [
3353
3605
  "pack",
3354
3606
  packageName,
3355
3607
  "--pack-destination",
@@ -3363,7 +3615,7 @@ async function installPackageFromNpm(packageName, targetDir) {
3363
3615
  const tgzPath = path$39.join(tmpDir, tgzFilename);
3364
3616
  const extractDir = path$39.join(tmpDir, "extracted");
3365
3617
  ensureDir(extractDir);
3366
- await execFileAsync$2("tar", [
3618
+ await execFileAsync$1("tar", [
3367
3619
  "-xzf",
3368
3620
  tgzPath,
3369
3621
  "-C",
@@ -3667,268 +3919,6 @@ var AddonManifest = class {
3667
3919
  }
3668
3920
  };
3669
3921
  //#endregion
3670
- //#region src/kernel/deps/ensure-native-prebuilds.ts
3671
- /**
3672
- * `ensureNativePrebuilds` — the post-install native-prebuild ENSURE step the
3673
- * shared `RootUpdateService` runs while staging a `@camstack/server` closure,
3674
- * BEFORE its `findMissingNativePrebuilds` validator (in `@camstack/node-root`)
3675
- * decides whether to arm the swap.
3676
- *
3677
- * Why this exists (Mac desktop incident, 2026-07-21): a runtime
3678
- * `applyServerUpdate` on a packaged desktop stages the closure with
3679
- * `npm install @camstack/server@X` under the app's BUNDLED bare Node. The one
3680
- * TRADITIONAL (non-N-API) native, `better-sqlite3`, resolves its `.node` via
3681
- * its `install` script `prebuild-install || node-gyp rebuild`. On a user's Mac
3682
- * with no build toolchain (and where the auto `prebuild-install` does not
3683
- * target the bundled Node's ABI/arch the way the DMG build's EXPLICIT
3684
- * `prebuild-install --runtime node --target <bundled> --arch <arch>` call does)
3685
- * that leaves the module SOURCE-ONLY → the closure has no `better-sqlite3`
3686
- * `.node` → the validator refuses the swap ("staged closure missing native
3687
- * prebuilds: better-sqlite3"). The docker image never hits this: its Node ABI
3688
- * has a published prebuild the auto path fetches cleanly, and it carries a
3689
- * build toolchain fallback.
3690
- *
3691
- * This mirrors the DMG build's explicit re-fetch (`scripts/stage-deps.mjs`)
3692
- * into the runtime staging path: for each traditional native that is present
3693
- * in the closure but missing its compiled `.node`, fetch the prebuild for the
3694
- * RUNNING Node ABI/arch (the same Node that will load the swapped closure).
3695
- *
3696
- * N-API natives (`sharp`, `node-av`) are ABI-stable and ship their binaries as
3697
- * platform SIBLING packages that npm fetches reliably with no compile step, so
3698
- * they are not in scope here — a genuine miss there is a broken install the
3699
- * validator should still reject, not something a prebuild re-fetch can heal.
3700
- *
3701
- * Injected into the update service from the construction site so the zero-dep
3702
- * `@camstack/node-root` layer never depends on npm/@camstack/system, and the
3703
- * fetch is unit-testable with a fake fetcher.
3704
- */
3705
- var execFileAsync$1 = promisify(execFile);
3706
- /** Bounded recursive `.node` scan depth inside a module dir. */
3707
- var NATIVE_SCAN_DEPTH = 4;
3708
- /** Timeout for a single `prebuild-install` fetch. */
3709
- var PREBUILD_FETCH_TIMEOUT_MS = 12e4;
3710
- /**
3711
- * Traditional (compile-or-prebuild) natives an installed closure must carry a
3712
- * `.node` for. Only these are ENSURE-able by a prebuild re-fetch; N-API natives
3713
- * are excluded (see file header).
3714
- */
3715
- var TRADITIONAL_NATIVE_PACKAGES = ["better-sqlite3"];
3716
- /** Bounded recursive scan for ANY `*.node` file under `dir`. */
3717
- function hasDotNode(dir, maxDepth) {
3718
- let entries;
3719
- try {
3720
- entries = fs$17.readdirSync(dir, { withFileTypes: true });
3721
- } catch {
3722
- return false;
3723
- }
3724
- for (const entry of entries) if (entry.isFile() && entry.name.endsWith(".node")) return true;
3725
- if (maxDepth <= 0) return false;
3726
- for (const entry of entries) if (entry.isDirectory() && hasDotNode(path$39.join(dir, entry.name), maxDepth - 1)) return true;
3727
- return false;
3728
- }
3729
- /** Locate the bundled `prebuild-install` bin.js inside the staged closure. */
3730
- function resolvePrebuildInstallBin(closureDir, moduleDir) {
3731
- return [path$39.join(moduleDir, "node_modules", "prebuild-install", "bin.js"), path$39.join(closureDir, "node_modules", "prebuild-install", "bin.js")].find((c) => fs$17.existsSync(c)) ?? null;
3732
- }
3733
- /**
3734
- * Default fetcher: run the closure's own `prebuild-install` under the CURRENT
3735
- * Node (`process.execPath`) — no reliance on `npx`/`npm` on PATH (a packaged
3736
- * app ships a bare Node). Explicitly targets the running ABI/arch, mirroring
3737
- * `scripts/stage-deps.mjs`.
3738
- */
3739
- function makeDefaultFetch(closureDir, logger) {
3740
- return async (moduleDir, target) => {
3741
- const bin = resolvePrebuildInstallBin(closureDir, moduleDir);
3742
- if (bin === null) throw new Error(`prebuild-install not found in the staged closure for ${moduleDir}`);
3743
- logger.info("fetching native prebuild via prebuild-install", { meta: {
3744
- moduleDir,
3745
- bin,
3746
- nodeVersion: target.nodeVersion,
3747
- arch: target.arch
3748
- } });
3749
- await execFileAsync$1(process.execPath, [
3750
- bin,
3751
- "--runtime",
3752
- "node",
3753
- "--target",
3754
- target.nodeVersion,
3755
- "--arch",
3756
- target.arch
3757
- ], {
3758
- cwd: moduleDir,
3759
- timeout: PREBUILD_FETCH_TIMEOUT_MS
3760
- });
3761
- };
3762
- }
3763
- /**
3764
- * Ensure every traditional native in `<closureDir>/node_modules` carries its
3765
- * compiled `.node`, fetching the prebuild for the running ABI when missing.
3766
- *
3767
- * A NO-OP when nothing is missing (docker / tests) and when a native package is
3768
- * absent from the closure. Never throws for a single package's fetch failure —
3769
- * it logs and continues so the downstream `findMissingNativePrebuilds`
3770
- * validator makes the final swap/abort decision. Returns the packages whose
3771
- * prebuild was successfully fetched (for logging/tests).
3772
- */
3773
- async function ensureNativePrebuilds(closureDir, options) {
3774
- const nm = path$39.join(closureDir, "node_modules");
3775
- const target = options.target ?? {
3776
- nodeVersion: process.versions.node,
3777
- arch: process.arch
3778
- };
3779
- const packages = options.packages ?? TRADITIONAL_NATIVE_PACKAGES;
3780
- const fetchPrebuild = options.fetchPrebuild ?? makeDefaultFetch(closureDir, options.logger);
3781
- const fetched = [];
3782
- for (const pkg of packages) {
3783
- const moduleDir = path$39.join(nm, pkg);
3784
- if (!fs$17.existsSync(moduleDir)) continue;
3785
- if (hasDotNode(moduleDir, 4)) continue;
3786
- options.logger.warn("staged closure native prebuild missing — fetching for running ABI", { meta: {
3787
- pkg,
3788
- moduleDir,
3789
- nodeVersion: target.nodeVersion,
3790
- arch: target.arch
3791
- } });
3792
- try {
3793
- await fetchPrebuild(moduleDir, target);
3794
- } catch (err) {
3795
- options.logger.error("native prebuild fetch failed (validator will decide)", { meta: {
3796
- pkg,
3797
- error: errMsg(err)
3798
- } });
3799
- continue;
3800
- }
3801
- if (hasDotNode(moduleDir, 4)) {
3802
- fetched.push(pkg);
3803
- options.logger.info("native prebuild fetched", { meta: { pkg } });
3804
- } else options.logger.error("native prebuild still missing after fetch", { meta: { pkg } });
3805
- }
3806
- return fetched;
3807
- }
3808
- //#endregion
3809
- //#region src/kernel/deps/ensure-addon-natives.ts
3810
- /**
3811
- * `ensureAddonNativePrebuilds` — the POST-install native-prebuild ENSURE pass an
3812
- * addon install runs on the INSTALLED addon dir AFTER `npm install`.
3813
- *
3814
- * Why this exists (Mac desktop first-boot FATAL, 2026-07-21): `installCopy`
3815
- * copies `dist/`, plants prebuilt natives from the bundled addon copy
3816
- * (`copyBundledNativeModules`), then `npm install`s the addon's runtime deps.
3817
- * On a TOOLCHAIN-LESS host that `npm install` RE-CREATES the traditional native
3818
- * `better-sqlite3` SOURCE-ONLY — clobbering the good `.node` the pre-install
3819
- * copy just planted — and the runner later dies at addon init with a cryptic
3820
- * "Could not locate the bindings file". The copy-BEFORE-install fix was
3821
- * empirically insufficient: npm's own install in the copied dir replaces the
3822
- * satisfied dep without its binary.
3823
- *
3824
- * This pass runs LAST, so it always sees the final on-disk state npm left, and
3825
- * per referenced traditional native still lacking its compiled `.node`:
3826
- * 1. bundled-copy first — if the bundled addon copy carries the matching
3827
- * `.node` (same machine → same platform/arch/ABI), re-plant it DIRECTLY.
3828
- * Cheapest + offline-safe; runs BEFORE any network fetch.
3829
- * 2. fetch fallback — otherwise fetch the prebuild for the running ABI via the
3830
- * shared `ensureNativePrebuilds` pointed at the addon dir.
3831
- * 3. FAIL LOUD — if the native is STILL source-only after both, log a clear
3832
- * error naming module + addon and THROW so the install fails at install
3833
- * time rather than at addon init.
3834
- *
3835
- * N-API natives (`sharp`, `node-av`) ship their binaries as ABI-stable platform
3836
- * SIBLING packages npm fetches without a compile step, so they are excluded from
3837
- * the default set — a miss there is a broken install, not something a prebuild
3838
- * re-fetch heals (same rationale as `ensureNativePrebuilds`).
3839
- */
3840
- /**
3841
- * Re-plant `<srcModuleDir>` → `<dstModuleDir>` when the source carries a `.node`.
3842
- * Returns whether the destination ends up with a compiled binary.
3843
- */
3844
- function replantFromBundled(srcModuleDir, dstModuleDir, hasNative) {
3845
- if (!hasNative(srcModuleDir)) return false;
3846
- try {
3847
- fs$17.rmSync(dstModuleDir, {
3848
- recursive: true,
3849
- force: true
3850
- });
3851
- fs$17.mkdirSync(path$39.dirname(dstModuleDir), { recursive: true });
3852
- fs$17.cpSync(srcModuleDir, dstModuleDir, {
3853
- recursive: true,
3854
- dereference: true
3855
- });
3856
- } catch {
3857
- return false;
3858
- }
3859
- return hasNative(dstModuleDir);
3860
- }
3861
- /**
3862
- * Ensure every referenced traditional native in `<addonDir>/node_modules`
3863
- * carries its compiled `.node` after the addon's `npm install`. Bundled-copy
3864
- * first (offline), prebuild-fetch fallback, LOUD throw on a residual miss.
3865
- *
3866
- * SKIPS a native absent from the addon's own `node_modules` (it resolves via a
3867
- * hoisted host copy — not this addon's concern). A NO-OP in docker / dev where
3868
- * npm produced a working `.node` (already-present). Returns the per-native
3869
- * outcomes for logging/tests.
3870
- *
3871
- * @throws if any required native is still source-only after copy + fetch.
3872
- */
3873
- async function ensureAddonNativePrebuilds(addonDir, options) {
3874
- const packages = options.packages ?? TRADITIONAL_NATIVE_PACKAGES;
3875
- const hasNative = options.hasNative ?? ((dir) => hasDotNode(dir, 4));
3876
- const nm = path$39.join(addonDir, "node_modules");
3877
- const results = [];
3878
- const missing = [];
3879
- for (const pkg of packages) {
3880
- const moduleDir = path$39.join(nm, pkg);
3881
- if (!fs$17.existsSync(moduleDir)) continue;
3882
- if (hasNative(moduleDir)) {
3883
- results.push({
3884
- pkg,
3885
- outcome: "already-present"
3886
- });
3887
- continue;
3888
- }
3889
- if (options.bundledSourceDir) {
3890
- const src = path$39.join(options.bundledSourceDir, "node_modules", pkg);
3891
- if (replantFromBundled(src, moduleDir, hasNative)) {
3892
- options.logger.info("addon native prebuild re-planted from bundled copy (offline)", { meta: {
3893
- addon: options.addonName,
3894
- pkg,
3895
- src,
3896
- moduleDir
3897
- } });
3898
- results.push({
3899
- pkg,
3900
- outcome: "copied"
3901
- });
3902
- continue;
3903
- }
3904
- }
3905
- if ((await ensureNativePrebuilds(addonDir, {
3906
- logger: options.logger,
3907
- packages: [pkg],
3908
- ...options.target ? { target: options.target } : {},
3909
- ...options.fetchPrebuild ? { fetchPrebuild: options.fetchPrebuild } : {}
3910
- })).includes(pkg)) {
3911
- results.push({
3912
- pkg,
3913
- outcome: "fetched"
3914
- });
3915
- continue;
3916
- }
3917
- options.logger.error("addon native prebuild MISSING after ensure — module has no compiled .node", { meta: {
3918
- addon: options.addonName,
3919
- pkg,
3920
- moduleDir
3921
- } });
3922
- results.push({
3923
- pkg,
3924
- outcome: "missing"
3925
- });
3926
- missing.push(pkg);
3927
- }
3928
- if (missing.length > 0) throw new Error(`${options.addonName} — required native module(s) missing a compiled .node after install (bundled-copy + prebuild-fetch both failed): ${missing.join(", ")}`);
3929
- return results;
3930
- }
3931
- //#endregion
3932
3922
  //#region src/kernel/addon-installer.ts
3933
3923
  var execFileAsync = promisify(execFile);
3934
3924
  function parseInstallSource(value) {
@@ -5445,6 +5435,19 @@ var CapabilityRegistry = class CapabilityRegistry {
5445
5435
  _ready = false;
5446
5436
  /** Boot-time dependency graph: capability → dependsOn names (from CapabilityDeclaration) */
5447
5437
  capabilityDeps = /* @__PURE__ */ new Map();
5438
+ /**
5439
+ * capability → addon ids whose MANIFEST declares it.
5440
+ *
5441
+ * Populated by {@link declareFromManifest}, which runs at addon-LOAD time —
5442
+ * before a forked addon's runner has spawned, let alone registered anything.
5443
+ * So this map answers a question `providers` cannot: **which addons still owe
5444
+ * this capability a provider**, i.e. is an absence final or merely early.
5445
+ *
5446
+ * It is not a second registry and nothing waits on it: it stores an argument
5447
+ * `declareFromManifest` was already being handed and dropping, and it is read
5448
+ * synchronously at the moment a caller needs the answer ([D3](../../../../docs/decisions/adr-0003.md)).
5449
+ */
5450
+ manifestDeclarers = /* @__PURE__ */ new Map();
5448
5451
  /** Per-device singleton overrides: deviceId → (capability → addonId) */
5449
5452
  deviceOverrides = /* @__PURE__ */ new Map();
5450
5453
  /** capName → (nodeId → bare addonId) per-node singleton overrides. */
@@ -5570,6 +5573,11 @@ var CapabilityRegistry = class CapabilityRegistry {
5570
5573
  */
5571
5574
  declareFromManifest(declaration, addonId) {
5572
5575
  if (declaration.dependsOn?.length) this.capabilityDeps.set(declaration.name, declaration.dependsOn);
5576
+ if (addonId !== void 0) {
5577
+ const declarers = this.manifestDeclarers.get(declaration.name);
5578
+ if (declarers) declarers.add(addonId);
5579
+ else this.manifestDeclarers.set(declaration.name, new Set([addonId]));
5580
+ }
5573
5581
  if (addonId !== void 0 && declaration.autoActivate !== void 0) this.autoActivateFlags.set(`${declaration.name}/${addonId}`, declaration.autoActivate);
5574
5582
  const state = this.capabilities.get(declaration.name);
5575
5583
  if (!state) {
@@ -5692,6 +5700,22 @@ var CapabilityRegistry = class CapabilityRegistry {
5692
5700
  hasProvider(capabilityName, addonId) {
5693
5701
  return this.capabilities.get(capabilityName)?.providers.has(addonId) ?? false;
5694
5702
  }
5703
+ /**
5704
+ * Addon ids whose manifest declares `capabilityName`, whether or not they
5705
+ * have registered a provider yet.
5706
+ *
5707
+ * Pair it with {@link hasProvider} to separate "this capability's collection
5708
+ * is still filling up" from "this is everything there will ever be" — the
5709
+ * difference between a 503 a client should retry and a 400 it should not.
5710
+ * Every entry is an addon INSTALLED on this node; an addon that is installed
5711
+ * but disabled therefore stays listed, which is the honest answer (the
5712
+ * capability is owed by something that is not going to supply it, and naming
5713
+ * it is the diagnosis).
5714
+ */
5715
+ getManifestDeclarers(capabilityName) {
5716
+ const declarers = this.manifestDeclarers.get(capabilityName);
5717
+ return declarers ? [...declarers] : [];
5718
+ }
5695
5719
  /** Unregister a provider. For singleton: clears active. For collection: removes from list. */
5696
5720
  unregisterProvider(capabilityName, addonId) {
5697
5721
  const state = this.capabilities.get(capabilityName);
@@ -94904,4 +94928,4 @@ var LifecycleJobEngine = class {
94904
94928
  }
94905
94929
  };
94906
94930
  //#endregion
94907
- export { AGENT_CAP_FWD_ACTION, AGENT_CAP_FWD_SERVICE, AGENT_READINESS_SERVICE_NAME, ALL_CAPABILITY_DEFINITIONS, AddonApiFactory, AddonDepsManager, AddonEngineManager, AddonHealthMonitor, AddonInstaller, AddonLoader, AddonManifest, AddonRouteRegistry, AlertCenterAddon, ApiKeyManager, AuthManager, CLUSTER_SECRET_MISMATCH_TYPE, CLUSTER_SECRET_REJECTED_EXIT_CODE, CORE_CAP_SERVICE_NAME, CapRouteError, CapRouteResolver, CapUsageRegistry, CapabilityHandle, CapabilityRegistry, CapabilityUnavailableError, ConfigManager, ConfigStore, ConsoleDestination, ConsoleLoggingAddon, CoreBlocksAddon, CustomActionRegistry, DEFAULT_DATA_PATH, DEVICE_SETTINGS_CONTRIBUTION_METHODS, DEVICE_STATUS_METHOD, DataPlaneRegistry, DeviceManagerAddon, DeviceRegistry, DeviceStore, EVENT_TOPIC_PREFIX, EngineManagerResolver, EventBus, FeatureManager, FilesystemStorageAddon, FilesystemStorageProvider, FrameDecoder, FsStorageBackend, HEALTH_MONITOR_GRACE_PERIOD_MS, HEALTH_MONITOR_RETRY_INTERVALS_MS, HEALTH_MONITOR_TICK_MS, HEAP_RECLAIM_MIN_INTERVAL_MS, HEAP_RECLAIM_TRIGGER_MB, HEAP_WATCH_INTERVAL_MS, HEAP_WATCH_WARN_RATIO, HOME_ASSISTANT_OAUTH_INTEGRATION, HUB_CAP_FWD_ACTION, HUB_CAP_FWD_SERVICE, HubForwarderAddon, HubForwarderDestination, HubLogForwarder, HubNodeRegistry, INFRA_CAPABILITIES, IntegrationRegistry, JobJournal, LifecycleJobEngine, LifecycleStateMachine, LivenessMonitorAddon, LocalAuthAddon, LocalChildClient, LocalChildRegistry, LogManager, LogRingBuffer, LokiDestination, LokiLoggingAddon, METHOD_ACCESS_MAP, ModelDownloadService, NATIVE_PROVIDER_SERVICE_INFIX, NATIVE_SCAN_DEPTH, NativeMetricsAddon, NativeMetricsProvider, NetworkQualityTracker, NotificationService, PYTHON_VERSION, PipelineRunner, PipelineValidator, PythonEnvManager, QUARANTINE_DIRNAME, RESTART_MARKER_FILE, RUNTIME_DEFAULTS, ReadinessRegistry, ReadinessTimeoutError, ReplEngine, RingBuffer, ScopedLogger, ScopedTokenManager, SocketChannel, SqliteSettingsAddon, SqliteSettingsBackend, StagingArea, StorageLocationManager, StorageManager, StorageOrchestratorAddon, StorageOrchestratorService, SystemConfigAddon, SystemEventBus, TRADITIONAL_NATIVE_PACKAGES, ToastService, UDS_NO_ROUTE_PREFIX, UdsLocalTransportClient, UdsLocalTransportServer, UserManager, WinstonDestination, WinstonLoggingAddon, __resetCapUsageRegistryForTests, adaptBrokerToCluster, addonSettingsCapability, bootstrapSchema, brokerCallForCap, brokerTransportLink, buildBinaryPath, buildCapRouters, buildHeapSample, buildLinkChain, buildNativeCapProxy, buildNodeManifest, buildStorageLocationRegistry, buildUdsNativeCapProxy, builderMountedCapNames, callRegisterNodeWithRetry, callWithServiceDiscovery, capActionName, capActionSuffix, capBareAction, capServiceName, classifyAddonDir, classifyCapRoute, clearPendingRestart, clusterEventTopic, clusterSecretMatches, collectModelFiles, contentTypeFor, copyDirRecursive, copyExtraFileDirs, createAddonContext, createAddonDataPlaneFacility, createAddonService, createAuthenticatedFileServer, createBroker, createBrokerDeviceManagerApi, createCoreCapService, createFileDataPlaneHandler, createHubCapForwardService, createHubService, createKernelHwAccel, createLocalTransport, createParentUnownedCallHandler, createProcessService, createReadinessService, createReadinessServiceForRegistry, createScopedProcessManager, createStreamProbeBrokerService, createUdsAddonContext, createUdsEventBridge, createUdsEventBus, createUdsLogger, createUdsLoggerWithControl, createV8Reclaimer, deleteModelFromDisk, deriveAgentListenPort, describeProviderKindDrift, detectWorkspacePackagesDir, downloadBinary, downloadFile, downloadModel, emitDownForOwnedCaps, encodeFrame, ensureAddonNativePrebuilds, ensureBinary, ensureDir, ensureFfmpeg, ensureLibraryBuilt, ensureModel, ensureNativePrebuilds, ensurePython, ensureTlsCert, expandCapMethods, fetchJson, findInPath, formatLogLine, getBrokerEventBus, getCapUsageRegistry, getFfmpegDownloadUrl, getModelFilePath, getMoleculerEventStats, getOrInitReadinessRegistry, getOrInitReadinessRegistryForClient, getPidStats, getPlatformInfo, getPythonDownloadUrl, getRestartMarkerPath, getSinglePidStats, getWorkerDeviceRegistry, hasDotNode, hashClusterSecret, installManifestNativeDeps, installManifestPythonDeps, installPackageFromNpm, installPythonPackages, installPythonRequirements, ipcChildLink, ipcParentLink, isAddonDeploySource, isArrayOutputSchema, isClusterSecretMismatchError, isCollectionArrayMethod, isInfraCapability, isModelDownloaded, isSourceNewer, loadTlsCert, localEndpointPath, localProviderLink, mountNativeCapService, parseCapAction, parseRangeHeader, parseTokenizedUrl, proxyToUpstream, quarantineAddonResidue, readPendingRestart, readinessKey, registerEventBusService, resolveFilePath, resolveHwAccel, resolveNpmInvocation, runNpm, scheduleSelfRestart, scopeKey, scopesAllowDeviceCap, selectAddonResidue, serializeTypedArrays, setHubConnected, setNodeEventInterest, shouldReclaim, startHeapWatch, strandedMb, stripCamstackDeps, subscribePassthrough, udsChildLogToWorkerEntry, validateProviderRegistrations, writePendingRestart };
94931
+ export { AGENT_CAP_FWD_ACTION, AGENT_CAP_FWD_SERVICE, AGENT_READINESS_SERVICE_NAME, ALL_CAPABILITY_DEFINITIONS, AddonApiFactory, AddonDepsManager, AddonEngineManager, AddonHealthMonitor, AddonInstaller, AddonLoader, AddonManifest, AddonRouteRegistry, AlertCenterAddon, ApiKeyManager, AuthManager, CLUSTER_SECRET_MISMATCH_TYPE, CLUSTER_SECRET_REJECTED_EXIT_CODE, CORE_CAP_SERVICE_NAME, CapRouteError, CapRouteResolver, CapUsageRegistry, CapabilityHandle, CapabilityRegistry, CapabilityUnavailableError, ConfigManager, ConfigStore, ConsoleDestination, ConsoleLoggingAddon, CoreBlocksAddon, CustomActionRegistry, DEFAULT_DATA_PATH, DEVICE_SETTINGS_CONTRIBUTION_METHODS, DEVICE_STATUS_METHOD, DataPlaneRegistry, DeviceManagerAddon, DeviceRegistry, DeviceStore, EVENT_TOPIC_PREFIX, EngineManagerResolver, EventBus, FeatureManager, FilesystemStorageAddon, FilesystemStorageProvider, FrameDecoder, FsStorageBackend, HEALTH_MONITOR_GRACE_PERIOD_MS, HEALTH_MONITOR_RETRY_INTERVALS_MS, HEALTH_MONITOR_TICK_MS, HEAP_RECLAIM_MIN_INTERVAL_MS, HEAP_RECLAIM_TRIGGER_MB, HEAP_WATCH_INTERVAL_MS, HEAP_WATCH_WARN_RATIO, HUB_CAP_FWD_ACTION, HUB_CAP_FWD_SERVICE, HubForwarderAddon, HubForwarderDestination, HubLogForwarder, HubNodeRegistry, INFRA_CAPABILITIES, IntegrationRegistry, JobJournal, LifecycleJobEngine, LifecycleStateMachine, LivenessMonitorAddon, LocalAuthAddon, LocalChildClient, LocalChildRegistry, LogManager, LogRingBuffer, LokiDestination, LokiLoggingAddon, METHOD_ACCESS_MAP, ModelDownloadService, NATIVE_PROVIDER_SERVICE_INFIX, NATIVE_SCAN_DEPTH, NativeMetricsAddon, NativeMetricsProvider, NetworkQualityTracker, NotificationService, PYTHON_VERSION, PipelineRunner, PipelineValidator, PythonEnvManager, QUARANTINE_DIRNAME, RESTART_MARKER_FILE, RUNTIME_DEFAULTS, ReadinessRegistry, ReadinessTimeoutError, ReplEngine, RingBuffer, ScopedLogger, ScopedTokenManager, SocketChannel, SqliteSettingsAddon, SqliteSettingsBackend, StagingArea, StorageLocationManager, StorageManager, StorageOrchestratorAddon, StorageOrchestratorService, SystemConfigAddon, SystemEventBus, TRADITIONAL_NATIVE_PACKAGES, ToastService, UDS_NO_ROUTE_PREFIX, UdsLocalTransportClient, UdsLocalTransportServer, UserManager, WinstonDestination, WinstonLoggingAddon, __resetCapUsageRegistryForTests, adaptBrokerToCluster, addonSettingsCapability, bootstrapSchema, brokerCallForCap, brokerTransportLink, buildBinaryPath, buildCapRouters, buildHeapSample, buildLinkChain, buildNativeCapProxy, buildNodeManifest, buildStorageLocationRegistry, buildUdsNativeCapProxy, builderMountedCapNames, callRegisterNodeWithRetry, callWithServiceDiscovery, capActionName, capActionSuffix, capBareAction, capServiceName, classifyAddonDir, classifyCapRoute, clearPendingRestart, clusterEventTopic, clusterSecretMatches, collectModelFiles, contentTypeFor, copyDirRecursive, copyExtraFileDirs, createAddonContext, createAddonDataPlaneFacility, createAddonService, createAuthenticatedFileServer, createBroker, createBrokerDeviceManagerApi, createCoreCapService, createFileDataPlaneHandler, createHubCapForwardService, createHubService, createKernelHwAccel, createLocalTransport, createParentUnownedCallHandler, createProcessService, createReadinessService, createReadinessServiceForRegistry, createScopedProcessManager, createStreamProbeBrokerService, createUdsAddonContext, createUdsEventBridge, createUdsEventBus, createUdsLogger, createUdsLoggerWithControl, createV8Reclaimer, deleteModelFromDisk, deriveAgentListenPort, describeProviderKindDrift, detectWorkspacePackagesDir, downloadBinary, downloadFile, downloadModel, emitDownForOwnedCaps, encodeFrame, ensureAddonNativePrebuilds, ensureBinary, ensureDir, ensureFfmpeg, ensureLibraryBuilt, ensureModel, ensureNativePrebuilds, ensurePython, ensureTlsCert, expandCapMethods, fetchJson, findInPath, formatLogLine, getBrokerEventBus, getCapUsageRegistry, getFfmpegDownloadUrl, getModelFilePath, getMoleculerEventStats, getOrInitReadinessRegistry, getOrInitReadinessRegistryForClient, getPidStats, getPlatformInfo, getPythonDownloadUrl, getRestartMarkerPath, getSinglePidStats, getWorkerDeviceRegistry, hasDotNode, hashClusterSecret, installManifestNativeDeps, installManifestPythonDeps, installPackageFromNpm, installPythonPackages, installPythonRequirements, ipcChildLink, ipcParentLink, isAddonDeploySource, isArrayOutputSchema, isClusterSecretMismatchError, isCollectionArrayMethod, isInfraCapability, isModelDownloaded, isSourceNewer, loadTlsCert, localEndpointPath, localProviderLink, mountNativeCapService, parseCapAction, parseRangeHeader, parseTokenizedUrl, proxyToUpstream, quarantineAddonResidue, readPendingRestart, readinessKey, registerEventBusService, resolveFilePath, resolveHwAccel, resolveNpmInvocation, runNpm, scheduleSelfRestart, scopeKey, scopesAllowAddon, scopesAllowDeviceCap, selectAddonResidue, serializeTypedArrays, setHubConnected, setNodeEventInterest, shouldReclaim, startHeapWatch, strandedMb, stripCamstackDeps, subscribePassthrough, udsChildLogToWorkerEntry, validateProviderRegistrations, writePendingRestart };