@camstack/server 1.0.0 → 1.0.2

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 (234) hide show
  1. package/{src/agent-status-page.ts → dist/agent-status-page.js} +30 -45
  2. package/dist/api/addon-upload.js +441 -0
  3. package/dist/api/addons-custom.router.js +91 -0
  4. package/dist/api/auth-whoami.js +55 -0
  5. package/dist/api/bridge-addons.router.js +109 -0
  6. package/dist/api/capabilities.router.js +229 -0
  7. package/dist/api/core/addon-settings.router.js +117 -0
  8. package/dist/api/core/agents.router.js +73 -0
  9. package/dist/api/core/auth.router.js +286 -0
  10. package/dist/api/core/bulk-update-coordinator.js +229 -0
  11. package/dist/api/core/cap-providers.js +1124 -0
  12. package/dist/api/core/capabilities.router.js +138 -0
  13. package/dist/api/core/collection-preference.js +17 -0
  14. package/dist/api/core/event-bus-proxy.router.js +45 -0
  15. package/dist/api/core/hwaccel.router.js +91 -0
  16. package/dist/api/core/live-events.router.js +61 -0
  17. package/dist/api/core/logs.router.js +172 -0
  18. package/dist/api/core/notifications.router.js +67 -0
  19. package/dist/api/core/repl.router.js +35 -0
  20. package/dist/api/core/settings-backend.router.js +121 -0
  21. package/dist/api/core/stream-probe.router.js +58 -0
  22. package/dist/api/core/system-events.router.js +100 -0
  23. package/dist/api/health/health.routes.js +68 -0
  24. package/{src/api/oauth2/consent-page.ts → dist/api/oauth2/consent-page.js} +11 -20
  25. package/dist/api/oauth2/oauth2-routes.js +219 -0
  26. package/dist/api/trpc/cap-mount-helpers.js +194 -0
  27. package/dist/api/trpc/cap-route-error-formatter.js +133 -0
  28. package/dist/api/trpc/client-ip.js +147 -0
  29. package/dist/api/trpc/core-cap-bridge.js +115 -0
  30. package/dist/api/trpc/generated-cap-mounts.js +388 -0
  31. package/dist/api/trpc/generated-cap-routers.js +7635 -0
  32. package/dist/api/trpc/scope-access.js +93 -0
  33. package/dist/api/trpc/trpc.context.js +184 -0
  34. package/dist/api/trpc/trpc.middleware.js +139 -0
  35. package/dist/api/trpc/trpc.router.js +188 -0
  36. package/dist/auth/session-cookie.js +47 -0
  37. package/dist/boot/boot-config.js +241 -0
  38. package/dist/boot/integration-id-backfill.js +76 -0
  39. package/dist/boot/post-boot.service.js +85 -0
  40. package/dist/core/addon/addon-call-gateway.js +99 -0
  41. package/dist/core/addon/addon-package.service.js +1560 -0
  42. package/dist/core/addon/addon-registry.service.js +2744 -0
  43. package/{src/core/addon/addon-row-manifest.ts → dist/core/addon/addon-row-manifest.js} +5 -5
  44. package/dist/core/addon/addon-search.service.js +62 -0
  45. package/dist/core/addon/addon-settings-provider.js +102 -0
  46. package/dist/core/addon/addon.tokens.js +5 -0
  47. package/dist/core/addon-bridge/addon-bridge.service.js +145 -0
  48. package/dist/core/addon-pages/addon-pages.service.js +107 -0
  49. package/dist/core/addon-widgets/addon-widgets.service.js +120 -0
  50. package/dist/core/agent/agent-registry.service.js +477 -0
  51. package/dist/core/auth/auth.service.js +10 -0
  52. package/dist/core/capability/capability.service.js +58 -0
  53. package/dist/core/config/config.schema.js +7 -0
  54. package/dist/core/config/config.service.js +10 -0
  55. package/dist/core/events/event-bus.service.js +83 -0
  56. package/dist/core/feature/feature.service.js +10 -0
  57. package/dist/core/lifecycle/lifecycle-state-machine.js +6 -0
  58. package/dist/core/logging/log-ring-buffer.js +6 -0
  59. package/dist/core/logging/logging.service.js +130 -0
  60. package/dist/core/logging/scoped-logger.js +6 -0
  61. package/dist/core/moleculer/cap-call-fn.js +50 -0
  62. package/dist/core/moleculer/cap-route-authority.js +122 -0
  63. package/dist/core/moleculer/moleculer.service.js +904 -0
  64. package/dist/core/network/network-quality.service.js +7 -0
  65. package/dist/core/notification/notification-wrapper.service.js +33 -0
  66. package/dist/core/notification/toast-wrapper.service.js +25 -0
  67. package/dist/core/provider/provider.tokens.js +4 -0
  68. package/dist/core/repl/repl-engine.service.js +140 -0
  69. package/dist/core/storage/fs-storage-backend.js +6 -0
  70. package/dist/core/storage/storage-location-manager.js +6 -0
  71. package/dist/core/storage/storage.service.js +7 -0
  72. package/dist/core/streaming/stream-probe.service.js +209 -0
  73. package/dist/core/topology/topology-emitter.service.js +106 -0
  74. package/dist/launcher.js +330 -0
  75. package/dist/main.js +1104 -0
  76. package/dist/manual-boot.js +227 -0
  77. package/package.json +5 -1
  78. package/src/__tests__/addon-install-e2e.test.ts +0 -74
  79. package/src/__tests__/addon-pages-e2e.test.ts +0 -200
  80. package/src/__tests__/addon-route-session.test.ts +0 -17
  81. package/src/__tests__/addon-settings-router.spec.ts +0 -67
  82. package/src/__tests__/addon-upload.spec.ts +0 -475
  83. package/src/__tests__/agent-registry.spec.ts +0 -179
  84. package/src/__tests__/agent-status-page.spec.ts +0 -82
  85. package/src/__tests__/auth-session-cookie.test.ts +0 -48
  86. package/src/__tests__/bulk-update-coordinator.spec.ts +0 -303
  87. package/src/__tests__/cap-ownership-authority.spec.ts +0 -431
  88. package/src/__tests__/cap-providers/cap-providers-location-import.spec.ts +0 -206
  89. package/src/__tests__/cap-providers/cap-usage-graph.spec.ts +0 -37
  90. package/src/__tests__/cap-providers/compute-topology-categories.spec.ts +0 -110
  91. package/src/__tests__/cap-providers/integrations-delete-cascade.spec.ts +0 -292
  92. package/src/__tests__/cap-providers-bulk-update.spec.ts +0 -408
  93. package/src/__tests__/cap-route-adapter.spec.ts +0 -302
  94. package/src/__tests__/cap-routers/_meta.spec.ts +0 -199
  95. package/src/__tests__/cap-routers/addon-settings.router.spec.ts +0 -115
  96. package/src/__tests__/cap-routers/broker-routing.router.spec.ts +0 -177
  97. package/src/__tests__/cap-routers/cap-route-error-formatter.spec.ts +0 -125
  98. package/src/__tests__/cap-routers/capabilities-node.spec.ts +0 -68
  99. package/src/__tests__/cap-routers/device-link-overlay.spec.ts +0 -137
  100. package/src/__tests__/cap-routers/device-manager-aggregate.router.spec.ts +0 -194
  101. package/src/__tests__/cap-routers/harness.ts +0 -163
  102. package/src/__tests__/cap-routers/metrics-provider.router.spec.ts +0 -133
  103. package/src/__tests__/cap-routers/null-provider-guard.spec.ts +0 -64
  104. package/src/__tests__/cap-routers/pipeline-executor.router.spec.ts +0 -159
  105. package/src/__tests__/cap-routers/settings-store.router.spec.ts +0 -291
  106. package/src/__tests__/capability-e2e.test.ts +0 -384
  107. package/src/__tests__/cli-e2e.test.ts +0 -150
  108. package/src/__tests__/core-cap-bridge.spec.ts +0 -91
  109. package/src/__tests__/dev-bootstrap-shm-ring.spec.ts +0 -40
  110. package/src/__tests__/device-settings-contribution-dispatch.spec.ts +0 -280
  111. package/src/__tests__/embedded-deps-e2e.test.ts +0 -125
  112. package/src/__tests__/event-bus-proxy-router.spec.ts +0 -75
  113. package/src/__tests__/fixtures/mock-analysis-addon-a.ts +0 -37
  114. package/src/__tests__/fixtures/mock-analysis-addon-b.ts +0 -37
  115. package/src/__tests__/fixtures/mock-log-addon.ts +0 -37
  116. package/src/__tests__/fixtures/mock-storage-addon.ts +0 -40
  117. package/src/__tests__/framework-allowlist.spec.ts +0 -96
  118. package/src/__tests__/framework-installer-defer-restart.spec.ts +0 -165
  119. package/src/__tests__/https-e2e.test.ts +0 -124
  120. package/src/__tests__/lifecycle-e2e.test.ts +0 -189
  121. package/src/__tests__/live-events-subscription.spec.ts +0 -149
  122. package/src/__tests__/moleculer/uds-readiness.spec.ts +0 -150
  123. package/src/__tests__/moleculer/uds-topology.spec.ts +0 -418
  124. package/src/__tests__/moleculer/uds-unowned-call.spec.ts +0 -383
  125. package/src/__tests__/moleculer-register-node-idempotency.spec.ts +0 -273
  126. package/src/__tests__/native-cap-route.spec.ts +0 -427
  127. package/src/__tests__/oauth2-account-linking.spec.ts +0 -867
  128. package/src/__tests__/post-boot-restart.spec.ts +0 -161
  129. package/src/__tests__/singleton-contention.test.ts +0 -499
  130. package/src/__tests__/streaming-diagnostic.test.ts +0 -615
  131. package/src/__tests__/streaming-scale.test.ts +0 -314
  132. package/src/__tests__/uds-addon-call-wiring.spec.ts +0 -242
  133. package/src/__tests__/uds-log-ingest.spec.ts +0 -183
  134. package/src/api/__tests__/addons-custom.spec.ts +0 -148
  135. package/src/api/__tests__/capabilities.router.test.ts +0 -56
  136. package/src/api/addon-upload.ts +0 -529
  137. package/src/api/addons-custom.router.ts +0 -101
  138. package/src/api/auth-whoami.ts +0 -101
  139. package/src/api/bridge-addons.router.ts +0 -122
  140. package/src/api/capabilities.router.ts +0 -265
  141. package/src/api/core/__tests__/auth-router-totp.spec.ts +0 -297
  142. package/src/api/core/__tests__/integration-markers.spec.ts +0 -10
  143. package/src/api/core/addon-settings.router.ts +0 -127
  144. package/src/api/core/agents.router.ts +0 -86
  145. package/src/api/core/auth.router.ts +0 -322
  146. package/src/api/core/bulk-update-coordinator.ts +0 -305
  147. package/src/api/core/cap-providers.ts +0 -1339
  148. package/src/api/core/capabilities.router.ts +0 -149
  149. package/src/api/core/collection-preference.ts +0 -40
  150. package/src/api/core/event-bus-proxy.router.ts +0 -45
  151. package/src/api/core/hwaccel.router.ts +0 -108
  152. package/src/api/core/live-events.router.ts +0 -67
  153. package/src/api/core/logs.router.ts +0 -195
  154. package/src/api/core/notifications.router.ts +0 -66
  155. package/src/api/core/repl.router.ts +0 -39
  156. package/src/api/core/settings-backend.router.ts +0 -140
  157. package/src/api/core/stream-probe.router.ts +0 -57
  158. package/src/api/core/system-events.router.ts +0 -125
  159. package/src/api/health/health.routes.ts +0 -117
  160. package/src/api/oauth2/__tests__/oauth2-routes.spec.ts +0 -62
  161. package/src/api/oauth2/oauth2-routes.ts +0 -281
  162. package/src/api/trpc/__tests__/client-ip.spec.ts +0 -146
  163. package/src/api/trpc/__tests__/scope-access-device.spec.ts +0 -268
  164. package/src/api/trpc/__tests__/scope-access.spec.ts +0 -102
  165. package/src/api/trpc/__tests__/webrtc-session-ua-enrich.spec.ts +0 -136
  166. package/src/api/trpc/cap-mount-helpers.ts +0 -245
  167. package/src/api/trpc/cap-route-error-formatter.ts +0 -171
  168. package/src/api/trpc/client-ip.ts +0 -147
  169. package/src/api/trpc/core-cap-bridge.ts +0 -154
  170. package/src/api/trpc/generated-cap-mounts.ts +0 -1240
  171. package/src/api/trpc/generated-cap-routers.ts +0 -11523
  172. package/src/api/trpc/scope-access.ts +0 -110
  173. package/src/api/trpc/trpc.context.ts +0 -258
  174. package/src/api/trpc/trpc.middleware.ts +0 -146
  175. package/src/api/trpc/trpc.router.ts +0 -389
  176. package/src/auth/session-cookie.ts +0 -54
  177. package/src/boot/__tests__/integration-id-backfill.spec.ts +0 -131
  178. package/src/boot/boot-config.ts +0 -259
  179. package/src/boot/integration-id-backfill.ts +0 -109
  180. package/src/boot/post-boot.service.ts +0 -105
  181. package/src/core/addon/__tests__/addon-registry-capability.test.ts +0 -62
  182. package/src/core/addon/__tests__/addon-row-manifest.spec.ts +0 -62
  183. package/src/core/addon/addon-call-gateway.ts +0 -171
  184. package/src/core/addon/addon-package.service.ts +0 -1787
  185. package/src/core/addon/addon-registry.service.ts +0 -3130
  186. package/src/core/addon/addon-search.service.ts +0 -91
  187. package/src/core/addon/addon-settings-provider.ts +0 -220
  188. package/src/core/addon/addon.tokens.ts +0 -2
  189. package/src/core/addon-bridge/addon-bridge.service.ts +0 -130
  190. package/src/core/addon-pages/addon-pages.service.spec.ts +0 -117
  191. package/src/core/addon-pages/addon-pages.service.ts +0 -82
  192. package/src/core/addon-widgets/addon-widgets.service.ts +0 -95
  193. package/src/core/agent/agent-registry.service.ts +0 -529
  194. package/src/core/auth/auth.service.spec.ts +0 -86
  195. package/src/core/auth/auth.service.ts +0 -8
  196. package/src/core/capability/capability.service.ts +0 -66
  197. package/src/core/config/config.schema.ts +0 -3
  198. package/src/core/config/config.service.spec.ts +0 -175
  199. package/src/core/config/config.service.ts +0 -7
  200. package/src/core/events/event-bus.service.spec.ts +0 -235
  201. package/src/core/events/event-bus.service.ts +0 -89
  202. package/src/core/feature/feature.service.spec.ts +0 -99
  203. package/src/core/feature/feature.service.ts +0 -8
  204. package/src/core/lifecycle/lifecycle-state-machine.spec.ts +0 -166
  205. package/src/core/lifecycle/lifecycle-state-machine.ts +0 -3
  206. package/src/core/logging/log-ring-buffer.ts +0 -3
  207. package/src/core/logging/logging.service.spec.ts +0 -287
  208. package/src/core/logging/logging.service.ts +0 -143
  209. package/src/core/logging/scoped-logger.ts +0 -3
  210. package/src/core/moleculer/cap-call-fn.spec.ts +0 -173
  211. package/src/core/moleculer/cap-call-fn.ts +0 -107
  212. package/src/core/moleculer/cap-route-authority.ts +0 -194
  213. package/src/core/moleculer/moleculer.service.ts +0 -1072
  214. package/src/core/network/network-quality.service.spec.ts +0 -53
  215. package/src/core/network/network-quality.service.ts +0 -5
  216. package/src/core/notification/notification-wrapper.service.ts +0 -34
  217. package/src/core/notification/toast-wrapper.service.ts +0 -27
  218. package/src/core/provider/provider.tokens.ts +0 -1
  219. package/src/core/repl/repl-engine.service.spec.ts +0 -444
  220. package/src/core/repl/repl-engine.service.ts +0 -155
  221. package/src/core/storage/fs-storage-backend.spec.ts +0 -70
  222. package/src/core/storage/fs-storage-backend.ts +0 -3
  223. package/src/core/storage/storage-location-manager.spec.ts +0 -130
  224. package/src/core/storage/storage-location-manager.ts +0 -3
  225. package/src/core/storage/storage.service.spec.ts +0 -73
  226. package/src/core/storage/storage.service.ts +0 -3
  227. package/src/core/streaming/stream-probe.service.ts +0 -221
  228. package/src/core/topology/topology-emitter.service.ts +0 -105
  229. package/src/launcher.ts +0 -314
  230. package/src/main.ts +0 -1245
  231. package/src/manual-boot.ts +0 -301
  232. package/tsconfig.build.json +0 -8
  233. package/tsconfig.json +0 -33
  234. package/vitest.config.ts +0 -26
@@ -0,0 +1,904 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MoleculerService = void 0;
4
+ exports.buildChildUdsManifest = buildChildUdsManifest;
5
+ const kernel_1 = require("@camstack/kernel");
6
+ const cap_call_fn_js_1 = require("./cap-call-fn.js");
7
+ const cap_route_authority_js_1 = require("./cap-route-authority.js");
8
+ const types_1 = require("@camstack/types");
9
+ const node_crypto_1 = require("node:crypto");
10
+ class MoleculerService {
11
+ eventBus;
12
+ config;
13
+ logging;
14
+ capabilityService;
15
+ streamProbe;
16
+ broker;
17
+ /** Narrow-typed view of `this.broker` — see `BrokerLike` doc above. */
18
+ get brokerSafe() {
19
+ return this.broker;
20
+ }
21
+ logger;
22
+ /**
23
+ * D3 authority: union of every node's manifest delivered via
24
+ * `$hub.registerNode`. Populated by `onRegisterNode` in `hubDeps`.
25
+ */
26
+ nodeRegistry = new kernel_1.HubNodeRegistry();
27
+ nodeCallFns = new Map();
28
+ /**
29
+ * D3: callback invoked whenever a bare-ID agent node completes the
30
+ * `$hub.registerNode` handshake. Registered by `AgentRegistryService`
31
+ * via `setOnAgentRegistered()`. The handshake is the authoritative
32
+ * completeness signal — the hub has the full manifest at this point
33
+ * and reconciliation can run immediately (no grace delay needed).
34
+ */
35
+ onAgentRegisteredCb = null;
36
+ /**
37
+ * Hub-side authoritative readiness registry. Subscribed to the
38
+ * shared `EventBusService` so it ingests both hub-local emits and
39
+ * remote emits forwarded via `$hub.event`. Exposed to:
40
+ * - the `$readiness.getSnapshot` Moleculer action (consumed by
41
+ * workers / agents on boot)
42
+ * - `ctx.kernel.readinessRegistry` on every hub addon context so
43
+ * hub consumers share the same snapshot.
44
+ */
45
+ readinessRegistry;
46
+ /**
47
+ * Resolved cluster secret (`CAMSTACK_CLUSTER_SECRET` env, else
48
+ * `cluster.secret` config), or `undefined` when none is configured.
49
+ * Threaded both into the broker factory and the hub's
50
+ * `expectedClusterSecretHash` so `$hub.registerNode` can gate on it.
51
+ */
52
+ clusterSecret;
53
+ /**
54
+ * UDS server that listens for addon-runners spawned by this hub node.
55
+ * `null` when the UDS server failed to start (children run broker-only).
56
+ */
57
+ localChildRegistry = null;
58
+ /**
59
+ * Tracks cap names already logged as UDS-routed to avoid log spam.
60
+ * Cleared on no external event — one INFO line per distinct capName
61
+ * across the lifetime of the process.
62
+ */
63
+ udsRoutedCaps = new Set();
64
+ /**
65
+ * CapRouteResolver — the single authority for cap dispatch routing.
66
+ * Constructed at the end of onModuleInit, once `localChildRegistry` is
67
+ * available and the broker has started. All cap dispatch flows through this.
68
+ */
69
+ resolver = null;
70
+ /**
71
+ * Disposer returned by `createUdsEventBridge`. Called in `onModuleDestroy`
72
+ * to unsubscribe the bridge from the parent bus and clear the child-event
73
+ * handler, preventing subscriber leaks on shutdown.
74
+ */
75
+ udsEventBridgeDispose = null;
76
+ get childRegistry() {
77
+ return this.localChildRegistry;
78
+ }
79
+ /** The CapRouteResolver once onModuleInit has completed; null before that. */
80
+ get capRouteResolver() {
81
+ return this.resolver;
82
+ }
83
+ /** This hub's Moleculer node id (e.g. `hub`). Hub-local forked children
84
+ * register under `${nodeId}/${runnerId}`. */
85
+ get nodeId() {
86
+ return this.brokerSafe.nodeID;
87
+ }
88
+ constructor(eventBus, config, logging, capabilityService, streamProbe) {
89
+ this.eventBus = eventBus;
90
+ this.config = config;
91
+ this.logging = logging;
92
+ this.capabilityService = capabilityService;
93
+ this.streamProbe = streamProbe;
94
+ this.logger = this.logging.createLogger('moleculer');
95
+ // Optional port overrides. Live primarily for the e2e harness: when
96
+ // a developer's dev:full is up on the default 6000/4445 ports, an
97
+ // isolated test hub can't reuse them. Production keeps the defaults
98
+ // so cluster discovery + agent-to-hub connections keep working
99
+ // without per-deploy config.
100
+ const tcpPortEnv = process.env['CAMSTACK_HUB_TCP_PORT'];
101
+ const udpPortEnv = process.env['CAMSTACK_HUB_UDP_PORT'];
102
+ const tcpPort = tcpPortEnv ? Number(tcpPortEnv) : undefined;
103
+ const udpPort = udpPortEnv ? Number(udpPortEnv) : undefined;
104
+ // Two-step cast: createBroker's dist `.d.ts` chains through
105
+ // moleculer→eventemitter2 whose types are unresolvable at this
106
+ // boundary, so the inference falls to `error` and trips
107
+ // `no-unsafe-assignment`. Going via `unknown` documents the boundary.
108
+ this.clusterSecret =
109
+ process.env['CAMSTACK_CLUSTER_SECRET'] ?? this.config.get('cluster.secret');
110
+ const broker = (0, kernel_1.createBroker)({
111
+ nodeID: 'hub',
112
+ mode: 'hub',
113
+ logLevel: this.config.get('moleculer.logLevel') ?? 'warn',
114
+ secret: this.clusterSecret,
115
+ ...(tcpPort && !Number.isNaN(tcpPort) ? { tcpPort } : {}),
116
+ ...(udpPort && !Number.isNaN(udpPort) ? { udpPort } : {}),
117
+ });
118
+ // `ServiceBroker` itself surfaces as `error`-typed at this boundary
119
+ // (eventemitter2 chain unresolvable). Documented + single-site cast.
120
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
121
+ this.broker = broker;
122
+ this.readinessRegistry = new types_1.ReadinessRegistry({
123
+ eventBus: this.eventBus,
124
+ sourceNodeId: this.brokerSafe.nodeID,
125
+ logger: this.logging.createLogger('readiness'),
126
+ });
127
+ }
128
+ /**
129
+ * D3: register the callback that fires when an agent node completes the
130
+ * `$hub.registerNode` handshake. Called by `AgentRegistryService` during
131
+ * its own `onModuleInit` — after `MoleculerService.onModuleInit` has
132
+ * returned, so the broker is already live. Option (b) direct-callback
133
+ * wiring: no event-bus round-trip needed for internal core wiring.
134
+ */
135
+ setOnAgentRegistered(cb) {
136
+ this.onAgentRegisteredCb = cb;
137
+ }
138
+ async onModuleInit() {
139
+ const logger = this.logging.createLogger('moleculer');
140
+ const hubDeps = {
141
+ getAddonConfig: (addonId) => {
142
+ return this.config.getAddonConfig(addonId);
143
+ },
144
+ getSettings: (scope, key) => {
145
+ return this.config.get(key ? `${scope}.${key}` : scope);
146
+ },
147
+ getRecentEvents: (category, limit) => {
148
+ return this.eventBus.getRecent(category ? { category } : undefined, limit);
149
+ },
150
+ onLog: (entry) => {
151
+ this.logging.writeFromWorker({
152
+ addonId: entry.addonId,
153
+ nodeId: entry.nodeId,
154
+ level: entry.level,
155
+ message: entry.message,
156
+ ...(entry.scope !== undefined ? { scope: entry.scope } : {}),
157
+ ...(entry.tags ? { tags: entry.tags } : {}),
158
+ ...(entry.meta ? { meta: entry.meta } : {}),
159
+ });
160
+ },
161
+ onSetLogLevel: (level) => {
162
+ const factory = this.brokerSafe.logger;
163
+ const appenders = factory['appenders'];
164
+ if (appenders) {
165
+ for (const appender of appenders) {
166
+ appender.opts.level = level;
167
+ }
168
+ }
169
+ const cache = factory['cache'];
170
+ if (cache) {
171
+ cache.clear();
172
+ }
173
+ logger.info('Moleculer log level changed', { meta: { level } });
174
+ this.brokerSafe.call('$process.setLogLevel', { level }).catch(() => { });
175
+ },
176
+ // D3: registration-handshake path. Nodes send $hub.registerNode with
177
+ // their complete capability manifest; the hub applies it immediately.
178
+ onRegisterNode: (params) => {
179
+ this.onRegisterNode(params);
180
+ },
181
+ onUnregisterNode: (nodeId) => {
182
+ this.removeNodeFromRegistry(nodeId);
183
+ },
184
+ expectedClusterSecretHash: this.clusterSecret
185
+ ? (0, kernel_1.hashClusterSecret)(this.clusterSecret)
186
+ : undefined,
187
+ };
188
+ const hubService = (0, kernel_1.createHubService)(hubDeps);
189
+ this.brokerSafe.createService(hubService);
190
+ // Forked addon-runner children must root their storage (addons-data,
191
+ // the sqlite settings DB) under the SAME data path as the hub's main
192
+ // process. The configured key is `server.dataPath` (populated from the
193
+ // CAMSTACK_DATA env var); reading the non-existent `dataDir` key here
194
+ // made every child silently fall back to the relative `camstack-data`,
195
+ // so the DB escaped the mounted data dir in container deployments.
196
+ const dataDir = this.config.get('server.dataPath') ?? 'camstack-data';
197
+ // UDS local transport: the hub hosts a LocalChildRegistry so its
198
+ // forked addon-runners route cap calls directly over a Unix-domain
199
+ // socket instead of through Moleculer. The broker stays available as
200
+ // the no-route fallback (remote agents + caps no local child owns).
201
+ // If the registry fails to start, children transparently fall back to
202
+ // broker-only — no parentUdsPath is propagated.
203
+ let parentUdsPath;
204
+ try {
205
+ const nodeId = this.brokerSafe.nodeID;
206
+ // F0 (slice-5 outbound): when a forked child issues `ctx.api.<cap>` for a
207
+ // cap NO local sibling owns, route it from the PARENT and return the
208
+ // result over UDS — resolver-first, broker-fallback. Closes over `this`
209
+ // so it reads `this.resolver` at CALL time (the resolver is constructed
210
+ // later in onModuleInit, after broker.start()). The broker fallback
211
+ // reaches the hub's core `$`-infra services (`$core-caps`, `$stream-probe`,
212
+ // settings-store, …) that are Moleculer services, NOT registered
213
+ // capabilities the resolver can see. Before F0 this fell through
214
+ // UDS_NO_ROUTE → the child's own brokerTransportLink; F1+F2 removes that
215
+ // child broker, so the parent must own this path.
216
+ const onUnownedCall = (0, kernel_1.createParentUnownedCallHandler)({
217
+ getResolver: () => this.resolver,
218
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- moleculer types unresolvable; see `broker` getter docstring
219
+ broker: this.broker,
220
+ // Single capability authority — lets the broker fallback pin a
221
+ // device-scoped call to its owning node instead of load-balancing it.
222
+ nodeRegistry: this.nodeRegistry,
223
+ // Hub-local UDS child dispatcher — routes a device-scoped native cap
224
+ // owned by a hub-local child (reolink/hikvision cameras) directly over
225
+ // UDS before any broker fallback. Getter: `this.localChildRegistry` is
226
+ // assigned later in this method, after the handler is constructed.
227
+ getLocalDispatcher: () => this.localChildRegistry,
228
+ // Device-native signal for the registration-race recovery: a forked
229
+ // child's device-native cap (e.g. `switch` on an export target) can be
230
+ // briefly absent from the LocalChildRegistry just after a respawn. The
231
+ // kernel layer has no cap registry, so feed it the `deviceNative` flag
232
+ // from the cap definition. When true + binding-not-yet-registered, the
233
+ // handler retries the hub-local route then throws a precise error rather
234
+ // than the unroutable broker fallback (`switch.switch.getStatus`).
235
+ isDeviceNativeCap: (capName) => this.capabilityService.getRegistry()?.getDefinition(capName)?.deviceNative === true,
236
+ logger: {
237
+ warn: (msg, meta) => logger.warn(msg, meta !== null && meta !== undefined
238
+ ? { meta: meta }
239
+ : undefined),
240
+ },
241
+ });
242
+ const registry = new kernel_1.LocalChildRegistry({
243
+ server: (0, kernel_1.createLocalTransport)().createServer(nodeId),
244
+ onUnownedCall,
245
+ logger: {
246
+ info: (msg, meta) => logger.info(msg, meta !== null && meta !== undefined
247
+ ? { meta: meta }
248
+ : undefined),
249
+ },
250
+ // Hand the UDS-routing layer a view into the operator's
251
+ // active-singleton preference. Without this, when two local
252
+ // children own the same singleton cap (e.g. two `webrtc-session`
253
+ // providers), routing returns
254
+ // the first-registered child by insertion order — silently
255
+ // bypassing `setActiveSingleton`. The closure reads the live
256
+ // registry on every call so a runtime swap takes effect
257
+ // immediately without rebuilding the resolver snapshot.
258
+ getActiveSingletonAddonId: (capName) => this.capabilityService.getRegistry()?.getSingletonAddonId(capName) ?? null,
259
+ });
260
+ await registry.start();
261
+ // E1: apply child manifest + cleanup from the UDS lifecycle (hub-local children).
262
+ // When a runner connects over UDS, apply its cap descriptors to the
263
+ // CapabilityRegistry — same effect as the `$hub.registerNode` RPC for
264
+ // `hub/<runner>` nodes. This runs in PARALLEL with the RPC path until
265
+ // Phase F removes the child broker; `onRegisterNode`'s diff logic ensures
266
+ // double-apply is idempotent (same nodeId + same caps → no-op on the second call).
267
+ registry.onChildRegistered((child) => {
268
+ const hubNodeId = this.brokerSafe.nodeID;
269
+ const nodeId = `${hubNodeId}/${child.childId}`;
270
+ const params = buildChildUdsManifest(nodeId, child.childId, child.caps);
271
+ this.onRegisterNode(params);
272
+ logger.info('UDS child registered — manifest applied', { meta: { nodeId } });
273
+ });
274
+ // E1: cleanup on child disconnect — same effect as `$node.disconnected`
275
+ // for hub-local children. The Moleculer path stays for AGENT nodes.
276
+ registry.onChildGone((childId) => {
277
+ const hubNodeId = this.brokerSafe.nodeID;
278
+ const nodeId = `${hubNodeId}/${childId}`;
279
+ logger.info('UDS child gone — removing from registry', { meta: { childId } });
280
+ this.removeNodeFromRegistry(nodeId);
281
+ });
282
+ // B2: ingest UDS child logs into the hub's LoggingService so they appear
283
+ // in the LogManager / admin-UI log stream alongside broker-forwarded logs.
284
+ // This runs in PARALLEL with the existing $hub.log / onLog broker path —
285
+ // both stay active until Phase F removes the broker path.
286
+ registry.onChildLog((childId, entry) => {
287
+ this.logging.writeFromWorker((0, kernel_1.udsChildLogToWorkerEntry)(childId, entry));
288
+ });
289
+ // D1: answer readiness-snapshot requests from UDS children so they can
290
+ // hydrate without a `$readiness.getSnapshot` Moleculer call.
291
+ // `this.readinessRegistry` is the hub-authoritative instance subscribed
292
+ // to the shared EventBusService — same source `$readiness.getSnapshot` uses.
293
+ // The handler is a live closure (calls `getSnapshotForTransport()` on each
294
+ // request) so children always receive the current snapshot, not a stale copy.
295
+ // Keep `$readiness.getSnapshot` intact — Phase F removes it.
296
+ registry.onReadinessSnapshotRequest(() => this.readinessRegistry.getSnapshotForTransport());
297
+ this.localChildRegistry = registry;
298
+ parentUdsPath = (0, kernel_1.localEndpointPath)(nodeId);
299
+ logger.info('UDS child registry listening', { meta: { path: parentUdsPath } });
300
+ }
301
+ catch (err) {
302
+ logger.warn('UDS child registry failed to start; children stay broker-only', {
303
+ meta: { err: err instanceof Error ? err.message : String(err) },
304
+ });
305
+ }
306
+ const processService = (0, kernel_1.createProcessService)(this.brokerSafe.nodeID, dataDir, undefined, undefined, parentUdsPath);
307
+ this.brokerSafe.createService(processService);
308
+ // $addonHost — REMOVED (Sprint 6). Three-level settings are now
309
+ // served by the `addon-settings` singleton capability. Per-addon
310
+ // Moleculer services expose `settings.*` actions for remote agents.
311
+ // D3: mirror $node.disconnected onto the registry path so nodes that
312
+ // sent a $hub.registerNode manifest get cleaned up on disconnect.
313
+ const bridgeBus = this.broker;
314
+ bridgeBus.localBus.on('$node.disconnected', ({ node }) => {
315
+ this.removeNodeFromRegistry(node.id);
316
+ });
317
+ // Register the $event-bus service BEFORE broker.start(). Moleculer
318
+ // announces service subscriptions to remote nodes only during discovery
319
+ // handshake, not dynamically after post-start `createService()`.
320
+ // Without this, cross-node broadcasts (camstack.evt.<category>) would
321
+ // arrive unreliably for the first ~10s after each node joins.
322
+ (0, kernel_1.registerEventBusService)(this.broker);
323
+ // Register the hub-authoritative `$readiness.getSnapshot` service
324
+ // BEFORE broker.start() so workers / agents see it in their initial
325
+ // INFO packet — post-start `createService` calls propagate via
326
+ // heartbeat (several seconds) and would force workers to poll.
327
+ this.brokerSafe.createService((0, kernel_1.createReadinessServiceForRegistry)(this.readinessRegistry));
328
+ // Register the hub-authoritative `$stream-probe` service —
329
+ // workers route RTSP probe + field-probe through this action when
330
+ // the tRPC WSS link isn't available (default path for forked
331
+ // workers). Keeps ffprobe + HTTP-reachability as a single
332
+ // hub-side implementation; see `createStreamProbeBrokerService`
333
+ // for the shape.
334
+ this.brokerSafe.createService((0, kernel_1.createStreamProbeBrokerService)({
335
+ probe: (url, options) => this.streamProbe.probe(url, options),
336
+ probeField: (key, value) => this.streamProbe.probeField(key, value),
337
+ }));
338
+ // Register `$hwaccel` on hub — every node in the cluster does the
339
+ // same so `broker.call('$hwaccel.resolve', params, { nodeID })`
340
+ // returns the backend list for whichever host the caller targets.
341
+ // Admin UI uses this to show per-agent hwaccel info on the
342
+ // pipeline / NodeDetail pages.
343
+ this.brokerSafe.createService((0, kernel_1.createHwAccelService)((0, kernel_1.createKernelHwAccel)()));
344
+ await this.brokerSafe.start();
345
+ logger.info('Moleculer broker started (TCP transport)');
346
+ // Construct the CapRouteResolver now that both the broker and
347
+ // localChildRegistry are ready. The resolver reads live registry state
348
+ // via closure accessors on every call (not a frozen snapshot), so new
349
+ // children connecting/disconnecting after this point are picked up
350
+ // correctly. The localChildRegistry reference is captured and may be
351
+ // null if UDS failed to start.
352
+ this.resolver = new kernel_1.CapRouteResolver({
353
+ hubNodeId: this.brokerSafe.nodeID,
354
+ broker: this.brokerSafe,
355
+ hubLocalRegistry: this.localChildRegistry,
356
+ nodeAuthority: (0, cap_route_authority_js_1.createNodeCapAuthority)(this.nodeRegistry, {
357
+ resolveSingleton: (capName, nodeId) => this.capabilityService.getRegistry()?.resolveSingletonAddonIdForNode(capName, nodeId) ??
358
+ null,
359
+ }),
360
+ inProcessProviders: (0, cap_route_authority_js_1.createInProcessProviderLookup)(this.capabilityService),
361
+ });
362
+ // Wire the hub's EventBusService into the broker so hub-addon
363
+ // emissions fan out to every remote process via
364
+ // `camstack.evt.<category>`, and incoming $event-bus events land on
365
+ // the same local bus that subscribers already use. The
366
+ // EventBusService's `emit` override handles the "only broadcast
367
+ // locally-originated events" guard, and id-based dedup absorbs the
368
+ // duplicate delivery when `createBrokerEventBus` on a remote uses
369
+ // both broadcast + `$hub.event` for back-compat.
370
+ this.eventBus.attachBroker(this.broker);
371
+ // C2: wire the UDS ↔ Moleculer event bridge so events emitted by UDS
372
+ // children fan to siblings and reach the cluster, and cluster / parent-
373
+ // local events propagate to every UDS child. Inert when no children
374
+ // are connected (bridge just adds a no-op bus subscriber). The bridge
375
+ // is wired after attachBroker so the parentBus is backed by the real
376
+ // shared broker bus and broker.broadcast is live.
377
+ if (this.localChildRegistry !== null) {
378
+ const hubNodeId = this.brokerSafe.nodeID;
379
+ this.udsEventBridgeDispose = (0, kernel_1.createUdsEventBridge)({
380
+ registry: this.localChildRegistry,
381
+ parentBus: this.eventBus,
382
+ parentNodeId: hubNodeId,
383
+ });
384
+ }
385
+ }
386
+ /**
387
+ * Register the log-receiver service for agent log forwarding.
388
+ * Must be called AFTER app.init() so Moleculer re-advertises
389
+ * the updated service list to the network.
390
+ */
391
+ registerLogReceiver() {
392
+ this.brokerSafe.createService({
393
+ name: 'log-receiver',
394
+ actions: {
395
+ ingest: {
396
+ handler: (ctx) => {
397
+ this.logging.writeFromWorker({
398
+ addonId: ctx.params.addonId,
399
+ nodeId: ctx.params.nodeId,
400
+ level: ctx.params.level,
401
+ message: ctx.params.message,
402
+ ...(ctx.params.scope !== undefined ? { scope: ctx.params.scope } : {}),
403
+ ...(ctx.params.tags ? { tags: ctx.params.tags } : {}),
404
+ ...(ctx.params.meta ? { meta: ctx.params.meta } : {}),
405
+ });
406
+ return true;
407
+ },
408
+ },
409
+ },
410
+ });
411
+ }
412
+ /**
413
+ * Register the `$core-caps` Moleculer service that bridges the hub's
414
+ * core (non-addon) tRPC routers onto the cluster mesh.
415
+ *
416
+ * Called from `main.ts` after the appRouter is built — that happens
417
+ * after `app.init()`, so the broker is already started. Post-start
418
+ * `createService` is fine: the service propagates to remote nodes via
419
+ * heartbeat and `brokerTransportLink` polls discovery, so forked
420
+ * addons and late-joining agents still resolve `ctx.api.<coreCap>`.
421
+ * `registerLogReceiver` relies on the same post-init registration.
422
+ */
423
+ registerCoreCapService(service) {
424
+ this.brokerSafe.createService(service);
425
+ }
426
+ /**
427
+ * Call a capability method on a specific node.
428
+ *
429
+ * Delegates all routing decisions to the CapRouteResolver, which classifies
430
+ * the (capName, nodeId) pair into a typed CapRoute and dispatches to the
431
+ * appropriate transport (hub-in-process, hub-local-uds, remote-moleculer,
432
+ * agent-child-forward). A genuinely-absent cap throws CapRouteError (typed,
433
+ * with reason + rejected routes) instead of the old opaque error string.
434
+ *
435
+ * Falls back to the legacy findCallFn path when the resolver is not yet
436
+ * constructed (before onModuleInit completes) or when the resolver throws a
437
+ * no-provider / node-offline error for a node that IS in nodeCallFns — this
438
+ * handles the window between registerNode applying a callFn and the resolver
439
+ * seeing the new node (the resolver reads live registry state via closure
440
+ * accessors, but nodeCallFns is populated by applyNodeManifest which may
441
+ * have run before the resolver was constructed).
442
+ */
443
+ async callCapabilityOnNode(nodeId, capabilityName, methodName, params) {
444
+ const resolver = this.resolver;
445
+ if (resolver !== null) {
446
+ // Extract deviceId from params so device-scoped native caps (ptz, motion-zones, …)
447
+ // resolve through the resolver's deviceId-aware snapshot instead of falling back to
448
+ // the legacy callFn store. The deviceId hint is a number extracted from the method args.
449
+ const rawDeviceId = params !== null && typeof params === 'object' ? Reflect.get(params, 'deviceId') : undefined;
450
+ const routeDeviceId = typeof rawDeviceId === 'number' ? rawDeviceId : undefined;
451
+ try {
452
+ const route = resolver.resolveCapRoute(capabilityName, { nodeId, deviceId: routeDeviceId });
453
+ return await resolver.dispatch(route, methodName, params);
454
+ }
455
+ catch (err) {
456
+ if (err instanceof kernel_1.CapRouteError &&
457
+ (err.reason === 'no-provider' || err.reason === 'node-offline')) {
458
+ // Resolver couldn't find the cap — try the legacy callFn store as a
459
+ // fallback. This covers caps registered in nodeCallFns (e.g. agent
460
+ // nodes that registered before the resolver's snapshot was built or
461
+ // caps that the resolver's nodeAuthority doesn't see yet because the
462
+ // resolver reads live registry state via closure accessors).
463
+ // Device-scoped native caps now resolve via the resolver (M1/M5 thread deviceId),
464
+ // so this fallback only handles genuinely-transitional stale-snapshot windows.
465
+ const callFn = this.findCallFn(nodeId, capabilityName);
466
+ if (callFn !== undefined) {
467
+ return callFn(methodName, params);
468
+ }
469
+ }
470
+ // Rethrow — includes transport-failed and all other errors
471
+ throw err;
472
+ }
473
+ }
474
+ // Pre-init fallback (resolver not yet constructed — before onModuleInit).
475
+ // This path is only reachable in tests that drive onRegisterNode without
476
+ // calling onModuleInit first.
477
+ if (nodeId === 'hub' || nodeId === this.brokerSafe.nodeID) {
478
+ const registry = this.capabilityService.getRegistry();
479
+ const provider = registry?.getSingleton(capabilityName) ?? null;
480
+ if (provider !== null) {
481
+ const fn = provider[methodName];
482
+ if (typeof fn !== 'function')
483
+ throw new Error(`Method "${methodName}" not found on "${capabilityName}"`);
484
+ return fn.call(provider, params);
485
+ }
486
+ }
487
+ const callFn = this.findCallFn(nodeId, capabilityName);
488
+ if (callFn) {
489
+ return callFn(methodName, params);
490
+ }
491
+ throw new kernel_1.CapRouteError(capabilityName, methodName, {
492
+ reason: 'no-provider',
493
+ nodeId,
494
+ rejected: [
495
+ { kind: 'hub-in-process', why: 'CapRouteResolver not initialised (pre-onModuleInit)' },
496
+ ],
497
+ });
498
+ }
499
+ /**
500
+ * D3 registration-handshake entrypoint — invoked by the `$hub.registerNode`
501
+ * Moleculer action (wired through `hubDeps.onRegisterNode`).
502
+ *
503
+ * Captures the node's PREVIOUS manifest before `nodeRegistry.registerNode`
504
+ * overwrites it, then hands both manifests to `applyNodeManifest` so the
505
+ * CapabilityRegistry update is a diff (atomic replace) rather than an
506
+ * unconditional re-register — see `applyNodeManifest` for the rationale.
507
+ */
508
+ onRegisterNode(params) {
509
+ const previousManifest = this.nodeRegistry.getNodeManifest(params.nodeId);
510
+ this.nodeRegistry.registerNode(params);
511
+ this.applyNodeManifest(params, previousManifest);
512
+ // Notify AgentRegistryService to reconcile placement for bare-ID
513
+ // agent nodes (no '/' = not a hub child worker, not the hub itself).
514
+ // The handshake is the authoritative completeness signal — the full
515
+ // manifest is available here so reconciliation runs without delay.
516
+ const { nodeId } = params;
517
+ if (nodeId !== 'hub' && !nodeId.includes('/') && this.onAgentRegisteredCb) {
518
+ this.onAgentRegisteredCb(nodeId);
519
+ }
520
+ }
521
+ /**
522
+ * D3: apply a node's registered manifest onto the CapabilityRegistry.
523
+ * Builds a method proxy for each capability — same registryKey rule
524
+ * (local child → bare addonId, remote agent → addonId@nodeId), same
525
+ * `broker.call` routing shape, same `expandCapMethods` method surface.
526
+ *
527
+ * Called from `onRegisterNode` whenever a node handshakes.
528
+ *
529
+ * Diff-based / idempotent: the D3 protocol legitimately re-handshakes (a
530
+ * node re-sends its COMPLETE manifest — e.g. the post-device-restore
531
+ * `nativeCaps` re-handshake). `registerProvider` throws on a duplicate
532
+ * `(cap, addonId)` pair, so a blind re-register would throw on every
533
+ * re-handshake and trip the registering node's retry loop into a storm.
534
+ * Instead this diffs the NEW manifest against `previousManifest`:
535
+ * unchanged caps are left untouched, dropped caps are unregistered, new
536
+ * caps are registered. This honours the invariant "`registerNode`
537
+ * replaces the node's entire cap set atomically".
538
+ *
539
+ * NOTE: `params.nativeCaps` is stored by `nodeRegistry.registerNode()`
540
+ * already; this method handles only `params.addons` (system caps).
541
+ * Native-cap wiring into device-manager is done in a later task.
542
+ */
543
+ applyNodeManifest(params, previousManifest) {
544
+ const { nodeId, addons } = params;
545
+ const hubNodeId = this.brokerSafe.nodeID;
546
+ const isLocalChild = nodeId.startsWith(hubNodeId + '/');
547
+ const isHubInProcess = nodeId === hubNodeId;
548
+ // Hub in-process addons register themselves during initialize() — skip.
549
+ if (isHubInProcess)
550
+ return;
551
+ const registry = this.capabilityService.getRegistry();
552
+ if (!registry)
553
+ return;
554
+ // Same registryKey rule as CapabilityBridge / onProviderConnected:
555
+ // local child → bare addonId (one instance per forked child)
556
+ // remote agent → addonId@nodeId (unique per agent node)
557
+ // `nodeId` is identical for the previous and new manifest (same node
558
+ // re-handshaking), so the rule resolves the same key on both sides.
559
+ const registryKeyFor = (addonId) => isLocalChild ? addonId : `${addonId}@${nodeId}`;
560
+ // Collect the `(registryKey, capName)` pairs a manifest would APPLY —
561
+ // applying the SAME `isInfraCapability` skip and `capDef` existence
562
+ // check the register block below uses, so the set reflects exactly
563
+ // what is (or would have been) registered. Keyed `${registryKey}::${capName}`.
564
+ // The resolved `capDef` is carried through so the register loop never
565
+ // re-looks it up (and never needs a non-null assertion).
566
+ const appliedKeys = (manifest) => {
567
+ const keys = new Map();
568
+ for (const addon of manifest) {
569
+ const registryKey = registryKeyFor(addon.addonId);
570
+ for (const capName of addon.capabilities) {
571
+ if ((0, kernel_1.isInfraCapability)(capName))
572
+ continue;
573
+ const capDef = registry.getDefinition(capName);
574
+ if (!capDef)
575
+ continue;
576
+ keys.set(`${registryKey}::${capName}`, { addonId: addon.addonId, capName, capDef });
577
+ }
578
+ }
579
+ return keys;
580
+ };
581
+ const desired = appliedKeys(addons);
582
+ const previous = appliedKeys(previousManifest ?? []);
583
+ // ── UNREGISTER ── caps the previous manifest applied but the new one
584
+ // does not. Quiet — readiness is driven by `$node.connected/disconnected`,
585
+ // not by a re-handshake, so no readiness events here.
586
+ for (const [key, { addonId, capName }] of previous) {
587
+ if (desired.has(key))
588
+ continue;
589
+ registry.unregisterProvider(capName, registryKeyFor(addonId));
590
+ this.nodeCallFns.delete(`${nodeId}::${capName}`);
591
+ }
592
+ // ── REGISTER ── caps the new manifest applies that the previous one
593
+ // did not. Caps present in BOTH sets are left untouched — zero churn,
594
+ // no duplicate `registerProvider`, no spurious page/widget re-emit.
595
+ for (const [key, { addonId, capName, capDef }] of desired) {
596
+ if (previous.has(key))
597
+ continue;
598
+ const registryKey = registryKeyFor(addonId);
599
+ // The runner id (= UDS childId) for a hub-local forked child is the
600
+ // trailing segment of its nodeId `${hubNodeId}/${runnerId}`. Only
601
+ // hub-local children are reachable over UDS; agent-hosted providers
602
+ // (`<agent>/<runner>`) fall through to Moleculer.
603
+ const udsChildId = isLocalChild ? nodeId.slice(hubNodeId.length + 1) : null;
604
+ // Per-(cap,node) dispatcher. Routing lives in the unit-tested
605
+ // `buildCapCallFn` (see cap-call-fn.ts):
606
+ // - hub-local child → per-child UDS (collection-safe; keyed by runner
607
+ // id, never by capName which would collapse a COLLECTION cap onto
608
+ // the first child). Fails fast if the child isn't providing — NEVER
609
+ // a Moleculer fallback, since a hub-local child is not a Moleculer
610
+ // service (a broker call would hang the full discovery timeout).
611
+ // - agent-hosted / remote → the unified `CapRouteResolver`, which
612
+ // classifies an agent node as `agent-child-forward` (hub→agent→UDS
613
+ // child) and a direct remote as `remote-moleculer`. This closes the
614
+ // UDS-migration gap where this dispatcher hand-rolled a `broker.call`
615
+ // to an agent that exposes no Moleculer service for the cap.
616
+ // - resolver not yet built (pre-init) → legacy Moleculer call.
617
+ const callFn = (0, cap_call_fn_js_1.buildCapCallFn)({
618
+ capName,
619
+ nodeId,
620
+ udsChildId,
621
+ getLocalChildRegistry: () => this.localChildRegistry,
622
+ getResolver: () => this.resolver,
623
+ legacyBrokerCall: (method, methodParams, targetNode) => (0, kernel_1.callWithServiceDiscovery)(this.brokerSafe, addonId, (0, kernel_1.capActionName)(addonId, capName, method, false), (0, kernel_1.serializeTypedArrays)(methodParams), { nodeID: targetNode, timeout: 60_000 }),
624
+ onUdsRoute: (cap) => {
625
+ if (!this.udsRoutedCaps.has(cap)) {
626
+ this.udsRoutedCaps.add(cap);
627
+ this.logger.info('routing cap over UDS', { meta: { capName: cap } });
628
+ }
629
+ },
630
+ });
631
+ const proxy = { id: addonId, nodeId };
632
+ for (const methodName of Object.keys((0, types_1.expandCapMethods)(capDef))) {
633
+ proxy[methodName] = (methodParams) => callFn(methodName, methodParams);
634
+ }
635
+ registry.registerProvider(capName, registryKey, proxy);
636
+ // Local-first singleton preference (UDS regression fix). A
637
+ // `placement: 'any-node'` singleton (e.g. `pipeline-executor`) can
638
+ // register on BOTH the hub-local forked child and a remote agent.
639
+ // `CapabilityRegistry` keeps the FIRST-registered provider active, so a
640
+ // race could leave the REMOTE agent proxy active — and its callFn routes
641
+ // over Moleculer to a UDS-only agent runner that no longer hosts the
642
+ // Moleculer service ("not found on <agent>"). The hub-local provider is
643
+ // reachable over UDS, so prefer it whenever the current active is absent
644
+ // or remote (`@`-keyed). Never steals from another local provider, so an
645
+ // operator's binding choice (a bare-key local provider) is preserved.
646
+ if (capDef.mode === 'singleton' && isLocalChild) {
647
+ const activeKey = registry.getSingletonAddonId(capName);
648
+ if (activeKey === null || activeKey.includes('@')) {
649
+ registry.setSingletonActiveAddon(capName, registryKey);
650
+ }
651
+ }
652
+ // Emit AddonPageReady / AddonWidgetReady so the admin-UI sidebar
653
+ // refreshes its page/widget registry for cross-process addons.
654
+ if (capName === 'addon-pages-source') {
655
+ this.eventBus.emit({
656
+ id: (0, node_crypto_1.randomUUID)(),
657
+ timestamp: new Date(),
658
+ source: { type: 'addon', id: addonId },
659
+ category: types_1.EventCategory.AddonPageReady,
660
+ data: { addonId, nodeId },
661
+ });
662
+ }
663
+ if (capName === 'addon-widgets-source') {
664
+ this.eventBus.emit({
665
+ id: (0, node_crypto_1.randomUUID)(),
666
+ timestamp: new Date(),
667
+ source: { type: 'addon', id: addonId },
668
+ category: types_1.EventCategory.AddonWidgetReady,
669
+ data: { addonId, nodeId },
670
+ });
671
+ }
672
+ // Store callFn so `callCapabilityOnNode` and `createCapabilityProxy`
673
+ // can reach manifest-registered nodes.
674
+ this.nodeCallFns.set(`${nodeId}::${capName}`, callFn);
675
+ }
676
+ }
677
+ /**
678
+ * D3: remove a node's manifest from the CapabilityRegistry on disconnect.
679
+ * Unregisters every cap the node's last manifest declared and emits
680
+ * synthetic readiness-down events for each.
681
+ */
682
+ removeNodeFromRegistry(nodeId) {
683
+ const manifest = this.nodeRegistry.getNodeManifest(nodeId);
684
+ if (!manifest)
685
+ return; // node never sent a handshake — nothing to do
686
+ const hubNodeId = this.brokerSafe.nodeID;
687
+ const isLocalChild = nodeId.startsWith(hubNodeId + '/');
688
+ const disconnectGen = `disconnect-${nodeId}-${(0, node_crypto_1.randomUUID)()}`;
689
+ const agentNodeId = nodeId.includes('/') ? nodeId.split('/')[0] : nodeId;
690
+ const registry = this.capabilityService.getRegistry();
691
+ for (const addon of manifest) {
692
+ const { addonId, capabilities } = addon;
693
+ const registryKey = isLocalChild ? addonId : `${addonId}@${nodeId}`;
694
+ if (registry) {
695
+ for (const capName of capabilities) {
696
+ registry.unregisterProvider(capName, registryKey);
697
+ }
698
+ }
699
+ for (const capName of capabilities) {
700
+ this.nodeCallFns.delete(`${nodeId}::${capName}`);
701
+ try {
702
+ (0, types_1.emitReadiness)(this.eventBus, {
703
+ capName,
704
+ scope: { type: 'node', nodeId: agentNodeId },
705
+ state: 'down',
706
+ generation: disconnectGen,
707
+ sourceNodeId: hubNodeId,
708
+ });
709
+ }
710
+ catch (err) {
711
+ this.logger.warn('Failed to emit synthetic readiness down', {
712
+ tags: { addonId, nodeId },
713
+ meta: { capName, err: err instanceof Error ? err.message : String(err) },
714
+ });
715
+ }
716
+ }
717
+ }
718
+ this.nodeRegistry.removeNode(nodeId);
719
+ }
720
+ findCallFn(nodeId, capabilityName) {
721
+ // Exact match first — direct hit when the caller knows the full
722
+ // nodeId (e.g. `hub/detection-pipeline`) or when the cap is hosted
723
+ // on a bare top-level node (remote agent with in-process addons).
724
+ const direct = this.nodeCallFns.get(`${nodeId}::${capabilityName}`);
725
+ if (direct)
726
+ return direct;
727
+ // Prefix fallback: forkable addons register under
728
+ // `<parent>/<processName>` (e.g. `dev-agent-0/detection-pipeline`).
729
+ // UI callers typically pass the bare parent nodeId (`dev-agent-0`)
730
+ // because that's what they get from AgentOnline events and the
731
+ // orchestrator assignments. Resolve by finding any registered node
732
+ // whose id starts with `<nodeId>/` and hosts the cap.
733
+ const prefix = `${nodeId}/`;
734
+ for (const key of this.nodeCallFns.keys()) {
735
+ const sep = key.lastIndexOf('::');
736
+ if (sep < 0)
737
+ continue;
738
+ const keyNode = key.slice(0, sep);
739
+ const keyCap = key.slice(sep + 2);
740
+ if (keyCap !== capabilityName)
741
+ continue;
742
+ if (keyNode.startsWith(prefix))
743
+ return this.nodeCallFns.get(key);
744
+ }
745
+ return undefined;
746
+ }
747
+ /**
748
+ * Returns true when a (nodeId, capabilityName) pair is reachable via the
749
+ * legacy fallback paths: either a stored callFn in nodeCallFns, or a
750
+ * hub-local forked child that is reachable over UDS (even without a
751
+ * manifest callFn — e.g. device-scoped native caps). Used by
752
+ * createCapabilityProxy to decide whether to build a proxy when the
753
+ * CapRouteResolver cannot find a route.
754
+ */
755
+ isReachableViaLegacy(nodeId, capabilityName) {
756
+ if (this.findCallFn(nodeId, capabilityName) !== undefined)
757
+ return true;
758
+ return this.localChildRegistry !== null && nodeId.startsWith(`${this.brokerSafe.nodeID}/`);
759
+ }
760
+ /**
761
+ * Build a proxy object that forwards every method call on a capability
762
+ * to the correct transport via CapRouteResolver. Returns null if the
763
+ * capability is provably not reachable on that node (resolver says no-provider
764
+ * AND no legacy callFn exists AND it is not a hub-local child).
765
+ *
766
+ * Used by the generated cap routers when a request includes a `nodeId` field
767
+ * for transparent node routing.
768
+ *
769
+ * Hub-local forked children (e.g. `hub/provider-reolink`) are reachable over
770
+ * UDS even when no manifest callFn exists — device-scoped NATIVE caps (ptz,
771
+ * motion-zones) aren't in `applyNodeManifest`'s callFn store. The proxy is
772
+ * built unconditionally for hub-local children so `callCapabilityOnNode` can
773
+ * route the actual method call via the resolver's hub-local-uds branch.
774
+ */
775
+ createCapabilityProxy(capabilityName, nodeId) {
776
+ const resolver = this.resolver;
777
+ if (resolver !== null) {
778
+ // Use the resolver to determine reachability. If it resolves a route, we
779
+ // can build a proxy. If it throws no-provider but a legacy callFn exists
780
+ // or the node is a hub-local child (for native caps), build the proxy anyway
781
+ // because callCapabilityOnNode's fallback will handle it at dispatch time.
782
+ try {
783
+ resolver.resolveCapRoute(capabilityName, { nodeId });
784
+ // Resolver found a route — proxy is reachable.
785
+ }
786
+ catch (err) {
787
+ if (err instanceof kernel_1.CapRouteError &&
788
+ (err.reason === 'no-provider' || err.reason === 'node-offline')) {
789
+ // Check legacy callFn store and hub-local child fallbacks.
790
+ if (!this.isReachableViaLegacy(nodeId, capabilityName))
791
+ return null;
792
+ // Proxy reachable via fallback paths — fall through to build it.
793
+ }
794
+ else {
795
+ throw err;
796
+ }
797
+ }
798
+ }
799
+ else {
800
+ // Pre-init: use legacy reachability check.
801
+ if (!this.isReachableViaLegacy(nodeId, capabilityName))
802
+ return null;
803
+ }
804
+ // Build a dynamic proxy: every property access returns a function that
805
+ // routes the call through callCapabilityOnNode (which delegates to the resolver).
806
+ return new Proxy({}, {
807
+ get: (_target, methodName) => {
808
+ return (params) => this.callCapabilityOnNode(nodeId, capabilityName, methodName, params);
809
+ },
810
+ });
811
+ }
812
+ /**
813
+ * D3 handshake-fed native-cap view of the whole cluster.
814
+ * Returns every `(nodeId, addonId, capName, deviceId)` tuple stored by
815
+ * `onRegisterNode` — updated atomically each time a node re-handshakes
816
+ * (e.g. after device restore completes). Used by `device-manager.addon.ts`
817
+ * as a reliable fallback when push-based `DeviceBindingsChanged` events
818
+ * were lost in the Moleculer transport handshake window.
819
+ *
820
+ * NOT a Moleculer action — only the hub process calls this directly
821
+ * through the `ctx.kernel.listClusterNativeCaps` injection.
822
+ */
823
+ listClusterNativeCaps() {
824
+ return this.nodeRegistry.listNativeCapEntries();
825
+ }
826
+ /**
827
+ * Per-device slice of {@link listClusterNativeCaps}, served from the
828
+ * registry's `deviceId → entries` index — O(caps-for-device). Used by the
829
+ * per-device `getBindings` hot path so `getAllBindings` doesn't flatten the
830
+ * whole cluster once per device.
831
+ */
832
+ listClusterNativeCapsForDevice(deviceId) {
833
+ return this.nodeRegistry.listNativeCapEntriesForDevice(deviceId);
834
+ }
835
+ /**
836
+ * E2: Send a `set-log-level` UDS message to a hub-local child identified by
837
+ * `nodeId` (e.g. `hub/provider-reolink`). Extracts the `childId` from the
838
+ * nodeId and delegates to `LocalChildRegistry.setChildLogLevel`.
839
+ *
840
+ * Returns `true` only if the nodeId is a hub-local child (`hub/<childId}`) AND
841
+ * the child is currently connected to the LocalChildRegistry (the UDS message
842
+ * was emitted). Returns `false` when the nodeId is not a hub-local child, the
843
+ * registry is absent, or the child is not yet/no longer connected — in all
844
+ * three cases the caller (setProcessLogLevel in cap-providers.ts) falls back
845
+ * to the Moleculer `$node-mgmt.setLogLevel` action.
846
+ */
847
+ setChildLogLevelByNodeId(nodeId, level) {
848
+ const hubNodeId = this.brokerSafe.nodeID;
849
+ if (!nodeId.startsWith(`${hubNodeId}/`))
850
+ return false;
851
+ const childId = nodeId.slice(hubNodeId.length + 1);
852
+ const registry = this.localChildRegistry;
853
+ if (registry === null)
854
+ return false;
855
+ return registry.setChildLogLevel(childId, level);
856
+ }
857
+ async onModuleDestroy() {
858
+ this.udsEventBridgeDispose?.();
859
+ this.udsEventBridgeDispose = null;
860
+ await this.brokerSafe.stop();
861
+ await this.localChildRegistry?.close();
862
+ }
863
+ }
864
+ exports.MoleculerService = MoleculerService;
865
+ // ---------------------------------------------------------------------------
866
+ // Module-level helpers
867
+ // ---------------------------------------------------------------------------
868
+ /**
869
+ * E1: Adapt a child's UDS `ChildCapDescriptor[]` (which has no `addonId`) into
870
+ * a `RegisterNodeParams` that `onRegisterNode` / `applyNodeManifest` can consume.
871
+ *
872
+ * Strategy: use `childId` as the synthetic `addonId`. For currently-shipped addons
873
+ * `childId = runnerId = addonId` (one-addon-one-process, no shared group), so the
874
+ * `registryKey = childId` produced here matches what the Moleculer `$hub.registerNode`
875
+ * path uses — making double-apply via both paths fully idempotent.
876
+ *
877
+ * Singleton vs. device-scoped caps: `ChildCapDescriptor.deviceId` is present only
878
+ * for device-scoped native caps. The `addons` array carries system (singleton/collection)
879
+ * cap names; device-scoped native caps are handled separately via `nativeCaps` in the
880
+ * full `RegisterNodeParams`. For the parallel-window phase (E1), we populate only
881
+ * the `addons` portion — the Moleculer path carries `nativeCaps` on the re-handshake.
882
+ *
883
+ * TODO(co-location): This function synthesises ONE manifest entry with `addonId = childId`
884
+ * (the runner id). This is correct under the current one-addon-one-process invariant
885
+ * where `childId = runnerId = addonId`. If `execution.group` co-location is ever
886
+ * activated (multiple addons sharing one runner), a single runner would host multiple
887
+ * addonIds but this function would register all their caps under one synthetic addonId —
888
+ * collapsing distinct provider registryKeys into one and breaking per-addon routing.
889
+ * Multi-addon manifest support (splitting the `ChildCapDescriptor[]` by addonId once the
890
+ * protocol carries addonId) would be needed here before enabling co-location post-Phase-F.
891
+ */
892
+ function buildChildUdsManifest(nodeId, childId, caps) {
893
+ // Collect unique system (non-device-scoped) cap names.
894
+ const systemCapNames = new Set();
895
+ for (const cap of caps) {
896
+ if (cap.deviceId === undefined) {
897
+ systemCapNames.add(cap.capName);
898
+ }
899
+ }
900
+ const addons = [
901
+ { addonId: childId, capabilities: [...systemCapNames] },
902
+ ];
903
+ return { nodeId, addons };
904
+ }