@camstack/server 1.2.718 → 1.2.720

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 (970) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/addon-root-inventory.js +1 -1
  3. package/dist/agent/addon-scan.js +11 -7
  4. package/dist/agent/agent-addon-updates.js +1 -1
  5. package/dist/agent/agent-cap-dispatch-service.js +1 -1
  6. package/dist/agent/agent-heap-watch.js +1 -1
  7. package/dist/agent/agent-http.js +1 -1
  8. package/dist/agent/agent-hub-addon-update.js +1 -1
  9. package/dist/agent/agent-hub-registration.js +1 -1
  10. package/dist/agent/agent-infra-capabilities.js +2 -2
  11. package/dist/agent/agent-mesh-gate.js +1 -1
  12. package/dist/agent/agent-node-certificates.js +1 -1
  13. package/dist/agent/agent-pairing-routes.js +1 -1
  14. package/dist/agent/agent-pairing-store.js +1 -1
  15. package/dist/agent/agent-service.js +6 -2
  16. package/dist/agent/agent-update-service.js +3 -1
  17. package/dist/agent/hub-membership-client.js +1 -1
  18. package/dist/agent/infra-boot-guard.js +2 -2
  19. package/dist/agent/main.js +9 -9
  20. package/dist/api/addon-upload.js +1 -1
  21. package/dist/api/core/addon-settings.router.js +1 -1
  22. package/dist/api/core/agent-pairing.router.js +1 -1
  23. package/dist/api/core/auth-device-cert.procedures.js +1 -1
  24. package/dist/api/core/cap-providers.js +6 -6
  25. package/dist/api/core/certificates.router.js +1 -1
  26. package/dist/api/core/lifecycle-job-runner.js +1 -1
  27. package/dist/api/core/logging-settings.js +1 -1
  28. package/dist/api/core/logs.router.js +2 -2
  29. package/dist/api/core/notifications.router.js +1 -1
  30. package/dist/api/core/preferences.router.js +1 -1
  31. package/dist/api/core/repl.router.js +1 -1
  32. package/dist/api/cors/cors-policy.js +1 -1
  33. package/dist/api/mesh-membership-routes.js +1 -1
  34. package/dist/api/model-distributor.js +1 -1
  35. package/dist/api/trpc/cap-route-error-formatter.js +1 -1
  36. package/dist/api/trpc/cap-router-runtime.js +2 -2
  37. package/dist/api/trpc/core-cap-bridge.js +1 -1
  38. package/dist/api/trpc/device-collection-dispatch.js +1 -1
  39. package/dist/api/trpc/generated-cap-routers.js +1 -1
  40. package/dist/api/trpc/principal-authorization.js +1 -1
  41. package/dist/api/trpc/principal-visibility.js +1 -1
  42. package/dist/api/trpc/scope-access.js +1 -1
  43. package/dist/api/trpc/trpc.context.js +1 -1
  44. package/dist/api/trpc/trpc.middleware.js +1 -1
  45. package/dist/api/trpc/trpc.router.js +3 -3
  46. package/dist/auth/auth-network-policy.js +1 -1
  47. package/dist/auth/client-address.js +1 -1
  48. package/dist/auth/hub-sessions.js +1 -1
  49. package/dist/auth/session-lifetimes.js +1 -1
  50. package/dist/auth/sso-finish-deps.js +1 -1
  51. package/dist/boot/boot-config.js +53 -133
  52. package/dist/boot/platform-keychain-key.js +1 -1
  53. package/dist/boot/post-boot.service.js +1 -1
  54. package/dist/bootstrap-packages.js +3 -3
  55. package/dist/core/addon/addon-call-gateway.js +1 -1
  56. package/dist/core/addon/addon-package.service.js +140 -21
  57. package/dist/core/addon/addon-registry.service.js +36 -32
  58. package/dist/core/addon/addon-requirements.js +81 -0
  59. package/dist/core/addon/hub-addon-api.js +1 -1
  60. package/dist/core/addon/installed-addon-versions.js +82 -0
  61. package/dist/core/addon/package-dir-utils.js +11 -1
  62. package/dist/core/addon/settings-door-wiring.js +1 -1
  63. package/dist/core/addon-bridge/addon-bridge.service.js +3 -3
  64. package/dist/core/addon-pages/addon-pages.service.js +1 -1
  65. package/dist/core/agent/agent-desired-set.js +1 -1
  66. package/dist/core/agent/agent-pairing-http.js +1 -1
  67. package/dist/core/agent/agent-registry.service.js +41 -7
  68. package/dist/core/agent/cluster-node-history-store.js +1 -1
  69. package/dist/core/agent/delivery-requirements.js +36 -0
  70. package/dist/core/agent/forgotten-node-revoker.js +1 -1
  71. package/dist/core/agent/node-removal-hooks.js +6 -2
  72. package/dist/core/auth/auth.service.js +1 -1
  73. package/dist/core/config/config.schema.js +2 -2
  74. package/dist/core/config/config.service.js +1 -1
  75. package/dist/core/events/event-bus.service.js +1 -1
  76. package/dist/core/feature/feature.service.js +1 -1
  77. package/dist/core/lifecycle/lifecycle-state-machine.js +2 -2
  78. package/dist/core/logging/log-history.js +1 -1
  79. package/dist/core/logging/log-ring-buffer.js +2 -2
  80. package/dist/core/logging/logging.service.js +2 -2
  81. package/dist/core/logging/scoped-logger.js +2 -2
  82. package/dist/core/moleculer/cap-route-authority.js +2 -2
  83. package/dist/core/moleculer/hub-mesh-guard.js +1 -1
  84. package/dist/core/moleculer/moleculer.service.js +1 -1
  85. package/dist/core/network/network-quality.service.js +1 -1
  86. package/dist/core/notification/notification-wrapper.service.js +1 -1
  87. package/dist/core/notification/toast-wrapper.service.js +1 -1
  88. package/dist/core/repl/repl-engine.service.js +1 -1
  89. package/dist/core/server-update/server-update.service.js +3 -0
  90. package/dist/core/server-update/system-ensure-prebuilds.js +3 -3
  91. package/dist/core/server-update/system-exec-npm.js +2 -2
  92. package/dist/core/storage/fs-storage-backend.js +2 -2
  93. package/dist/core/storage/storage-location-manager.js +2 -2
  94. package/dist/core/storage/storage.service.js +1 -1
  95. package/dist/framework-nodepath.js +14 -1
  96. package/dist/launcher.js +23 -23
  97. package/dist/legacy-package-names.js +15 -0
  98. package/dist/main.js +2 -2
  99. package/dist/manual-boot.js +4 -3
  100. package/dist/package-inventory.js +6 -3
  101. package/dist/server-root/index.js +182 -30
  102. package/dist/single-copy-cleanup-runner.js +3 -3
  103. package/dist/single-copy-cleanup.js +19 -14
  104. package/package.json +53 -19
  105. package/scripts/closure-postinstall.mjs +1 -1
  106. package/system/assets/addon-pages-aggregator/icon.svg +5 -0
  107. package/system/assets/addon-widgets-aggregator/icon.svg +6 -0
  108. package/system/assets/alert-center/icon.svg +5 -0
  109. package/system/assets/autotrack/icon.svg +5 -0
  110. package/system/assets/backup-orchestrator/icon.svg +5 -0
  111. package/system/assets/calendars/icon.svg +5 -0
  112. package/system/assets/camera-grid/icon.svg +10 -0
  113. package/system/assets/composer/icon.svg +7 -0
  114. package/system/assets/console-logging/icon.svg +4 -0
  115. package/system/assets/core-blocks/icon.svg +6 -0
  116. package/system/assets/device-history/icon.svg +4 -0
  117. package/system/assets/device-manager/icon.svg +6 -0
  118. package/system/assets/filesystem-storage/icon.svg +6 -0
  119. package/system/assets/hub-forwarder/icon.svg +7 -0
  120. package/system/assets/keychain/icon.svg +6 -0
  121. package/system/assets/liveness-monitor/icon.svg +4 -0
  122. package/system/assets/local-auth/icon.svg +5 -0
  123. package/system/assets/local-network/icon.svg +7 -0
  124. package/system/assets/loki-logging/icon.svg +7 -0
  125. package/system/assets/metrics-native/icon.svg +3 -0
  126. package/system/assets/platform-probe/icon.svg +5 -0
  127. package/system/assets/record-entries/icon.svg +8 -0
  128. package/system/assets/remote-access-orchestrator/icon.svg +5 -0
  129. package/system/assets/snapshot/icon.svg +4 -0
  130. package/system/assets/sqlite-settings/icon.svg +5 -0
  131. package/system/assets/storage-orchestrator/icon.svg +8 -0
  132. package/system/assets/system-config/icon.svg +4 -0
  133. package/system/assets/winston-logging/icon.svg +6 -0
  134. package/system/dist/addon/addon-api-factory.d.ts +35 -0
  135. package/system/dist/addon-routes/addon-route-registry.d.ts +37 -0
  136. package/system/dist/addon-runner.js +11894 -0
  137. package/system/dist/addon-runner.mjs +11840 -0
  138. package/system/dist/addon-utils.d.ts +23 -0
  139. package/system/dist/addon-utils.js +27 -0
  140. package/system/dist/addon-utils.mjs +3 -0
  141. package/system/dist/agent-https-BMbnmX5u.mjs +1042 -0
  142. package/system/dist/agent-https-DslXCDRW.js +1289 -0
  143. package/system/dist/amd-accelerators-CEuPFBBK.js +36 -0
  144. package/system/dist/amd-accelerators-U_RsoEDd.mjs +35 -0
  145. package/system/dist/auth/auth-audit-log.d.ts +45 -0
  146. package/system/dist/auth/auth-manager.d.ts +155 -0
  147. package/system/dist/auth/cidr.d.ts +22 -0
  148. package/system/dist/auth/device-ca-store.d.ts +57 -0
  149. package/system/dist/auth/device-ca.d.ts +65 -0
  150. package/system/dist/auth/device-credential-manager.d.ts +158 -0
  151. package/system/dist/auth/external-identity-manager.d.ts +42 -0
  152. package/system/dist/auth/jwt-signing-key.d.ts +42 -0
  153. package/system/dist/auth/legacy-token-tables.d.ts +16 -0
  154. package/system/dist/auth/login-session-manager.d.ts +140 -0
  155. package/system/dist/auth/origin.d.ts +34 -0
  156. package/system/dist/auth/parse-record.d.ts +18 -0
  157. package/system/dist/auth/scope-matcher.d.ts +8 -0
  158. package/system/dist/auth/session-revocation-bus.d.ts +32 -0
  159. package/system/dist/auth/token-expiry.d.ts +62 -0
  160. package/system/dist/auth/totp-manager.d.ts +107 -0
  161. package/system/dist/auth/user-management-internal.d.ts +90 -0
  162. package/system/dist/auth/user-manager.d.ts +69 -0
  163. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.d.ts +57 -0
  164. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +271 -0
  165. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +263 -0
  166. package/system/dist/builtins/addon-pages-aggregator/dedupe-pages.d.ts +24 -0
  167. package/system/dist/builtins/addon-pages-aggregator/index.d.ts +1 -0
  168. package/system/dist/builtins/addon-pages-aggregator/index.js +8 -0
  169. package/system/dist/builtins/addon-pages-aggregator/index.mjs +2 -0
  170. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.d.ts +57 -0
  171. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +257 -0
  172. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +249 -0
  173. package/system/dist/builtins/addon-widgets-aggregator/index.d.ts +1 -0
  174. package/system/dist/builtins/addon-widgets-aggregator/index.js +8 -0
  175. package/system/dist/builtins/addon-widgets-aggregator/index.mjs +2 -0
  176. package/system/dist/builtins/alerts/alert-episode-policy.d.ts +39 -0
  177. package/system/dist/builtins/alerts/alert-store.d.ts +32 -0
  178. package/system/dist/builtins/alerts/alerts.addon.d.ts +148 -0
  179. package/system/dist/builtins/alerts/alerts.addon.js +1566 -0
  180. package/system/dist/builtins/alerts/alerts.addon.mjs +1559 -0
  181. package/system/dist/builtins/alerts/device-label.d.ts +8 -0
  182. package/system/dist/builtins/alerts/emit-alert-policy.d.ts +15 -0
  183. package/system/dist/builtins/alerts/index.d.ts +1 -0
  184. package/system/dist/builtins/alerts/index.js +4 -0
  185. package/system/dist/builtins/alerts/index.mjs +2 -0
  186. package/system/dist/builtins/alerts/migration-alerts.d.ts +13 -0
  187. package/system/dist/builtins/alerts/prune-policy.d.ts +44 -0
  188. package/system/dist/builtins/alerts/record-kinds.d.ts +15 -0
  189. package/system/dist/builtins/alerts/runner-alert.d.ts +58 -0
  190. package/system/dist/builtins/autotrack/autotrack-cameras.d.ts +125 -0
  191. package/system/dist/builtins/autotrack/autotrack-config.d.ts +89 -0
  192. package/system/dist/builtins/autotrack/autotrack-decision.d.ts +86 -0
  193. package/system/dist/builtins/autotrack/autotrack-loop.d.ts +95 -0
  194. package/system/dist/builtins/autotrack/autotrack.addon.d.ts +108 -0
  195. package/system/dist/builtins/autotrack/frame-error.d.ts +50 -0
  196. package/system/dist/builtins/autotrack/frame-measurements.d.ts +97 -0
  197. package/system/dist/builtins/autotrack/index.d.ts +2 -0
  198. package/system/dist/builtins/autotrack/index.js +1018 -0
  199. package/system/dist/builtins/autotrack/index.mjs +1012 -0
  200. package/system/dist/builtins/autotrack/ptz-mirror.d.ts +54 -0
  201. package/system/dist/builtins/autotrack/target-selection.d.ts +46 -0
  202. package/system/dist/builtins/backup-orchestrator/backup-databases.d.ts +51 -0
  203. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.d.ts +291 -0
  204. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +3213 -0
  205. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +3204 -0
  206. package/system/dist/builtins/backup-orchestrator/cron-helpers.d.ts +23 -0
  207. package/system/dist/builtins/backup-orchestrator/destination-policy.d.ts +91 -0
  208. package/system/dist/builtins/backup-orchestrator/download-helpers.d.ts +12 -0
  209. package/system/dist/builtins/backup-orchestrator/encryption-key-store.d.ts +49 -0
  210. package/system/dist/builtins/backup-orchestrator/index.d.ts +2 -0
  211. package/system/dist/builtins/backup-orchestrator/index.js +8 -0
  212. package/system/dist/builtins/backup-orchestrator/index.mjs +2 -0
  213. package/system/dist/builtins/backup-orchestrator/manifest-store.d.ts +134 -0
  214. package/system/dist/builtins/backup-orchestrator/record-kinds.d.ts +56 -0
  215. package/system/dist/builtins/backup-orchestrator/restore-archive.d.ts +24 -0
  216. package/system/dist/builtins/backup-orchestrator/run-queue.d.ts +106 -0
  217. package/system/dist/builtins/backup-orchestrator/schedule-store.d.ts +59 -0
  218. package/system/dist/builtins/backup-orchestrator/seed-marker-store.d.ts +26 -0
  219. package/system/dist/builtins/backup-orchestrator/staging-paths.d.ts +36 -0
  220. package/system/dist/builtins/backup-orchestrator/write-targets.d.ts +63 -0
  221. package/system/dist/builtins/calendars/calendar-color.d.ts +9 -0
  222. package/system/dist/builtins/calendars/calendar-prefs-store.d.ts +34 -0
  223. package/system/dist/builtins/calendars/calendars.addon.d.ts +19 -0
  224. package/system/dist/builtins/calendars/calendars.addon.js +227 -0
  225. package/system/dist/builtins/calendars/calendars.addon.mjs +220 -0
  226. package/system/dist/builtins/calendars/index.d.ts +1 -0
  227. package/system/dist/builtins/calendars/index.js +8 -0
  228. package/system/dist/builtins/calendars/index.mjs +2 -0
  229. package/system/dist/builtins/calendars/record-kinds.d.ts +18 -0
  230. package/system/dist/builtins/camera-grid/acquire-retry.d.ts +30 -0
  231. package/system/dist/builtins/camera-grid/addon.d.ts +205 -0
  232. package/system/dist/builtins/camera-grid/flv-join.d.ts +40 -0
  233. package/system/dist/builtins/camera-grid/grid-activity-mirror.d.ts +42 -0
  234. package/system/dist/builtins/camera-grid/grid-activity.d.ts +91 -0
  235. package/system/dist/builtins/camera-grid/grid-camera-declarations.d.ts +59 -0
  236. package/system/dist/builtins/camera-grid/grid-camera-device.d.ts +68 -0
  237. package/system/dist/builtins/camera-grid/grid-canvas-derivation.d.ts +54 -0
  238. package/system/dist/builtins/camera-grid/grid-canvas-seed.d.ts +112 -0
  239. package/system/dist/builtins/camera-grid/grid-canvas.d.ts +85 -0
  240. package/system/dist/builtins/camera-grid/grid-child.d.ts +32 -0
  241. package/system/dist/builtins/camera-grid/grid-compositor-child.d.ts +3 -0
  242. package/system/dist/builtins/camera-grid/grid-compositor-invocation.d.ts +47 -0
  243. package/system/dist/builtins/camera-grid/grid-compositor.d.ts +54 -0
  244. package/system/dist/builtins/camera-grid/grid-detection-mapping.d.ts +61 -0
  245. package/system/dist/builtins/camera-grid/grid-device-settings.d.ts +35 -0
  246. package/system/dist/builtins/camera-grid/grid-filter-graph.d.ts +53 -0
  247. package/system/dist/builtins/camera-grid/grid-frame-sample.d.ts +53 -0
  248. package/system/dist/builtins/camera-grid/grid-instances.d.ts +22 -0
  249. package/system/dist/builtins/camera-grid/grid-last-frame-store.d.ts +58 -0
  250. package/system/dist/builtins/camera-grid/grid-layout-native-provider.d.ts +34 -0
  251. package/system/dist/builtins/camera-grid/grid-plan.d.ts +34 -0
  252. package/system/dist/builtins/camera-grid/grid-profiles.d.ts +104 -0
  253. package/system/dist/builtins/camera-grid/grid-row-normalization.d.ts +10 -0
  254. package/system/dist/builtins/camera-grid/grid-sentry-sources.d.ts +64 -0
  255. package/system/dist/builtins/camera-grid/grid-snapshot.d.ts +62 -0
  256. package/system/dist/builtins/camera-grid/grid-stream-descriptor.d.ts +53 -0
  257. package/system/dist/builtins/camera-grid/grid-stream-invocation.d.ts +44 -0
  258. package/system/dist/builtins/camera-grid/grid-stream-relay.d.ts +35 -0
  259. package/system/dist/builtins/camera-grid/grid-stream-session.d.ts +143 -0
  260. package/system/dist/builtins/camera-grid/grid-tile-feed.d.ts +50 -0
  261. package/system/dist/builtins/camera-grid/grid-tile-plan.d.ts +66 -0
  262. package/system/dist/builtins/camera-grid/grid-wire-format.d.ts +30 -0
  263. package/system/dist/builtins/camera-grid/index.d.ts +45 -0
  264. package/system/dist/builtins/camera-grid/index.js +3994 -0
  265. package/system/dist/builtins/camera-grid/index.mjs +3961 -0
  266. package/system/dist/builtins/camera-grid/silence-analysis.d.ts +37 -0
  267. package/system/dist/builtins/cluster-agent/record-kinds.d.ts +49 -0
  268. package/system/dist/builtins/composer/actuator-dispatch.d.ts +13 -0
  269. package/system/dist/builtins/composer/actuator-groups.d.ts +68 -0
  270. package/system/dist/builtins/composer/actuator-invoke.d.ts +32 -0
  271. package/system/dist/builtins/composer/claim-gate.d.ts +59 -0
  272. package/system/dist/builtins/composer/composed-device-set.d.ts +52 -0
  273. package/system/dist/builtins/composer/composed-device.d.ts +57 -0
  274. package/system/dist/builtins/composer/composer-apply-waits.d.ts +28 -0
  275. package/system/dist/builtins/composer/composer-grafts.d.ts +73 -0
  276. package/system/dist/builtins/composer/composer-live-set.d.ts +30 -0
  277. package/system/dist/builtins/composer/composer-plan.d.ts +112 -0
  278. package/system/dist/builtins/composer/composer-runtime-factory.d.ts +30 -0
  279. package/system/dist/builtins/composer/composer-seeds.d.ts +28 -0
  280. package/system/dist/builtins/composer/composer-verdict.d.ts +33 -0
  281. package/system/dist/builtins/composer/composer.addon.d.ts +26 -0
  282. package/system/dist/builtins/composer/composer.addon.js +6229 -0
  283. package/system/dist/builtins/composer/composer.addon.mjs +6223 -0
  284. package/system/dist/builtins/composer/composer.d.ts +208 -0
  285. package/system/dist/builtins/composer/composition-declarations.d.ts +64 -0
  286. package/system/dist/builtins/composer/composition-evaluation.d.ts +53 -0
  287. package/system/dist/builtins/composer/composition-runtime.d.ts +203 -0
  288. package/system/dist/builtins/composer/composition-target.d.ts +60 -0
  289. package/system/dist/builtins/composer/confirmed-seed.d.ts +44 -0
  290. package/system/dist/builtins/composer/deadline-timer.d.ts +18 -0
  291. package/system/dist/builtins/composer/existing-target.d.ts +131 -0
  292. package/system/dist/builtins/composer/field-record.d.ts +64 -0
  293. package/system/dist/builtins/composer/forward-commands.d.ts +61 -0
  294. package/system/dist/builtins/composer/graft-host.d.ts +71 -0
  295. package/system/dist/builtins/composer/held-claims.d.ts +29 -0
  296. package/system/dist/builtins/composer/history-helpers.d.ts +67 -0
  297. package/system/dist/builtins/composer/index.d.ts +1 -0
  298. package/system/dist/builtins/composer/index.js +8 -0
  299. package/system/dist/builtins/composer/index.mjs +2 -0
  300. package/system/dist/builtins/composer/math-quantity.d.ts +20 -0
  301. package/system/dist/builtins/composer/own-field-reads.d.ts +30 -0
  302. package/system/dist/builtins/composer/owned-fields-target.d.ts +95 -0
  303. package/system/dist/builtins/composer/pulse-seed-resolve.d.ts +59 -0
  304. package/system/dist/builtins/composer/pulse-seed.d.ts +75 -0
  305. package/system/dist/builtins/composer/slice-assembler.d.ts +26 -0
  306. package/system/dist/builtins/composer/source-readings.d.ts +128 -0
  307. package/system/dist/builtins/composer/source-tracker.d.ts +135 -0
  308. package/system/dist/builtins/console-logging/console-destination.d.ts +19 -0
  309. package/system/dist/builtins/console-logging/console-logging.addon.d.ts +26 -0
  310. package/system/dist/builtins/console-logging/index.d.ts +3 -0
  311. package/system/dist/builtins/console-logging/index.js +108 -0
  312. package/system/dist/builtins/console-logging/index.mjs +99 -0
  313. package/system/dist/builtins/core-blocks/actions-service.d.ts +113 -0
  314. package/system/dist/builtins/core-blocks/actions-store.d.ts +32 -0
  315. package/system/dist/builtins/core-blocks/actions-wiring.d.ts +32 -0
  316. package/system/dist/builtins/core-blocks/block-package.d.ts +54 -0
  317. package/system/dist/builtins/core-blocks/block-settings-store.d.ts +93 -0
  318. package/system/dist/builtins/core-blocks/block-supervisor.d.ts +176 -0
  319. package/system/dist/builtins/core-blocks/block-type-defs.d.ts +29 -0
  320. package/system/dist/builtins/core-blocks/blocks-integration.d.ts +89 -0
  321. package/system/dist/builtins/core-blocks/compile-block.d.ts +52 -0
  322. package/system/dist/builtins/core-blocks/composition-api.d.ts +50 -0
  323. package/system/dist/builtins/core-blocks/composition-peers.d.ts +31 -0
  324. package/system/dist/builtins/core-blocks/composition-sources.d.ts +40 -0
  325. package/system/dist/builtins/core-blocks/core-block-store.d.ts +120 -0
  326. package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +108 -0
  327. package/system/dist/builtins/core-blocks/core-blocks.addon.js +6374 -0
  328. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +6355 -0
  329. package/system/dist/builtins/core-blocks/extract-settings-schema.d.ts +6 -0
  330. package/system/dist/builtins/core-blocks/index.d.ts +8 -0
  331. package/system/dist/builtins/core-blocks/index.js +21 -0
  332. package/system/dist/builtins/core-blocks/index.mjs +2 -0
  333. package/system/dist/builtins/core-blocks/lock-door-gate.d.ts +31 -0
  334. package/system/dist/builtins/core-blocks/lock-door-sensor.d.ts +35 -0
  335. package/system/dist/builtins/core-blocks/power-source-service.d.ts +70 -0
  336. package/system/dist/builtins/core-blocks/record-kinds.d.ts +83 -0
  337. package/system/dist/builtins/core-blocks/remote-call-redirect.d.ts +23 -0
  338. package/system/dist/builtins/core-blocks/remote-components-service.d.ts +10 -0
  339. package/system/dist/builtins/core-blocks/remote-service.d.ts +85 -0
  340. package/system/dist/builtins/core-blocks/remote-wiring.d.ts +49 -0
  341. package/system/dist/builtins/core-blocks/runs-api.d.ts +30 -0
  342. package/system/dist/builtins/core-blocks/runs-ledger.d.ts +64 -0
  343. package/system/dist/builtins/core-blocks/scheduler/scheduler-engine.d.ts +91 -0
  344. package/system/dist/builtins/core-blocks/scheduler/scheduler-holds.d.ts +54 -0
  345. package/system/dist/builtins/core-blocks/scheduler/scheduler-service.d.ts +76 -0
  346. package/system/dist/builtins/core-blocks/scheduler/scheduler-store.d.ts +23 -0
  347. package/system/dist/builtins/core-blocks/scheduler/scheduler-timeline.d.ts +53 -0
  348. package/system/dist/builtins/core-blocks/scheduler/scheduler-trace.d.ts +17 -0
  349. package/system/dist/builtins/core-blocks/scheduler/scheduler-types.d.ts +20 -0
  350. package/system/dist/builtins/core-blocks/scheduler/scheduler-wiring.d.ts +41 -0
  351. package/system/dist/builtins/core-blocks/templates-service.d.ts +24 -0
  352. package/system/dist/builtins/device-history/capture/capture-engine.d.ts +113 -0
  353. package/system/dist/builtins/device-history/capture/capture-filter.d.ts +37 -0
  354. package/system/dist/builtins/device-history/capture/device-directory.d.ts +47 -0
  355. package/system/dist/builtins/device-history/capture/field-path.d.ts +10 -0
  356. package/system/dist/builtins/device-history/capture/point-writer.d.ts +63 -0
  357. package/system/dist/builtins/device-history/device-history.addon.d.ts +53 -0
  358. package/system/dist/builtins/device-history/device-history.addon.js +2885 -0
  359. package/system/dist/builtins/device-history/device-history.addon.mjs +2878 -0
  360. package/system/dist/builtins/device-history/index.d.ts +3 -0
  361. package/system/dist/builtins/device-history/ingest/producer-ingest.d.ts +99 -0
  362. package/system/dist/builtins/device-history/query/history-query.d.ts +116 -0
  363. package/system/dist/builtins/device-history/query/point-shape.d.ts +31 -0
  364. package/system/dist/builtins/device-history/retention/departure-tracker.d.ts +33 -0
  365. package/system/dist/builtins/device-history/retention/orphans.d.ts +50 -0
  366. package/system/dist/builtins/device-history/retention/retention.d.ts +74 -0
  367. package/system/dist/builtins/device-history/rollup/rollup-engine.d.ts +74 -0
  368. package/system/dist/builtins/device-history/rollup/rollup-math.d.ts +50 -0
  369. package/system/dist/builtins/device-history/runtime/history-runtime.d.ts +118 -0
  370. package/system/dist/builtins/device-history/status/counters.d.ts +55 -0
  371. package/system/dist/builtins/device-history/store/history-door.d.ts +7 -0
  372. package/system/dist/builtins/device-history/store/history-schema.d.ts +28 -0
  373. package/system/dist/builtins/device-history/store/history-store.d.ts +109 -0
  374. package/system/dist/builtins/device-history/store/row-readers.d.ts +11 -0
  375. package/system/dist/builtins/device-history/store/series-registry.d.ts +64 -0
  376. package/system/dist/builtins/device-history/store/series-scale.d.ts +37 -0
  377. package/system/dist/builtins/device-history/time/bucket-time.d.ts +25 -0
  378. package/system/dist/builtins/device-manager/adoption-job-engine.d.ts +153 -0
  379. package/system/dist/builtins/device-manager/claimed-status-overlay.d.ts +45 -0
  380. package/system/dist/builtins/device-manager/contribution-cache.d.ts +85 -0
  381. package/system/dist/builtins/device-manager/day-night-config-schema.d.ts +30 -0
  382. package/system/dist/builtins/device-manager/device-aggregation-merge.d.ts +22 -0
  383. package/system/dist/builtins/device-manager/device-aggregation.d.ts +335 -0
  384. package/system/dist/builtins/device-manager/device-bindings-store.d.ts +278 -0
  385. package/system/dist/builtins/device-manager/device-config-contribution.d.ts +45 -0
  386. package/system/dist/builtins/device-manager/device-config-secrets.d.ts +40 -0
  387. package/system/dist/builtins/device-manager/device-event-propagator.d.ts +26 -0
  388. package/system/dist/builtins/device-manager/device-extension-linked-slot.d.ts +27 -0
  389. package/system/dist/builtins/device-manager/device-form-secrets.d.ts +25 -0
  390. package/system/dist/builtins/device-manager/device-linked-devices.d.ts +201 -0
  391. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +234 -0
  392. package/system/dist/builtins/device-manager/device-manager.addon.js +11369 -0
  393. package/system/dist/builtins/device-manager/device-manager.addon.mjs +11358 -0
  394. package/system/dist/builtins/device-manager/device-meta-actions.d.ts +338 -0
  395. package/system/dist/builtins/device-manager/device-meta-store.d.ts +103 -0
  396. package/system/dist/builtins/device-manager/device-meta-types.d.ts +277 -0
  397. package/system/dist/builtins/device-manager/device-online-fallback.d.ts +35 -0
  398. package/system/dist/builtins/device-manager/device-projection.d.ts +71 -0
  399. package/system/dist/builtins/device-manager/device-provider-context.d.ts +126 -0
  400. package/system/dist/builtins/device-manager/device-queries.d.ts +67 -0
  401. package/system/dist/builtins/device-manager/device-removal-hooks.d.ts +92 -0
  402. package/system/dist/builtins/device-manager/device-row-store.d.ts +449 -0
  403. package/system/dist/builtins/device-manager/device-source-activation.d.ts +103 -0
  404. package/system/dist/builtins/device-manager/device-state-claim-views.d.ts +92 -0
  405. package/system/dist/builtins/device-manager/device-state-claims.d.ts +66 -0
  406. package/system/dist/builtins/device-manager/device-state-mirror.d.ts +267 -0
  407. package/system/dist/builtins/device-manager/device-sync-resolvers.d.ts +30 -0
  408. package/system/dist/builtins/device-manager/device-tombstone-store.d.ts +29 -0
  409. package/system/dist/builtins/device-manager/discovery-orchestrator.d.ts +45 -0
  410. package/system/dist/builtins/device-manager/field-claims-index.d.ts +96 -0
  411. package/system/dist/builtins/device-manager/field-ownership.d.ts +71 -0
  412. package/system/dist/builtins/device-manager/fleet-read-census.d.ts +104 -0
  413. package/system/dist/builtins/device-manager/image-settings-config-schema.d.ts +22 -0
  414. package/system/dist/builtins/device-manager/index.d.ts +2 -0
  415. package/system/dist/builtins/device-manager/index.js +8 -0
  416. package/system/dist/builtins/device-manager/index.mjs +2 -0
  417. package/system/dist/builtins/device-manager/linked-devices-manual-backfill.d.ts +27 -0
  418. package/system/dist/builtins/device-manager/location-alignment.d.ts +61 -0
  419. package/system/dist/builtins/device-manager/migrate-device.d.ts +192 -0
  420. package/system/dist/builtins/device-manager/migrate-guard.d.ts +78 -0
  421. package/system/dist/builtins/device-manager/migrate-hardware-state.d.ts +79 -0
  422. package/system/dist/builtins/device-manager/migrate-reload.d.ts +46 -0
  423. package/system/dist/builtins/device-manager/migration-refused.d.ts +23 -0
  424. package/system/dist/builtins/device-manager/mirror-row-writer.d.ts +222 -0
  425. package/system/dist/builtins/device-manager/record-kinds.d.ts +14 -0
  426. package/system/dist/builtins/device-manager/recording-onboard-config-schema.d.ts +65 -0
  427. package/system/dist/builtins/device-manager/removal-cleanup.d.ts +50 -0
  428. package/system/dist/builtins/device-manager/removal-fence.d.ts +58 -0
  429. package/system/dist/builtins/device-manager/running-flip.d.ts +11 -0
  430. package/system/dist/builtins/device-manager/runtime-state-persist-gate.d.ts +64 -0
  431. package/system/dist/builtins/device-manager/secret-config-paths.d.ts +24 -0
  432. package/system/dist/builtins/device-manager/stale-wrapper-activations.d.ts +59 -0
  433. package/system/dist/builtins/device-manager/write-lock.d.ts +17 -0
  434. package/system/dist/builtins/hub-forwarder/hub-forwarder-destination.d.ts +43 -0
  435. package/system/dist/builtins/hub-forwarder/hub-forwarder.addon.d.ts +16 -0
  436. package/system/dist/builtins/hub-forwarder/index.d.ts +3 -0
  437. package/system/dist/builtins/hub-forwarder/index.js +151 -0
  438. package/system/dist/builtins/hub-forwarder/index.mjs +142 -0
  439. package/system/dist/builtins/keychain/index.d.ts +1 -0
  440. package/system/dist/builtins/keychain/index.js +2059 -0
  441. package/system/dist/builtins/keychain/index.mjs +2052 -0
  442. package/system/dist/builtins/keychain/key-sources.d.ts +37 -0
  443. package/system/dist/builtins/keychain/keychain-crypto.d.ts +28 -0
  444. package/system/dist/builtins/keychain/keychain-reset-trigger.d.ts +25 -0
  445. package/system/dist/builtins/keychain/keychain-service.d.ts +180 -0
  446. package/system/dist/builtins/keychain/keychain-store.d.ts +125 -0
  447. package/system/dist/builtins/keychain/keychain-usage.d.ts +17 -0
  448. package/system/dist/builtins/keychain/keychain.addon.d.ts +36 -0
  449. package/system/dist/builtins/keychain/platform-key-source.d.ts +24 -0
  450. package/system/dist/builtins/keychain/record-kinds.d.ts +16 -0
  451. package/system/dist/builtins/keychain/system-held-secrets.d.ts +25 -0
  452. package/system/dist/builtins/liveness-monitor/index.d.ts +2 -0
  453. package/system/dist/builtins/liveness-monitor/index.js +6 -0
  454. package/system/dist/builtins/liveness-monitor/index.mjs +2 -0
  455. package/system/dist/builtins/liveness-monitor/liveness-checks.d.ts +85 -0
  456. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.d.ts +46 -0
  457. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +443 -0
  458. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +437 -0
  459. package/system/dist/builtins/liveness-monitor/liveness-reporter.d.ts +28 -0
  460. package/system/dist/builtins/liveness-monitor/storage-root-access.d.ts +53 -0
  461. package/system/dist/builtins/local-auth/admin-account-boot.d.ts +27 -0
  462. package/system/dist/builtins/local-auth/auth-config-reader.d.ts +39 -0
  463. package/system/dist/builtins/local-auth/auth-schema.d.ts +93 -0
  464. package/system/dist/builtins/local-auth/index.d.ts +1 -0
  465. package/system/dist/builtins/local-auth/index.js +4 -0
  466. package/system/dist/builtins/local-auth/index.mjs +2 -0
  467. package/system/dist/builtins/local-auth/jwt-signing-key-keeper.d.ts +30 -0
  468. package/system/dist/builtins/local-auth/local-auth.addon.d.ts +48 -0
  469. package/system/dist/builtins/local-auth/local-auth.addon.js +12418 -0
  470. package/system/dist/builtins/local-auth/local-auth.addon.mjs +12388 -0
  471. package/system/dist/builtins/local-auth/oauth-grants.d.ts +71 -0
  472. package/system/dist/builtins/local-auth/oauth-session-manager.d.ts +44 -0
  473. package/system/dist/builtins/local-auth/person-scopes.d.ts +7 -0
  474. package/system/dist/builtins/local-auth/preferences-record-kinds.d.ts +27 -0
  475. package/system/dist/builtins/local-auth/record-kinds.d.ts +137 -0
  476. package/system/dist/builtins/local-auth/user-preferences-store.d.ts +56 -0
  477. package/system/dist/builtins/local-network/address-book.d.ts +128 -0
  478. package/system/dist/builtins/local-network/agent-mdns.d.ts +56 -0
  479. package/system/dist/builtins/local-network/hub-mdns-ciao.d.ts +7 -0
  480. package/system/dist/builtins/local-network/hub-mdns.d.ts +58 -0
  481. package/system/dist/builtins/local-network/index.d.ts +1 -0
  482. package/system/dist/builtins/local-network/index.js +10 -0
  483. package/system/dist/builtins/local-network/index.mjs +2 -0
  484. package/system/dist/builtins/local-network/ipv6-lan.d.ts +21 -0
  485. package/system/dist/builtins/local-network/local-hostname.d.ts +15 -0
  486. package/system/dist/builtins/local-network/local-network.addon.d.ts +334 -0
  487. package/system/dist/builtins/local-network/local-network.addon.js +2487 -0
  488. package/system/dist/builtins/local-network/local-network.addon.mjs +2466 -0
  489. package/system/dist/builtins/local-network/scan/dns-wire.d.ts +17 -0
  490. package/system/dist/builtins/local-network/scan/scan-engine.d.ts +31 -0
  491. package/system/dist/builtins/local-network/scan/scan-io-node.d.ts +2 -0
  492. package/system/dist/builtins/local-network/scan/scan-io.d.ts +56 -0
  493. package/system/dist/builtins/local-network/scan/subnets.d.ts +57 -0
  494. package/system/dist/builtins/loki-logging/index.d.ts +4 -0
  495. package/system/dist/builtins/loki-logging/index.js +915 -0
  496. package/system/dist/builtins/loki-logging/index.mjs +901 -0
  497. package/system/dist/builtins/loki-logging/loki-destination.d.ts +142 -0
  498. package/system/dist/builtins/loki-logging/loki-logging.addon.d.ts +66 -0
  499. package/system/dist/builtins/loki-logging/loki-payload.d.ts +100 -0
  500. package/system/dist/builtins/loki-logging/loki-read.d.ts +51 -0
  501. package/system/dist/builtins/loki-logging/retire-enabled-flag.d.ts +48 -0
  502. package/system/dist/builtins/native-metrics/cgroup-memory.d.ts +240 -0
  503. package/system/dist/builtins/native-metrics/cgroup-pids.d.ts +159 -0
  504. package/system/dist/builtins/native-metrics/container-memory-ring.d.ts +18 -0
  505. package/system/dist/builtins/native-metrics/darwin-memory.d.ts +26 -0
  506. package/system/dist/builtins/native-metrics/gpu-probe.d.ts +18 -0
  507. package/system/dist/builtins/native-metrics/index.d.ts +2 -0
  508. package/system/dist/builtins/native-metrics/load-series-config.d.ts +83 -0
  509. package/system/dist/builtins/native-metrics/load-series-reader.d.ts +63 -0
  510. package/system/dist/builtins/native-metrics/load-series-types.d.ts +14 -0
  511. package/system/dist/builtins/native-metrics/native-metrics-provider.d.ts +49 -0
  512. package/system/dist/builtins/native-metrics/native-metrics.addon.d.ts +233 -0
  513. package/system/dist/builtins/native-metrics/native-metrics.addon.js +3116 -0
  514. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +3106 -0
  515. package/system/dist/builtins/native-metrics/node-load-ring.d.ts +212 -0
  516. package/system/dist/builtins/native-metrics/node-metrics-history-recorder.d.ts +155 -0
  517. package/system/dist/builtins/native-metrics/proc-process-table.d.ts +25 -0
  518. package/system/dist/builtins/native-metrics/process-classification.d.ts +110 -0
  519. package/system/dist/builtins/native-metrics/thread-cpu-sampler.d.ts +116 -0
  520. package/system/dist/builtins/platform-probe/accelerator-facts-probe.d.ts +24 -0
  521. package/system/dist/builtins/platform-probe/accelerator-reprobe.d.ts +23 -0
  522. package/system/dist/builtins/platform-probe/amd-accelerators.d.ts +15 -0
  523. package/system/dist/builtins/platform-probe/amd-npu.d.ts +35 -0
  524. package/system/dist/builtins/platform-probe/coral-accelerators.d.ts +87 -0
  525. package/system/dist/builtins/platform-probe/index.d.ts +57 -0
  526. package/system/dist/builtins/platform-probe/index.js +1151 -0
  527. package/system/dist/builtins/platform-probe/index.mjs +1140 -0
  528. package/system/dist/builtins/platform-probe/inference-config-resolver.d.ts +29 -0
  529. package/system/dist/builtins/platform-probe/intel-accelerators.d.ts +14 -0
  530. package/system/dist/builtins/platform-probe/intel-npu.d.ts +38 -0
  531. package/system/dist/builtins/platform-probe/platform-scorer.d.ts +66 -0
  532. package/system/dist/builtins/platform-probe/runtime-packages.d.ts +6 -0
  533. package/system/dist/builtins/platform-probe/windows-hardware.d.ts +77 -0
  534. package/system/dist/builtins/record-entries/entries-service.d.ts +42 -0
  535. package/system/dist/builtins/record-entries/index.d.ts +1 -0
  536. package/system/dist/builtins/record-entries/index.js +162 -0
  537. package/system/dist/builtins/record-entries/index.mjs +156 -0
  538. package/system/dist/builtins/record-entries/record-entries.addon.d.ts +13 -0
  539. package/system/dist/builtins/records-isolated.d.ts +10 -0
  540. package/system/dist/builtins/remote-access-orchestrator/enabled-providers-reconcile.d.ts +96 -0
  541. package/system/dist/builtins/remote-access-orchestrator/index.d.ts +1 -0
  542. package/system/dist/builtins/remote-access-orchestrator/index.js +8 -0
  543. package/system/dist/builtins/remote-access-orchestrator/index.mjs +2 -0
  544. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.d.ts +71 -0
  545. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +214 -0
  546. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +208 -0
  547. package/system/dist/builtins/shared/device-state-changed.d.ts +16 -0
  548. package/system/dist/builtins/shared/settle-sources.d.ts +22 -0
  549. package/system/dist/builtins/snapshot/index.d.ts +2 -0
  550. package/system/dist/builtins/snapshot/index.js +2720 -0
  551. package/system/dist/builtins/snapshot/index.mjs +2713 -0
  552. package/system/dist/builtins/snapshot/snapshot-cache.d.ts +108 -0
  553. package/system/dist/builtins/snapshot/snapshot-coalescing.d.ts +135 -0
  554. package/system/dist/builtins/snapshot/snapshot-courtesy.d.ts +68 -0
  555. package/system/dist/builtins/snapshot/snapshot-durable-store.d.ts +36 -0
  556. package/system/dist/builtins/snapshot/snapshot-fatigue.d.ts +41 -0
  557. package/system/dist/builtins/snapshot/snapshot-grab-pick.d.ts +20 -0
  558. package/system/dist/builtins/snapshot/snapshot-link-url.d.ts +66 -0
  559. package/system/dist/builtins/snapshot/snapshot-media-handler.d.ts +121 -0
  560. package/system/dist/builtins/snapshot/snapshot-resize.d.ts +75 -0
  561. package/system/dist/builtins/snapshot/snapshot.addon.d.ts +581 -0
  562. package/system/dist/builtins/sqlite-storage/analyze-stats.d.ts +83 -0
  563. package/system/dist/builtins/sqlite-storage/config-store.d.ts +8 -0
  564. package/system/dist/builtins/sqlite-storage/database-snapshot-provider.d.ts +18 -0
  565. package/system/dist/builtins/sqlite-storage/device-store.d.ts +23 -0
  566. package/system/dist/builtins/sqlite-storage/file-host-client.d.ts +75 -0
  567. package/system/dist/builtins/sqlite-storage/file-host-handlers.d.ts +27 -0
  568. package/system/dist/builtins/sqlite-storage/file-host-protocol.d.ts +167 -0
  569. package/system/dist/builtins/sqlite-storage/file-host-worker.d.ts +1 -0
  570. package/system/dist/builtins/sqlite-storage/filesystem-browse-provider.d.ts +25 -0
  571. package/system/dist/builtins/sqlite-storage/filesystem-storage-provider.d.ts +83 -0
  572. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.d.ts +33 -0
  573. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +419 -0
  574. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +411 -0
  575. package/system/dist/builtins/sqlite-storage/filter-compiler.d.ts +126 -0
  576. package/system/dist/builtins/sqlite-storage/index.d.ts +12 -0
  577. package/system/dist/builtins/sqlite-storage/index.js +82 -0
  578. package/system/dist/builtins/sqlite-storage/index.mjs +50 -0
  579. package/system/dist/builtins/sqlite-storage/integration-record-kinds.d.ts +31 -0
  580. package/system/dist/builtins/sqlite-storage/integration-registry.d.ts +34 -0
  581. package/system/dist/builtins/sqlite-storage/migrations/migration-actions.d.ts +12 -0
  582. package/system/dist/builtins/sqlite-storage/migrations/migration-edits.d.ts +35 -0
  583. package/system/dist/builtins/sqlite-storage/migrations/migration-engine.d.ts +125 -0
  584. package/system/dist/builtins/sqlite-storage/migrations/migration-hold.d.ts +23 -0
  585. package/system/dist/builtins/sqlite-storage/migrations/migration-pass.d.ts +48 -0
  586. package/system/dist/builtins/sqlite-storage/migrations/migration-restore-marker.d.ts +3 -0
  587. package/system/dist/builtins/sqlite-storage/migrations/migration-types.d.ts +151 -0
  588. package/system/dist/builtins/sqlite-storage/migrations/migrations-provider.d.ts +61 -0
  589. package/system/dist/builtins/sqlite-storage/owned-sqlite-file.d.ts +173 -0
  590. package/system/dist/builtins/sqlite-storage/path-guard.d.ts +11 -0
  591. package/system/dist/builtins/sqlite-storage/placement-errors.d.ts +60 -0
  592. package/system/dist/builtins/sqlite-storage/placement-router.d.ts +85 -0
  593. package/system/dist/builtins/sqlite-storage/prefix-range.d.ts +50 -0
  594. package/system/dist/builtins/sqlite-storage/query-bounds.d.ts +110 -0
  595. package/system/dist/builtins/sqlite-storage/query-profiler.d.ts +242 -0
  596. package/system/dist/builtins/sqlite-storage/records/records-catalog.d.ts +27 -0
  597. package/system/dist/builtins/sqlite-storage/records/records-engine-types.d.ts +48 -0
  598. package/system/dist/builtins/sqlite-storage/records/records-engine.d.ts +115 -0
  599. package/system/dist/builtins/sqlite-storage/records/records-explain.d.ts +18 -0
  600. package/system/dist/builtins/sqlite-storage/records/records-plan.d.ts +95 -0
  601. package/system/dist/builtins/sqlite-storage/records/records-probe.d.ts +33 -0
  602. package/system/dist/builtins/sqlite-storage/records/records-provider.d.ts +72 -0
  603. package/system/dist/builtins/sqlite-storage/records/records-rows.d.ts +46 -0
  604. package/system/dist/builtins/sqlite-storage/records/records-sql.d.ts +39 -0
  605. package/system/dist/builtins/sqlite-storage/retired-settings-keys.d.ts +276 -0
  606. package/system/dist/builtins/sqlite-storage/shm-lock-canary.d.ts +60 -0
  607. package/system/dist/builtins/sqlite-storage/sqlite-pragmas.d.ts +191 -0
  608. package/system/dist/builtins/sqlite-storage/sqlite-settings-backend.d.ts +583 -0
  609. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.d.ts +52 -0
  610. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +2960 -0
  611. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +2952 -0
  612. package/system/dist/builtins/sqlite-storage/sqlite-snapshot-protocol.d.ts +54 -0
  613. package/system/dist/builtins/sqlite-storage/sqlite-snapshot-worker.d.ts +33 -0
  614. package/system/dist/builtins/sqlite-storage/sqlite-snapshotter.d.ts +118 -0
  615. package/system/dist/builtins/sqlite-storage/stale-data/stale-data-audit.d.ts +81 -0
  616. package/system/dist/builtins/sqlite-storage/stale-data/stale-data-ports.d.ts +17 -0
  617. package/system/dist/builtins/sqlite-storage/statement-shape.d.ts +64 -0
  618. package/system/dist/builtins/sqlite-storage/storage-admin-provider.d.ts +33 -0
  619. package/system/dist/builtins/sqlite-storage/table-sizes.d.ts +95 -0
  620. package/system/dist/builtins/sqlite-storage/vector-index-shared.d.ts +81 -0
  621. package/system/dist/builtins/sqlite-storage/vector-index-vec.d.ts +143 -0
  622. package/system/dist/builtins/sqlite-storage/vector-provider.d.ts +30 -0
  623. package/system/dist/builtins/sqlite-storage/wal-checkpoint-policy.d.ts +196 -0
  624. package/system/dist/builtins/sqlite-storage/wal-checkpoint-worker.d.ts +1 -0
  625. package/system/dist/builtins/sqlite-storage/wal-checkpointer.d.ts +76 -0
  626. package/system/dist/builtins/sqlite-storage/wal-maintenance.d.ts +130 -0
  627. package/system/dist/builtins/storage-orchestrator/access-guards.d.ts +43 -0
  628. package/system/dist/builtins/storage-orchestrator/data-store-dispatch.d.ts +39 -0
  629. package/system/dist/builtins/storage-orchestrator/drain-ratchet.d.ts +104 -0
  630. package/system/dist/builtins/storage-orchestrator/drain-state-store.d.ts +26 -0
  631. package/system/dist/builtins/storage-orchestrator/hub-settings-forward.d.ts +128 -0
  632. package/system/dist/builtins/storage-orchestrator/index.d.ts +7 -0
  633. package/system/dist/builtins/storage-orchestrator/index.js +11 -0
  634. package/system/dist/builtins/storage-orchestrator/index.mjs +2 -0
  635. package/system/dist/builtins/storage-orchestrator/location-class-paths.d.ts +13 -0
  636. package/system/dist/builtins/storage-orchestrator/location-history-recorder.d.ts +76 -0
  637. package/system/dist/builtins/storage-orchestrator/location-occupancy-slice.d.ts +71 -0
  638. package/system/dist/builtins/storage-orchestrator/location-occupancy.d.ts +19 -0
  639. package/system/dist/builtins/storage-orchestrator/location-protection.d.ts +20 -0
  640. package/system/dist/builtins/storage-orchestrator/location-repoint-move.d.ts +57 -0
  641. package/system/dist/builtins/storage-orchestrator/location-repointer.d.ts +97 -0
  642. package/system/dist/builtins/storage-orchestrator/location-root-collision.d.ts +80 -0
  643. package/system/dist/builtins/storage-orchestrator/location-secrets.d.ts +114 -0
  644. package/system/dist/builtins/storage-orchestrator/location-store.d.ts +82 -0
  645. package/system/dist/builtins/storage-orchestrator/location-volume-capacity.d.ts +58 -0
  646. package/system/dist/builtins/storage-orchestrator/provider-discovery.d.ts +24 -0
  647. package/system/dist/builtins/storage-orchestrator/record-kinds.d.ts +43 -0
  648. package/system/dist/builtins/storage-orchestrator/storage-cleanup-coordinator.d.ts +68 -0
  649. package/system/dist/builtins/storage-orchestrator/storage-location-band-monitor.d.ts +77 -0
  650. package/system/dist/builtins/storage-orchestrator/storage-migration-coordinator.d.ts +241 -0
  651. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.d.ts +318 -0
  652. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +5280 -0
  653. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +5264 -0
  654. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.service.d.ts +475 -0
  655. package/system/dist/builtins/storage-orchestrator/storage-pressure-manager.d.ts +115 -0
  656. package/system/dist/builtins/system-backup/backup-encryption.d.ts +94 -0
  657. package/system/dist/builtins/system-backup/system-backup.service.d.ts +308 -0
  658. package/system/dist/builtins/system-config/index.d.ts +2 -0
  659. package/system/dist/builtins/system-config/index.js +10 -0
  660. package/system/dist/builtins/system-config/index.mjs +2 -0
  661. package/system/dist/builtins/system-config/mesh-actions.d.ts +3 -0
  662. package/system/dist/builtins/system-config/record-kinds.d.ts +32 -0
  663. package/system/dist/builtins/system-config/system-config.addon.d.ts +56 -0
  664. package/system/dist/builtins/system-config/system-config.addon.js +89334 -0
  665. package/system/dist/builtins/system-config/system-config.addon.mjs +89233 -0
  666. package/system/dist/builtins/winston-logging/index.d.ts +3 -0
  667. package/system/dist/builtins/winston-logging/index.js +324 -0
  668. package/system/dist/builtins/winston-logging/index.mjs +313 -0
  669. package/system/dist/builtins/winston-logging/log-file-cursor.d.ts +12 -0
  670. package/system/dist/builtins/winston-logging/log-file-index-store.d.ts +11 -0
  671. package/system/dist/builtins/winston-logging/log-file-index.d.ts +77 -0
  672. package/system/dist/builtins/winston-logging/log-file-read-client.d.ts +44 -0
  673. package/system/dist/builtins/winston-logging/log-file-read-protocol.d.ts +41 -0
  674. package/system/dist/builtins/winston-logging/log-file-read-worker.d.ts +1 -0
  675. package/system/dist/builtins/winston-logging/log-file-reader.d.ts +51 -0
  676. package/system/dist/builtins/winston-logging/winston-destination.d.ts +39 -0
  677. package/system/dist/builtins/winston-logging/winston-logging.addon.d.ts +20 -0
  678. package/system/dist/chunk-CNf5ZN-e.mjs +37 -0
  679. package/system/dist/chunk-Cek0wNdY.js +64 -0
  680. package/system/dist/composition-sources-C14epb_m.js +155 -0
  681. package/system/dist/composition-sources-EXNuxmGQ.mjs +132 -0
  682. package/system/dist/constants-DIGWBiNC.mjs +20 -0
  683. package/system/dist/constants-M7NtSiRo.js +66 -0
  684. package/system/dist/coral-accelerators-BSVsBVzt.js +250 -0
  685. package/system/dist/coral-accelerators-DBlgWB8k.mjs +231 -0
  686. package/system/dist/custom-action-registry-JuMHGKEc.js +1638 -0
  687. package/system/dist/custom-action-registry-oHl1xltx.mjs +1482 -0
  688. package/system/dist/device-ca-3vmBP1i0.js +474 -0
  689. package/system/dist/device-ca-DZlvNBWU.mjs +367 -0
  690. package/system/dist/dist-DcMqHB_N.mjs +108095 -0
  691. package/system/dist/dist-M9yHiIY7.js +110554 -0
  692. package/system/dist/download/hosted-model-revisions.d.ts +10 -0
  693. package/system/dist/download/model-download-service.d.ts +35 -0
  694. package/system/dist/download/model-downloader.d.ts +156 -0
  695. package/system/dist/events/event-bus.d.ts +10 -0
  696. package/system/dist/events/system-event-bus.d.ts +14 -0
  697. package/system/dist/feature/feature-manager.d.ts +11 -0
  698. package/system/dist/file-host-worker.js +160 -0
  699. package/system/dist/file-host-worker.mjs +160 -0
  700. package/system/dist/formatter-DkYZ4LXp.mjs +162 -0
  701. package/system/dist/formatter-xbxeV4GD.js +167 -0
  702. package/system/dist/framework-resolver-hook.mjs +49 -0
  703. package/system/dist/http/asset-compression.d.ts +55 -0
  704. package/system/dist/http/authenticated-file-server.d.ts +53 -0
  705. package/system/dist/http/data-plane-registry.d.ts +58 -0
  706. package/system/dist/http/file-data-plane.d.ts +18 -0
  707. package/system/dist/http/lan-http-bind.d.ts +41 -0
  708. package/system/dist/http/reverse-proxy.d.ts +42 -0
  709. package/system/dist/hub-mdns-ciao-CpCKuQnK.js +1163 -0
  710. package/system/dist/hub-mdns-ciao-Czz2ssit.mjs +942 -0
  711. package/system/dist/i18n/catalog-registry.d.ts +35 -0
  712. package/system/dist/i18n/index.d.ts +2 -0
  713. package/system/dist/index.d.ts +156 -0
  714. package/system/dist/index.js +28736 -0
  715. package/system/dist/index.mjs +28065 -0
  716. package/system/dist/intel-accelerators-BvBjZn4j.js +16 -0
  717. package/system/dist/intel-accelerators-idEumqk1.mjs +15 -0
  718. package/system/dist/intel-npu-C8HKvRQF.mjs +27 -0
  719. package/system/dist/intel-npu-DYF5hO5K.js +28 -0
  720. package/system/dist/kernel/addon-class-resolver.d.ts +4 -0
  721. package/system/dist/kernel/addon-engine-manager.d.ts +22 -0
  722. package/system/dist/kernel/addon-health-monitor.d.ts +163 -0
  723. package/system/dist/kernel/addon-installer.d.ts +651 -0
  724. package/system/dist/kernel/addon-loader.d.ts +144 -0
  725. package/system/dist/kernel/addon-manifest.d.ts +128 -0
  726. package/system/dist/kernel/addon-refused-error.d.ts +30 -0
  727. package/system/dist/kernel/addon-residue.d.ts +45 -0
  728. package/system/dist/kernel/addon-settings-store.d.ts +43 -0
  729. package/system/dist/kernel/addon-version-policy.d.ts +34 -0
  730. package/system/dist/kernel/anon-rss.d.ts +12 -0
  731. package/system/dist/kernel/array-buffer-census.d.ts +118 -0
  732. package/system/dist/kernel/bootstrap-config.d.ts +7 -0
  733. package/system/dist/kernel/cap-router-builder.d.ts +180 -0
  734. package/system/dist/kernel/capability-handle.d.ts +46 -0
  735. package/system/dist/kernel/capability-registry.d.ts +621 -0
  736. package/system/dist/kernel/config-manager.d.ts +174 -0
  737. package/system/dist/kernel/config-schema.d.ts +37 -0
  738. package/system/dist/kernel/custom-action-registry.d.ts +32 -0
  739. package/system/dist/kernel/deps/addon-deps-manager.d.ts +28 -0
  740. package/system/dist/kernel/deps/closure-dedupe.d.ts +105 -0
  741. package/system/dist/kernel/deps/ensure-addon-natives.d.ts +41 -0
  742. package/system/dist/kernel/deps/ensure-native-prebuilds.d.ts +40 -0
  743. package/system/dist/kernel/deps/manifest-native-deps.d.ts +42 -0
  744. package/system/dist/kernel/deps/manifest-python-deps.d.ts +20 -0
  745. package/system/dist/kernel/deps/manifest-system-deps.d.ts +18 -0
  746. package/system/dist/kernel/deps/npm-command.d.ts +60 -0
  747. package/system/dist/kernel/deps/system-package-allowlist.d.ts +12 -0
  748. package/system/dist/kernel/deps/system-package-broker.d.ts +31 -0
  749. package/system/dist/kernel/deps/system-package-client.d.ts +9 -0
  750. package/system/dist/kernel/device-call-redirect.d.ts +18 -0
  751. package/system/dist/kernel/device-registry.d.ts +29 -0
  752. package/system/dist/kernel/device-settings-store.d.ts +74 -0
  753. package/system/dist/kernel/event-loop-stall-monitor.d.ts +41 -0
  754. package/system/dist/kernel/event-plane-report.d.ts +225 -0
  755. package/system/dist/kernel/fs-utils.d.ts +88 -0
  756. package/system/dist/kernel/gc-census.d.ts +161 -0
  757. package/system/dist/kernel/heap-spaces.d.ts +112 -0
  758. package/system/dist/kernel/heap-watch.d.ts +816 -0
  759. package/system/dist/kernel/host-externals.d.ts +12 -0
  760. package/system/dist/kernel/hwaccel/hwaccel-resolver.d.ts +56 -0
  761. package/system/dist/kernel/hwaccel/vaapi-init-probe.d.ts +29 -0
  762. package/system/dist/kernel/index.d.ts +116 -0
  763. package/system/dist/kernel/inference/inference-resolver.d.ts +22 -0
  764. package/system/dist/kernel/inference/local-python-runtimes.d.ts +2 -0
  765. package/system/dist/kernel/infra-capabilities.d.ts +13 -0
  766. package/system/dist/kernel/isolated-builtin-phase.d.ts +57 -0
  767. package/system/dist/kernel/lifecycle/job-journal.d.ts +19 -0
  768. package/system/dist/kernel/lifecycle/lifecycle-job-engine.d.ts +106 -0
  769. package/system/dist/kernel/lifecycle/staging-area.d.ts +31 -0
  770. package/system/dist/kernel/moleculer/accessory-prune-gate.d.ts +55 -0
  771. package/system/dist/kernel/moleculer/addon-context-factory.d.ts +104 -0
  772. package/system/dist/kernel/moleculer/addon-data-plane-facility.d.ts +19 -0
  773. package/system/dist/kernel/moleculer/addon-deploy-source.d.ts +16 -0
  774. package/system/dist/kernel/moleculer/addon-peer-bytes-facility.d.ts +25 -0
  775. package/system/dist/kernel/moleculer/addon-runner.d.ts +1 -0
  776. package/system/dist/kernel/moleculer/addon-service-factory.d.ts +50 -0
  777. package/system/dist/kernel/moleculer/agent-event-scope.d.ts +49 -0
  778. package/system/dist/kernel/moleculer/agent-ui-unlock.d.ts +67 -0
  779. package/system/dist/kernel/moleculer/broker-factory.d.ts +95 -0
  780. package/system/dist/kernel/moleculer/broker-transport-swap.d.ts +60 -0
  781. package/system/dist/kernel/moleculer/cap-usage-registry.d.ts +126 -0
  782. package/system/dist/kernel/moleculer/capabilities-access.d.ts +21 -0
  783. package/system/dist/kernel/moleculer/child-addon-call-dispatch.d.ts +53 -0
  784. package/system/dist/kernel/moleculer/child-cap-descriptors.d.ts +34 -0
  785. package/system/dist/kernel/moleculer/child-cap-dispatch.d.ts +59 -0
  786. package/system/dist/kernel/moleculer/children-batch-loader.d.ts +98 -0
  787. package/system/dist/kernel/moleculer/core-cap-service.d.ts +65 -0
  788. package/system/dist/kernel/moleculer/crash-supervisor.d.ts +50 -0
  789. package/system/dist/kernel/moleculer/device-cap-proxy.d.ts +70 -0
  790. package/system/dist/kernel/moleculer/device-event-ring.d.ts +155 -0
  791. package/system/dist/kernel/moleculer/event-bus-core.d.ts +198 -0
  792. package/system/dist/kernel/moleculer/event-bus.d.ts +106 -0
  793. package/system/dist/kernel/moleculer/hub-log-forwarder.d.ts +36 -0
  794. package/system/dist/kernel/moleculer/hub-service.d.ts +39 -0
  795. package/system/dist/kernel/moleculer/init-watchdog.d.ts +60 -0
  796. package/system/dist/kernel/moleculer/mesh-access-middleware.d.ts +42 -0
  797. package/system/dist/kernel/moleculer/mesh-identity.d.ts +57 -0
  798. package/system/dist/kernel/moleculer/mesh-mtls/constants.d.ts +17 -0
  799. package/system/dist/kernel/moleculer/mesh-mtls/index.d.ts +12 -0
  800. package/system/dist/kernel/moleculer/mesh-mtls/mesh-ca-keeper.d.ts +60 -0
  801. package/system/dist/kernel/moleculer/mesh-mtls/mesh-ca.d.ts +49 -0
  802. package/system/dist/kernel/moleculer/mesh-mtls/mesh-certificate-registry.d.ts +105 -0
  803. package/system/dist/kernel/moleculer/mesh-mtls/mesh-crl.d.ts +16 -0
  804. package/system/dist/kernel/moleculer/mesh-mtls/mesh-membership.d.ts +64 -0
  805. package/system/dist/kernel/moleculer/mesh-mtls/mesh-peer-transport.d.ts +47 -0
  806. package/system/dist/kernel/moleculer/mesh-mtls/mesh-renewal.d.ts +135 -0
  807. package/system/dist/kernel/moleculer/mesh-mtls/mesh-tls-enabler.d.ts +9 -0
  808. package/system/dist/kernel/moleculer/mesh-mtls/mesh-tls-gate.d.ts +40 -0
  809. package/system/dist/kernel/moleculer/mesh-mtls/pairing/agent-pairing.d.ts +214 -0
  810. package/system/dist/kernel/moleculer/mesh-mtls/pairing/hub-pairing.d.ts +115 -0
  811. package/system/dist/kernel/moleculer/mesh-mtls/pairing/index.d.ts +3 -0
  812. package/system/dist/kernel/moleculer/mesh-mtls/pairing/pairing-protocol.d.ts +107 -0
  813. package/system/dist/kernel/moleculer/mesh-mtls/tls-tcp-transporter.d.ts +242 -0
  814. package/system/dist/kernel/moleculer/mesh-queue-report.d.ts +51 -0
  815. package/system/dist/kernel/moleculer/node-registry.d.ts +146 -0
  816. package/system/dist/kernel/moleculer/process-context.d.ts +4 -0
  817. package/system/dist/kernel/moleculer/process-service.d.ts +92 -0
  818. package/system/dist/kernel/moleculer/provider-registry.d.ts +28 -0
  819. package/system/dist/kernel/moleculer/readiness-context.d.ts +67 -0
  820. package/system/dist/kernel/moleculer/readiness-service.d.ts +37 -0
  821. package/system/dist/kernel/moleculer/records-api-transport.d.ts +9 -0
  822. package/system/dist/kernel/moleculer/register-framework-resolver.d.ts +8 -0
  823. package/system/dist/kernel/moleculer/register-node-client.d.ts +49 -0
  824. package/system/dist/kernel/moleculer/remote-logger.d.ts +43 -0
  825. package/system/dist/kernel/moleculer/resilient-cap-call.d.ts +28 -0
  826. package/system/dist/kernel/moleculer/runner-addon-settings.d.ts +29 -0
  827. package/system/dist/kernel/moleculer/runner-device-settings.d.ts +39 -0
  828. package/system/dist/kernel/moleculer/runner-heap-flags.d.ts +228 -0
  829. package/system/dist/kernel/moleculer/runner-native-allocator.d.ts +107 -0
  830. package/system/dist/kernel/moleculer/runner-process-group.d.ts +96 -0
  831. package/system/dist/kernel/moleculer/runner-refusal.d.ts +27 -0
  832. package/system/dist/kernel/moleculer/runtime-state-load.d.ts +29 -0
  833. package/system/dist/kernel/moleculer/settings-read-guard.d.ts +49 -0
  834. package/system/dist/kernel/moleculer/stream-probe-service.d.ts +28 -0
  835. package/system/dist/kernel/moleculer/trpc-links.d.ts +244 -0
  836. package/system/dist/kernel/moleculer/typed-array-serde.d.ts +14 -0
  837. package/system/dist/kernel/moleculer/worker-device-restore.d.ts +10 -0
  838. package/system/dist/kernel/outbound-queue-watch.d.ts +94 -0
  839. package/system/dist/kernel/prefix-walk.d.ts +39 -0
  840. package/system/dist/kernel/process-cpu-census.d.ts +74 -0
  841. package/system/dist/kernel/provider-kind-drift.d.ts +21 -0
  842. package/system/dist/kernel/restart-coordinator.d.ts +90 -0
  843. package/system/dist/kernel/sections-store.d.ts +20 -0
  844. package/system/dist/kernel/settings-door-view.d.ts +41 -0
  845. package/system/dist/kernel/settings-read-error.d.ts +35 -0
  846. package/system/dist/kernel/settings-view-types.d.ts +80 -0
  847. package/system/dist/kernel/socket-plane-report.d.ts +268 -0
  848. package/system/dist/kernel/status-overlay.d.ts +38 -0
  849. package/system/dist/kernel/storage-location-registry.d.ts +55 -0
  850. package/system/dist/kernel/store-settings-view.d.ts +14 -0
  851. package/system/dist/kernel/system-settings-mirror.d.ts +46 -0
  852. package/system/dist/kernel/system-settings-policy.d.ts +28 -0
  853. package/system/dist/kernel/transport/cap-action-census.d.ts +218 -0
  854. package/system/dist/kernel/transport/cap-action-name.d.ts +100 -0
  855. package/system/dist/kernel/transport/cap-child-index.d.ts +49 -0
  856. package/system/dist/kernel/transport/cap-route-resolver.d.ts +231 -0
  857. package/system/dist/kernel/transport/cap-route.d.ts +168 -0
  858. package/system/dist/kernel/transport/cap-routing-hints.d.ts +42 -0
  859. package/system/dist/kernel/transport/child-cap-protocol.d.ts +307 -0
  860. package/system/dist/kernel/transport/claimed-get-status.d.ts +39 -0
  861. package/system/dist/kernel/transport/create-local-transport.d.ts +7 -0
  862. package/system/dist/kernel/transport/device-call-redirect.d.ts +39 -0
  863. package/system/dist/kernel/transport/frame-codec.d.ts +122 -0
  864. package/system/dist/kernel/transport/hub-cap-forward.d.ts +96 -0
  865. package/system/dist/kernel/transport/index.d.ts +38 -0
  866. package/system/dist/kernel/transport/local-child-client.d.ts +199 -0
  867. package/system/dist/kernel/transport/local-child-registry.d.ts +654 -0
  868. package/system/dist/kernel/transport/local-endpoint-path.d.ts +6 -0
  869. package/system/dist/kernel/transport/local-transport.d.ts +122 -0
  870. package/system/dist/kernel/transport/parent-unowned-call.d.ts +283 -0
  871. package/system/dist/kernel/transport/peer-answered-error.d.ts +21 -0
  872. package/system/dist/kernel/transport/socket-channel.d.ts +116 -0
  873. package/system/dist/kernel/transport/socket-traffic.d.ts +118 -0
  874. package/system/dist/kernel/transport/uds-event-bridge.d.ts +85 -0
  875. package/system/dist/kernel/transport/uds-event-bus.d.ts +93 -0
  876. package/system/dist/kernel/transport/uds-local-transport.d.ts +18 -0
  877. package/system/dist/kernel/transport/uds-log-ingest.d.ts +43 -0
  878. package/system/dist/kernel/transport/uds-logger.d.ts +44 -0
  879. package/system/dist/kernel/utils/ring-buffer.d.ts +15 -0
  880. package/system/dist/kernel/workspace-detect.d.ts +9 -0
  881. package/system/dist/lib-5THG9eKz.mjs +15545 -0
  882. package/system/dist/lib-C3U1yluo.js +7110 -0
  883. package/system/dist/lib-CZ3g2WTS.js +15549 -0
  884. package/system/dist/lib-DFZblCIu.mjs +7106 -0
  885. package/system/dist/lifecycle/lifecycle-state-machine.d.ts +28 -0
  886. package/system/dist/log-file-read-protocol-B7M3X3bT.mjs +785 -0
  887. package/system/dist/log-file-read-protocol-D0WcLbIV.js +817 -0
  888. package/system/dist/log-file-read-worker.js +64 -0
  889. package/system/dist/log-file-read-worker.mjs +64 -0
  890. package/system/dist/log-read-filter-Bi066jwU.js +134 -0
  891. package/system/dist/log-read-filter-D7Ev3zm-.mjs +93 -0
  892. package/system/dist/logging/formatter.d.ts +57 -0
  893. package/system/dist/logging/log-manager.d.ts +145 -0
  894. package/system/dist/logging/log-read-filter.d.ts +43 -0
  895. package/system/dist/logging/log-redactor.d.ts +30 -0
  896. package/system/dist/logging/log-ring-buffer.d.ts +62 -0
  897. package/system/dist/logging/logging-gate.d.ts +76 -0
  898. package/system/dist/logging/logging-gate.singleton.d.ts +16 -0
  899. package/system/dist/logging/partitioned-log-buffer.d.ts +169 -0
  900. package/system/dist/logging/scoped-logger.d.ts +17 -0
  901. package/system/dist/migrations/hub/index.d.ts +11 -0
  902. package/system/dist/ms-CgH2OFlD.mjs +120 -0
  903. package/system/dist/ms-LB3giGoU.js +124 -0
  904. package/system/dist/network/network-quality.d.ts +11 -0
  905. package/system/dist/notification/notification-service.d.ts +43 -0
  906. package/system/dist/notification/toast-service.d.ts +22 -0
  907. package/system/dist/pipeline/engine-manager-resolver.d.ts +15 -0
  908. package/system/dist/pipeline/pipeline-runner.d.ts +8 -0
  909. package/system/dist/pipeline/pipeline-validator.d.ts +13 -0
  910. package/system/dist/platform-key-source-BWlq0jjn.mjs +23 -0
  911. package/system/dist/platform-key-source-Di7HrlGR.js +40 -0
  912. package/system/dist/prefix-range-D_KueXbQ.js +27 -0
  913. package/system/dist/prefix-range-Dl0znowN.mjs +22 -0
  914. package/system/dist/prefix-walk-DAOBSyH1.mjs +88 -0
  915. package/system/dist/prefix-walk-Dv6MLZlM.js +99 -0
  916. package/system/dist/process/proc-stat.d.ts +75 -0
  917. package/system/dist/process/resource-monitor.d.ts +28 -0
  918. package/system/dist/python/python-env-manager.d.ts +12 -0
  919. package/system/dist/read-all-rows-CVoO1ONM.js +29 -0
  920. package/system/dist/read-all-rows-TaPqdWNF.mjs +25 -0
  921. package/system/dist/records/read-all-rows.d.ts +6 -0
  922. package/system/dist/repl/interfaces.d.ts +31 -0
  923. package/system/dist/repl/repl-engine.d.ts +8 -0
  924. package/system/dist/resource-monitor-Di9daRwI.mjs +96 -0
  925. package/system/dist/resource-monitor-mio9dSCT.js +113 -0
  926. package/system/dist/restore-archive-Cy7jGqiD.js +4325 -0
  927. package/system/dist/restore-archive-DS4nvQ43.mjs +4213 -0
  928. package/system/dist/retention-Dqm_EiVq.mjs +893 -0
  929. package/system/dist/retention-Ufa2fci-.js +1024 -0
  930. package/system/dist/retired-settings-keys-C8nOOr5H.js +381 -0
  931. package/system/dist/retired-settings-keys-u6xQA6r7.mjs +364 -0
  932. package/system/dist/safe-buffer-B1OjL1I9.mjs +42 -0
  933. package/system/dist/safe-buffer-D3aoa-7X.js +46 -0
  934. package/system/dist/settle-sources-Bhsy57y-.js +38 -0
  935. package/system/dist/settle-sources-CDtNC8ub.mjs +33 -0
  936. package/system/dist/snapshot-courtesy-CyFs1M3I.mjs +167 -0
  937. package/system/dist/snapshot-courtesy-D_C5-nC0.js +192 -0
  938. package/system/dist/sqlite-snapshot-protocol-2QaTouWV.mjs +34 -0
  939. package/system/dist/sqlite-snapshot-protocol-B9OndqZv.js +51 -0
  940. package/system/dist/sqlite-snapshot-worker.js +185 -0
  941. package/system/dist/sqlite-snapshot-worker.mjs +179 -0
  942. package/system/dist/src-CnAqG6EF.js +714 -0
  943. package/system/dist/src-hG4grMU4.mjs +709 -0
  944. package/system/dist/storage/fs-storage-backend.d.ts +40 -0
  945. package/system/dist/storage/storage-location-manager.d.ts +23 -0
  946. package/system/dist/storage/storage-manager.d.ts +83 -0
  947. package/system/dist/tls/agent-https-names.d.ts +25 -0
  948. package/system/dist/tls/agent-https.d.ts +111 -0
  949. package/system/dist/tls/boot-tls.d.ts +35 -0
  950. package/system/dist/tls/cert-backdate.d.ts +10 -0
  951. package/system/dist/tls/cert-evaluation.d.ts +41 -0
  952. package/system/dist/tls/cert-identity.d.ts +60 -0
  953. package/system/dist/tls/cert-issue.d.ts +57 -0
  954. package/system/dist/tls/cert-manager.d.ts +124 -0
  955. package/system/dist/tls/cert-name-constraints.d.ts +53 -0
  956. package/system/dist/tls/cert-utc-time.d.ts +1 -0
  957. package/system/dist/tls/https-listener.d.ts +30 -0
  958. package/system/dist/tls/index.d.ts +12 -0
  959. package/system/dist/tls/tls-actions.d.ts +49 -0
  960. package/system/dist/tls/tls-status.d.ts +57 -0
  961. package/system/dist/tls/uploaded-cert.d.ts +46 -0
  962. package/system/dist/wal-checkpoint-policy-BahrTtyD.mjs +186 -0
  963. package/system/dist/wal-checkpoint-policy-d2z2qPqx.js +233 -0
  964. package/system/dist/wal-checkpoint-worker.js +144 -0
  965. package/system/dist/wal-checkpoint-worker.mjs +143 -0
  966. package/system/dist/wal-maintenance-BmugbgS7.js +0 -0
  967. package/system/dist/wal-maintenance-Bnb2QzYG.mjs +0 -0
  968. package/system/dist/x509.es-BRiJgOvu.mjs +11939 -0
  969. package/system/dist/x509.es-WtnRNyYS.js +12076 -0
  970. package/system/package.json +516 -0
@@ -0,0 +1,3961 @@
1
+ import { As as DeviceType, G as DeclaredDevices, Ho as createEvent, I as DERIVED_CAMERA_SILENCED_CAP_NAMES, Kr as memoizePinnedFfmpeg, Ms as EventCategory, Oa as buildFfmpegArgs, Os as DeviceFeature, Qa as BaseAddon, Qo as hydrateSchema, Rn as declarationOwnerNodeId, Zi as snapshotCapability, Zr as motionCapability, gt as MOTION_CLOSE_AFTER_MS, hn as cameraGridLayoutCapability, ia as streamCatalogCapability, js as errMsg, m as BaseDevice } from "../../dist-DcMqHB_N.mjs";
2
+ import { z } from "zod";
3
+ import { FfmpegProcess } from "@camstack/types/node";
4
+ import { join } from "node:path";
5
+ import { promises } from "node:fs";
6
+ import { spawn } from "node:child_process";
7
+ import { createServer } from "node:http";
8
+ //#region src/builtins/camera-grid/grid-camera-declarations.ts
9
+ /**
10
+ * Turning persisted grid rows into the camera declarations `DeclaredDevices`
11
+ * reconciles.
12
+ *
13
+ * Modelled on `terminal-camera-declarations.ts`, and for the same reasons: the
14
+ * declaration set is the ONLY thing standing between a transient RPC failure
15
+ * and a sweep that deletes every camera this addon owns.
16
+ */
17
+ /** The prefix every stable id this addon has ever minted starts with. */
18
+ var GRID_CAMERA_STABLE_ID_PREFIX = "camera-grid-";
19
+ /**
20
+ * The stable id is `camera-grid-<instance uuid>` and NOTHING else.
21
+ *
22
+ * A stable id is permanent the instant it is minted: bindings, grid layouts in
23
+ * other addons, recording rows, the timeline and this addon's own tombstones
24
+ * all reference it, and a device whose stable id changes is a NEW camera with
25
+ * an empty history. So it may only be derived from something that itself never
26
+ * changes.
27
+ *
28
+ * The instance uuid is the only such thing here. Deriving it from the NAME
29
+ * would rename-break every reference; deriving it from the CELLS would mint a
30
+ * new camera every time the operator drags a rectangle — which is the entire
31
+ * activity this addon exists for. Terminal learned the same lesson from the
32
+ * other end: its original one-camera-per-node id is permanent, and its profile
33
+ * migration had to ENRICH that row rather than mint a replacement.
34
+ */
35
+ function newGridCameraStableId(instanceId) {
36
+ return `${GRID_CAMERA_STABLE_ID_PREFIX}${instanceId}`;
37
+ }
38
+ /**
39
+ * Explicit persisted instances only. A grid camera exists because an operator
40
+ * created a grid, never because some source camera happens to exist.
41
+ *
42
+ * A grid with NO cells is declared like any other: creation is name-only and
43
+ * the layout is authored afterwards in the camera's own device details, so
44
+ * "no cells yet" is the normal first state, not an invalid row.
45
+ */
46
+ function buildGridCameraDeclarations(instances) {
47
+ return instances.filter((instance) => instance.enabled).map((instance) => ({
48
+ stableId: instance.cameraStableId,
49
+ name: instance.name,
50
+ config: { instanceId: instance.id }
51
+ }));
52
+ }
53
+ /**
54
+ * The rows `DeclaredDevices` is allowed to consider — every live declaration
55
+ * plus ONE bounded batch of orphans.
56
+ *
57
+ * Two guards, both copied from Terminal because both were paid for there:
58
+ *
59
+ * 1. **An unknown integration id yields an EMPTY index.** `null`/`undefined`
60
+ * means "the integration lookup has not answered", which is not the same
61
+ * fact as "this addon owns no rows" — and only the second one may drive a
62
+ * withdrawal.
63
+ * 2. **The orphan batch is bounded and deterministically ordered.** The generic
64
+ * sweep refuses an over-limit set outright; selecting a batch here drains a
65
+ * large historical orphan set across passes without weakening that guard.
66
+ */
67
+ function gridCameraReconciliationIndex(rows, integrationId, declarations, managedStableIds = /* @__PURE__ */ new Set()) {
68
+ if (!integrationId) return [];
69
+ const declared = new Set(declarations.map((camera) => camera.stableId));
70
+ const owned = rows.filter((row) => row.integrationId === integrationId && (declared.has(row.stableId) || managedStableIds.has(row.stableId) || row.stableId.startsWith(GRID_CAMERA_STABLE_ID_PREFIX)));
71
+ return [...owned.filter((row) => declared.has(row.stableId)), ...owned.filter((row) => !declared.has(row.stableId)).sort((left, right) => left.id - right.id).slice(0, 32)];
72
+ }
73
+ //#endregion
74
+ //#region src/builtins/camera-grid/grid-device-settings.ts
75
+ /** The widget id, registered in `ui-library`'s `HOST_WIDGETS`. */
76
+ var GRID_LAYOUT_WIDGET_ID = "host/camera-grid-layout";
77
+ /**
78
+ * The layout section, or `null` when this device is not a grid.
79
+ *
80
+ * `isGrid` is the ANSWER to "is this a grid", never "do we know yet". A caller
81
+ * that cannot tell must not call this — an unresolved read rendered as `null`
82
+ * would hide the editor from a real grid (D315).
83
+ */
84
+ function buildGridDeviceSchema(isGrid) {
85
+ if (!isGrid) return null;
86
+ return { sections: [{
87
+ id: "camera-grid-layout",
88
+ tab: "general",
89
+ title: "Grid layout",
90
+ titleKey: "server:gridDevice.s_camera-grid-layout.title",
91
+ order: 20,
92
+ fields: [{
93
+ type: "widget",
94
+ key: "_gridLayout",
95
+ label: "",
96
+ labelKey: "server:gridDevice.s_camera-grid-layout._gridLayout.label",
97
+ widgetId: GRID_LAYOUT_WIDGET_ID
98
+ }]
99
+ }] };
100
+ }
101
+ //#endregion
102
+ //#region src/builtins/camera-grid/grid-layout-native-provider.ts
103
+ /**
104
+ * The `camera-grid-layout` provider, contribution included.
105
+ *
106
+ * ## Why the section lives on the DEVICE provider and not on the addon
107
+ *
108
+ * `camera-grid-layout` is registered per device, through
109
+ * `DeviceContext.registerNativeCap`. `child-cap-dispatch` resolves a call that
110
+ * carries a `deviceId` to the device-scoped provider FIRST, and when the method
111
+ * is absent there it throws rather than falling back to the singleton — the
112
+ * fallback exists only for a collection cap's list method. Every contribution
113
+ * method carries a `deviceId` by definition, so an addon-level wrapper is
114
+ * simply never reached: it registered, it type-checked, and the live hub
115
+ * answered HTTP 500 with
116
+ * `method 'getDeviceSettingsContribution' not found on provider
117
+ * 'camera-grid-layout'`.
118
+ *
119
+ * That is why the whole provider is built here, in one place, and handed to
120
+ * `registerNativeCap` as a single object. `exposesDeviceSettings` widens
121
+ * `InferProvider` and not `InferNativeProvider`, so the type below is the wider
122
+ * one; registering it is safe because a native registration only ever needs a
123
+ * SUBSET of what this carries.
124
+ *
125
+ * The refusal (D526) rides along: a device the addon cannot name as a grid gets
126
+ * `null`, so a camera that is not a grid gets no section at all rather than a
127
+ * panel that renders its own emptiness.
128
+ */
129
+ function buildGridLayoutNativeProvider(source) {
130
+ return {
131
+ getLayout: async ({ deviceId }) => source.getLayout(deviceId),
132
+ saveLayout: async (patch) => source.saveLayout(patch),
133
+ getDeviceSettingsContribution: async ({ deviceId }) => {
134
+ const schema = buildGridDeviceSchema(source.getLayout(deviceId) !== null);
135
+ return schema === null ? null : hydrateSchema(schema, {});
136
+ },
137
+ getDeviceLiveContribution: async () => null,
138
+ applyDeviceSettingsPatch: async () => ({ success: true })
139
+ };
140
+ }
141
+ //#endregion
142
+ //#region src/builtins/camera-grid/grid-camera-device.ts
143
+ /**
144
+ * The composite camera device.
145
+ *
146
+ * An ORDINARY camera in every respect the rest of the system can see: it
147
+ * records, it appears in the timeline, it has profile slots, it is bound like
148
+ * any other. What makes it a grid is invisible from here — its streams are
149
+ * composed rather than dialled, and object detection is switched off at
150
+ * CREATION (see `silence-analysis.ts`), never re-asserted.
151
+ *
152
+ * ## The three native caps, and why each is native
153
+ *
154
+ * - **`stream-catalog`** — what this grid OFFERS, one descriptor per profile it
155
+ * can honestly compose. Named on every pull, idle included: the broker sweeps
156
+ * anything its registry holds that a catalog does not name.
157
+ * - **`camera-grid-layout`** — the geometry, on the camera's own page. Device
158
+ * scoped so the widget asks THE CAMERA; the addon-scoped custom actions it
159
+ * replaces could only be reached by a caller that already knew the addon id,
160
+ * which is why the editor rendered nowhere.
161
+ * - **`snapshot`** — a frame of the composition. It used to be deliberately
162
+ * ABSENT, on the reasoning that the broker's ordinary grab takes one from the
163
+ * profile slot and taking one IS a consumer. That is true and it is the
164
+ * defect: it means a thumbnail in a list starts N decodes, and on a battery
165
+ * source it would be a wake. A native provider runs BEFORE that grab and
166
+ * answers from the live composition or from the frame it kept
167
+ * (`grid-snapshot.ts`).
168
+ */
169
+ var gridCameraSchema = z.object({
170
+ /** The persisted grid row this camera was declared from. */
171
+ instanceId: z.string().min(1) });
172
+ var runtime = null;
173
+ function installGridCameraRuntime(next) {
174
+ runtime = next;
175
+ }
176
+ function activeRuntime() {
177
+ if (runtime === null) throw new Error("camera-grid: the addon runtime is not installed");
178
+ return runtime;
179
+ }
180
+ var GridCameraDevice = class extends BaseDevice {
181
+ features = [DeviceFeature.NativeSnapshot];
182
+ constructor(ctx) {
183
+ super(ctx, gridCameraSchema, { type: ctx.deviceMeta.type });
184
+ this.ctx.registerNativeCap(streamCatalogCapability, { getCatalog: async ({ deviceId }) => {
185
+ if (deviceId !== this.id) return [];
186
+ return this.catalog();
187
+ } });
188
+ const layoutProvider = buildGridLayoutNativeProvider({
189
+ getLayout: (deviceId) => activeRuntime().getLayout(deviceId),
190
+ saveLayout: (patch) => activeRuntime().saveLayout(patch)
191
+ });
192
+ this.ctx.registerNativeCap(cameraGridLayoutCapability, layoutProvider);
193
+ this.ctx.registerNativeCap(snapshotCapability, {
194
+ getSnapshot: async ({ deviceId }) => activeRuntime().getSnapshot(deviceId),
195
+ invalidateCache: async () => {}
196
+ });
197
+ this.ctx.registerNativeCap(motionCapability, {
198
+ getStatus: async ({ deviceId }) => activeRuntime().motionStatus(deviceId),
199
+ isDetected: async ({ deviceId }) => activeRuntime().motionStatus(deviceId).detected
200
+ });
201
+ this.markOnline(true);
202
+ }
203
+ catalog() {
204
+ const descriptors = activeRuntime().descriptorsFor(this.config.get("instanceId"));
205
+ if (descriptors === null) throw new Error(`camera-grid: cannot describe the streams of instance ${this.config.get("instanceId")}`);
206
+ return descriptors;
207
+ }
208
+ setAddonOnline(online) {
209
+ this.markOnline(online);
210
+ }
211
+ };
212
+ //#endregion
213
+ //#region src/builtins/camera-grid/acquire-retry.ts
214
+ async function acquireWithRetry(attempt, deps) {
215
+ const startedAt = deps.now();
216
+ for (;;) try {
217
+ return await attempt();
218
+ } catch (error) {
219
+ const waited = deps.now() - startedAt;
220
+ if (waited >= deps.budgetMs) throw error;
221
+ deps.onRetry?.(waited);
222
+ await deps.sleep();
223
+ }
224
+ }
225
+ //#endregion
226
+ //#region src/builtins/camera-grid/grid-instances.ts
227
+ /**
228
+ * The operator-written grid rows.
229
+ *
230
+ * Shape follows `readTerminalInstances`: a grid is a persisted row that
231
+ * DECLARES a camera, and the declaration reconcile turns rows into devices.
232
+ *
233
+ * Config is operator-writable, so a malformed or duplicate row is IGNORED
234
+ * rather than allowed to make the reconcile destructive. One bad row must never
235
+ * delete every camera this addon declares — that failure mode is why the
236
+ * Terminal addon reads its rows the same way.
237
+ */
238
+ /** A rectangle in normalized [0,1] coordinates of whatever contains it. */
239
+ var NormalizedRectSchema = z.object({
240
+ x: z.number().min(0).max(1),
241
+ y: z.number().min(0).max(1),
242
+ width: z.number().gt(0).max(1),
243
+ height: z.number().gt(0).max(1)
244
+ });
245
+ /**
246
+ * One source camera, the part of its picture taken, and where that part lands
247
+ * on the composite's canvas. Both rectangles are NORMALIZED so a source that
248
+ * changes resolution does not silently start cutting the wrong region.
249
+ */
250
+ var GridCellSchema = z.object({
251
+ deviceId: z.number().int().positive(),
252
+ source: NormalizedRectSchema,
253
+ cell: NormalizedRectSchema
254
+ });
255
+ var GridInstanceSchema = z.object({
256
+ id: z.string().uuid(),
257
+ cameraStableId: z.string().min(1).max(256),
258
+ name: z.string().min(1).max(160),
259
+ enabled: z.boolean(),
260
+ /**
261
+ * NO canvas size. It is DERIVED, per profile, from the cells and the sources'
262
+ * own dimensions (`grid-canvas-derivation.ts`) — the two numbers that used to
263
+ * live here were typed into the editor and silently decided both how much the
264
+ * composite cost and how sharp it was.
265
+ *
266
+ * Rows written before that change still carry `width`/`height`; zod drops
267
+ * unknown keys, so they are ignored rather than migrated. Nothing reads them,
268
+ * and a migration that rewrote every row to delete two fields would be a
269
+ * write with no reader.
270
+ */
271
+ fps: z.number().int().min(1).max(60),
272
+ /**
273
+ * Which profiles this grid PUBLISHES, of the ones it could serve.
274
+ *
275
+ * Default `mid` + `low`, and the default is the finding: a grid's `high` is
276
+ * composed of its sources' `high`, so on this fleet it is a 4K canvas built
277
+ * from 4K decodes — a thing to opt into, not to be handed by a viewer's
278
+ * adaptive climbing to the top rung it can see.
279
+ *
280
+ * Absent on rows written before this, which is why the default lives in the
281
+ * schema rather than at the call site: an old grid starts publishing the two
282
+ * cheap rungs without anyone touching it.
283
+ */
284
+ publishedProfiles: z.array(z.enum([
285
+ "high",
286
+ "mid",
287
+ "low"
288
+ ])).max(3).default(["mid", "low"]),
289
+ /**
290
+ * Empty is the NORMAL freshly-created state: a grid is created from the
291
+ * integration page with a name only, and laid out afterwards in the camera's
292
+ * own settings. A grid with no cells declares its camera and emits nothing.
293
+ */
294
+ cells: z.array(GridCellSchema).max(16).default([])
295
+ });
296
+ function readGridInstances(raw, onInvalid) {
297
+ const ids = /* @__PURE__ */ new Set();
298
+ const stableIds = /* @__PURE__ */ new Set();
299
+ const instances = [];
300
+ for (const value of raw) {
301
+ const parsed = GridInstanceSchema.safeParse(value);
302
+ if (!parsed.success) {
303
+ onInvalid?.("Ignoring malformed camera-grid configuration");
304
+ continue;
305
+ }
306
+ const instance = parsed.data;
307
+ if (ids.has(instance.id) || stableIds.has(instance.cameraStableId)) {
308
+ onInvalid?.(`Ignoring duplicate camera-grid instance ${instance.id}`);
309
+ continue;
310
+ }
311
+ ids.add(instance.id);
312
+ stableIds.add(instance.cameraStableId);
313
+ instances.push(instance);
314
+ }
315
+ return instances;
316
+ }
317
+ //#endregion
318
+ //#region src/builtins/camera-grid/grid-plan.ts
319
+ /**
320
+ * Bits per pixel per frame. A composite is mostly static furniture with a few
321
+ * moving subjects, so it compresses well; this lands a 1920x1080@10 grid near
322
+ * 3 Mbps and a 640x360@10 one near 0.35 Mbps. A single flat number would either
323
+ * starve a 4K canvas or spend a 4K budget on a thumbnail-sized one.
324
+ */
325
+ var BITS_PER_PIXEL_PER_FRAME = .15;
326
+ var MIN_BITRATE_KBPS = 256;
327
+ var MAX_BITRATE_KBPS = 16e3;
328
+ function bitrateFor(width, height, fps) {
329
+ const bps = width * height * fps * BITS_PER_PIXEL_PER_FRAME;
330
+ return Math.min(MAX_BITRATE_KBPS, Math.max(MIN_BITRATE_KBPS, Math.round(bps / 1e3)));
331
+ }
332
+ /** `null` when the grid has nothing to compose — the normal freshly-created state. */
333
+ function gridPlanFor(instance, encode) {
334
+ if (instance.cells.length === 0) return null;
335
+ const ordinalByDeviceId = /* @__PURE__ */ new Map();
336
+ const sourceDeviceIds = [];
337
+ const cells = instance.cells.map((cell) => {
338
+ let ordinal = ordinalByDeviceId.get(cell.deviceId);
339
+ if (ordinal === void 0) {
340
+ ordinal = sourceDeviceIds.length;
341
+ ordinalByDeviceId.set(cell.deviceId, ordinal);
342
+ sourceDeviceIds.push(cell.deviceId);
343
+ }
344
+ return {
345
+ inputIndex: ordinal,
346
+ source: cell.source,
347
+ cell: cell.cell
348
+ };
349
+ });
350
+ const canvas = encode.canvas;
351
+ return {
352
+ layout: {
353
+ width: canvas.width,
354
+ height: canvas.height,
355
+ cells
356
+ },
357
+ sourceDeviceIds,
358
+ encoder: encode.encoder,
359
+ decodeHwAccel: encode.decodeHwAccel,
360
+ fps: instance.fps,
361
+ bitrateKbps: bitrateFor(canvas.width, canvas.height, instance.fps)
362
+ };
363
+ }
364
+ //#endregion
365
+ //#region src/builtins/camera-grid/grid-row-normalization.ts
366
+ /**
367
+ * Creation is NAME ONLY.
368
+ *
369
+ * The operator adds a row on the integration page and types a name. Everything
370
+ * else — the identity the rest of the cluster will reference forever, the
371
+ * canvas, the frame rate, the cells — is filled in here on the way past, and
372
+ * then edited in the camera's own device details.
373
+ *
374
+ * This runs BEFORE `readGridInstances`, which deliberately IGNORES a row it
375
+ * cannot parse so one bad row can never make the declaration reconcile
376
+ * destructive. A freshly typed name is exactly such a row, so without this step
377
+ * a new grid would be silently discarded at the moment of creation.
378
+ */
379
+ /** Canvas and cadence a grid starts life with, until the layout editor changes them. */
380
+ var DEFAULT_WIDTH = 1920;
381
+ var DEFAULT_HEIGHT = 1080;
382
+ var DEFAULT_FPS = 10;
383
+ function nonEmptyString(value) {
384
+ if (typeof value !== "string") return null;
385
+ const trimmed = value.trim();
386
+ return trimmed.length > 0 ? trimmed : null;
387
+ }
388
+ function positiveInt(value, fallback) {
389
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
390
+ }
391
+ /**
392
+ * @param mintId a UUID factory — injected so the normalization is testable
393
+ * without reaching for `crypto`.
394
+ */
395
+ function normalizeGridRows(raw, mintId) {
396
+ let changed = false;
397
+ const rows = [];
398
+ for (const row of raw) {
399
+ const name = nonEmptyString(row["name"]);
400
+ if (name === null) {
401
+ changed = true;
402
+ continue;
403
+ }
404
+ const id = nonEmptyString(row["id"]) ?? mintId();
405
+ const cameraStableId = nonEmptyString(row["cameraStableId"]) ?? newGridCameraStableId(id);
406
+ const normalized = {
407
+ ...row,
408
+ id,
409
+ cameraStableId,
410
+ name,
411
+ enabled: typeof row["enabled"] === "boolean" ? row["enabled"] : true,
412
+ width: positiveInt(row["width"], DEFAULT_WIDTH),
413
+ height: positiveInt(row["height"], DEFAULT_HEIGHT),
414
+ fps: positiveInt(row["fps"], DEFAULT_FPS),
415
+ cells: Array.isArray(row["cells"]) ? row["cells"] : []
416
+ };
417
+ if (!changed) changed = Object.keys(normalized).some((key) => normalized[key] !== row[key]);
418
+ rows.push(normalized);
419
+ }
420
+ return {
421
+ rows,
422
+ changed
423
+ };
424
+ }
425
+ //#endregion
426
+ //#region src/builtins/camera-grid/grid-activity-mirror.ts
427
+ /**
428
+ * What a grid says about ITSELF, kept from what its sources said.
429
+ *
430
+ * ## Why the grid answers at all
431
+ *
432
+ * A grid is a camera, and the viewer already knows how to light a camera: the
433
+ * motion ring keys off `motion.on-motion-changed` filtered by `deviceId`, the
434
+ * audio one off `pipeline.audio-inference-result`. So the grid does not need a
435
+ * new channel, a new cap or a line of app code — it needs to answer those
436
+ * questions about its own device id. The operator set both rules: motion is on
437
+ * if AT LEAST ONE source has it, and the audio level is the LOUDEST of them.
438
+ *
439
+ * It is derived from the SOURCES' events and never from the composed picture.
440
+ * Analysing the composite would be a second motion authority for cameras that
441
+ * already have one, and a decode this addon does not pay today.
442
+ *
443
+ * ## The falling edge is the whole difficulty
444
+ *
445
+ * Bus events are telemetry and may be dropped (D8/D11). A lost `detected:
446
+ * false` would leave a grid lit for ever, and the grid has no phase machine to
447
+ * produce a falling edge of its own — a real camera's comes from the pipeline
448
+ * runner, which a grid deliberately does not run.
449
+ *
450
+ * So a source's motion is remembered WITH ITS TIME and expires on its own. That
451
+ * is D49's shape: in-memory state refreshed off the event path, never a gate
452
+ * that re-reads something fallible in order to decide. A dropped clear costs a
453
+ * ring that stays lit until the expiry instead of for ever, and a subject that
454
+ * is genuinely still there keeps renewing it.
455
+ *
456
+ * The expiry is `MOTION_CLOSE_AFTER_MS`, imported and not re-spelled: it is the
457
+ * system's one answer to "how long after the last push is a camera still
458
+ * moving", and a second number here would be a second authority disagreeing
459
+ * with the first on exactly the cameras that make up the grid.
460
+ */
461
+ /**
462
+ * How long an audio reading counts as current.
463
+ *
464
+ * The analyzer emits one per window per camera, so a source that has gone quiet
465
+ * simply stops arriving — there is no "silence" event to wait for. Without a
466
+ * window the loudest reading of the day would be the grid's level for ever.
467
+ * Chosen to span several analysis windows so an ordinary gap does not blink the
468
+ * level away, and to be far shorter than a person notices a stale ring.
469
+ */
470
+ var AUDIO_FRESH_MS = 5e3;
471
+ var GridActivityMirror = class {
472
+ motion = /* @__PURE__ */ new Map();
473
+ audio = /* @__PURE__ */ new Map();
474
+ lastDetectedAt = null;
475
+ /**
476
+ * One source's motion push. `detected: false` is as important as `true`.
477
+ *
478
+ * `lastDetectedAt` moves only on a source's RISING edge — the source was not
479
+ * moving, or its last `true` had expired. A source's pushes include a
480
+ * heartbeat (the bridge's sustain ticks, every `true` a camera re-sends while
481
+ * a subject stays), and moving the stamp on each one made the grid's
482
+ * `lastDetectedAt` "the last tick of any cell" while every camera's is its
483
+ * last effective RISE (D696): the viewer's Motion order then ranked the grid
484
+ * above the very cells it shows (2026-10-06).
485
+ */
486
+ noteMotion(sourceDeviceId, detected, atMs) {
487
+ const prev = this.motion.get(sourceDeviceId);
488
+ const wasMoving = prev !== void 0 && prev.detected && atMs - prev.atMs <= 15e3;
489
+ this.motion.set(sourceDeviceId, {
490
+ detected,
491
+ atMs
492
+ });
493
+ if (detected && !wasMoving) this.lastDetectedAt = Math.max(this.lastDetectedAt ?? 0, atMs);
494
+ }
495
+ /** One source's audio window. `dbfs` is the level, on the analyzer's scale. */
496
+ noteAudio(sourceDeviceId, dbfs, atMs) {
497
+ this.audio.set(sourceDeviceId, {
498
+ dbfs,
499
+ atMs
500
+ });
501
+ }
502
+ /**
503
+ * Drop every source this grid no longer composes.
504
+ *
505
+ * A cell removed while its camera was moving would otherwise hold the grid
506
+ * lit until the expiry, for a picture the source is not even in.
507
+ */
508
+ keepOnly(sourceDeviceIds) {
509
+ const keep = new Set(sourceDeviceIds);
510
+ const motionIds = Array.from(this.motion.keys());
511
+ const audioIds = Array.from(this.audio.keys());
512
+ for (const id of motionIds) if (!keep.has(id)) this.motion.delete(id);
513
+ for (const id of audioIds) if (!keep.has(id)) this.audio.delete(id);
514
+ }
515
+ /** At least one source moving, as of `nowMs`. */
516
+ motionAt(nowMs) {
517
+ let detected = false;
518
+ for (const state of this.motion.values()) {
519
+ if (!state.detected) continue;
520
+ if (nowMs - state.atMs > 15e3) continue;
521
+ detected = true;
522
+ break;
523
+ }
524
+ return {
525
+ detected,
526
+ lastDetectedAt: this.lastDetectedAt
527
+ };
528
+ }
529
+ /**
530
+ * The loudest CURRENT reading, or `null` when nothing fresh has been heard.
531
+ *
532
+ * Null and not `-Infinity`: "nobody has reported a level" is a different
533
+ * answer from "it is silent", and a number here would have the viewer draw a
534
+ * level for a grid whose sources are not being analysed at all.
535
+ */
536
+ loudestAt(nowMs) {
537
+ let loudest = null;
538
+ for (const state of this.audio.values()) {
539
+ if (nowMs - state.atMs > AUDIO_FRESH_MS) continue;
540
+ if (loudest === null || state.dbfs > loudest) loudest = state.dbfs;
541
+ }
542
+ return loudest;
543
+ }
544
+ };
545
+ //#endregion
546
+ //#region src/builtins/camera-grid/grid-detection-mapping.ts
547
+ /**
548
+ * Where this detection lands on the canvas — once per cell that shows it.
549
+ *
550
+ * Empty is a real answer: the subject is in a part of the source this grid does
551
+ * not display, or the frame arrived with no size to measure against. Neither is
552
+ * a reason to guess.
553
+ */
554
+ function mapDetectionToCanvas(input) {
555
+ const { width: frameW, height: frameH } = input.sourceFrame;
556
+ if (frameW <= 0 || frameH <= 0) return [];
557
+ const left = input.bbox.x / frameW;
558
+ const top = input.bbox.y / frameH;
559
+ const right = (input.bbox.x + input.bbox.width) / frameW;
560
+ const bottom = (input.bbox.y + input.bbox.height) / frameH;
561
+ const out = [];
562
+ for (const { source, cell } of input.cells) {
563
+ if (source.width <= 0 || source.height <= 0) continue;
564
+ const l = Math.max(left, source.x);
565
+ const t = Math.max(top, source.y);
566
+ const r = Math.min(right, source.x + source.width);
567
+ const b = Math.min(bottom, source.y + source.height);
568
+ if (r <= l || b <= t) continue;
569
+ const cx = (l - source.x) / source.width;
570
+ const cy = (t - source.y) / source.height;
571
+ const cw = (r - l) / source.width;
572
+ const ch = (b - t) / source.height;
573
+ out.push({
574
+ x: (cell.x + cx * cell.width) * input.canvas.width,
575
+ y: (cell.y + cy * cell.height) * input.canvas.height,
576
+ width: cw * cell.width * input.canvas.width,
577
+ height: ch * cell.height * input.canvas.height
578
+ });
579
+ }
580
+ return out;
581
+ }
582
+ //#endregion
583
+ //#region src/builtins/camera-grid/grid-activity.ts
584
+ /**
585
+ * The grid's own motion / audio / detection, forwarded from its sources.
586
+ *
587
+ * ## Why the grid speaks a camera's language instead of a new one
588
+ *
589
+ * The operator asked for the grid's tile to light up in the viewer exactly as a
590
+ * camera's card does, with NO app change. The app already knows how: it filters
591
+ * `motion.on-motion-changed` by `deviceId` for the motion ring,
592
+ * `pipeline.audio-inference-result` for the audio one, and `detection.result`
593
+ * for the detection one. So the grid answers those three questions about its
594
+ * own device id, in the same shapes. Nothing new is invented, and nothing in
595
+ * the viewer is touched.
596
+ *
597
+ * The rules are the operator's: motion if AT LEAST ONE source has it, and the
598
+ * LOUDEST source's level for audio.
599
+ *
600
+ * ## What speaking a camera's language costs, and why it is safe here
601
+ *
602
+ * Those categories have other listeners, and emitting on them makes the grid a
603
+ * motion source for the whole system. Checked, one by one, before shipping:
604
+ * the recorder's event capture, the HomeKit and Alexa exports and the Home
605
+ * Assistant export are all per-device and do nothing until an operator enables
606
+ * them for this camera — and if an operator DOES export a grid to HomeKit, a
607
+ * grid reporting motion is correct, not a surprise.
608
+ *
609
+ * The one listener with no gate of its own was `pipeline-analytics`, which
610
+ * would have opened a motion EPISODE per grid, duplicating the rows its sources
611
+ * already write. Its gate turned out to be the `pipeline-analytics` WRAPPER
612
+ * BINDING, so the answer is the one the operator gave: a derived camera is
613
+ * created with the analytics wrappers OFF (`grid-analytics-defaults.ts`).
614
+ * That is a binding, not a new flag, so an operator who wants a grid analysed
615
+ * can simply turn it back on.
616
+ *
617
+ * ## Detection carries boxes whether or not anyone wanted them
618
+ *
619
+ * `detection.result` is the same event the viewer draws BOXES from, so a grid
620
+ * that reports detections reports boxes. Sending the source's own pixel box
621
+ * would draw it against the composed canvas at confidently wrong coordinates,
622
+ * so every box is carried through the cell geometry first
623
+ * (`grid-detection-mapping.ts`) and lands where the subject actually is.
624
+ */
625
+ /**
626
+ * One mirror per grid, and the emission that follows an update.
627
+ *
628
+ * Deliberately NOT one mirror per source: the question is always "is THIS grid
629
+ * lit", and a source shared by two grids answers it twice, differently, because
630
+ * the other cells differ.
631
+ */
632
+ var GridActivityForwarder = class {
633
+ deps;
634
+ mirrors = /* @__PURE__ */ new Map();
635
+ constructor(deps) {
636
+ this.deps = deps;
637
+ }
638
+ /** A source camera's motion push. */
639
+ onSourceMotion(sourceDeviceId, detected, atMs) {
640
+ for (const grid of this.deps.gridsForSource(sourceDeviceId)) {
641
+ const mirror = this.mirrorFor(grid);
642
+ const before = mirror.motionAt(atMs).detected;
643
+ mirror.noteMotion(sourceDeviceId, detected, atMs);
644
+ const after = mirror.motionAt(atMs);
645
+ if (after.detected === before) continue;
646
+ this.emitMotion(grid.deviceId, after, atMs);
647
+ }
648
+ }
649
+ /** A source camera's audio window. */
650
+ onSourceAudio(sourceDeviceId, dbfs, atMs) {
651
+ for (const grid of this.deps.gridsForSource(sourceDeviceId)) {
652
+ const mirror = this.mirrorFor(grid);
653
+ mirror.noteAudio(sourceDeviceId, dbfs, atMs);
654
+ const loudest = mirror.loudestAt(atMs);
655
+ if (loudest === null) continue;
656
+ this.emitAudio(grid.deviceId, loudest, atMs);
657
+ }
658
+ }
659
+ /** A source camera's detection frame, with its boxes in SOURCE pixels. */
660
+ onSourceDetections(frame) {
661
+ for (const grid of this.deps.gridsForSource(frame.deviceId)) {
662
+ const cells = grid.cellsForSource(frame.deviceId);
663
+ if (cells.length === 0) continue;
664
+ const detections = [];
665
+ for (const detection of frame.detections) for (const bbox of mapDetectionToCanvas({
666
+ bbox: detection.bbox,
667
+ sourceFrame: {
668
+ width: frame.width,
669
+ height: frame.height
670
+ },
671
+ canvas: grid.canvas,
672
+ cells
673
+ })) {
674
+ const { refinedBbox: _refined, mask: _mask, ...rest } = detection;
675
+ detections.push({
676
+ ...rest,
677
+ bbox
678
+ });
679
+ }
680
+ if (detections.length === 0) continue;
681
+ this.emitDetections(grid, frame, detections);
682
+ }
683
+ }
684
+ /** The grid's own motion answer, for `motion.getStatus`. */
685
+ motionStatusFor(deviceId, nowMs) {
686
+ return this.mirrors.get(deviceId)?.motionAt(nowMs) ?? {
687
+ detected: false,
688
+ lastDetectedAt: null
689
+ };
690
+ }
691
+ /** Drop the mirror of a grid that no longer exists. */
692
+ forget(deviceId) {
693
+ this.mirrors.delete(deviceId);
694
+ }
695
+ mirrorFor(grid) {
696
+ let mirror = this.mirrors.get(grid.deviceId);
697
+ if (mirror === void 0) {
698
+ mirror = new GridActivityMirror();
699
+ this.mirrors.set(grid.deviceId, mirror);
700
+ }
701
+ mirror.keepOnly(grid.sourceDeviceIds);
702
+ return mirror;
703
+ }
704
+ source(deviceId) {
705
+ return {
706
+ type: "device",
707
+ id: deviceId,
708
+ addonId: this.deps.addonId,
709
+ deviceId
710
+ };
711
+ }
712
+ emitMotion(deviceId, state, atMs) {
713
+ const payload = {
714
+ deviceId,
715
+ detected: state.detected,
716
+ timestamp: atMs,
717
+ source: "onboard"
718
+ };
719
+ this.deps.eventBus.emit(createEvent(EventCategory.MotionOnMotionChanged, this.source(deviceId), payload));
720
+ this.deps.logger.debug("camera grid: motion forwarded", {
721
+ tags: { deviceId },
722
+ meta: { detected: state.detected }
723
+ });
724
+ }
725
+ emitAudio(deviceId, dbfs, atMs) {
726
+ const payload = {
727
+ deviceId,
728
+ frame: {
729
+ kind: "audio-window",
730
+ windowId: `grid-${String(deviceId)}-${String(atMs)}`,
731
+ deviceId,
732
+ timestamp: atMs,
733
+ startMs: atMs,
734
+ endMs: atMs,
735
+ level: {
736
+ rms: 0,
737
+ dbfs
738
+ },
739
+ detections: []
740
+ },
741
+ nodeId: "hub"
742
+ };
743
+ this.deps.eventBus.emit(createEvent(EventCategory.PipelineAudioInferenceResult, this.source(deviceId), payload));
744
+ }
745
+ emitDetections(grid, sourceFrame, detections) {
746
+ const payload = {
747
+ frame: {
748
+ kind: "frame",
749
+ frameId: `grid-${String(grid.deviceId)}-${sourceFrame.frameId}`,
750
+ deviceId: grid.deviceId,
751
+ timestamp: sourceFrame.timestamp,
752
+ width: grid.canvas.width,
753
+ height: grid.canvas.height,
754
+ detections
755
+ },
756
+ analysisResults: []
757
+ };
758
+ this.deps.eventBus.emit(createEvent(EventCategory.DetectionResult, this.source(grid.deviceId), payload));
759
+ }
760
+ };
761
+ //#endregion
762
+ //#region src/builtins/camera-grid/grid-wire-format.ts
763
+ /** What the relay answers with, and what the sampler must demux. */
764
+ var GRID_WIRE_CONTENT_TYPE = "video/x-flv";
765
+ /** `/grid/<instanceId>/<profile>.flv`. */
766
+ var GRID_WIRE_PATH_SUFFIX = ".flv";
767
+ /**
768
+ * How the broker must ingest it: `pull-flv` is documented as ALWAYS read
769
+ * through the ffmpeg source reader with `-c copy`. `pull-http` would have been
770
+ * the intuitive choice and means MJPEG in this broker — it answers with
771
+ * `HTTP_MJPEG_H264_OUTPUT_ARGS` and re-encodes an already-encoded H.264.
772
+ */
773
+ var GRID_WIRE_STREAM_KIND = "pull-flv";
774
+ //#endregion
775
+ //#region src/builtins/camera-grid/grid-frame-sample.ts
776
+ /**
777
+ * ONE JPEG out of a composition that is already running.
778
+ *
779
+ * ## Why this is not the ffmpeg primitive
780
+ *
781
+ * `FfmpegProcess` + `buildFfmpegArgs` own the STREAM job: a long-lived encode
782
+ * with a hardware cascade, a first-data deadline and a bounded restart. This is
783
+ * the other kind — run-to-completion, no encode plan worth sharing, finishes or
784
+ * is killed — which is the class `scripts/check-ffmpeg-primitive.ts` already
785
+ * carves out by name for `recorder/still/still-frame-service.ts` ("single-JPEG
786
+ * still grab") and `builtins/snapshot/snapshot.addon.ts` ("keyframe snapshot
787
+ * grab"). It is the same job as those two, on a pipe instead of a URL.
788
+ *
789
+ * ## Why a pipe and not the grid's own URL
790
+ *
791
+ * Dialling the relay would be a CONSUMER, and a consumer of a cold grid starts
792
+ * the composition — N broker acquisitions for a thumbnail, which is the one
793
+ * thing the operator ruled out. Reading the bytes of a session that is ALREADY
794
+ * running costs nothing: the child is up, the packets are being produced, and
795
+ * this just takes a copy of them.
796
+ *
797
+ * Bounded on both ends. A composition whose first key frame is far away must
798
+ * not hold an ffmpeg (or this promise) open for ever, so the grab has a
799
+ * deadline and the child is killed at it — a snapshot that did not arrive is
800
+ * `null`, and `null` is a real answer.
801
+ */
802
+ /** Long enough for a 2 s GOP plus a probe, short enough that a list does not hang. */
803
+ var DEFAULT_TIMEOUT_MS = 8e3;
804
+ /** JPEG quality. 4 is visually clean at thumbnail and list sizes and ~40 KB at 1080p. */
805
+ var JPEG_QUALITY = "4";
806
+ var GridFrameSampler = class {
807
+ options;
808
+ constructor(options) {
809
+ this.options = options;
810
+ }
811
+ /**
812
+ * @returns the JPEG, or `null` — a grab that produced nothing, could not be
813
+ * attached, or ran out of time. Every one of those is logged with the
814
+ * device: a branch that accepts the request and produces nothing must say so.
815
+ */
816
+ async sample(deviceId, source) {
817
+ const spawnFn = this.options.spawnFn ?? spawn;
818
+ const timeoutMs = this.options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
819
+ const child = spawnFn(this.options.binaryPath, [
820
+ "-hide_banner",
821
+ "-loglevel",
822
+ "error",
823
+ "-f",
824
+ "flv",
825
+ "-i",
826
+ "pipe:0",
827
+ "-frames:v",
828
+ "1",
829
+ "-q:v",
830
+ JPEG_QUALITY,
831
+ "-f",
832
+ "mjpeg",
833
+ "pipe:1"
834
+ ], { stdio: [
835
+ "pipe",
836
+ "pipe",
837
+ "pipe"
838
+ ] });
839
+ const chunks = [];
840
+ child.stdout?.on("data", (chunk) => chunks.push(chunk));
841
+ child.stderr?.on("data", () => {});
842
+ const hold = source.attach((chunk) => {
843
+ if (child.stdin?.writable === true) child.stdin.write(chunk);
844
+ });
845
+ if (hold === null) {
846
+ child.kill("SIGKILL");
847
+ this.options.logger.warn("camera grid: could not attach to sample a frame", { tags: { deviceId } });
848
+ return null;
849
+ }
850
+ const timer = setTimeout(() => {
851
+ child.kill("SIGKILL");
852
+ }, timeoutMs);
853
+ timer.unref?.();
854
+ try {
855
+ await new Promise((resolve) => {
856
+ child.once("exit", () => resolve());
857
+ child.once("error", () => resolve());
858
+ });
859
+ } finally {
860
+ clearTimeout(timer);
861
+ hold.close();
862
+ try {
863
+ child.stdin?.end();
864
+ } catch (error) {
865
+ this.options.logger.debug("camera grid: the frame grab stdin refused to close", {
866
+ tags: { deviceId },
867
+ meta: { error: errMsg(error) }
868
+ });
869
+ }
870
+ }
871
+ const jpeg = Buffer.concat(chunks);
872
+ if (jpeg.length === 0) {
873
+ this.options.logger.warn("camera grid: the frame grab produced no bytes", {
874
+ tags: { deviceId },
875
+ meta: { timeoutMs }
876
+ });
877
+ return null;
878
+ }
879
+ return jpeg;
880
+ }
881
+ };
882
+ //#endregion
883
+ //#region src/builtins/camera-grid/grid-last-frame-store.ts
884
+ /**
885
+ * The last COMPOSED frame per grid, on disk, so it outlives the process.
886
+ *
887
+ * ## Why not `@camstack/server/system`'s SnapshotDurableStore
888
+ *
889
+ * Because the shape is right and the reach is not: that class lives under
890
+ * `builtins/snapshot/` and `@camstack/server/system` does not export it — a builtin's
891
+ * internals are not an addon-facing module, and an addon that reached into one
892
+ * would be importing another addon, which this repo forbids outright. What is
893
+ * shared is the REASONING, and it is worth restating rather than linking,
894
+ * because the failure it prevents here is the same one measured on 2026-09-17:
895
+ * the cache is RAM, three server updates emptied it, and a camera that cannot
896
+ * be asked for a fresh frame showed the courtesy card all morning with nothing
897
+ * broken.
898
+ *
899
+ * A grid is that camera by construction. It has no fresh frame whenever nobody
900
+ * is watching it, which is most of the time and is the entire point of D519.
901
+ *
902
+ * ## Shape
903
+ *
904
+ * One file per device under `ctx.dataDir` — `<nodeDataDir>/addons-data/
905
+ * camera-grid`, which this addon owns exclusively — overwritten rather than
906
+ * appended: what is wanted is A recent frame, not a history. A history here
907
+ * would grow without a reaper and compete with the recordings for the disk.
908
+ *
909
+ * Writes are THROTTLED. A composition emits 10 frames a second and a process
910
+ * restarts a few times a week; persisting every frame buys nothing and costs a
911
+ * write per frame.
912
+ *
913
+ * NOTHING here throws. The caller already has its picture; persistence is a
914
+ * bonus for the NEXT boot, and a disk that refuses must never cost a snapshot
915
+ * that succeeded. A frame that cannot be read is reported ABSENT — absent is
916
+ * the truth, and the courtesy card is the correct answer to it.
917
+ */
918
+ /** One recent frame is the value; a newer one is not worth the disk. */
919
+ var DEFAULT_MIN_INTERVAL_MS = 6e4;
920
+ /** Its own subdirectory, so the addon's other state is never mistaken for a frame. */
921
+ var SUBDIR = "last-frame";
922
+ /**
923
+ * How long the caller may be made to wait on the disk, for ANY of it.
924
+ *
925
+ * A bonus that costs a snapshot is not a bonus. One second is far more than a
926
+ * healthy local write needs and far less than a viewer will sit through.
927
+ */
928
+ var DEFAULT_DEADLINE_MS = 1e3;
929
+ var GridLastFrameFileStore = class {
930
+ dir;
931
+ minIntervalMs;
932
+ now;
933
+ fs;
934
+ deadlineMs;
935
+ logger;
936
+ /** Last write per device, so the throttle survives without touching disk. */
937
+ lastWriteMs = /* @__PURE__ */ new Map();
938
+ constructor(options) {
939
+ this.dir = join(options.dataDir, SUBDIR);
940
+ this.minIntervalMs = options.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS;
941
+ this.now = options.now ?? (() => Date.now());
942
+ this.fs = options.fs ?? promises;
943
+ this.deadlineMs = options.deadlineMs ?? DEFAULT_DEADLINE_MS;
944
+ this.logger = options.logger;
945
+ }
946
+ async put(deviceId, jpeg) {
947
+ if (jpeg.length === 0) return;
948
+ const at = this.now();
949
+ const previous = this.lastWriteMs.get(deviceId);
950
+ if (previous !== void 0 && at - previous < this.minIntervalMs) return;
951
+ if (await this.bounded(deviceId, "keep the composed frame", false, async () => {
952
+ await this.fs.mkdir(this.dir, { recursive: true });
953
+ const target = this.pathFor(deviceId);
954
+ const staging = `${target}.writing`;
955
+ await this.fs.writeFile(staging, jpeg);
956
+ await this.fs.rename(staging, target);
957
+ return true;
958
+ })) this.lastWriteMs.set(deviceId, at);
959
+ }
960
+ async get(deviceId) {
961
+ return this.bounded(deviceId, "read the kept frame", null, async () => {
962
+ const jpeg = await this.fs.readFile(this.pathFor(deviceId));
963
+ return jpeg.length > 0 ? jpeg : null;
964
+ });
965
+ }
966
+ /**
967
+ * Run one piece of disk work, and answer `fallback` whether it REFUSES or
968
+ * never answers at all.
969
+ *
970
+ * The `try/catch` this replaces covered only the first of those. Measured on
971
+ * the CI runner (Linux, root, in a container) 2026-09-20: `fs.mkdir` with
972
+ * `recursive: true` under a parent that cannot hold a directory never
973
+ * settles — procfs answers ENOENT and Node's recursive mkdir retries the
974
+ * child forever — and `put` is AWAITED on the snapshot answer path, so the
975
+ * grid's snapshot RPC never answered either. An exception is not the only
976
+ * way the disk says no.
977
+ */
978
+ async bounded(deviceId, what, fallback, work) {
979
+ let timer = null;
980
+ const expiry = new Promise((resolve) => {
981
+ timer = setTimeout(() => resolve({ settled: false }), this.deadlineMs);
982
+ timer.unref();
983
+ });
984
+ try {
985
+ const outcome = await Promise.race([work().then((value) => ({
986
+ settled: true,
987
+ value
988
+ })), expiry]);
989
+ if (!outcome.settled) {
990
+ this.logger.warn(`camera grid: the disk did not ${what} within its deadline`, {
991
+ tags: { deviceId },
992
+ meta: { deadlineMs: this.deadlineMs }
993
+ });
994
+ return fallback;
995
+ }
996
+ return outcome.value;
997
+ } catch (error) {
998
+ this.logger.warn(`camera grid: the disk could not ${what}`, {
999
+ tags: { deviceId },
1000
+ meta: { error: errMsg(error) }
1001
+ });
1002
+ return fallback;
1003
+ } finally {
1004
+ if (timer !== null) clearTimeout(timer);
1005
+ }
1006
+ }
1007
+ pathFor(deviceId) {
1008
+ return join(this.dir, `${String(deviceId)}.jpg`);
1009
+ }
1010
+ };
1011
+ //#endregion
1012
+ //#region src/builtins/camera-grid/grid-canvas.ts
1013
+ /** Bytes one yuv420p frame of this size occupies. */
1014
+ function yuv420pSize(width, height) {
1015
+ return width * height + 2 * (width / 2) * (height / 2);
1016
+ }
1017
+ /**
1018
+ * Round DOWN to even.
1019
+ *
1020
+ * Down and not nearest: a tile that rounded UP would claim a row of samples the
1021
+ * decoder was never asked to produce, and the copy would either overrun or be
1022
+ * refused at the moment the picture is wanted.
1023
+ */
1024
+ function evenDown(value) {
1025
+ return Math.max(0, Math.floor(value / 2) * 2);
1026
+ }
1027
+ var GridCanvas = class {
1028
+ width;
1029
+ height;
1030
+ buffer;
1031
+ lumaBytes;
1032
+ chromaBytes;
1033
+ constructor(width, height) {
1034
+ this.width = width;
1035
+ this.height = height;
1036
+ this.lumaBytes = width * height;
1037
+ this.chromaBytes = width / 2 * (height / 2);
1038
+ this.buffer = Buffer.alloc(yuv420pSize(width, height));
1039
+ this.clear();
1040
+ }
1041
+ /**
1042
+ * Legible black — Y 0, chroma 128 (neutral).
1043
+ *
1044
+ * `Buffer.alloc` already zeroes, and zeroed CHROMA is not black: it is a
1045
+ * strong green. A cell nobody has filled yet has to look like an empty cell,
1046
+ * not like a fault.
1047
+ */
1048
+ clear() {
1049
+ this.buffer.fill(0, 0, this.lumaBytes);
1050
+ this.buffer.fill(128, this.lumaBytes);
1051
+ }
1052
+ /**
1053
+ * Copy one decoded tile in at `origin`.
1054
+ *
1055
+ * Returns false — never throws, never writes a partial tile — when the tile
1056
+ * does not fit, is the wrong size for the dimensions it claims, or sits on an
1057
+ * odd boundary. This runs on the output tick, so a bad frame from one source
1058
+ * must cost that source's rectangle and nothing else.
1059
+ */
1060
+ blit(tile, size, origin) {
1061
+ if (!isEven(size.width) || !isEven(size.height)) return false;
1062
+ if (!isEven(origin.x) || !isEven(origin.y)) return false;
1063
+ if (size.width <= 0 || size.height <= 0) return false;
1064
+ if (origin.x < 0 || origin.y < 0) return false;
1065
+ if (origin.x + size.width > this.width) return false;
1066
+ if (origin.y + size.height > this.height) return false;
1067
+ if (tile.length !== yuv420pSize(size.width, size.height)) return false;
1068
+ for (let row = 0; row < size.height; row += 1) {
1069
+ const from = row * size.width;
1070
+ const to = (origin.y + row) * this.width + origin.x;
1071
+ tile.copy(this.buffer, to, from, from + size.width);
1072
+ }
1073
+ const tileLuma = size.width * size.height;
1074
+ const tileChroma = size.width / 2 * (size.height / 2);
1075
+ const halfW = size.width / 2;
1076
+ const halfH = size.height / 2;
1077
+ const canvasHalfW = this.width / 2;
1078
+ for (let plane = 0; plane < 2; plane += 1) {
1079
+ const tileBase = tileLuma + plane * tileChroma;
1080
+ const canvasBase = this.lumaBytes + plane * this.chromaBytes;
1081
+ for (let row = 0; row < halfH; row += 1) {
1082
+ const from = tileBase + row * halfW;
1083
+ const to = canvasBase + (origin.y / 2 + row) * canvasHalfW + origin.x / 2;
1084
+ tile.copy(this.buffer, to, from, from + halfW);
1085
+ }
1086
+ }
1087
+ return true;
1088
+ }
1089
+ };
1090
+ function isEven(value) {
1091
+ return Number.isInteger(value) && value % 2 === 0;
1092
+ }
1093
+ //#endregion
1094
+ //#region src/builtins/camera-grid/grid-canvas-derivation.ts
1095
+ /**
1096
+ * The canvas is a RESULT, not a field.
1097
+ *
1098
+ * ## Why the operator stopped typing it
1099
+ *
1100
+ * A grid's resolution used to be two numbers in the editor, beside FPS. They
1101
+ * looked harmless and were not: that number silently decided how much the
1102
+ * composite cost and how sharp it was. An operator typing 1920x1080 was, without
1103
+ * being told, committing the hub to reading two 4 MP streams — or, with the
1104
+ * rule before it, to upscaling a 640x360 sub-stream by 3x. Neither is a thing
1105
+ * anyone can be expected to work out from a text field.
1106
+ *
1107
+ * ## What it is derived from
1108
+ *
1109
+ * The operator draws two rectangles per camera — which part of the source to
1110
+ * take, and where it lands — and both are fractions, so nothing is pixels yet.
1111
+ * Exactly one number is missing: how many pixels the whole canvas is worth.
1112
+ *
1113
+ * A cell has `sourceResolution x crop` REAL pixels behind it. Showing them 1:1
1114
+ * neither invents nor discards anything, so the cell should be exactly that
1115
+ * many pixels — and since the cell is a fraction `f` of the canvas, the canvas
1116
+ * it implies is `real / f`. Each cell proposes one, and the LARGEST wins: the
1117
+ * hungriest cell is served 1:1 and the others scale down by a hair, never up.
1118
+ *
1119
+ * Gaps change nothing. Cells need not cover the canvas, and an uncovered part
1120
+ * is background — it has no pixels to propose.
1121
+ *
1122
+ * ## One per profile
1123
+ *
1124
+ * A source is a different size at each profile, so each profile derives its own
1125
+ * canvas: a grid's `low` composes its sources' `low` onto the canvas their
1126
+ * `low` implies. That is what makes the three outputs 1:1 with what they are
1127
+ * made of, and what lets a viewer's adaptive pick a rung without the grid
1128
+ * needing to know it exists.
1129
+ */
1130
+ /**
1131
+ * What an encoder will take. Not a taste: `libx264` refuses beyond 8192 in
1132
+ * either axis, and a canvas that large is a composition nobody can decode
1133
+ * anyway. Reached only by a cell that shows a sliver of a source at full
1134
+ * canvas width, which is a layout, not a mistake — so it is CLAMPED rather
1135
+ * than refused, and clamped in both axes together so the picture the operator
1136
+ * drew keeps its shape.
1137
+ */
1138
+ var MAX_CANVAS_WIDTH = 7680;
1139
+ var MAX_CANVAS_HEIGHT = 4320;
1140
+ /** Below this a composition is not a cheaper picture, it is no picture. */
1141
+ var MIN_CANVAS_EDGE = 160;
1142
+ /**
1143
+ * The canvas these cells imply, or `null` when they imply none.
1144
+ *
1145
+ * `null` for a grid with no cells — the normal freshly-created state — and for
1146
+ * a layout whose every rectangle is degenerate. Both are "there is no picture
1147
+ * to size", which the caller turns into "this profile is not on offer" rather
1148
+ * than into a guess.
1149
+ */
1150
+ function deriveGridCanvas(cells) {
1151
+ let width = 0;
1152
+ let height = 0;
1153
+ for (const entry of cells) {
1154
+ if (entry.cell.width <= 0 || entry.cell.height <= 0) continue;
1155
+ if (entry.sourceSize.width <= 0 || entry.sourceSize.height <= 0) continue;
1156
+ const realWidth = entry.sourceSize.width * entry.source.width;
1157
+ const realHeight = entry.sourceSize.height * entry.source.height;
1158
+ if (realWidth <= 0 || realHeight <= 0) continue;
1159
+ width = Math.max(width, realWidth / entry.cell.width);
1160
+ height = Math.max(height, realHeight / entry.cell.height);
1161
+ }
1162
+ if (width <= 0 || height <= 0) return null;
1163
+ const overshoot = Math.max(width / MAX_CANVAS_WIDTH, height / MAX_CANVAS_HEIGHT, 1);
1164
+ const factor = Math.max(MIN_CANVAS_EDGE / width, MIN_CANVAS_EDGE / height, 1) / overshoot;
1165
+ return {
1166
+ width: Math.max(2, evenDown(width * factor)),
1167
+ height: Math.max(2, evenDown(height * factor))
1168
+ };
1169
+ }
1170
+ //#endregion
1171
+ //#region src/builtins/camera-grid/grid-profiles.ts
1172
+ /**
1173
+ * One id per profile, for every grid, forever.
1174
+ *
1175
+ * D519's reason is what keeps `high`'s id bare: a newly-spelled id mints a
1176
+ * second cam-stream and orphans whatever profile assignment the operator had
1177
+ * made. `grid` was `high` on the live hub before any of this and still is.
1178
+ */
1179
+ var GRID_CAM_STREAM_ID = "grid";
1180
+ /** Every profile a grid can compose, in descending quality. */
1181
+ var GRID_PROFILES = [
1182
+ "high",
1183
+ "mid",
1184
+ "low"
1185
+ ];
1186
+ /** The cam-stream id a grid publishes for one profile. */
1187
+ function gridCamStreamId(profile) {
1188
+ return profile === "high" ? GRID_CAM_STREAM_ID : `${GRID_CAM_STREAM_ID}-${profile}`;
1189
+ }
1190
+ /**
1191
+ * What this grid can honestly publish, per profile, with the canvas or the
1192
+ * refusal.
1193
+ *
1194
+ * Every profile gets a row whether it is offered or not: an absent row says
1195
+ * nothing, and the caller logging a refusal needs the reason more than the
1196
+ * caller publishing an offer needs the offer.
1197
+ */
1198
+ function gridProfilePlans(input) {
1199
+ const sourceDeviceIds = [...new Set(input.cells.map((cell) => cell.deviceId))];
1200
+ const servedBy = /* @__PURE__ */ new Map();
1201
+ for (const deviceId of sourceDeviceIds) servedBy.set(deviceId, input.profilesServedBy(deviceId));
1202
+ return GRID_PROFILES.map((profile) => {
1203
+ if (sourceDeviceIds.length === 0) return {
1204
+ profile,
1205
+ offered: false,
1206
+ missingSources: []
1207
+ };
1208
+ const sizeBySource = /* @__PURE__ */ new Map();
1209
+ const missingSources = [];
1210
+ for (const deviceId of sourceDeviceIds) {
1211
+ const match = (servedBy.get(deviceId) ?? null)?.find((entry) => entry.profile === profile);
1212
+ if (match === void 0 || match.width <= 0 || match.height <= 0) {
1213
+ missingSources.push(deviceId);
1214
+ continue;
1215
+ }
1216
+ sizeBySource.set(deviceId, {
1217
+ width: match.width,
1218
+ height: match.height
1219
+ });
1220
+ }
1221
+ if (missingSources.length > 0) return {
1222
+ profile,
1223
+ offered: false,
1224
+ missingSources
1225
+ };
1226
+ const canvas = deriveGridCanvas(input.cells.map((cell) => ({
1227
+ source: cell.source,
1228
+ cell: cell.cell,
1229
+ sourceSize: sizeBySource.get(cell.deviceId) ?? {
1230
+ width: 0,
1231
+ height: 0
1232
+ }
1233
+ })));
1234
+ if (canvas === null) return {
1235
+ profile,
1236
+ offered: false,
1237
+ missingSources: []
1238
+ };
1239
+ return {
1240
+ profile,
1241
+ offered: true,
1242
+ canvas,
1243
+ published: input.publishedProfiles.includes(profile)
1244
+ };
1245
+ });
1246
+ }
1247
+ //#endregion
1248
+ //#region src/builtins/camera-grid/grid-sentry-sources.ts
1249
+ function gridSourceDial(acquired) {
1250
+ const sentryUrl = acquired.sentryUrl;
1251
+ if (typeof sentryUrl === "string" && sentryUrl.length > 0) return {
1252
+ url: sentryUrl,
1253
+ pipelineKey: acquired.pipelineKey,
1254
+ mode: "sentry"
1255
+ };
1256
+ return {
1257
+ url: acquired.url,
1258
+ pipelineKey: acquired.pipelineKey,
1259
+ mode: "live"
1260
+ };
1261
+ }
1262
+ //#endregion
1263
+ //#region src/builtins/camera-grid/grid-snapshot.ts
1264
+ /**
1265
+ * A grid's snapshot — a frame of the COMPOSITION, never a dial.
1266
+ *
1267
+ * ## The decision, and the two things it rejects
1268
+ *
1269
+ * The operator: *"Lo snapshot possiamo sempre farlo dallo stream sempre, non
1270
+ * c'e' bisogno di comporre gli snapshots"* [we can always take the snapshot from the stream, there is no need to compose the snapshots]. So:
1271
+ *
1272
+ * - **Not composed from source snapshots.** That would be a SECOND compositor,
1273
+ * with its own geometry, its own aspect handling and its own bugs, producing
1274
+ * a picture that differs from the real one in ways nobody would ever notice
1275
+ * until they mattered.
1276
+ * - **Not produced by starting the composition.** The whole of D519 is "a grid
1277
+ * costs nothing when nobody watches". A thumbnail that dials N cameras — and
1278
+ * on a battery camera, wakes one — spends the entire budget of the feature on
1279
+ * a 160-pixel-wide picture in a list.
1280
+ *
1281
+ * ## The three states, all answered
1282
+ *
1283
+ * | state | answer |
1284
+ * | --- | --- |
1285
+ * | a composition is running | one frame sampled out of the bytes it is already emitting |
1286
+ * | nothing running, a frame was kept | that frame — stale, and honest about it |
1287
+ * | nothing running, nothing ever kept | `null`, logged with the reason |
1288
+ *
1289
+ * `null` is the courtesy card, which is the correct picture of "this grid has
1290
+ * never been watched". What it must never be is a reason to dial.
1291
+ *
1292
+ * ## Why this is a NATIVE snapshot provider
1293
+ *
1294
+ * The wrapper's ladder is native-first: a native that produces a frame
1295
+ * short-circuits before the broker frame-grab, and the broker frame-grab is the
1296
+ * thing that would wake the sources. A grid with a stored frame or a live
1297
+ * composition therefore never reaches it. The residual — a grid that has never
1298
+ * once been composed — is documented in D519; it cannot wake a battery camera,
1299
+ * because a grid never dials one live at all (`grid-sentry-sources.ts`).
1300
+ */
1301
+ /**
1302
+ * Which of the three answers applies. Pure, so the rule can be read — and
1303
+ * sabotaged — without a socket, a file or an ffmpeg.
1304
+ */
1305
+ function gridSnapshotAnswerFor(input) {
1306
+ if (input.running) return { kind: "live" };
1307
+ if (input.hasStoredFrame) return { kind: "stored" };
1308
+ return {
1309
+ kind: "none",
1310
+ reason: "never-composed"
1311
+ };
1312
+ }
1313
+ var GridSnapshotSource = class {
1314
+ deps;
1315
+ constructor(deps) {
1316
+ this.deps = deps;
1317
+ }
1318
+ async getSnapshot(deviceId) {
1319
+ const sessions = this.deps.sessionsFor(deviceId);
1320
+ if (sessions.length === 0) return null;
1321
+ const live = sessions.find((session) => session.isRunning()) ?? null;
1322
+ const stored = await this.readStored(deviceId);
1323
+ const answer = gridSnapshotAnswerFor({
1324
+ running: live !== null,
1325
+ hasStoredFrame: stored !== null
1326
+ });
1327
+ if (answer.kind === "live" && live !== null) {
1328
+ const sampled = await this.sample(deviceId, live);
1329
+ if (sampled !== null) {
1330
+ await this.keep(deviceId, sampled);
1331
+ return toImage(sampled);
1332
+ }
1333
+ if (stored !== null) return toImage(stored);
1334
+ this.deps.logger.warn("camera grid: the composition is running but produced no frame, and none was kept", { tags: { deviceId } });
1335
+ return null;
1336
+ }
1337
+ if (answer.kind === "stored" && stored !== null) return toImage(stored);
1338
+ this.deps.logger.warn("camera grid: no frame for this grid — nothing is composing it and none was ever kept", {
1339
+ tags: { deviceId },
1340
+ meta: {
1341
+ reason: "never-composed",
1342
+ compositions: sessions.length
1343
+ }
1344
+ });
1345
+ return null;
1346
+ }
1347
+ async sample(deviceId, session) {
1348
+ try {
1349
+ const jpeg = await this.deps.sampleFrame(session);
1350
+ if (jpeg !== null && jpeg.length > 0) return jpeg;
1351
+ this.deps.logger.warn("camera grid: could not sample a frame from the live composition", { tags: { deviceId } });
1352
+ return null;
1353
+ } catch (error) {
1354
+ this.deps.logger.warn("camera grid: could not sample a frame from the live composition", {
1355
+ tags: { deviceId },
1356
+ meta: { error: errMsg(error) }
1357
+ });
1358
+ return null;
1359
+ }
1360
+ }
1361
+ async readStored(deviceId) {
1362
+ try {
1363
+ const jpeg = await this.deps.store.get(deviceId);
1364
+ return jpeg !== null && jpeg.length > 0 ? jpeg : null;
1365
+ } catch (error) {
1366
+ this.deps.logger.warn("camera grid: the kept frame could not be read", {
1367
+ tags: { deviceId },
1368
+ meta: { error: errMsg(error) }
1369
+ });
1370
+ return null;
1371
+ }
1372
+ }
1373
+ async keep(deviceId, jpeg) {
1374
+ try {
1375
+ await this.deps.store.put(deviceId, jpeg);
1376
+ } catch (error) {
1377
+ this.deps.logger.warn("camera grid: the composed frame could not be kept", {
1378
+ tags: { deviceId },
1379
+ meta: { error: errMsg(error) }
1380
+ });
1381
+ }
1382
+ }
1383
+ };
1384
+ function toImage(jpeg) {
1385
+ return {
1386
+ base64: jpeg.toString("base64"),
1387
+ contentType: "image/jpeg"
1388
+ };
1389
+ }
1390
+ //#endregion
1391
+ //#region src/builtins/camera-grid/grid-stream-relay.ts
1392
+ /**
1393
+ * The loopback HTTP endpoint the broker dials to consume a grid.
1394
+ *
1395
+ * A GET is the demand signal and the transport in one: the connection opening
1396
+ * is the first consumer arriving, and the connection closing is it leaving.
1397
+ * There is no other way to start or stop a composition, which is what makes
1398
+ * "off when nobody watches" true by construction rather than by a policy
1399
+ * somebody has to remember to apply.
1400
+ *
1401
+ * Bound on 127.0.0.1 only. The broker is hub-only and so is this addon
1402
+ * ({@link ../package.json} `placement: hub-only`), so the endpoint never needs
1403
+ * to be reachable from another node — and an MPEG-TS of every camera in the
1404
+ * grid is not something to expose on a LAN interface by accident.
1405
+ */
1406
+ var PATH_PREFIX = "/grid/";
1407
+ var PATH_SUFFIX = GRID_WIRE_PATH_SUFFIX;
1408
+ /** How long a reader may refuse to drain before it is cut. */
1409
+ var SLOW_READER_MS = 5e3;
1410
+ function asProfile(raw) {
1411
+ return GRID_PROFILES.find((profile) => profile === raw) ?? null;
1412
+ }
1413
+ /** `/grid/<instanceId>/<profile>.flv`, or `null` when it is anything else. */
1414
+ function parseGridStreamPath(url) {
1415
+ const path = (url ?? "").split("?")[0] ?? "";
1416
+ if (!path.startsWith(PATH_PREFIX) || !path.endsWith(PATH_SUFFIX)) return null;
1417
+ const raw = path.slice(6, path.length - PATH_SUFFIX.length);
1418
+ const at = raw.lastIndexOf("/");
1419
+ if (at <= 0) return null;
1420
+ const profile = asProfile(raw.slice(at + 1));
1421
+ if (profile === null) return null;
1422
+ try {
1423
+ const instanceId = decodeURIComponent(raw.slice(0, at));
1424
+ return instanceId.length > 0 ? {
1425
+ instanceId,
1426
+ profile
1427
+ } : null;
1428
+ } catch {
1429
+ return null;
1430
+ }
1431
+ }
1432
+ var GridStreamRelay = class {
1433
+ deps;
1434
+ server = null;
1435
+ baseUrl = "";
1436
+ open = /* @__PURE__ */ new Set();
1437
+ constructor(deps) {
1438
+ this.deps = deps;
1439
+ }
1440
+ async start() {
1441
+ if (this.server) return;
1442
+ const server = createServer((req, res) => {
1443
+ const request = parseGridStreamPath(req.url);
1444
+ if (req.method !== "GET" || request === null) {
1445
+ res.writeHead(404).end();
1446
+ return;
1447
+ }
1448
+ this.serve(request, res);
1449
+ });
1450
+ await new Promise((resolve, reject) => {
1451
+ server.once("error", reject);
1452
+ server.listen(0, "127.0.0.1", resolve);
1453
+ });
1454
+ const address = server.address();
1455
+ if (typeof address !== "object" || address === null) {
1456
+ server.close();
1457
+ throw new Error("camera-grid: the stream relay did not bind a TCP port");
1458
+ }
1459
+ this.server = server;
1460
+ this.baseUrl = `http://127.0.0.1:${String(address.port)}`;
1461
+ }
1462
+ /** The URL a grid's catalog descriptor advertises. Empty before {@link start}. */
1463
+ streamUrl(request) {
1464
+ if (!this.baseUrl) throw new Error("camera-grid: the stream relay is not started");
1465
+ const instance = encodeURIComponent(request.instanceId);
1466
+ return `${this.baseUrl}${PATH_PREFIX}${instance}/${request.profile}${PATH_SUFFIX}`;
1467
+ }
1468
+ async serve(request, res) {
1469
+ const { instanceId, profile } = request;
1470
+ const session = this.deps.sessionFor(request);
1471
+ if (session === null) {
1472
+ this.deps.logger.warn("camera grid: a stream was requested for an unknown grid", { meta: {
1473
+ instanceId,
1474
+ profile
1475
+ } });
1476
+ res.writeHead(404).end();
1477
+ return;
1478
+ }
1479
+ this.open.add(res);
1480
+ let hold = null;
1481
+ let stallTimer = null;
1482
+ const sendHead = () => {
1483
+ if (res.headersSent) return;
1484
+ res.writeHead(200, {
1485
+ "content-type": GRID_WIRE_CONTENT_TYPE,
1486
+ "cache-control": "no-store",
1487
+ connection: "keep-alive"
1488
+ });
1489
+ res.flushHeaders();
1490
+ };
1491
+ const clearStall = () => {
1492
+ if (stallTimer === null) return;
1493
+ clearTimeout(stallTimer);
1494
+ stallTimer = null;
1495
+ };
1496
+ res.on("drain", clearStall);
1497
+ try {
1498
+ hold = await session.open({
1499
+ onData: (chunk) => {
1500
+ if (res.writableEnded || res.destroyed) return;
1501
+ sendHead();
1502
+ if (res.write(chunk) || stallTimer !== null) return;
1503
+ stallTimer = setTimeout(() => {
1504
+ stallTimer = null;
1505
+ this.deps.logger.warn("camera grid: cutting a reader that never drained — it was holding the composition", {
1506
+ tags: { deviceId: session.deviceId },
1507
+ meta: {
1508
+ instanceId,
1509
+ profile,
1510
+ stalledForMs: SLOW_READER_MS
1511
+ }
1512
+ });
1513
+ res.destroy();
1514
+ }, SLOW_READER_MS);
1515
+ stallTimer.unref?.();
1516
+ },
1517
+ onClose: (reason) => {
1518
+ this.deps.logger.info("camera grid: ending a reader", {
1519
+ tags: { deviceId: session.deviceId },
1520
+ meta: {
1521
+ instanceId,
1522
+ profile,
1523
+ reason
1524
+ }
1525
+ });
1526
+ clearStall();
1527
+ res.end();
1528
+ }
1529
+ });
1530
+ } catch (error) {
1531
+ this.deps.logger.warn("camera grid: could not serve a grid stream", {
1532
+ tags: { deviceId: session.deviceId },
1533
+ meta: {
1534
+ instanceId,
1535
+ profile,
1536
+ error: errMsg(error)
1537
+ }
1538
+ });
1539
+ if (!res.headersSent) res.writeHead(503, { "content-type": "text/plain" });
1540
+ res.end("camera grid unavailable");
1541
+ this.open.delete(res);
1542
+ return;
1543
+ }
1544
+ sendHead();
1545
+ res.on("close", () => {
1546
+ this.open.delete(res);
1547
+ clearStall();
1548
+ hold?.close();
1549
+ });
1550
+ }
1551
+ async dispose() {
1552
+ for (const res of this.open) res.destroy();
1553
+ this.open.clear();
1554
+ const server = this.server;
1555
+ this.server = null;
1556
+ this.baseUrl = "";
1557
+ if (server) await new Promise((resolve) => server.close(() => resolve()));
1558
+ }
1559
+ };
1560
+ //#endregion
1561
+ //#region src/builtins/camera-grid/grid-stream-descriptor.ts
1562
+ /**
1563
+ * `profileHint` is load-bearing, not decoration.
1564
+ *
1565
+ * A device publishing a SINGLE stream with no hint is ranked by pixel count,
1566
+ * and a single stream ranks into `mid` — the slot `recordings` does not select
1567
+ * on its own (`high|mid` picks high), that `recordingsLow` ignores, and that
1568
+ * scrub never reads. The Dreame robot's one 720p relay landed exactly there and
1569
+ * its footage was written nowhere anything looked.
1570
+ *
1571
+ * With several compositions published the hint does a second job: it says which
1572
+ * slot each one is FOR. Ranked by pixels a grid's `mid` would take the `high`
1573
+ * slot on any grid whose `high` was not offered.
1574
+ */
1575
+ function gridStreamDescriptor(input) {
1576
+ return {
1577
+ camStreamId: gridCamStreamId(input.profile),
1578
+ kind: GRID_WIRE_STREAM_KIND,
1579
+ url: input.url,
1580
+ codec: "h264",
1581
+ resolution: {
1582
+ width: input.width,
1583
+ height: input.height
1584
+ },
1585
+ fps: input.fps,
1586
+ label: `Grid composition (${input.profile})`,
1587
+ profileHint: input.profile,
1588
+ autoEligible: true
1589
+ };
1590
+ }
1591
+ //#endregion
1592
+ //#region src/builtins/camera-grid/flv-join.ts
1593
+ /**
1594
+ * Making one FLV stream joinable by many readers.
1595
+ *
1596
+ * MPEG-TS is self-describing: a reader attaches mid-stream, waits for the next
1597
+ * PAT/PMT and decodes. FLV is not. Its 9-byte signature, its `onMetaData`
1598
+ * script tag and its AVC sequence header appear ONCE, at the top, and a reader
1599
+ * that arrives later is handed the middle of a tag — ffmpeg answers `Invalid
1600
+ * data found when processing input`, which is exactly what the hub did the
1601
+ * minute the grid started emitting FLV (2026-09-17). The grid emits FLV because
1602
+ * the bundled ffmpeg segfaults remuxing MPEG-TS (D519 notes, same day), so the
1603
+ * format is not negotiable and this is the price of it.
1604
+ *
1605
+ * The join point therefore does two things, and nothing else:
1606
+ *
1607
+ * - **remembers what describes the stream** — the header, the newest script
1608
+ * tag, the newest AVC sequence header. Newest, not first: an encoder that
1609
+ * respawns emits a new sequence header, and a reader handed the old one
1610
+ * decodes noise;
1611
+ * - **starts each reader on a tag boundary at a KEYFRAME**, never mid-tag and
1612
+ * never on an inter frame that references pictures the reader never saw.
1613
+ *
1614
+ * It is a parser, not a buffer: nothing is retained beyond the preamble and the
1615
+ * partial tag currently being assembled. A composite at 10 fps with a 2-second
1616
+ * GOP makes a reader wait at most two seconds to join, which is the same wait
1617
+ * MPEG-TS would have imposed for its next key frame.
1618
+ */
1619
+ /** FLV tag header: type(1) + dataSize(3) + timestamp(3) + extended(1) + streamId(3). */
1620
+ var TAG_HEADER_BYTES = 11;
1621
+ /** Every tag is followed by its own size as a 4-byte trailer. */
1622
+ var TAG_TRAILER_BYTES = 4;
1623
+ /** `FLV` + version(1) + flags(1) + dataOffset(4), then PreviousTagSize0(4). */
1624
+ var FLV_HEADER_BYTES = 13;
1625
+ var TAG_TYPE_SCRIPT = 18;
1626
+ var TAG_TYPE_VIDEO = 9;
1627
+ /** High nibble of a video tag's first byte: 1 = key frame. */
1628
+ var VIDEO_FRAME_TYPE_KEY = 1;
1629
+ /** Second byte of an AVC video tag: 0 = sequence header, 1 = NALU. */
1630
+ var AVC_PACKET_TYPE_SEQUENCE_HEADER = 0;
1631
+ /**
1632
+ * One reader's view of the stream.
1633
+ *
1634
+ * Every consumer holds one, the first included: a join point with a privileged
1635
+ * "primary" reader would have two code paths for the same question, and the
1636
+ * grid's first consumer is not special — it just happens to arrive when the
1637
+ * preamble is still being learnt.
1638
+ */
1639
+ var FlvReader = class {
1640
+ state;
1641
+ detach;
1642
+ constructor(state, detach) {
1643
+ this.state = state;
1644
+ this.detach = detach;
1645
+ }
1646
+ /** True until the preamble and a key frame have been handed over. */
1647
+ get pending() {
1648
+ return !this.state.started;
1649
+ }
1650
+ /** The bytes owed to this reader since the last call, or `null`. */
1651
+ take() {
1652
+ const queued = this.state.queued;
1653
+ if (queued.length === 0) return null;
1654
+ this.state.queued = [];
1655
+ return queued.length === 1 ? queued[0] ?? null : Buffer.concat(queued);
1656
+ }
1657
+ /** Stop receiving. Anything queued is dropped with the reader. */
1658
+ close() {
1659
+ this.state.queued = [];
1660
+ this.detach(this.state);
1661
+ }
1662
+ };
1663
+ function parseVideoFlags(body) {
1664
+ const first = body[0];
1665
+ const second = body[1];
1666
+ if (first === void 0) return {
1667
+ isKeyFrame: false,
1668
+ isSequenceHeader: false
1669
+ };
1670
+ const frameType = first >> 4;
1671
+ const sequenceHeader = second === AVC_PACKET_TYPE_SEQUENCE_HEADER;
1672
+ return {
1673
+ isKeyFrame: frameType === VIDEO_FRAME_TYPE_KEY && !sequenceHeader,
1674
+ isSequenceHeader: sequenceHeader
1675
+ };
1676
+ }
1677
+ var FlvJoinPoint = class {
1678
+ buffer = Buffer.alloc(0);
1679
+ header = null;
1680
+ script = null;
1681
+ sequenceHeader = null;
1682
+ readers = /* @__PURE__ */ new Set();
1683
+ /** Attach a reader. It receives the preamble at the next key frame. */
1684
+ join() {
1685
+ const state = {
1686
+ started: false,
1687
+ queued: []
1688
+ };
1689
+ this.readers.add(state);
1690
+ return new FlvReader(state, (gone) => this.readers.delete(gone));
1691
+ }
1692
+ /** Feed bytes from the encoder; each reader then takes what it is owed. */
1693
+ accept(chunk) {
1694
+ this.buffer = this.buffer.length === 0 ? chunk : Buffer.concat([this.buffer, chunk]);
1695
+ this.consumeHeader();
1696
+ for (const tag of this.consumeTags()) this.dispatch(tag);
1697
+ }
1698
+ consumeHeader() {
1699
+ if (this.header !== null) return;
1700
+ if (this.buffer.length < FLV_HEADER_BYTES) return;
1701
+ this.header = this.buffer.subarray(0, FLV_HEADER_BYTES);
1702
+ this.buffer = this.buffer.subarray(FLV_HEADER_BYTES);
1703
+ }
1704
+ *consumeTags() {
1705
+ if (this.header === null) return;
1706
+ for (;;) {
1707
+ if (this.buffer.length < TAG_HEADER_BYTES) return;
1708
+ const dataSize = this.buffer.readUIntBE(1, 3);
1709
+ const total = TAG_HEADER_BYTES + dataSize + TAG_TRAILER_BYTES;
1710
+ if (this.buffer.length < total) return;
1711
+ const bytes = this.buffer.subarray(0, total);
1712
+ const type = bytes.readUInt8(0);
1713
+ const body = bytes.subarray(TAG_HEADER_BYTES, TAG_HEADER_BYTES + dataSize);
1714
+ const flags = type === TAG_TYPE_VIDEO ? parseVideoFlags(body) : {
1715
+ isKeyFrame: false,
1716
+ isSequenceHeader: false
1717
+ };
1718
+ this.buffer = this.buffer.subarray(total);
1719
+ yield {
1720
+ bytes,
1721
+ type,
1722
+ ...flags
1723
+ };
1724
+ }
1725
+ }
1726
+ dispatch(tag) {
1727
+ if (tag.type === TAG_TYPE_SCRIPT) this.script = tag.bytes;
1728
+ if (tag.isSequenceHeader) this.sequenceHeader = tag.bytes;
1729
+ for (const reader of this.readers) {
1730
+ if (reader.started) {
1731
+ reader.queued.push(tag.bytes);
1732
+ continue;
1733
+ }
1734
+ if (!tag.isKeyFrame) continue;
1735
+ const preamble = this.preamble();
1736
+ if (preamble === null) continue;
1737
+ reader.started = true;
1738
+ reader.queued.push(preamble, tag.bytes);
1739
+ }
1740
+ }
1741
+ /** The bytes that describe the stream, or `null` while any is still unknown. */
1742
+ preamble() {
1743
+ if (this.header === null || this.sequenceHeader === null) return null;
1744
+ const parts = [this.header];
1745
+ if (this.script !== null) parts.push(this.script);
1746
+ parts.push(this.sequenceHeader);
1747
+ return Buffer.concat(parts);
1748
+ }
1749
+ };
1750
+ //#endregion
1751
+ //#region src/builtins/camera-grid/grid-stream-session.ts
1752
+ var DEFAULT_LINGER_MS = 3e3;
1753
+ var GridStreamSession = class {
1754
+ options;
1755
+ consumers = /* @__PURE__ */ new Map();
1756
+ /**
1757
+ * The FLV stream's describing bytes, and where each reader may start.
1758
+ *
1759
+ * Rebuilt with every cold start: a new child means a new header and a new
1760
+ * sequence header, and handing a reader the previous child's would decode
1761
+ * noise. See `flv-join.ts` for why FLV needs this and MPEG-TS did not.
1762
+ */
1763
+ join = new FlvJoinPoint();
1764
+ running = null;
1765
+ starting = null;
1766
+ lingerTimer = null;
1767
+ teardown = null;
1768
+ disposed = false;
1769
+ constructor(options) {
1770
+ this.options = options;
1771
+ }
1772
+ get logTags() {
1773
+ return { deviceId: this.options.deviceId };
1774
+ }
1775
+ /** The COMPOSITE camera's device id — what every log line about this grid is tagged with. */
1776
+ get deviceId() {
1777
+ return this.options.deviceId;
1778
+ }
1779
+ isRunning() {
1780
+ return this.running !== null;
1781
+ }
1782
+ consumerCount() {
1783
+ return this.consumers.size;
1784
+ }
1785
+ /** Resolves once any in-flight start or teardown has finished. For tests and shutdown. */
1786
+ async settled() {
1787
+ await this.starting?.catch(() => void 0);
1788
+ await this.teardown;
1789
+ }
1790
+ /**
1791
+ * Attach a consumer, starting the composition if this is the first one.
1792
+ *
1793
+ * @throws when the grid has nothing to compose, or a source could not be
1794
+ * acquired. Both are LOGGED before they are thrown: a branch that accepts a
1795
+ * consumer and then produces no media is exactly the branch that reads as
1796
+ * "nothing ever happened".
1797
+ */
1798
+ async open(consumer) {
1799
+ if (this.disposed) throw new Error("camera-grid: this stream session is disposed");
1800
+ this.cancelLinger();
1801
+ this.consumers.set(consumer, this.join.join());
1802
+ try {
1803
+ await this.ensureRunning();
1804
+ } catch (error) {
1805
+ this.dropConsumer(consumer);
1806
+ this.scheduleTeardownIfIdle();
1807
+ throw error;
1808
+ }
1809
+ let closed = false;
1810
+ return { close: () => {
1811
+ if (closed) return;
1812
+ closed = true;
1813
+ this.dropConsumer(consumer);
1814
+ this.options.deps.logger.debug("camera grid: consumer left", {
1815
+ tags: this.logTags,
1816
+ meta: { remaining: this.consumers.size }
1817
+ });
1818
+ this.scheduleTeardownIfIdle();
1819
+ } };
1820
+ }
1821
+ /**
1822
+ * Attach to a composition that is ALREADY running, or refuse.
1823
+ *
1824
+ * The whole difference from {@link open} is the refusal, and the refusal is
1825
+ * the feature. A snapshot of a grid is a frame of the composition — which
1826
+ * only exists while something is watching it — and the operator's rule is
1827
+ * that producing a thumbnail must never be the reason N cameras get dialled.
1828
+ * `open()` would start the composition, acquire every source, and on a
1829
+ * battery camera that is a wake nobody asked for.
1830
+ *
1831
+ * `null` is a real answer: "there is no composition to take a frame from",
1832
+ * which the caller turns into the stored last frame, or into nothing.
1833
+ */
1834
+ openIfRunning(consumer) {
1835
+ if (this.disposed || this.running === null) return null;
1836
+ this.cancelLinger();
1837
+ this.consumers.set(consumer, this.join.join());
1838
+ let closed = false;
1839
+ return { close: () => {
1840
+ if (closed) return;
1841
+ closed = true;
1842
+ this.dropConsumer(consumer);
1843
+ this.scheduleTeardownIfIdle();
1844
+ } };
1845
+ }
1846
+ /** Forget a consumer AND the reader holding bytes on its behalf. */
1847
+ dropConsumer(consumer) {
1848
+ this.consumers.get(consumer)?.close();
1849
+ this.consumers.delete(consumer);
1850
+ }
1851
+ /**
1852
+ * The child ended on its own. Every consumer is told WHY — a stream that
1853
+ * simply stops is indistinguishable from a stalled one at the far end.
1854
+ */
1855
+ onChildEnded(reason) {
1856
+ if (this.running === null) return;
1857
+ this.options.deps.logger.warn("camera grid: the composition ended", {
1858
+ tags: this.logTags,
1859
+ meta: {
1860
+ reason,
1861
+ consumers: this.consumers.size
1862
+ }
1863
+ });
1864
+ for (const [consumer, reader] of [...this.consumers]) {
1865
+ reader.close();
1866
+ consumer.onClose(reason);
1867
+ }
1868
+ this.consumers.clear();
1869
+ this.teardown = this.stopNow();
1870
+ }
1871
+ async dispose() {
1872
+ this.disposed = true;
1873
+ this.cancelLinger();
1874
+ for (const [consumer, reader] of [...this.consumers]) {
1875
+ reader.close();
1876
+ consumer.onClose("shutdown");
1877
+ }
1878
+ this.consumers.clear();
1879
+ await this.settled();
1880
+ await this.stopNow();
1881
+ }
1882
+ async ensureRunning() {
1883
+ if (this.running) return this.running;
1884
+ if (this.starting) return this.starting;
1885
+ const starting = this.startCold();
1886
+ this.starting = starting;
1887
+ try {
1888
+ const state = await starting;
1889
+ this.running = state;
1890
+ return state;
1891
+ } finally {
1892
+ if (this.starting === starting) this.starting = null;
1893
+ }
1894
+ }
1895
+ async startCold() {
1896
+ const plan = this.options.resolvePlan();
1897
+ if (plan === null || plan.layout.cells.length === 0 || plan.sourceDeviceIds.length === 0) {
1898
+ this.options.deps.logger.warn("camera grid: a consumer attached but the grid has no cells — nothing to compose", { tags: this.logTags });
1899
+ throw new Error("camera-grid: this grid has no cells to compose");
1900
+ }
1901
+ const acquired = [];
1902
+ try {
1903
+ for (const sourceDeviceId of plan.sourceDeviceIds) acquired.push(await this.options.deps.acquireSource(sourceDeviceId));
1904
+ } catch (error) {
1905
+ this.options.deps.logger.error("camera grid: could not acquire every source — releasing the ones already taken", {
1906
+ tags: this.logTags,
1907
+ meta: {
1908
+ acquired: acquired.length,
1909
+ error: errMsg(error)
1910
+ }
1911
+ });
1912
+ await this.releaseAll(acquired);
1913
+ throw error;
1914
+ }
1915
+ try {
1916
+ this.join = new FlvJoinPoint();
1917
+ for (const consumer of this.consumers.keys()) this.consumers.set(consumer, this.join.join());
1918
+ const child = await this.options.deps.startChild(plan, acquired);
1919
+ child.stdout.on("data", (chunk) => {
1920
+ this.join.accept(chunk);
1921
+ for (const [consumer, reader] of this.consumers) {
1922
+ const owed = reader.take();
1923
+ if (owed !== null) consumer.onData(owed);
1924
+ }
1925
+ });
1926
+ this.options.deps.logger.info("camera grid: composition started", {
1927
+ tags: this.logTags,
1928
+ meta: {
1929
+ cells: plan.layout.cells.length,
1930
+ sources: [...plan.sourceDeviceIds],
1931
+ canvas: `${String(plan.layout.width)}x${String(plan.layout.height)}`,
1932
+ fps: plan.fps
1933
+ }
1934
+ });
1935
+ return {
1936
+ child,
1937
+ sources: acquired
1938
+ };
1939
+ } catch (error) {
1940
+ this.options.deps.logger.error("camera grid: the composition failed to start", {
1941
+ tags: this.logTags,
1942
+ meta: { error: errMsg(error) }
1943
+ });
1944
+ await this.releaseAll(acquired);
1945
+ throw error;
1946
+ }
1947
+ }
1948
+ scheduleTeardownIfIdle() {
1949
+ if (this.consumers.size > 0) return;
1950
+ if (this.running === null && this.starting === null) return;
1951
+ const lingerMs = this.options.deps.lingerMs ?? DEFAULT_LINGER_MS;
1952
+ if (lingerMs <= 0) {
1953
+ this.teardown = this.stopNow();
1954
+ return;
1955
+ }
1956
+ this.cancelLinger();
1957
+ this.lingerTimer = setTimeout(() => {
1958
+ this.lingerTimer = null;
1959
+ if (this.consumers.size > 0) return;
1960
+ this.teardown = this.stopNow();
1961
+ }, lingerMs);
1962
+ this.lingerTimer.unref?.();
1963
+ }
1964
+ cancelLinger() {
1965
+ if (this.lingerTimer === null) return;
1966
+ clearTimeout(this.lingerTimer);
1967
+ this.lingerTimer = null;
1968
+ }
1969
+ async stopNow() {
1970
+ const state = this.running;
1971
+ this.running = null;
1972
+ if (state === null) return;
1973
+ try {
1974
+ await state.child.stop();
1975
+ } catch (error) {
1976
+ this.options.deps.logger.warn("camera grid: the composition did not stop cleanly", {
1977
+ tags: this.logTags,
1978
+ meta: { error: errMsg(error) }
1979
+ });
1980
+ }
1981
+ await this.releaseAll(state.sources);
1982
+ this.options.deps.logger.info("camera grid: composition stopped — no consumers left", {
1983
+ tags: this.logTags,
1984
+ meta: { released: state.sources.length }
1985
+ });
1986
+ }
1987
+ async releaseAll(sources) {
1988
+ for (const source of sources) try {
1989
+ await this.options.deps.releaseSource(source.pipelineKey);
1990
+ } catch (error) {
1991
+ this.options.deps.logger.error("camera grid: could NOT release a source handle", {
1992
+ tags: this.logTags,
1993
+ meta: {
1994
+ pipelineKey: source.pipelineKey,
1995
+ error: errMsg(error)
1996
+ }
1997
+ });
1998
+ }
1999
+ }
2000
+ };
2001
+ //#endregion
2002
+ //#region src/builtins/camera-grid/silence-analysis.ts
2003
+ /**
2004
+ * Every analyzer a composite camera is created with switched OFF.
2005
+ *
2006
+ * A grid is a picture we composed from cameras that are ALREADY analyzed. Running
2007
+ * detection on the composite would pay for the same subjects a second time, and
2008
+ * would attribute them to a camera that does not exist as a viewpoint — a person
2009
+ * detected in the bottom-right cell is a person on THAT camera, not on the grid.
2010
+ *
2011
+ * `motion-detection` sits first deliberately: it is the one that holds the decode
2012
+ * session open, so its absence is the difference between a grid costing a
2013
+ * composition and costing a full decode pipeline. Same ordering, and the same
2014
+ * reason, as the Terminal addon's list.
2015
+ *
2016
+ * Called ONLY on creation. An operator who deliberately turns detection back on
2017
+ * for a grid must win, and a reconcile that re-asserted every pass would silently
2018
+ * overrule them once a minute.
2019
+ */
2020
+ /**
2021
+ * The list lives in `@camstack/types` now, and this is an alias rather than a
2022
+ * second copy. There WERE two — this one and the Terminal addon's — and they
2023
+ * had drifted: neither named `pipeline-analytics`, the one cap with no gate of
2024
+ * its own, which is what a grid forwarding its sources' motion would have used
2025
+ * to write a duplicate motion episode per event.
2026
+ */
2027
+ var GRID_SILENCED_CAP_NAMES = DERIVED_CAMERA_SILENCED_CAP_NAMES;
2028
+ /**
2029
+ * Resolve the addon currently providing `capName` for this device, from the
2030
+ * device's OWN bindings. `listBindableCapsForDeviceType` answers for the device
2031
+ * TYPE and would happily name a wrapper that is not the one bound here.
2032
+ *
2033
+ * `null` when the cap is not bound at all — not an error: a deployment with no
2034
+ * audio analyzer has nothing to switch off, and demanding one would make every
2035
+ * grid creation fail on a perfectly valid hub.
2036
+ */
2037
+ async function resolveBoundWrapper(api, deviceId, capName) {
2038
+ const bindings = await api.deviceManager.getBindings.query({ deviceId });
2039
+ for (const entry of bindings.entries) {
2040
+ if (entry.capName !== capName) continue;
2041
+ if (entry.kind !== "wrapped") continue;
2042
+ if (entry.providerAddonId === "") return null;
2043
+ return entry.providerAddonId;
2044
+ }
2045
+ return null;
2046
+ }
2047
+ /**
2048
+ * @throws if a cap IS bound and the write to its authority failed. The composite
2049
+ * would then be running a full analyzer over a picture whose subjects are already
2050
+ * counted elsewhere — exactly the cost this removes — and a silent version of
2051
+ * that failure is unfindable.
2052
+ */
2053
+ async function silenceAnalysisFor(deps, deviceId) {
2054
+ const failures = [];
2055
+ for (const capName of GRID_SILENCED_CAP_NAMES) try {
2056
+ const wrapperAddonId = await resolveBoundWrapper(deps.api, deviceId, capName);
2057
+ if (wrapperAddonId === null) {
2058
+ deps.logger.debug("camera grid: no analyzer bound for this capability", {
2059
+ tags: { deviceId },
2060
+ meta: { capName }
2061
+ });
2062
+ continue;
2063
+ }
2064
+ await deps.api.deviceManager.setWrapperActive.mutate({
2065
+ deviceId,
2066
+ capName,
2067
+ wrapperAddonId,
2068
+ active: false
2069
+ });
2070
+ deps.logger.info("camera grid: analyzer switched off at its authority", {
2071
+ tags: { deviceId },
2072
+ meta: {
2073
+ capName,
2074
+ wrapperAddonId
2075
+ }
2076
+ });
2077
+ } catch (err) {
2078
+ failures.push(`${capName}: ${errMsg(err)}`);
2079
+ deps.logger.error("camera grid: could NOT switch an analyzer off", {
2080
+ tags: { deviceId },
2081
+ meta: {
2082
+ capName,
2083
+ error: errMsg(err)
2084
+ }
2085
+ });
2086
+ }
2087
+ if (failures.length > 0) throw new Error(`camera grid ${deviceId}: could not switch off ${failures.length} analyzer(s) — it will run at full detection cost (${failures.join("; ")})`);
2088
+ }
2089
+ //#endregion
2090
+ //#region src/builtins/camera-grid/grid-canvas-seed.ts
2091
+ /**
2092
+ * What the canvas SAYS before a single camera has delivered a frame.
2093
+ *
2094
+ * ## Why black was not good enough
2095
+ *
2096
+ * The compositor emits from its very first tick (`grid-compositor.ts`) — that
2097
+ * is the whole point of a canvas, and it is what removed the ~9 s cold start.
2098
+ * But what it emitted until now was black, and black is the same picture for
2099
+ * four different situations: a grid with no cells, a grid whose sources are all
2100
+ * broken, a grid whose sources are merely slow, and a viewer that connected to
2101
+ * the wrong camera. An operator cannot tell them apart, and the one they
2102
+ * actually hit — sources still opening — is the one that fixes itself.
2103
+ *
2104
+ * The seed paints the LAYOUT instead: one card per cell, at the cell's own
2105
+ * rectangle, carrying the camera's name and the word `Waiting`. Three states
2106
+ * become three pictures — "no cards" is an empty grid, "a card still there" is
2107
+ * a tile that has not arrived, and "a picture" is a tile that has.
2108
+ *
2109
+ * It is honest about what it is. It is not a stand-in picture of the camera,
2110
+ * and it never carries a state it has not been told (a tile whose source is
2111
+ * genuinely broken is a matter for the tile's own decoder and its logs — this
2112
+ * says only "nothing has arrived here yet", which is true of both).
2113
+ *
2114
+ * ## Drawn ONCE, before the tick exists
2115
+ *
2116
+ * The seed is a full-canvas frame blitted in at the compositor's construction,
2117
+ * so the first tick already carries it and the tick never waits on anything.
2118
+ * Rendering it is the only asynchronous part, and it happens BEFORE the
2119
+ * compositor is built — never on the tick, which serves every cell.
2120
+ *
2121
+ * ## Why SVG → sharp, and why the conversion is here
2122
+ *
2123
+ * `snapshot-courtesy.ts` already renders text this way and states the reason:
2124
+ * shelling out to ffmpeg's `drawtext` was 52 ms against sharp's 4.8 ms, and an
2125
+ * SVG names a font FAMILY that fontconfig resolves instead of a font PATH that
2126
+ * has to be probed. This is that pattern, not a second one.
2127
+ *
2128
+ * What is different is the output. The canvas is yuv420p — that is what makes a
2129
+ * blit a strided memcpy — and sharp has no yuv output, so the raster is
2130
+ * converted once, here, by `rgbToYuv420p`. Once per composition start, over a
2131
+ * frame that is already being allocated; never per tick.
2132
+ *
2133
+ * ## Even, like everything else that touches the canvas
2134
+ *
2135
+ * The cards are the TILES' own rectangles, which `buildGridTilePlan` has
2136
+ * already snapped to even pixels — yuv420p subsamples chroma 2×2, and an odd
2137
+ * rectangle tints a tile rather than breaking it. Nothing here re-derives a
2138
+ * rectangle; it copies the one the decoder was sized against, so a card cannot
2139
+ * land anywhere other than exactly where its picture will.
2140
+ */
2141
+ /**
2142
+ * The word a card carries. Deliberately not a fault: nothing has arrived YET,
2143
+ * which is true of a camera that is slow and of one that is broken, and this
2144
+ * placeholder knows which it is for neither.
2145
+ */
2146
+ var GRID_SEED_WAITING_LABEL = "Waiting";
2147
+ /**
2148
+ * Family names, not paths — librsvg resolves them through fontconfig, and the
2149
+ * trailing generics keep a host without DejaVu rendering something legible
2150
+ * rather than nothing. Same stack as the courtesy frame, for the same reason.
2151
+ */
2152
+ var SEED_FONT_STACK = "DejaVu Sans,DejaVu Sans Mono,Helvetica,Arial,sans-serif";
2153
+ /** The card. Dark enough to read as "empty", lit enough to read as "a cell". */
2154
+ var CARD_FILL = "#1b1b21";
2155
+ var CARD_BORDER = "#3f3f4c";
2156
+ var CARD_NAME = "#e8e8ee";
2157
+ var CARD_STATE = "#8f8f9e";
2158
+ /**
2159
+ * The label for one source.
2160
+ *
2161
+ * A name we could not read is not a reason to paint an anonymous rectangle: the
2162
+ * DEVICE ID is what every log line about that tile carries, so it is the one
2163
+ * label an operator can act on. A blank or whitespace name is treated as no
2164
+ * name for the same reason.
2165
+ */
2166
+ function gridSeedName(names, deviceId) {
2167
+ const name = names.get(deviceId)?.trim();
2168
+ return name === void 0 || name.length === 0 ? `Camera ${String(deviceId)}` : name;
2169
+ }
2170
+ /**
2171
+ * The seed a tile plan implies — pure, and the plan is the ONLY input to the
2172
+ * geometry. A card is its tile's rectangle, never a recomputed one.
2173
+ */
2174
+ function buildGridSeedSpec(plan, names) {
2175
+ return {
2176
+ canvas: plan.canvas,
2177
+ cells: plan.tiles.map((tile) => ({
2178
+ origin: tile.origin,
2179
+ size: tile.size,
2180
+ name: gridSeedName(names, tile.deviceId)
2181
+ }))
2182
+ };
2183
+ }
2184
+ /** XML escaping for text placed inside an SVG `<text>` node. */
2185
+ function escapeSeedText(value) {
2186
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
2187
+ }
2188
+ /**
2189
+ * The document the seed is rasterized from.
2190
+ *
2191
+ * No full-bleed background: the uncovered part of a canvas is NOT a cell — the
2192
+ * cells need not cover it (`grid-canvas-derivation.ts`) — and painting a card's
2193
+ * treatment over it would say "waiting" about a tile that does not exist. It
2194
+ * stays the canvas' own black.
2195
+ *
2196
+ * Each card clips its own text. A camera named for a whole street would
2197
+ * otherwise spill across the cell next to it, and a label on the wrong tile is
2198
+ * worse than a truncated one.
2199
+ */
2200
+ function buildGridSeedSvg(spec) {
2201
+ const parts = [`<svg xmlns="http://www.w3.org/2000/svg" width="${String(spec.canvas.width)}" height="${String(spec.canvas.height)}">`];
2202
+ for (const [index, cell] of spec.cells.entries()) {
2203
+ const { width, height } = cell.size;
2204
+ const nameSize = Math.max(9, Math.min(Math.round(width / 12), Math.round(height / 8)));
2205
+ const stateSize = Math.max(8, Math.round(nameSize * .62));
2206
+ const stroke = Math.max(2, Math.round(Math.min(width, height) / 100));
2207
+ const inset = stroke / 2;
2208
+ const centreX = cell.origin.x + width / 2;
2209
+ const centreY = cell.origin.y + height / 2;
2210
+ const clipId = `seed-cell-${String(index)}`;
2211
+ parts.push(`<clipPath id="${clipId}"><rect x="${String(cell.origin.x)}" y="${String(cell.origin.y)}" width="${String(width)}" height="${String(height)}"/></clipPath>`, `<rect x="${String(cell.origin.x + inset)}" y="${String(cell.origin.y + inset)}" width="${String(width - stroke)}" height="${String(height - stroke)}" fill="${CARD_FILL}" stroke="${CARD_BORDER}" stroke-width="${String(stroke)}"/>`, `<g clip-path="url(#${clipId})" font-family="${SEED_FONT_STACK}" text-anchor="middle">`, `<text x="${String(centreX)}" y="${String(Math.round(centreY))}" font-size="${String(nameSize)}" fill="${CARD_NAME}">${escapeSeedText(cell.name)}</text>`, `<text x="${String(centreX)}" y="${String(Math.round(centreY + nameSize * 1.15))}" font-size="${String(stateSize)}" fill="${CARD_STATE}">${GRID_SEED_WAITING_LABEL}</text>`, `</g>`);
2212
+ }
2213
+ parts.push("</svg>");
2214
+ return parts.join("");
2215
+ }
2216
+ /** Limited-range BT.601, which is what a raw yuv420p stream handed to x264 is read as. */
2217
+ var Y_OFFSET = 16;
2218
+ var CHROMA_OFFSET = 128;
2219
+ function clampByte(value) {
2220
+ return Math.min(255, Math.max(0, Math.round(value)));
2221
+ }
2222
+ function luma(r, g, b) {
2223
+ return Y_OFFSET + (65.481 * r + 128.553 * g + 24.966 * b) / 255;
2224
+ }
2225
+ function chromaU(r, g, b) {
2226
+ return CHROMA_OFFSET + (-37.797 * r - 74.203 * g + 112 * b) / 255;
2227
+ }
2228
+ function chromaV(r, g, b) {
2229
+ return CHROMA_OFFSET + (112 * r - 93.786 * g - 18.214 * b) / 255;
2230
+ }
2231
+ /**
2232
+ * Packed RGB → yuv420p, once.
2233
+ *
2234
+ * Chroma is the average of each 2×2 block's colour, converted once per block —
2235
+ * which is what 4:2:0 means, and what keeps a card's border from fringing.
2236
+ * Sizes must be even; the canvas refuses anything else, so a caller that got
2237
+ * here with an odd size has a bug the blit would hide.
2238
+ */
2239
+ function rgbToYuv420p(rgb, size) {
2240
+ const { width, height } = size;
2241
+ const out = Buffer.alloc(yuv420pSize(width, height));
2242
+ const lumaBytes = width * height;
2243
+ const chromaBytes = width / 2 * (height / 2);
2244
+ for (let y = 0; y < height; y += 1) for (let x = 0; x < width; x += 1) {
2245
+ const at = (y * width + x) * 3;
2246
+ out[y * width + x] = clampByte(luma(rgb[at] ?? 0, rgb[at + 1] ?? 0, rgb[at + 2] ?? 0));
2247
+ }
2248
+ const halfW = width / 2;
2249
+ for (let y = 0; y < height / 2; y += 1) for (let x = 0; x < halfW; x += 1) {
2250
+ let r = 0;
2251
+ let g = 0;
2252
+ let b = 0;
2253
+ for (let dy = 0; dy < 2; dy += 1) for (let dx = 0; dx < 2; dx += 1) {
2254
+ const at = ((y * 2 + dy) * width + (x * 2 + dx)) * 3;
2255
+ r += rgb[at] ?? 0;
2256
+ g += rgb[at + 1] ?? 0;
2257
+ b += rgb[at + 2] ?? 0;
2258
+ }
2259
+ const at = y * halfW + x;
2260
+ out[lumaBytes + at] = clampByte(chromaU(r / 4, g / 4, b / 4));
2261
+ out[lumaBytes + chromaBytes + at] = clampByte(chromaV(r / 4, g / 4, b / 4));
2262
+ }
2263
+ return out;
2264
+ }
2265
+ /**
2266
+ * Render the seed as one yuv420p frame the canvas can take whole.
2267
+ *
2268
+ * Rejects on failure rather than answering black: the caller decides, and it
2269
+ * decides to carry on without a seed — a grid that would not start because its
2270
+ * placeholder would not draw is a worse grid than one that starts black.
2271
+ */
2272
+ async function renderGridSeed(spec) {
2273
+ const { default: sharp } = await import("sharp");
2274
+ const rgb = await sharp(Buffer.from(buildGridSeedSvg(spec))).flatten({ background: {
2275
+ r: 0,
2276
+ g: 0,
2277
+ b: 0
2278
+ } }).raw().toBuffer();
2279
+ const expected = spec.canvas.width * spec.canvas.height * 3;
2280
+ if (rgb.length !== expected) throw new Error(`camera-grid: the seed rasterized to ${String(rgb.length)} bytes, expected ${String(expected)}`);
2281
+ return rgbToYuv420p(rgb, spec.canvas);
2282
+ }
2283
+ //#endregion
2284
+ //#region src/builtins/camera-grid/grid-tile-feed.ts
2285
+ /**
2286
+ * One source's decoded tiles, of which only the LATEST is ever wanted.
2287
+ *
2288
+ * ## Why dropping is the point, not a compromise
2289
+ *
2290
+ * ffmpeg's `overlay` consumes one frame per input per output frame, so an input
2291
+ * that got ahead of another stays ahead for the life of the child — that is the
2292
+ * tile gap. A canvas asks a different question: "what does this camera look
2293
+ * like NOW". Everything behind the newest frame is not a backlog to work
2294
+ * through, it is history, and dropping it is what keeps every tile at the same
2295
+ * moment however unevenly their frames arrive.
2296
+ *
2297
+ * It is also the only bound on memory here. A decoder child that outruns the
2298
+ * output tick — or a tick that stalls — would otherwise grow an unbounded queue
2299
+ * of raw frames, and a raw frame is 345 KB at 640x360.
2300
+ *
2301
+ * ## The last frame is HELD
2302
+ *
2303
+ * A tick that finds nothing new redraws what was there. A tile must not blink
2304
+ * because a source was 40 ms late, and a source that has genuinely stopped is a
2305
+ * still picture — which is legible, and which the snapshot path already treats
2306
+ * as the honest answer for a camera that is not sending.
2307
+ */
2308
+ var GridTileFeed = class {
2309
+ frameBytes;
2310
+ partial = Buffer.alloc(0);
2311
+ newest = null;
2312
+ fresh = false;
2313
+ constructor(frameBytes) {
2314
+ this.frameBytes = frameBytes;
2315
+ }
2316
+ /** Feed bytes from the decoder. Any whole frames inside replace the newest. */
2317
+ push(chunk) {
2318
+ let buf = this.partial.length === 0 ? chunk : Buffer.concat([this.partial, chunk]);
2319
+ while (buf.length >= this.frameBytes) {
2320
+ this.newest = Buffer.from(buf.subarray(0, this.frameBytes));
2321
+ this.fresh = true;
2322
+ buf = buf.subarray(this.frameBytes);
2323
+ }
2324
+ this.partial = buf.length === 0 ? Buffer.alloc(0) : Buffer.from(buf);
2325
+ }
2326
+ /** The newest whole frame, or `null` while none has arrived. */
2327
+ latest() {
2328
+ this.fresh = false;
2329
+ return this.newest;
2330
+ }
2331
+ /** Has a new frame arrived since the last {@link latest}? */
2332
+ hasFresh() {
2333
+ return this.fresh;
2334
+ }
2335
+ /**
2336
+ * Forget the half frame, keep the picture.
2337
+ *
2338
+ * Raw video has no framing: the feed cuts on a fixed length, so bytes from a
2339
+ * NEW decoder concatenated onto a partial frame from the old one would be
2340
+ * misaligned for ever — every frame after it sheared, with nothing to
2341
+ * re-sync on. Called whenever a tile's decoder is replaced.
2342
+ *
2343
+ * The newest frame is kept deliberately: the cell holds its last picture
2344
+ * while its decoder comes back, instead of blinking to black.
2345
+ */
2346
+ resetPartial() {
2347
+ this.partial = Buffer.alloc(0);
2348
+ }
2349
+ /** For the bound in the spec: one frame plus at most a partial one. */
2350
+ bufferedBytes() {
2351
+ return (this.newest?.length ?? 0) + this.partial.length;
2352
+ }
2353
+ };
2354
+ //#endregion
2355
+ //#region src/builtins/camera-grid/grid-compositor.ts
2356
+ /**
2357
+ * The composition, driven by the OUTPUT's clock.
2358
+ *
2359
+ * ## What this replaces, and why it is the only thing that works
2360
+ *
2361
+ * `overlay` pairs its inputs BY PTS and ffmpeg gives each input pts 0 at its
2362
+ * own first frame, so two sources that joined at different moments compose
2363
+ * different moments for the life of the child. Measured at 4-5 s on this hub,
2364
+ * drifting over hours as the sources' key-frame phases slide through each other.
2365
+ * Every cheaper fix was tried and measured: `-use_wallclock_as_timestamps`
2366
+ * re-times by arrival and wrecked the pacing; `-copyts` changes nothing because
2367
+ * the broker re-bases each session (both restreams report `pts_time:0`), so
2368
+ * there is no shared timeline to align against; and serving each dial from the
2369
+ * newest key frame it already holds only moves the offsets into the past,
2370
+ * because those key frames are of different ages.
2371
+ *
2372
+ * Here there is nothing to pair. Every tick asks each source "what do you look
2373
+ * like NOW" and the answer is whatever arrived last. The gap is zero by
2374
+ * construction rather than by tuning.
2375
+ *
2376
+ * ## It also removes the wait
2377
+ *
2378
+ * A cell with no frame yet is not a reason to hold the picture back. The output
2379
+ * exists from the first tick and cells fill in as their sources arrive —
2380
+ * instead of the whole grid waiting for the slowest source's first key frame,
2381
+ * which is what the ~9 s cold start was.
2382
+ *
2383
+ * What a cell with no frame yet SHOWS is the seed (`grid-canvas-seed.ts`),
2384
+ * blitted in once at construction: its own rectangle, with its camera's name
2385
+ * and the word `Waiting`. It was black, and black said the same thing about an
2386
+ * empty grid, a broken grid and a grid that is merely still opening.
2387
+ *
2388
+ * ## What it costs
2389
+ *
2390
+ * The same N decodes ffmpeg already paid, in N children instead of one, plus
2391
+ * one strided memcpy per tile per tick (`grid-canvas.ts`). It does NOT reuse the
2392
+ * frames the detection pipeline decodes: those live in per-session decode
2393
+ * workers behind two process boundaries, the shm plane that once joined them was
2394
+ * removed on 2026-07-16, and what the pipeline retains is a model-sized view
2395
+ * (320x180 JPEG, on demand), not a tile.
2396
+ */
2397
+ var GridCompositor = class {
2398
+ deps;
2399
+ canvas;
2400
+ /** Keyed by tile id — unique per CELL, because one camera can hold two. */
2401
+ placed = /* @__PURE__ */ new Map();
2402
+ closed = false;
2403
+ constructor(deps) {
2404
+ this.deps = deps;
2405
+ this.canvas = new GridCanvas(deps.plan.canvas.width, deps.plan.canvas.height);
2406
+ if (deps.seed !== null) this.canvas.blit(deps.seed, deps.plan.canvas, {
2407
+ x: 0,
2408
+ y: 0
2409
+ });
2410
+ for (const tile of deps.plan.tiles) this.placed.set(tile.id, {
2411
+ tile,
2412
+ feed: new GridTileFeed(tile.frameBytes)
2413
+ });
2414
+ }
2415
+ /**
2416
+ * Raw bytes from one decoder output.
2417
+ *
2418
+ * A tile this composition has no rectangle for is IGNORED, never thrown on: a
2419
+ * child that outlives a layout change would otherwise take the tick down with
2420
+ * it, and the tick is what every other cell depends on.
2421
+ */
2422
+ onTile(tileId, chunk) {
2423
+ this.placed.get(tileId)?.feed.push(chunk);
2424
+ }
2425
+ /**
2426
+ * Compose and emit one frame. Returns what the sink said about back-pressure.
2427
+ *
2428
+ * Every tile is redrawn, fresh or not: a tile that produced nothing this tick
2429
+ * is a still picture, not a hole, and clearing it would make a late source
2430
+ * flicker. The canvas is never cleared between ticks for the same reason.
2431
+ */
2432
+ tick() {
2433
+ if (this.closed) return true;
2434
+ for (const { tile, feed } of this.placed.values()) {
2435
+ const frame = feed.latest();
2436
+ if (frame === null) continue;
2437
+ this.canvas.blit(frame, tile.size, tile.origin);
2438
+ }
2439
+ return this.deps.write(this.canvas.buffer);
2440
+ }
2441
+ /**
2442
+ * A tile's decoder was replaced: drop its half frame, keep its picture.
2443
+ *
2444
+ * Without this the new decoder's bytes would be appended to the old one's
2445
+ * partial frame and every frame after would be sheared — raw video has no
2446
+ * framing to re-sync on.
2447
+ */
2448
+ resetTile(tileId) {
2449
+ this.placed.get(tileId)?.feed.resetPartial();
2450
+ }
2451
+ /** After this, a tick emits nothing — a dead child must not keep writing. */
2452
+ close() {
2453
+ this.closed = true;
2454
+ }
2455
+ };
2456
+ //#endregion
2457
+ //#region src/builtins/camera-grid/grid-tile-plan.ts
2458
+ /**
2459
+ * The operator's layout, as one decoder child per CELL.
2460
+ *
2461
+ * ## Why per cell, when `grid-plan.ts` dedupes per source
2462
+ *
2463
+ * The single ffmpeg that this replaces made a camera used by two cells ONE
2464
+ * input, because decoding it twice doubles the expensive half of the job. A
2465
+ * compositor cannot do that with the same shape: this repo has exactly one
2466
+ * ffmpeg argv builder (`scripts/check-ffmpeg-primitive.ts`, Rule 1) and it
2467
+ * expresses one output per process, so a source feeding two differently cropped
2468
+ * and differently scaled tiles needs two children.
2469
+ *
2470
+ * The trade is small and worth stating: since D528 every source is read at its
2471
+ * CHEAPEST stream, so the duplicate is a second 640x360 sub-stream decode, not a
2472
+ * second 4 MP one. Teaching the builder several outputs would buy that back, and
2473
+ * is the right change to make if a grid ever shows one camera many times — it is
2474
+ * deliberately not made for a case that costs this little.
2475
+ *
2476
+ * ## Why the tile is scaled in the DECODER
2477
+ *
2478
+ * ffmpeg's scaler is SIMD and already there. Scaling in this process would be a
2479
+ * per-pixel loop in JavaScript, on the event loop that also answers the grid's
2480
+ * RPCs. Handing each child the exact pixel size its rectangle needs makes the
2481
+ * composition a strided memcpy (`grid-canvas.ts`) and keeps the only per-pixel
2482
+ * work where it belongs.
2483
+ *
2484
+ * ## Even, and snapped DOWN
2485
+ *
2486
+ * yuv420p subsamples chroma 2x2, so an odd origin lands a tile's chroma half a
2487
+ * sample off its luma — which TINTS the tile instead of breaking it, and
2488
+ * survives review. Sizes round DOWN so a tile never claims a row the decoder
2489
+ * was not asked to produce; a cell that rounds away to nothing is dropped
2490
+ * rather than emitted at zero size, because a zero-size output is an ffmpeg
2491
+ * start-up failure that would take the whole grid with it.
2492
+ */
2493
+ /** Smallest tile worth decoding. Below this it is not a cheaper picture, it is none. */
2494
+ var MIN_TILE_PX = 2;
2495
+ /** The one pixel format the canvas is in, so a blit is a copy and not a convert. */
2496
+ var TILE_PIXEL_FORMAT = "yuv420p";
2497
+ var FULL_FRAME_EPSILON$1 = 1e-6;
2498
+ function isFullFrame$1(rect) {
2499
+ return Math.abs(rect.x) < FULL_FRAME_EPSILON$1 && Math.abs(rect.y) < FULL_FRAME_EPSILON$1 && Math.abs(rect.width - 1) < FULL_FRAME_EPSILON$1 && Math.abs(rect.height - 1) < FULL_FRAME_EPSILON$1;
2500
+ }
2501
+ /**
2502
+ * `crop` resolved against the source's OWN size at runtime (`iw`/`ih`), never
2503
+ * against a resolution guessed here — which is what lets a stored rectangle
2504
+ * survive a camera that changes resolution under us.
2505
+ */
2506
+ function cropExpression$1(source) {
2507
+ return `crop=iw*${source.width}:ih*${source.height}:iw*${source.x}:ih*${source.y}`;
2508
+ }
2509
+ function buildGridTilePlan(input) {
2510
+ const tiles = [];
2511
+ for (const [index, cell] of input.cells.entries()) {
2512
+ const width = evenDown(cell.cell.width * input.canvas.width);
2513
+ const height = evenDown(cell.cell.height * input.canvas.height);
2514
+ if (width < MIN_TILE_PX || height < MIN_TILE_PX) continue;
2515
+ const x = Math.min(evenDown(cell.cell.x * input.canvas.width), evenDown(input.canvas.width - width));
2516
+ const y = Math.min(evenDown(cell.cell.y * input.canvas.height), evenDown(input.canvas.height - height));
2517
+ tiles.push({
2518
+ id: `cell-${String(index)}`,
2519
+ deviceId: cell.deviceId,
2520
+ size: {
2521
+ width,
2522
+ height
2523
+ },
2524
+ origin: {
2525
+ x,
2526
+ y
2527
+ },
2528
+ frameBytes: yuv420pSize(width, height),
2529
+ filter: [
2530
+ ...isFullFrame$1(cell.source) ? [] : [cropExpression$1(cell.source)],
2531
+ `scale=${String(width)}:${String(height)}`,
2532
+ `format=${TILE_PIXEL_FORMAT}`
2533
+ ].join(",")
2534
+ });
2535
+ }
2536
+ return {
2537
+ canvas: input.canvas,
2538
+ tiles
2539
+ };
2540
+ }
2541
+ //#endregion
2542
+ //#region src/builtins/camera-grid/grid-compositor-invocation.ts
2543
+ /** See D527: the probe returns from the SDP instead of reading media. */
2544
+ var ANALYZE_DURATION_US$1 = 0;
2545
+ var PROBE_SIZE_BYTES$1 = 32;
2546
+ /**
2547
+ * Threads per child, and why they are BOUNDED rather than automatic.
2548
+ *
2549
+ * ffmpeg's default is one thread per core, applied to decode, the filter graph
2550
+ * and the output — and it applies it per CHILD. A compositor has N+1 of them,
2551
+ * so on the hub's 20-core CPU two tiles reading 640x360 sub-streams were
2552
+ * measured holding 71 and 56 threads (2026-09-18). That is not a CPU problem:
2553
+ * the container's pid cgroup counts THREADS, its ceiling is 2048, and it was
2554
+ * sitting at 1858. Every new `pthread_create` then fails with EAGAIN, which
2555
+ * ffmpeg reports as `ff_frame_thread_encoder_init failed` — the grid stopped
2556
+ * working, and nothing about the message says "out of pids".
2557
+ *
2558
+ * A tile decodes one small stream and scales it once; one thread does that at a
2559
+ * few percent of a core (measured: 2.2-2.4%). The encoder gets a few more
2560
+ * because it is the only piece whose work scales with the canvas.
2561
+ *
2562
+ * The DECODER needs its own number. `threadCount` lands after the video args,
2563
+ * so it bounds the encoder only — a tile set to `threadCount: 1` still carried
2564
+ * `min(cores, 16)` decoder frame threads plus a filter pool, and measured 72.
2565
+ * With all three set it measures 26.
2566
+ */
2567
+ var TILE_THREADS = 1;
2568
+ /** libavfilter's own slice pool, which neither of the other two touches. */
2569
+ var FILTER_THREADS = 1;
2570
+ var ENCODER_THREADS = 4;
2571
+ var PRESET$1 = "veryfast";
2572
+ var TUNE$1 = "zerolatency";
2573
+ var GOP_SECONDS$1 = 1;
2574
+ /** One tile's decoder: dial in, raw yuv420p frames out. */
2575
+ function gridTileDecoderInvocation(input) {
2576
+ return {
2577
+ logLevel: "error",
2578
+ decodeHwAccel: null,
2579
+ input: {
2580
+ url: input.url,
2581
+ rtspTransport: "tcp",
2582
+ fflags: ["+discardcorrupt"],
2583
+ lowDelay: true,
2584
+ analyzeDurationUs: ANALYZE_DURATION_US$1,
2585
+ probeSizeBytes: PROBE_SIZE_BYTES$1,
2586
+ decodeThreadCount: TILE_THREADS
2587
+ },
2588
+ video: {
2589
+ kind: "raw",
2590
+ pixelFormat: TILE_PIXEL_FORMAT,
2591
+ filter: input.tile.filter,
2592
+ fps: input.fps
2593
+ },
2594
+ audio: { kind: "none" },
2595
+ threadCount: TILE_THREADS,
2596
+ filterThreadCount: FILTER_THREADS,
2597
+ outputArgs: [],
2598
+ sink: {
2599
+ kind: "stdout",
2600
+ container: "rawvideo"
2601
+ }
2602
+ };
2603
+ }
2604
+ /** The canvas encoder: raw frames on stdin, one compressed stream out. */
2605
+ function gridCanvasEncoderInvocation(input) {
2606
+ const video = {
2607
+ kind: "encode",
2608
+ encoder: input.encoder,
2609
+ preset: PRESET$1,
2610
+ tune: TUNE$1,
2611
+ pixelFormat: TILE_PIXEL_FORMAT,
2612
+ fps: input.fps,
2613
+ gopFrames: input.fps * GOP_SECONDS$1,
2614
+ bitrateKbps: input.bitrateKbps,
2615
+ scale: null
2616
+ };
2617
+ return {
2618
+ logLevel: "error",
2619
+ decodeHwAccel: null,
2620
+ input: {
2621
+ url: "pipe:0",
2622
+ rawVideo: {
2623
+ pixelFormat: TILE_PIXEL_FORMAT,
2624
+ width: input.canvas.width,
2625
+ height: input.canvas.height,
2626
+ framerate: input.fps
2627
+ }
2628
+ },
2629
+ video,
2630
+ audio: { kind: "none" },
2631
+ threadCount: ENCODER_THREADS,
2632
+ filterThreadCount: FILTER_THREADS,
2633
+ outputArgs: [],
2634
+ sink: {
2635
+ kind: "stdout",
2636
+ container: "flv"
2637
+ }
2638
+ };
2639
+ }
2640
+ //#endregion
2641
+ //#region src/builtins/camera-grid/grid-compositor-child.ts
2642
+ /**
2643
+ * The composition as processes: one decoder per tile, one encoder, one tick.
2644
+ *
2645
+ * It presents the SAME shape the single ffmpeg did — `{ stdout, stop }` — so
2646
+ * `GridStreamSession` is untouched. The seam is deliberate: the session owns
2647
+ * demand, acquisition and teardown, and none of that changes because the
2648
+ * picture is assembled differently.
2649
+ *
2650
+ * ## The order things start in, and why it is the order
2651
+ *
2652
+ * The seed first, then the encoder, then the tick, then the decoders. The tick
2653
+ * writes the canvas from its very first beat, so the encoder produces a stream
2654
+ * — and the consumer sees a picture — before any camera has delivered anything.
2655
+ * That is the cold start the old shape spent waiting for the slowest source's
2656
+ * first key frame, and it is now spent watching cells fill in.
2657
+ *
2658
+ * What that first picture SAYS is the seed (`grid-canvas-seed.ts`): one card
2659
+ * per cell, at the cell's own rectangle, naming its camera. It is drawn once,
2660
+ * here, before the compositor is built — a tick must never wait on a render —
2661
+ * and it is bounded and fallible: a seed that cannot be drawn leaves the canvas
2662
+ * black, which is what it was before, and never stops the composition.
2663
+ *
2664
+ * ## Back-pressure is a SKIPPED tick, never a queue
2665
+ *
2666
+ * A raw canvas frame is 3.1 MB at 1080p. If the encoder stops draining, the one
2667
+ * safe thing is to stop composing until it drains again: a queue of raw frames
2668
+ * is how a stalled encoder becomes an OOM, and a dropped frame in a live
2669
+ * composite costs nothing anybody can see.
2670
+ *
2671
+ * ## A tile comes back; only the ENCODER ends the composition
2672
+ *
2673
+ * Every child exiting used to end it, on the reasoning that a frozen tile is a
2674
+ * nicer picture and a worse fact. In practice it produced neither: a 4K source
2675
+ * ended mid-run (`code=0` — the input simply finished), the composition tore
2676
+ * down, the consumer re-dialled, and the grid served nothing but restarts. That
2677
+ * is what the operator saw as the `auto` rung being stuck.
2678
+ *
2679
+ * A canvas makes the better answer cheap: while a decoder comes back, its cell
2680
+ * holds the last frame it produced and every other cell carries on. The bound
2681
+ * (`TILE_MAX_RESTARTS`) keeps a source that is genuinely gone from respawning
2682
+ * for ever — and when it is reached, the composition does end, with the tile
2683
+ * named.
2684
+ *
2685
+ * The encoder is different: nothing downstream of it exists without it, so its
2686
+ * exit is the composition's exit, first time.
2687
+ */
2688
+ /**
2689
+ * The encoder must produce its first bytes quickly, because the tick feeds it a
2690
+ * black canvas immediately — a silence here is the encoder failing to start,
2691
+ * not a camera being slow.
2692
+ */
2693
+ var ENCODER_FIRST_DATA_MS = 5e3;
2694
+ /**
2695
+ * A decoder's first frame waits for its source's next key frame, which on this
2696
+ * fleet is up to a GOP. Generous, and it costs only that tile: the picture is
2697
+ * already on screen.
2698
+ */
2699
+ var DECODER_FIRST_DATA_MS = 15e3;
2700
+ /**
2701
+ * How many times a tile's decoder may come back before the composition gives up
2702
+ * on it.
2703
+ *
2704
+ * The bound exists so a source that is genuinely gone still ends the
2705
+ * composition rather than respawning for ever; below it, a decoder that dies is
2706
+ * simply replaced while its cell holds the last frame it produced.
2707
+ */
2708
+ var TILE_MAX_RESTARTS = 5;
2709
+ /**
2710
+ * How long the seed may wait for the source cameras' names.
2711
+ *
2712
+ * The seed is drawn BEFORE the encoder is spawned — that is what puts it on the
2713
+ * first tick — so everything it waits for is added to the cold start the rest
2714
+ * of this file exists to keep short. A name is a nicety; the card exists
2715
+ * either way, labelled by device id. So the read is bounded and the deadline
2716
+ * is not an error.
2717
+ */
2718
+ var SEED_NAMES_TIMEOUT_MS = 1500;
2719
+ /**
2720
+ * The names for the cards, or an empty map.
2721
+ *
2722
+ * Never throws and never delays past the deadline: an unnamed card is a
2723
+ * complete card (`gridSeedName` falls back to the device id), and a grid that
2724
+ * started late because a name lookup was slow would be a worse grid.
2725
+ */
2726
+ async function resolveSeedNames(ctx, deviceIds) {
2727
+ const resolve = ctx.resolveSourceNames;
2728
+ if (resolve === void 0) return /* @__PURE__ */ new Map();
2729
+ const empty = /* @__PURE__ */ new Map();
2730
+ return new Promise((settle) => {
2731
+ const timer = setTimeout(() => {
2732
+ ctx.logger.warn("camera grid: the seed could not read the source names in time", {
2733
+ tags: { deviceId: ctx.deviceId },
2734
+ meta: {
2735
+ sources: deviceIds.length,
2736
+ timeoutMs: SEED_NAMES_TIMEOUT_MS
2737
+ }
2738
+ });
2739
+ settle(empty);
2740
+ }, SEED_NAMES_TIMEOUT_MS);
2741
+ timer.unref();
2742
+ resolve(deviceIds).then((names) => {
2743
+ clearTimeout(timer);
2744
+ settle(names);
2745
+ }, (error) => {
2746
+ clearTimeout(timer);
2747
+ ctx.logger.warn("camera grid: the seed could not read the source names", {
2748
+ tags: { deviceId: ctx.deviceId },
2749
+ meta: {
2750
+ sources: deviceIds.length,
2751
+ error: errMsg(error)
2752
+ }
2753
+ });
2754
+ settle(empty);
2755
+ });
2756
+ });
2757
+ }
2758
+ /**
2759
+ * The picture the canvas starts as: one card per cell, naming its camera.
2760
+ *
2761
+ * `null` — black, which is what this was before — when it cannot be drawn. A
2762
+ * placeholder that refused to render must never be the reason a grid does not
2763
+ * start, so every failure here is a warning and a composition that carries on.
2764
+ */
2765
+ async function buildCanvasSeed(ctx, tilePlan) {
2766
+ const names = await resolveSeedNames(ctx, [...new Set(tilePlan.tiles.map((tile) => tile.deviceId))]);
2767
+ try {
2768
+ return await renderGridSeed(buildGridSeedSpec(tilePlan, names));
2769
+ } catch (error) {
2770
+ ctx.logger.warn("camera grid: the canvas seed could not be drawn - starting black", {
2771
+ tags: { deviceId: ctx.deviceId },
2772
+ meta: {
2773
+ error: errMsg(error),
2774
+ tiles: tilePlan.tiles.length
2775
+ }
2776
+ });
2777
+ return null;
2778
+ }
2779
+ }
2780
+ async function startGridCompositorChild(ctx, plan, sources, onEnded) {
2781
+ const tilePlan = buildGridTilePlan({
2782
+ canvas: {
2783
+ width: plan.layout.width,
2784
+ height: plan.layout.height
2785
+ },
2786
+ cells: plan.layout.cells.map((cell) => ({
2787
+ deviceId: plan.sourceDeviceIds[cell.inputIndex] ?? 0,
2788
+ source: cell.source,
2789
+ cell: cell.cell
2790
+ }))
2791
+ });
2792
+ if (tilePlan.tiles.length === 0) throw new Error("camera-grid: every cell rounded away to nothing — there is no picture to make");
2793
+ let ended = false;
2794
+ const end = (reason) => {
2795
+ if (ended) return;
2796
+ ended = true;
2797
+ onEnded(reason);
2798
+ };
2799
+ const seed = await buildCanvasSeed(ctx, tilePlan);
2800
+ let encoderIn = null;
2801
+ let encoderOut = null;
2802
+ let draining = false;
2803
+ let tick = null;
2804
+ const compositor = new GridCompositor({
2805
+ plan: tilePlan,
2806
+ seed,
2807
+ write: (frame) => {
2808
+ const sink = encoderIn;
2809
+ if (sink === null || draining || sink.destroyed) return false;
2810
+ const accepted = sink.write(frame);
2811
+ if (!accepted) draining = true;
2812
+ return accepted;
2813
+ }
2814
+ });
2815
+ const startTick = () => {
2816
+ if (tick !== null) return;
2817
+ tick = setInterval(() => {
2818
+ compositor.tick();
2819
+ }, Math.max(1, Math.round(1e3 / plan.fps)));
2820
+ tick.unref();
2821
+ };
2822
+ const encoder = new FfmpegProcess({
2823
+ binaryPath: ctx.binaryPath,
2824
+ buildArgs: () => buildFfmpegArgs(gridCanvasEncoderInvocation({
2825
+ canvas: tilePlan.canvas,
2826
+ fps: plan.fps,
2827
+ encoder: plan.encoder,
2828
+ bitrateKbps: plan.bitrateKbps
2829
+ })),
2830
+ decodeHwAccel: null,
2831
+ logger: ctx.logger.child("encode"),
2832
+ deviceId: ctx.deviceId,
2833
+ role: "camera-grid-encode",
2834
+ tags: { tiles: tilePlan.tiles.length },
2835
+ firstDataTimeoutMs: ENCODER_FIRST_DATA_MS,
2836
+ maxRestarts: 0,
2837
+ stdio: [
2838
+ "pipe",
2839
+ "pipe",
2840
+ "pipe"
2841
+ ],
2842
+ onChild: (child) => {
2843
+ encoderIn = child.stdin;
2844
+ if (child.stdout) encoderOut = child.stdout;
2845
+ child.stdin?.on("drain", () => {
2846
+ draining = false;
2847
+ });
2848
+ startTick();
2849
+ child.stderr?.on("data", () => {});
2850
+ child.stdin?.on("error", () => {});
2851
+ },
2852
+ onExit: (exit) => end(`encoder:${exit.classification}`)
2853
+ });
2854
+ try {
2855
+ await encoder.start();
2856
+ } catch (error) {
2857
+ if (tick !== null) clearInterval(tick);
2858
+ compositor.close();
2859
+ throw error;
2860
+ }
2861
+ if (encoderIn === null || encoderOut === null) {
2862
+ await encoder.stop();
2863
+ throw new Error("camera-grid: the canvas encoder exposed no stdin/stdout to compose into");
2864
+ }
2865
+ const urlByDeviceId = /* @__PURE__ */ new Map();
2866
+ for (const [index, deviceId] of plan.sourceDeviceIds.entries()) {
2867
+ const url = sources[index]?.url;
2868
+ if (url !== void 0) urlByDeviceId.set(deviceId, url);
2869
+ }
2870
+ const decoders = [];
2871
+ const startDecoder = async (tile) => {
2872
+ const url = urlByDeviceId.get(tile.deviceId);
2873
+ if (url === void 0) throw new Error(`camera-grid: no acquired source for device ${String(tile.deviceId)}`);
2874
+ const decoder = new FfmpegProcess({
2875
+ binaryPath: ctx.binaryPath,
2876
+ buildArgs: () => buildFfmpegArgs(gridTileDecoderInvocation({
2877
+ tile,
2878
+ url,
2879
+ fps: plan.fps
2880
+ })),
2881
+ decodeHwAccel: null,
2882
+ logger: ctx.logger.child("tile"),
2883
+ deviceId: tile.deviceId,
2884
+ role: "camera-grid-tile",
2885
+ tags: {
2886
+ tile: tile.id,
2887
+ width: tile.size.width,
2888
+ height: tile.size.height
2889
+ },
2890
+ firstDataTimeoutMs: DECODER_FIRST_DATA_MS,
2891
+ maxRestarts: TILE_MAX_RESTARTS,
2892
+ onChild: (child) => {
2893
+ child.stdout?.on("data", (chunk) => {
2894
+ compositor.onTile(tile.id, chunk);
2895
+ });
2896
+ child.stderr?.on("data", () => {});
2897
+ },
2898
+ onExit: () => {
2899
+ compositor.resetTile(tile.id);
2900
+ },
2901
+ onGiveUp: (error) => end(`tile ${tile.id}: ${error.message}`)
2902
+ });
2903
+ decoders.push(decoder);
2904
+ await decoder.start();
2905
+ };
2906
+ const stopAll = async () => {
2907
+ if (tick !== null) clearInterval(tick);
2908
+ compositor.close();
2909
+ await Promise.allSettled(decoders.map((d) => d.stop()));
2910
+ await encoder.stop();
2911
+ };
2912
+ try {
2913
+ for (const tile of tilePlan.tiles) await startDecoder(tile);
2914
+ } catch (error) {
2915
+ await stopAll();
2916
+ throw error;
2917
+ }
2918
+ ctx.logger.info("camera grid: composing on an output clock", {
2919
+ tags: { deviceId: ctx.deviceId },
2920
+ meta: {
2921
+ tiles: tilePlan.tiles.length,
2922
+ canvas: `${String(tilePlan.canvas.width)}x${String(tilePlan.canvas.height)}`,
2923
+ fps: plan.fps,
2924
+ seeded: seed !== null
2925
+ }
2926
+ });
2927
+ return {
2928
+ stdout: encoderOut,
2929
+ stop: stopAll
2930
+ };
2931
+ }
2932
+ //#endregion
2933
+ //#region src/builtins/camera-grid/addon.ts
2934
+ var INTEGRATION_NAME = "Camera Grids";
2935
+ var RECONCILE_MS = 6e4;
2936
+ /**
2937
+ * How long a source acquire may keep asking while a provider is still coming up.
2938
+ * Long enough to cover the republish window after a hub restart, short enough
2939
+ * that a genuinely missing profile fails while the operator is still looking.
2940
+ */
2941
+ var SOURCE_ACQUIRE_BUDGET_MS = 8e3;
2942
+ var SOURCE_ACQUIRE_PAUSE_MS = 700;
2943
+ var DEFAULTS = {
2944
+ cameraGrids: [],
2945
+ cameraGridTombstones: []
2946
+ };
2947
+ /** One composition per (grid, profile) — a grid composes each separately. */
2948
+ function sessionKey(instanceId, profile) {
2949
+ return `${instanceId}::${profile}`;
2950
+ }
2951
+ /**
2952
+ * One grid's composition of one profile.
2953
+ *
2954
+ * The profile is back in the key after a spell with a single output. What made
2955
+ * the per-profile shape painful was never the count: it was that a rebuild
2956
+ * meant a blank screen until the slowest source produced a key frame. An output
2957
+ * clock (D530) shows the picture at once and fills the cells in, so a rung the
2958
+ * adaptive can stand on costs what it is worth.
2959
+ */
2960
+ var GridSessionEntry = class {
2961
+ instanceId;
2962
+ profile;
2963
+ session;
2964
+ constructor(instanceId, profile, session) {
2965
+ this.instanceId = instanceId;
2966
+ this.profile = profile;
2967
+ this.session = session;
2968
+ }
2969
+ isRunning() {
2970
+ return this.session.isRunning();
2971
+ }
2972
+ };
2973
+ var CameraGridAddon = class extends BaseAddon {
2974
+ relay = null;
2975
+ reconcileTimer = null;
2976
+ /** Keyed by instance id — ONE composition per grid. */
2977
+ sessions = /* @__PURE__ */ new Map();
2978
+ deviceIdByInstanceId = /* @__PURE__ */ new Map();
2979
+ tombstones = /* @__PURE__ */ new Set();
2980
+ /**
2981
+ * What each grid can honestly publish, per profile.
2982
+ *
2983
+ * ABSENT means "not asked yet", and it is a REFUSAL to describe — the device
2984
+ * throws rather than answering an empty catalog, because an empty catalog
2985
+ * retracts every stream the broker holds for the grid. It is refreshed on
2986
+ * every reconcile and on every layout save; the window belongs to the READER
2987
+ * (D224), and 60 s is the window for a fact — "does 101 have a low assigned"
2988
+ * — that only changes when an operator changes it.
2989
+ */
2990
+ plansByInstanceId = /* @__PURE__ */ new Map();
2991
+ activity = null;
2992
+ snapshots = null;
2993
+ frameSampler = null;
2994
+ /** The node's pinned ffmpeg (D540). `null` until init resolved it — a
2995
+ * composition then refuses by name; there is no PATH default. */
2996
+ ffmpegBinaryPath = null;
2997
+ /** The node's pinned build, remembered only on success (D540). */
2998
+ pinnedFfmpeg = memoizePinnedFfmpeg(() => this.ctx.deps.ensureFfmpeg());
2999
+ /** A resolution in flight, so a reconcile pass never starts a second. */
3000
+ ffmpegResolving = null;
3001
+ integrationId;
3002
+ constructor() {
3003
+ super({ ...DEFAULTS });
3004
+ }
3005
+ async onInitialize() {
3006
+ this.replaceTombstones(this.config.cameraGridTombstones);
3007
+ await this.normalizeRows();
3008
+ if (declarationOwnerNodeId(this.ctx.kernel.localNodeId) === "hub") {
3009
+ await this.resolveFfmpeg();
3010
+ const relay = new GridStreamRelay({
3011
+ logger: this.ctx.logger.child("relay"),
3012
+ sessionFor: (request) => this.sessionFor(request)
3013
+ });
3014
+ await relay.start();
3015
+ this.relay = relay;
3016
+ this.snapshots = new GridSnapshotSource({
3017
+ logger: this.ctx.logger.child("snapshot"),
3018
+ sessionsFor: (deviceId) => this.sessionsForDevice(deviceId),
3019
+ sampleFrame: async (session) => this.sampleFrame(session),
3020
+ store: new GridLastFrameFileStore({
3021
+ dataDir: this.ctx.dataDir,
3022
+ logger: this.ctx.logger.child("snapshot")
3023
+ })
3024
+ });
3025
+ this.activity = new GridActivityForwarder({
3026
+ eventBus: this.ctx.eventBus,
3027
+ logger: this.ctx.logger.child("activity"),
3028
+ addonId: this.ctx.id,
3029
+ gridsForSource: (sourceDeviceId) => this.gridsForSource(sourceDeviceId),
3030
+ now: () => Date.now()
3031
+ });
3032
+ this.subscribeSourceActivity();
3033
+ installGridCameraRuntime({
3034
+ descriptorsFor: (instanceId) => this.descriptorsFor(instanceId),
3035
+ getLayout: (deviceId) => this.gridViewFor(deviceId),
3036
+ saveLayout: async (patch) => this.saveGridLayout(patch),
3037
+ getSnapshot: async (deviceId) => this.getSnapshot(deviceId),
3038
+ motionStatus: (deviceId) => {
3039
+ const state = this.activity?.motionStatusFor(deviceId, Date.now()) ?? {
3040
+ detected: false,
3041
+ lastDetectedAt: null
3042
+ };
3043
+ return {
3044
+ ...state,
3045
+ autoClearAfterMs: state.detected ? MOTION_CLOSE_AFTER_MS : null
3046
+ };
3047
+ }
3048
+ });
3049
+ await this.reconcile().catch((error) => {
3050
+ this.ctx.logger.warn("camera grid: initial reconciliation failed — will retry", { meta: { error: errMsg(error) } });
3051
+ });
3052
+ this.reconcileTimer = setInterval(() => {
3053
+ this.reconcile().catch((error) => {
3054
+ this.ctx.logger.warn("camera grid: reconciliation failed", { meta: { error: errMsg(error) } });
3055
+ });
3056
+ }, RECONCILE_MS);
3057
+ this.reconcileTimer.unref?.();
3058
+ }
3059
+ return { providers: [{
3060
+ capability: cameraGridLayoutCapability,
3061
+ provider: buildGridLayoutNativeProvider({
3062
+ getLayout: (deviceId) => this.gridViewFor(deviceId),
3063
+ saveLayout: (patch) => this.saveGridLayout(patch)
3064
+ })
3065
+ }] };
3066
+ }
3067
+ async onConfigChanged() {
3068
+ this.replaceTombstones(this.config.cameraGridTombstones);
3069
+ await this.normalizeRows();
3070
+ await this.applyLayoutChanges();
3071
+ if (this.relay) this.reconcile().catch((error) => {
3072
+ this.ctx.logger.warn("camera grid: reconciliation after a config change failed", { meta: { error: errMsg(error) } });
3073
+ });
3074
+ }
3075
+ async onShutdown() {
3076
+ if (this.reconcileTimer) clearInterval(this.reconcileTimer);
3077
+ this.reconcileTimer = null;
3078
+ installGridCameraRuntime(null);
3079
+ await this.relay?.dispose();
3080
+ this.relay = null;
3081
+ for (const entry of this.sessions.values()) await entry.session.dispose();
3082
+ this.sessions.clear();
3083
+ this.snapshots = null;
3084
+ this.frameSampler = null;
3085
+ }
3086
+ instances() {
3087
+ return readGridInstances(this.config.cameraGrids, (message) => {
3088
+ this.ctx.logger.warn(message);
3089
+ });
3090
+ }
3091
+ instanceById(instanceId) {
3092
+ return this.instances().find((instance) => instance.id === instanceId);
3093
+ }
3094
+ /**
3095
+ * Fill in everything a name-only row is missing, and persist if it changed.
3096
+ *
3097
+ * Without this a freshly typed row is unparseable, and `readGridInstances`
3098
+ * IGNORES what it cannot parse — so creation would silently do nothing.
3099
+ */
3100
+ async normalizeRows() {
3101
+ const normalized = normalizeGridRows(this.config.cameraGrids, () => crypto.randomUUID());
3102
+ if (!normalized.changed) return;
3103
+ this.ctx.logger.info("camera grid: completing operator-created rows", { meta: {
3104
+ rows: normalized.rows.length,
3105
+ wasRows: this.config.cameraGrids.length
3106
+ } });
3107
+ await this.updateGlobalSettings({ cameraGrids: [...normalized.rows] });
3108
+ }
3109
+ replaceTombstones(stableIds) {
3110
+ this.tombstones.clear();
3111
+ for (const stableId of stableIds) if (typeof stableId === "string" && stableId.length > 0) this.tombstones.add(stableId);
3112
+ }
3113
+ async reconcile() {
3114
+ if (!this.relay) return;
3115
+ const instances = this.instances();
3116
+ const declarations = buildGridCameraDeclarations(instances);
3117
+ await this.refreshSourcePlans(instances);
3118
+ await this.retireWithdrawnSessions(instances);
3119
+ const result = await new DeclaredDevices({
3120
+ logger: this.ctx.logger.child("declaration"),
3121
+ addonId: this.ctx.id,
3122
+ devices: this.ctx.kernel.devices,
3123
+ localNodeId: this.ctx.kernel.localNodeId,
3124
+ getIntegration: async (addonId) => {
3125
+ const integration = await this.ctx.api.integrations.getByAddonId.query({ addonId });
3126
+ this.integrationId = integration?.id ?? null;
3127
+ return integration;
3128
+ },
3129
+ createIntegration: async (input) => {
3130
+ const integration = await this.ctx.api.integrations.create.mutate(input);
3131
+ this.integrationId = integration.id;
3132
+ return integration;
3133
+ },
3134
+ updateIntegration: async ({ id, info }) => {
3135
+ await this.ctx.api.integrations.update.mutate({
3136
+ id,
3137
+ info,
3138
+ skipRestart: true
3139
+ });
3140
+ },
3141
+ listOwnDevices: async () => {
3142
+ return gridCameraReconciliationIndex(await this.ctx.api.deviceManager.listAll.query({ addonId: this.ctx.id }), this.integrationId, declarations, this.tombstones);
3143
+ }
3144
+ }).reconcile({
3145
+ integrationName: INTEGRATION_NAME,
3146
+ placement: "hub",
3147
+ devices: declarations.map((camera) => ({
3148
+ stableId: camera.stableId,
3149
+ name: camera.name,
3150
+ type: DeviceType.Camera,
3151
+ DeviceClass: GridCameraDevice,
3152
+ config: camera.config,
3153
+ role: "camera-grid"
3154
+ }))
3155
+ });
3156
+ const declaredByStableId = new Map(declarations.map((camera) => [camera.stableId, camera]));
3157
+ for (const outcome of result.devices) {
3158
+ if (!(outcome.device instanceof GridCameraDevice)) continue;
3159
+ const declaration = declaredByStableId.get(outcome.stableId);
3160
+ if (!declaration) continue;
3161
+ const config = outcome.device.config;
3162
+ if (config.get("instanceId") !== declaration.config.instanceId) await config.setAll(declaration.config);
3163
+ const instanceId = declaration.config.instanceId;
3164
+ this.deviceIdByInstanceId.set(instanceId, outcome.device.id);
3165
+ this.ensureSessions(instanceId, outcome.device.id);
3166
+ if (outcome.created) await this.silenceAnalysis(outcome.device.id);
3167
+ outcome.device.setAddonOnline(true);
3168
+ }
3169
+ }
3170
+ async silenceAnalysis(deviceId) {
3171
+ try {
3172
+ await silenceAnalysisFor({
3173
+ api: this.ctx.api,
3174
+ logger: this.ctx.logger
3175
+ }, deviceId);
3176
+ } catch (error) {
3177
+ this.ctx.logger.error("camera grid: a new grid could not be silenced", {
3178
+ tags: { deviceId },
3179
+ meta: { error: errMsg(error) }
3180
+ });
3181
+ }
3182
+ }
3183
+ /**
3184
+ * Listen to the SOURCES, so the grid can say the same things about itself.
3185
+ *
3186
+ * Filtered by source id inside the handler rather than by subscribing per
3187
+ * camera: the bus filter is per category, the set of sources changes whenever
3188
+ * an operator drags a cell, and a per-camera subscription would have to be
3189
+ * torn down and rebuilt on every layout save.
3190
+ *
3191
+ * Every handler is TOTAL — a malformed payload is ignored, never thrown out
3192
+ * of. These are telemetry events on a shared bus (D8/D11), and a throw here
3193
+ * would take the grid's forwarding down for every grid because one camera
3194
+ * emitted something unexpected.
3195
+ */
3196
+ subscribeSourceActivity() {
3197
+ this.subscribe({ category: EventCategory.MotionOnMotionChanged }, (event) => {
3198
+ const data = event.data;
3199
+ if (typeof data.deviceId !== "number" || typeof data.detected !== "boolean") return;
3200
+ const at = typeof data.timestamp === "number" ? data.timestamp : Date.now();
3201
+ this.activity?.onSourceMotion(data.deviceId, data.detected, at);
3202
+ });
3203
+ this.subscribe({ category: EventCategory.PipelineAudioInferenceResult }, (event) => {
3204
+ const data = event.data;
3205
+ const dbfs = data.frame?.level?.dbfs;
3206
+ if (typeof data.deviceId !== "number" || typeof dbfs !== "number") return;
3207
+ this.activity?.onSourceAudio(data.deviceId, dbfs, Date.now());
3208
+ });
3209
+ this.subscribe({ category: EventCategory.DetectionResult }, (event) => {
3210
+ const frame = event.data.frame;
3211
+ if (frame === void 0 || frame.kind !== "frame") return;
3212
+ this.activity?.onSourceDetections(frame);
3213
+ });
3214
+ }
3215
+ /**
3216
+ * Which grids show this camera. Empty for the overwhelming majority of
3217
+ * events, which is why it is the FIRST thing every handler asks.
3218
+ */
3219
+ gridsForSource(sourceDeviceId) {
3220
+ const targets = [];
3221
+ for (const [instanceId, deviceId] of this.deviceIdByInstanceId) {
3222
+ const instance = this.instanceById(instanceId);
3223
+ if (!instance || !instance.enabled) continue;
3224
+ if (sourceDeviceId === deviceId) continue;
3225
+ if (instance.cells.filter((cell) => cell.deviceId === sourceDeviceId).length === 0) continue;
3226
+ targets.push({
3227
+ deviceId,
3228
+ canvas: this.canvasFor(instanceId) ?? {
3229
+ width: 0,
3230
+ height: 0
3231
+ },
3232
+ cellsForSource: (id) => instance.cells.filter((cell) => cell.deviceId === id).map((cell) => ({
3233
+ source: cell.source,
3234
+ cell: cell.cell
3235
+ })),
3236
+ sourceDeviceIds: [...new Set(instance.cells.map((cell) => cell.deviceId))]
3237
+ });
3238
+ }
3239
+ return targets;
3240
+ }
3241
+ /**
3242
+ * Which stream each grid reads each of its sources at, asked of the BROKER.
3243
+ *
3244
+ * `listAllProfileSlots` is the one authority on "does 101 have a low
3245
+ * assigned", and `sourceCamStreamId === null` is its way of saying no. A read
3246
+ * that FAILS leaves the previous answer in place and says so — it is not an
3247
+ * empty catalog, and turning it into one would retract the streams of every
3248
+ * grid on the hub.
3249
+ */
3250
+ async refreshSourcePlans(instances) {
3251
+ let slots;
3252
+ try {
3253
+ slots = await this.ctx.api.streamBroker.listAllProfileSlots.query();
3254
+ } catch (error) {
3255
+ this.ctx.logger.warn("camera grid: could not read the broker profile slots - keeping the last answer", { meta: {
3256
+ error: errMsg(error),
3257
+ grids: instances.length
3258
+ } });
3259
+ return;
3260
+ }
3261
+ const servedBy = /* @__PURE__ */ new Map();
3262
+ for (const slot of slots) {
3263
+ if (slot.sourceCamStreamId === null) continue;
3264
+ const profiles = servedBy.get(slot.deviceId) ?? [];
3265
+ profiles.push({
3266
+ profile: slot.profile,
3267
+ width: slot.resolution?.width ?? 0,
3268
+ height: slot.resolution?.height ?? 0
3269
+ });
3270
+ servedBy.set(slot.deviceId, profiles);
3271
+ }
3272
+ for (const instance of instances) {
3273
+ const plans = gridProfilePlans({
3274
+ publishedProfiles: instance.publishedProfiles,
3275
+ cells: instance.cells.map((cell) => ({
3276
+ deviceId: cell.deviceId,
3277
+ source: cell.source,
3278
+ cell: cell.cell
3279
+ })),
3280
+ profilesServedBy: (deviceId) => servedBy.get(deviceId) ?? null
3281
+ });
3282
+ const previous = this.plansByInstanceId.get(instance.id);
3283
+ this.plansByInstanceId.set(instance.id, plans);
3284
+ this.logSourcePlan(instance, plans, previous);
3285
+ }
3286
+ }
3287
+ /**
3288
+ * Say WHICH stream each cell is read at, and who could not be read - once per
3289
+ * change.
3290
+ *
3291
+ * Both halves earn their line. A grid silently missing from a catalog is
3292
+ * indistinguishable from a broker that swept it, so the refusal names the
3293
+ * sources. And the chosen profiles are the answer to "why is this tile
3294
+ * soft?" — a camera whose only assigned slot is `high` is read at `high`, and
3295
+ * nothing else in the system would ever say so.
3296
+ *
3297
+ * Logged on the EDGE: a grid that cannot be composed would otherwise write a
3298
+ * line a minute for ever.
3299
+ */
3300
+ logSourcePlan(instance, plans, previous) {
3301
+ const shape = (value) => JSON.stringify(value);
3302
+ if (previous !== void 0 && shape(previous) === shape(plans)) return;
3303
+ const deviceId = this.deviceIdByInstanceId.get(instance.id) ?? 0;
3304
+ for (const row of plans) {
3305
+ if (row.offered || row.missingSources.length === 0) continue;
3306
+ this.ctx.logger.info("camera grid: a profile is NOT on offer", {
3307
+ tags: { deviceId },
3308
+ meta: {
3309
+ instanceId: instance.id,
3310
+ profile: row.profile,
3311
+ missingSources: [...row.missingSources]
3312
+ }
3313
+ });
3314
+ }
3315
+ this.ctx.logger.info("camera grid: published profiles", {
3316
+ tags: { deviceId },
3317
+ meta: {
3318
+ instanceId: instance.id,
3319
+ offered: Object.fromEntries(plans.filter((row) => row.offered && row.published).map((row) => [row.profile, row.offered ? `${String(row.canvas.width)}x${String(row.canvas.height)}` : ""]))
3320
+ }
3321
+ });
3322
+ }
3323
+ plansFor(instanceId) {
3324
+ return this.plansByInstanceId.get(instanceId) ?? null;
3325
+ }
3326
+ planFor(instanceId, profile) {
3327
+ return this.plansFor(instanceId)?.find((row) => row.profile === profile) ?? null;
3328
+ }
3329
+ /**
3330
+ * The canvas of the BEST profile this grid offers.
3331
+ *
3332
+ * Used where a single geometry is needed for something that is not a
3333
+ * composition — the detection boxes a grid forwards (`grid-activity`), which
3334
+ * are normalized against whatever picture the viewer is looking at. The best
3335
+ * offered one is the honest default; a grid offering nothing has no geometry
3336
+ * and says so.
3337
+ */
3338
+ canvasFor(instanceId) {
3339
+ for (const row of this.plansFor(instanceId) ?? []) if (row.offered) return row.canvas;
3340
+ return null;
3341
+ }
3342
+ ensureSessions(instanceId, deviceId) {
3343
+ for (const profile of GRID_PROFILES) {
3344
+ const key = sessionKey(instanceId, profile);
3345
+ const plan = this.planFor(instanceId, profile);
3346
+ if (plan === null || !plan.offered || !plan.published) {
3347
+ const stale = this.sessions.get(key);
3348
+ if (stale) {
3349
+ this.sessions.delete(key);
3350
+ stale.session.dispose();
3351
+ }
3352
+ continue;
3353
+ }
3354
+ if (this.sessions.has(key)) continue;
3355
+ const binaryPath = this.ffmpegBinaryPath;
3356
+ if (binaryPath === null) {
3357
+ this.ctx.logger.error("camera-grid: composition refused — no pinned ffmpeg on this node (D540)", {
3358
+ tags: { deviceId },
3359
+ meta: {
3360
+ instanceId,
3361
+ profile
3362
+ }
3363
+ });
3364
+ this.resolveFfmpeg();
3365
+ continue;
3366
+ }
3367
+ this.sessions.set(key, new GridSessionEntry(instanceId, profile, this.makeSession(instanceId, deviceId, profile, binaryPath)));
3368
+ }
3369
+ }
3370
+ /**
3371
+ * The source cameras' names, for the cards the canvas is seeded with.
3372
+ *
3373
+ * Asked of the device manager, which OWNS the name, at the moment the seed is
3374
+ * drawn — never kept here. A consumer that mirrored this would be stale on
3375
+ * exactly the write an operator makes (D224), for a label.
3376
+ *
3377
+ * A device that cannot be read is simply absent from the map, and its card
3378
+ * carries the device id instead. One unreadable camera never costs the other
3379
+ * cards their names, which is why these are settled rather than awaited as
3380
+ * one batch.
3381
+ */
3382
+ async sourceNames(deviceIds) {
3383
+ const names = /* @__PURE__ */ new Map();
3384
+ const results = await Promise.allSettled(deviceIds.map(async (deviceId) => {
3385
+ return {
3386
+ deviceId,
3387
+ name: (await this.ctx.api.deviceManager.getDevice.query({ deviceId }))?.name ?? null
3388
+ };
3389
+ }));
3390
+ for (const result of results) {
3391
+ if (result.status !== "fulfilled") continue;
3392
+ const { deviceId, name } = result.value;
3393
+ if (name !== null) names.set(deviceId, name);
3394
+ }
3395
+ return names;
3396
+ }
3397
+ makeSession(instanceId, deviceId, profile, binaryPath) {
3398
+ const childContext = {
3399
+ binaryPath,
3400
+ logger: this.ctx.logger,
3401
+ deviceId,
3402
+ resolveSourceNames: (deviceIds) => this.sourceNames(deviceIds)
3403
+ };
3404
+ const session = new GridStreamSession({
3405
+ deviceId,
3406
+ deps: {
3407
+ logger: this.ctx.logger,
3408
+ acquireSource: async (sourceDeviceId) => {
3409
+ const dial = gridSourceDial(await acquireWithRetry(() => this.ctx.api.streamBroker.getStreamWithCodec.mutate({
3410
+ deviceId: sourceDeviceId,
3411
+ video: "copy",
3412
+ audio: "none",
3413
+ profile,
3414
+ tag: `camera-grid:${String(deviceId)}:${profile}`
3415
+ }), {
3416
+ budgetMs: SOURCE_ACQUIRE_BUDGET_MS,
3417
+ now: () => Date.now(),
3418
+ sleep: () => new Promise((resolve) => setTimeout(resolve, SOURCE_ACQUIRE_PAUSE_MS)),
3419
+ onRetry: (waitedMs) => {
3420
+ this.ctx.logger.info("camera grid: a source has not republished yet — asking again", {
3421
+ tags: { deviceId },
3422
+ meta: {
3423
+ instanceId,
3424
+ profile,
3425
+ sourceDeviceId,
3426
+ waitedMs
3427
+ }
3428
+ });
3429
+ }
3430
+ }));
3431
+ this.ctx.logger.info("camera grid: source acquired", {
3432
+ tags: { deviceId },
3433
+ meta: {
3434
+ instanceId,
3435
+ profile,
3436
+ sourceDeviceId,
3437
+ mode: dial.mode,
3438
+ ...dial.mode === "sentry" ? { why: "battery source - the sentry dial never asks for the camera" } : {}
3439
+ }
3440
+ });
3441
+ return {
3442
+ url: dial.url,
3443
+ pipelineKey: dial.pipelineKey
3444
+ };
3445
+ },
3446
+ releaseSource: async (pipelineKey) => {
3447
+ await this.ctx.api.streamBroker.releaseStreamWithCodec.mutate({ pipelineKey });
3448
+ },
3449
+ startChild: async (plan, sources) => startGridCompositorChild(childContext, plan, sources, (reason) => {
3450
+ session.onChildEnded(reason);
3451
+ })
3452
+ },
3453
+ resolvePlan: () => {
3454
+ const instance = this.instanceById(instanceId);
3455
+ const plan = this.planFor(instanceId, profile);
3456
+ if (!instance || plan === null || !plan.offered || !plan.published) return null;
3457
+ return gridPlanFor(instance, {
3458
+ encoder: "libx264",
3459
+ decodeHwAccel: null,
3460
+ canvas: plan.canvas
3461
+ });
3462
+ }
3463
+ });
3464
+ return session;
3465
+ }
3466
+ /** The session a dial is asking for, or `null` - which the relay answers 404 to. */
3467
+ sessionFor(request) {
3468
+ return this.sessions.get(sessionKey(request.instanceId, request.profile))?.session ?? null;
3469
+ }
3470
+ /** This grid's sessions, in DESCENDING quality — the snapshot takes the first running one. */
3471
+ sessionsForDevice(deviceId) {
3472
+ const instanceId = this.instanceIdForDevice(deviceId);
3473
+ if (instanceId === null) return [];
3474
+ const entries = [];
3475
+ for (const profile of GRID_PROFILES) {
3476
+ const entry = this.sessions.get(sessionKey(instanceId, profile));
3477
+ if (entry) entries.push(entry);
3478
+ }
3479
+ return entries;
3480
+ }
3481
+ /** A grid that is gone stops immediately - it must not keep N sources dialled. */
3482
+ async retireWithdrawnSessions(instances) {
3483
+ const live = new Set(instances.filter((instance) => instance.enabled).map((i) => i.id));
3484
+ for (const [key, entry] of [...this.sessions]) {
3485
+ if (live.has(entry.instanceId)) continue;
3486
+ this.ctx.logger.info("camera grid: retiring a withdrawn grid", {
3487
+ tags: { deviceId: this.deviceIdByInstanceId.get(entry.instanceId) ?? 0 },
3488
+ meta: { instanceId: entry.instanceId }
3489
+ });
3490
+ this.sessions.delete(key);
3491
+ await entry.session.dispose();
3492
+ }
3493
+ for (const instanceId of [...this.deviceIdByInstanceId.keys()]) {
3494
+ if (live.has(instanceId)) continue;
3495
+ this.activity?.forget(this.deviceIdByInstanceId.get(instanceId) ?? 0);
3496
+ this.deviceIdByInstanceId.delete(instanceId);
3497
+ this.plansByInstanceId.delete(instanceId);
3498
+ }
3499
+ }
3500
+ /**
3501
+ * A geometry change is a NEW composition. The running child is composing the
3502
+ * old one, and ffmpeg has no way to be told otherwise, so it is stopped: the
3503
+ * consumer's next read re-dials and gets the new picture.
3504
+ */
3505
+ async applyLayoutChanges() {
3506
+ for (const entry of this.sessions.values()) {
3507
+ if (!entry.session.isRunning()) continue;
3508
+ this.ctx.logger.info("camera grid: the layout changed - restarting the composition", {
3509
+ tags: { deviceId: this.deviceIdByInstanceId.get(entry.instanceId) ?? 0 },
3510
+ meta: { instanceId: entry.instanceId }
3511
+ });
3512
+ entry.session.onChildEnded("layout-changed");
3513
+ }
3514
+ }
3515
+ async getSnapshot(deviceId) {
3516
+ const snapshots = this.snapshots;
3517
+ if (snapshots === null) return null;
3518
+ return snapshots.getSnapshot(deviceId);
3519
+ }
3520
+ /**
3521
+ * One frame out of a composition that is ALREADY running.
3522
+ *
3523
+ * `openIfRunning` is the whole guarantee: it refuses a cold session, so a
3524
+ * thumbnail can never be the reason N sources get acquired. A grid that is
3525
+ * not being watched has no fresh frame, and that is the honest answer.
3526
+ */
3527
+ async sampleFrame(entry) {
3528
+ const sampler = this.frameSampler;
3529
+ if (sampler === null) return null;
3530
+ return sampler.sample(entry.session.deviceId, { attach: (onChunk) => entry.session.openIfRunning({
3531
+ onData: onChunk,
3532
+ onClose: () => {}
3533
+ }) });
3534
+ }
3535
+ /**
3536
+ * Every stream this grid offers, or `null` when the addon cannot say.
3537
+ *
3538
+ * `null` is a refusal to describe and the device turns it into a THROW. An
3539
+ * empty array would be the broker reading "this camera offers nothing" and
3540
+ * sweeping every stream it holds for the grid.
3541
+ */
3542
+ descriptorsFor(instanceId) {
3543
+ const instance = this.instanceById(instanceId);
3544
+ const relay = this.relay;
3545
+ const plans = this.plansFor(instanceId);
3546
+ if (!instance || !relay || plans === null) return null;
3547
+ return plans.filter((row) => row.offered && row.published).map((row) => gridStreamDescriptor({
3548
+ profile: row.profile,
3549
+ width: row.offered ? row.canvas.width : 0,
3550
+ height: row.offered ? row.canvas.height : 0,
3551
+ fps: instance.fps,
3552
+ url: relay.streamUrl({
3553
+ instanceId,
3554
+ profile: row.profile
3555
+ })
3556
+ }));
3557
+ }
3558
+ instanceIdForDevice(deviceId) {
3559
+ for (const [instanceId, id] of this.deviceIdByInstanceId) if (id === deviceId) return instanceId;
3560
+ return null;
3561
+ }
3562
+ instanceForDevice(deviceId) {
3563
+ const instanceId = this.instanceIdForDevice(deviceId);
3564
+ return instanceId === null ? null : this.instanceById(instanceId) ?? null;
3565
+ }
3566
+ gridViewFor(deviceId) {
3567
+ const instance = this.instanceForDevice(deviceId);
3568
+ if (!instance) return null;
3569
+ return {
3570
+ instanceId: instance.id,
3571
+ deviceId,
3572
+ name: instance.name,
3573
+ fps: instance.fps,
3574
+ cells: instance.cells.map((cell) => ({
3575
+ deviceId: cell.deviceId,
3576
+ source: cell.source,
3577
+ cell: cell.cell
3578
+ })),
3579
+ profiles: (this.plansByInstanceId.get(instance.id) ?? []).map((row) => ({
3580
+ profile: row.profile,
3581
+ offered: row.offered,
3582
+ published: row.offered && row.published,
3583
+ missingSources: row.offered ? [] : [...row.missingSources],
3584
+ canvas: row.offered ? `${String(row.canvas.width)}x${String(row.canvas.height)}` : ""
3585
+ }))
3586
+ };
3587
+ }
3588
+ async saveGridLayout(input) {
3589
+ const instance = this.instanceForDevice(input.deviceId);
3590
+ if (!instance) throw new Error(`camera-grid: device ${String(input.deviceId)} is not a grid camera`);
3591
+ const updated = {
3592
+ ...instance,
3593
+ ...input.name !== void 0 ? { name: input.name.trim() } : {},
3594
+ ...input.fps !== void 0 ? { fps: input.fps } : {},
3595
+ ...input.publishedProfiles !== void 0 ? { publishedProfiles: [...input.publishedProfiles] } : {},
3596
+ cells: input.cells.map((cell) => ({ ...cell }))
3597
+ };
3598
+ this.ctx.logger.info("camera grid: layout saved", {
3599
+ tags: { deviceId: input.deviceId },
3600
+ meta: {
3601
+ cells: updated.cells.length,
3602
+ sources: [...new Set(updated.cells.map((cell) => cell.deviceId))],
3603
+ fps: updated.fps
3604
+ }
3605
+ });
3606
+ await this.updateGlobalSettings({ cameraGrids: this.config.cameraGrids.map((row) => row["id"] === instance.id ? {
3607
+ ...row,
3608
+ ...updated
3609
+ } : row) });
3610
+ await this.refreshSourcePlans(this.instances());
3611
+ this.ensureSessions(instance.id, input.deviceId);
3612
+ const view = this.gridViewFor(input.deviceId);
3613
+ if (!view) throw new Error("camera-grid: the grid vanished while it was being saved");
3614
+ return view;
3615
+ }
3616
+ /**
3617
+ * Resolve the pinned build, single-flighted, and hand it to the frame sampler.
3618
+ * Never throws: a failure is an ERROR and leaves the binary unknown, so the
3619
+ * next pass that wants a composition asks again. Never PATH: the host's
3620
+ * ffmpeg is not ours (`packages/types/src/deps/ffmpeg-binary-source.ts`).
3621
+ */
3622
+ resolveFfmpeg() {
3623
+ if (this.ffmpegBinaryPath !== null) return Promise.resolve();
3624
+ if (this.ffmpegResolving !== null) return this.ffmpegResolving;
3625
+ const attempt = this.pinnedFfmpeg().then((binaryPath) => {
3626
+ this.ffmpegBinaryPath = binaryPath;
3627
+ this.frameSampler = new GridFrameSampler({
3628
+ binaryPath,
3629
+ logger: this.ctx.logger.child("snapshot")
3630
+ });
3631
+ }).catch((err) => {
3632
+ this.ctx.logger.error("camera-grid: the pinned ffmpeg could not be resolved — compositions refuse until it is (D540)", { meta: { error: errMsg(err) } });
3633
+ }).finally(() => {
3634
+ this.ffmpegResolving = null;
3635
+ });
3636
+ this.ffmpegResolving = attempt;
3637
+ return attempt;
3638
+ }
3639
+ /**
3640
+ * The integration page: a list of grids, with a NAME.
3641
+ *
3642
+ * Deliberately nothing else. A generated form for the geometry would render
3643
+ * "cell 1 source = 592, cell 1 crop x = 0.25" and be unusable, so the
3644
+ * geometry lives in a WIDGET on the camera's own device details, declared by
3645
+ * the `camera-grid-layout` CAPABILITY (`camera-grid-layout.cap.ts`). It used
3646
+ * to be a `type:'widget'` field in this addon's own `deviceSettingsSchema()`
3647
+ * and it rendered NOWHERE: that section is only fetched for the four addons
3648
+ * hand-listed in `PIPELINE_CLUSTER_DEVICE_ADDONS`, and an addon not on the
3649
+ * list falls off silently. A cap-declared widget is placed by the framework,
3650
+ * on the camera, beside PTZ and motion zones.
3651
+ */
3652
+ globalSettingsSchema() {
3653
+ return this.schema({ sections: [{
3654
+ id: "camera-grids",
3655
+ title: "Camera grids",
3656
+ titleKey: "server:globalSettings.s_camera-grids.title",
3657
+ description: "A grid is a composite camera: several cameras composed into one picture, recorded and played back like any other camera. Create one here with a name; open its camera to lay it out. Object detection is switched OFF on a new grid — the cameras it is composed from are already analysed.",
3658
+ descriptionKey: "server:globalSettings.s_camera-grids.description",
3659
+ columns: 1,
3660
+ fields: [this.field({
3661
+ type: "editable-array",
3662
+ key: "cameraGrids",
3663
+ label: "Grids",
3664
+ labelKey: "server:globalSettings.s_camera-grids.cameraGrids.label",
3665
+ default: [],
3666
+ maxRows: 16,
3667
+ addLabel: "Add grid",
3668
+ emptyMessage: "No camera grids yet.",
3669
+ rowTitleTemplate: "{name}",
3670
+ defaultItem: {
3671
+ name: "",
3672
+ enabled: true
3673
+ },
3674
+ itemFields: [{
3675
+ type: "text",
3676
+ key: "name",
3677
+ label: "Name",
3678
+ labelKey: "server:globalSettings.s_camera-grids.cameraGrids.name.label",
3679
+ required: true
3680
+ }, {
3681
+ type: "boolean",
3682
+ key: "enabled",
3683
+ label: "Enabled",
3684
+ labelKey: "server:globalSettings.s_camera-grids.cameraGrids.enabled.label",
3685
+ description: "A disabled grid withdraws its camera.",
3686
+ descriptionKey: "server:globalSettings.s_camera-grids.cameraGrids.enabled.description",
3687
+ default: true
3688
+ }]
3689
+ })]
3690
+ }] });
3691
+ }
3692
+ integrationSettingSections() {
3693
+ return ["camera-grids"];
3694
+ }
3695
+ };
3696
+ //#endregion
3697
+ //#region src/builtins/camera-grid/grid-filter-graph.ts
3698
+ var CANVAS_LABEL = "canvas";
3699
+ var OUT_LABEL = "grid";
3700
+ /** Full-frame within a tolerance, i.e. nothing to crop. */
3701
+ var FULL_FRAME_EPSILON = 1e-6;
3702
+ function isFullFrame(rect) {
3703
+ return Math.abs(rect.x) < FULL_FRAME_EPSILON && Math.abs(rect.y) < FULL_FRAME_EPSILON && Math.abs(rect.width - 1) < FULL_FRAME_EPSILON && Math.abs(rect.height - 1) < FULL_FRAME_EPSILON;
3704
+ }
3705
+ /**
3706
+ * yuv420p subsamples chroma 2x2, so an odd width or height is rejected by every
3707
+ * encoder we use. Rounding here lets the reason be stated; rounding inside the
3708
+ * child is a start-up failure with no context.
3709
+ */
3710
+ function toEven(value) {
3711
+ const rounded = Math.round(value);
3712
+ const even = rounded % 2 === 0 ? rounded : rounded - 1;
3713
+ return Math.max(2, even);
3714
+ }
3715
+ function assertWithin(rect, what, cellIndex) {
3716
+ if (rect.x < 0 || rect.y < 0 || rect.width <= 0 || rect.height <= 0 || rect.x + rect.width > 1.000001 || rect.y + rect.height > 1.000001) throw new Error(`camera-grid: cell ${cellIndex} falls ${what} (x=${rect.x} y=${rect.y} w=${rect.width} h=${rect.height}) — ffmpeg would render this as a silently clipped picture`);
3717
+ }
3718
+ /**
3719
+ * `crop` resolved against the source's OWN size at runtime (`iw`/`ih`), never
3720
+ * against a resolution guessed here. That is what makes the stored rectangle
3721
+ * survive a source that changes resolution.
3722
+ */
3723
+ function cropExpression(source) {
3724
+ return `crop=iw*${source.width}:ih*${source.height}:iw*${source.x}:ih*${source.y}`;
3725
+ }
3726
+ function buildGridFilterGraph(layout) {
3727
+ if (layout.cells.length === 0) throw new Error("camera-grid: a composite needs at least one cell to emit anything");
3728
+ const steps = [`color=c=black:s=${layout.width}x${layout.height}:d=1[${CANVAS_LABEL}]`];
3729
+ const cellLabels = [];
3730
+ layout.cells.forEach((cell, index) => {
3731
+ assertWithin(cell.source, "outside its source", index);
3732
+ assertWithin(cell.cell, "outside the canvas", index);
3733
+ const targetWidth = toEven(cell.cell.width * layout.width);
3734
+ const targetHeight = toEven(cell.cell.height * layout.height);
3735
+ const label = `c${index}`;
3736
+ const filters = [...isFullFrame(cell.source) ? [] : [cropExpression(cell.source)], `scale=${targetWidth}:${targetHeight}`];
3737
+ steps.push(`[${cell.inputIndex}:v]${filters.join(",")}[${label}]`);
3738
+ cellLabels.push(label);
3739
+ });
3740
+ let base = CANVAS_LABEL;
3741
+ layout.cells.forEach((cell, index) => {
3742
+ const x = Math.round(cell.cell.x * layout.width);
3743
+ const y = Math.round(cell.cell.y * layout.height);
3744
+ const out = index === layout.cells.length - 1 ? OUT_LABEL : `s${index}`;
3745
+ steps.push(`[${base}][${cellLabels[index]}]overlay=${x}:${y}[${out}]`);
3746
+ base = out;
3747
+ });
3748
+ return {
3749
+ graph: steps.join(";"),
3750
+ videoOutLabel: OUT_LABEL
3751
+ };
3752
+ }
3753
+ //#endregion
3754
+ //#region src/builtins/camera-grid/grid-stream-invocation.ts
3755
+ /**
3756
+ * The encoder preset. `veryfast` because a composite is the one encode in the
3757
+ * cluster whose input cost already scales with the number of cameras in it —
3758
+ * the decode side of a 2x2 is four decodes — so the encode side is where a
3759
+ * cheap default matters most.
3760
+ */
3761
+ var PRESET = "veryfast";
3762
+ /**
3763
+ * `-tune zerolatency`, and this one is worth several SECONDS.
3764
+ *
3765
+ * x264's defaults hold frames before emitting any: a rate-control lookahead of
3766
+ * ~40 frames plus B-frames. At a composite's 10 fps that lookahead alone is
3767
+ * about four seconds of picture sitting inside the encoder — the operator saw
3768
+ * it as "ritardi di secondi" and it was not the network, the relay or the
3769
+ * broker. `zerolatency` sets `rc-lookahead=0`, `sync-lookahead=0` and
3770
+ * `bframes=0`, which is exactly the trade a live composite wants: a few percent
3771
+ * more bitrate for the same picture, in exchange for the encoder emitting each
3772
+ * frame as it arrives.
3773
+ *
3774
+ * It is not a preset. `veryfast` says how hard the encoder searches; this says
3775
+ * how long it is allowed to WAIT, and the two are independent.
3776
+ */
3777
+ var TUNE = "zerolatency";
3778
+ /** yuv420p: the only pixel format every consumer of a CamStack profile reads. */
3779
+ var PIXEL_FORMAT = "yuv420p";
3780
+ /**
3781
+ * Key-frame cadence, in seconds.
3782
+ *
3783
+ * Two things ride on this and they pull the same way. A recorder cuts its
3784
+ * segments on a key frame, so a long GOP produces long segments and a scrub
3785
+ * that lands far from where the operator clicked. And every consumer — the
3786
+ * broker's reader included — starts at a key frame, so the GOP is the WORST
3787
+ * CASE wait before a grid appears at all: at two seconds a viewer could stare
3788
+ * at nothing for two seconds after pressing play.
3789
+ *
3790
+ * One second halves that wait. It costs bitrate (an IDR is expensive and there
3791
+ * are now twice as many), which is why it is not lower: below a second the
3792
+ * bitrate paid buys a wait nobody can feel.
3793
+ */
3794
+ var GOP_SECONDS = 1;
3795
+ /**
3796
+ * `-analyzeduration` / `-probesize`, as small as ffmpeg allows.
3797
+ *
3798
+ * ## The probes are SEQUENTIAL, and this is what the tile skew was
3799
+ *
3800
+ * The sentence that used to be here said the probes are "PARALLEL inputs of one
3801
+ * child". They are not. ffmpeg opens its inputs one after another and each open
3802
+ * BLOCKS in `avformat_find_stream_info` until its budget is spent — so input 0
3803
+ * is already connected and receiving while ffmpeg is still opening input 1, its
3804
+ * frames pile up, and `overlay` (which pairs inputs BY PTS) marries input 0's
3805
+ * oldest frame to input 1's newest. The lag is fixed for the life of the child:
3806
+ * both tiles then advance one frame per output frame, so nothing ever closes it.
3807
+ * The FIRST cell is the most behind; the last is live.
3808
+ *
3809
+ * Reproduced in one command on 2026-09-18 — two sources hstacked, one frame,
3810
+ * reading the cameras' own burnt-in clocks out of the composed picture:
3811
+ *
3812
+ * ```
3813
+ * 13:11:21 | 13:11:23 two seconds, and the earlier input is the late one
3814
+ * ```
3815
+ *
3816
+ * ## Why the old numbers cost seconds
3817
+ *
3818
+ * `-probesize` is a BYTE budget, and 1 MB of a 640x360 sub-stream is tens of
3819
+ * seconds of video — so `-analyzeduration 1s` never got the chance to stop it
3820
+ * and each open ran until the byte budget filled. Zero and 32 make the probe
3821
+ * return from the SDP, which already declares the codec, without reading media.
3822
+ *
3823
+ * Measured on this hub, the two sources of the live grid, three runs each,
3824
+ * production input args otherwise identical — time to the first composed frame,
3825
+ * and the skew read off the two burnt-in clocks in that frame:
3826
+ *
3827
+ * ```
3828
+ * 1 s / 1 MB 8986, 9728, 9712 ms skew 5 s, 5 s, 4 s
3829
+ * 0 / 32 2281, 2270, 2304 ms skew 1 s, 1 s, 0 s
3830
+ * ```
3831
+ *
3832
+ * The same numbers are the ~9 s cold start the operator had accepted: it was a
3833
+ * SUM of the opens, never the wait for the slowest source.
3834
+ *
3835
+ * Checked before shipping, because a probe that reads nothing has to survive
3836
+ * what it is not told: h264, h265 and a derived (`mid-to-low`) source all open
3837
+ * with `rc=0`, a 20 s run produces 200 frames of 200 either way (so the pacing
3838
+ * this file already lost once is untouched), and the skew is still 0 at 25 s
3839
+ * into a run — it is set at start-up and does not drift.
3840
+ *
3841
+ * What remains is the spread in when each source's first key frame arrives, and
3842
+ * a `/muted` dial waits for the next IDR. That spread is small here; if it ever
3843
+ * is not, the answer is to start the inputs from a join point we hold, NOT to
3844
+ * re-time the inputs (see `useWallclockTimestamps` below).
3845
+ */
3846
+ var ANALYZE_DURATION_US = 0;
3847
+ var PROBE_SIZE_BYTES = 32;
3848
+ function inputPlanFor(source) {
3849
+ return {
3850
+ url: source.url,
3851
+ rtspTransport: "tcp",
3852
+ fflags: ["+discardcorrupt"],
3853
+ lowDelay: true,
3854
+ analyzeDurationUs: ANALYZE_DURATION_US,
3855
+ probeSizeBytes: PROBE_SIZE_BYTES
3856
+ };
3857
+ }
3858
+ /**
3859
+ * @throws when the layout addresses an input the sources do not contain, or
3860
+ * when there is nothing to compose. Both are plan errors: ffmpeg would refuse
3861
+ * them at start-up with a message about a filter pad, which names the graph
3862
+ * rather than the configuration that produced it.
3863
+ */
3864
+ function gridStreamInvocation(input) {
3865
+ if (input.sources.length === 0 || input.layout.cells.length === 0) throw new Error("camera-grid: a composite needs at least one cell with a source before it can emit anything");
3866
+ for (const cell of input.layout.cells) if (cell.inputIndex < 0 || cell.inputIndex >= input.sources.length) throw new Error(`camera-grid: cell addresses input ordinal ${cell.inputIndex}, but only ${input.sources.length} input(s) were acquired`);
3867
+ const graph = buildGridFilterGraph(input.layout);
3868
+ const [first, ...rest] = input.sources;
3869
+ if (first === void 0) throw new Error("camera-grid: a composite needs at least one cell with a source");
3870
+ const video = {
3871
+ kind: "encode",
3872
+ encoder: input.encoder,
3873
+ preset: PRESET,
3874
+ tune: TUNE,
3875
+ pixelFormat: PIXEL_FORMAT,
3876
+ fps: input.fps,
3877
+ gopFrames: input.fps * GOP_SECONDS,
3878
+ bitrateKbps: input.bitrateKbps,
3879
+ scale: null
3880
+ };
3881
+ return {
3882
+ logLevel: "error",
3883
+ decodeHwAccel: input.decodeHwAccel,
3884
+ input: inputPlanFor(first),
3885
+ extraInputs: rest.map(inputPlanFor),
3886
+ filterGraph: graph,
3887
+ video,
3888
+ audio: { kind: "none" },
3889
+ threadCount: 0,
3890
+ outputArgs: [],
3891
+ sink: {
3892
+ kind: "stdout",
3893
+ container: "flv"
3894
+ }
3895
+ };
3896
+ }
3897
+ //#endregion
3898
+ //#region src/builtins/camera-grid/grid-child.ts
3899
+ /**
3900
+ * Spawning the composition, through the ONE primitive.
3901
+ *
3902
+ * `FfmpegProcess` (`@camstack/types`) owns spawn, the first-data deadline, the
3903
+ * hardware→software retry, exit classification and the bounded restart. This
3904
+ * file owns only the PLUMBING — which bytes go where — because that is the one
3905
+ * thing the primitive deliberately does not own.
3906
+ *
3907
+ * `maxRestarts: 0`. A composite is demand-driven: if the child dies, the
3908
+ * session tells every consumer why and tears down, and the consumer's next read
3909
+ * starts a cold one with freshly acquired sources. A restart inside the process
3910
+ * would reuse broker handles that may already have been released.
3911
+ */
3912
+ /** No first-data deadline retry loop: one attempt, and the session hears about it. */
3913
+ var FIRST_DATA_TIMEOUT_MS = 15e3;
3914
+ async function startGridChild(ctx, plan, sources, onEnded) {
3915
+ const invocation = (decodeHwAccel) => gridStreamInvocation({
3916
+ layout: plan.layout,
3917
+ sources: plan.sourceDeviceIds.map((deviceId, index) => ({
3918
+ deviceId,
3919
+ url: sources[index]?.url ?? ""
3920
+ })),
3921
+ decodeHwAccel,
3922
+ encoder: plan.encoder,
3923
+ fps: plan.fps,
3924
+ bitrateKbps: plan.bitrateKbps
3925
+ });
3926
+ let stdout = null;
3927
+ const process = new FfmpegProcess({
3928
+ binaryPath: ctx.binaryPath,
3929
+ buildArgs: (decodeHwAccel) => buildFfmpegArgs(invocation(decodeHwAccel)),
3930
+ decodeHwAccel: plan.decodeHwAccel,
3931
+ logger: ctx.logger,
3932
+ deviceId: ctx.deviceId,
3933
+ role: "camera-grid",
3934
+ tags: {
3935
+ cells: plan.layout.cells.length,
3936
+ inputs: plan.sourceDeviceIds.length
3937
+ },
3938
+ firstDataTimeoutMs: FIRST_DATA_TIMEOUT_MS,
3939
+ maxRestarts: 0,
3940
+ onChild: (child) => {
3941
+ if (child.stdout) stdout = child.stdout;
3942
+ child.stderr?.on("data", () => {});
3943
+ },
3944
+ onExit: (exit) => {
3945
+ onEnded(exit.classification);
3946
+ }
3947
+ });
3948
+ await process.start();
3949
+ if (stdout === null) {
3950
+ await process.stop();
3951
+ throw new Error("camera-grid: the composition child produced no stdout to read");
3952
+ }
3953
+ return {
3954
+ stdout,
3955
+ stop: async () => {
3956
+ await process.stop();
3957
+ }
3958
+ };
3959
+ }
3960
+ //#endregion
3961
+ export { CameraGridAddon, CameraGridAddon as default, GRID_CAM_STREAM_ID, GRID_PROFILES, GRID_SILENCED_CAP_NAMES, GridCameraDevice, GridFrameSampler, GridLastFrameFileStore, GridSnapshotSource, GridStreamRelay, GridStreamSession, buildGridCameraDeclarations, buildGridFilterGraph, deriveGridCanvas, gridCamStreamId, gridCameraReconciliationIndex, gridPlanFor, gridProfilePlans, gridSnapshotAnswerFor, gridSourceDial, gridStreamDescriptor, gridStreamInvocation, installGridCameraRuntime, newGridCameraStableId, normalizeGridRows, parseGridStreamPath, readGridInstances, silenceAnalysisFor, startGridChild };