@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,2720 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ const require_chunk = require("../../chunk-Cek0wNdY.js");
6
+ const require_dist = require("../../dist-M9yHiIY7.js");
7
+ const require_snapshot_courtesy = require("../../snapshot-courtesy-D_C5-nC0.js");
8
+ let zod = require("zod");
9
+ let node_crypto = require("node:crypto");
10
+ let _camstack_types_node = require("@camstack/types/node");
11
+ let node_path = require("node:path");
12
+ let node_fs = require("node:fs");
13
+ let node_child_process = require("node:child_process");
14
+ let sharp = require("sharp");
15
+ sharp = require_chunk.__toESM(sharp);
16
+ //#region src/builtins/snapshot/snapshot-cache.ts
17
+ /** A request with no explicit stream is its OWN entry, not a wildcard: the
18
+ * per-device preference decides what it captures, and conflating it with an
19
+ * explicit request is how the original bug read. */
20
+ var AUTO = "auto";
21
+ function keyOf(deviceId, streamId) {
22
+ return `${deviceId}:${streamId ?? AUTO}`;
23
+ }
24
+ var SnapshotCache = class {
25
+ byKey = /* @__PURE__ */ new Map();
26
+ /** deviceId → its live keys, so invalidation is O(streams) not O(cache). */
27
+ keysByDevice = /* @__PURE__ */ new Map();
28
+ maxBytes;
29
+ idleTtlMs;
30
+ now;
31
+ onEvict;
32
+ totalBytes = 0;
33
+ constructor(options = {}) {
34
+ this.maxBytes = options.maxBytes ?? 67108864;
35
+ this.idleTtlMs = options.idleTtlMs ?? 36e5;
36
+ this.now = options.now ?? (() => Date.now());
37
+ this.onEvict = options.onEvict;
38
+ }
39
+ get(deviceId, streamId) {
40
+ return this.read(keyOf(deviceId, streamId));
41
+ }
42
+ set(deviceId, streamId, entry) {
43
+ const key = keyOf(deviceId, streamId);
44
+ this.forget(key);
45
+ this.byKey.set(key, {
46
+ entry,
47
+ deviceId,
48
+ bytes: entry.data.base64.length,
49
+ lastAccessAt: this.now()
50
+ });
51
+ this.totalBytes += entry.data.base64.length;
52
+ const keys = this.keysByDevice.get(deviceId) ?? /* @__PURE__ */ new Set();
53
+ keys.add(key);
54
+ this.keysByDevice.set(deviceId, keys);
55
+ this.enforceBudget(key);
56
+ }
57
+ /** The newest entry for a device, whichever stream produced it. */
58
+ latest(deviceId) {
59
+ let newest;
60
+ for (const key of [...this.keysByDevice.get(deviceId) ?? []]) {
61
+ const entry = this.read(key);
62
+ if (entry !== void 0 && (newest === void 0 || entry.ts > newest.ts)) newest = entry;
63
+ }
64
+ return newest;
65
+ }
66
+ /** Base64 bytes currently retained. The number the budget is enforced on. */
67
+ sizeBytes() {
68
+ return this.totalBytes;
69
+ }
70
+ /** Entries currently retained. */
71
+ entryCount() {
72
+ return this.byKey.size;
73
+ }
74
+ /** Read through the idle timeout: an entry nobody has touched inside
75
+ * `idleTtlMs` is dropped here rather than on a sweep, so the cost is paid by
76
+ * the caller that proves it was not wanted. */
77
+ read(key) {
78
+ const slot = this.byKey.get(key);
79
+ if (slot === void 0) return void 0;
80
+ const at = this.now();
81
+ if (at - slot.lastAccessAt > this.idleTtlMs) {
82
+ this.evict(key, "idle");
83
+ return;
84
+ }
85
+ slot.lastAccessAt = at;
86
+ return slot.entry;
87
+ }
88
+ /** Evict least-recently-ACCESSED first until the budget holds. `protectedKey`
89
+ * is the entry just written — evicting it would make `set` a no-op. */
90
+ enforceBudget(protectedKey) {
91
+ if (this.totalBytes <= this.maxBytes) return;
92
+ const coldestFirst = [...this.byKey.entries()].filter(([key]) => key !== protectedKey).toSorted((a, b) => a[1].lastAccessAt - b[1].lastAccessAt);
93
+ for (const [key] of coldestFirst) {
94
+ if (this.totalBytes <= this.maxBytes) return;
95
+ this.evict(key, "budget");
96
+ }
97
+ }
98
+ evict(key, reason) {
99
+ const slot = this.byKey.get(key);
100
+ if (slot === void 0) return;
101
+ this.forget(key);
102
+ this.onEvict?.(slot.deviceId, slot.entry.streamId, reason);
103
+ }
104
+ /** Remove a key and everything that indexes or accounts for it. */
105
+ forget(key) {
106
+ const slot = this.byKey.get(key);
107
+ if (slot === void 0) return;
108
+ this.totalBytes -= slot.bytes;
109
+ this.byKey.delete(key);
110
+ const keys = this.keysByDevice.get(slot.deviceId);
111
+ if (keys !== void 0) {
112
+ keys.delete(key);
113
+ if (keys.size === 0) this.keysByDevice.delete(slot.deviceId);
114
+ }
115
+ }
116
+ /**
117
+ * Drop every stream of one device.
118
+ *
119
+ * Device-wide on purpose: a settings change or an operator refresh
120
+ * invalidates the CAMERA, and leaving a sibling entry behind would keep
121
+ * serving the pre-change frame from the other key.
122
+ */
123
+ deleteDevice(deviceId) {
124
+ for (const key of [...this.keysByDevice.get(deviceId) ?? []]) this.forget(key);
125
+ this.keysByDevice.delete(deviceId);
126
+ }
127
+ clear() {
128
+ this.byKey.clear();
129
+ this.keysByDevice.clear();
130
+ this.totalBytes = 0;
131
+ }
132
+ };
133
+ //#endregion
134
+ //#region src/builtins/snapshot/snapshot-durable-store.ts
135
+ /**
136
+ * The last good frame per camera, on disk, so it outlives the process.
137
+ *
138
+ * ## Why
139
+ *
140
+ * The snapshot cache is RAM-only and says so: *"after a hub restart this
141
+ * legitimately answers nothing and the generated card is the picture"*. That is
142
+ * accurate and it is also the whole defect, because the cameras that most need
143
+ * a cached frame are the ones that can never be asked for a fresh one. A
144
+ * sleeping battery camera refuses every snapshot that does not carry `force`,
145
+ * and the sentry deliberately never passes it — forcing would wake the very
146
+ * camera the window exists so as not to disturb.
147
+ *
148
+ * Measured 2026-09-17: the baby monitor showed the courtesy card all morning.
149
+ * Nothing was broken. Three server updates had emptied the cache, and the
150
+ * camera had been asleep since.
151
+ *
152
+ * ## Shape
153
+ *
154
+ * One file per device under the addon's OWN private directory (`ctx.dataDir` —
155
+ * `<nodeDataDir>/addons-data/<addonId>`, which the addon owns exclusively), and
156
+ * it is overwritten rather than appended: what is wanted is A recent frame, not
157
+ * a history. A history here would grow without a reaper and compete with the
158
+ * recordings for the same disk.
159
+ *
160
+ * Writes are THROTTLED per device. Snapshots are captured far more often than a
161
+ * process restarts, and persisting every one buys nothing — one recent frame is
162
+ * the entire value.
163
+ *
164
+ * Nothing here throws. The caller already has its picture; persistence is a
165
+ * bonus for the NEXT boot, and a disk that refuses must never cost a snapshot
166
+ * that succeeded. A frame that cannot be read is reported ABSENT, never as an
167
+ * error and never as an empty buffer — absent is the truth and the courtesy
168
+ * card is the correct answer to it.
169
+ */
170
+ /** One recent frame is the value; a newer one is not worth the disk. */
171
+ var DEFAULT_MIN_INTERVAL_MS = 6e4;
172
+ /** Its own subdirectory, so the addon's other state is never mistaken for a frame. */
173
+ var SUBDIR = "last-frame";
174
+ /** Monotonic within the process; with the pid it makes a staging name unique. */
175
+ var stagingSeq = 0;
176
+ function nextStagingId() {
177
+ stagingSeq += 1;
178
+ return stagingSeq;
179
+ }
180
+ var SnapshotDurableStore = class {
181
+ dir;
182
+ minIntervalMs;
183
+ now;
184
+ logger;
185
+ /** Last write per device, so the throttle survives without touching disk. */
186
+ lastWriteMs = /* @__PURE__ */ new Map();
187
+ constructor(options) {
188
+ this.dir = (0, node_path.join)(options.dataDir, SUBDIR);
189
+ this.minIntervalMs = options.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS;
190
+ this.now = options.now ?? (() => Date.now());
191
+ this.logger = options.logger;
192
+ }
193
+ /** @returns whether the frame was written. `false` is throttled or refused. */
194
+ async put(deviceId, jpeg) {
195
+ if (jpeg.length === 0) return false;
196
+ const at = this.now();
197
+ const previous = this.lastWriteMs.get(deviceId);
198
+ if (previous !== void 0 && at - previous < this.minIntervalMs) return false;
199
+ try {
200
+ await node_fs.promises.mkdir(this.dir, { recursive: true });
201
+ const target = this.pathFor(deviceId);
202
+ const staging = `${target}.${String(process.pid)}.${String(nextStagingId())}.writing`;
203
+ try {
204
+ await node_fs.promises.writeFile(staging, jpeg);
205
+ await node_fs.promises.rename(staging, target);
206
+ } catch (err) {
207
+ await node_fs.promises.rm(staging, { force: true }).catch(() => void 0);
208
+ throw err;
209
+ }
210
+ this.lastWriteMs.set(deviceId, at);
211
+ return true;
212
+ } catch (err) {
213
+ this.logger?.warn("durable last-frame write failed", {
214
+ tags: { deviceId },
215
+ meta: { error: require_dist.errMsg(err) }
216
+ });
217
+ return false;
218
+ }
219
+ }
220
+ /** The frame from a previous process, or `null` — which is a real answer. */
221
+ async get(deviceId) {
222
+ return (await this.getDated(deviceId))?.jpeg ?? null;
223
+ }
224
+ /**
225
+ * The frame WITH the moment it was captured.
226
+ *
227
+ * The age travels with it because everything downstream decides on age, and
228
+ * a frame restored from disk that claims to be new is worse than no frame:
229
+ * it would satisfy a freshness gate it has no right to pass. The file's own
230
+ * mtime is the honest answer — it is when this frame was written.
231
+ */
232
+ async getDated(deviceId) {
233
+ try {
234
+ const path = this.pathFor(deviceId);
235
+ const [jpeg, stat] = await Promise.all([node_fs.promises.readFile(path), node_fs.promises.stat(path)]);
236
+ if (jpeg.length === 0) return null;
237
+ return {
238
+ jpeg,
239
+ capturedAtMs: stat.mtimeMs
240
+ };
241
+ } catch {
242
+ return null;
243
+ }
244
+ }
245
+ pathFor(deviceId) {
246
+ return (0, node_path.join)(this.dir, `${String(deviceId)}.jpg`);
247
+ }
248
+ };
249
+ //#endregion
250
+ //#region src/builtins/snapshot/snapshot-coalescing.ts
251
+ /**
252
+ * Pure, side-effect-free coalescing / stale-while-revalidate / bounded-pool
253
+ * primitives for the snapshot wrapper.
254
+ *
255
+ * These are extracted from `SnapshotAddon` so the decision logic is unit-testable
256
+ * without instantiating the addon (no camera, no ffmpeg, no tRPC). The addon wires
257
+ * them to its cache + ladder; this module owns only the mechanics:
258
+ *
259
+ * - {@link decideSnapshotServe} — the pure serve/refresh decision (fresh cache vs
260
+ * stale-while-revalidate vs cold blocking capture) keyed off the cached frame
261
+ * age, the per-device max-age, and whether the caller forced a refresh.
262
+ * - {@link Semaphore} — a counting semaphore bounding concurrent grabs.
263
+ * - {@link SingleFlight} — de-dupes concurrent captures for the same key and
264
+ * retains a SETTLED success for a short hold window so a mount burst collapses
265
+ * into one capture.
266
+ * - {@link raceForResult} — races a promise against a wait bound without
267
+ * cancelling the promise (the loser keeps running in the background).
268
+ */
269
+ /**
270
+ * Retain a SETTLED single-flight capture this long so a grid-mount burst of
271
+ * `getSnapshot` calls (and a row of refresh buttons) collapses into ONE capture
272
+ * instead of one dial per tile. Only success outcomes are held — a null/failed
273
+ * capture expires immediately so a transiently-unreachable camera is retried on
274
+ * the next call rather than pinned blank for the window.
275
+ */
276
+ var COALESCE_MS = 4e3;
277
+ /**
278
+ * Stale-while-revalidate: when a cached frame exists but is past its max-age,
279
+ * start the refresh and wait at most this long for it to land before returning
280
+ * the STALE frame (the refresh keeps running and populates the cache for the
281
+ * next poll). Keeps a grid mount painting instantly from cache.
282
+ */
283
+ var SWR_STALE_WAIT_MS = 2500;
284
+ /**
285
+ * Cold path (no cached frame) or a forced refresh: wait up to this long for a
286
+ * fresh capture. On a cold miss there is nothing to fall back to, so we block
287
+ * (bounded) on the capture; on a forced refresh with a stale frame available we
288
+ * still prefer a fresh one but cap the wait, falling back to stale on timeout.
289
+ */
290
+ var SWR_COLD_WAIT_MS = 1e4;
291
+ /**
292
+ * Pure serve/refresh decision.
293
+ *
294
+ * - fresh cache + !force -> serve-cache
295
+ * - stale cache + !force -> SWR: wait SWR_STALE_WAIT_MS, then stale
296
+ * - no cache + !force -> cold: wait SWR_COLD_WAIT_MS, no fallback
297
+ * - force (cache present or not) -> prefer fresh: wait SWR_COLD_WAIT_MS,
298
+ * fall back to stale only if a frame exists
299
+ */
300
+ function decideSnapshotServe(input) {
301
+ const { now, cachedAt, effectiveMaxAgeMs, force } = input;
302
+ const hasFrame = cachedAt !== null;
303
+ const fresh = hasFrame && now - cachedAt < effectiveMaxAgeMs;
304
+ if (!force && fresh) return { kind: "serve-cache" };
305
+ if (force) return {
306
+ kind: "await-refresh",
307
+ waitMs: SWR_COLD_WAIT_MS,
308
+ staleFallback: hasFrame
309
+ };
310
+ if (hasFrame) return {
311
+ kind: "await-refresh",
312
+ waitMs: SWR_STALE_WAIT_MS,
313
+ staleFallback: true
314
+ };
315
+ return {
316
+ kind: "await-refresh",
317
+ waitMs: SWR_COLD_WAIT_MS,
318
+ staleFallback: false
319
+ };
320
+ }
321
+ /**
322
+ * A counting semaphore. `run` acquires a permit, awaits `fn`, and releases the
323
+ * permit (even if `fn` throws), so at most `max` `fn`s run concurrently. Waiters
324
+ * are served FIFO.
325
+ */
326
+ var Semaphore = class {
327
+ available;
328
+ waiters = [];
329
+ constructor(max) {
330
+ if (!Number.isInteger(max) || max < 1) throw new Error(`Semaphore max must be a positive integer, got ${String(max)}`);
331
+ this.available = max;
332
+ }
333
+ async run(fn) {
334
+ const release = await this.acquire();
335
+ try {
336
+ return await fn();
337
+ } finally {
338
+ release();
339
+ }
340
+ }
341
+ async acquire() {
342
+ if (this.available > 0) {
343
+ this.available -= 1;
344
+ return this.makeReleaser();
345
+ }
346
+ await new Promise((resolve) => this.waiters.push(resolve));
347
+ return this.makeReleaser();
348
+ }
349
+ makeReleaser() {
350
+ let released = false;
351
+ return () => {
352
+ if (released) return;
353
+ released = true;
354
+ const next = this.waiters.shift();
355
+ if (next) {
356
+ next();
357
+ return;
358
+ }
359
+ this.available += 1;
360
+ };
361
+ }
362
+ };
363
+ /**
364
+ * One in-flight capture per key. A settled SUCCESS is retained for `holdMs` so a
365
+ * burst collapses into one capture; a settled failure/empty expires immediately
366
+ * so the next caller retries. Concurrent callers ALWAYS join the running flight
367
+ * regardless of eventual outcome.
368
+ */
369
+ var Flight = class {
370
+ promise;
371
+ settledAt = null;
372
+ hold = false;
373
+ constructor(factory, now, holdWorthy) {
374
+ this.promise = (async () => {
375
+ try {
376
+ const value = await factory();
377
+ this.hold = holdWorthy(value);
378
+ return value;
379
+ } catch (err) {
380
+ this.hold = false;
381
+ throw err;
382
+ } finally {
383
+ this.settledAt = now();
384
+ }
385
+ })();
386
+ }
387
+ };
388
+ var SingleFlight = class {
389
+ holdMs;
390
+ holdWorthy;
391
+ now;
392
+ flights = /* @__PURE__ */ new Map();
393
+ /**
394
+ * @param holdMs how long a settled hold-worthy result is reused
395
+ * @param holdWorthy predicate deciding whether a settled value is worth holding
396
+ * (e.g. a successful capture with a real frame)
397
+ * @param now clock injection for tests
398
+ */
399
+ constructor(holdMs, holdWorthy, now = () => Date.now()) {
400
+ this.holdMs = holdMs;
401
+ this.holdWorthy = holdWorthy;
402
+ this.now = now;
403
+ }
404
+ run(key, factory) {
405
+ const existing = this.flights.get(key);
406
+ if (existing && this.isReusable(existing)) return existing.promise;
407
+ const flight = new Flight(factory, this.now, this.holdWorthy);
408
+ this.flights.set(key, flight);
409
+ return flight.promise;
410
+ }
411
+ /** Drop every held flight whose key starts with `prefix` (e.g. `"<deviceId>:"`). */
412
+ invalidatePrefix(prefix) {
413
+ for (const key of [...this.flights.keys()]) if (key.startsWith(prefix)) this.flights.delete(key);
414
+ }
415
+ clear() {
416
+ this.flights.clear();
417
+ }
418
+ isReusable(flight) {
419
+ if (flight.settledAt === null) return true;
420
+ if (!flight.hold) return false;
421
+ return this.now() - flight.settledAt < this.holdMs;
422
+ }
423
+ };
424
+ /**
425
+ * Race `promise` against a `timeoutMs` bound WITHOUT cancelling it — on timeout
426
+ * the promise keeps running (its result lands in the cache for the next poll).
427
+ * Rejections propagate: if `promise` rejects before the timeout, this rejects.
428
+ * The caller passes a promise that never rejects (a settled outcome union) when
429
+ * background continuation must stay unhandled-safe.
430
+ */
431
+ function raceForResult(promise, timeoutMs) {
432
+ let timer;
433
+ const timeout = new Promise((resolve) => {
434
+ timer = setTimeout(() => resolve({ settled: false }), timeoutMs);
435
+ });
436
+ const settled = promise.then((value) => ({
437
+ settled: true,
438
+ value
439
+ }));
440
+ return Promise.race([settled, timeout]).finally(() => {
441
+ if (timer) clearTimeout(timer);
442
+ });
443
+ }
444
+ var NativeSnapshotFatigue = class {
445
+ baseMs;
446
+ maxMs;
447
+ entries = /* @__PURE__ */ new Map();
448
+ constructor(options = {}) {
449
+ this.baseMs = options.baseMs ?? 1e4;
450
+ this.maxMs = options.maxMs ?? 3e5;
451
+ }
452
+ /** The instant the rest ends, or `null` when the camera may be dialled now. */
453
+ restingUntil(deviceId, now) {
454
+ const entry = this.entries.get(deviceId);
455
+ if (entry === void 0 || entry.restingUntil <= now) return null;
456
+ return entry.restingUntil;
457
+ }
458
+ /** A dial that did not produce a frame — thrown or answered `null`. */
459
+ recordFailure(deviceId, now) {
460
+ const streak = (this.entries.get(deviceId)?.streak ?? 0) + 1;
461
+ const restMs = Math.min(this.maxMs, this.baseMs * 2 ** (streak - 1));
462
+ this.entries.set(deviceId, {
463
+ streak,
464
+ restingUntil: now + restMs
465
+ });
466
+ return {
467
+ streak,
468
+ restMs
469
+ };
470
+ }
471
+ /** A frame landed: the camera is answering again. */
472
+ recordSuccess(deviceId) {
473
+ this.entries.delete(deviceId);
474
+ }
475
+ forget(deviceId) {
476
+ this.entries.delete(deviceId);
477
+ }
478
+ };
479
+ //#endregion
480
+ //#region src/builtins/snapshot/snapshot-link-url.ts
481
+ /**
482
+ * Signed, expiring links to a CLIENT-SIZED snapshot frame.
483
+ *
484
+ * ## Why a link plane exists at all
485
+ *
486
+ * The authenticated `/addon/snapshot/media/<id>.jpg` plane works, and it is not
487
+ * going away. What it cannot do is guarantee that a client asking for a tile
488
+ * actually REACHES the server — and that turned out to be the whole bug.
489
+ *
490
+ * Under D93 the image URL is versioned by the frame identity, and an image
491
+ * request is what signalled demand for a camera. Both halves are satisfied by
492
+ * the client's own image cache: `expo-image` is URL-keyed and never
493
+ * revalidates, so a URL the app painted in a previous session is served from
494
+ * disk with **zero network**. Measured on the live hub, reopening the app after
495
+ * two minutes idle painted 15 of 16 tiles from disk — frames **168 s old**, with
496
+ * not one HTTP request, therefore no demand, therefore no capture. The
497
+ * operator's report ("gli snapshot sono vecchi, devo aggiornare più volte" [the snapshots are old, I have to refresh several times]) is
498
+ * that measurement.
499
+ *
500
+ * That gap used to be covered on BOTH sides — by this link plane and by a
501
+ * server-side keep-warm timer. The timer was removed on 2026-08-11 (operator
502
+ * directive: snapshots are on-demand, always), which makes this plane the only
503
+ * thing standing between a client cache and a frozen tile. It carries the whole
504
+ * job now.
505
+ *
506
+ * A minted link breaks the loop from both ends. It is produced by an RPC —
507
+ * `snapshot.getSnapshotLinks` — which no image cache can answer, so the demand
508
+ * signal always lands; and it carries the capture identity the RPC just WAITED
509
+ * for, rather than one a cache-only poll happened to be holding.
510
+ *
511
+ * ## What is signed, and what is only a cache key
512
+ *
513
+ * The signature covers `"<deviceId>:<width>"` and the expiry. The width is
514
+ * inside it deliberately: a leaked 240 px tile link must not be replayable as a
515
+ * request for the full 4 K frame. `v` (the capture identity) is NOT signed — it
516
+ * exists only to key the client's image cache, so an unchanged frame is a
517
+ * byte-identical URL and costs no bytes, and a new frame is a new URL and costs
518
+ * exactly one fetch.
519
+ *
520
+ * `exp` is bucketed rather than exact. A URL that were unique per mint would
521
+ * defeat the client cache completely — correct for freshness, and it would make
522
+ * a phone re-download every tile on every 5 s poll whether or not anything
523
+ * changed. Bucketing means the URL moves when the FRAME moves, and otherwise at
524
+ * most once per bucket.
525
+ *
526
+ * Pure and side-effect-free; the addon owns the secret and the clock. Unit
527
+ * tested in `__tests__/snapshot-link-url.spec.ts`.
528
+ */
529
+ /**
530
+ * How long a minted link stays valid.
531
+ *
532
+ * A snapshot is a live view of the operator's home, so this is short on purpose
533
+ * — the exposure of a leaked link is bounded by it. Two minutes is long enough
534
+ * that a page renders, re-renders and survives a brief backgrounding on the URL
535
+ * it was given, and short enough that a link pasted somewhere is dead before it
536
+ * is useful. The client re-mints on every overview poll (5 s), so it never
537
+ * depends on the tail of this window.
538
+ */
539
+ var SNAPSHOT_LINK_TTL_MS = 12e4;
540
+ /**
541
+ * Quantum the expiry is rounded UP to, so a link is stable between mints.
542
+ *
543
+ * Without it every mint produces a different `exp`, hence a different URL, hence
544
+ * a full re-download of an unchanged frame on every poll. With it the URL is a
545
+ * pure function of (device, width, frame, bucket) — so a tile fetches when its
546
+ * frame moves, and at most once more per bucket.
547
+ */
548
+ var SNAPSHOT_LINK_EXP_BUCKET_MS = 3e4;
549
+ /** The token the signature is computed over. Width is part of the identity so a
550
+ * tile link cannot be escalated into a full-frame request. */
551
+ function snapshotLinkId(deviceId, width) {
552
+ return `${String(deviceId)}:${width === void 0 ? "full" : String(width)}`;
553
+ }
554
+ /** The bucketed expiry for a link minted at `nowMs`. Always ≥ `nowMs + TTL`. */
555
+ function snapshotLinkExpiry(nowMs, ttlMs = SNAPSHOT_LINK_TTL_MS, bucketMs = SNAPSHOT_LINK_EXP_BUCKET_MS) {
556
+ return Math.ceil((nowMs + ttlMs) / bucketMs) * bucketMs;
557
+ }
558
+ /**
559
+ * The link, as a ROOT-RELATIVE path.
560
+ *
561
+ * Deliberately not absolute. The artifact and HA planes must mint absolute URLs
562
+ * because the fetcher is a phone or a notifier backend that has no idea where
563
+ * the hub is — and picking that base is the `hubUrl: localhost` trap the Alexa
564
+ * work paid for. Here the fetcher is a client that is already connected to the
565
+ * hub and holds its own `serverUrl`, so the correct base is the one it used to
566
+ * make the call. Returning a path makes it impossible to hand a client a link
567
+ * pointing somewhere it cannot reach.
568
+ */
569
+ function buildSnapshotLinkUrl(input) {
570
+ const base = (input.routePrefix.startsWith("/") ? input.routePrefix : `/${input.routePrefix}`).replace(/\/+$/, "");
571
+ const id = snapshotLinkId(input.deviceId, input.width);
572
+ const sig = (0, _camstack_types_node.signExpiringUrl)(input.secret, id, input.expMs);
573
+ const params = new URLSearchParams();
574
+ if (input.width !== void 0) params.set("w", String(input.width));
575
+ if (input.capturedAt !== null) params.set("v", String(input.capturedAt));
576
+ params.set("exp", String(input.expMs));
577
+ params.set("sig", sig);
578
+ return `${base}/${String(input.deviceId)}.jpg?${params.toString()}`;
579
+ }
580
+ /**
581
+ * Parse and VERIFY a link request in one step, so a caller cannot accidentally
582
+ * use the device id before checking the signature. Null = refuse (404/403);
583
+ * there is deliberately no way to distinguish "bad signature" from "expired"
584
+ * from "malformed" at this boundary, so a public route cannot be probed.
585
+ */
586
+ function parseVerifiedSnapshotLink(input) {
587
+ const qIdx = input.url.indexOf("?");
588
+ const rawPath = qIdx === -1 ? input.url : input.url.slice(0, qIdx);
589
+ const query = qIdx === -1 ? "" : input.url.slice(qIdx + 1);
590
+ const segment = rawPath.replace(/^\/+/, "");
591
+ if (segment.length === 0 || segment.includes("/")) return null;
592
+ const idPart = segment.replace(/\.jpe?g$/i, "");
593
+ if (!/^\d+$/.test(idPart)) return null;
594
+ const deviceId = Number.parseInt(idPart, 10);
595
+ if (!Number.isSafeInteger(deviceId) || deviceId <= 0) return null;
596
+ const params = new URLSearchParams(query);
597
+ const rawWidth = params.get("w");
598
+ if (rawWidth !== null && !/^\d+$/.test(rawWidth)) return null;
599
+ const width = rawWidth === null ? void 0 : Number.parseInt(rawWidth, 10);
600
+ if (width !== void 0 && (!Number.isSafeInteger(width) || width <= 0)) return null;
601
+ return (0, _camstack_types_node.verifyExpiringUrl)({
602
+ secret: input.secret,
603
+ id: snapshotLinkId(deviceId, width),
604
+ exp: params.get("exp") ?? void 0,
605
+ sig: params.get("sig") ?? void 0,
606
+ nowMs: input.nowMs
607
+ }) ? {
608
+ deviceId,
609
+ width
610
+ } : null;
611
+ }
612
+ //#endregion
613
+ //#region src/builtins/snapshot/snapshot-media-handler.ts
614
+ /**
615
+ * The widths a thumbnail may be served at.
616
+ *
617
+ * A ladder, not a free integer: the width is a cache key AND an ffmpeg run, so
618
+ * honouring `?w=` verbatim would let any caller mint unbounded work and
619
+ * unbounded memory. Twelve tiles measured at 181–240 px collapse onto one
620
+ * variant instead of twelve.
621
+ *
622
+ * Rungs are chosen for the card sizes the viewer actually renders (180–390 px)
623
+ * with headroom for a 2× device pixel ratio.
624
+ */
625
+ var SNAPSHOT_WIDTH_LADDER = [
626
+ 160,
627
+ 240,
628
+ 320,
629
+ 480,
630
+ 640,
631
+ 960
632
+ ];
633
+ /** Snap UP to the next rung — never below what was asked, so the client is not
634
+ * handed an image it has to upscale. Above the ladder, the largest rung: the
635
+ * point is to stop serving the 4K original. */
636
+ function snapSnapshotWidth(requested) {
637
+ for (const rung of SNAPSHOT_WIDTH_LADDER) if (requested <= rung) return rung;
638
+ return SNAPSHOT_WIDTH_LADDER[SNAPSHOT_WIDTH_LADDER.length - 1] ?? requested;
639
+ }
640
+ /**
641
+ * Parse the handler-relative path (`/<deviceId>.jpg?query`) into a request.
642
+ * Returns null for a malformed / nested / non-numeric id so the handler answers
643
+ * 404 without ever reaching `getMedia`.
644
+ */
645
+ function parseSnapshotMediaRequest(url) {
646
+ const qIdx = url.indexOf("?");
647
+ const rawPath = qIdx === -1 ? url : url.slice(0, qIdx);
648
+ const query = qIdx === -1 ? "" : url.slice(qIdx + 1);
649
+ const segment = rawPath.replace(/^\/+/, "");
650
+ if (segment.length === 0 || segment.includes("/")) return null;
651
+ const idPart = segment.replace(/\.jpe?g$/i, "");
652
+ if (!/^\d+$/.test(idPart)) return null;
653
+ const deviceId = Number.parseInt(idPart, 10);
654
+ if (!Number.isSafeInteger(deviceId)) return null;
655
+ const params = new URLSearchParams(query);
656
+ const rawStream = params.get("streamId");
657
+ const streamId = rawStream !== null && rawStream.length > 0 ? rawStream : void 0;
658
+ const rawForce = params.get("force");
659
+ const force = rawForce === "1" || rawForce === "true";
660
+ const rawWidth = params.get("w");
661
+ return {
662
+ deviceId,
663
+ streamId,
664
+ force,
665
+ width: rawWidth !== null && /^\d+$/.test(rawWidth) && Number.parseInt(rawWidth, 10) > 0 ? snapSnapshotWidth(Number.parseInt(rawWidth, 10)) : void 0
666
+ };
667
+ }
668
+ /**
669
+ * The response's entity tag.
670
+ *
671
+ * It has to identify the VARIANT, not just the frame: the same capture can now
672
+ * be served at several widths, from several streams, and with a camera-state
673
+ * treatment, and a plain
674
+ * `"<device>-<capturedAt>"` would let a client that fetched `?w=320` receive a
675
+ * 304 for `?w=960` and render the small image at full size. The base form is
676
+ * unchanged for a plain request, so the identity
677
+ * `snapshot.getSnapshotOverview` advertises still matches the frame nobody
678
+ * asked to resize.
679
+ */
680
+ function snapshotEtag(variant, capturedAt) {
681
+ const parts = [`${String(variant.deviceId)}-${String(capturedAt)}`];
682
+ if (variant.streamId !== void 0) parts.push(`s${variant.streamId}`);
683
+ if (variant.width !== void 0) parts.push(`w${String(variant.width)}`);
684
+ if (variant.variantKey !== void 0) parts.push(`v${variant.variantKey}`);
685
+ return `"${parts.join("-")}"`;
686
+ }
687
+ /**
688
+ * Create a data-plane handler that serves per-device snapshots as JPEG images.
689
+ * `deps.getMedia` is called once per request; null → 404, throw → 500. A
690
+ * conditional GET with a matching `If-None-Match` produces a 304.
691
+ */
692
+ function createSnapshotMediaHandler(deps) {
693
+ return async (req, res) => {
694
+ if (req.method !== "GET" && req.method !== "HEAD") {
695
+ res.writeHead(405, { allow: "GET, HEAD" }).end();
696
+ return;
697
+ }
698
+ const parsed = parseSnapshotMediaRequest(req.url ?? "/");
699
+ if (parsed === null) {
700
+ res.writeHead(404).end();
701
+ return;
702
+ }
703
+ const inm = req.headers["if-none-match"];
704
+ if (typeof inm === "string" && !parsed.force && deps.peekFresh !== void 0) {
705
+ let peeked = null;
706
+ try {
707
+ peeked = await deps.peekFresh(parsed.deviceId, parsed.streamId);
708
+ } catch {
709
+ peeked = null;
710
+ }
711
+ if (peeked !== null) {
712
+ const peekedEtag = snapshotEtag({
713
+ deviceId: parsed.deviceId,
714
+ streamId: parsed.streamId,
715
+ width: parsed.width,
716
+ variantKey: peeked.variantKey
717
+ }, peeked.capturedAt);
718
+ if (inm === peekedEtag) {
719
+ res.writeHead(304, {
720
+ etag: peekedEtag,
721
+ "cache-control": `private, max-age=${Math.max(0, Math.floor(peeked.maxAgeS))}`
722
+ }).end();
723
+ return;
724
+ }
725
+ }
726
+ }
727
+ let media;
728
+ try {
729
+ media = await deps.getMedia(parsed.deviceId, parsed.streamId, parsed.force, parsed.width);
730
+ } catch {
731
+ const body = "Internal server error";
732
+ res.writeHead(500, {
733
+ "content-type": "text/plain",
734
+ "content-length": String(Buffer.byteLength(body))
735
+ });
736
+ if (req.method === "HEAD") res.end();
737
+ else res.end(body);
738
+ return;
739
+ }
740
+ if (media === null) {
741
+ res.writeHead(404).end();
742
+ return;
743
+ }
744
+ const etag = snapshotEtag({
745
+ deviceId: parsed.deviceId,
746
+ streamId: parsed.streamId,
747
+ width: "servedWidth" in media ? media.servedWidth : parsed.width,
748
+ variantKey: media.variantKey
749
+ }, media.capturedAt);
750
+ const cacheControl = `private, max-age=${Math.max(0, Math.floor(media.maxAgeS))}`;
751
+ if (inm === etag) {
752
+ res.writeHead(304, {
753
+ etag,
754
+ "cache-control": cacheControl
755
+ }).end();
756
+ return;
757
+ }
758
+ res.writeHead(200, {
759
+ "content-type": media.contentType,
760
+ "cache-control": cacheControl,
761
+ etag,
762
+ "content-length": String(media.bytes.byteLength)
763
+ });
764
+ if (req.method === "HEAD") res.end();
765
+ else res.end(Buffer.from(media.bytes));
766
+ };
767
+ }
768
+ //#endregion
769
+ //#region src/builtins/snapshot/snapshot-resize.ts
770
+ /**
771
+ * Downscaling a captured frame to a card-sized thumbnail.
772
+ *
773
+ * Applied AFTER capture rather than during it, and that is deliberate: the two
774
+ * capture paths (the vendor's native HTTP snapshot and the ffmpeg keyframe
775
+ * grab) produce a JPEG by different routes, and only one of them has an
776
+ * ffmpeg filter chain to hook into. Resizing the finished bytes gives both the
777
+ * same behaviour with one implementation.
778
+ *
779
+ * ── Why sharp and not ffmpeg (2026-08-11) ─────────────────────────────────
780
+ * This used to `spawn('ffmpeg')` per resize. The snapshot wrapper is a system
781
+ * builtin, so it loads in the hub's ROOT process: sampled on the live hub,
782
+ * ~1.6 of those children were running at any instant, every one of them
783
+ * parented by the root PID.
784
+ *
785
+ * Be precise about what that cost the root process, because it is easy to
786
+ * overstate. The transcode itself ran in the CHILD and was charged to ffmpeg
787
+ * (16 % + 13 % of a core in that same sample), not to the parent. What the
788
+ * parent paid was the fork, the exec, the JPEG written into one pipe and read
789
+ * back out of the other, and the base64 — real event-loop work, on the loop
790
+ * that also serves the tRPC API, but NOT the 52 ms below.
791
+ *
792
+ * Benchmarked in that container, 2560×1440 → 640 wide, wall-clock per resize:
793
+ *
794
+ * ffmpeg 52.0 ms (fork + exec + pipe round-trip + teardown)
795
+ * sharp 4.8 ms (in-process libvips, on its own threadpool)
796
+ *
797
+ * So this removes ~29 % of a core of container CPU and the per-resize process
798
+ * churn from the root process. It was NOT verified to be the cause of that
799
+ * process sitting at 90 % — nobody has profiled it.
800
+ *
801
+ * `sharp` is not a new dependency: it is already a host-external
802
+ * (`HOST_EXTERNAL_SPECIFIERS`), already resolved from the framework closure at
803
+ * runtime, and already used by the terminal frame renderer. The build preset
804
+ * keeps it out of the bundle, so this import costs nothing at pack time.
805
+ *
806
+ * The cost is still one resize per (device, stream, width) per cache window —
807
+ * not one per request. What changed is what a resize COSTS.
808
+ */
809
+ var RESIZE_TIMEOUT_MS = 1e4;
810
+ /**
811
+ * Encode quality for a derived thumbnail. Matches what the ffmpeg path
812
+ * produced (`-q:v 5` on the mjpeg encoder) closely enough that no card visibly
813
+ * changes — this migration is about COST, not about re-tuning the picture.
814
+ */
815
+ var JPEG_QUALITY = 82;
816
+ /**
817
+ * Scale to `width`, preserving aspect ratio.
818
+ *
819
+ * Rejects on failure or timeout. It NEVER falls back to the original silently —
820
+ * a caller that quietly served the 4K frame when the resize failed would
821
+ * reproduce exactly the bug this whole module exists to fix, and nobody would
822
+ * see it. The caller decides, and logs.
823
+ *
824
+ * It DOES upscale a source narrower than `width`, and that is deliberate. A
825
+ * `withoutEnlargement: true` was tried first — it is the obvious saving, since
826
+ * upscaling pays encode cost for a blurrier, larger image. But the caller
827
+ * stamps the response ETag from the width it asked for, and its resize-FAILURE
828
+ * path already returns `width: undefined` specifically so a response can never
829
+ * "claim a width the bytes do not have". Silently returning 320 px bytes for a
830
+ * `w=640` request breaks that invariant on the SUCCESS path, where nobody is
831
+ * looking. Honest output width beats a few saved pixels; revisit only together
832
+ * with the ETag.
833
+ */
834
+ function resizeJpeg(bytes, width, timeoutMs = RESIZE_TIMEOUT_MS) {
835
+ const work = (0, sharp.default)(bytes).resize({ width }).jpeg({
836
+ quality: JPEG_QUALITY,
837
+ mozjpeg: false
838
+ }).toBuffer().then((out) => {
839
+ if (out.length === 0) throw new Error("snapshot resize produced no bytes");
840
+ return out;
841
+ });
842
+ let timer;
843
+ const bound = new Promise((_, reject) => {
844
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`snapshot resize timed out after ${String(timeoutMs)}ms`)), timeoutMs);
845
+ });
846
+ return Promise.race([work, bound]).finally(() => {
847
+ if (timer !== void 0) clearTimeout(timer);
848
+ });
849
+ }
850
+ var SnapshotVariantCache = class SnapshotVariantCache {
851
+ byKey = /* @__PURE__ */ new Map();
852
+ keysByDevice = /* @__PURE__ */ new Map();
853
+ maxBytes;
854
+ now;
855
+ totalBytes = 0;
856
+ constructor(options = {}) {
857
+ this.maxBytes = options.maxBytes ?? 16777216;
858
+ this.now = options.now ?? (() => Date.now());
859
+ }
860
+ static key(deviceId, streamId, width, variantKey) {
861
+ return `${deviceId}:${streamId ?? "auto"}:${width}:${variantKey ?? "raw"}`;
862
+ }
863
+ /** The variant for this exact frame, or undefined when it is missing or was
864
+ * derived from an older capture.
865
+ *
866
+ * A superseded variant is DELETED here, not merely reported missing. It used
867
+ * to be left in the map: unreachable by every future read (its `sourceTs` can
868
+ * never match again) and removed by nothing, so every recapture added a dead
869
+ * key. Returning `undefined` while retaining the bytes is the leak. */
870
+ get(deviceId, streamId, width, sourceTs, variantKey) {
871
+ const key = SnapshotVariantCache.key(deviceId, streamId, width, variantKey);
872
+ const slot = this.byKey.get(key);
873
+ if (slot === void 0) return void 0;
874
+ if (slot.sourceTs !== sourceTs) {
875
+ this.forget(key);
876
+ return;
877
+ }
878
+ slot.lastAccessAt = this.now();
879
+ return slot.bytes;
880
+ }
881
+ set(deviceId, streamId, width, sourceTs, bytes, variantKey) {
882
+ const key = SnapshotVariantCache.key(deviceId, streamId, width, variantKey);
883
+ this.forget(key);
884
+ this.byKey.set(key, {
885
+ bytes,
886
+ sourceTs,
887
+ deviceId,
888
+ lastAccessAt: this.now()
889
+ });
890
+ this.totalBytes += bytes.byteLength;
891
+ const keys = this.keysByDevice.get(deviceId) ?? /* @__PURE__ */ new Set();
892
+ keys.add(key);
893
+ this.keysByDevice.set(deviceId, keys);
894
+ this.enforceBudget(key);
895
+ }
896
+ /** Variant bytes currently retained. */
897
+ sizeBytes() {
898
+ return this.totalBytes;
899
+ }
900
+ /** Variants currently retained — including any that are no longer readable.
901
+ * The number that used to only ever go up. */
902
+ entryCount() {
903
+ return this.byKey.size;
904
+ }
905
+ /** Evict least-recently-accessed first until the budget holds. */
906
+ enforceBudget(protectedKey) {
907
+ if (this.totalBytes <= this.maxBytes) return;
908
+ const coldestFirst = [...this.byKey.entries()].filter(([key]) => key !== protectedKey).toSorted((a, b) => a[1].lastAccessAt - b[1].lastAccessAt);
909
+ for (const [key] of coldestFirst) {
910
+ if (this.totalBytes <= this.maxBytes) return;
911
+ this.forget(key);
912
+ }
913
+ }
914
+ forget(key) {
915
+ const slot = this.byKey.get(key);
916
+ if (slot === void 0) return;
917
+ this.totalBytes -= slot.bytes.byteLength;
918
+ this.byKey.delete(key);
919
+ const keys = this.keysByDevice.get(slot.deviceId);
920
+ if (keys !== void 0) {
921
+ keys.delete(key);
922
+ if (keys.size === 0) this.keysByDevice.delete(slot.deviceId);
923
+ }
924
+ }
925
+ deleteDevice(deviceId) {
926
+ for (const key of [...this.keysByDevice.get(deviceId) ?? []]) this.forget(key);
927
+ this.keysByDevice.delete(deviceId);
928
+ }
929
+ clear() {
930
+ this.byKey.clear();
931
+ this.keysByDevice.clear();
932
+ this.totalBytes = 0;
933
+ }
934
+ };
935
+ //#endregion
936
+ //#region src/builtins/snapshot/snapshot-grab-pick.ts
937
+ /**
938
+ * Which restream ffmpeg should grab a snapshot JPEG from.
939
+ *
940
+ * `status: 'streaming'` is not enough. A derived whose source profile is
941
+ * unassigned sits in that state with zero packets (618, 2026-08-16: `derived:Mid
942
+ * to low` had four subscribers and never a frame). Preferring it as "warm"
943
+ * parked every grab on a 15 s ffmpeg timeout, so the connecting poster never
944
+ * moved.
945
+ *
946
+ * Derived brokers are never the warm shortcut. A native that is actually
947
+ * streaming still wins; otherwise the caller walks the ranked list and will
948
+ * wake an idle source.
949
+ */
950
+ function isDerivedBrokerId(brokerId, devicePrefix) {
951
+ return (brokerId.startsWith(devicePrefix) ? brokerId.slice(devicePrefix.length) : brokerId).startsWith("derived:");
952
+ }
953
+ /** Highest-quality currently-streaming NON-derived broker, or undefined. */
954
+ function pickWarmSnapshotBroker(ranked, devicePrefix) {
955
+ return ranked.find((c) => c.status === "streaming" && !isDerivedBrokerId(c.brokerId, devicePrefix));
956
+ }
957
+ //#endregion
958
+ //#region src/builtins/snapshot/snapshot.addon.ts
959
+ /**
960
+ * States that make a dial pointless — the ladder is skipped entirely.
961
+ *
962
+ * `offline` is deliberately absent: a camera that is never probed can never be
963
+ * observed to come back, and this layer's own capture is one of the two ways a
964
+ * wrong `online:false` gets discovered (the other is the reachability poller
965
+ * that set it).
966
+ */
967
+ var CAPTURE_BLOCKING_REASONS = [
968
+ "disabled",
969
+ "sleeping",
970
+ "unreachable",
971
+ "waking"
972
+ ];
973
+ /** True when this state must answer WITHOUT touching the camera. */
974
+ function blocksCapture(reason) {
975
+ return CAPTURE_BLOCKING_REASONS.includes(reason);
976
+ }
977
+ /**
978
+ * How long `getSnapshotLinks` waits for the capture it triggered before minting
979
+ * the link over whatever frame it has.
980
+ *
981
+ * Sized against the paint budget, not against the slowest camera. A cold fleet
982
+ * is paced by `MAX_CONCURRENT_GRABS`, so waiting for the last of sixteen would
983
+ * hold the whole grid for tens of seconds — and the frame that lands late is not
984
+ * lost, it populates the cache and the client's next 5 s poll picks it up. The
985
+ * value matches `SWR_STALE_WAIT_MS`'s intent: long enough that a warm broker
986
+ * answers inside it, short enough that a dead camera cannot stall the batch.
987
+ */
988
+ var LINK_MINT_DEADLINE_MS = 2500;
989
+ /**
990
+ * A links RPC is one Viewer-wide batch. Never let one slow camera hold every
991
+ * fast camera behind its individual capture deadline: wait briefly for the
992
+ * common fast path, then mint from the cache as it stands. Slow captures keep
993
+ * running and their new generation is returned by the next 5 s poll.
994
+ */
995
+ var LINK_BATCH_WAIT_MS = 750;
996
+ /** Frames older than this are never represented as current by the Viewer. */
997
+ var LINK_CURRENT_MAX_AGE_MS = 15e3;
998
+ /**
999
+ * Memo TTL for the per-device `deviceManager.getDevice` lookup.
1000
+ *
1001
+ * Every serve decision — each `getSnapshotLinks` target, each media-plane GET,
1002
+ * each conditional-GET peek — used to pay this cross-process round trip (plus
1003
+ * the battery-slice one) before it could even look at the cache: 21-target
1004
+ * grids paid 42 UDS calls per 5 s poll, on top of the captures themselves
1005
+ * (live hub, 2026-08-15). Registry facts (name/type/disabled/online/features)
1006
+ * change on operator action or provider reconnect, not mid-second, so ten
1007
+ * seconds of staleness is invisible next to the poll cadence — and every
1008
+ * lifecycle event that changes one of those fields evicts the entry
1009
+ * immediately (see the `device.*` subscriptions in `onInitialize`).
1010
+ *
1011
+ * The BATTERY SLICE is deliberately NOT memoized: sleep/wake transitions must
1012
+ * be reactive (a camera that just fell asleep must not be dialed — the
1013
+ * Baichuan wake-on-login incident), and `waking` is already live from the
1014
+ * in-memory `wakingDevices` map.
1015
+ */
1016
+ var DEVICE_META_MEMO_MS = 1e4;
1017
+ /** Wake-on-play's 8 s firmware wait + 20 s broker settle, with scheduling
1018
+ * slack. A lost completion event must not leave a camera "Waking" forever. */
1019
+ var SNAPSHOT_WAKING_TTL_MS = 35e3;
1020
+ /** Delay before the single wake-capture retry — covers a camera whose status
1021
+ * flips awake a beat before its snapshot endpoint actually answers. */
1022
+ var WAKE_CAPTURE_RETRY_MS = 5e3;
1023
+ /** Default cache window for non-battery cams (seconds). Matches the Viewer's
1024
+ * 15 s currency contract (`LINK_CURRENT_MAX_AGE_MS`): a frame younger than
1025
+ * that is presented as current, so re-capturing INSIDE the window bought
1026
+ * nothing the client would show — under the 5 s links poll it made every
1027
+ * other poll recapture the whole fleet through the 6-permit grab pools. */
1028
+ var NON_BATTERY_DEFAULT_MAX_AGE_S = 15;
1029
+ /** Default cache window for battery cams (seconds). 1h ≈ "don't wake the cam unless asked". */
1030
+ var BATTERY_DEFAULT_MAX_AGE_S = 3600;
1031
+ /**
1032
+ * Effective per-device max cache age (seconds): the operator override
1033
+ * (`snapshotMaxAgeS`) when a finite non-negative number, else the battery-aware
1034
+ * default. Shared by the freshness gate (`getSnapshot`) and the HTTP endpoint's
1035
+ * `Cache-Control: max-age` (so the browser/`expo-image` layer caches for exactly
1036
+ * as long as the wrapper considers the frame fresh).
1037
+ */
1038
+ function effectiveMaxAgeS(prefs, isBattery) {
1039
+ const def = isBattery ? BATTERY_DEFAULT_MAX_AGE_S : NON_BATTERY_DEFAULT_MAX_AGE_S;
1040
+ return typeof prefs.snapshotMaxAgeS === "number" && prefs.snapshotMaxAgeS >= 0 ? prefs.snapshotMaxAgeS : def;
1041
+ }
1042
+ /**
1043
+ * SnapshotAddon — wrapper over the `snapshot` capability.
1044
+ *
1045
+ * Activated per-device (toggleable by user; default active). When active,
1046
+ * caches fresh snapshots in memory. On cache miss, delegates to the native
1047
+ * provider for this device via `ctx.getNativeProvider(snapshotCapability, id)`.
1048
+ *
1049
+ * No silent fallback — if the native fails, propagate the error up. Stale
1050
+ * cache is returned ONLY when the native throws AND a stale entry exists,
1051
+ * and the failure is logged so the fallback is never silent.
1052
+ *
1053
+ * Frame-grab fallback: when the native provider is absent (or returns null /
1054
+ * throws), we ask the `stream-broker` capability for the device's RTSP
1055
+ * restream URL and pipe one JPEG out of ffmpeg. stream-broker intentionally
1056
+ * does NOT expose a `grabFrame` method — the orchestration (native-first,
1057
+ * ffmpeg fallback, caching) is this addon's concern; stream-broker only
1058
+ * publishes stream endpoints.
1059
+ */
1060
+ var SnapshotAddon = class SnapshotAddon extends require_dist.BaseAddon {
1061
+ /**
1062
+ * The frame cache. Bounded by a byte budget + an idle timeout — it used to be
1063
+ * unbounded in both. Every eviction is logged with the device tag: a frame
1064
+ * that silently left the cache is the reason a later capture had to happen,
1065
+ * and per-camera is the only way that question is ever asked.
1066
+ */
1067
+ /** Cameras resting after a native miss — see `snapshot-fatigue.ts`. */
1068
+ fatigue = new NativeSnapshotFatigue();
1069
+ /**
1070
+ * The last good frame per camera, on disk, so it outlives the process.
1071
+ *
1072
+ * The cache above is RAM-only and the cameras that most need it are the ones
1073
+ * that can never be asked for a fresh frame: a sleeping battery camera
1074
+ * refuses every snapshot without `force`, and the background callers that
1075
+ * would want one deliberately never pass it. Measured 2026-09-17 — the baby
1076
+ * monitor showed the courtesy card all morning because three server updates
1077
+ * had emptied this cache and the camera had been asleep since.
1078
+ */
1079
+ durableStore = null;
1080
+ /**
1081
+ * Built on first use, never in a field initializer: `ctx` does not exist
1082
+ * until `initialize()`, and reading it at construction throws
1083
+ * "ctx accessed before initialize()" for the whole addon.
1084
+ */
1085
+ get durable() {
1086
+ this.durableStore ??= new SnapshotDurableStore({
1087
+ dataDir: this.ctx.dataDir,
1088
+ logger: this.ctx.logger
1089
+ });
1090
+ return this.durableStore;
1091
+ }
1092
+ cache = new SnapshotCache({ onEvict: (deviceId, streamId, reason) => {
1093
+ this.ctx.logger.debug("snapshot cache evicted", {
1094
+ tags: { deviceId },
1095
+ meta: {
1096
+ stream: streamId ?? "auto",
1097
+ reason
1098
+ }
1099
+ });
1100
+ } });
1101
+ /** Card-sized derivatives of the frames above, keyed by width and validated
1102
+ * against the source frame's timestamp. */
1103
+ variants = new SnapshotVariantCache();
1104
+ /**
1105
+ * Rendered courtesy frames, by (reason, size, device name).
1106
+ *
1107
+ * A courtesy frame is a pure function of those three, so it is rendered once
1108
+ * and reused for as long as the process lives — a disabled camera must not
1109
+ * cost an ffmpeg run per poll. Unbounded on purpose: the key space is
1110
+ * (state reasons × this node's own cameras), not user input.
1111
+ */
1112
+ courtesyFrames = /* @__PURE__ */ new Map();
1113
+ /** State overlays over real cached frames, grouped by device so invalidation
1114
+ * can discard every generation in O(1). */
1115
+ stateFrames = /* @__PURE__ */ new Map();
1116
+ /** Devices inside the explicit battery wake-in-progress window. */
1117
+ wakingDevices = /* @__PURE__ */ new Map();
1118
+ /** Last sleeping flag per battery device, for wake-EDGE detection (the map
1119
+ * starts empty; only an observed true→false transition is a wake). */
1120
+ lastKnownSleeping = /* @__PURE__ */ new Map();
1121
+ /**
1122
+ * Short-TTL memo for `lookupDeviceMeta` (see {@link DEVICE_META_MEMO_MS}).
1123
+ * The PROMISE is stored (not the resolved value), so a burst of concurrent
1124
+ * callers — a links batch plus the image fetches it mints — joins one
1125
+ * in-flight lookup instead of stampeding `deviceManager.getDevice`.
1126
+ * `fetchDeviceMeta` never rejects (failure → null), so a settled rejection
1127
+ * can never be served from the memo.
1128
+ */
1129
+ deviceMetaMemo = /* @__PURE__ */ new Map();
1130
+ /**
1131
+ * De-dupes concurrent captures per `${deviceId}:${streamId}` and holds a
1132
+ * settled SUCCESS for COALESCE_MS so a grid-mount burst (and a row of refresh
1133
+ * buttons) collapses into one capture instead of one dial per tile.
1134
+ */
1135
+ captureFlight = new SingleFlight(COALESCE_MS, (outcome) => outcome.ok && outcome.image !== null);
1136
+ /** Bounds simultaneous ffmpeg keyframe grabs (the wrapper path — common case). */
1137
+ grabPool = new Semaphore(6);
1138
+ /** This node's PINNED ffmpeg (D540), asked once. The keyframe grab used to
1139
+ * spawn a bare `'ffmpeg'` — the HOST's binary — off PATH. */
1140
+ pinnedFfmpeg = require_dist.memoizePinnedFfmpeg(() => this.ctx.deps.ensureFfmpeg());
1141
+ /** Bounds simultaneous native (vendor HTTP/ONVIF) snapshot fetches. */
1142
+ nativePool = new Semaphore(6);
1143
+ /**
1144
+ * Cached resolution of `pipelineOrchestrator.getIngestOwner` — SnapshotAddon
1145
+ * has no per-request attach hook to resolve this fresh, so it's cached with
1146
+ * a short TTL and invalidated on `onConfigChanged` (covers the common case
1147
+ * of an operator re-saving cluster/agent settings). A stale owner for up to
1148
+ * `OWNER_CACHE_TTL_MS` just means a snapshot fallback briefly targets the
1149
+ * previous ingest owner — self-heals on the next resolve.
1150
+ */
1151
+ ownerCache = null;
1152
+ static OWNER_CACHE_TTL_MS = 3e4;
1153
+ /**
1154
+ * Handle for the `/addon/snapshot/media/<deviceId>.jpg` HTTP data-plane
1155
+ * endpoint (§3.1). Null when the host provides no `ctx.dataPlane` facility
1156
+ * (the tRPC `getSnapshot` base64 surface still works — the endpoint is a
1157
+ * strictly-additive delivery path). Disposed on shutdown.
1158
+ */
1159
+ mediaDataPlane = null;
1160
+ /**
1161
+ * The PUBLIC, signature-authenticated twin of the media plane. Null when the
1162
+ * host has no `ctx.dataPlane` facility, or before the per-install secret has
1163
+ * been minted — in which case `getSnapshotLinks` reports `url: null` and the
1164
+ * client keeps using the authenticated plane exactly as before.
1165
+ */
1166
+ linkDataPlane = null;
1167
+ /** Per-install HMAC secret for link signatures. Minted once and persisted: a
1168
+ * secret that rolled on every boot would invalidate every link a client is
1169
+ * currently holding, which is a fleet-wide blank grid after each restart. */
1170
+ linkSecret = null;
1171
+ /**
1172
+ * In-flight `serveLinkDataPlane` attempt, so the retry below cannot start a
1173
+ * second one while the first is still awaiting the settings store.
1174
+ */
1175
+ linkPlaneAttempt = null;
1176
+ /**
1177
+ * How a full frame becomes a card-sized one. Defaults to the real ffmpeg
1178
+ * resize; injectable so the wrapper's own logic is testable without spawning a
1179
+ * process for every fixture. `JpegResizer` was declared for exactly this and
1180
+ * had no injector — which is why the resize-failure path had never been
1181
+ * exercised anywhere but production.
1182
+ */
1183
+ resize;
1184
+ constructor(resize = resizeJpeg) {
1185
+ super({ staleTtlMs: 6e4 });
1186
+ this.resize = resize;
1187
+ }
1188
+ async onInitialize() {
1189
+ this.ctx.logger.info("Snapshot wrapper initialized");
1190
+ const provider = {
1191
+ getSnapshot: (input) => this.getSnapshot(input),
1192
+ invalidateCache: (input) => this.invalidateCache(input),
1193
+ getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(input.deviceId),
1194
+ getDeviceLiveContribution: async () => null,
1195
+ applyDeviceSettingsPatch: (input) => this.saveDeviceSettingsPatch(input.deviceId, input.patch),
1196
+ getStatus: async (input) => this.getStatus(input.deviceId),
1197
+ getSnapshotOverview: (input) => this.getSnapshotOverview(input),
1198
+ getSnapshotLinks: (input) => this.getSnapshotLinks(input),
1199
+ getDebugState: (input) => this.getSnapshotDebugState(input.deviceId)
1200
+ };
1201
+ this.subscribe({ category: require_dist.EventCategory.DeviceUnregistered }, (event) => {
1202
+ const deviceId = event.data.deviceId;
1203
+ if (typeof deviceId === "number") this.evictRemovedDevice(deviceId, "device-unregistered");
1204
+ });
1205
+ const dropMetaMemo = (data) => {
1206
+ const deviceId = data?.deviceId;
1207
+ if (typeof deviceId === "number") this.deviceMetaMemo.delete(deviceId);
1208
+ };
1209
+ this.subscribe({ category: require_dist.EventCategory.DeviceRegistered }, (event) => dropMetaMemo(event.data));
1210
+ this.subscribe({ category: require_dist.EventCategory.DeviceEnabled }, (event) => dropMetaMemo(event.data));
1211
+ this.subscribe({ category: require_dist.EventCategory.DeviceDisabled }, (event) => dropMetaMemo(event.data));
1212
+ this.subscribe({ category: require_dist.EventCategory.DeviceMetaChanged }, (event) => dropMetaMemo(event.data));
1213
+ this.subscribe({ category: require_dist.EventCategory.DeviceOnline }, (event) => dropMetaMemo(event.data));
1214
+ this.subscribe({ category: require_dist.EventCategory.DeviceOffline }, (event) => dropMetaMemo(event.data));
1215
+ this.subscribe({ category: require_dist.EventCategory.DeviceBindingsChanged }, (event) => dropMetaMemo(event.data));
1216
+ this.subscribe({ category: require_dist.EventCategory.BatteryOnWakeStarted }, (event) => {
1217
+ this.wakingDevices.set(event.data.deviceId, Date.now());
1218
+ });
1219
+ this.subscribe({ category: require_dist.EventCategory.BatteryOnStatusChanged }, (event) => {
1220
+ this.wakingDevices.delete(event.data.deviceId);
1221
+ const prevSleeping = this.lastKnownSleeping.get(event.data.deviceId);
1222
+ this.lastKnownSleeping.set(event.data.deviceId, event.data.status.sleeping);
1223
+ if (prevSleeping === true && !event.data.status.sleeping) this.captureOnWake(event.data.deviceId);
1224
+ });
1225
+ await this.serveMediaDataPlane();
1226
+ await this.ensureLinkDataPlane();
1227
+ return [{
1228
+ capability: require_dist.snapshotCapability,
1229
+ provider
1230
+ }];
1231
+ }
1232
+ /**
1233
+ * Serve the per-device snapshot image endpoint on the addon data-plane
1234
+ * (§3.1). Delivery: `GET /addon/snapshot/media/<deviceId>.jpg` → raw JPEG with
1235
+ * `ETag` + `Cache-Control: private, max-age=<device maxAgeS>`, so a grid is N
1236
+ * independent `<Image>` tiles served from the coalesced server cache (no
1237
+ * base64 tax, no batch head-of-line blocking, browser/`expo-image` caching for
1238
+ * free). Best-effort: a host without a `dataPlane` facility keeps the tRPC
1239
+ * base64 path.
1240
+ */
1241
+ async serveMediaDataPlane() {
1242
+ const handler = createSnapshotMediaHandler({
1243
+ getMedia: (deviceId, streamId, force, width) => this.resolveSnapshotMedia(deviceId, streamId, force, width),
1244
+ peekFresh: (deviceId, streamId) => this.peekFreshFrame(deviceId, streamId)
1245
+ });
1246
+ try {
1247
+ this.mediaDataPlane = await this.ctx.dataPlane?.serve({
1248
+ prefix: "media",
1249
+ access: "authenticated",
1250
+ handler
1251
+ }) ?? null;
1252
+ this.ctx.logger.info("snapshot media data-plane served", { meta: { baseUrl: this.mediaDataPlane ? `/addon/${require_dist.bareAddonId(this.ctx.id)}/media` : "(no dataPlane facility)" } });
1253
+ } catch (err) {
1254
+ this.ctx.logger.warn("snapshot media data-plane failed to serve", { meta: { error: require_dist.errMsg(err) } });
1255
+ this.mediaDataPlane = null;
1256
+ }
1257
+ }
1258
+ /**
1259
+ * Serve the link plane if it is not already served — at init, and again on
1260
+ * the first `getSnapshotLinks` after an attempt that could not finish.
1261
+ *
1262
+ * The retry is not defensive padding, it is the whole reason this wrapper
1263
+ * exists. The plane needs a persisted signing secret, and the secret needs
1264
+ * the settings store; this addon now boots in its OWN process, so "the store
1265
+ * is not answering yet" is a state it can genuinely observe. A one-shot
1266
+ * attempt turns that instant into a permanent condition: `linkDataPlane`
1267
+ * stays null, every `getSnapshotLinks` row answers `url: null`, and every
1268
+ * tile on every grid stays blank until someone restarts the runner. Nothing
1269
+ * in the logs would say why, because nothing failed twice.
1270
+ *
1271
+ * Single-flighted: a burst of link requests joins one attempt.
1272
+ */
1273
+ async ensureLinkDataPlane() {
1274
+ if (this.linkDataPlane !== null) return;
1275
+ if (this.linkPlaneAttempt !== null) {
1276
+ await this.linkPlaneAttempt;
1277
+ return;
1278
+ }
1279
+ const attempt = this.serveLinkDataPlane().finally(() => {
1280
+ this.linkPlaneAttempt = null;
1281
+ });
1282
+ this.linkPlaneAttempt = attempt;
1283
+ await attempt;
1284
+ }
1285
+ /**
1286
+ * Serve the PUBLIC link plane: `GET /addon/snapshot/link/<deviceId>.jpg?w&v&exp&sig`.
1287
+ *
1288
+ * `access: 'public'` is deliberate and is the only interesting decision here.
1289
+ * The authority is the HMAC, exactly as for the notification artifact plane
1290
+ * and the Home Assistant media plane — but unlike those, what sits behind it
1291
+ * is a LIVE view of the operator's home, so the compensating choices are
1292
+ * explicit: a short TTL (`SNAPSHOT_LINK_TTL_MS`), the width inside the signed
1293
+ * identity so a leaked tile cannot be escalated to the full frame, and
1294
+ * **`force` is not honoured on this route at all** — a public URL must never
1295
+ * be able to wake a battery camera.
1296
+ *
1297
+ * A leaked link therefore grants: one camera, at one thumbnail width, for at
1298
+ * most the TTL. No token, no other device, no session.
1299
+ */
1300
+ async serveLinkDataPlane() {
1301
+ try {
1302
+ const secret = await this.ensureLinkSecret();
1303
+ if (secret === null) return;
1304
+ const prefix = this.linkRoutePrefix();
1305
+ const handler = createSnapshotMediaHandler({
1306
+ getMedia: (deviceId, streamId, _force, width) => this.resolveSnapshotMedia(deviceId, streamId, false, width),
1307
+ peekFresh: (deviceId, streamId) => this.peekFreshFrame(deviceId, streamId)
1308
+ });
1309
+ this.linkDataPlane = await this.ctx.dataPlane?.serve({
1310
+ prefix: "link",
1311
+ access: "public",
1312
+ handler: (req, res) => this.handleLinkRequest(req, res, secret, handler)
1313
+ }) ?? null;
1314
+ this.ctx.logger.info("snapshot link data-plane served", { meta: {
1315
+ served: this.linkDataPlane !== null,
1316
+ prefix
1317
+ } });
1318
+ } catch (err) {
1319
+ this.ctx.logger.warn("snapshot link data-plane failed to serve", { meta: { error: require_dist.errMsg(err) } });
1320
+ this.linkDataPlane = null;
1321
+ }
1322
+ }
1323
+ /**
1324
+ * Verify first, then hand the request to the ordinary media handler with a
1325
+ * REWRITTEN url carrying only the signed `(deviceId, width)`.
1326
+ *
1327
+ * Rewriting rather than passing the original through is what stops an unsigned
1328
+ * query parameter reaching the capture path: `force`, `streamId` and any other
1329
+ * lever the authenticated plane honours are simply not present in what the
1330
+ * handler parses.
1331
+ */
1332
+ async handleLinkRequest(req, res, secret, inner) {
1333
+ const verified = parseVerifiedSnapshotLink({
1334
+ url: req.url ?? "/",
1335
+ secret,
1336
+ nowMs: Date.now()
1337
+ });
1338
+ if (verified === null) {
1339
+ res.writeHead(404).end();
1340
+ return;
1341
+ }
1342
+ const rewritten = `/${String(verified.deviceId)}.jpg${verified.width === void 0 ? "" : `?w=${String(verified.width)}`}`;
1343
+ const original = req.url;
1344
+ try {
1345
+ req.url = rewritten;
1346
+ await inner(req, res);
1347
+ } finally {
1348
+ req.url = original;
1349
+ }
1350
+ }
1351
+ linkRoutePrefix() {
1352
+ return `/addon/${require_dist.bareAddonId(this.ctx.id)}/link`;
1353
+ }
1354
+ /**
1355
+ * Mint-once-and-persist the signing secret. Null when it cannot be
1356
+ * ESTABLISHED — a secret held only in memory would break every outstanding
1357
+ * link on restart, so no plane is better than a plane whose links die
1358
+ * unpredictably.
1359
+ *
1360
+ * A null is never cached, so the next `getSnapshotLinks` tries again. That
1361
+ * matters now the wrapper runs in its own process: the settings store can be
1362
+ * a moment behind at boot, and this used to be a one-shot.
1363
+ *
1364
+ * The read-back is the gate. `state.get()` cannot distinguish "no secret
1365
+ * yet" from "the store could not be read" — `readAddonStoreWithRetry` gives
1366
+ * up and answers `{}` — so a store that is merely slow reads as empty and
1367
+ * this would mint a SECOND secret over a perfectly good first one, silently
1368
+ * invalidating every link a client is holding. Reading back what we just
1369
+ * wrote is the only evidence available at this layer that the store is
1370
+ * actually answering, and a mismatch means it is not.
1371
+ */
1372
+ async ensureLinkSecret() {
1373
+ if (this.linkSecret !== null) return this.linkSecret;
1374
+ try {
1375
+ const state = this.state("snapshotLinkSecret", zod.z.string(), "");
1376
+ const stored = await state.get();
1377
+ if (stored !== "") {
1378
+ this.linkSecret = stored;
1379
+ return stored;
1380
+ }
1381
+ const minted = (0, node_crypto.randomUUID)().replace(/-/g, "");
1382
+ await state.set(minted);
1383
+ const confirmed = await state.get();
1384
+ if (confirmed !== minted) {
1385
+ this.ctx.logger.warn("snapshot: link secret did not persist — deferring the link plane rather than signing with a secret that will not survive", { meta: { confirmedEmpty: confirmed === "" } });
1386
+ return null;
1387
+ }
1388
+ this.linkSecret = minted;
1389
+ return minted;
1390
+ } catch (err) {
1391
+ this.ctx.logger.warn("snapshot: could not establish link signing secret", { meta: { error: require_dist.errMsg(err) } });
1392
+ return null;
1393
+ }
1394
+ }
1395
+ /**
1396
+ * Mint signed links for the tiles a surface is rendering — and, in the same
1397
+ * call, make those tiles CURRENT.
1398
+ *
1399
+ * This is the demand signal the design was missing. Under D93 enrolment rode
1400
+ * on the image request, and D93/D94/D95 each fixed a different way for that
1401
+ * request not to happen; none of them could fix the last one, because the
1402
+ * client's own image cache answers a repeated URL with no network at all. An
1403
+ * RPC has no such cache in front of it.
1404
+ *
1405
+ * So: note every target (creating a subscription, which `getSnapshotOverview`
1406
+ * deliberately cannot), then join the ordinary non-forced capture path and
1407
+ * wait a BOUNDED time for it. The Viewer never presents a frame older than
1408
+ * 15 seconds as current, so this path tightens a looser per-device cache
1409
+ * window to that contract without using `force` (and its battery-wake
1410
+ * semantics). What comes back is the identity of the frame the link serves.
1411
+ *
1412
+ * The bound matters more than its exact value. A cold fleet is paced by
1413
+ * `MAX_CONCURRENT_GRABS`, so sixteen cameras cannot all capture at once and
1414
+ * the last of them would hold the whole batch well past any sensible paint
1415
+ * budget. Devices that miss the bound return their real, older `capturedAt` —
1416
+ * honest rather than blocking — and the client's next poll carries them
1417
+ * forward.
1418
+ */
1419
+ async getSnapshotLinks(input) {
1420
+ await this.ensureLinkDataPlane();
1421
+ const secret = await this.ensureLinkSecret();
1422
+ const expMs = snapshotLinkExpiry(Date.now(), SNAPSHOT_LINK_TTL_MS);
1423
+ const served = this.linkDataPlane !== null && secret !== null;
1424
+ const prefix = this.linkRoutePrefix();
1425
+ const stateByDevice = /* @__PURE__ */ new Map();
1426
+ const refreshes = input.targets.map(async (target) => {
1427
+ const state = await this.snapshotStateForLink(target.deviceId);
1428
+ stateByDevice.set(target.deviceId, state);
1429
+ if (state.reason !== void 0) return;
1430
+ if (state.isBattery && !await this.hasStreamingBrokerForDevice(target.deviceId)) return;
1431
+ await this.awaitFreshEnough(target.deviceId);
1432
+ });
1433
+ await raceForResult(Promise.allSettled(refreshes), LINK_BATCH_WAIT_MS);
1434
+ const rows = input.targets.map((target) => {
1435
+ const { deviceId } = target;
1436
+ const width = target.width === void 0 ? void 0 : snapSnapshotWidth(target.width);
1437
+ const capturedAt = this.cache.latest(deviceId)?.ts ?? null;
1438
+ const answeredAt = Date.now();
1439
+ return {
1440
+ deviceId,
1441
+ url: served && secret !== null ? buildSnapshotLinkUrl({
1442
+ routePrefix: prefix,
1443
+ deviceId,
1444
+ width,
1445
+ capturedAt,
1446
+ secret,
1447
+ expMs
1448
+ }) : null,
1449
+ capturedAt,
1450
+ ageMs: capturedAt === null ? null : answeredAt - capturedAt,
1451
+ expiresAt: served ? expMs : null,
1452
+ width: width ?? null,
1453
+ neverCaptured: capturedAt === null,
1454
+ sleeping: stateByDevice.get(deviceId)?.reason === "sleeping",
1455
+ stateReason: stateByDevice.get(deviceId)?.reason ?? null,
1456
+ battery: stateByDevice.get(deviceId)?.isBattery ?? false
1457
+ };
1458
+ });
1459
+ this.ctx.logger.debug("snapshot: minted links", { meta: {
1460
+ targets: input.targets.length,
1461
+ served,
1462
+ stale: rows.filter((r) => r.ageMs !== null && r.ageMs > 15e3).length
1463
+ } });
1464
+ return rows;
1465
+ }
1466
+ /**
1467
+ * The debug readout's data — the decision chain for one device, cache-only
1468
+ * and capture-free (a debug poll must never wake a battery camera).
1469
+ */
1470
+ async getSnapshotDebugState(deviceId) {
1471
+ const meta = await this.lookupDeviceMeta(deviceId);
1472
+ const state = await this.resolveSnapshotState(deviceId, meta);
1473
+ const hit = this.cache.latest(deviceId);
1474
+ const batterySlice = await this.ctx.api.deviceState.getCapSlice.query({
1475
+ deviceId,
1476
+ capName: require_dist.batteryCapability.name
1477
+ }).catch(() => null);
1478
+ const parsed = require_dist.BatteryStatusSchema.safeParse(batterySlice);
1479
+ return {
1480
+ battery: parsed.success ? {
1481
+ sleeping: parsed.data.sleeping,
1482
+ lastUpdated: parsed.data.lastUpdated,
1483
+ ...parsed.data.lastContactAt !== void 0 ? { lastContactAt: parsed.data.lastContactAt } : {}
1484
+ } : null,
1485
+ state: {
1486
+ isBattery: state.isBattery,
1487
+ reason: state.reason ?? null
1488
+ },
1489
+ frame: {
1490
+ capturedAt: hit?.ts ?? null,
1491
+ ageMs: hit ? Date.now() - hit.ts : null
1492
+ },
1493
+ waking: this.isDeviceWaking(deviceId)
1494
+ };
1495
+ }
1496
+ /**
1497
+ * Join the ordinary capture path for one device and wait, bounded, for it.
1498
+ *
1499
+ * Deliberately `getSnapshot` with `force: false`: the single flight, grab
1500
+ * pool, and sleeping-battery refusal apply unchanged. The only override is
1501
+ * the Viewer's 15-second currency contract and the link-mint wait bound.
1502
+ */
1503
+ async awaitFreshEnough(deviceId) {
1504
+ const before = this.cache.latest(deviceId)?.ts ?? null;
1505
+ const alreadyCurrent = before !== null && Date.now() - before <= LINK_CURRENT_MAX_AGE_MS;
1506
+ await this.getSnapshot({
1507
+ deviceId,
1508
+ force: false
1509
+ }, LINK_MINT_DEADLINE_MS, LINK_CURRENT_MAX_AGE_MS, LINK_MINT_DEADLINE_MS).catch(() => null);
1510
+ const current = this.cache.latest(deviceId)?.ts ?? null;
1511
+ if (alreadyCurrent || current !== null && (before === null || current > before)) return;
1512
+ this.ctx.logger.debug("snapshot: link mint gave up waiting; serving the older frame", {
1513
+ tags: { deviceId },
1514
+ meta: {
1515
+ deadlineMs: LINK_MINT_DEADLINE_MS,
1516
+ previousCapturedAt: before
1517
+ }
1518
+ });
1519
+ }
1520
+ /**
1521
+ * The one fresh frame an awake battery camera gets outside an active stream:
1522
+ * captured at the WAKE edge, because the link poll deliberately never
1523
+ * recaptures an idle-awake battery camera (every capture is a camera hit
1524
+ * that would keep it out of sleep — the link-mint gate documents the
1525
+ * incident).
1526
+ *
1527
+ * `force: true` is correct here — not a violation of "never wake for a
1528
+ * snapshot": the camera is ALREADY awake (the status edge is what fired),
1529
+ * and the battery 1 h cache default would otherwise answer the wake with
1530
+ * the pre-sleep frame. The single flight coalesces a burst of edges; one
1531
+ * delayed retry covers a camera whose status flipped a beat before its
1532
+ * snapshot endpoint is actually answering (firmware boot lag).
1533
+ */
1534
+ async captureOnWake(deviceId) {
1535
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1536
+ if (attempt > 0) await new Promise((r) => setTimeout(r, WAKE_CAPTURE_RETRY_MS));
1537
+ if ((await this.resolveSnapshotState(deviceId, await this.lookupDeviceMeta(deviceId)).catch(() => null))?.reason === "sleeping") return;
1538
+ try {
1539
+ if (await this.getSnapshot({
1540
+ deviceId,
1541
+ force: true
1542
+ }) !== null) {
1543
+ this.ctx.logger.debug("snapshot: wake capture landed", { tags: { deviceId } });
1544
+ return;
1545
+ }
1546
+ } catch (err) {
1547
+ this.ctx.logger.debug("snapshot: wake capture failed", {
1548
+ tags: { deviceId },
1549
+ meta: {
1550
+ error: require_dist.errMsg(err),
1551
+ attempt
1552
+ }
1553
+ });
1554
+ }
1555
+ }
1556
+ }
1557
+ /** Resolve the state advertised by a minted link before deciding whether a
1558
+ * background capture is allowed. */
1559
+ async snapshotStateForLink(deviceId) {
1560
+ try {
1561
+ const meta = await this.lookupDeviceMeta(deviceId);
1562
+ return await this.resolveSnapshotState(deviceId, meta);
1563
+ } catch (err) {
1564
+ this.ctx.logger.debug("snapshot: link state resolution failed", {
1565
+ tags: { deviceId },
1566
+ meta: { error: require_dist.errMsg(err) }
1567
+ });
1568
+ return { isBattery: false };
1569
+ }
1570
+ }
1571
+ /**
1572
+ * Resolve a device (+ optional stream, + force) to renderable JPEG bytes for
1573
+ * the HTTP endpoint. Runs the same coalesced capture ladder as the tRPC
1574
+ * `getSnapshot` (so every consumer shares one upstream pull), then decodes the
1575
+ * base64 cache into raw bytes and stamps the frame identity: `capturedAt` from
1576
+ * the cache entry (matching the ETag `getSnapshotOverview` advertises) and the
1577
+ * effective per-device `maxAgeS` for `Cache-Control`. Null → 404.
1578
+ */
1579
+ async resolveSnapshotMedia(deviceId, streamId, force, width) {
1580
+ const resolutionMeta = {};
1581
+ const image = await this.getSnapshot({
1582
+ deviceId,
1583
+ ...streamId !== void 0 ? { streamId } : {},
1584
+ force
1585
+ }, 0, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, resolutionMeta, 0);
1586
+ if (!image) return null;
1587
+ const capturedAt = this.cache.get(deviceId, streamId)?.ts ?? Date.now();
1588
+ const prefs = await this.readDeviceSettings(deviceId).catch(() => ({}));
1589
+ const isBattery = resolutionMeta.isBattery ?? false;
1590
+ if (width === void 0) return {
1591
+ bytes: Buffer.from(image.base64, "base64"),
1592
+ contentType: image.contentType,
1593
+ capturedAt,
1594
+ maxAgeS: effectiveMaxAgeS(prefs, isBattery),
1595
+ variantKey: resolutionMeta.stateReason,
1596
+ servedWidth: void 0
1597
+ };
1598
+ const thumb = await this.thumbnailBytes(deviceId, streamId, width, capturedAt, image, prefs, resolutionMeta.stateReason);
1599
+ return {
1600
+ bytes: thumb.bytes,
1601
+ contentType: image.contentType,
1602
+ capturedAt,
1603
+ maxAgeS: effectiveMaxAgeS(prefs, isBattery),
1604
+ variantKey: resolutionMeta.stateReason,
1605
+ servedWidth: thumb.width
1606
+ };
1607
+ }
1608
+ /**
1609
+ * Cache-only freshness peek for the data-plane's conditional-GET fast path.
1610
+ * Never captures, never resizes, never dials anything: a cached frame that is
1611
+ * still inside its per-device max-age, or null.
1612
+ *
1613
+ * Returning null for a STALE entry is the important half. A 304 there would
1614
+ * pin the tile to the old frame for as long as the client kept revalidating,
1615
+ * which is the exact staleness this change exists to remove.
1616
+ */
1617
+ async peekFreshFrame(deviceId, streamId) {
1618
+ const hit = this.cache.get(deviceId, streamId);
1619
+ if (!hit) return null;
1620
+ const prefs = await this.readDeviceSettings(deviceId).catch(() => ({}));
1621
+ const meta = await this.lookupDeviceMeta(deviceId);
1622
+ const state = await this.resolveSnapshotState(deviceId, meta);
1623
+ const maxAgeS = effectiveMaxAgeS(prefs, state.isBattery);
1624
+ if (Date.now() - hit.ts >= maxAgeS * 1e3) return null;
1625
+ return {
1626
+ capturedAt: hit.ts,
1627
+ maxAgeS,
1628
+ variantKey: state.reason
1629
+ };
1630
+ }
1631
+ /**
1632
+ * The frame at a card-sized width, derived once per
1633
+ * (device, stream, width, state treatment) per capture.
1634
+ *
1635
+ * A failed resize falls back to the FULL frame — a visible card beats a
1636
+ * broken one — but never silently: the card would otherwise keep costing a
1637
+ * megabyte with nothing anywhere saying why, which is the shape of the bug
1638
+ * this whole change came from.
1639
+ */
1640
+ async thumbnailBytes(deviceId, streamId, width, capturedAt, image, prefs, variantKey) {
1641
+ const cached = this.variants.get(deviceId, streamId, width, capturedAt, variantKey);
1642
+ if (cached !== void 0) return {
1643
+ bytes: cached,
1644
+ width
1645
+ };
1646
+ const full = Buffer.from(image.base64, "base64");
1647
+ try {
1648
+ const resized = await this.resize(full, width);
1649
+ this.variants.set(deviceId, streamId, width, capturedAt, resized, variantKey);
1650
+ if (prefs.snapshotDebug) this.ctx.logger.info("snapshot: thumbnail derived", {
1651
+ tags: { deviceId },
1652
+ meta: {
1653
+ width,
1654
+ fullBytes: full.length,
1655
+ thumbBytes: resized.length
1656
+ }
1657
+ });
1658
+ return {
1659
+ bytes: resized,
1660
+ width
1661
+ };
1662
+ } catch (err) {
1663
+ this.ctx.logger.warn("snapshot: resize failed — serving the full frame", {
1664
+ tags: { deviceId },
1665
+ meta: {
1666
+ width,
1667
+ bytes: full.length,
1668
+ error: require_dist.errMsg(err)
1669
+ }
1670
+ });
1671
+ return {
1672
+ bytes: full,
1673
+ width: void 0
1674
+ };
1675
+ }
1676
+ }
1677
+ async onShutdown() {
1678
+ if (this.mediaDataPlane) {
1679
+ await this.mediaDataPlane.dispose().catch(() => void 0);
1680
+ this.mediaDataPlane = null;
1681
+ }
1682
+ if (this.linkDataPlane) {
1683
+ await this.linkDataPlane.dispose().catch(() => void 0);
1684
+ this.linkDataPlane = null;
1685
+ }
1686
+ this.cache.clear();
1687
+ this.variants.clear();
1688
+ this.stateFrames.clear();
1689
+ this.wakingDevices.clear();
1690
+ this.lastKnownSleeping.clear();
1691
+ this.deviceMetaMemo.clear();
1692
+ this.captureFlight.clear();
1693
+ this.ownerCache = null;
1694
+ }
1695
+ /**
1696
+ * Drop the cached ingest owner whenever addon-level settings change —
1697
+ * cheap, correct-by-construction refresh point (BaseAddon calls this
1698
+ * after every `updateGlobalSettings`/`updateAddonSettings`). Combined
1699
+ * with the TTL in `resolveIngestOwner`, a cluster topology change is
1700
+ * picked up either on the next settings save or within
1701
+ * `OWNER_CACHE_TTL_MS`, whichever comes first.
1702
+ */
1703
+ async onConfigChanged() {
1704
+ this.ownerCache = null;
1705
+ }
1706
+ globalSettingsSchema() {
1707
+ return this.schema({ sections: [{
1708
+ id: "snapshot-cache",
1709
+ title: "Snapshot Cache",
1710
+ titleKey: "server:globalSettings.s_snapshot-cache.title",
1711
+ description: "Stale fallback when live capture fails. Per-device freshness is configured under Device → Snapshot → Max cache age.",
1712
+ descriptionKey: "server:globalSettings.s_snapshot-cache.description",
1713
+ columns: 1,
1714
+ fields: [this.field({
1715
+ type: "number",
1716
+ key: "staleTtlMs",
1717
+ label: "Stale fallback TTL (ms)",
1718
+ labelKey: "server:globalSettings.s_snapshot-cache.staleTtlMs.label",
1719
+ description: "If live capture fails, cached snapshot younger than this is still returned.",
1720
+ descriptionKey: "server:globalSettings.s_snapshot-cache.staleTtlMs.description",
1721
+ min: 0,
1722
+ max: 36e5,
1723
+ step: 1e3,
1724
+ default: 6e4
1725
+ })]
1726
+ }] });
1727
+ }
1728
+ async getSnapshot(input, minimumCaptureWaitMs = 0, maximumCacheAgeMs = Number.POSITIVE_INFINITY, maximumCaptureWaitMs = Number.POSITIVE_INFINITY, resolutionMeta, staleWaitCapMs = Number.POSITIVE_INFINITY) {
1729
+ const { deviceId } = input;
1730
+ const force = input.force === true;
1731
+ const meta = await this.lookupDeviceMeta(deviceId);
1732
+ const deviceName = meta?.name;
1733
+ const log = this.ctx.logger.withTags({
1734
+ deviceId,
1735
+ ...deviceName ? { deviceName } : {}
1736
+ });
1737
+ const now = Date.now();
1738
+ const prefs = await this.readDeviceSettings(deviceId).catch(() => ({}));
1739
+ const rawPref = prefs.snapshotStreamId;
1740
+ const effectiveStreamId = input.streamId ?? (rawPref && rawPref !== "auto" ? rawPref : void 0);
1741
+ if (prefs.snapshotDebug) log.info("debug on", {
1742
+ tags: { deviceId },
1743
+ meta: { stream: effectiveStreamId ?? "auto" }
1744
+ });
1745
+ const hit = this.cache.get(deviceId, effectiveStreamId);
1746
+ const state = await this.resolveSnapshotState(deviceId, meta);
1747
+ const isBatteryDevice = state.isBattery;
1748
+ if (resolutionMeta) {
1749
+ resolutionMeta.isBattery = isBatteryDevice;
1750
+ delete resolutionMeta.stateReason;
1751
+ }
1752
+ if (state.reason !== void 0 && blocksCapture(state.reason) && (!force || state.reason !== "sleeping")) {
1753
+ if (resolutionMeta) resolutionMeta.stateReason = state.reason;
1754
+ log.debug("snapshot: camera state overrides raw cache", {
1755
+ tags: { deviceId },
1756
+ meta: {
1757
+ reason: state.reason,
1758
+ hasCache: hit !== void 0,
1759
+ ageMs: hit ? now - hit.ts : null
1760
+ }
1761
+ });
1762
+ const base = hit ?? await this.durableEntry(deviceId);
1763
+ return await this.stateImage(deviceId, state.reason, deviceName, base);
1764
+ }
1765
+ const effectiveMaxAgeMs = Math.min(maximumCacheAgeMs, Math.max(0, effectiveMaxAgeS(prefs, isBatteryDevice) * 1e3));
1766
+ const decision = decideSnapshotServe({
1767
+ now,
1768
+ cachedAt: hit?.ts ?? null,
1769
+ effectiveMaxAgeMs,
1770
+ force
1771
+ });
1772
+ if (decision.kind === "serve-cache") {
1773
+ if (prefs.snapshotDebug && hit) log.debug("snapshot: cache hit", {
1774
+ tags: { deviceId },
1775
+ meta: {
1776
+ ageMs: now - hit.ts,
1777
+ maxAgeMs: effectiveMaxAgeMs,
1778
+ isBattery: isBatteryDevice
1779
+ }
1780
+ });
1781
+ if (!hit) return null;
1782
+ return state.reason === "offline" ? await this.offlineImage(deviceId, deviceName, hit, resolutionMeta) : hit.data;
1783
+ }
1784
+ const flightKey = `${deviceId}:${effectiveStreamId ?? "auto"}`;
1785
+ const flight = this.captureFlight.run(flightKey, () => this.captureFresh({
1786
+ deviceId,
1787
+ input,
1788
+ effectiveStreamId,
1789
+ isBatteryDevice,
1790
+ log
1791
+ }));
1792
+ flight.catch(() => void 0);
1793
+ const waitMs = !force && decision.staleFallback && hit !== void 0 ? Math.min(decision.waitMs, staleWaitCapMs) : decision.waitMs;
1794
+ const raced = await raceForResult(flight, Math.min(Math.max(waitMs, minimumCaptureWaitMs), maximumCaptureWaitMs));
1795
+ if (raced.settled) {
1796
+ const captured = raced.value.ok && raced.value.image !== null;
1797
+ try {
1798
+ const resolved = await this.resolveOutcome(raced.value, deviceId, hit, log);
1799
+ if (resolved !== null) return captured || state.reason !== "offline" ? resolved : await this.offlineImage(deviceId, deviceName, hit, resolutionMeta);
1800
+ return state.reason === "offline" ? await this.offlineImage(deviceId, deviceName, void 0, resolutionMeta) : null;
1801
+ } catch (err) {
1802
+ if (state.reason === "offline") {
1803
+ const stateFrame = await this.offlineImage(deviceId, deviceName, hit, resolutionMeta);
1804
+ if (stateFrame !== null) return stateFrame;
1805
+ }
1806
+ throw err;
1807
+ }
1808
+ }
1809
+ if (decision.staleFallback && hit) {
1810
+ if (prefs.snapshotDebug) log.debug("snapshot: SWR — returning stale frame; refresh continues in background", {
1811
+ tags: { deviceId },
1812
+ meta: {
1813
+ ageMs: now - hit.ts,
1814
+ waitMs: decision.waitMs
1815
+ }
1816
+ });
1817
+ return state.reason === "offline" ? await this.offlineImage(deviceId, deviceName, hit, resolutionMeta) : hit.data;
1818
+ }
1819
+ if (state.reason === "offline") {
1820
+ const stateFrame = await this.offlineImage(deviceId, deviceName, void 0, resolutionMeta);
1821
+ if (stateFrame !== null) return stateFrame;
1822
+ }
1823
+ return null;
1824
+ }
1825
+ /**
1826
+ * Map a settled capture outcome onto the response, preserving the legacy
1827
+ * semantics: a fresh frame wins; a soft miss (native null + broker null)
1828
+ * falls back to stale cache (or null); a HARD native error with no frame
1829
+ * and no cache propagates.
1830
+ */
1831
+ async resolveOutcome(outcome, deviceId, hit, log) {
1832
+ if (outcome.ok) {
1833
+ if (outcome.image) return outcome.image;
1834
+ if (hit) {
1835
+ const ageMs = Date.now() - hit.ts;
1836
+ if (ageMs > this.config.staleTtlMs) {
1837
+ if (await this.staleHitBelongsToRemovedDevice(deviceId, ageMs)) return null;
1838
+ log.warn("snapshot: all live paths failed — serving stale cache", {
1839
+ tags: { deviceId },
1840
+ meta: { ageMs }
1841
+ });
1842
+ }
1843
+ return hit.data;
1844
+ }
1845
+ return null;
1846
+ }
1847
+ if (hit) {
1848
+ const ageMs = Date.now() - hit.ts;
1849
+ if (ageMs > this.config.staleTtlMs) {
1850
+ if (await this.staleHitBelongsToRemovedDevice(deviceId, ageMs)) return null;
1851
+ log.warn("snapshot: native failed — serving stale cache", {
1852
+ tags: { deviceId },
1853
+ meta: { ageMs }
1854
+ });
1855
+ }
1856
+ return hit.data;
1857
+ }
1858
+ throw outcome.error;
1859
+ }
1860
+ /**
1861
+ * Reconcile backstop for a stale hit: is the frame we are about to serve the
1862
+ * property of a device that no longer exists?
1863
+ *
1864
+ * Asked ONLY past `staleTtlMs`, which is already the "something is wrong"
1865
+ * threshold — so the common path costs nothing. A `true` answer evicts and
1866
+ * the caller returns null; anything else leaves the existing
1867
+ * keep-the-UI-from-going-blank contract untouched.
1868
+ */
1869
+ async staleHitBelongsToRemovedDevice(deviceId, ageMs) {
1870
+ if (await this.deviceStillExists(deviceId) !== false) return false;
1871
+ this.evictRemovedDevice(deviceId, "stale-hit-absent");
1872
+ this.ctx.logger.debug("snapshot: refused a stale frame for a device that is gone", {
1873
+ tags: { deviceId },
1874
+ meta: { ageMs }
1875
+ });
1876
+ return true;
1877
+ }
1878
+ /**
1879
+ * Run the capture ladder ONCE for a device: native provider first, then the
1880
+ * stream-broker ffmpeg fallback. Never rejects — resolves a {@link
1881
+ * CaptureOutcome}. On a produced frame it populates the cache (so a
1882
+ * background SWR refresh lands for the next poll) and returns it. A hard
1883
+ * native error with no broker frame resolves `{ ok:false }` so the caller
1884
+ * can surface it; a soft miss resolves `{ ok:true, image:null }`.
1885
+ *
1886
+ * TODO(decoded-frame fast path): for a device whose detection pipeline is
1887
+ * already decoding (the always-on subscription, see docs/design/decode-path.md),
1888
+ * the freshest decoded frame is already in the shared-memory ring — a single
1889
+ * JPEG encode of the latest FrameHandle would cost zero dials and beat the
1890
+ * ffmpeg grab for the wrapper fleet. Slotting it as native -> latest-decoded
1891
+ * -> broker needs cross-addon plumbing not cheaply reachable from the hub
1892
+ * builtin today: frames are session-scoped (decoder `pullHandles`/`getFrame`
1893
+ * need the device's active session id) and raw-pixel (need a JPEG encoder the
1894
+ * builtin lacks). Deferred as its own slice.
1895
+ */
1896
+ async captureFresh(args) {
1897
+ const { deviceId, input, effectiveStreamId, isBatteryDevice, log } = args;
1898
+ const now = Date.now();
1899
+ let nativeError = null;
1900
+ let nativeAbsent = false;
1901
+ const restingUntil = input.force === true ? null : this.fatigue.restingUntil(deviceId, now);
1902
+ try {
1903
+ const native = restingUntil === null ? this.ctx.getNativeProvider(require_dist.snapshotCapability, deviceId) : null;
1904
+ if (restingUntil !== null) log.info("native snapshot: camera resting after a miss — not dialled", {
1905
+ tags: { deviceId },
1906
+ meta: { restMsLeft: restingUntil - now }
1907
+ });
1908
+ else if (native) {
1909
+ const result = await this.nativePool.run(() => native.getSnapshot(input));
1910
+ if (result) {
1911
+ this.fatigue.recordSuccess(deviceId);
1912
+ this.stateFrames.delete(deviceId);
1913
+ this.cache.set(deviceId, effectiveStreamId, {
1914
+ data: result,
1915
+ ts: now,
1916
+ streamId: effectiveStreamId ?? null
1917
+ });
1918
+ this.durable.put(deviceId, Buffer.from(result.base64, "base64"));
1919
+ return {
1920
+ ok: true,
1921
+ image: result
1922
+ };
1923
+ }
1924
+ const rest = this.fatigue.recordFailure(deviceId, now);
1925
+ log.debug("native snapshot returned null — falling through to broker", {
1926
+ tags: { deviceId },
1927
+ meta: {
1928
+ restMs: rest.restMs,
1929
+ streak: rest.streak
1930
+ }
1931
+ });
1932
+ } else {
1933
+ nativeAbsent = true;
1934
+ log.debug("native snapshot provider not resolved — falling through to broker", { tags: { deviceId } });
1935
+ }
1936
+ } catch (err) {
1937
+ const msg = require_dist.errMsg(err);
1938
+ if (isAbsentNativeError(msg)) {
1939
+ nativeAbsent = true;
1940
+ log.debug("native snapshot absent", {
1941
+ tags: { deviceId },
1942
+ meta: { error: msg }
1943
+ });
1944
+ } else {
1945
+ nativeError = err;
1946
+ const rest = this.fatigue.recordFailure(deviceId, now);
1947
+ log.warn("native snapshot failed", {
1948
+ tags: { deviceId },
1949
+ meta: {
1950
+ error: msg,
1951
+ restMs: rest.restMs,
1952
+ streak: rest.streak
1953
+ }
1954
+ });
1955
+ }
1956
+ }
1957
+ if (!(isBatteryDevice && nativeAbsent && !await this.hasStreamingBrokerForDevice(deviceId))) try {
1958
+ const fallback = await this.grabFrameFromBroker(deviceId, effectiveStreamId);
1959
+ if (fallback) {
1960
+ this.stateFrames.delete(deviceId);
1961
+ this.cache.set(deviceId, effectiveStreamId, {
1962
+ data: fallback,
1963
+ ts: now,
1964
+ streamId: effectiveStreamId ?? null
1965
+ });
1966
+ this.durable.put(deviceId, Buffer.from(fallback.base64, "base64"));
1967
+ return {
1968
+ ok: true,
1969
+ image: fallback
1970
+ };
1971
+ }
1972
+ } catch (err) {
1973
+ log.warn("stream-broker snapshot fallback failed", {
1974
+ tags: { deviceId },
1975
+ meta: { error: require_dist.errMsg(err) }
1976
+ });
1977
+ }
1978
+ else log.debug("snapshot: skipping broker fallback — battery device with absent native and no streaming broker", { tags: { deviceId } });
1979
+ if (nativeError) return {
1980
+ ok: false,
1981
+ error: nativeError
1982
+ };
1983
+ return {
1984
+ ok: true,
1985
+ image: null
1986
+ };
1987
+ }
1988
+ /**
1989
+ * Pull one JPEG from the device's stream-broker RTSP restream using
1990
+ * a short-lived ffmpeg invocation.
1991
+ *
1992
+ * Stream selection strategy (picks the broker that won't stall):
1993
+ * 1. Explicit `preferredStreamId` (user set in per-device settings)
1994
+ * — always honoured, even if currently idle. Operator choice
1995
+ * wins.
1996
+ * 2. Auto: highest-quality broker currently in `streaming` state.
1997
+ * This is the whole point — prefer the stream that has active
1998
+ * subscribers (usually `low` for detection, but `mid`/`high`
1999
+ * if WebRTC is watching) so ffmpeg hits a warm pipe and
2000
+ * doesn't race the broker's resume.
2001
+ * 3. Fallback: highest-quality enabled entry regardless of status
2002
+ * (will wake a suspended broker — retry-guarded against the
2003
+ * cold-start error).
2004
+ *
2005
+ * The stream-broker auto-suspends idle streams on the "no demand"
2006
+ * signal; snapshots used to default to `high` which was often the
2007
+ * first to go idle, racing every snapshot with a broker resume.
2008
+ * Now we ask the orchestrator of streams which one is warm and grab
2009
+ * from there.
2010
+ *
2011
+ * Source acquisition is pinned to the cluster's ingest owner (the node
2012
+ * the stream-broker actually runs on) instead of the device-scoped
2013
+ * `dev.cameraStreams` facade — `dev.cameraStreams` resolves against
2014
+ * whichever node the cap-router picks by default, which double-pulls
2015
+ * the camera (or dials a hub-local restream that isn't serving) when
2016
+ * `ingestNode != hub`. `fetchSnapshotBrokerEntries` does the pinned
2017
+ * fetch + owner-relative URL host rewrite; hub-owner + no reachable
2018
+ * host is byte-identical to the previous unpinned call.
2019
+ */
2020
+ async grabFrameFromBroker(deviceId, preferredStreamId) {
2021
+ const prefix = `${deviceId}/`;
2022
+ const owner = await this.resolveIngestOwner();
2023
+ const { entries: deviceEntries, slots: profileSlots } = await fetchSnapshotBrokerEntries(this.ctx.api, {
2024
+ deviceId,
2025
+ ownerNodeId: owner.ownerNodeId,
2026
+ reachableHost: owner.reachableHost
2027
+ });
2028
+ const usable = deviceEntries.filter((e) => e.enabled && !!e.url);
2029
+ if (usable.length === 0) return null;
2030
+ if (preferredStreamId && preferredStreamId !== "auto") {
2031
+ const explicit = usable.find((e) => e.brokerId === `${prefix}${preferredStreamId}`);
2032
+ if (explicit) {
2033
+ const grabbed = await this.runGrabWithResumeRetry(explicit.url, deviceId);
2034
+ if (grabbed) return grabbed;
2035
+ this.ctx.logger.debug("grabFrame: explicit stream failed — falling back to auto", { meta: { preferredStreamId } });
2036
+ }
2037
+ }
2038
+ const ranked = [...usable].toSorted((a, b) => qualityRank(b.brokerId, prefix) - qualityRank(a.brokerId, prefix));
2039
+ const statusByBrokerId = /* @__PURE__ */ new Map();
2040
+ for (const slot of profileSlots) statusByBrokerId.set(slot.brokerId, slot.status);
2041
+ const statuses = ranked.map((e) => ({
2042
+ entry: e,
2043
+ status: statusByBrokerId.get(e.brokerId) ?? "idle"
2044
+ }));
2045
+ const warm = pickWarmSnapshotBroker(statuses.map((s) => ({
2046
+ brokerId: s.entry.brokerId,
2047
+ status: s.status
2048
+ })), prefix);
2049
+ if (warm) {
2050
+ const match = statuses.find((s) => s.entry.brokerId === warm.brokerId);
2051
+ if (match) {
2052
+ const grabbed = await this.runGrabWithResumeRetry(match.entry.url, deviceId);
2053
+ if (grabbed) return grabbed;
2054
+ }
2055
+ }
2056
+ for (const { entry } of statuses) {
2057
+ if (isDerivedBrokerId(entry.brokerId, prefix)) continue;
2058
+ const grabbed = await this.runGrabWithResumeRetry(entry.url, deviceId).catch(() => null);
2059
+ if (grabbed) return grabbed;
2060
+ }
2061
+ return null;
2062
+ }
2063
+ /**
2064
+ * Cached, TTL-bounded resolution of the cluster's camera-source owner.
2065
+ * See `ownerCache` doc for the invalidation story.
2066
+ */
2067
+ async resolveIngestOwner() {
2068
+ const now = Date.now();
2069
+ if (this.ownerCache && now - this.ownerCache.ts < SnapshotAddon.OWNER_CACHE_TTL_MS) return this.ownerCache.owner;
2070
+ const owner = await this.fetchIngestOwner();
2071
+ this.ownerCache = {
2072
+ owner,
2073
+ ts: now
2074
+ };
2075
+ return owner;
2076
+ }
2077
+ /**
2078
+ * Same graceful degrade as the recorder's `resolveIngestOwner`
2079
+ * (`packages/addon-pipeline/src/recorder/addon/index.ts`) — the cap may
2080
+ * not be mounted yet (pre-image-release) or the pipeline-orchestrator
2081
+ * addon may be absent entirely; either way we fall back to `'hub'`,
2082
+ * which is byte-identical to the previous hardcoded hub-only behaviour.
2083
+ */
2084
+ async fetchIngestOwner() {
2085
+ try {
2086
+ return await this.ctx.api.pipelineOrchestrator.getIngestOwner.query();
2087
+ } catch (err) {
2088
+ this.ctx.logger.warn("snapshot: getIngestOwner unavailable — defaulting to hub (cap not mounted yet?)", { meta: { error: require_dist.errMsg(err) } });
2089
+ return { ownerNodeId: "hub" };
2090
+ }
2091
+ }
2092
+ /**
2093
+ * Ffmpeg grab with one retry on the broker-cold-start error
2094
+ * signature. Covers the window between "client connected" and
2095
+ * "first keyframe" when a suspended broker resumes.
2096
+ */
2097
+ async runGrabWithResumeRetry(url, deviceId) {
2098
+ let ffmpegPath;
2099
+ try {
2100
+ ffmpegPath = await this.pinnedFfmpeg();
2101
+ } catch (err) {
2102
+ this.ctx.logger.error("grabFrame refused — no pinned ffmpeg on this node (D540)", {
2103
+ tags: { deviceId },
2104
+ meta: { error: require_dist.errMsg(err) }
2105
+ });
2106
+ throw new Error(`grabFrame: no pinned ffmpeg for device ${deviceId} — ${require_dist.errMsg(err)}`, { cause: err });
2107
+ }
2108
+ let buf;
2109
+ try {
2110
+ buf = await this.grabPool.run(() => runFfmpegFrameGrab(ffmpegPath, url, 15e3));
2111
+ } catch (err) {
2112
+ if (isBrokerColdError(require_dist.errMsg(err))) {
2113
+ this.ctx.logger.debug("grabFrame: broker-resume race — retrying in 1500ms", { tags: { deviceId } });
2114
+ await new Promise((r) => setTimeout(r, 1500));
2115
+ buf = await this.grabPool.run(() => runFfmpegFrameGrab(ffmpegPath, url, 15e3));
2116
+ } else throw err;
2117
+ }
2118
+ if (buf.length === 0) return null;
2119
+ return {
2120
+ base64: buf.toString("base64"),
2121
+ contentType: "image/jpeg"
2122
+ };
2123
+ }
2124
+ async invalidateCache(input) {
2125
+ this.dropDeviceCaches(input.deviceId);
2126
+ }
2127
+ /** Forget every cached artefact of one device: frames, derived variants and
2128
+ * any settled single-flight result that would answer the next request. */
2129
+ dropDeviceCaches(deviceId) {
2130
+ this.cache.deleteDevice(deviceId);
2131
+ this.variants.deleteDevice(deviceId);
2132
+ this.stateFrames.delete(deviceId);
2133
+ this.wakingDevices.delete(deviceId);
2134
+ this.deviceMetaMemo.delete(deviceId);
2135
+ this.captureFlight.invalidatePrefix(`${deviceId}:`);
2136
+ }
2137
+ /**
2138
+ * The device is GONE — drop its cached frames and say so.
2139
+ *
2140
+ * Distinct from `invalidateCache` (a refresh, expected and silent): this is
2141
+ * the terminal case, and a deleted camera that keeps answering with its last
2142
+ * JPEG looks to an operator exactly like a camera that was never deleted.
2143
+ */
2144
+ evictRemovedDevice(deviceId, reason) {
2145
+ this.dropDeviceCaches(deviceId);
2146
+ this.fatigue.forget(deviceId);
2147
+ this.ctx.logger.info("snapshot: dropped cache for removed device", {
2148
+ tags: { deviceId },
2149
+ meta: { reason }
2150
+ });
2151
+ }
2152
+ /**
2153
+ * Does device-manager still know this id?
2154
+ *
2155
+ * `null` means the question could not be answered — a transport hiccup is
2156
+ * not a deletion (D49), and the caller keeps serving what it has. Only an
2157
+ * explicit "no such device" evicts.
2158
+ */
2159
+ async deviceStillExists(deviceId) {
2160
+ const api = this.ctx.api;
2161
+ if (!api) return null;
2162
+ try {
2163
+ return await api.deviceManager.getDevice.query({ deviceId }) ? true : false;
2164
+ } catch (err) {
2165
+ this.ctx.logger.debug("snapshot: device existence check failed — keeping cache", {
2166
+ tags: { deviceId },
2167
+ meta: { error: require_dist.errMsg(err) }
2168
+ });
2169
+ return null;
2170
+ }
2171
+ }
2172
+ /**
2173
+ * Resolve the state that must be visible on a snapshot.
2174
+ *
2175
+ * Uses the same two canonical sources as wake-on-play:
2176
+ * 1. `deviceManager.getDevice` for the registry's BatteryOperated feature;
2177
+ * 2. `deviceState.getCapSlice('battery')` for the durable runtime mirror.
2178
+ *
2179
+ * A valid battery slice is itself positive evidence that the device is
2180
+ * battery-operated. That closes the field failure where "Baby monitor" had a
2181
+ * sleeping battery slice but a stale persisted feature projection, so the
2182
+ * snapshot wrapper classified it as mains and a Viewer thumbnail logged in
2183
+ * to the sleeping camera. The reverse is deliberately not guessed: no
2184
+ * feature + no valid slice remains a mains/unknown camera and follows the
2185
+ * ordinary capture path.
2186
+ *
2187
+ * Once battery-operated is established, a missing slice fails safe toward
2188
+ * `sleeping` through the shared `deriveBatteryPresence` function. This avoids
2189
+ * a background wake without inventing an `unreachable` fault.
2190
+ */
2191
+ async resolveSnapshotState(deviceId, meta) {
2192
+ if (meta?.disabled === true) return {
2193
+ isBattery: meta.isBattery,
2194
+ reason: "disabled"
2195
+ };
2196
+ const waking = this.isDeviceWaking(deviceId);
2197
+ let batteryStatus = null;
2198
+ try {
2199
+ const raw = await this.ctx.api.deviceState.getCapSlice.query({
2200
+ deviceId,
2201
+ capName: require_dist.batteryCapability.name
2202
+ });
2203
+ const parsed = require_dist.BatteryStatusSchema.safeParse(raw);
2204
+ if (parsed.success) batteryStatus = parsed.data;
2205
+ } catch (err) {
2206
+ this.ctx.logger.debug("snapshot: battery runtime-state read failed", {
2207
+ tags: { deviceId },
2208
+ meta: { error: require_dist.errMsg(err) }
2209
+ });
2210
+ }
2211
+ const isBattery = meta?.isBattery === true || batteryStatus !== null || waking;
2212
+ const unreachableVerdict = meta?.online === false ? {
2213
+ isBattery,
2214
+ reason: "offline"
2215
+ } : null;
2216
+ if (!isBattery) return unreachableVerdict ?? { isBattery: false };
2217
+ if (waking) return {
2218
+ isBattery: true,
2219
+ reason: "waking"
2220
+ };
2221
+ const presence = require_dist.deriveBatteryPresence({
2222
+ status: batteryStatus,
2223
+ nowMs: Date.now()
2224
+ });
2225
+ if (presence !== "awake") return {
2226
+ isBattery: true,
2227
+ reason: presence
2228
+ };
2229
+ return unreachableVerdict ?? { isBattery: true };
2230
+ }
2231
+ isDeviceWaking(deviceId) {
2232
+ const startedAt = this.wakingDevices.get(deviceId);
2233
+ if (startedAt === void 0) return false;
2234
+ if (Date.now() - startedAt <= SNAPSHOT_WAKING_TTL_MS) return true;
2235
+ this.wakingDevices.delete(deviceId);
2236
+ return false;
2237
+ }
2238
+ /**
2239
+ * True when at least one of the device's brokers is actively
2240
+ * streaming (status === 'streaming'). Used by the battery-cam guard
2241
+ * around `grabFrameFromBroker` to allow the fallback ONLY when
2242
+ * grabbing a frame is free (a consumer is already keeping the
2243
+ * stream warm). When everything is suspended, the fallback would
2244
+ * dial the camera and wake it — defeats the sleeping cache.
2245
+ *
2246
+ * Pinned to the ingest owner via `fetchSnapshotBrokerEntries` — same
2247
+ * rationale as `grabFrameFromBroker`: the device-scoped
2248
+ * `dev.cameraStreams` facade resolves against whichever node the
2249
+ * cap-router picks by default, which is wrong once `ingestNode !=
2250
+ * hub` (queries the hub for slots that only exist on the agent,
2251
+ * always reporting no streaming broker). Owner === hub (no reachable
2252
+ * host) is byte-identical to the previous unpinned call.
2253
+ */
2254
+ async hasStreamingBrokerForDevice(deviceId) {
2255
+ try {
2256
+ const owner = await this.resolveIngestOwner();
2257
+ const { slots } = await fetchSnapshotBrokerEntries(this.ctx.api, {
2258
+ deviceId,
2259
+ ownerNodeId: owner.ownerNodeId,
2260
+ reachableHost: owner.reachableHost
2261
+ });
2262
+ return slots.some((s) => s.status === "streaming");
2263
+ } catch {
2264
+ return false;
2265
+ }
2266
+ }
2267
+ /**
2268
+ * Cache-only batch overview — O(n) over the in-memory cache, NEVER triggers
2269
+ * a capture. Lets a grid skip requesting images for devices that never
2270
+ * produced a frame, and hands each an ETag for conditional image fetches.
2271
+ */
2272
+ getSnapshotOverview(input) {
2273
+ const now = Date.now();
2274
+ const rows = input.deviceIds.map((deviceId) => {
2275
+ const hit = this.cache.latest(deviceId);
2276
+ if (!hit) return {
2277
+ deviceId,
2278
+ lastCapturedAt: null,
2279
+ cacheAgeMs: null,
2280
+ etag: null
2281
+ };
2282
+ return {
2283
+ deviceId,
2284
+ lastCapturedAt: hit.ts,
2285
+ cacheAgeMs: now - hit.ts,
2286
+ etag: `"${deviceId}-${hit.ts}"`
2287
+ };
2288
+ });
2289
+ return Promise.resolve(rows);
2290
+ }
2291
+ /**
2292
+ * Diagnostic status for the `status` auto-injected cap method. Reports
2293
+ * the cache bookkeeping for this device — when the last snapshot was
2294
+ * captured, how stale the cached image is, its size, and which stream
2295
+ * was used. Returns null when the device has never been captured
2296
+ * (cache miss) since the addon started.
2297
+ */
2298
+ async getStatus(deviceId) {
2299
+ const hit = this.cache.latest(deviceId);
2300
+ if (!hit) return null;
2301
+ return {
2302
+ lastCapturedAt: hit.ts,
2303
+ cacheAgeMs: Date.now() - hit.ts,
2304
+ lastBytes: hit.data.base64.length,
2305
+ lastStreamId: hit.streamId
2306
+ };
2307
+ }
2308
+ async readDeviceSettings(deviceId) {
2309
+ if (!this.ctx.settings) return {};
2310
+ const raw = await this.ctx.settings.readDeviceStore(deviceId);
2311
+ const rawAge = raw["snapshotMaxAgeS"];
2312
+ const maxAgeS = typeof rawAge === "number" && rawAge >= 0 && Number.isFinite(rawAge) ? rawAge : void 0;
2313
+ return {
2314
+ snapshotStreamId: typeof raw["snapshotStreamId"] === "string" ? raw["snapshotStreamId"] : void 0,
2315
+ snapshotDebug: raw["snapshotDebug"] === true,
2316
+ ...maxAgeS !== void 0 ? { snapshotMaxAgeS: maxAgeS } : {}
2317
+ };
2318
+ }
2319
+ async buildDeviceSettingsContribution(deviceId) {
2320
+ const meta = await this.lookupDeviceMeta(deviceId);
2321
+ if (meta && meta.type !== require_dist.DeviceType.Camera) return null;
2322
+ const current = await this.readDeviceSettings(deviceId);
2323
+ const streamOptions = await this.getStreamOptions(deviceId);
2324
+ const isBattery = await this.isDeviceBattery(deviceId);
2325
+ const defaultMaxAgeS = isBattery ? BATTERY_DEFAULT_MAX_AGE_S : NON_BATTERY_DEFAULT_MAX_AGE_S;
2326
+ return { sections: [{
2327
+ id: "snapshot-preferences",
2328
+ title: "Snapshot",
2329
+ titleKey: "server:deviceSettingsContribution.s_snapshot-preferences.title",
2330
+ tab: "snapshot",
2331
+ order: 60,
2332
+ fields: [
2333
+ {
2334
+ type: "select",
2335
+ key: "snapshotStreamId",
2336
+ label: "Preferred stream",
2337
+ labelKey: "server:deviceSettingsContribution.s_snapshot-preferences.snapshotStreamId.label",
2338
+ description: "Stream used when grabbing a snapshot",
2339
+ descriptionKey: "server:deviceSettingsContribution.s_snapshot-preferences.snapshotStreamId.description",
2340
+ options: streamOptions,
2341
+ required: true,
2342
+ value: current.snapshotStreamId || "auto"
2343
+ },
2344
+ {
2345
+ type: "number",
2346
+ key: "snapshotMaxAgeS",
2347
+ label: "Max cache age (s)",
2348
+ labelKey: "server:deviceSettingsContribution.s_snapshot-preferences.snapshotMaxAgeS.label",
2349
+ description: `Serve cached snapshot up to this age before re-capturing. Default ${defaultMaxAgeS}s for ${isBattery ? "battery cams (avoids gratuitous wake-ups)" : "non-battery cams (live-feel)"}. The UI refresh button always forces a fresh capture regardless of this value.`,
2350
+ min: 0,
2351
+ max: 24 * 3600,
2352
+ step: 1,
2353
+ value: current.snapshotMaxAgeS ?? defaultMaxAgeS
2354
+ },
2355
+ {
2356
+ type: "boolean",
2357
+ key: "snapshotDebug",
2358
+ label: "Debug logging",
2359
+ labelKey: "server:deviceSettingsContribution.s_snapshot-preferences.snapshotDebug.label",
2360
+ description: "Log stream selection and timing details for this device.",
2361
+ descriptionKey: "server:deviceSettingsContribution.s_snapshot-preferences.snapshotDebug.description",
2362
+ value: current.snapshotDebug ?? false
2363
+ }
2364
+ ]
2365
+ }] };
2366
+ }
2367
+ /**
2368
+ * The frame a camera that CANNOT capture answers with.
2369
+ *
2370
+ * Returns null only if rendering itself fails — the caller then falls through
2371
+ * to its previous behaviour, so a broken courtesy path degrades to the old
2372
+ * 404 rather than masking a real capture failure as a placeholder.
2373
+ *
2374
+ * Rendered at the full tile size; the existing resize ladder derives the
2375
+ * card-sized variants from it exactly as it does for a real frame, so no
2376
+ * downstream consumer needs to know this frame is synthetic.
2377
+ */
2378
+ async courtesyFrame(deviceId, reason, deviceName) {
2379
+ const width = 640;
2380
+ const height = Math.round(width * 9 / 16);
2381
+ const key = require_snapshot_courtesy.courtesyCacheKey({
2382
+ deviceName,
2383
+ reason,
2384
+ width,
2385
+ height
2386
+ });
2387
+ const cached = this.courtesyFrames.get(key);
2388
+ if (cached !== void 0) return cached;
2389
+ try {
2390
+ const bytes = await require_snapshot_courtesy.renderCourtesyJpeg({
2391
+ deviceName,
2392
+ reason,
2393
+ width,
2394
+ height
2395
+ });
2396
+ this.courtesyFrames.set(key, bytes);
2397
+ return bytes;
2398
+ } catch (err) {
2399
+ this.ctx.logger.warn("snapshot: courtesy frame failed — falling back to no image", {
2400
+ tags: { deviceId },
2401
+ meta: {
2402
+ reason,
2403
+ error: require_dist.errMsg(err)
2404
+ }
2405
+ });
2406
+ return null;
2407
+ }
2408
+ }
2409
+ /** A courtesy frame shaped as the cap's response, or null when unrenderable. */
2410
+ async courtesyImage(deviceId, reason, deviceName) {
2411
+ const bytes = await this.courtesyFrame(deviceId, reason, deviceName ?? `#${String(deviceId)}`);
2412
+ return bytes === null ? null : {
2413
+ base64: bytes.toString("base64"),
2414
+ contentType: "image/jpeg"
2415
+ };
2416
+ }
2417
+ /**
2418
+ * The answer for a camera the hub cannot reach: its last good frame, with
2419
+ * `Offline` painted over it, and `offline` stamped on the response identity.
2420
+ *
2421
+ * Called only AFTER the ladder has run (offline is not in
2422
+ * {@link CAPTURE_BLOCKING_REASONS}), so this dresses a frame that could not be
2423
+ * refreshed — never one that just landed.
2424
+ *
2425
+ * The `stateReason` is set FIRST and unconditionally, because it is what a
2426
+ * surface labels the tile from and what puts `offline` in the ETag: a client
2427
+ * holding the live frame has to see a new identity the moment the camera
2428
+ * drops, or it paints the unlabelled photograph until the camera comes back.
2429
+ * A failed render therefore degrades to the raw frame rather than to nothing —
2430
+ * the metadata still says offline, so the tile is still honest.
2431
+ */
2432
+ async offlineImage(deviceId, deviceName, hit, resolutionMeta) {
2433
+ if (resolutionMeta) resolutionMeta.stateReason = "offline";
2434
+ this.ctx.logger.debug("snapshot: serving the offline treatment", {
2435
+ tags: { deviceId },
2436
+ meta: {
2437
+ hasCache: hit !== void 0,
2438
+ ageMs: hit ? Date.now() - hit.ts : null
2439
+ }
2440
+ });
2441
+ return await this.stateImage(deviceId, "offline", deviceName, hit) ?? hit?.data ?? null;
2442
+ }
2443
+ /**
2444
+ * Render a state-labelled answer. A cached real frame is the background, not
2445
+ * the answer by itself; if it cannot be decoded, fall back to the generated
2446
+ * courtesy background rather than leaking an unlabelled stale frame.
2447
+ */
2448
+ /** The persisted frame as a cache entry, with its real age. */
2449
+ async durableEntry(deviceId) {
2450
+ const dated = await this.durable.getDated(deviceId);
2451
+ if (dated === null) return void 0;
2452
+ this.ctx.logger.debug("snapshot: serving the frame kept from a previous process", {
2453
+ tags: { deviceId },
2454
+ meta: { ageMs: Date.now() - dated.capturedAtMs }
2455
+ });
2456
+ return {
2457
+ data: {
2458
+ base64: dated.jpeg.toString("base64"),
2459
+ contentType: "image/jpeg"
2460
+ },
2461
+ ts: dated.capturedAtMs,
2462
+ streamId: null
2463
+ };
2464
+ }
2465
+ async stateImage(deviceId, reason, deviceName, hit) {
2466
+ const resolvedName = deviceName ?? `#${String(deviceId)}`;
2467
+ if (!hit) return await this.courtesyImage(deviceId, reason, resolvedName);
2468
+ const key = `${String(hit.ts)}:${hit.streamId ?? "auto"}:${reason}:${resolvedName}`;
2469
+ const deviceFrames = this.stateFrames.get(deviceId) ?? /* @__PURE__ */ new Map();
2470
+ this.stateFrames.set(deviceId, deviceFrames);
2471
+ const cached = deviceFrames.get(key);
2472
+ if (cached !== void 0) return {
2473
+ base64: cached.toString("base64"),
2474
+ contentType: "image/jpeg"
2475
+ };
2476
+ try {
2477
+ const bytes = await require_snapshot_courtesy.renderCourtesyOverlayJpeg(Buffer.from(hit.data.base64, "base64"), {
2478
+ deviceName: resolvedName,
2479
+ reason
2480
+ });
2481
+ deviceFrames.set(key, bytes);
2482
+ return {
2483
+ base64: bytes.toString("base64"),
2484
+ contentType: "image/jpeg"
2485
+ };
2486
+ } catch (err) {
2487
+ this.ctx.logger.warn("snapshot: state overlay failed — using generated courtesy background", {
2488
+ tags: { deviceId },
2489
+ meta: {
2490
+ reason,
2491
+ error: require_dist.errMsg(err)
2492
+ }
2493
+ });
2494
+ return await this.courtesyImage(deviceId, reason, resolvedName);
2495
+ }
2496
+ }
2497
+ /**
2498
+ * Single-trip device lookup against device-manager — memoized for
2499
+ * {@link DEVICE_META_MEMO_MS} (promise-keyed, so bursts single-flight).
2500
+ * Registry facts only; nothing battery-runtime lives here, so the TTL never
2501
+ * masks a sleep/wake transition. Announced changes evict immediately (the
2502
+ * `device.*` subscriptions in `onInitialize`); the TTL bounds silent drift.
2503
+ */
2504
+ lookupDeviceMeta(deviceId) {
2505
+ const hit = this.deviceMetaMemo.get(deviceId);
2506
+ if (hit !== void 0 && Date.now() - hit.ts < DEVICE_META_MEMO_MS) return hit.promise;
2507
+ const promise = this.fetchDeviceMeta(deviceId);
2508
+ this.deviceMetaMemo.set(deviceId, {
2509
+ ts: Date.now(),
2510
+ promise
2511
+ });
2512
+ return promise;
2513
+ }
2514
+ /**
2515
+ * The actual `deviceManager.getDevice` round trip behind
2516
+ * {@link lookupDeviceMeta}. Returns the stable registry fields the wrapper
2517
+ * consults. Battery classification is completed by `resolveSnapshotState`
2518
+ * from this feature flag PLUS the canonical runtime-state mirror, so a stale
2519
+ * persisted feature projection cannot authorize a snapshot dial against a
2520
+ * known sleeping battery camera.
2521
+ *
2522
+ * Logged at debug + null return on failure: every call site already
2523
+ * has a sensible fallback path (cache hit, conservative default, …),
2524
+ * so we don't want a transient device-manager hiccup to throw.
2525
+ */
2526
+ async fetchDeviceMeta(deviceId) {
2527
+ const api = this.ctx.api;
2528
+ if (!api) return null;
2529
+ try {
2530
+ const found = await api.deviceManager.getDevice.query({ deviceId });
2531
+ if (!found) return null;
2532
+ const features = found.features ?? [];
2533
+ const rawType = found.type;
2534
+ const row = found;
2535
+ return {
2536
+ ...found.name ? { name: found.name } : {},
2537
+ isBattery: features.includes(require_dist.DeviceFeature.BatteryOperated),
2538
+ ...rawType ? { type: rawType } : {},
2539
+ disabled: row.disabled === true,
2540
+ online: row.online !== false
2541
+ };
2542
+ } catch (err) {
2543
+ this.ctx.logger.debug("deviceManager.getDevice failed during snapshot", {
2544
+ tags: { deviceId },
2545
+ meta: { error: err instanceof Error ? err.message : String(err) }
2546
+ });
2547
+ return null;
2548
+ }
2549
+ }
2550
+ /** Settings-UI helper — battery flag drives the default max-age in the field description. */
2551
+ async isDeviceBattery(deviceId) {
2552
+ const meta = await this.lookupDeviceMeta(deviceId);
2553
+ return (await this.resolveSnapshotState(deviceId, meta)).isBattery;
2554
+ }
2555
+ /**
2556
+ * Feeds the settings-UI stream picker. Pinned to the ingest owner via
2557
+ * `fetchSnapshotBrokerEntries` — the device-scoped `dev.cameraStreams`
2558
+ * facade this used to call resolves against whichever node the
2559
+ * cap-router picks by default, which is empty once `ingestNode !=
2560
+ * hub` (the picker would render nothing but "Auto"). Owner === hub
2561
+ * (no reachable host) is byte-identical to the previous unpinned call.
2562
+ */
2563
+ async getStreamOptions(deviceId) {
2564
+ const prefix = `${deviceId}/`;
2565
+ try {
2566
+ const owner = await this.resolveIngestOwner();
2567
+ const { entries } = await fetchSnapshotBrokerEntries(this.ctx.api, {
2568
+ deviceId,
2569
+ ownerNodeId: owner.ownerNodeId,
2570
+ reachableHost: owner.reachableHost
2571
+ });
2572
+ return [{
2573
+ value: "auto",
2574
+ label: "Auto"
2575
+ }, ...entries.filter((e) => e.enabled).map((e) => e.brokerId.slice(prefix.length)).map((id) => ({
2576
+ value: id,
2577
+ label: require_dist.streamQualityLabel(id)
2578
+ }))];
2579
+ } catch (err) {
2580
+ this.ctx.logger.error("getStreamOptions failed", {
2581
+ tags: { deviceId },
2582
+ meta: { error: require_dist.errMsg(err) }
2583
+ });
2584
+ return [{
2585
+ value: "auto",
2586
+ label: "Auto"
2587
+ }];
2588
+ }
2589
+ }
2590
+ async saveDeviceSettingsPatch(deviceId, patch) {
2591
+ if (!this.ctx.settings) throw new Error("[snapshot] settings store unavailable — cannot persist per-device settings");
2592
+ const next = { ...await this.ctx.settings.readDeviceStore(deviceId) };
2593
+ if ("snapshotStreamId" in patch) {
2594
+ const v = patch["snapshotStreamId"];
2595
+ next["snapshotStreamId"] = typeof v === "string" && v.trim().length > 0 ? v.trim() : "";
2596
+ }
2597
+ if ("snapshotDebug" in patch) next["snapshotDebug"] = patch["snapshotDebug"] === true;
2598
+ if ("snapshotMaxAgeS" in patch) {
2599
+ const v = patch["snapshotMaxAgeS"];
2600
+ if (typeof v === "number" && Number.isFinite(v) && v >= 0) next["snapshotMaxAgeS"] = v;
2601
+ else delete next["snapshotMaxAgeS"];
2602
+ }
2603
+ await this.ctx.settings.writeDeviceStore(deviceId, next);
2604
+ this.cache.deleteDevice(deviceId);
2605
+ this.variants.deleteDevice(deviceId);
2606
+ this.captureFlight.invalidatePrefix(`${deviceId}:`);
2607
+ return { success: true };
2608
+ }
2609
+ };
2610
+ function isAbsentNativeError(msg) {
2611
+ return msg.includes("no provider for") || msg.includes("no native provider for capability");
2612
+ }
2613
+ /**
2614
+ * Pinned, testable fetch of this device's RTSP restream entries + profile
2615
+ * slots from the system `streamBroker` cap. Module-level (not a class
2616
+ * method) so `grabFrameFromBroker`'s owner-pin + host-rewrite contract is
2617
+ * directly unit-testable without instantiating the addon — mirrors
2618
+ * `acquireSessionDecodeRestreamFrom` in `pipeline-runner/index.ts`.
2619
+ *
2620
+ * Replaces the former `dev.cameraStreams.getRtspEntries({})` /
2621
+ * `getBrokerStreams({})` device-scoped facade calls, which resolve against
2622
+ * whichever node the cap-router picks by default — wrong once
2623
+ * `ingestNode != hub` (double-pulls the camera, or dials a hub-local
2624
+ * restream nobody is serving). `getAllRtspEntries`/`listAllProfileSlots`
2625
+ * are cluster-wide system-cap methods; pinning the call with `nodePin` +
2626
+ * filtering by the `${deviceId}/` brokerId prefix reproduces the exact
2627
+ * device-scoped result set the facade used to return.
2628
+ *
2629
+ * `reachableHost`, when present, rides as the cap's own `hostname` input —
2630
+ * the broker rewrites the returned URLs' host itself (same mechanism
2631
+ * `getStreamWithCodec` callers use for cross-node pulls), so no separate
2632
+ * client-side host-substitution is needed here. Omitting `hostname`
2633
+ * (owner === hub, no reachable host registered) leaves the broker's
2634
+ * default `127.0.0.1` URLs untouched — byte-identical to today.
2635
+ */
2636
+ async function fetchSnapshotBrokerEntries(api, params) {
2637
+ const { deviceId, ownerNodeId, reachableHost } = params;
2638
+ const prefix = `${deviceId}/`;
2639
+ const pin = require_dist.nodePin(ownerNodeId);
2640
+ const [allEntries, allSlots] = await Promise.all([api.streamBroker.getAllRtspEntries.query(reachableHost !== void 0 ? { hostname: reachableHost } : {}, pin), api.streamBroker.listAllProfileSlots.query(void 0, pin)]);
2641
+ return {
2642
+ entries: allEntries.filter((e) => e.brokerId.startsWith(prefix)),
2643
+ slots: allSlots.filter((s) => s.deviceId === deviceId)
2644
+ };
2645
+ }
2646
+ /**
2647
+ * Quality ordering for broker picker: `high` > `mid` > `low` > other.
2648
+ * The streamId is the suffix after `${deviceId}/` in the brokerId.
2649
+ * Unknown labels fall through to 0 so they land at the bottom of the
2650
+ * preference list without crashing.
2651
+ */
2652
+ function qualityRank(brokerId, prefix) {
2653
+ const normalized = (brokerId.startsWith(prefix) ? brokerId.slice(prefix.length) : brokerId).toLowerCase();
2654
+ if (normalized.includes("high") || normalized === "main" || normalized === "hd") return 3;
2655
+ if (normalized.includes("mid") || normalized === "medium") return 2;
2656
+ if (normalized.includes("low") || normalized === "sub" || normalized === "sd") return 1;
2657
+ return 0;
2658
+ }
2659
+ /**
2660
+ * Detect ffmpeg failure signatures that indicate the broker wasn't
2661
+ * streaming yet when we tried to read its RTSP restream — a race
2662
+ * window that closes as soon as the broker lands its first keyframe.
2663
+ * Used by `grabFrameFromBroker` to retry once instead of giving up.
2664
+ */
2665
+ function isBrokerColdError(msg) {
2666
+ return msg.includes("Invalid data found when processing input") || msg.includes("Error opening input") || msg.includes("Connection refused") || msg.includes("No route to host");
2667
+ }
2668
+ function runFfmpegFrameGrab(ffmpegPath, url, timeoutMs) {
2669
+ return new Promise((resolve, reject) => {
2670
+ (0, node_child_process.execFile)(ffmpegPath, [
2671
+ "-loglevel",
2672
+ "error",
2673
+ "-threads",
2674
+ "1",
2675
+ "-filter_threads",
2676
+ "1",
2677
+ "-rtsp_transport",
2678
+ "tcp",
2679
+ "-fflags",
2680
+ "+discardcorrupt",
2681
+ "-skip_frame",
2682
+ "nokey",
2683
+ "-i",
2684
+ url,
2685
+ "-vf",
2686
+ "select=eq(pict_type\\,I)",
2687
+ "-vsync",
2688
+ "vfr",
2689
+ "-frames:v",
2690
+ "1",
2691
+ "-q:v",
2692
+ "3",
2693
+ "-f",
2694
+ "image2pipe",
2695
+ "-vcodec",
2696
+ "mjpeg",
2697
+ "pipe:1"
2698
+ ], {
2699
+ encoding: "buffer",
2700
+ maxBuffer: 16 * 1024 * 1024,
2701
+ timeout: timeoutMs
2702
+ }, (err, stdout, stderr) => {
2703
+ if (err) {
2704
+ const errWithMeta = err;
2705
+ const stderrText = Buffer.isBuffer(stderr) ? stderr.toString("utf8").trim() : String(stderr ?? "").trim();
2706
+ const parts = [err instanceof Error ? err.message : String(err)];
2707
+ if (errWithMeta.killed) parts.push("killed=true");
2708
+ if (errWithMeta.code !== void 0) parts.push(`code=${String(errWithMeta.code)}`);
2709
+ if (errWithMeta.signal) parts.push(`signal=${errWithMeta.signal}`);
2710
+ if (stderrText) parts.push(`stderr: ${stderrText.slice(0, 500)}`);
2711
+ reject(new Error(parts.join(" — ")));
2712
+ return;
2713
+ }
2714
+ resolve(Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout));
2715
+ }).on("error", (e) => reject(e));
2716
+ });
2717
+ }
2718
+ //#endregion
2719
+ exports.SnapshotAddon = SnapshotAddon;
2720
+ exports.default = SnapshotAddon;