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