@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,2878 @@
1
+ import { Jn as deviceRemovalHookCapability, Kn as deviceHistoryCapability, Ms as EventCategory, Qa as BaseAddon, R as DEVICE_HISTORY_ENERGY_KEY, Za as wattMillisecondsToKwh, Zo as historyUnitFor, ns as isReadingQuantity, nt as HISTORY_CATALOG, qo as emitReadiness, rn as armRemovalReconcile, rt as HISTORY_ITEM_CATALOG } from "../../dist-DcMqHB_N.mjs";
2
+ import { S as subjectIdOf, _ as readUnit, a as FIVE_MINUTES_MS, b as SeriesRegistry, c as bucketEndOf, d as CAP_KEY_PREFIX, f as CaptureEngine, g as readPath, h as catalogMetrics, i as DAY_MS, l as bucketStartOf, m as capSeriesKey, n as RetentionJob, o as HOUR_MS, p as capItemSeriesKey, r as DepartureTracker, s as ROLLUP_GRACE_MS, t as DEFAULT_RETENTION, u as floorTo, v as DeviceDirectory, x as identityOf, y as isRealDeviceType } from "../../retention-Dqm_EiVq.mjs";
3
+ //#region src/builtins/device-history/capture/point-writer.ts
4
+ var FLUSH_INTERVAL_MS = 1e4;
5
+ var MAX_BUFFER_AGE_MS = 6e4;
6
+ /** Beyond this many queued points the oldest are dropped. */
7
+ var MAX_QUEUE_POINTS = 1e5;
8
+ /** The share of the queue dropped at once when it is full. */
9
+ var QUEUE_DROP_FRACTION = .1;
10
+ /** Device ids named in a drop line, so a line stays short. */
11
+ var MAX_DEVICES_IN_DROP_LINE = 20;
12
+ /** Tagged per-device drop lines per event, and the quiet time between events that print them. */
13
+ var MAX_DEVICE_LINES_PER_DROP = 10;
14
+ var DEVICE_LINES_MIN_GAP_MS = 1e4;
15
+ var PointWriter = class {
16
+ deps;
17
+ queue = [];
18
+ flushing = null;
19
+ lastDeviceLinesAt = Number.NEGATIVE_INFINITY;
20
+ constructor(deps) {
21
+ this.deps = deps;
22
+ }
23
+ enqueue(point) {
24
+ this.queue.push({
25
+ ...point,
26
+ bufferedAt: this.deps.clock()
27
+ });
28
+ if (this.queue.length > 1e5) {
29
+ const count = Math.ceil(MAX_QUEUE_POINTS * QUEUE_DROP_FRACTION);
30
+ this.drop(this.queue.splice(0, count), "queue full");
31
+ }
32
+ }
33
+ depth() {
34
+ return this.queue.length;
35
+ }
36
+ /** One flush at a time; a call while one runs waits for it and returns. */
37
+ flush() {
38
+ if (this.flushing !== null) return this.flushing;
39
+ const run = this.doFlush().finally(() => {
40
+ this.flushing = null;
41
+ });
42
+ this.flushing = run;
43
+ return run;
44
+ }
45
+ async doFlush() {
46
+ const batch = this.queue;
47
+ if (batch.length === 0) return;
48
+ this.queue = [];
49
+ const { registry, store, counters, logger, clock } = this.deps;
50
+ try {
51
+ await registry.persistDirtyMetrics();
52
+ const bySeries = /* @__PURE__ */ new Map();
53
+ for (const point of batch) {
54
+ const series = await registry.ensure(point.key, point.subject, point.scope, point.ts);
55
+ const list = bySeries.get(series.id) ?? [];
56
+ list.push({
57
+ ts: point.ts,
58
+ value: point.value
59
+ });
60
+ bySeries.set(series.id, list);
61
+ }
62
+ const rows = [...bySeries].flatMap(([seriesId, points]) => points.map((p) => ({
63
+ seriesId,
64
+ ts: p.ts,
65
+ value: p.value
66
+ })));
67
+ await store.upsertRaw(rows);
68
+ await this.recordSpans(bySeries);
69
+ counters.pointsWritten += rows.length;
70
+ counters.addRawRows(rows.length);
71
+ counters.lastFlushAt = clock();
72
+ this.deps.onWritten([...bySeries].map(([seriesId, points]) => ({
73
+ seriesId,
74
+ timestamps: points.map((p) => p.ts)
75
+ })));
76
+ } catch (err) {
77
+ counters.flushFailures += 1;
78
+ logger.warn("device-history: raw flush failed — keeping the batch", { meta: {
79
+ points: batch.length,
80
+ error: err instanceof Error ? err.message : String(err)
81
+ } });
82
+ this.requeue(batch);
83
+ }
84
+ }
85
+ async recordSpans(bySeries) {
86
+ const { registry, store } = this.deps;
87
+ const touch = [];
88
+ for (const [seriesId, points] of bySeries) {
89
+ const current = registry.byIdOf(seriesId);
90
+ if (current === void 0) continue;
91
+ let minTs = Number.POSITIVE_INFINITY;
92
+ let maxTs = Number.NEGATIVE_INFINITY;
93
+ for (const p of points) {
94
+ if (p.ts < minTs) minTs = p.ts;
95
+ if (p.ts > maxTs) maxTs = p.ts;
96
+ }
97
+ if (minTs < current.firstTs) await store.widenSeriesStart(seriesId, minTs);
98
+ if (maxTs > current.lastTs) touch.push({
99
+ id: seriesId,
100
+ lastTs: maxTs
101
+ });
102
+ registry.noteSpan(seriesId, minTs, maxTs);
103
+ }
104
+ await store.touchSeries(touch);
105
+ }
106
+ requeue(batch) {
107
+ const now = this.deps.clock();
108
+ const keep = [];
109
+ const dropped = [];
110
+ for (const point of batch) if (now - point.bufferedAt > 6e4) dropped.push(point);
111
+ else keep.push(point);
112
+ this.queue = [...keep, ...this.queue];
113
+ if (dropped.length > 0) this.drop(dropped, `older than ${MAX_BUFFER_AGE_MS} ms`);
114
+ }
115
+ /** Account for, say, and report to the owner a set of points that will never be written. */
116
+ drop(dropped, reason) {
117
+ if (dropped.length === 0) return;
118
+ const { counters, logger, clock } = this.deps;
119
+ counters.pointsDropped += dropped.length;
120
+ const perDevice = /* @__PURE__ */ new Map();
121
+ for (const p of dropped) if (p.subject.kind === "device") perDevice.set(p.subject.deviceId, (perDevice.get(p.subject.deviceId) ?? 0) + 1);
122
+ logger.error("device-history: dropped points the store would not take", { meta: {
123
+ dropped: dropped.length,
124
+ reason,
125
+ maxAgeMs: MAX_BUFFER_AGE_MS,
126
+ deviceIds: [...perDevice.keys()].slice(0, MAX_DEVICES_IN_DROP_LINE)
127
+ } });
128
+ const now = clock();
129
+ if (now - this.lastDeviceLinesAt >= DEVICE_LINES_MIN_GAP_MS) {
130
+ this.lastDeviceLinesAt = now;
131
+ for (const [deviceId, count] of [...perDevice].slice(0, MAX_DEVICE_LINES_PER_DROP)) logger.warn("device-history: points dropped for this device", {
132
+ tags: { deviceId },
133
+ meta: {
134
+ dropped: count,
135
+ reason
136
+ }
137
+ });
138
+ }
139
+ this.deps.onDropped(dropped);
140
+ }
141
+ };
142
+ //#endregion
143
+ //#region src/builtins/device-history/ingest/producer-ingest.ts
144
+ /** One point per series per this many ms, sustained. */
145
+ var RECORD_MIN_INTERVAL_MS = 1e4;
146
+ /**
147
+ * The slot after accepting a point at `ts`. A point older than the newest
148
+ * accepted one (a late arrival) moves nothing. Otherwise the consumed slot is
149
+ * the later of the one that was due and `ts` itself: an early point uses the
150
+ * due slot (the grid holds, so slack never compounds into a higher rate), a
151
+ * late one restarts the grid at `ts` (no credit is banked for a gap).
152
+ */
153
+ function nextSlot(slot, ts) {
154
+ if (slot === void 0) return {
155
+ lastTs: ts,
156
+ nextDue: ts + RECORD_MIN_INTERVAL_MS
157
+ };
158
+ if (ts < slot.lastTs) return slot;
159
+ return {
160
+ lastTs: ts,
161
+ nextDue: Math.max(slot.nextDue, ts) + RECORD_MIN_INTERVAL_MS
162
+ };
163
+ }
164
+ function addRefusal(refusals, key, reason) {
165
+ const byReason = refusals.get(key) ?? /* @__PURE__ */ new Map();
166
+ byReason.set(reason, (byReason.get(reason) ?? 0) + 1);
167
+ refusals.set(key, byReason);
168
+ }
169
+ function toResult(accepted, refusals) {
170
+ return {
171
+ accepted,
172
+ refused: [...refusals].flatMap(([key, byReason]) => [...byReason].map(([reason, count]) => ({
173
+ key,
174
+ reason,
175
+ count
176
+ })))
177
+ };
178
+ }
179
+ var ProducerIngest = class {
180
+ deps;
181
+ /** Rate state per series identity, for the sustained-rate bound. */
182
+ lastAccepted = /* @__PURE__ */ new Map();
183
+ constructor(deps) {
184
+ this.deps = deps;
185
+ }
186
+ /** A purged series leaves no rate-limit state behind. */
187
+ forgetSeries(series) {
188
+ this.lastAccepted.delete(identityOf(series.key, series.subject, series.scope));
189
+ }
190
+ async declareSeries(callerAddonId, input) {
191
+ if (callerAddonId === null) throw new Error("declareSeries: the caller addon could not be identified");
192
+ const key = `addon:${callerAddonId}/${input.name}`;
193
+ const metric = {
194
+ key,
195
+ source: "addon",
196
+ ownerAddon: callerAddonId,
197
+ subjectKind: input.subjectKind,
198
+ kind: input.kind,
199
+ unit: input.unit ?? null,
200
+ displayName: input.displayName,
201
+ ingest: input.ingest,
202
+ declaredAt: this.deps.clock(),
203
+ values: null
204
+ };
205
+ await this.deps.registry.declareMetric(metric);
206
+ return { key };
207
+ }
208
+ /** Why a write to `metric` by `caller` for this subject must be refused, or null. */
209
+ async refusalFor(callerAddonId, metric, ingest, subject) {
210
+ if (metric === void 0) return "undeclared";
211
+ if (callerAddonId === null || metric.ownerAddon !== callerAddonId) return "not-owner";
212
+ if (metric.ingest !== ingest) return "ingest-mismatch";
213
+ if (metric.subjectKind !== subject.kind) return "undeclared";
214
+ if (subject.kind === "device") {
215
+ if (this.deps.optedOut().has(subject.deviceId)) return "opted-out";
216
+ const type = await this.deps.directory.ensure(subject.deviceId);
217
+ if (type === void 0 || !isRealDeviceType(type)) return "not-a-real-device";
218
+ }
219
+ return null;
220
+ }
221
+ async record(callerAddonId, points) {
222
+ const { clock, counters } = this.deps;
223
+ const now = clock();
224
+ const { rawMs } = this.deps.retention();
225
+ const refusals = /* @__PURE__ */ new Map();
226
+ let accepted = 0;
227
+ for (const point of points) {
228
+ const reason = await this.refusalFor(callerAddonId, this.deps.registry.metric(point.key), "points", point.subject);
229
+ if (reason !== null) {
230
+ addRefusal(refusals, point.key, reason);
231
+ counters.refuse(reason);
232
+ continue;
233
+ }
234
+ if (!Number.isFinite(point.value) || !Number.isFinite(point.ts) || point.ts > now + 3e5 || point.ts < now - rawMs) {
235
+ addRefusal(refusals, point.key, "out-of-range");
236
+ counters.refuse("out-of-range");
237
+ continue;
238
+ }
239
+ const identity = identityOf(point.key, subjectIdOf(point.subject), point.scope);
240
+ const slot = this.lastAccepted.get(identity);
241
+ if (slot !== void 0 && point.ts >= slot.lastTs && point.ts < slot.nextDue - 1e3) {
242
+ addRefusal(refusals, point.key, "rate");
243
+ counters.refuse("rate");
244
+ continue;
245
+ }
246
+ this.lastAccepted.set(identity, nextSlot(slot, point.ts));
247
+ this.deps.writer.enqueue({
248
+ key: point.key,
249
+ subject: point.subject,
250
+ scope: point.scope,
251
+ ts: point.ts,
252
+ value: point.value
253
+ });
254
+ accepted += 1;
255
+ }
256
+ counters.ingestAccepted += accepted;
257
+ return toResult(accepted, refusals);
258
+ }
259
+ async recordBuckets(callerAddonId, buckets) {
260
+ const { clock, counters, registry, store } = this.deps;
261
+ const now = clock();
262
+ const { fiveMinuteMs } = this.deps.retention();
263
+ const refusals = /* @__PURE__ */ new Map();
264
+ const rows = [];
265
+ for (const bucket of buckets) {
266
+ const reason = await this.refusalFor(callerAddonId, registry.metric(bucket.key), "buckets", bucket.subject);
267
+ if (reason !== null) {
268
+ addRefusal(refusals, bucket.key, reason);
269
+ counters.refuse(reason);
270
+ continue;
271
+ }
272
+ const aligned = bucket.bucketStart % FIVE_MINUTES_MS === 0;
273
+ const consistent = Number.isFinite(bucket.sum) && Number.isFinite(bucket.min) && Number.isFinite(bucket.max) && bucket.min <= bucket.max;
274
+ if (!aligned || !consistent || bucket.bucketStart > now + 3e5 || bucket.bucketStart < now - fiveMinuteMs) {
275
+ addRefusal(refusals, bucket.key, "out-of-range");
276
+ counters.refuse("out-of-range");
277
+ continue;
278
+ }
279
+ const series = await registry.ensure(bucket.key, bucket.subject, bucket.scope, bucket.bucketStart);
280
+ rows.push({
281
+ seriesId: series.id,
282
+ bucketStart: bucket.bucketStart,
283
+ samples: bucket.samples,
284
+ sum: bucket.sum,
285
+ min: bucket.min,
286
+ max: bucket.max,
287
+ last: bucket.last,
288
+ lastTs: bucket.lastTs,
289
+ twSum: null,
290
+ twMs: null,
291
+ states: null
292
+ });
293
+ }
294
+ await store.upsertRollups("5m", rows);
295
+ const bySeries = /* @__PURE__ */ new Map();
296
+ for (const row of rows) bySeries.set(row.seriesId, [...bySeries.get(row.seriesId) ?? [], row.bucketStart]);
297
+ for (const [seriesId, starts] of bySeries) counters.noteRollupRows("5m", seriesId, starts.toSorted((a, b) => a - b));
298
+ await this.recordSpans(rows);
299
+ for (const row of rows) this.deps.onBucketWritten(row.seriesId, row.bucketStart);
300
+ counters.ingestAccepted += rows.length;
301
+ return toResult(rows.length, refusals);
302
+ }
303
+ /** Persist the widened span of every series a bucket batch touched, then remember it. */
304
+ async recordSpans(rows) {
305
+ const { registry, store } = this.deps;
306
+ const spans = /* @__PURE__ */ new Map();
307
+ for (const row of rows) {
308
+ const end = row.lastTs ?? row.bucketStart;
309
+ const span = spans.get(row.seriesId);
310
+ spans.set(row.seriesId, {
311
+ first: span === void 0 ? row.bucketStart : Math.min(span.first, row.bucketStart),
312
+ last: span === void 0 ? end : Math.max(span.last, end)
313
+ });
314
+ }
315
+ const touch = [];
316
+ for (const [id, span] of spans) {
317
+ const current = registry.byIdOf(id);
318
+ if (current === void 0) continue;
319
+ if (span.first < current.firstTs) await store.widenSeriesStart(id, span.first);
320
+ if (span.last > current.lastTs) touch.push({
321
+ id,
322
+ lastTs: span.last
323
+ });
324
+ registry.noteSpan(id, span.first, span.last);
325
+ }
326
+ await store.touchSeries(touch);
327
+ }
328
+ };
329
+ //#endregion
330
+ //#region src/builtins/device-history/query/point-shape.ts
331
+ /**
332
+ * Stored rows → the wire points of a query (PURE). What a point MEANS depends on
333
+ * the series' kind:
334
+ *
335
+ * - `gauge` / `boolean`: the stored numbers as they are (`twMean` of a boolean
336
+ * is the fraction of time true);
337
+ * - `counter`: plus `delta`, the growth since the previous point or bucket. A
338
+ * reading LOWER than the previous one is a reset (a replaced meter, a
339
+ * firmware wipe): the growth is counted from zero, never negative. With no
340
+ * previous reading, a bucket's own growth is `last - min`;
341
+ * - `enum`: the stored number is an ordinal, so `mean` / `twMean` mean nothing
342
+ * and are `null`; `state` names the ordinal and a rollup's `states` gives the
343
+ * milliseconds spent in each state, by name.
344
+ */
345
+ /** Growth from `prev` to `cur`; a drop is a reset counted from zero. `fallback` when `prev` is unknown. */
346
+ function counterDelta(prev, cur, fallback) {
347
+ if (cur === null) return null;
348
+ if (prev === null) return fallback;
349
+ return cur >= prev ? cur - prev : cur;
350
+ }
351
+ /** The name of an ordinal, or `null` when the series is not an enum or the ordinal is unknown. */
352
+ function stateName(meaning, ordinal) {
353
+ if (meaning.kind !== "enum" || meaning.values === null || ordinal === null) return null;
354
+ return meaning.values[ordinal] ?? null;
355
+ }
356
+ function namedStates(meaning, states) {
357
+ if (meaning.kind !== "enum" || states === null) return null;
358
+ const out = {};
359
+ for (const [ordinal, ms] of Object.entries(states)) {
360
+ const name = stateName(meaning, Number(ordinal));
361
+ if (name !== null) out[name] = (out[name] ?? 0) + ms;
362
+ }
363
+ return out;
364
+ }
365
+ /** Raw points, oldest first; `prev` is the value of the point before the first one. */
366
+ function rawPoints(rows, meaning, prev) {
367
+ const isEnum = meaning.kind === "enum";
368
+ let held = prev;
369
+ return rows.map((r) => {
370
+ const delta = meaning.kind === "counter" ? counterDelta(held, r.value, null) : null;
371
+ held = r.value;
372
+ return {
373
+ t: r.ts,
374
+ samples: 1,
375
+ mean: isEnum ? null : r.value,
376
+ twMean: null,
377
+ min: r.value,
378
+ max: r.value,
379
+ last: r.value,
380
+ delta,
381
+ state: stateName(meaning, r.value),
382
+ states: null
383
+ };
384
+ });
385
+ }
386
+ /** Rollup rows, oldest first; `prevLast` is the `last` of the bucket before the first one. */
387
+ function rollupPoints(rows, meaning, prevLast) {
388
+ const isEnum = meaning.kind === "enum";
389
+ let held = prevLast;
390
+ return rows.map((row) => {
391
+ const delta = meaning.kind === "counter" ? counterDelta(held, row.last, row.last === null ? null : row.last - row.min) : null;
392
+ if (row.last !== null) held = row.last;
393
+ return {
394
+ t: row.bucketStart,
395
+ samples: row.samples,
396
+ mean: isEnum || row.samples <= 0 ? null : row.sum / row.samples,
397
+ twMean: !isEnum && row.twSum !== null && row.twMs !== null && row.twMs > 0 ? row.twSum / row.twMs : null,
398
+ min: row.min,
399
+ max: row.max,
400
+ last: row.last,
401
+ delta,
402
+ state: stateName(meaning, row.last),
403
+ states: namedStates(meaning, row.states)
404
+ };
405
+ });
406
+ }
407
+ /** Energy used in each bucket of a `power` gauge: its time-weighted integral, in kWh. */
408
+ function integratedEnergyPoints(rows) {
409
+ return rows.map((row) => ({
410
+ t: row.bucketStart,
411
+ samples: row.samples,
412
+ mean: null,
413
+ twMean: null,
414
+ min: row.min,
415
+ max: row.max,
416
+ last: null,
417
+ delta: row.twSum === null ? null : wattMillisecondsToKwh(row.twSum),
418
+ state: null,
419
+ states: null
420
+ }));
421
+ }
422
+ //#endregion
423
+ //#region src/builtins/device-history/query/history-query.ts
424
+ /**
425
+ * Reads: `listSeries`, `query` and `queryMany` (plan §5.1).
426
+ *
427
+ * `auto` resolution picks the finest tier whose retention covers `from` and
428
+ * whose point count fits `maxPoints`: a rollup tier fits when
429
+ * `ceil(range / bucket) <= maxPoints`, raw fits when a read of `maxPoints + 1`
430
+ * rows comes back short. The coarsest covering tier is the last resort and is
431
+ * truncated to its newest `maxPoints` points (`truncated: true`) rather than
432
+ * answering nothing. A series fed by closed buckets has NO raw rows, so raw is
433
+ * never a candidate for it: an empty raw read "fits" every window.
434
+ *
435
+ * `before` is the last point strictly before the window in the chosen tier, so a
436
+ * step chart can start at the value in force when the window opens — a quiet
437
+ * bucket has no row, and the held value is otherwise invisible.
438
+ *
439
+ * {@link DEVICE_HISTORY_ENERGY_KEY} is computed here at read time, never stored:
440
+ * the device's `energy` meter when it has one (per-bucket growth), else the
441
+ * time-weighted integral of its `power` (`tw_sum`, already in every rollup).
442
+ * One place makes that choice, so two charts of one device cannot disagree, and
443
+ * it covers every hour of history recorded before the key existed.
444
+ */
445
+ var TIER_ORDER = [
446
+ "raw",
447
+ "5m",
448
+ "1h",
449
+ "1d"
450
+ ];
451
+ var BUCKET_MS = {
452
+ "5m": FIVE_MINUTES_MS,
453
+ "1h": HOUR_MS,
454
+ "1d": DAY_MS
455
+ };
456
+ /** A key with more scopes than this is cut (a zone x class matrix, not a chart). */
457
+ var MAX_SCOPES = 50;
458
+ /** The power-meter series the energy key is derived from, meter first. */
459
+ var ENERGY_METER_KEY = capSeriesKey("power-meter", "energy");
460
+ var ENERGY_POWER_KEY = capSeriesKey("power-meter", "power");
461
+ /**
462
+ * Series whose quantity is chosen per device (D944). Weather is not here:
463
+ * each weather field has its own quantity on the capability, and the catalog
464
+ * unit is that base. A past weather point stored in another unit cannot be
465
+ * rescaled — the unit at sample time was not kept.
466
+ */
467
+ var DEVICE_QUANTITY_KEYS = new Set([capSeriesKey("numeric-sensor", "value"), capSeriesKey("meter", "value")]);
468
+ function retentionMsOf(tier, policy) {
469
+ if (tier === "raw") return policy.rawDays * DAY_MS;
470
+ if (tier === "5m") return policy.fiveMinuteDays * DAY_MS;
471
+ if (tier === "1h") return policy.hourDays * DAY_MS;
472
+ return policy.dayDays === null || policy.dayDays <= 0 ? null : policy.dayDays * DAY_MS;
473
+ }
474
+ /** Rows arrive newest first and one over the bound; keep the newest `maxPoints`, oldest first. */
475
+ function bounded(newestFirst, maxPoints) {
476
+ const overflow = newestFirst.length > maxPoints;
477
+ return {
478
+ rows: (overflow ? newestFirst.slice(0, maxPoints) : newestFirst).toReversed(),
479
+ overflow
480
+ };
481
+ }
482
+ function errorText(err) {
483
+ return err instanceof Error ? err.message : String(err);
484
+ }
485
+ var HistoryQuery = class {
486
+ deps;
487
+ itemFields;
488
+ constructor(deps) {
489
+ this.deps = deps;
490
+ this.itemFields = itemFieldsByKey(deps.itemCatalog);
491
+ }
492
+ async query(input) {
493
+ if (input.key === "derived:energy.kwh") return this.queryEnergy(input);
494
+ const { registry } = this.deps;
495
+ const wanted = this.seriesOf(input);
496
+ const metric = registry.metric(input.key);
497
+ const meaning = {
498
+ kind: metric?.kind ?? "gauge",
499
+ values: metric?.values ?? null
500
+ };
501
+ const { chosen, reads } = await this.choose(input, wanted, metric?.ingest === "buckets");
502
+ const series = [];
503
+ for (const [s, read] of reads) {
504
+ const before = await this.before(chosen, s, input.from, meaning);
505
+ const points = read.tier === "raw" ? rawPoints(read.rows, meaning, before?.value ?? null) : rollupPoints(read.rows, meaning, before?.value ?? null);
506
+ series.push({
507
+ scope: s.scope,
508
+ before,
509
+ points,
510
+ derivedFrom: null
511
+ });
512
+ }
513
+ return {
514
+ resolution: chosen,
515
+ series,
516
+ truncated: reads.some(([, r]) => r.overflow)
517
+ };
518
+ }
519
+ /** Several reads over one window; one failing item answers its error, not the batch's. */
520
+ async queryMany(input) {
521
+ const out = [];
522
+ for (const item of input.items) {
523
+ const subject = "deviceId" in item ? {
524
+ kind: "device",
525
+ deviceId: item.deviceId
526
+ } : {
527
+ kind: "node",
528
+ nodeId: item.forNodeId
529
+ };
530
+ try {
531
+ const result = await this.query({
532
+ key: item.key,
533
+ subject,
534
+ ...item.scope !== void 0 ? { scope: item.scope } : {},
535
+ from: input.from,
536
+ to: input.to,
537
+ resolution: input.resolution,
538
+ maxPoints: input.maxPoints
539
+ });
540
+ out.push({
541
+ ok: true,
542
+ result
543
+ });
544
+ } catch (err) {
545
+ out.push({
546
+ ok: false,
547
+ error: errorText(err)
548
+ });
549
+ }
550
+ }
551
+ return out;
552
+ }
553
+ seriesOf(input) {
554
+ return this.deps.registry.forKeyAndSubject(input.key, subjectIdOf(input.subject)).filter((s) => input.scope === void 0 || s.scope === input.scope).toSorted((a, b) => a.scope.localeCompare(b.scope)).slice(0, MAX_SCOPES);
555
+ }
556
+ /** The tier to answer from and its reads. `noRaw`: the series has no raw rows to read. */
557
+ async choose(input, wanted, noRaw) {
558
+ const covering = this.coveringTiers(input.from);
559
+ const candidates = noRaw ? withoutRaw(covering) : covering;
560
+ const forced = input.resolution === "auto" ? null : input.resolution;
561
+ const order = forced === null ? candidates : [noRaw && forced === "raw" ? "5m" : forced];
562
+ let chosen = order[order.length - 1] ?? "1d";
563
+ let reads = [];
564
+ for (const [index, tier] of order.entries()) {
565
+ const last = index === order.length - 1;
566
+ if (!this.fits(tier, input, wanted) && !last) continue;
567
+ chosen = tier;
568
+ reads = await Promise.all(wanted.map(async (s) => [s, await this.readTier(tier, s, input)]));
569
+ if (reads.some(([, r]) => r.overflow) && !last) continue;
570
+ break;
571
+ }
572
+ return {
573
+ chosen,
574
+ reads
575
+ };
576
+ }
577
+ /** Tiers whose retention covers `from`, finest first; the coarsest is always present. */
578
+ coveringTiers(from) {
579
+ const policy = this.deps.retention();
580
+ const now = this.deps.clock();
581
+ const covering = TIER_ORDER.filter((tier) => {
582
+ const ms = retentionMsOf(tier, policy);
583
+ return ms === null || from >= now - ms;
584
+ });
585
+ return covering.length > 0 ? covering : ["1d"];
586
+ }
587
+ /** Cheap fit test for rollup tiers; raw is decided by the read itself. */
588
+ fits(tier, input, series) {
589
+ if (tier === "raw" || series.length === 0) return true;
590
+ const width = BUCKET_MS[tier];
591
+ return Math.ceil((input.to - input.from) / width) <= input.maxPoints;
592
+ }
593
+ async readTier(tier, series, input) {
594
+ const { store } = this.deps;
595
+ const limit = input.maxPoints + 1;
596
+ if (tier === "raw") return {
597
+ tier,
598
+ ...bounded(await store.readRaw(series.id, input.from, input.to, limit, "desc"), input.maxPoints)
599
+ };
600
+ const lower = bucketStartOf(tier, input.from);
601
+ return {
602
+ tier,
603
+ ...bounded(await store.readRollups(tier, series.id, lower, input.to, limit, "desc"), input.maxPoints)
604
+ };
605
+ }
606
+ async before(tier, series, from, meaning) {
607
+ const { store } = this.deps;
608
+ if (tier === "raw") {
609
+ const p = await store.rawBefore(series.id, from);
610
+ return p === null ? null : {
611
+ t: p.ts,
612
+ value: p.value,
613
+ state: stateName(meaning, p.value)
614
+ };
615
+ }
616
+ const row = await store.rollupBefore(tier, series.id, bucketStartOf(tier, from));
617
+ return row === null ? null : {
618
+ t: row.bucketStart,
619
+ value: row.last,
620
+ state: stateName(meaning, row.last)
621
+ };
622
+ }
623
+ /** The series energy is derived from for a device: the meter when it has one, else its power. */
624
+ energySource(subject) {
625
+ if (subject.kind !== "device") return null;
626
+ const subjectId = subjectIdOf(subject);
627
+ const meter = this.deps.registry.find(ENERGY_METER_KEY, subjectId, "");
628
+ if (meter !== void 0) return {
629
+ series: meter,
630
+ from: "meter"
631
+ };
632
+ const power = this.deps.registry.find(ENERGY_POWER_KEY, subjectId, "");
633
+ return power === void 0 ? null : {
634
+ series: power,
635
+ from: "power"
636
+ };
637
+ }
638
+ async queryEnergy(input) {
639
+ const source = this.energySource(input.subject);
640
+ if (source === null || input.scope !== void 0 && input.scope !== "") return {
641
+ resolution: "5m",
642
+ series: [],
643
+ truncated: false
644
+ };
645
+ const { chosen, reads } = await this.choose(input, [source.series], true);
646
+ const read = reads[0]?.[1];
647
+ if (read === void 0 || read.tier === "raw") return {
648
+ resolution: chosen,
649
+ series: [],
650
+ truncated: false
651
+ };
652
+ let points;
653
+ if (source.from === "meter") {
654
+ const prev = await this.deps.store.rollupBefore(read.tier, source.series.id, bucketStartOf(read.tier, input.from));
655
+ points = rollupPoints(read.rows, {
656
+ kind: "counter",
657
+ values: null
658
+ }, prev?.last ?? null);
659
+ } else points = integratedEnergyPoints(read.rows);
660
+ return {
661
+ resolution: chosen,
662
+ series: [{
663
+ scope: "",
664
+ before: null,
665
+ points,
666
+ derivedFrom: source.series.key
667
+ }],
668
+ truncated: read.overflow
669
+ };
670
+ }
671
+ async listSeries(subject) {
672
+ const { registry } = this.deps;
673
+ const slices = /* @__PURE__ */ new Map();
674
+ const infos = [];
675
+ for (const s of registry.forSubject(subjectIdOf(subject))) {
676
+ const metric = registry.metric(s.key);
677
+ if (metric === void 0) continue;
678
+ const item = this.itemFields.get(s.key);
679
+ const named = item === void 0 || subject.kind !== "device" ? null : await this.itemNaming(subject.deviceId, item, s.scope, metric.unit, slices);
680
+ infos.push({
681
+ key: s.key,
682
+ scope: s.scope,
683
+ kind: metric.kind,
684
+ unit: named !== null ? named.unit : await this.unitOf(subject, s, metric.unit, slices),
685
+ displayName: named !== null ? `${named.label} · ${metric.displayName}` : metric.displayName,
686
+ source: metric.source,
687
+ values: metric.kind === "enum" ? metric.values ?? [] : null,
688
+ firstTs: s.firstTs,
689
+ lastTs: s.lastTs
690
+ });
691
+ }
692
+ const energy = this.energySource(subject);
693
+ if (energy !== null) infos.push({
694
+ key: DEVICE_HISTORY_ENERGY_KEY,
695
+ scope: "",
696
+ kind: "counter",
697
+ unit: "kWh",
698
+ displayName: "Energy",
699
+ source: "derived",
700
+ values: null,
701
+ firstTs: energy.series.firstTs,
702
+ lastTs: energy.series.lastTs
703
+ });
704
+ return infos.toSorted((a, b) => a.key.localeCompare(b.key) || a.scope.localeCompare(b.scope));
705
+ }
706
+ /**
707
+ * An item series (D917) is named after its item and takes its `unitFrom`
708
+ * from it, both read from the device's CURRENT slice: the item's `label`,
709
+ * else its key (the scope) when the item is gone or the slice unreadable.
710
+ */
711
+ async itemNaming(deviceId, item, scope, fixed, slices) {
712
+ const slice = await this.sliceOf(deviceId, item.capName, slices);
713
+ const list = slice === null ? void 0 : readPath(slice, item.items.path);
714
+ const entry = Array.isArray(list) ? list.find((e) => isObject(e) && e[item.items.key] === scope) : void 0;
715
+ const rawLabel = entry !== void 0 && item.items.label !== void 0 ? entry[item.items.label] : void 0;
716
+ const label = typeof rawLabel === "string" && rawLabel.length > 0 ? rawLabel : scope;
717
+ if (fixed !== null || item.spec.unitFrom === void 0) return {
718
+ label,
719
+ unit: fixed
720
+ };
721
+ return {
722
+ label,
723
+ unit: entry === void 0 ? null : readUnit(entry, item.spec.unitFrom)
724
+ };
725
+ }
726
+ sliceOf(deviceId, capName, slices) {
727
+ const pending = slices.get(capName) ?? this.deps.readCapSlice(deviceId, capName).catch(() => null);
728
+ slices.set(capName, pending);
729
+ return pending;
730
+ }
731
+ /** The metric's fixed unit, else the device's own (a `unitFrom` field), else unknown. */
732
+ async unitOf(subject, series, fixed, slices) {
733
+ if (fixed !== null || subject.kind !== "device" || !series.key.startsWith("cap:")) return fixed;
734
+ if (DEVICE_QUANTITY_KEYS.has(series.key)) {
735
+ const quantity = await this.quantityOf(subject.deviceId);
736
+ if (quantity === null || quantity === "device" || quantity === "none") return null;
737
+ return historyUnitFor(quantity) ?? null;
738
+ }
739
+ const spec = this.specOf(series.key);
740
+ if (spec?.unitFrom === void 0) return null;
741
+ const capName = series.key.slice(CAP_KEY_PREFIX.length, series.key.indexOf("."));
742
+ const slice = await this.sliceOf(subject.deviceId, capName, slices);
743
+ return slice === null ? null : readUnit(slice, spec.unitFrom);
744
+ }
745
+ quantityOf(deviceId) {
746
+ const pending = this.quantities.get(deviceId);
747
+ if (pending !== void 0) return pending;
748
+ const read = this.deps.readDeviceQuantity;
749
+ const run = read === void 0 ? Promise.resolve(null) : read(deviceId).catch(() => null);
750
+ this.quantities.set(deviceId, run);
751
+ return run;
752
+ }
753
+ quantities = /* @__PURE__ */ new Map();
754
+ specOf(key) {
755
+ const body = key.slice(CAP_KEY_PREFIX.length);
756
+ const dot = body.indexOf(".");
757
+ if (dot < 0) return void 0;
758
+ return this.deps.catalog[body.slice(0, dot)]?.[body.slice(dot + 1)];
759
+ }
760
+ };
761
+ function isObject(value) {
762
+ return typeof value === "object" && value !== null && !Array.isArray(value);
763
+ }
764
+ /** Series key → keyed-item field, for every item field of the catalog. */
765
+ function itemFieldsByKey(itemCatalog) {
766
+ return new Map(Object.entries(itemCatalog).flatMap(([capName, items]) => Object.entries(items.fields).map(([field, spec]) => [capItemSeriesKey(capName, items, field), {
767
+ capName,
768
+ items,
769
+ spec
770
+ }])));
771
+ }
772
+ /** Every covering tier but raw; the coarsest stays when it is the only one. */
773
+ function withoutRaw(tiers) {
774
+ const rollups = tiers.filter((t) => t !== "raw");
775
+ return rollups.length > 0 ? rollups : ["5m"];
776
+ }
777
+ //#endregion
778
+ //#region src/builtins/device-history/retention/orphans.ts
779
+ /**
780
+ * The orphan verdict of one series, or `null` when it is linked. PURE. A node
781
+ * series is never orphan here (its subject is a node, not a device).
782
+ */
783
+ function judgeOrphan(series, declaredCapKeys, missingSince) {
784
+ if (series.deviceId === null) return null;
785
+ if (missingSince !== void 0) return {
786
+ reason: "device-gone",
787
+ missingSince
788
+ };
789
+ if (series.key.startsWith("cap:") && !declaredCapKeys.has(series.key)) return {
790
+ reason: "undeclared",
791
+ missingSince: null
792
+ };
793
+ return null;
794
+ }
795
+ var OrphanSeries = class {
796
+ deps;
797
+ constructor(deps) {
798
+ this.deps = deps;
799
+ }
800
+ verdictOf(series) {
801
+ const { departures, declaredCapKeys } = this.deps;
802
+ return judgeOrphan(series, declaredCapKeys, series.deviceId === null ? void 0 : departures.missingSince(series.deviceId));
803
+ }
804
+ /** Every orphan, ordered by device, key and scope, the first {@link DEVICE_HISTORY_ORPHAN_LIST_MAX} counted. */
805
+ async list() {
806
+ const found = this.deps.registry.all().flatMap((series) => {
807
+ const verdict = this.verdictOf(series);
808
+ return verdict === null || series.deviceId === null ? [] : [{
809
+ series,
810
+ deviceId: series.deviceId,
811
+ verdict
812
+ }];
813
+ }).toSorted((a, b) => a.deviceId - b.deviceId || a.series.key.localeCompare(b.series.key) || a.series.scope.localeCompare(b.series.scope));
814
+ const out = [];
815
+ for (const { series, deviceId, verdict } of found.slice(0, 200)) out.push({
816
+ seriesId: series.id,
817
+ deviceId,
818
+ key: series.key,
819
+ scope: series.scope,
820
+ displayName: this.deps.registry.metric(series.key)?.displayName ?? null,
821
+ reason: verdict.reason,
822
+ missingSince: verdict.missingSince,
823
+ firstTs: series.firstTs,
824
+ lastTs: series.lastTs,
825
+ rows: await this.rowsOf(series.id)
826
+ });
827
+ return {
828
+ series: out,
829
+ truncated: found.length > 200
830
+ };
831
+ }
832
+ async rowsOf(seriesId) {
833
+ const { store } = this.deps;
834
+ return {
835
+ raw: await store.countSeriesRows("raw", seriesId),
836
+ "5m": await store.countSeriesRows("5m", seriesId),
837
+ "1h": await store.countSeriesRows("1h", seriesId),
838
+ "1d": await store.countSeriesRows("1d", seriesId)
839
+ };
840
+ }
841
+ /** Delete orphans by id, one at a time, each re-judged now. One entry per id, in order. */
842
+ async delete(seriesIds) {
843
+ const out = [];
844
+ for (const seriesId of seriesIds) out.push(await this.deleteOne(seriesId));
845
+ return out;
846
+ }
847
+ async deleteOne(seriesId) {
848
+ const { registry, retention, logger, clock } = this.deps;
849
+ const series = registry.all().find((s) => s.id === seriesId);
850
+ if (series === void 0) return {
851
+ seriesId,
852
+ ok: false,
853
+ reason: "not-found"
854
+ };
855
+ const verdict = this.verdictOf(series);
856
+ if (verdict === null || series.deviceId === null) {
857
+ logger.info("device-history: refused to delete a series that is not orphan", {
858
+ ...series.deviceId === null ? {} : { tags: { deviceId: series.deviceId } },
859
+ meta: {
860
+ seriesId,
861
+ key: series.key,
862
+ scope: series.scope
863
+ }
864
+ });
865
+ return {
866
+ seriesId,
867
+ ok: false,
868
+ reason: "not-orphan"
869
+ };
870
+ }
871
+ try {
872
+ const deleted = await retention.purgeSeries(series, clock());
873
+ registry.remove(series.id);
874
+ const rows = {
875
+ raw: deleted.raw,
876
+ "5m": deleted["5m"],
877
+ "1h": deleted["1h"],
878
+ "1d": deleted["1d"]
879
+ };
880
+ logger.info("device-history: deleted an orphan series", {
881
+ tags: { deviceId: series.deviceId },
882
+ meta: {
883
+ seriesId,
884
+ key: series.key,
885
+ scope: series.scope,
886
+ reason: verdict.reason,
887
+ rows
888
+ }
889
+ });
890
+ return {
891
+ seriesId,
892
+ ok: true,
893
+ deleted: rows
894
+ };
895
+ } catch (err) {
896
+ logger.warn("device-history: deleting an orphan series failed — it stays listed, retry the delete", {
897
+ tags: { deviceId: series.deviceId },
898
+ meta: {
899
+ seriesId,
900
+ key: series.key,
901
+ error: err instanceof Error ? err.message : String(err)
902
+ }
903
+ });
904
+ return {
905
+ seriesId,
906
+ ok: false,
907
+ reason: "failed"
908
+ };
909
+ }
910
+ }
911
+ };
912
+ //#endregion
913
+ //#region src/builtins/device-history/store/series-scale.ts
914
+ /**
915
+ * One-shot rescales of series whose every stored point shared one factor
916
+ * (D944). A reading already in the base unit is at or above `legacyMax` and
917
+ * is left alone, so a second pass does not multiply it again.
918
+ *
919
+ * Rollup `sum` / `tw_sum` follow the bucket when min, max and last are still
920
+ * in the old unit. Judging the sum itself would skip a day's samples of a
921
+ * large gauge (many × GiB already exceeds the ceiling) and keep the raw
922
+ * points and the rollup in different units.
923
+ */
924
+ var GIB_TO_BYTES = 1024 ** 3;
925
+ var DAY_TO_SECONDS = 86400;
926
+ /** A homelab array in GiB is below 1 MiB; the same array in bytes is not. */
927
+ var INFORMATION_LEGACY_MAX = 1024 ** 2;
928
+ /** Desiccant life in days is below this; the same life in seconds is not. */
929
+ var DESICCANT_LEGACY_MAX_DAYS = 1e4;
930
+ var DESICCANT_SERIES_KEY = "cap:pet-feeder.desiccantLeftDays";
931
+ var DESICCANT_SCALE_ID = "pet-feeder-desiccant-days-to-seconds";
932
+ var UNRAID_INFORMATION_KEYS = [
933
+ "array_total",
934
+ "array_used",
935
+ "array_free"
936
+ ];
937
+ var NUMERIC_SENSOR_SERIES_KEY = "cap:numeric-sensor.value";
938
+ /** The stored number after one rescale, or the same number when it is already base. */
939
+ function scaledMagnitude(value, factor, legacyMax) {
940
+ if (!Number.isFinite(value) || value === 0) return value;
941
+ if (Math.abs(value) >= legacyMax) return value;
942
+ return value * factor;
943
+ }
944
+ function rollupIsLegacy(row, legacyMax) {
945
+ const samples = [
946
+ row.min,
947
+ row.max,
948
+ ...row.last === null ? [] : [row.last]
949
+ ];
950
+ if (samples.some((value) => !Number.isFinite(value))) return false;
951
+ if (samples.every((value) => value === 0)) return false;
952
+ return samples.every((value) => Math.abs(value) < legacyMax);
953
+ }
954
+ /** Unraid array capacity children. Other numeric sensors on the same key stay put. */
955
+ function unraidInformationScale(deviceId, entityKey) {
956
+ if (!UNRAID_INFORMATION_KEYS.includes(entityKey)) return null;
957
+ return {
958
+ seriesKey: NUMERIC_SENSOR_SERIES_KEY,
959
+ deviceId,
960
+ factor: GIB_TO_BYTES,
961
+ legacyMax: INFORMATION_LEGACY_MAX,
962
+ migrationId: `unraid-gib-to-bytes:${String(deviceId)}`
963
+ };
964
+ }
965
+ //#endregion
966
+ //#region src/builtins/device-history/store/history-schema.ts
967
+ var HISTORY_NAMESPACE = "device-history";
968
+ var COLLECTIONS = {
969
+ metrics: "metrics",
970
+ series: "series",
971
+ raw: "raw",
972
+ rollup5m: "rollup-5m",
973
+ rollup1h: "rollup-1h",
974
+ rollup1d: "rollup-1d",
975
+ optOuts: "device-opt-outs",
976
+ departures: "device-departures",
977
+ /** One row per applied base-unit rescale, in history.db so it travels with the points. */
978
+ appliedScales: "applied-scales"
979
+ };
980
+ function rollupCollectionOf(tier) {
981
+ if (tier === "5m") return COLLECTIONS.rollup5m;
982
+ if (tier === "1h") return COLLECTIONS.rollup1h;
983
+ return COLLECTIONS.rollup1d;
984
+ }
985
+ function rollupDeclaration(collection) {
986
+ return {
987
+ namespace: HISTORY_NAMESPACE,
988
+ collection,
989
+ database: "history",
990
+ primaryKey: ["series_id", "bucket_start"],
991
+ withoutRowid: true,
992
+ columns: [
993
+ {
994
+ name: "series_id",
995
+ type: "INTEGER"
996
+ },
997
+ {
998
+ name: "bucket_start",
999
+ type: "INTEGER"
1000
+ },
1001
+ {
1002
+ name: "samples",
1003
+ type: "INTEGER",
1004
+ notNull: true
1005
+ },
1006
+ {
1007
+ name: "sum",
1008
+ type: "REAL",
1009
+ notNull: true
1010
+ },
1011
+ {
1012
+ name: "min",
1013
+ type: "REAL",
1014
+ notNull: true
1015
+ },
1016
+ {
1017
+ name: "max",
1018
+ type: "REAL",
1019
+ notNull: true
1020
+ },
1021
+ {
1022
+ name: "last",
1023
+ type: "REAL"
1024
+ },
1025
+ {
1026
+ name: "last_ts",
1027
+ type: "INTEGER"
1028
+ },
1029
+ {
1030
+ name: "tw_sum",
1031
+ type: "REAL"
1032
+ },
1033
+ {
1034
+ name: "tw_ms",
1035
+ type: "INTEGER"
1036
+ },
1037
+ {
1038
+ name: "state_ms",
1039
+ type: "TEXT"
1040
+ }
1041
+ ]
1042
+ };
1043
+ }
1044
+ var HISTORY_DECLARATIONS = [
1045
+ {
1046
+ namespace: HISTORY_NAMESPACE,
1047
+ collection: COLLECTIONS.metrics,
1048
+ database: "history",
1049
+ columns: [
1050
+ {
1051
+ name: "key",
1052
+ type: "TEXT",
1053
+ primaryKey: true,
1054
+ notNull: true
1055
+ },
1056
+ {
1057
+ name: "source",
1058
+ type: "TEXT",
1059
+ notNull: true
1060
+ },
1061
+ {
1062
+ name: "owner_addon",
1063
+ type: "TEXT",
1064
+ notNull: true
1065
+ },
1066
+ {
1067
+ name: "subject_kind",
1068
+ type: "TEXT",
1069
+ notNull: true
1070
+ },
1071
+ {
1072
+ name: "kind",
1073
+ type: "TEXT",
1074
+ notNull: true
1075
+ },
1076
+ {
1077
+ name: "unit",
1078
+ type: "TEXT"
1079
+ },
1080
+ {
1081
+ name: "display_name",
1082
+ type: "TEXT",
1083
+ notNull: true
1084
+ },
1085
+ {
1086
+ name: "ingest",
1087
+ type: "TEXT",
1088
+ notNull: true
1089
+ },
1090
+ {
1091
+ name: "declared_at",
1092
+ type: "INTEGER",
1093
+ notNull: true
1094
+ },
1095
+ {
1096
+ name: "enum_values",
1097
+ type: "TEXT"
1098
+ }
1099
+ ]
1100
+ },
1101
+ {
1102
+ namespace: HISTORY_NAMESPACE,
1103
+ collection: COLLECTIONS.series,
1104
+ database: "history",
1105
+ columns: [
1106
+ {
1107
+ name: "id",
1108
+ type: "INTEGER",
1109
+ primaryKey: true
1110
+ },
1111
+ {
1112
+ name: "key",
1113
+ type: "TEXT",
1114
+ notNull: true
1115
+ },
1116
+ {
1117
+ name: "subject",
1118
+ type: "TEXT",
1119
+ notNull: true
1120
+ },
1121
+ {
1122
+ name: "device_id",
1123
+ type: "INTEGER"
1124
+ },
1125
+ {
1126
+ name: "scope",
1127
+ type: "TEXT",
1128
+ notNull: true,
1129
+ defaultValue: ""
1130
+ },
1131
+ {
1132
+ name: "first_ts",
1133
+ type: "INTEGER",
1134
+ notNull: true
1135
+ },
1136
+ {
1137
+ name: "last_ts",
1138
+ type: "INTEGER",
1139
+ notNull: true
1140
+ }
1141
+ ],
1142
+ indexes: [{
1143
+ name: "idx_dh_series_identity",
1144
+ columns: [
1145
+ "key",
1146
+ "subject",
1147
+ "scope"
1148
+ ],
1149
+ unique: true
1150
+ }, {
1151
+ name: "idx_dh_series_device",
1152
+ columns: ["device_id"]
1153
+ }]
1154
+ },
1155
+ {
1156
+ namespace: HISTORY_NAMESPACE,
1157
+ collection: COLLECTIONS.raw,
1158
+ database: "history",
1159
+ primaryKey: ["series_id", "ts"],
1160
+ withoutRowid: true,
1161
+ columns: [
1162
+ {
1163
+ name: "series_id",
1164
+ type: "INTEGER"
1165
+ },
1166
+ {
1167
+ name: "ts",
1168
+ type: "INTEGER"
1169
+ },
1170
+ {
1171
+ name: "value",
1172
+ type: "REAL",
1173
+ notNull: true
1174
+ }
1175
+ ]
1176
+ },
1177
+ rollupDeclaration(COLLECTIONS.rollup5m),
1178
+ rollupDeclaration(COLLECTIONS.rollup1h),
1179
+ rollupDeclaration(COLLECTIONS.rollup1d),
1180
+ {
1181
+ namespace: HISTORY_NAMESPACE,
1182
+ collection: COLLECTIONS.optOuts,
1183
+ columns: [
1184
+ {
1185
+ name: "id",
1186
+ type: "INTEGER",
1187
+ primaryKey: true
1188
+ },
1189
+ {
1190
+ name: "device_id",
1191
+ type: "INTEGER",
1192
+ notNull: true
1193
+ },
1194
+ {
1195
+ name: "opted_out_at",
1196
+ type: "INTEGER",
1197
+ notNull: true
1198
+ }
1199
+ ],
1200
+ indexes: [{
1201
+ name: "idx_dh_opt_outs_device",
1202
+ columns: ["device_id"],
1203
+ unique: true
1204
+ }]
1205
+ },
1206
+ {
1207
+ namespace: HISTORY_NAMESPACE,
1208
+ collection: COLLECTIONS.departures,
1209
+ columns: [
1210
+ {
1211
+ name: "id",
1212
+ type: "INTEGER",
1213
+ primaryKey: true
1214
+ },
1215
+ {
1216
+ name: "device_id",
1217
+ type: "INTEGER",
1218
+ notNull: true
1219
+ },
1220
+ {
1221
+ name: "missing_since",
1222
+ type: "INTEGER",
1223
+ notNull: true
1224
+ }
1225
+ ],
1226
+ indexes: [{
1227
+ name: "idx_dh_departures_device",
1228
+ columns: ["device_id"],
1229
+ unique: true
1230
+ }]
1231
+ },
1232
+ {
1233
+ namespace: HISTORY_NAMESPACE,
1234
+ collection: COLLECTIONS.appliedScales,
1235
+ database: "history",
1236
+ columns: [{
1237
+ name: "id",
1238
+ type: "TEXT",
1239
+ primaryKey: true,
1240
+ notNull: true
1241
+ }, {
1242
+ name: "applied_at",
1243
+ type: "INTEGER",
1244
+ notNull: true
1245
+ }]
1246
+ }
1247
+ ];
1248
+ //#endregion
1249
+ //#region src/builtins/device-history/store/row-readers.ts
1250
+ function readNumber(data, column) {
1251
+ const v = data[column];
1252
+ if (typeof v === "number" && Number.isFinite(v)) return v;
1253
+ throw new Error(`history row: column "${column}" is not a number (${typeof v})`);
1254
+ }
1255
+ function readNumberOrNull(data, column) {
1256
+ const v = data[column];
1257
+ if (v === null || v === void 0) return null;
1258
+ if (typeof v === "number" && Number.isFinite(v)) return v;
1259
+ throw new Error(`history row: column "${column}" is not a number or null (${typeof v})`);
1260
+ }
1261
+ function readText(data, column) {
1262
+ const v = data[column];
1263
+ if (typeof v === "string") return v;
1264
+ throw new Error(`history row: column "${column}" is not a string (${typeof v})`);
1265
+ }
1266
+ function readTextOrNull(data, column) {
1267
+ const v = data[column];
1268
+ if (v === null || v === void 0) return null;
1269
+ if (typeof v === "string") return v;
1270
+ throw new Error(`history row: column "${column}" is not a string or null (${typeof v})`);
1271
+ }
1272
+ //#endregion
1273
+ //#region src/builtins/device-history/store/history-store.ts
1274
+ /** Rows per `upsertMany` call: bounds one transaction on the history thread. */
1275
+ var WRITE_CHUNK = 1e3;
1276
+ /** Operations per `transact`. */
1277
+ var TRANSACT_CHUNK = 200;
1278
+ /** Rows per read page. */
1279
+ var READ_PAGE = 5e3;
1280
+ function chunks(items, size) {
1281
+ const out = [];
1282
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
1283
+ return out;
1284
+ }
1285
+ function parseKind(value) {
1286
+ if (value === "gauge" || value === "counter" || value === "boolean" || value === "enum") return value;
1287
+ throw new Error(`history row: unknown kind "${value}"`);
1288
+ }
1289
+ /** A JSON TEXT column: the engine hands back the decoded value, or the text itself. */
1290
+ function jsonColumn(data, column) {
1291
+ const raw = data[column];
1292
+ if (raw === null || raw === void 0) return null;
1293
+ return typeof raw === "string" ? JSON.parse(raw) : raw;
1294
+ }
1295
+ /** A JSON column that must hold a string array, or nothing. */
1296
+ function parseValues(data) {
1297
+ const parsed = jsonColumn(data, "enum_values");
1298
+ if (parsed === null) return null;
1299
+ if (Array.isArray(parsed) && parsed.every((v) => typeof v === "string")) return parsed;
1300
+ throw new Error("history row: column \"enum_values\" is not a JSON string array");
1301
+ }
1302
+ /** A JSON column that must hold `{ "<ordinal>": ms }`, or nothing. */
1303
+ function parseStates(data) {
1304
+ const parsed = jsonColumn(data, "state_ms");
1305
+ if (parsed === null) return null;
1306
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("history row: column \"state_ms\" is not a JSON object");
1307
+ const out = {};
1308
+ for (const [k, v] of Object.entries(parsed)) {
1309
+ if (typeof v !== "number" || !Number.isFinite(v)) throw new Error("history row: column \"state_ms\" holds a non-number");
1310
+ out[k] = v;
1311
+ }
1312
+ return out;
1313
+ }
1314
+ function parseMetric(data) {
1315
+ const source = readText(data, "source");
1316
+ const subjectKind = readText(data, "subject_kind");
1317
+ const ingest = readText(data, "ingest");
1318
+ if (source !== "cap" && source !== "addon") throw new Error(`history row: unknown source "${source}"`);
1319
+ if (subjectKind !== "device" && subjectKind !== "node") throw new Error(`history row: unknown subject_kind "${subjectKind}"`);
1320
+ if (ingest !== "points" && ingest !== "buckets") throw new Error(`history row: unknown ingest "${ingest}"`);
1321
+ return {
1322
+ key: readText(data, "key"),
1323
+ source,
1324
+ ownerAddon: readText(data, "owner_addon"),
1325
+ subjectKind,
1326
+ kind: parseKind(readText(data, "kind")),
1327
+ unit: readTextOrNull(data, "unit"),
1328
+ displayName: readText(data, "display_name"),
1329
+ ingest,
1330
+ declaredAt: readNumber(data, "declared_at"),
1331
+ values: parseValues(data)
1332
+ };
1333
+ }
1334
+ function parseSeries(data) {
1335
+ return {
1336
+ id: readNumber(data, "id"),
1337
+ key: readText(data, "key"),
1338
+ subject: readText(data, "subject"),
1339
+ deviceId: readNumberOrNull(data, "device_id"),
1340
+ scope: readText(data, "scope"),
1341
+ firstTs: readNumber(data, "first_ts"),
1342
+ lastTs: readNumber(data, "last_ts")
1343
+ };
1344
+ }
1345
+ function parseRollup(data) {
1346
+ return {
1347
+ seriesId: readNumber(data, "series_id"),
1348
+ bucketStart: readNumber(data, "bucket_start"),
1349
+ samples: readNumber(data, "samples"),
1350
+ sum: readNumber(data, "sum"),
1351
+ min: readNumber(data, "min"),
1352
+ max: readNumber(data, "max"),
1353
+ last: readNumberOrNull(data, "last"),
1354
+ lastTs: readNumberOrNull(data, "last_ts"),
1355
+ twSum: readNumberOrNull(data, "tw_sum"),
1356
+ twMs: readNumberOrNull(data, "tw_ms"),
1357
+ states: parseStates(data)
1358
+ };
1359
+ }
1360
+ function rollupData(row) {
1361
+ return {
1362
+ series_id: row.seriesId,
1363
+ bucket_start: row.bucketStart,
1364
+ samples: row.samples,
1365
+ sum: row.sum,
1366
+ min: row.min,
1367
+ max: row.max,
1368
+ last: row.last,
1369
+ last_ts: row.lastTs,
1370
+ tw_sum: row.twSum,
1371
+ tw_ms: row.twMs,
1372
+ state_ms: row.states === null ? null : JSON.stringify(row.states)
1373
+ };
1374
+ }
1375
+ function collectionOf(tier) {
1376
+ return tier === "raw" ? COLLECTIONS.raw : rollupCollectionOf(tier);
1377
+ }
1378
+ function orderColumnOf(tier) {
1379
+ return tier === "raw" ? "ts" : "bucket_start";
1380
+ }
1381
+ var HistoryStore = class {
1382
+ door;
1383
+ constructor(door) {
1384
+ this.door = door;
1385
+ }
1386
+ async declare() {
1387
+ for (const declaration of HISTORY_DECLARATIONS) await this.door.declareCollection.mutate(declaration);
1388
+ }
1389
+ async loadMetrics() {
1390
+ return (await this.door.query.query({
1391
+ namespace: HISTORY_NAMESPACE,
1392
+ collection: COLLECTIONS.metrics,
1393
+ filter: { limit: 2e4 }
1394
+ })).map((r) => parseMetric(r.data));
1395
+ }
1396
+ /**
1397
+ * Delete metric rows no lookup can reach: rows an earlier build wrote under an
1398
+ * engine-minted random key (every metric key is `cap:` / `addon:` prefixed).
1399
+ */
1400
+ async deleteMetrics(keys) {
1401
+ for (const batch of chunks(keys, WRITE_CHUNK)) await this.door.deleteWhere.mutate({
1402
+ namespace: HISTORY_NAMESPACE,
1403
+ collection: COLLECTIONS.metrics,
1404
+ filter: { whereIn: { key: [...batch] } }
1405
+ });
1406
+ }
1407
+ async upsertMetric(metric) {
1408
+ await this.door.upsertMany.mutate({
1409
+ namespace: HISTORY_NAMESPACE,
1410
+ collection: COLLECTIONS.metrics,
1411
+ conflict: ["key"],
1412
+ records: [{
1413
+ id: metric.key,
1414
+ data: {
1415
+ key: metric.key,
1416
+ source: metric.source,
1417
+ owner_addon: metric.ownerAddon,
1418
+ subject_kind: metric.subjectKind,
1419
+ kind: metric.kind,
1420
+ unit: metric.unit,
1421
+ display_name: metric.displayName,
1422
+ ingest: metric.ingest,
1423
+ declared_at: metric.declaredAt,
1424
+ enum_values: metric.values === null ? null : JSON.stringify(metric.values)
1425
+ }
1426
+ }]
1427
+ });
1428
+ }
1429
+ /** Series with `id > afterId`, ascending — the boot load pages with this. */
1430
+ async loadSeriesPage(afterId, limit) {
1431
+ return (await this.door.query.query({
1432
+ namespace: HISTORY_NAMESPACE,
1433
+ collection: COLLECTIONS.series,
1434
+ filter: {
1435
+ whereBetween: { id: [afterId + 1, Number.MAX_SAFE_INTEGER] },
1436
+ orderBy: {
1437
+ field: "id",
1438
+ direction: "asc"
1439
+ },
1440
+ limit
1441
+ }
1442
+ })).map((r) => parseSeries(r.data));
1443
+ }
1444
+ async findSeries(key, subject, scope) {
1445
+ const first = (await this.door.query.query({
1446
+ namespace: HISTORY_NAMESPACE,
1447
+ collection: COLLECTIONS.series,
1448
+ filter: {
1449
+ where: {
1450
+ key,
1451
+ subject,
1452
+ scope
1453
+ },
1454
+ limit: 1
1455
+ }
1456
+ }))[0];
1457
+ return first === void 0 ? null : parseSeries(first.data);
1458
+ }
1459
+ async insertSeries(series) {
1460
+ const { id } = await this.door.insert.mutate({
1461
+ namespace: HISTORY_NAMESPACE,
1462
+ collection: COLLECTIONS.series,
1463
+ record: { data: {
1464
+ key: series.key,
1465
+ subject: series.subject,
1466
+ device_id: series.deviceId,
1467
+ scope: series.scope,
1468
+ first_ts: series.ts,
1469
+ last_ts: series.ts
1470
+ } }
1471
+ });
1472
+ return {
1473
+ id: typeof id === "number" ? id : Number(id),
1474
+ key: series.key,
1475
+ subject: series.subject,
1476
+ deviceId: series.deviceId,
1477
+ scope: series.scope,
1478
+ firstTs: series.ts,
1479
+ lastTs: series.ts
1480
+ };
1481
+ }
1482
+ async touchSeries(updates) {
1483
+ for (const batch of chunks(updates, TRANSACT_CHUNK)) await this.door.transact.mutate({
1484
+ namespace: HISTORY_NAMESPACE,
1485
+ ops: batch.map((u) => ({
1486
+ op: "update",
1487
+ collection: COLLECTIONS.series,
1488
+ id: String(u.id),
1489
+ data: { last_ts: u.lastTs }
1490
+ }))
1491
+ });
1492
+ }
1493
+ async widenSeriesStart(id, firstTs) {
1494
+ await this.door.update.mutate({
1495
+ namespace: HISTORY_NAMESPACE,
1496
+ collection: COLLECTIONS.series,
1497
+ id: String(id),
1498
+ data: { first_ts: firstTs }
1499
+ });
1500
+ }
1501
+ async upsertRaw(rows) {
1502
+ for (const batch of chunks(rows, WRITE_CHUNK)) await this.door.upsertMany.mutate({
1503
+ namespace: HISTORY_NAMESPACE,
1504
+ collection: COLLECTIONS.raw,
1505
+ conflict: ["series_id", "ts"],
1506
+ records: batch.map((r) => ({ data: {
1507
+ series_id: r.seriesId,
1508
+ ts: r.ts,
1509
+ value: r.value
1510
+ } }))
1511
+ });
1512
+ }
1513
+ /** Points of a series in `[from, toInclusive]`, ascending, at most `limit`. */
1514
+ async readRaw(seriesId, from, toInclusive, limit, direction = "asc") {
1515
+ return (await this.door.query.query({
1516
+ namespace: HISTORY_NAMESPACE,
1517
+ collection: COLLECTIONS.raw,
1518
+ filter: {
1519
+ where: { series_id: seriesId },
1520
+ whereBetween: { ts: [from, toInclusive] },
1521
+ orderBy: {
1522
+ field: "ts",
1523
+ direction
1524
+ },
1525
+ limit
1526
+ }
1527
+ })).map((r) => ({
1528
+ ts: readNumber(r.data, "ts"),
1529
+ value: readNumber(r.data, "value")
1530
+ }));
1531
+ }
1532
+ /** The newest raw point strictly before `ts`, if any. */
1533
+ async rawBefore(seriesId, ts) {
1534
+ return (await this.readRaw(seriesId, 0, ts - 1, 1, "desc"))[0] ?? null;
1535
+ }
1536
+ async upsertRollups(tier, rows) {
1537
+ for (const batch of chunks(rows, WRITE_CHUNK)) await this.door.upsertMany.mutate({
1538
+ namespace: HISTORY_NAMESPACE,
1539
+ collection: rollupCollectionOf(tier),
1540
+ conflict: ["series_id", "bucket_start"],
1541
+ records: batch.map((r) => ({ data: rollupData(r) }))
1542
+ });
1543
+ }
1544
+ async readRollups(tier, seriesId, from, toInclusive, limit, direction = "asc") {
1545
+ return (await this.door.query.query({
1546
+ namespace: HISTORY_NAMESPACE,
1547
+ collection: rollupCollectionOf(tier),
1548
+ filter: {
1549
+ where: { series_id: seriesId },
1550
+ whereBetween: { bucket_start: [from, toInclusive] },
1551
+ orderBy: {
1552
+ field: "bucket_start",
1553
+ direction
1554
+ },
1555
+ limit
1556
+ }
1557
+ })).map((r) => parseRollup(r.data));
1558
+ }
1559
+ /** The newest rollup row of `tier` strictly before `bucketStart`, if any. */
1560
+ async rollupBefore(tier, seriesId, bucketStart) {
1561
+ return (await this.readRollups(tier, seriesId, 0, bucketStart - 1, 1, "desc"))[0] ?? null;
1562
+ }
1563
+ /** Delete one series' rows of a tier with the order column in `[lo, hiInclusive]`. */
1564
+ async deleteRange(tier, seriesId, lo, hiInclusive) {
1565
+ const { deleted } = await this.door.deleteWhere.mutate({
1566
+ namespace: HISTORY_NAMESPACE,
1567
+ collection: collectionOf(tier),
1568
+ filter: {
1569
+ where: { series_id: seriesId },
1570
+ whereBetween: { [orderColumnOf(tier)]: [lo, hiInclusive] }
1571
+ }
1572
+ });
1573
+ return deleted;
1574
+ }
1575
+ /** Delete every row of one series, in every tier, then the series row. */
1576
+ async deleteSeries(seriesId) {
1577
+ for (const tier of [
1578
+ "raw",
1579
+ "5m",
1580
+ "1h",
1581
+ "1d"
1582
+ ]) await this.door.deleteWhere.mutate({
1583
+ namespace: HISTORY_NAMESPACE,
1584
+ collection: collectionOf(tier),
1585
+ filter: { where: { series_id: seriesId } }
1586
+ });
1587
+ await this.door.delete.mutate({
1588
+ namespace: HISTORY_NAMESPACE,
1589
+ collection: COLLECTIONS.series,
1590
+ key: String(seriesId)
1591
+ });
1592
+ }
1593
+ /**
1594
+ * One series' rows of a tier: a range of the primary key (`series_id = ?`),
1595
+ * never a scan of the tier (D447, asserted in `history-query-plans.spec.ts`).
1596
+ */
1597
+ async countSeriesRows(tier, seriesId) {
1598
+ return this.door.count.query({
1599
+ namespace: HISTORY_NAMESPACE,
1600
+ collection: collectionOf(tier),
1601
+ filter: { where: { series_id: seriesId } }
1602
+ });
1603
+ }
1604
+ async countRows(tier) {
1605
+ return this.door.count.query({
1606
+ namespace: HISTORY_NAMESPACE,
1607
+ collection: collectionOf(tier)
1608
+ });
1609
+ }
1610
+ async loadOptOuts() {
1611
+ const rows = await this.door.query.query({
1612
+ namespace: HISTORY_NAMESPACE,
1613
+ collection: COLLECTIONS.optOuts,
1614
+ filter: { limit: 2e4 }
1615
+ });
1616
+ return new Set(rows.map((r) => readNumber(r.data, "device_id")));
1617
+ }
1618
+ async setOptOut(deviceId, at) {
1619
+ await this.door.upsertMany.mutate({
1620
+ namespace: HISTORY_NAMESPACE,
1621
+ collection: COLLECTIONS.optOuts,
1622
+ conflict: ["device_id"],
1623
+ records: [{ data: {
1624
+ device_id: deviceId,
1625
+ opted_out_at: at
1626
+ } }]
1627
+ });
1628
+ }
1629
+ async loadDepartures() {
1630
+ const rows = await this.door.query.query({
1631
+ namespace: HISTORY_NAMESPACE,
1632
+ collection: COLLECTIONS.departures,
1633
+ filter: { limit: 2e4 }
1634
+ });
1635
+ return new Map(rows.map((r) => [readNumber(r.data, "device_id"), readNumber(r.data, "missing_since")]));
1636
+ }
1637
+ async markMissing(deviceIds, at) {
1638
+ for (const batch of chunks(deviceIds, WRITE_CHUNK)) await this.door.upsertMany.mutate({
1639
+ namespace: HISTORY_NAMESPACE,
1640
+ collection: COLLECTIONS.departures,
1641
+ conflict: ["device_id"],
1642
+ records: batch.map((id) => ({ data: {
1643
+ device_id: id,
1644
+ missing_since: at
1645
+ } }))
1646
+ });
1647
+ }
1648
+ async clearMissing(deviceIds) {
1649
+ for (const batch of chunks(deviceIds, WRITE_CHUNK)) await this.door.deleteWhere.mutate({
1650
+ namespace: HISTORY_NAMESPACE,
1651
+ collection: COLLECTIONS.departures,
1652
+ filter: { whereIn: { device_id: [...batch] } }
1653
+ });
1654
+ }
1655
+ async clearOptOut(deviceId) {
1656
+ await this.door.deleteWhere.mutate({
1657
+ namespace: HISTORY_NAMESPACE,
1658
+ collection: COLLECTIONS.optOuts,
1659
+ filter: { where: { device_id: deviceId } }
1660
+ });
1661
+ }
1662
+ /** True when this rescale already finished. A missing row is "not yet". */
1663
+ async scaleApplied(id) {
1664
+ return (await this.door.query.query({
1665
+ namespace: HISTORY_NAMESPACE,
1666
+ collection: COLLECTIONS.appliedScales,
1667
+ filter: {
1668
+ where: { id },
1669
+ limit: 1
1670
+ }
1671
+ })).length > 0;
1672
+ }
1673
+ async markScale(id, at) {
1674
+ await this.door.upsertMany.mutate({
1675
+ namespace: HISTORY_NAMESPACE,
1676
+ collection: COLLECTIONS.appliedScales,
1677
+ conflict: ["id"],
1678
+ records: [{
1679
+ id,
1680
+ data: {
1681
+ id,
1682
+ applied_at: at
1683
+ }
1684
+ }]
1685
+ });
1686
+ }
1687
+ /**
1688
+ * Multiply one series' raw points and rollups that are still in the old
1689
+ * unit. Points already at or above `legacyMax` stay. Returns how many rows
1690
+ * changed.
1691
+ */
1692
+ async scaleSeries(seriesId, factor, legacyMax) {
1693
+ const raw = await this.scaleRaw(seriesId, factor, legacyMax);
1694
+ let rollups = 0;
1695
+ for (const tier of [
1696
+ "5m",
1697
+ "1h",
1698
+ "1d"
1699
+ ]) rollups += await this.scaleRollupTier(tier, seriesId, factor, legacyMax);
1700
+ return raw + rollups;
1701
+ }
1702
+ async scaleRaw(seriesId, factor, legacyMax) {
1703
+ let after = -1;
1704
+ let changed = 0;
1705
+ for (;;) {
1706
+ const rows = await this.readRaw(seriesId, after + 1, Number.MAX_SAFE_INTEGER, READ_PAGE, "asc");
1707
+ if (rows.length === 0) break;
1708
+ const next = rows.flatMap((row) => {
1709
+ const value = scaledMagnitude(row.value, factor, legacyMax);
1710
+ return value === row.value ? [] : [{
1711
+ seriesId,
1712
+ ts: row.ts,
1713
+ value
1714
+ }];
1715
+ });
1716
+ if (next.length > 0) {
1717
+ await this.upsertRaw(next);
1718
+ changed += next.length;
1719
+ }
1720
+ const last = rows[rows.length - 1];
1721
+ if (last === void 0 || rows.length < 5e3) break;
1722
+ after = last.ts;
1723
+ }
1724
+ return changed;
1725
+ }
1726
+ async scaleRollupTier(tier, seriesId, factor, legacyMax) {
1727
+ let after = -1;
1728
+ let changed = 0;
1729
+ for (;;) {
1730
+ const rows = await this.readRollups(tier, seriesId, after + 1, Number.MAX_SAFE_INTEGER, READ_PAGE, "asc");
1731
+ if (rows.length === 0) break;
1732
+ const next = rows.flatMap((row) => rollupIsLegacy(row, legacyMax) ? [scaleRollup(row, factor)] : []);
1733
+ if (next.length > 0) {
1734
+ await this.upsertRollups(tier, next);
1735
+ changed += next.length;
1736
+ }
1737
+ const last = rows[rows.length - 1];
1738
+ if (last === void 0 || rows.length < 5e3) break;
1739
+ after = last.bucketStart;
1740
+ }
1741
+ return changed;
1742
+ }
1743
+ };
1744
+ function scaleRollup(row, factor) {
1745
+ return {
1746
+ ...row,
1747
+ sum: row.sum * factor,
1748
+ min: row.min * factor,
1749
+ max: row.max * factor,
1750
+ last: row.last === null ? null : row.last * factor,
1751
+ twSum: row.twSum === null ? null : row.twSum * factor
1752
+ };
1753
+ }
1754
+ //#endregion
1755
+ //#region src/builtins/device-history/rollup/rollup-math.ts
1756
+ /**
1757
+ * Rollup arithmetic (D850, plan §4/§5.5). PURE: rows in, rows out.
1758
+ *
1759
+ * Two operations, both a RECOMPUTE from the lower tier — never an increment —
1760
+ * so running one twice, or after a late write, gives the same answer:
1761
+ *
1762
+ * - {@link rawToFiveMinuteRows}: change-only raw points into 5-minute rows,
1763
+ * with the time-weighted sum `tw_sum` (Σ value·ms) a change-only gauge
1764
+ * needs: 4m59s at 50 and 1s at 100 is a time-weighted mean of ~50, not 75.
1765
+ * - {@link combineRows}: rows of the child tier into one row of the next.
1766
+ *
1767
+ * Held values. A change-only series writes a point only when the value
1768
+ * changes, so a quiet bucket has NO row and the value in force across it is
1769
+ * the last one before. Both operations take that value in (`carryIn`) and
1770
+ * credit the gap with it; without that, an hour that sat at 10 for 55 minutes
1771
+ * and jumped to 100 in the last five would be averaged over those five alone.
1772
+ * The held value also counts toward `min`/`max` when it was in force at the
1773
+ * start of a bucket, because it really was the series' value then.
1774
+ */
1775
+ function credit(states, value, ms) {
1776
+ if (states === null || ms <= 0) return;
1777
+ const key = String(value);
1778
+ states[key] = (states[key] ?? 0) + ms;
1779
+ }
1780
+ /** One row per 5-minute bucket that has at least one point. */
1781
+ function rawToFiveMinuteRows(input) {
1782
+ const rows = [];
1783
+ const { points, seriesId, horizon } = input;
1784
+ let held = input.carryIn === null ? null : input.carryIn.value;
1785
+ let i = 0;
1786
+ while (i < points.length) {
1787
+ const first = points[i];
1788
+ if (first === void 0) break;
1789
+ const bucketStart = floorTo(first.ts, FIVE_MINUTES_MS);
1790
+ const bucketEnd = bucketStart + FIVE_MINUTES_MS;
1791
+ const coverageEnd = Math.min(bucketEnd, Math.max(horizon, bucketStart));
1792
+ let samples = 0;
1793
+ let sum = 0;
1794
+ let min = Number.POSITIVE_INFINITY;
1795
+ let max = Number.NEGATIVE_INFINITY;
1796
+ let twSum = 0;
1797
+ let twMs = 0;
1798
+ const states = input.trackStates === true ? {} : null;
1799
+ let cursor = bucketStart;
1800
+ let value = held;
1801
+ if (value !== null) {
1802
+ min = value;
1803
+ max = value;
1804
+ }
1805
+ let last = first;
1806
+ while (i < points.length) {
1807
+ const p = points[i];
1808
+ if (p === void 0 || p.ts >= bucketEnd) break;
1809
+ if (value !== null) {
1810
+ const dt = p.ts - cursor;
1811
+ twSum += value * dt;
1812
+ twMs += dt;
1813
+ credit(states, value, dt);
1814
+ }
1815
+ cursor = p.ts;
1816
+ value = p.value;
1817
+ samples += 1;
1818
+ sum += p.value;
1819
+ if (p.value < min) min = p.value;
1820
+ if (p.value > max) max = p.value;
1821
+ last = p;
1822
+ i += 1;
1823
+ }
1824
+ if (value !== null && coverageEnd > cursor) {
1825
+ twSum += value * (coverageEnd - cursor);
1826
+ twMs += coverageEnd - cursor;
1827
+ credit(states, value, coverageEnd - cursor);
1828
+ }
1829
+ held = last.value;
1830
+ rows.push({
1831
+ seriesId,
1832
+ bucketStart,
1833
+ samples,
1834
+ sum,
1835
+ min,
1836
+ max,
1837
+ last: last.value,
1838
+ lastTs: last.ts,
1839
+ twSum,
1840
+ twMs,
1841
+ states
1842
+ });
1843
+ }
1844
+ return rows;
1845
+ }
1846
+ /** One row of the next tier from the child rows of its window; `null` when there are none. */
1847
+ function combineRows(input) {
1848
+ const { rows } = input;
1849
+ const lastRow = rows[rows.length - 1];
1850
+ if (lastRow === void 0) return null;
1851
+ const hasTw = rows.some((r) => r.twSum !== null && r.twMs !== null);
1852
+ let samples = 0;
1853
+ let sum = 0;
1854
+ let min = Number.POSITIVE_INFINITY;
1855
+ let max = Number.NEGATIVE_INFINITY;
1856
+ let twSum = 0;
1857
+ let twMs = 0;
1858
+ const states = input.trackStates === true ? {} : null;
1859
+ let held = input.carryIn;
1860
+ let cursor = input.windowStart;
1861
+ for (const row of rows) {
1862
+ samples += row.samples;
1863
+ sum += row.sum;
1864
+ if (row.min < min) min = row.min;
1865
+ if (row.max > max) max = row.max;
1866
+ const gap = row.bucketStart - cursor;
1867
+ if (hasTw && gap > 0 && held !== null) {
1868
+ twSum += held * gap;
1869
+ twMs += gap;
1870
+ credit(states, held, gap);
1871
+ if (held < min) min = held;
1872
+ if (held > max) max = held;
1873
+ }
1874
+ if (row.twSum !== null && row.twMs !== null) {
1875
+ twSum += row.twSum;
1876
+ twMs += row.twMs;
1877
+ }
1878
+ if (states !== null && row.states !== null) for (const [state, ms] of Object.entries(row.states)) states[state] = (states[state] ?? 0) + ms;
1879
+ cursor = row.bucketStart + input.childWidthMs;
1880
+ held = row.last;
1881
+ }
1882
+ const coverageEnd = Math.min(input.windowEnd, input.horizon);
1883
+ if (hasTw && held !== null && coverageEnd > cursor) {
1884
+ twSum += held * (coverageEnd - cursor);
1885
+ twMs += coverageEnd - cursor;
1886
+ credit(states, held, coverageEnd - cursor);
1887
+ }
1888
+ return {
1889
+ seriesId: input.seriesId,
1890
+ bucketStart: input.windowStart,
1891
+ samples,
1892
+ sum,
1893
+ min,
1894
+ max,
1895
+ last: lastRow.last,
1896
+ lastTs: lastRow.lastTs,
1897
+ twSum: hasTw ? twSum : null,
1898
+ twMs: hasTw ? twMs : null,
1899
+ states
1900
+ };
1901
+ }
1902
+ /** How far back a boot rebuilds from raw and re-marks the upper tiers. */
1903
+ var BOOT_WINDOW_MS = 3 * HOUR_MS;
1904
+ var markVersion = 0;
1905
+ function mark(sets, seriesId, bucketStart) {
1906
+ const map = sets.get(seriesId) ?? /* @__PURE__ */ new Map();
1907
+ markVersion += 1;
1908
+ map.set(bucketStart, markVersion);
1909
+ sets.set(seriesId, map);
1910
+ }
1911
+ /**
1912
+ * Clear what a recompute handled — but only a mark that was not RENEWED while the
1913
+ * recompute awaited: a late write that re-marked the bucket mid-flight carries a newer
1914
+ * version and must be computed again, not erased with the old mark.
1915
+ */
1916
+ function settle(sets, seriesId, handled) {
1917
+ const map = sets.get(seriesId);
1918
+ if (map === void 0) return;
1919
+ for (const { bucket, version } of handled) if (map.get(bucket) === version) map.delete(bucket);
1920
+ if (map.size === 0) sets.delete(seriesId);
1921
+ }
1922
+ /** Buckets further apart than this are recomputed as separate ranges, not one long read. */
1923
+ var MAX_RANGE_GAP_MS = HOUR_MS;
1924
+ /** `[from, toExclusive)` ranges covering sorted 5-minute bucket starts, split at long gaps. */
1925
+ function clusterRanges(sorted) {
1926
+ const ranges = [];
1927
+ for (const start of sorted) {
1928
+ const current = ranges[ranges.length - 1];
1929
+ if (current !== void 0 && start - current[1] <= MAX_RANGE_GAP_MS) current[1] = start + FIVE_MINUTES_MS;
1930
+ else ranges.push([start, start + FIVE_MINUTES_MS]);
1931
+ }
1932
+ return ranges;
1933
+ }
1934
+ var RollupEngine = class {
1935
+ deps;
1936
+ dirty5m = /* @__PURE__ */ new Map();
1937
+ dirty1h = /* @__PURE__ */ new Map();
1938
+ dirty1d = /* @__PURE__ */ new Map();
1939
+ ticking = null;
1940
+ constructor(deps) {
1941
+ this.deps = deps;
1942
+ }
1943
+ dirtyCounts() {
1944
+ const count = (sets) => [...sets.values()].reduce((n, set) => n + set.size, 0);
1945
+ return {
1946
+ m5: count(this.dirty5m),
1947
+ h1: count(this.dirty1h),
1948
+ d1: count(this.dirty1d)
1949
+ };
1950
+ }
1951
+ /** Raw points landed: their 5-minute buckets (and a late bucket's successor) are dirty. */
1952
+ markPoints(written) {
1953
+ const now = this.deps.clock();
1954
+ for (const { seriesId, timestamps } of written) for (const ts of timestamps) {
1955
+ const bucket = floorTo(ts, FIVE_MINUTES_MS);
1956
+ mark(this.dirty5m, seriesId, bucket);
1957
+ if (bucket + 3e5 + ROLLUP_GRACE_MS["5m"] <= now) mark(this.dirty5m, seriesId, bucket + FIVE_MINUTES_MS);
1958
+ }
1959
+ }
1960
+ /** A 5m row landed (computed, or a producer bucket): its hour is dirty. */
1961
+ markFiveMinuteRow(seriesId, bucketStart) {
1962
+ mark(this.dirty1h, seriesId, bucketStartOf("1h", bucketStart));
1963
+ }
1964
+ /** One pass over the three tiers. Single-flight; errors are counted and the work stays dirty. */
1965
+ tick() {
1966
+ if (this.ticking !== null) return this.ticking;
1967
+ const run = this.doTick().finally(() => {
1968
+ this.ticking = null;
1969
+ });
1970
+ this.ticking = run;
1971
+ return run;
1972
+ }
1973
+ async doTick() {
1974
+ const now = this.deps.clock();
1975
+ await this.guarded("5m", () => this.tickFiveMinute(now));
1976
+ await this.guarded("1h", () => this.tickHour(now));
1977
+ await this.guarded("1d", () => this.tickDay(now));
1978
+ }
1979
+ async guarded(tier, run) {
1980
+ try {
1981
+ await run();
1982
+ } catch (err) {
1983
+ this.deps.counters.rollupErrors += 1;
1984
+ this.deps.logger.warn(`device-history: ${tier} rollup pass failed — work stays dirty`, { meta: { error: err instanceof Error ? err.message : String(err) } });
1985
+ }
1986
+ }
1987
+ closedBuckets(map, tier, now) {
1988
+ return [...map].filter(([start]) => bucketEndOf(tier, start) + ROLLUP_GRACE_MS[tier] <= now).map(([bucket, version]) => ({
1989
+ bucket,
1990
+ version
1991
+ })).toSorted((a, b) => a.bucket - b.bucket);
1992
+ }
1993
+ /** Forget everything held for a series that was purged. */
1994
+ forgetSeries(seriesId) {
1995
+ this.dirty5m.delete(seriesId);
1996
+ this.dirty1h.delete(seriesId);
1997
+ this.dirty1d.delete(seriesId);
1998
+ this.deps.counters.forgetSeries(seriesId);
1999
+ }
2000
+ async tickFiveMinute(now) {
2001
+ let handled = 0;
2002
+ for (const [seriesId, set] of this.dirty5m) {
2003
+ if (handled >= 400) break;
2004
+ const closed = this.closedBuckets(set, "5m", now);
2005
+ if (closed.length === 0) continue;
2006
+ handled += 1;
2007
+ for (const [from, to] of clusterRanges(closed.map((c) => c.bucket))) await this.recomputeFiveMinute(seriesId, from, to, now);
2008
+ settle(this.dirty5m, seriesId, closed);
2009
+ }
2010
+ if (handled > 0) this.deps.counters.last5mAt = now;
2011
+ }
2012
+ async tickHour(now) {
2013
+ let handled = 0;
2014
+ for (const [seriesId, set] of this.dirty1h) {
2015
+ if (handled >= 400) break;
2016
+ const closed = this.closedBuckets(set, "1h", now);
2017
+ if (closed.length === 0) continue;
2018
+ handled += 1;
2019
+ for (const hour of closed) {
2020
+ await this.recomputeHour(seriesId, hour.bucket, now);
2021
+ settle(this.dirty1h, seriesId, [hour]);
2022
+ }
2023
+ }
2024
+ if (handled > 0) this.deps.counters.last1hAt = now;
2025
+ }
2026
+ async tickDay(now) {
2027
+ let handled = 0;
2028
+ for (const [seriesId, set] of this.dirty1d) {
2029
+ if (handled >= 400) break;
2030
+ const closed = this.closedBuckets(set, "1d", now);
2031
+ if (closed.length === 0) continue;
2032
+ handled += 1;
2033
+ for (const day of closed) {
2034
+ await this.recomputeDay(seriesId, day.bucket, now);
2035
+ settle(this.dirty1d, seriesId, [day]);
2036
+ }
2037
+ }
2038
+ if (handled > 0) this.deps.counters.last1dAt = now;
2039
+ }
2040
+ /** An `enum` series keeps the time spent in each state in its rollups. */
2041
+ isEnum(seriesId) {
2042
+ const series = this.deps.registry.byIdOf(seriesId);
2043
+ return series !== void 0 && this.deps.registry.metric(series.key)?.kind === "enum";
2044
+ }
2045
+ /** Raw → 5m rows for buckets in `[from, toExclusive)`; writes them and marks their hours. */
2046
+ async recomputeFiveMinute(seriesId, from, toExclusive, horizon) {
2047
+ const { store } = this.deps;
2048
+ const points = [];
2049
+ let cursor = from;
2050
+ for (;;) {
2051
+ const page = await store.readRaw(seriesId, cursor, toExclusive - 1, READ_PAGE);
2052
+ points.push(...page);
2053
+ const last = page[page.length - 1];
2054
+ if (last === void 0 || page.length < 5e3) break;
2055
+ cursor = last.ts + 1;
2056
+ }
2057
+ const rows = rawToFiveMinuteRows({
2058
+ seriesId,
2059
+ points,
2060
+ carryIn: await store.rawBefore(seriesId, from),
2061
+ horizon,
2062
+ trackStates: this.isEnum(seriesId)
2063
+ });
2064
+ if (rows.length === 0) return 0;
2065
+ await store.upsertRollups("5m", rows);
2066
+ this.deps.counters.noteRollupRows("5m", seriesId, rows.map((r) => r.bucketStart));
2067
+ for (const row of rows) this.markFiveMinuteRow(seriesId, row.bucketStart);
2068
+ return rows.length;
2069
+ }
2070
+ async recomputeHour(seriesId, hour, now) {
2071
+ await this.recomputeFrom("5m", "1h", FIVE_MINUTES_MS, seriesId, hour, now);
2072
+ }
2073
+ async recomputeDay(seriesId, day, now) {
2074
+ await this.recomputeFrom("1h", "1d", HOUR_MS, seriesId, day, now);
2075
+ }
2076
+ async recomputeFrom(child, parent, childWidthMs, seriesId, windowStart, now) {
2077
+ const { store } = this.deps;
2078
+ const windowEnd = bucketEndOf(parent, windowStart);
2079
+ const combined = combineRows({
2080
+ seriesId,
2081
+ windowStart,
2082
+ windowEnd,
2083
+ childWidthMs,
2084
+ rows: await store.readRollups(child, seriesId, windowStart, windowEnd - 1, READ_PAGE),
2085
+ carryIn: (await store.rollupBefore(child, seriesId, windowStart))?.last ?? null,
2086
+ horizon: now,
2087
+ trackStates: this.isEnum(seriesId)
2088
+ });
2089
+ if (combined === null) return;
2090
+ await store.upsertRollups(parent, [combined]);
2091
+ this.deps.counters.noteRollupRows(parent, seriesId, [combined.bucketStart]);
2092
+ if (parent === "1h") mark(this.dirty1d, seriesId, bucketStartOf("1d", windowStart));
2093
+ }
2094
+ /**
2095
+ * After a restart the dirty sets are gone. Rebuild the recent window from raw
2096
+ * (the still-open bucket included, time-weighted up to `now`), then mark the
2097
+ * 1h / 1d buckets of that window dirty so the next ticks recompute them.
2098
+ */
2099
+ async bootRecompute(now) {
2100
+ const windowStart = floorTo(now - BOOT_WINDOW_MS, FIVE_MINUTES_MS);
2101
+ const openBucket = floorTo(now, FIVE_MINUTES_MS);
2102
+ let series = 0;
2103
+ for (const s of this.deps.registry.all()) {
2104
+ if (s.lastTs < windowStart) continue;
2105
+ const metric = this.deps.registry.metric(s.key);
2106
+ series += 1;
2107
+ if (metric?.ingest === "points") {
2108
+ await this.recomputeFiveMinute(s.id, windowStart, openBucket + FIVE_MINUTES_MS, now);
2109
+ mark(this.dirty5m, s.id, openBucket);
2110
+ mark(this.dirty5m, s.id, openBucket - FIVE_MINUTES_MS);
2111
+ }
2112
+ for (let hour = floorTo(windowStart, HOUR_MS); hour <= now; hour += HOUR_MS) mark(this.dirty1h, s.id, hour);
2113
+ mark(this.dirty1d, s.id, bucketStartOf("1d", windowStart));
2114
+ mark(this.dirty1d, s.id, bucketStartOf("1d", now));
2115
+ }
2116
+ return series;
2117
+ }
2118
+ };
2119
+ //#endregion
2120
+ //#region src/builtins/device-history/status/counters.ts
2121
+ function deltas(now, before) {
2122
+ const out = {};
2123
+ for (const [k, v] of now) {
2124
+ const d = v - (before.get(k) ?? 0);
2125
+ if (d > 0) out[k] = d;
2126
+ }
2127
+ return out;
2128
+ }
2129
+ var HistoryCounters = class {
2130
+ eventsSeen = 0;
2131
+ pointsEmitted = 0;
2132
+ pointsWritten = 0;
2133
+ pointsDropped = 0;
2134
+ trailingEmitted = 0;
2135
+ reconciledPoints = 0;
2136
+ reconcileRuns = 0;
2137
+ reconcileFailures = 0;
2138
+ lastReconcileAt = null;
2139
+ lastFlushAt = null;
2140
+ flushFailures = 0;
2141
+ ingestAccepted = 0;
2142
+ rollupErrors = 0;
2143
+ last5mAt = null;
2144
+ last1hAt = null;
2145
+ last1dAt = null;
2146
+ retentionLastRunAt = null;
2147
+ purgedSeries = 0;
2148
+ directoryRefreshAt = null;
2149
+ skipped = /* @__PURE__ */ new Map();
2150
+ refused = /* @__PURE__ */ new Map();
2151
+ deleted = /* @__PURE__ */ new Map();
2152
+ reported = {
2153
+ skipped: /* @__PURE__ */ new Map(),
2154
+ refused: /* @__PURE__ */ new Map(),
2155
+ deleted: /* @__PURE__ */ new Map(),
2156
+ flushFailures: 0
2157
+ };
2158
+ /** Net rows written minus deleted per tier since boot — the estimate behind `getStatus` row counts. */
2159
+ rowDelta = /* @__PURE__ */ new Map();
2160
+ /** Newest bucket seen per (tier, series): a row beyond it is NEW, a rewrite of an older one is not. */
2161
+ newestBucket = /* @__PURE__ */ new Map();
2162
+ skip(reason, count = 1) {
2163
+ this.skipped.set(reason, (this.skipped.get(reason) ?? 0) + count);
2164
+ }
2165
+ refuse(reason, count = 1) {
2166
+ this.refused.set(reason, (this.refused.get(reason) ?? 0) + count);
2167
+ }
2168
+ addDeleted(tier, count) {
2169
+ if (count <= 0) return;
2170
+ this.deleted.set(tier, (this.deleted.get(tier) ?? 0) + count);
2171
+ if (tier === "raw" || tier === "5m" || tier === "1h" || tier === "1d") this.rowDelta.set(tier, (this.rowDelta.get(tier) ?? 0) - count);
2172
+ }
2173
+ addRawRows(count) {
2174
+ this.rowDelta.set("raw", (this.rowDelta.get("raw") ?? 0) + count);
2175
+ }
2176
+ /** Rollup rows written: only a bucket newer than the series' newest known is counted as a new row. */
2177
+ noteRollupRows(tier, seriesId, bucketStarts) {
2178
+ const marker = `${tier}:${seriesId}`;
2179
+ let newest = this.newestBucket.get(marker) ?? Number.NEGATIVE_INFINITY;
2180
+ let added = 0;
2181
+ for (const b of bucketStarts) if (b > newest) {
2182
+ added += 1;
2183
+ newest = b;
2184
+ }
2185
+ this.newestBucket.set(marker, newest);
2186
+ if (added > 0) this.rowDelta.set(tier, (this.rowDelta.get(tier) ?? 0) + added);
2187
+ }
2188
+ rowDeltaOf(tier) {
2189
+ return this.rowDelta.get(tier) ?? 0;
2190
+ }
2191
+ forgetSeries(seriesId) {
2192
+ for (const tier of [
2193
+ "5m",
2194
+ "1h",
2195
+ "1d"
2196
+ ]) this.newestBucket.delete(`${tier}:${seriesId}`);
2197
+ }
2198
+ skippedRecord() {
2199
+ return Object.fromEntries(this.skipped);
2200
+ }
2201
+ refusedRecord() {
2202
+ return Object.fromEntries(this.refused);
2203
+ }
2204
+ deletedRecord() {
2205
+ return Object.fromEntries(this.deleted);
2206
+ }
2207
+ /** What was skipped, refused, deleted or failed since the last call; `null` when nothing. */
2208
+ summarySinceLast() {
2209
+ const summary = {
2210
+ skipped: deltas(this.skipped, this.reported.skipped),
2211
+ refused: deltas(this.refused, this.reported.refused),
2212
+ deleted: deltas(this.deleted, this.reported.deleted),
2213
+ flushFailures: this.flushFailures - this.reported.flushFailures
2214
+ };
2215
+ this.reported = {
2216
+ skipped: new Map(this.skipped),
2217
+ refused: new Map(this.refused),
2218
+ deleted: new Map(this.deleted),
2219
+ flushFailures: this.flushFailures
2220
+ };
2221
+ return Object.keys(summary.skipped).length === 0 && Object.keys(summary.refused).length === 0 && Object.keys(summary.deleted).length === 0 && summary.flushFailures === 0 ? null : summary;
2222
+ }
2223
+ };
2224
+ //#endregion
2225
+ //#region src/builtins/device-history/runtime/history-runtime.ts
2226
+ var ROLLUP_INTERVAL_MS = 6e4;
2227
+ var RECONCILE_INTERVAL_MS = 5 * 6e4;
2228
+ var RETENTION_INTERVAL_MS = 10 * 6e4;
2229
+ /**
2230
+ * ONE exact row count per boot (a `COUNT(*)` is a full scan on the history thread), taken late so
2231
+ * boot is not spent scanning the raw table. After it the figures move with the writes and deletes
2232
+ * the addon itself makes — an estimate, labelled so in the docs.
2233
+ */
2234
+ var FIRST_COUNT_DELAY_MS = 9e4;
2235
+ /** Per-row size estimates behind `approxBytes` (WITHOUT ROWID rows incl. page overhead). */
2236
+ var APPROX_BYTES_PER_ROW = {
2237
+ raw: 24,
2238
+ "5m": 72,
2239
+ "1h": 72,
2240
+ "1d": 72
2241
+ };
2242
+ var HistoryRuntime = class {
2243
+ deps;
2244
+ counters = new HistoryCounters();
2245
+ store;
2246
+ registry;
2247
+ directory;
2248
+ rollup;
2249
+ writer;
2250
+ capture;
2251
+ ingest;
2252
+ query;
2253
+ retentionJob;
2254
+ departures;
2255
+ orphans;
2256
+ optedOutDevices = /* @__PURE__ */ new Set();
2257
+ tierCounts = /* @__PURE__ */ new Map();
2258
+ startedAt;
2259
+ timers = [];
2260
+ countTimeout = null;
2261
+ ready = false;
2262
+ constructor(deps) {
2263
+ this.deps = deps;
2264
+ const { logger, clock, catalog, itemCatalog } = deps;
2265
+ this.startedAt = clock();
2266
+ this.store = new HistoryStore(deps.door);
2267
+ this.registry = new SeriesRegistry(this.store);
2268
+ this.directory = new DeviceDirectory(deps.deviceSource, this.counters, logger, clock);
2269
+ this.rollup = new RollupEngine({
2270
+ store: this.store,
2271
+ registry: this.registry,
2272
+ counters: this.counters,
2273
+ logger,
2274
+ clock
2275
+ });
2276
+ this.writer = new PointWriter({
2277
+ registry: this.registry,
2278
+ store: this.store,
2279
+ counters: this.counters,
2280
+ logger,
2281
+ clock,
2282
+ onWritten: (written) => this.rollup.markPoints(written),
2283
+ onDropped: (dropped) => this.capture.forget(dropped)
2284
+ });
2285
+ const optedOut = () => this.optedOutDevices;
2286
+ this.capture = new CaptureEngine({
2287
+ catalog,
2288
+ itemCatalog,
2289
+ registry: this.registry,
2290
+ store: this.store,
2291
+ directory: this.directory,
2292
+ writer: this.writer,
2293
+ optedOut,
2294
+ counters: this.counters,
2295
+ logger,
2296
+ clock
2297
+ });
2298
+ this.ingest = new ProducerIngest({
2299
+ registry: this.registry,
2300
+ store: this.store,
2301
+ directory: this.directory,
2302
+ writer: this.writer,
2303
+ counters: this.counters,
2304
+ logger,
2305
+ clock,
2306
+ optedOut,
2307
+ retention: () => {
2308
+ const policy = deps.retention();
2309
+ return {
2310
+ rawMs: policy.rawDays * DAY_MS,
2311
+ fiveMinuteMs: policy.fiveMinuteDays * DAY_MS
2312
+ };
2313
+ },
2314
+ onBucketWritten: (seriesId, bucketStart) => this.rollup.markFiveMinuteRow(seriesId, bucketStart)
2315
+ });
2316
+ this.query = new HistoryQuery({
2317
+ registry: this.registry,
2318
+ store: this.store,
2319
+ clock,
2320
+ retention: deps.retention,
2321
+ catalog,
2322
+ itemCatalog,
2323
+ readCapSlice: deps.readCapSlice,
2324
+ readDeviceQuantity: deps.readDeviceQuantity
2325
+ });
2326
+ this.departures = new DepartureTracker(this.store, this.registry, logger);
2327
+ this.registry.onRemove((series) => {
2328
+ this.capture.forgetSeries(series);
2329
+ this.ingest.forgetSeries(series);
2330
+ this.rollup.forgetSeries(series.id);
2331
+ this.retentionJob.forgetSeries(series.id);
2332
+ });
2333
+ this.retentionJob = new RetentionJob({
2334
+ store: this.store,
2335
+ registry: this.registry,
2336
+ departures: this.departures,
2337
+ counters: this.counters,
2338
+ logger
2339
+ });
2340
+ this.orphans = new OrphanSeries({
2341
+ store: this.store,
2342
+ registry: this.registry,
2343
+ departures: this.departures,
2344
+ retention: this.retentionJob,
2345
+ declaredCapKeys: new Set(catalogMetrics(catalog, itemCatalog, 0).map((m) => m.key)),
2346
+ logger,
2347
+ clock
2348
+ });
2349
+ }
2350
+ async prepare() {
2351
+ await this.store.declare();
2352
+ await this.registry.load();
2353
+ for (const metric of catalogMetrics(this.deps.catalog, this.deps.itemCatalog, this.deps.clock())) await this.registry.declareMetric(metric);
2354
+ this.optedOutDevices = await this.store.loadOptOuts();
2355
+ await this.departures.load();
2356
+ await this.directory.refresh();
2357
+ await this.capture.seed();
2358
+ }
2359
+ async finishBoot() {
2360
+ await this.applyLegacyScales();
2361
+ const series = await this.rollup.bootRecompute(this.deps.clock());
2362
+ this.deps.logger.info("device-history: recent rollup window rebuilt", { meta: { series } });
2363
+ await this.reconcile();
2364
+ }
2365
+ /**
2366
+ * PetKit desiccant was stored in days; the quantity base is seconds.
2367
+ * Unraid array counters were stored in GiB; the base is bytes. Both
2368
+ * factors are honest because the unit never varied inside the series.
2369
+ * Weather and numeric-sensor are not rescaled: the unit at sample time
2370
+ * was not stored, so a factor would invent a number (D393).
2371
+ */
2372
+ async applyLegacyScales() {
2373
+ await this.scaleMatching(DESICCANT_SERIES_KEY, void 0, DAY_TO_SECONDS, DESICCANT_LEGACY_MAX_DAYS, DESICCANT_SCALE_ID);
2374
+ const list = this.deps.listLegacyScales;
2375
+ if (list === void 0) return;
2376
+ let subjects;
2377
+ try {
2378
+ subjects = await list();
2379
+ } catch (err) {
2380
+ this.deps.logger.warn("device-history: legacy scale listing failed — stored points unchanged", { meta: { error: err instanceof Error ? err.message : String(err) } });
2381
+ return;
2382
+ }
2383
+ for (const subject of subjects) await this.scaleMatching(subject.seriesKey, subject.deviceId, subject.factor, subject.legacyMax, subject.migrationId);
2384
+ }
2385
+ async scaleMatching(key, deviceId, factor, legacyMax, migrationId) {
2386
+ if (await this.store.scaleApplied(migrationId)) return;
2387
+ const subject = deviceId === void 0 ? void 0 : subjectIdOf({
2388
+ kind: "device",
2389
+ deviceId
2390
+ });
2391
+ const series = this.registry.all().filter((row) => {
2392
+ if (row.key !== key) return false;
2393
+ return subject === void 0 || row.subject === subject;
2394
+ });
2395
+ let changed = 0;
2396
+ for (const row of series) changed += await this.store.scaleSeries(row.id, factor, legacyMax);
2397
+ await this.store.markScale(migrationId, this.deps.clock());
2398
+ if (changed > 0) this.deps.logger.info("device-history: rescaled a series into its base unit", {
2399
+ ...deviceId === void 0 ? {} : { tags: { deviceId } },
2400
+ meta: {
2401
+ migrationId,
2402
+ key,
2403
+ changed
2404
+ }
2405
+ });
2406
+ }
2407
+ startTimers() {
2408
+ const every = (ms, run) => {
2409
+ const timer = setInterval(() => {
2410
+ run().catch((err) => {
2411
+ this.deps.logger.warn("device-history: scheduled pass threw", { meta: { error: err instanceof Error ? err.message : String(err) } });
2412
+ });
2413
+ }, ms);
2414
+ timer.unref();
2415
+ this.timers.push(timer);
2416
+ };
2417
+ every(FLUSH_INTERVAL_MS, () => this.flushNow());
2418
+ every(ROLLUP_INTERVAL_MS, async () => {
2419
+ await this.rollup.tick();
2420
+ this.reportWindow();
2421
+ });
2422
+ every(RECONCILE_INTERVAL_MS, async () => {
2423
+ await this.reconcile();
2424
+ this.reportWindow();
2425
+ });
2426
+ every(RETENTION_INTERVAL_MS, async () => {
2427
+ await this.retentionJob.run(this.deps.retention(), this.deps.clock());
2428
+ this.reportWindow();
2429
+ });
2430
+ this.countTimeout = setTimeout(() => {
2431
+ this.refreshCounts().catch(() => void 0);
2432
+ }, FIRST_COUNT_DELAY_MS);
2433
+ this.countTimeout.unref();
2434
+ }
2435
+ async stop() {
2436
+ for (const t of this.timers) clearInterval(t);
2437
+ this.timers = [];
2438
+ if (this.countTimeout !== null) clearTimeout(this.countTimeout);
2439
+ this.countTimeout = null;
2440
+ await this.writer.flush();
2441
+ }
2442
+ /** Emit pending trailing points, then write the buffer. */
2443
+ async flushNow() {
2444
+ this.capture.tickPending(this.deps.clock());
2445
+ await this.writer.flush();
2446
+ }
2447
+ /**
2448
+ * Restore changes a dropped event missed. A FAILED read changes nothing (D49):
2449
+ * it is counted and logged, and the next pass tries again.
2450
+ */
2451
+ async reconcile() {
2452
+ const { logger, clock } = this.deps;
2453
+ if (await this.directory.refresh()) await this.departures.observe(this.directory.listedIds(), clock());
2454
+ let snapshots;
2455
+ try {
2456
+ snapshots = await this.deps.readSnapshots();
2457
+ } catch (err) {
2458
+ this.counters.reconcileFailures += 1;
2459
+ logger.warn("device-history: reconcile read failed — nothing changed", { meta: { error: err instanceof Error ? err.message : String(err) } });
2460
+ return;
2461
+ }
2462
+ const now = clock();
2463
+ this.capture.reconcile(snapshots, now);
2464
+ this.counters.reconcileRuns += 1;
2465
+ this.counters.lastReconcileAt = now;
2466
+ this.ready = true;
2467
+ }
2468
+ async refreshCounts() {
2469
+ for (const tier of [
2470
+ "raw",
2471
+ "5m",
2472
+ "1h",
2473
+ "1d"
2474
+ ]) {
2475
+ const deltaAtCount = this.counters.rowDeltaOf(tier);
2476
+ const rows = await this.store.countRows(tier);
2477
+ this.tierCounts.set(tier, {
2478
+ rows,
2479
+ countedAt: this.deps.clock(),
2480
+ deltaAtCount
2481
+ });
2482
+ }
2483
+ }
2484
+ /**
2485
+ * ONE aggregated INFO naming what was skipped, refused, deleted or failed since the
2486
+ * previous report (D391) — the counts a per-event line would drown. Silent when
2487
+ * nothing happened.
2488
+ */
2489
+ reportWindow() {
2490
+ const summary = this.counters.summarySinceLast();
2491
+ if (summary === null) return;
2492
+ this.deps.logger.info("device-history: since the last report", { meta: { ...summary } });
2493
+ }
2494
+ isEnabled(deviceId) {
2495
+ return !this.optedOutDevices.has(deviceId);
2496
+ }
2497
+ async setEnabled(deviceId, enabled) {
2498
+ if (enabled) {
2499
+ await this.store.clearOptOut(deviceId);
2500
+ this.optedOutDevices = new Set([...this.optedOutDevices].filter((id) => id !== deviceId));
2501
+ } else {
2502
+ await this.store.setOptOut(deviceId, this.deps.clock());
2503
+ this.optedOutDevices = new Set([...this.optedOutDevices, deviceId]);
2504
+ }
2505
+ return enabled;
2506
+ }
2507
+ /** Delete the history of a deleted device: its series, opt-out and absence clock. */
2508
+ async removeDevice(deviceId) {
2509
+ const series = await this.retentionJob.purgeDevice(deviceId, this.deps.clock());
2510
+ await this.store.clearOptOut(deviceId);
2511
+ await this.departures.forget(deviceId);
2512
+ this.optedOutDevices = new Set([...this.optedOutDevices].filter((id) => id !== deviceId));
2513
+ return { series };
2514
+ }
2515
+ /** Device series no longer linked to a device — reported, never purged here. */
2516
+ listOrphans() {
2517
+ return this.orphans.list();
2518
+ }
2519
+ /** Delete orphan series by id; a series that is not orphan NOW is refused. */
2520
+ deleteOrphans(seriesIds) {
2521
+ return this.orphans.delete(seriesIds);
2522
+ }
2523
+ /** Series held per device, for the admin clean-up listing. */
2524
+ seriesByDevice() {
2525
+ const out = /* @__PURE__ */ new Map();
2526
+ for (const s of this.registry.all()) {
2527
+ if (s.deviceId === null) continue;
2528
+ out.set(s.deviceId, (out.get(s.deviceId) ?? 0) + 1);
2529
+ }
2530
+ return out;
2531
+ }
2532
+ status() {
2533
+ const c = this.counters;
2534
+ const dirty = this.rollup.dirtyCounts();
2535
+ return {
2536
+ startedAt: this.startedAt,
2537
+ ready: this.ready,
2538
+ series: this.registry.all().length,
2539
+ metrics: this.registry.allMetrics().length,
2540
+ optedOutDevices: this.optedOutDevices.size,
2541
+ tiers: [
2542
+ "raw",
2543
+ "5m",
2544
+ "1h",
2545
+ "1d"
2546
+ ].map((tier) => {
2547
+ const count = this.tierCounts.get(tier);
2548
+ const rows = count === void 0 ? null : Math.max(0, count.rows + this.counters.rowDeltaOf(tier) - count.deltaAtCount);
2549
+ return {
2550
+ tier,
2551
+ rows,
2552
+ approxBytes: rows === null ? null : rows * APPROX_BYTES_PER_ROW[tier],
2553
+ countedAt: count?.countedAt ?? null
2554
+ };
2555
+ }),
2556
+ capture: {
2557
+ eventsSeen: c.eventsSeen,
2558
+ pointsEmitted: c.pointsEmitted,
2559
+ pointsWritten: c.pointsWritten,
2560
+ pointsDropped: c.pointsDropped,
2561
+ bufferDepth: this.writer.depth(),
2562
+ trailingEmitted: c.trailingEmitted,
2563
+ reconciledPoints: c.reconciledPoints,
2564
+ reconcileRuns: c.reconcileRuns,
2565
+ reconcileFailures: c.reconcileFailures,
2566
+ lastReconcileAt: c.lastReconcileAt,
2567
+ lastFlushAt: c.lastFlushAt,
2568
+ flushFailures: c.flushFailures,
2569
+ skipped: c.skippedRecord()
2570
+ },
2571
+ ingest: {
2572
+ accepted: c.ingestAccepted,
2573
+ refused: c.refusedRecord()
2574
+ },
2575
+ rollup: {
2576
+ last5mAt: c.last5mAt,
2577
+ last1hAt: c.last1hAt,
2578
+ last1dAt: c.last1dAt,
2579
+ errors: c.rollupErrors,
2580
+ dirty5m: dirty.m5,
2581
+ dirty1h: dirty.h1,
2582
+ dirty1d: dirty.d1
2583
+ },
2584
+ retention: {
2585
+ lastRunAt: c.retentionLastRunAt,
2586
+ deleted: c.deletedRecord(),
2587
+ purgedSeries: c.purgedSeries
2588
+ },
2589
+ directory: {
2590
+ devices: this.directory.size(),
2591
+ lastRefreshAt: this.directory.lastRefreshAt()
2592
+ }
2593
+ };
2594
+ }
2595
+ };
2596
+ //#endregion
2597
+ //#region src/builtins/device-history/device-history.addon.ts
2598
+ /**
2599
+ * device-history — the ONE mechanism for numeric history (D850). Hub-only, its
2600
+ * own runner (not grouped, D29): it writes through the settings door into
2601
+ * `history.db`, a file with its own serving thread (D851), so a slow rollup can
2602
+ * never queue behind — or in front of — configuration reads.
2603
+ *
2604
+ * This shell only wires: the capability provider, the bus subscription, the
2605
+ * timers and the retention settings. The engine is {@link HistoryRuntime}.
2606
+ *
2607
+ * Boot waits for `onHubReachable` — the settings door and the device manager
2608
+ * are hub capabilities, and a forked runner cannot call them from
2609
+ * `onInitialize`. Until then the provider answers "starting" rather than an
2610
+ * empty history (an unanswered query is not an empty one, D315).
2611
+ *
2612
+ * Readiness follows the STORE, not the registration: the provider registers at
2613
+ * `onInitialize`, but `ready` is emitted only once the runtime is open in
2614
+ * `onHubReachable` (`autoEmitReadiness` is off). Producers declare their
2615
+ * series on `ready`; the automatic emit at registration sent every one of
2616
+ * them into "device-history is starting" on each boot (`.50`, 1.2.607:
2617
+ * metrics-native and pipeline-analytics).
2618
+ */
2619
+ var DEFAULT_CONFIG = {
2620
+ rawDays: DEFAULT_RETENTION.rawDays,
2621
+ fiveMinuteDays: DEFAULT_RETENTION.fiveMinuteDays,
2622
+ hourDays: DEFAULT_RETENTION.hourDays,
2623
+ dayDays: 0
2624
+ };
2625
+ function isRecord(value) {
2626
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2627
+ }
2628
+ /** The caller the transport stamped (never in an input schema); `null` when unstamped. */
2629
+ function callerOf(input) {
2630
+ if (!isRecord(input)) return null;
2631
+ const raw = input["callerAddonId"];
2632
+ return typeof raw === "string" && raw.length > 0 ? raw : null;
2633
+ }
2634
+ function positiveOr(value, fallback) {
2635
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2636
+ }
2637
+ var DeviceHistoryAddon = class extends BaseAddon {
2638
+ runtime = null;
2639
+ unsubscribe = null;
2640
+ removalHook = null;
2641
+ /** This instance's readiness generation (the base class keeps its own private). */
2642
+ readinessGeneration = `device-history-${Date.now().toString(36)}`;
2643
+ constructor() {
2644
+ super({ ...DEFAULT_CONFIG });
2645
+ }
2646
+ /** `ready` is the store being open, emitted by {@link emitStoreReadiness}. */
2647
+ get autoEmitReadiness() {
2648
+ return false;
2649
+ }
2650
+ /** Readiness of both provided caps, on the bare node this runner belongs to. */
2651
+ emitStoreReadiness(state) {
2652
+ const ctx = this.ctxIfReady;
2653
+ if (ctx === null) return;
2654
+ const raw = ctx.kernel?.localNodeId ?? "hub";
2655
+ const nodeId = raw.includes("/") ? raw.split("/")[0] ?? raw : raw;
2656
+ for (const capName of [deviceHistoryCapability.name, deviceRemovalHookCapability.name]) try {
2657
+ emitReadiness(ctx.eventBus, {
2658
+ capName,
2659
+ scope: {
2660
+ type: "node",
2661
+ nodeId
2662
+ },
2663
+ state,
2664
+ generation: this.readinessGeneration,
2665
+ sourceNodeId: nodeId
2666
+ });
2667
+ } catch (err) {
2668
+ ctx.logger.warn("device-history: readiness not emitted", { meta: {
2669
+ capName,
2670
+ state,
2671
+ error: err instanceof Error ? err.message : String(err)
2672
+ } });
2673
+ }
2674
+ }
2675
+ retention() {
2676
+ const c = this.config;
2677
+ return {
2678
+ rawDays: positiveOr(c.rawDays, DEFAULT_RETENTION.rawDays),
2679
+ fiveMinuteDays: positiveOr(c.fiveMinuteDays, DEFAULT_RETENTION.fiveMinuteDays),
2680
+ hourDays: positiveOr(c.hourDays, DEFAULT_RETENTION.hourDays),
2681
+ dayDays: positiveOr(c.dayDays, 0) > 0 ? c.dayDays : null
2682
+ };
2683
+ }
2684
+ /** Unraid array counters still stored in GiB. A failed listing throws to the caller. */
2685
+ async legacyScales() {
2686
+ const devices = await this.ctx.api.deviceManager.listAll.query({});
2687
+ const scales = [];
2688
+ for (const device of devices) {
2689
+ if (device.addonId !== "provider-unraid") continue;
2690
+ const entityKey = device.config["entityKey"];
2691
+ if (typeof entityKey !== "string") continue;
2692
+ const scale = unraidInformationScale(device.id, entityKey);
2693
+ if (scale !== null) scales.push(scale);
2694
+ }
2695
+ return scales;
2696
+ }
2697
+ requireRuntime() {
2698
+ if (this.runtime === null) throw new Error("device-history is starting — the history store is not open yet");
2699
+ return this.runtime;
2700
+ }
2701
+ async onInitialize() {
2702
+ const provider = {
2703
+ listSeries: async (input) => this.requireRuntime().query.listSeries({
2704
+ kind: "device",
2705
+ deviceId: input.deviceId
2706
+ }),
2707
+ listNodeSeries: async (input) => this.requireRuntime().query.listSeries({
2708
+ kind: "node",
2709
+ nodeId: input.forNodeId
2710
+ }),
2711
+ query: async ({ deviceId, ...window }) => this.requireRuntime().query.query({
2712
+ ...window,
2713
+ subject: {
2714
+ kind: "device",
2715
+ deviceId
2716
+ }
2717
+ }),
2718
+ queryNode: async ({ forNodeId, ...window }) => this.requireRuntime().query.query({
2719
+ ...window,
2720
+ subject: {
2721
+ kind: "node",
2722
+ nodeId: forNodeId
2723
+ }
2724
+ }),
2725
+ queryMany: async (input) => ({ results: await this.requireRuntime().query.queryMany(input) }),
2726
+ declareSeries: async (input) => this.requireRuntime().ingest.declareSeries(callerOf(input), input),
2727
+ record: async (input) => this.requireRuntime().ingest.record(callerOf(input), input.points),
2728
+ recordBuckets: async (input) => this.requireRuntime().ingest.recordBuckets(callerOf(input), input.buckets),
2729
+ getDeviceEnabled: async (input) => ({ enabled: this.requireRuntime().isEnabled(input.deviceId) }),
2730
+ setDeviceEnabled: async (input) => ({ enabled: await this.requireRuntime().setEnabled(input.deviceId, input.enabled) }),
2731
+ getStatus: async () => this.requireRuntime().status(),
2732
+ listOrphanSeries: async () => this.requireRuntime().listOrphans(),
2733
+ deleteOrphanSeries: async (input) => ({ results: await this.requireRuntime().deleteOrphans(input.seriesIds) })
2734
+ };
2735
+ this.emitStoreReadiness("starting");
2736
+ this.ctx.logger.info("Initialized — device-history provider registered (store opens on hub link)");
2737
+ const removalHook = {
2738
+ onDeviceRemoved: async (input) => {
2739
+ const { series } = await this.requireRuntime().removeDevice(input.deviceId);
2740
+ if (series > 0) this.ctx.logger.info("device-history: removed the history of a deleted device", {
2741
+ tags: { deviceId: input.deviceId },
2742
+ meta: {
2743
+ counts: { series },
2744
+ deletedAt: input.deletedAt
2745
+ }
2746
+ });
2747
+ return { counts: { series } };
2748
+ },
2749
+ listDeviceData: async () => [...this.requireRuntime().seriesByDevice()].map(([deviceId, count]) => ({
2750
+ store: "series",
2751
+ deviceId,
2752
+ count
2753
+ }))
2754
+ };
2755
+ this.removalHook = removalHook;
2756
+ return [{
2757
+ capability: deviceHistoryCapability,
2758
+ provider
2759
+ }, {
2760
+ capability: deviceRemovalHookCapability,
2761
+ provider: removalHook
2762
+ }];
2763
+ }
2764
+ async onHubReachable() {
2765
+ const api = this.ctx.api;
2766
+ const runtime = new HistoryRuntime({
2767
+ door: api.settingsStore,
2768
+ catalog: HISTORY_CATALOG,
2769
+ itemCatalog: HISTORY_ITEM_CATALOG,
2770
+ deviceSource: {
2771
+ listAll: async () => {
2772
+ return (await api.deviceManager.listAll.query({ projection: "slim" })).map((d) => ({
2773
+ id: d.id,
2774
+ type: d.type
2775
+ }));
2776
+ },
2777
+ getDevice: async (deviceId) => {
2778
+ const d = await api.deviceManager.getDevice.query({ deviceId });
2779
+ return d === null ? null : {
2780
+ id: d.id,
2781
+ type: d.type
2782
+ };
2783
+ }
2784
+ },
2785
+ readSnapshots: async () => api.deviceState.getAllSnapshots.query({}),
2786
+ readCapSlice: (deviceId, capName) => api.deviceState.getCapSlice.query({
2787
+ deviceId,
2788
+ capName
2789
+ }),
2790
+ readDeviceQuantity: async (deviceId) => {
2791
+ const quantity = (await api.deviceManager.getDevice.query({ deviceId }))?.sourceInfo?.quantity;
2792
+ return isReadingQuantity(quantity) ? quantity : null;
2793
+ },
2794
+ listLegacyScales: () => this.legacyScales(),
2795
+ retention: () => this.retention(),
2796
+ logger: this.ctx.logger,
2797
+ clock: () => Date.now()
2798
+ });
2799
+ await runtime.prepare();
2800
+ this.unsubscribe = this.ctx.eventBus.subscribe({ category: EventCategory.DeviceStateChanged }, (event) => {
2801
+ const data = event.data;
2802
+ if (!isRecord(data)) return;
2803
+ const { deviceId, capName, slice } = data;
2804
+ if (typeof deviceId !== "number" || typeof capName !== "string" || !isRecord(slice)) return;
2805
+ const at = event.timestamp instanceof Date ? event.timestamp.getTime() : Date.now();
2806
+ runtime.capture.handleState(deviceId, capName, slice, at);
2807
+ });
2808
+ this.ctx.addDisposer(async () => this.stopRuntime());
2809
+ this.runtime = runtime;
2810
+ await runtime.finishBoot();
2811
+ runtime.startTimers();
2812
+ const removalHook = this.removalHook;
2813
+ if (removalHook !== null) this.ctx.addDisposer(armRemovalReconcile({
2814
+ api: this.ctx.api,
2815
+ logger: this.ctx.logger,
2816
+ remove: (input) => removalHook.onDeviceRemoved(input)
2817
+ }));
2818
+ this.emitStoreReadiness("ready");
2819
+ this.ctx.logger.info("device-history: capturing", { meta: {
2820
+ series: runtime.status().series,
2821
+ metrics: runtime.status().metrics
2822
+ } });
2823
+ }
2824
+ async stopRuntime() {
2825
+ this.unsubscribe?.();
2826
+ this.unsubscribe = null;
2827
+ await this.runtime?.stop();
2828
+ }
2829
+ async onShutdown() {
2830
+ this.emitStoreReadiness("down");
2831
+ await this.stopRuntime();
2832
+ this.runtime = null;
2833
+ }
2834
+ globalSettingsSchema() {
2835
+ return this.schema({ sections: [{
2836
+ id: "retention",
2837
+ title: "Retention",
2838
+ description: "How long each tier is kept. The raw points feed the 5-minute rollup; the 1-day tier is kept forever unless a number of days is set.",
2839
+ columns: 2,
2840
+ fields: [
2841
+ {
2842
+ type: "number",
2843
+ key: "rawDays",
2844
+ label: "Raw points (days)",
2845
+ min: 1,
2846
+ max: 60,
2847
+ step: 1
2848
+ },
2849
+ {
2850
+ type: "number",
2851
+ key: "fiveMinuteDays",
2852
+ label: "5-minute rollup (days)",
2853
+ min: 1,
2854
+ max: 365,
2855
+ step: 1
2856
+ },
2857
+ {
2858
+ type: "number",
2859
+ key: "hourDays",
2860
+ label: "1-hour rollup (days)",
2861
+ min: 7,
2862
+ max: 3650,
2863
+ step: 1
2864
+ },
2865
+ {
2866
+ type: "number",
2867
+ key: "dayDays",
2868
+ label: "1-day rollup (days, 0 = forever)",
2869
+ min: 0,
2870
+ max: 36500,
2871
+ step: 1
2872
+ }
2873
+ ]
2874
+ }] });
2875
+ }
2876
+ };
2877
+ //#endregion
2878
+ export { DeviceHistoryAddon, DeviceHistoryAddon as default, callerOf };