@camstack/server 1.2.942 → 1.2.944

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 (158) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/closure-pins.json +350 -0
  3. package/dist/api/core/auth-sessions.procedures.js +18 -0
  4. package/dist/api/core/auth.router.js +19 -6
  5. package/dist/api/server-upload.js +17 -1
  6. package/dist/api/trpc/generated-cap-routers.js +83 -0
  7. package/dist/auth/native-return.js +9 -3
  8. package/dist/auth/sso-routes.js +5 -1
  9. package/dist/core/addon/instance-lifecycle.js +4 -1
  10. package/dist/core/auth/handoff-code.service.js +35 -1
  11. package/dist/server-root/index.js +313 -70
  12. package/package.json +22 -26
  13. package/system/dist/{action-index-B1fgpQBt.mjs → action-index-DpYmsOKh.mjs} +1 -1
  14. package/system/dist/{action-index-B_cLRwXJ.js → action-index-Dz9rd1qa.js} +1 -1
  15. package/system/dist/{addon-settings.cap-CZ4MC7ha.mjs → addon-settings.cap-CHpmuaQG.mjs} +1 -1
  16. package/system/dist/{addon-settings.cap-DrLdMFIe.js → addon-settings.cap-nZVHPo3X.js} +1 -1
  17. package/system/dist/{alert-episode-Be--PngO.mjs → alert-episode-D-1VUUkZ.mjs} +1 -1
  18. package/system/dist/{alert-episode-Bqktmt-i.js → alert-episode-DaQ3prSe.js} +1 -1
  19. package/system/dist/{base-addon-CRsXtYFG.js → base-addon-BG7p06Hb.js} +136 -15
  20. package/system/dist/{base-addon-BcS6r1cT.mjs → base-addon-BcVoYZbC.mjs} +136 -15
  21. package/system/dist/{base-device-DAdWzDOl.js → base-device-DeSNiwZ4.js} +4 -4
  22. package/system/dist/{base-device-DJXF5eDN.mjs → base-device-w_MD0Bf4.mjs} +4 -4
  23. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  24. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  25. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  26. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  27. package/system/dist/builtins/alerts/alerts.addon.js +3 -3
  28. package/system/dist/builtins/alerts/alerts.addon.mjs +3 -3
  29. package/system/dist/builtins/autotrack/index.js +1 -1
  30. package/system/dist/builtins/autotrack/index.mjs +1 -1
  31. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +1 -1
  32. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +1 -1
  33. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  34. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  35. package/system/dist/builtins/camera-grid/index.js +3 -3
  36. package/system/dist/builtins/camera-grid/index.mjs +3 -3
  37. package/system/dist/builtins/composer/composer.addon.js +7 -7
  38. package/system/dist/builtins/composer/composer.addon.mjs +7 -7
  39. package/system/dist/builtins/console-logging/index.js +1 -1
  40. package/system/dist/builtins/console-logging/index.mjs +1 -1
  41. package/system/dist/builtins/core-blocks/actions-store.d.ts +2 -0
  42. package/system/dist/builtins/core-blocks/block-supervisor.d.ts +16 -4
  43. package/system/dist/builtins/core-blocks/core-block-store.d.ts +2 -0
  44. package/system/dist/builtins/core-blocks/core-blocks.addon.js +1018 -323
  45. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +986 -291
  46. package/system/dist/builtins/core-blocks/migrations/index.d.ts +5 -2
  47. package/system/dist/builtins/core-blocks/migrations/tag-ids.d.ts +42 -0
  48. package/system/dist/builtins/core-blocks/migrations/tags-as-records.d.ts +47 -0
  49. package/system/dist/builtins/core-blocks/record-kinds.d.ts +12 -1
  50. package/system/dist/builtins/core-blocks/runs-api.d.ts +3 -1
  51. package/system/dist/builtins/core-blocks/runs-ledger.d.ts +3 -1
  52. package/system/dist/builtins/core-blocks/scheduler/scheduler-store.d.ts +2 -0
  53. package/system/dist/builtins/core-blocks/tags-service.d.ts +52 -27
  54. package/system/dist/builtins/core-blocks/tags-wiring.d.ts +2 -0
  55. package/system/dist/builtins/core-notifier/core-notifier.addon.js +76 -67
  56. package/system/dist/builtins/core-notifier/core-notifier.addon.mjs +76 -67
  57. package/system/dist/builtins/device-history/device-history.addon.js +4 -4
  58. package/system/dist/builtins/device-history/device-history.addon.mjs +4 -4
  59. package/system/dist/builtins/device-manager/device-config-secrets.d.ts +14 -0
  60. package/system/dist/builtins/device-manager/device-manager.addon.js +1655 -764
  61. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1641 -750
  62. package/system/dist/builtins/device-manager/device-meta-actions.d.ts +13 -136
  63. package/system/dist/builtins/device-manager/device-meta-types.d.ts +5 -1
  64. package/system/dist/builtins/device-manager/device-provider-context.d.ts +9 -0
  65. package/system/dist/builtins/device-manager/device-row-store.d.ts +21 -4
  66. package/system/dist/builtins/device-manager/device-search.d.ts +6 -0
  67. package/system/dist/builtins/device-manager/location-alignment.d.ts +9 -2
  68. package/system/dist/builtins/device-manager/migrate-device.d.ts +7 -2
  69. package/system/dist/builtins/device-manager/migrate-hardware-state.d.ts +132 -1
  70. package/system/dist/builtins/device-manager/migrations/device-tag-ids.d.ts +25 -0
  71. package/system/dist/builtins/device-manager/migrations/index.d.ts +16 -0
  72. package/system/dist/builtins/device-manager/migrations/orphan-children.d.ts +33 -0
  73. package/system/dist/builtins/device-manager/migrations/ports.d.ts +17 -0
  74. package/system/dist/builtins/device-manager/migrations/rooms-as-records.d.ts +52 -0
  75. package/system/dist/builtins/device-manager/record-kinds.d.ts +3 -1
  76. package/system/dist/builtins/device-manager/removal-cleanup.d.ts +7 -0
  77. package/system/dist/builtins/device-manager/room-actions.d.ts +27 -0
  78. package/system/dist/builtins/device-manager/room-store.d.ts +19 -0
  79. package/system/dist/builtins/device-manager/tag-names.d.ts +32 -0
  80. package/system/dist/builtins/device-manager/wireable-enum-catalog.d.ts +18 -0
  81. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  82. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  83. package/system/dist/builtins/keychain/index.js +2 -2
  84. package/system/dist/builtins/keychain/index.mjs +2 -2
  85. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  86. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  87. package/system/dist/builtins/local-auth/local-auth.addon.js +1 -1
  88. package/system/dist/builtins/local-auth/local-auth.addon.mjs +1 -1
  89. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  90. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  91. package/system/dist/builtins/loki-logging/index.js +2 -2
  92. package/system/dist/builtins/loki-logging/index.mjs +2 -2
  93. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  94. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  95. package/system/dist/builtins/platform-probe/index.js +1 -1
  96. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  97. package/system/dist/builtins/record-entries/index.js +1 -1
  98. package/system/dist/builtins/record-entries/index.mjs +1 -1
  99. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  100. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  101. package/system/dist/builtins/snapshot/index.js +1 -1
  102. package/system/dist/builtins/snapshot/index.mjs +1 -1
  103. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  104. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  105. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  106. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  107. package/system/dist/builtins/sqlite-storage/migrations/migration-engine.d.ts +3 -1
  108. package/system/dist/builtins/sqlite-storage/migrations/migrations-provider.d.ts +1 -0
  109. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +15 -10
  110. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +15 -10
  111. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  112. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  113. package/system/dist/builtins/system-config/system-config.addon.js +1 -1
  114. package/system/dist/builtins/system-config/system-config.addon.mjs +1 -1
  115. package/system/dist/builtins/winston-logging/index.js +2 -2
  116. package/system/dist/builtins/winston-logging/index.mjs +2 -2
  117. package/system/dist/{command-catalog-C29hVOOg.js → command-catalog-CI0tu1Nt.js} +1 -1
  118. package/system/dist/{command-catalog-xAeqxbZk.mjs → command-catalog-zwlIA3T5.mjs} +1 -1
  119. package/system/dist/{composition-sources-C327LGFn.mjs → composition-sources-CXxXfh1z.mjs} +1 -1
  120. package/system/dist/{composition-sources-Do5qM6EB.js → composition-sources-DNgSItK-.js} +1 -1
  121. package/system/dist/{core-blocks.cap-CdTGUKtr.js → core-blocks.cap-BHEok4VO.js} +125 -373
  122. package/system/dist/{core-blocks.cap-DLkEfV5b.mjs → core-blocks.cap-CPgZRcpj.mjs} +109 -327
  123. package/system/dist/{device-manager.cap-DJs8izI6.js → device-manager.cap-B9qVf7ag.js} +163 -22
  124. package/system/dist/{device-manager.cap-eYrj1Ezp.mjs → device-manager.cap-CV4KGp3e.mjs} +134 -17
  125. package/system/dist/{error.cap-CU1FB6uE.mjs → error.cap-B8l7L8e4.mjs} +7 -1
  126. package/system/dist/{error.cap-BuKbL3Ac.js → error.cap-BqlvgBJd.js} +7 -1
  127. package/system/dist/file-host-worker.js +1 -1
  128. package/system/dist/file-host-worker.mjs +1 -1
  129. package/system/dist/index.js +7 -7
  130. package/system/dist/index.mjs +6 -6
  131. package/system/dist/{legacy-integration-rows-door-CdqYAj-o.js → legacy-integration-rows-door-BK8eoGlF.js} +1 -1
  132. package/system/dist/{legacy-integration-rows-door-LSgpClpX.mjs → legacy-integration-rows-door-CwzC5XNk.mjs} +1 -1
  133. package/system/dist/{migration-DGAc6ywR.mjs → migration-BvbfW9g-.mjs} +6 -0
  134. package/system/dist/{migration-BOQlFZCN.js → migration-CHPdAdNh.js} +6 -0
  135. package/system/dist/{prefix-walk-BFnw8NBu.js → named-entity-store-DFwLij9c.js} +244 -90
  136. package/system/dist/{prefix-walk-Mtij0NNT.mjs → named-entity-store-DOnyyFFf.mjs} +195 -89
  137. package/system/dist/{notification-rules.cap-BUIuYPlQ.mjs → notification-rules.cap-ClvK6QT1.mjs} +10 -5
  138. package/system/dist/{notification-rules.cap-BJKUjizS.js → notification-rules.cap-uSLoe2pA.js} +10 -5
  139. package/system/dist/{notification-targets-DMW7xgR2.js → notification-targets-ChqpBbtR.js} +2 -2
  140. package/system/dist/{notification-targets-4bGYH5J7.mjs → notification-targets-DUA6-F2t.mjs} +2 -2
  141. package/system/dist/{device-row-store-CTocYKqC.mjs → record-kinds-BD2xv4Pd.mjs} +222 -93
  142. package/system/dist/{device-row-store-C0P2H18h.js → record-kinds-BV8Gcpsx.js} +246 -93
  143. package/system/dist/records/named-entity-store.d.ts +60 -0
  144. package/system/dist/{rename-composition-block-Cdh-dRmY.mjs → rename-composition-block-C3QQ9UUE.mjs} +134 -33
  145. package/system/dist/{rename-composition-block-D9Uc1AF7.js → rename-composition-block-Cx3X8QSm.js} +134 -33
  146. package/system/dist/{retention-source.cap-C6Hy0hlM.js → retention-source.cap-A-TMhU5O.js} +1 -1
  147. package/system/dist/{retention-source.cap-550kkyp5.mjs → retention-source.cap-Ct07pM30.mjs} +1 -1
  148. package/system/dist/{storage-admin.cap-Ci4QbL6P.mjs → storage-admin.cap-C54s9_B9.mjs} +8 -2
  149. package/system/dist/{storage-admin.cap-DqW1ol4j.js → storage-admin.cap-DSPHi7ut.js} +8 -2
  150. package/system/dist/{stream-catalog.cap-CjEQFknc.js → stream-catalog.cap-7WPsugOy.js} +1 -1
  151. package/system/dist/{stream-catalog.cap-DVniDdRD.mjs → stream-catalog.cap-CzwRDaqT.mjs} +1 -1
  152. package/system/dist/{tag-BxLazvVb.js → tag-BLraBqvp.js} +12 -0
  153. package/system/dist/{tag-uZBAq6ox.mjs → tag-DU8pm9Bi.mjs} +7 -1
  154. package/system/dist/time-window-B6UhCArd.js +679 -0
  155. package/system/dist/time-window-BnUBULgu.mjs +578 -0
  156. package/system/dist/{wal-maintenance-BgYiAy5b.js → wal-maintenance-CkPfVApC.js} +0 -0
  157. package/system/dist/{wal-maintenance-Bey5ChBb.mjs → wal-maintenance-u84_1sVl.mjs} +0 -0
  158. package/system/package.json +1 -1
@@ -1,27 +1,28 @@
1
- import { E as deviceStatusCapability, T as DeviceStatusSchema } from "../../stream-catalog.cap-DVniDdRD.mjs";
2
- import { b as EventCategory$1, g as WELL_KNOWN_TAB_MAP, n as secretTreeFromPaths, o as resolveSecretMarkers, s as transformSecretWrite, t as BaseAddon } from "../../base-addon-BcS6r1cT.mjs";
3
- import { B as SECRET_CLEAR, G as isSecretMarkerLike, H as isSecretClear, W as isSecretMarker, X as isKeychainStoredField, Z as errMsg$1, q as toSecretFieldView } from "../../scoped-settings-DVWUIP7Z.mjs";
4
- import { Jn as ExportNameRefusedError, _n as deviceStateCapability, b as workloadTransition, c as kebabToCamel, fn as PUSH_CONFIRM_WINDOW_MS, g as WorkloadStateSchema, gn as FieldClaimSchema, h as WORKLOAD_TRANSITION_CATEGORY, hn as FieldClaimModeSchema, m as ALL_CAPABILITY_DEFINITIONS, mn as effectiveRefreshIntervalMs, n as renameCompositionBlock, pn as commandBurstOffsets, t as composedBlockIdOf, v as isWorkloadSettled, vn as deviceExtensionCapability, y as workloadCapability, yn as EXTENSION_SLOTS } from "../../rename-composition-block-Cdh-dRmY.mjs";
1
+ import { E as deviceStatusCapability, T as DeviceStatusSchema } from "../../stream-catalog.cap-CzwRDaqT.mjs";
2
+ import { b as EventCategory$1, f as defineAddonMigrations, g as WELL_KNOWN_TAB_MAP, n as secretTreeFromPaths, o as resolveSecretMarkers, s as transformSecretWrite, t as BaseAddon } from "../../base-addon-BcVoYZbC.mjs";
3
+ import { B as SECRET_CLEAR, G as isSecretMarkerLike, H as isSecretClear, K as makeSecretMarker, W as isSecretMarker, X as isKeychainStoredField, Z as errMsg$1, b as buildSecretRef, q as toSecretFieldView, w as parseSecretRef } from "../../scoped-settings-DVWUIP7Z.mjs";
4
+ import { Jn as ExportNameRefusedError, _n as deviceStateCapability, b as workloadTransition, c as kebabToCamel, fn as PUSH_CONFIRM_WINDOW_MS, g as WorkloadStateSchema, gn as FieldClaimSchema, h as WORKLOAD_TRANSITION_CATEGORY, hn as FieldClaimModeSchema, m as ALL_CAPABILITY_DEFINITIONS, mn as effectiveRefreshIntervalMs, n as renameCompositionBlock, pn as commandBurstOffsets, t as composedBlockIdOf, v as isWorkloadSettled, vn as deviceExtensionCapability, y as workloadCapability, yn as EXTENSION_SLOTS } from "../../rename-composition-block-C3QQ9UUE.mjs";
5
5
  import { t as userError } from "../../camstack-error-viZYfcj9.mjs";
6
6
  import { a as expandCapMethods$1, s as isDeviceConfigCap } from "../../capability-definition-C1TLUVJR.mjs";
7
7
  import { t as collectZodSecretPaths$1 } from "../../zod-secret-zY4nM61M.mjs";
8
- import { _ as resolveTemplateRef, a as deviceManagerCapability, d as siteZoneKey, f as DEVICE_TEMPLATE_FILTERS, g as DEVICE_TEMPLATE_VALUES_CAP, l as identityLinkId, m as DEVICE_TEMPLATE_MAX_OUTPUT, p as DEVICE_TEMPLATE_MAX_LENGTH, u as identityLinkSidesRefusal, v as checkDeviceAlias, y as generateDeviceAlias } from "../../device-manager.cap-eYrj1Ezp.mjs";
8
+ import { C as generateDeviceAlias, S as checkDeviceAlias, _ as DEVICE_TEMPLATE_MAX_LENGTH, a as deviceManagerCapability, b as DEVICE_TEMPLATE_VALUES_CAP, d as ZoneBodySchema, g as DEVICE_TEMPLATE_FILTERS, h as identityLinkSidesRefusal, m as identityLinkId, s as RoomBodySchema, v as DEVICE_TEMPLATE_MAX_OUTPUT, x as resolveTemplateRef } from "../../device-manager.cap-CV4KGp3e.mjs";
9
9
  import { a as isEmptyIdentifiers, c as sameIdentifiers, i as identifierStrength, l as CAMERA_SWITCH_ORDER, o as mergeIdentifiers, r as DeviceIdentifiersSchema, t as DEVICE_IDENTIFIER_KEYS } from "../../device-identifiers-iSuQCKmK.mjs";
10
- import { d as canonicalIconKey, o as normalizeTags } from "../../tag-uZBAq6ox.mjs";
10
+ import { a as deviceRowBackendOf, c as recordUpsertEdit, i as DeviceRowStore, n as DEVICE_ROWS_COLLECTION, o as MigrationRefusedError, r as DEVICE_ROWS_FLEET_LIMIT, t as deviceManagerRecordKinds } from "../../record-kinds-BD2xv4Pd.mjs";
11
+ import { u as preconditionOf } from "../../migration-BvbfW9g-.mjs";
12
+ import { f as canonicalIconKey, s as normalizeTags, u as tagKey } from "../../tag-DU8pm9Bi.mjs";
11
13
  import { n as DeviceRole, r as DeviceType$1, t as DeviceFeature } from "../../device-type-TUGqGmaI.mjs";
12
14
  import { n as capAppliesToDeviceKind } from "../../device-kind-C37Ra2wd.mjs";
13
- import { c as CAP_VOCABULARY_BY_NAME, o as vocabActionIdFor } from "../../action-index-B1fgpQBt.mjs";
14
- import { u as locationIconKey } from "../../addon-settings.cap-CZ4MC7ha.mjs";
15
- import { $ as CAP_RUNTIME_FIELD_UNITS, Xt as enumerateSchemaFields, Yt as enumerateItemArrayFields } from "../../core-blocks.cap-DLkEfV5b.mjs";
15
+ import { $ as CAP_RUNTIME_FIELD_UNITS, Xt as enumerateItemArrayFields, Zt as enumerateSchemaFields } from "../../core-blocks.cap-CPgZRcpj.mjs";
16
+ import { c as CAP_VOCABULARY_BY_NAME, o as vocabActionIdFor } from "../../action-index-DpYmsOKh.mjs";
17
+ import { u as locationIconKey } from "../../addon-settings.cap-CHpmuaQG.mjs";
16
18
  import "../../compile-OBMHlqD-.mjs";
17
19
  import { a as normalizeUnit, r as extractSourceInfoFromMetadata } from "../../source-info-DGB7SdB_.mjs";
18
- import { r as ConditionMirror, t as loadPrefixed } from "../../prefix-walk-Mtij0NNT.mjs";
19
- import { a as effectConditionHolds, i as commandHoldMs, n as commandEffect, o as isCommand$1, r as commandEffects, s as resolveSideEffect } from "../../command-catalog-xAeqxbZk.mjs";
20
+ import { a as loadPrefixed, c as roomIdFromKey, d as ConditionMirror, i as createWriteLock, l as tagIdFromKey, n as EntityNotFoundError, r as NamedEntityStore, s as entityNameKey, t as EntityNameTakenError, u as zoneIdFromKey } from "../../named-entity-store-DOnyyFFf.mjs";
21
+ import { a as effectConditionHolds, i as commandHoldMs, n as commandEffect, o as isCommand$1, r as commandEffects, s as resolveSideEffect } from "../../command-catalog-zwlIA3T5.mjs";
20
22
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
21
23
  import { a as redactLogText, i as redactLogMeta, n as isSecretArgumentKey } from "../../log-redactor-XLDrPzOi.mjs";
22
24
  import { t as prefixRange } from "../../prefix-range-Dl0znowN.mjs";
23
25
  import { n as purgeRetiredSettingsRows } from "../../retired-settings-keys-u6xQA6r7.mjs";
24
- import { a as MigrationRefusedError, i as deviceManagerRecordKinds, n as DeviceRowStore, r as deviceRowBackendOf } from "../../device-row-store-CTocYKqC.mjs";
25
26
  import { n as isRenderResponse, r as analyzeTemplate } from "../../template-protocol-SgPDx3Hw.mjs";
26
27
  import { s as normalizeServiceType } from "../../dns-wire-Dm3H_7ST.mjs";
27
28
  import { createRequire } from "node:module";
@@ -2941,6 +2942,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
2941
2942
  access: "create",
2942
2943
  role: "admin"
2943
2944
  },
2945
+ "deviceManager.deleteRoom": {
2946
+ capName: "device-manager",
2947
+ capScope: "system",
2948
+ addonId: null,
2949
+ access: "delete",
2950
+ role: "admin"
2951
+ },
2944
2952
  "deviceManager.disable": {
2945
2953
  capName: "device-manager",
2946
2954
  capScope: "system",
@@ -2997,6 +3005,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
2997
3005
  access: "create",
2998
3006
  role: "admin"
2999
3007
  },
3008
+ "deviceManager.ensureRoom": {
3009
+ capName: "device-manager",
3010
+ capScope: "system",
3011
+ addonId: null,
3012
+ access: "create",
3013
+ role: "admin"
3014
+ },
3000
3015
  "deviceManager.getAllBindings": {
3001
3016
  capName: "device-manager",
3002
3017
  capScope: "system",
@@ -3221,6 +3236,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3221
3236
  access: "view",
3222
3237
  role: "admin"
3223
3238
  },
3239
+ "deviceManager.listRooms": {
3240
+ capName: "device-manager",
3241
+ capScope: "system",
3242
+ addonId: null,
3243
+ access: "view",
3244
+ role: "viewer"
3245
+ },
3224
3246
  "deviceManager.listSiteZones": {
3225
3247
  capName: "device-manager",
3226
3248
  capScope: "system",
@@ -3361,6 +3383,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3361
3383
  access: "view",
3362
3384
  role: "admin"
3363
3385
  },
3386
+ "deviceManager.repairMigrationSecrets": {
3387
+ capName: "device-manager",
3388
+ capScope: "system",
3389
+ addonId: null,
3390
+ access: "create",
3391
+ role: "admin"
3392
+ },
3364
3393
  "deviceManager.reportDiscoveryObservations": {
3365
3394
  capName: "device-manager",
3366
3395
  capScope: "system",
@@ -3592,6 +3621,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3592
3621
  access: "create",
3593
3622
  role: "admin"
3594
3623
  },
3624
+ "deviceManager.updateRoom": {
3625
+ capName: "device-manager",
3626
+ capScope: "system",
3627
+ addonId: null,
3628
+ access: "create",
3629
+ role: "admin"
3630
+ },
3595
3631
  "deviceOps.getConfigEntries": {
3596
3632
  capName: "device-ops",
3597
3633
  capScope: "device",
@@ -10438,6 +10474,20 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
10438
10474
  access: "create",
10439
10475
  role: "admin"
10440
10476
  },
10477
+ "tags.deleteTag": {
10478
+ capName: "tags",
10479
+ capScope: "system",
10480
+ addonId: null,
10481
+ access: "delete",
10482
+ role: "admin"
10483
+ },
10484
+ "tags.ensureTag": {
10485
+ capName: "tags",
10486
+ capScope: "system",
10487
+ addonId: null,
10488
+ access: "create",
10489
+ role: "admin"
10490
+ },
10441
10491
  "tags.list": {
10442
10492
  capName: "tags",
10443
10493
  capScope: "system",
@@ -10445,6 +10495,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
10445
10495
  access: "view",
10446
10496
  role: "admin"
10447
10497
  },
10498
+ "tags.listTags": {
10499
+ capName: "tags",
10500
+ capScope: "system",
10501
+ addonId: null,
10502
+ access: "view",
10503
+ role: "admin"
10504
+ },
10448
10505
  "tags.remove": {
10449
10506
  capName: "tags",
10450
10507
  capScope: "system",
@@ -10466,6 +10523,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
10466
10523
  access: "create",
10467
10524
  role: "admin"
10468
10525
  },
10526
+ "tags.updateTag": {
10527
+ capName: "tags",
10528
+ capScope: "system",
10529
+ addonId: null,
10530
+ access: "create",
10531
+ role: "admin"
10532
+ },
10469
10533
  "tamper.getStatus": {
10470
10534
  capName: "tamper",
10471
10535
  capScope: "device",
@@ -12513,104 +12577,629 @@ function resolveCommandHold(cap, method, args, current, option, shown = current)
12513
12577
  };
12514
12578
  }
12515
12579
  //#endregion
12516
- //#region src/builtins/device-manager/adoption-job-engine.ts
12517
- /** How many finished jobs are kept per (addonId, integrationId). */
12518
- var JOB_HISTORY = 20;
12519
- function snapshot(j) {
12520
- let adopted = 0;
12521
- let alreadyAdopted = 0;
12522
- let failed = 0;
12523
- let processed = 0;
12524
- let accessoriesCreated = 0;
12525
- for (const r of j.results) {
12526
- if (r.outcome === "cancelled") continue;
12527
- processed += 1;
12528
- accessoriesCreated += r.accessoryCount;
12529
- if (r.outcome === "adopted") adopted += 1;
12530
- else if (r.outcome === "already-adopted") alreadyAdopted += 1;
12531
- else if (r.outcome === "failed") failed += 1;
12580
+ //#region src/builtins/device-manager/migrations/device-tag-ids.ts
12581
+ /**
12582
+ * A device row gets the ids of its tags (D1089, the device-manager step of the tags
12583
+ * migration): `tagIds` is added beside the kept `tags` names, aligned by index, with each id
12584
+ * derived from the folded name (`tagIdFromKey`) so every owner of that name mints the same
12585
+ * one. The names stay for one release; the `tags` records are written later by the
12586
+ * core-blocks tags-as-records procedure, which `dependsOn` this step.
12587
+ *
12588
+ * ONE plan, one transaction. A row that already has `tagIds` is left alone (a rerun is
12589
+ * empty); a row whose names repeat one tag in two spellings is rewritten with both columns
12590
+ * de-duplicated, so the index alignment holds.
12591
+ */
12592
+ var DEVICE_TAG_IDS_ID = "device-manager/2026-11-23-device-tag-ids";
12593
+ async function planDeviceTagIds(ports) {
12594
+ const rows = await ports.readDeviceTags();
12595
+ const edits = [];
12596
+ for (const row of rows) {
12597
+ if (row.hasTagIds) continue;
12598
+ const names = normalizeTags(row.tags);
12599
+ if (names.length === 0) continue;
12600
+ const sameNames = names.length === row.tags.length;
12601
+ edits.push({
12602
+ op: "putRow",
12603
+ table: DEVICE_ROWS_COLLECTION,
12604
+ key: { deviceId: row.deviceId },
12605
+ row: {
12606
+ tagIds: names.map((name) => tagIdFromKey(tagKey(name))),
12607
+ ...sameNames ? {} : { tags: names }
12608
+ },
12609
+ preconditionColumns: ["tagIds"],
12610
+ precondition: preconditionOf({ tagIds: null })
12611
+ });
12612
+ }
12613
+ return { edits };
12614
+ }
12615
+ //#endregion
12616
+ //#region src/builtins/device-manager/migrations/orphan-children.ts
12617
+ /** The rows that name a parent no row answers to. */
12618
+ function orphansOf(rows) {
12619
+ const ids = new Set(rows.map((r) => r.id));
12620
+ return rows.filter((r) => r.parentDeviceId !== null && !ids.has(r.parentDeviceId));
12621
+ }
12622
+ /**
12623
+ * Destructive on one read is never enough (D49): a row is removed only when TWO
12624
+ * reads agree it is an orphan, and nothing is removed from a read that may have
12625
+ * been cut short at the row limit. The candidate ids are recorded in the summary
12626
+ * and the log BEFORE any removal.
12627
+ */
12628
+ async function removeOrphanChildren(ports) {
12629
+ const first = await ports.listRows();
12630
+ if (first.length >= ports.rowLimit) throw new Error(`device-manager: ${first.length} rows read, the limit is ${ports.rowLimit} — the read may be truncated, nothing removed`);
12631
+ const candidates = orphansOf(first);
12632
+ if (candidates.length === 0) return {
12633
+ outcome: "already-done",
12634
+ summary: {
12635
+ candidates: [],
12636
+ removed: []
12637
+ }
12638
+ };
12639
+ const second = await ports.listRows();
12640
+ const stillOrphans = new Set(orphansOf(second).map((r) => r.id));
12641
+ const confirmed = candidates.filter((r) => stillOrphans.has(r.id));
12642
+ const candidateIds = candidates.map((r) => r.id);
12643
+ ports.summary({
12644
+ rows: first.length,
12645
+ candidateCount: candidateIds.length,
12646
+ candidates: candidateIds,
12647
+ confirmedCount: confirmed.length,
12648
+ confirmed: confirmed.map((r) => r.id)
12649
+ });
12650
+ const removed = [];
12651
+ for (const orphan of confirmed) {
12652
+ if (orphan.parentDeviceId === null) continue;
12653
+ ports.info("device-manager: removing an orphan child, its parent no longer exists", orphan.id, orphan.parentDeviceId);
12654
+ await ports.removeDevice(orphan.id);
12655
+ removed.push(orphan.id);
12532
12656
  }
12533
12657
  return {
12534
- jobId: j.jobId,
12535
- addonId: j.addonId,
12536
- integrationId: j.integrationId,
12537
- state: j.state,
12538
- total: j.total,
12539
- processed,
12540
- adopted,
12541
- alreadyAdopted,
12542
- failed,
12543
- accessoriesCreated,
12544
- currentChildNativeId: j.currentChildNativeId,
12545
- results: j.results.map((r) => ({
12546
- childNativeId: r.childNativeId,
12547
- outcome: r.outcome,
12548
- parentDeviceId: r.parentDeviceId,
12549
- accessoryCount: r.accessoryCount,
12550
- error: r.error
12551
- })),
12552
- startedAt: j.startedAt,
12553
- finishedAt: j.finishedAt,
12554
- error: j.error
12658
+ outcome: "done",
12659
+ summary: {
12660
+ candidates: candidateIds,
12661
+ removed
12662
+ }
12555
12663
  };
12556
12664
  }
12557
- var AdoptionJobEngine = class {
12558
- deps;
12559
- jobs = /* @__PURE__ */ new Map();
12560
- seq = 0;
12561
- constructor(deps) {
12562
- this.deps = deps;
12563
- }
12564
- now() {
12565
- return this.deps.now?.() ?? Date.now();
12665
+ //#endregion
12666
+ //#region src/builtins/device-manager/device-meta-types.ts
12667
+ /**
12668
+ * Decode the raw `ctx.settings.readAddonStore()` record into {@link AddonStore}.
12669
+ *
12670
+ * A field of the wrong shape reads as ABSENT rather than being trusted through
12671
+ * a cast: the store is JSON on disk and a hand-edit or a partial restore must
12672
+ * cost the caller its default, never a downstream `TypeError`.
12673
+ */
12674
+ function decodeAddonStore(raw) {
12675
+ const nextDeviceId = raw["nextDeviceId"];
12676
+ const locations = raw["locations"];
12677
+ const roleDisplayDefaults = raw["roleDisplayDefaults"];
12678
+ const locationIcons = decodeLocationIcons(raw["locationIcons"]);
12679
+ const locationDescriptions = decodeLocationDescriptions(raw["locationDescriptions"]);
12680
+ const siteZones = decodeSiteZones(raw["siteZones"]);
12681
+ const locationZones = decodeStringMap(raw["locationZones"]);
12682
+ return {
12683
+ ...typeof nextDeviceId === "number" && Number.isFinite(nextDeviceId) ? { nextDeviceId } : {},
12684
+ ...Array.isArray(locations) ? { locations: locations.filter((l) => typeof l === "string") } : {},
12685
+ ...isRoleDisplayDefaults(roleDisplayDefaults) ? { roleDisplayDefaults } : {},
12686
+ ...locationIcons !== null ? { locationIcons } : {},
12687
+ ...locationDescriptions !== null ? { locationDescriptions } : {},
12688
+ ...siteZones !== null ? { siteZones } : {},
12689
+ ...locationZones !== null ? { locationZones } : {}
12690
+ };
12691
+ }
12692
+ /**
12693
+ * Decode the `locationIcons` map, dropping every entry whose value is not a
12694
+ * member of the closed vocabulary.
12695
+ *
12696
+ * Dropping, not passing through: the icon's whole point is that both surfaces
12697
+ * can draw it, and an id from a hand-edit or a newer hub is exactly the value
12698
+ * that draws nothing. Absent reads as "no icon chosen", which every renderer
12699
+ * already degrades to the fallback pin. Returns `null` when the key itself is
12700
+ * absent or of the wrong shape, so the field stays OMITTED rather than being
12701
+ * written back as an empty object.
12702
+ */
12703
+ function decodeLocationIcons(raw) {
12704
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12705
+ const out = {};
12706
+ for (const [key, value] of Object.entries(raw)) {
12707
+ const icon = canonicalIconKey(value);
12708
+ if (icon === void 0) continue;
12709
+ out[key] = icon;
12566
12710
  }
12567
- newId() {
12568
- if (this.deps.newId) return this.deps.newId();
12569
- this.seq += 1;
12570
- return `adopt-${Date.now().toString(36)}-${this.seq}`;
12711
+ return out;
12712
+ }
12713
+ /**
12714
+ * Decode the `locationDescriptions` map, dropping every entry that is not a
12715
+ * non-blank string.
12716
+ *
12717
+ * Same posture as the icons: a blank description and a missing one are the
12718
+ * same instruction to every reader, and storing the first would send an empty
12719
+ * line to a vision model. Over-long text is TRUNCATED rather than dropped —
12720
+ * losing the whole description because a hand-edit ran long is a worse answer
12721
+ * than losing its tail.
12722
+ */
12723
+ function decodeLocationDescriptions(raw) {
12724
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12725
+ const out = {};
12726
+ for (const [key, value] of Object.entries(raw)) {
12727
+ if (typeof value !== "string") continue;
12728
+ const text = value.trim();
12729
+ if (text.length === 0) continue;
12730
+ out[key] = text.slice(0, 400);
12571
12731
  }
12572
- /**
12573
- * Accept the batch and return immediately. The provider is resolved BEFORE
12574
- * returning so an unroutable `addonId` is refused at the call the operator
12575
- * made, not buried in a job they have to go looking for.
12576
- */
12577
- async start(input) {
12578
- const provider = await this.deps.resolveProvider(input.addonId);
12579
- const job = {
12580
- jobId: this.newId(),
12581
- addonId: input.addonId,
12582
- integrationId: input.integrationId,
12583
- state: "running",
12584
- total: input.childNativeIds.length,
12585
- currentChildNativeId: null,
12586
- results: [],
12587
- startedAt: this.now(),
12588
- finishedAt: null,
12589
- error: null,
12590
- cancelRequested: false,
12591
- done: Promise.resolve()
12732
+ return out;
12733
+ }
12734
+ /**
12735
+ * Decode the zone registry, dropping any entry without a usable label.
12736
+ *
12737
+ * A zone whose label did not survive a hand-edit cannot be shown or renamed —
12738
+ * it would be a row the operator can see the effects of and never name. An
12739
+ * icon outside the vocabulary is dropped on its own, leaving the zone: losing
12740
+ * a glyph is a smaller loss than losing the grouping.
12741
+ */
12742
+ function decodeSiteZones(raw) {
12743
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12744
+ const out = {};
12745
+ for (const [key, value] of Object.entries(raw)) {
12746
+ if (value === null || typeof value !== "object" || Array.isArray(value)) continue;
12747
+ const rec = value;
12748
+ const label = typeof rec["label"] === "string" ? rec["label"].trim() : "";
12749
+ if (label.length === 0) continue;
12750
+ const icon = canonicalIconKey(rec["icon"]);
12751
+ out[key] = icon === void 0 ? { label } : {
12752
+ label,
12753
+ icon
12592
12754
  };
12593
- this.jobs.set(job.jobId, job);
12594
- this.prune(input.addonId, input.integrationId);
12595
- this.deps.logger.info("adoption job started", {
12596
- tags: { addonId: input.addonId },
12597
- meta: {
12598
- jobId: job.jobId,
12599
- integrationId: input.integrationId,
12600
- total: job.total
12601
- }
12602
- });
12603
- job.done = this.run(job, provider, input);
12604
- return { jobId: job.jobId };
12605
12755
  }
12606
- get(jobId) {
12607
- const j = this.jobs.get(jobId);
12608
- return j ? snapshot(j) : null;
12609
- }
12610
- list(filter) {
12611
- return [...this.jobs.values()].filter((j) => (filter.addonId === void 0 || j.addonId === filter.addonId) && (filter.integrationId === void 0 || j.integrationId === filter.integrationId)).sort((a, b) => b.startedAt - a.startedAt || b.jobId.localeCompare(a.jobId)).map(snapshot);
12756
+ return out;
12757
+ }
12758
+ /** Decode a plain `string → string` map, dropping anything else. */
12759
+ function decodeStringMap(raw) {
12760
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12761
+ const out = {};
12762
+ for (const [key, value] of Object.entries(raw)) {
12763
+ if (typeof value !== "string" || value.trim().length === 0) continue;
12764
+ out[key] = value;
12612
12765
  }
12613
- /** Cooperative cancel — the in-flight candidate finishes, the rest do not start. */
12766
+ return out;
12767
+ }
12768
+ function isRoleDisplayDefaults(value) {
12769
+ return value !== null && typeof value === "object" && !Array.isArray(value);
12770
+ }
12771
+ //#endregion
12772
+ //#region src/builtins/device-manager/migrations/rooms-as-records.ts
12773
+ /**
12774
+ * Rooms and site zones become records with an id (D1089, step 1 of the migration).
12775
+ *
12776
+ * Before: a room was a LABEL. The registry (`locations`), its icon and description maps
12777
+ * and the two zone maps (`siteZones`, `locationZones`) lived as keys of the addon store,
12778
+ * and a device carried the label in its `location` column.
12779
+ *
12780
+ * After: one `rooms` record per label and one `zones` record per site zone, with an id
12781
+ * derived from the folded name (`roomIdFromKey` / `zoneIdFromKey`, so a rerun and a
12782
+ * restored older snapshot reach the same ids); a device carries `locationId`; the maps and
12783
+ * the `location` column are gone.
12784
+ *
12785
+ * ONE plan, so ONE transaction with the ledger row: the records, the device rows and the
12786
+ * deleted keys land together or not at all. A rerun finds no legacy key and no device with
12787
+ * a `location`, and the plan is empty. A record that already exists is never rewritten (a
12788
+ * seed never overwrites): a room an operator edited after a partial restore keeps its edit.
12789
+ *
12790
+ * The display spelling is the registry's, else the one most devices use (the first
12791
+ * alphabetically on a tie), else the folded key a map entry carries.
12792
+ */
12793
+ var DEVICE_MANAGER_ID = "device-manager";
12794
+ var ROOMS_AS_RECORDS_ID = "device-manager/2026-11-23-rooms-as-records";
12795
+ /** The canonical settings table: one row per key, id `<addonId>.<key>`. */
12796
+ var ADDON_SETTINGS_TABLE = "addon-settings";
12797
+ /** The addon-store keys this migration retires. */
12798
+ var LEGACY_ROOM_KEYS = [
12799
+ "locations",
12800
+ "locationIcons",
12801
+ "locationDescriptions",
12802
+ "siteZones",
12803
+ "locationZones"
12804
+ ];
12805
+ var isPlainMap = (raw) => raw !== null && typeof raw === "object" && !Array.isArray(raw);
12806
+ /** The entries the decode drops or shortens, raw, before the keys are deleted. */
12807
+ function droppedLegacyEntries(stored) {
12808
+ const out = [];
12809
+ const icons = stored["locationIcons"];
12810
+ if (isPlainMap(icons)) {
12811
+ for (const [key, value] of Object.entries(icons)) if (canonicalIconKey(value) === void 0) out.push({
12812
+ map: "locationIcons",
12813
+ key,
12814
+ reason: "icon not in the catalogue",
12815
+ value
12816
+ });
12817
+ }
12818
+ const descriptions = stored["locationDescriptions"];
12819
+ if (isPlainMap(descriptions)) {
12820
+ for (const [key, value] of Object.entries(descriptions)) if (typeof value !== "string" || value.trim().length === 0) out.push({
12821
+ map: "locationDescriptions",
12822
+ key,
12823
+ reason: "blank description",
12824
+ value
12825
+ });
12826
+ else if (value.trim().length > 400) out.push({
12827
+ map: "locationDescriptions",
12828
+ key,
12829
+ reason: "description truncated",
12830
+ value
12831
+ });
12832
+ }
12833
+ const zones = stored["siteZones"];
12834
+ if (isPlainMap(zones)) {
12835
+ for (const [key, value] of Object.entries(zones)) if ((isPlainMap(value) && typeof value["label"] === "string" ? value["label"].trim() : "").length === 0) out.push({
12836
+ map: "siteZones",
12837
+ key,
12838
+ reason: "zone without a label",
12839
+ value
12840
+ });
12841
+ else if (isPlainMap(value) && value["icon"] !== void 0 && canonicalIconKey(value["icon"]) === void 0) out.push({
12842
+ map: "siteZones",
12843
+ key,
12844
+ reason: "zone icon not in the catalogue",
12845
+ value
12846
+ });
12847
+ }
12848
+ const membership = stored["locationZones"];
12849
+ if (isPlainMap(membership)) {
12850
+ for (const [key, value] of Object.entries(membership)) if (typeof value !== "string" || value.trim().length === 0) out.push({
12851
+ map: "locationZones",
12852
+ key,
12853
+ reason: "blank zone",
12854
+ value
12855
+ });
12856
+ else if (!isPlainMap(zones) || zones[value] === void 0) out.push({
12857
+ map: "locationZones",
12858
+ key,
12859
+ reason: "zone not in the registry",
12860
+ value
12861
+ });
12862
+ }
12863
+ return out;
12864
+ }
12865
+ /** A map keyed by the FOLDED room key: a legacy key that was never folded still matches. */
12866
+ function foldedBy(map) {
12867
+ const out = /* @__PURE__ */ new Map();
12868
+ for (const [key, value] of Object.entries(map ?? {})) {
12869
+ const folded = locationIconKey(key);
12870
+ if (folded.length > 0 && !out.has(folded)) out.set(folded, value);
12871
+ }
12872
+ return out;
12873
+ }
12874
+ var settingsRowId = (key) => `${DEVICE_MANAGER_ID}.${key}`;
12875
+ function clip(name) {
12876
+ return name.trim().slice(0, 80);
12877
+ }
12878
+ /** The spelling to show for each folded room key: registry first, else the most used on devices. */
12879
+ function spellings(registry, devices) {
12880
+ const out = /* @__PURE__ */ new Map();
12881
+ for (const label of registry) {
12882
+ const key = locationIconKey(label);
12883
+ if (key.length > 0 && !out.has(key)) out.set(key, clip(label));
12884
+ }
12885
+ const used = /* @__PURE__ */ new Map();
12886
+ for (const { location } of devices) {
12887
+ if (location === null) continue;
12888
+ const key = locationIconKey(location);
12889
+ if (key.length === 0) continue;
12890
+ const counts = used.get(key) ?? /* @__PURE__ */ new Map();
12891
+ counts.set(location.trim(), (counts.get(location.trim()) ?? 0) + 1);
12892
+ used.set(key, counts);
12893
+ }
12894
+ for (const [key, counts] of used) {
12895
+ if (out.has(key)) continue;
12896
+ const best = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0];
12897
+ if (best !== void 0) out.set(key, clip(best[0]));
12898
+ }
12899
+ return out;
12900
+ }
12901
+ async function planRoomsAsRecords(ports) {
12902
+ const stored = await ports.readStored(LEGACY_ROOM_KEYS);
12903
+ const store = decodeAddonStore(stored);
12904
+ const devices = await ports.readDeviceLocations();
12905
+ const existingRooms = await ports.readRoomIds();
12906
+ const existingZones = await ports.readZoneIds();
12907
+ const names = spellings(store.locations ?? [], devices);
12908
+ for (const key of [
12909
+ ...Object.keys(store.locationIcons ?? {}),
12910
+ ...Object.keys(store.locationDescriptions ?? {}),
12911
+ ...Object.keys(store.locationZones ?? {})
12912
+ ]) {
12913
+ const folded = locationIconKey(key);
12914
+ if (folded.length > 0 && !names.has(folded)) names.set(folded, clip(key));
12915
+ }
12916
+ const zones = store.siteZones ?? {};
12917
+ const membership = foldedBy(store.locationZones);
12918
+ const iconsByRoom = foldedBy(store.locationIcons);
12919
+ const descriptionsByRoom = foldedBy(store.locationDescriptions);
12920
+ const dropped = droppedLegacyEntries(stored);
12921
+ if (dropped.length > 0) {
12922
+ const counts = {};
12923
+ for (const entry of dropped) counts[entry.map] = (counts[entry.map] ?? 0) + 1;
12924
+ ports.report?.("rooms migration: legacy entries not carried over", {
12925
+ counts,
12926
+ dropped
12927
+ });
12928
+ }
12929
+ const edits = [];
12930
+ for (const [zoneKey, zone] of Object.entries(zones)) {
12931
+ const id = zoneIdFromKey(zoneKey);
12932
+ if (existingZones.has(id)) continue;
12933
+ const body = {
12934
+ name: clip(zone.label),
12935
+ ...zone.icon === void 0 ? {} : { icon: zone.icon }
12936
+ };
12937
+ edits.push(recordUpsertEdit({
12938
+ owner: DEVICE_MANAGER_ID,
12939
+ kind: deviceManagerRecordKinds.zones,
12940
+ id,
12941
+ data: body,
12942
+ read: null
12943
+ }));
12944
+ }
12945
+ for (const [key, name] of names) {
12946
+ const id = roomIdFromKey(key);
12947
+ if (existingRooms.has(id)) continue;
12948
+ const icon = iconsByRoom.get(key);
12949
+ const description = descriptionsByRoom.get(key);
12950
+ const zoneKey = membership.get(key);
12951
+ const zoneId = zoneKey !== void 0 && zones[zoneKey] !== void 0 ? zoneIdFromKey(zoneKey) : void 0;
12952
+ const body = {
12953
+ name,
12954
+ ...icon === void 0 ? {} : { icon },
12955
+ ...description === void 0 ? {} : { description },
12956
+ ...zoneId === void 0 ? {} : { zoneId }
12957
+ };
12958
+ edits.push(recordUpsertEdit({
12959
+ owner: DEVICE_MANAGER_ID,
12960
+ kind: deviceManagerRecordKinds.rooms,
12961
+ id,
12962
+ data: body,
12963
+ read: null
12964
+ }));
12965
+ }
12966
+ for (const device of devices) {
12967
+ if (device.location === null) continue;
12968
+ const folded = locationIconKey(device.location);
12969
+ const locationId = device.locationId ?? (folded.length === 0 ? null : roomIdFromKey(folded));
12970
+ edits.push({
12971
+ op: "putRow",
12972
+ table: DEVICE_ROWS_COLLECTION,
12973
+ key: { deviceId: device.deviceId },
12974
+ row: {
12975
+ locationId,
12976
+ location: null
12977
+ },
12978
+ preconditionColumns: ["location", "locationId"],
12979
+ precondition: preconditionOf({
12980
+ location: device.location,
12981
+ locationId: device.locationId
12982
+ })
12983
+ });
12984
+ }
12985
+ const present = LEGACY_ROOM_KEYS.filter((key) => key in stored);
12986
+ if (present.length > 0) edits.push({
12987
+ op: "deleteKeys",
12988
+ scope: ADDON_SETTINGS_TABLE,
12989
+ keys: present.map(settingsRowId),
12990
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [settingsRowId(key), {
12991
+ addonId: DEVICE_MANAGER_ID,
12992
+ key,
12993
+ value: stored[key]
12994
+ }])))
12995
+ });
12996
+ return { edits };
12997
+ }
12998
+ //#endregion
12999
+ //#region src/builtins/device-manager/migrations/index.ts
13000
+ var REMOVE_ORPHAN_CHILDREN_ID = "device-manager/2026-11-23-remove-orphan-children";
13001
+ /** Rooms, zones and tag ids: run BEFORE the first read resolves a name (D1089). */
13002
+ var ROOMS_AND_TAGS_MIGRATIONS = [{
13003
+ meta: {
13004
+ id: ROOMS_AS_RECORDS_ID,
13005
+ owner: DEVICE_MANAGER_ID,
13006
+ level: "addon-state",
13007
+ seq: 1,
13008
+ dependsOn: [],
13009
+ store: "settings",
13010
+ scope: "cluster",
13011
+ onFailure: "tolerate",
13012
+ bodyKind: "plan",
13013
+ description: "Rooms and site zones become records with an id: one record per label, a locationId on each device, and the label maps and the location column deleted, in one transaction",
13014
+ fixtureMark: "a device column and a room icon the migration does not know"
13015
+ },
13016
+ plan: (ports) => planRoomsAsRecords(ports)
13017
+ }, {
13018
+ meta: {
13019
+ id: DEVICE_TAG_IDS_ID,
13020
+ owner: DEVICE_MANAGER_ID,
13021
+ level: "addon-state",
13022
+ seq: 2,
13023
+ dependsOn: [],
13024
+ store: "settings",
13025
+ scope: "cluster",
13026
+ onFailure: "tolerate",
13027
+ bodyKind: "plan",
13028
+ description: "Add the ids of its tags to each device row beside the kept names, derived from the folded name",
13029
+ fixtureMark: "a device column the migration does not know"
13030
+ },
13031
+ plan: (ports) => planDeviceTagIds(ports)
13032
+ }];
13033
+ /** Accessory rows left behind by a removal that did not cascade: run once the fleet is up (D987). */
13034
+ var ORPHAN_CHILDREN_MIGRATIONS = [{
13035
+ meta: {
13036
+ id: REMOVE_ORPHAN_CHILDREN_ID,
13037
+ owner: DEVICE_MANAGER_ID,
13038
+ level: "addon-state",
13039
+ seq: 3,
13040
+ dependsOn: [],
13041
+ store: "settings",
13042
+ scope: "cluster",
13043
+ onFailure: "tolerate",
13044
+ bodyKind: "procedure",
13045
+ description: "Remove every device row whose parentDeviceId names no row, through the tombstoned removal, each one logged",
13046
+ fixtureMark: "a child of a live parent and a top-level row, both kept"
13047
+ },
13048
+ procedure: removeOrphanChildren
13049
+ }];
13050
+ [...ROOMS_AND_TAGS_MIGRATIONS, ...ORPHAN_CHILDREN_MIGRATIONS];
13051
+ //#endregion
13052
+ //#region src/builtins/device-manager/migrations/ports.ts
13053
+ var import_read_all_rows = require_read_all_rows();
13054
+ var stringOrNull = (value) => typeof value === "string" ? value : null;
13055
+ function stringArray(value) {
13056
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
13057
+ }
13058
+ function deviceManagerMigrationPorts(source) {
13059
+ return {
13060
+ readStored: async (keys) => {
13061
+ const found = {};
13062
+ for (const key of keys) {
13063
+ const answer = await source.readStoredKey(key);
13064
+ if (answer.kind === "unreadable") throw new Error(`${DEVICE_MANAGER_ID}: the setting ${key} cannot be read (${answer.reason})`);
13065
+ if (answer.kind === "present") found[key] = answer.value;
13066
+ }
13067
+ return found;
13068
+ },
13069
+ readDeviceLocations: async () => {
13070
+ return (await source.rows.readRawColumns([
13071
+ "deviceId",
13072
+ "location",
13073
+ "locationId"
13074
+ ])).flatMap((row) => {
13075
+ const deviceId = row["deviceId"];
13076
+ if (typeof deviceId !== "number") return [];
13077
+ return [{
13078
+ deviceId,
13079
+ location: stringOrNull(row["location"]),
13080
+ locationId: stringOrNull(row["locationId"])
13081
+ }];
13082
+ });
13083
+ },
13084
+ readDeviceTags: async () => {
13085
+ return (await source.rows.readRawColumns([
13086
+ "deviceId",
13087
+ "tags",
13088
+ "tagIds"
13089
+ ])).flatMap((row) => {
13090
+ const deviceId = row["deviceId"];
13091
+ if (typeof deviceId !== "number") return [];
13092
+ return [{
13093
+ deviceId,
13094
+ tags: stringArray(row["tags"]),
13095
+ hasTagIds: row["tagIds"] !== null && row["tagIds"] !== void 0
13096
+ }];
13097
+ });
13098
+ },
13099
+ readRoomIds: async () => new Set((await (0, import_read_all_rows.readAllRows)(source.rooms)).map((row) => row.id)),
13100
+ readZoneIds: async () => new Set((await (0, import_read_all_rows.readAllRows)(source.zones)).map((row) => row.id)),
13101
+ ...source.report === void 0 ? {} : { report: source.report }
13102
+ };
13103
+ }
13104
+ //#endregion
13105
+ //#region src/builtins/device-manager/adoption-job-engine.ts
13106
+ /** How many finished jobs are kept per (addonId, integrationId). */
13107
+ var JOB_HISTORY = 20;
13108
+ function snapshot(j) {
13109
+ let adopted = 0;
13110
+ let alreadyAdopted = 0;
13111
+ let failed = 0;
13112
+ let processed = 0;
13113
+ let accessoriesCreated = 0;
13114
+ for (const r of j.results) {
13115
+ if (r.outcome === "cancelled") continue;
13116
+ processed += 1;
13117
+ accessoriesCreated += r.accessoryCount;
13118
+ if (r.outcome === "adopted") adopted += 1;
13119
+ else if (r.outcome === "already-adopted") alreadyAdopted += 1;
13120
+ else if (r.outcome === "failed") failed += 1;
13121
+ }
13122
+ return {
13123
+ jobId: j.jobId,
13124
+ addonId: j.addonId,
13125
+ integrationId: j.integrationId,
13126
+ state: j.state,
13127
+ total: j.total,
13128
+ processed,
13129
+ adopted,
13130
+ alreadyAdopted,
13131
+ failed,
13132
+ accessoriesCreated,
13133
+ currentChildNativeId: j.currentChildNativeId,
13134
+ results: j.results.map((r) => ({
13135
+ childNativeId: r.childNativeId,
13136
+ outcome: r.outcome,
13137
+ parentDeviceId: r.parentDeviceId,
13138
+ accessoryCount: r.accessoryCount,
13139
+ error: r.error
13140
+ })),
13141
+ startedAt: j.startedAt,
13142
+ finishedAt: j.finishedAt,
13143
+ error: j.error
13144
+ };
13145
+ }
13146
+ var AdoptionJobEngine = class {
13147
+ deps;
13148
+ jobs = /* @__PURE__ */ new Map();
13149
+ seq = 0;
13150
+ constructor(deps) {
13151
+ this.deps = deps;
13152
+ }
13153
+ now() {
13154
+ return this.deps.now?.() ?? Date.now();
13155
+ }
13156
+ newId() {
13157
+ if (this.deps.newId) return this.deps.newId();
13158
+ this.seq += 1;
13159
+ return `adopt-${Date.now().toString(36)}-${this.seq}`;
13160
+ }
13161
+ /**
13162
+ * Accept the batch and return immediately. The provider is resolved BEFORE
13163
+ * returning so an unroutable `addonId` is refused at the call the operator
13164
+ * made, not buried in a job they have to go looking for.
13165
+ */
13166
+ async start(input) {
13167
+ const provider = await this.deps.resolveProvider(input.addonId);
13168
+ const job = {
13169
+ jobId: this.newId(),
13170
+ addonId: input.addonId,
13171
+ integrationId: input.integrationId,
13172
+ state: "running",
13173
+ total: input.childNativeIds.length,
13174
+ currentChildNativeId: null,
13175
+ results: [],
13176
+ startedAt: this.now(),
13177
+ finishedAt: null,
13178
+ error: null,
13179
+ cancelRequested: false,
13180
+ done: Promise.resolve()
13181
+ };
13182
+ this.jobs.set(job.jobId, job);
13183
+ this.prune(input.addonId, input.integrationId);
13184
+ this.deps.logger.info("adoption job started", {
13185
+ tags: { addonId: input.addonId },
13186
+ meta: {
13187
+ jobId: job.jobId,
13188
+ integrationId: input.integrationId,
13189
+ total: job.total
13190
+ }
13191
+ });
13192
+ job.done = this.run(job, provider, input);
13193
+ return { jobId: job.jobId };
13194
+ }
13195
+ get(jobId) {
13196
+ const j = this.jobs.get(jobId);
13197
+ return j ? snapshot(j) : null;
13198
+ }
13199
+ list(filter) {
13200
+ return [...this.jobs.values()].filter((j) => (filter.addonId === void 0 || j.addonId === filter.addonId) && (filter.integrationId === void 0 || j.integrationId === filter.integrationId)).sort((a, b) => b.startedAt - a.startedAt || b.jobId.localeCompare(a.jobId)).map(snapshot);
13201
+ }
13202
+ /** Cooperative cancel — the in-flight candidate finishes, the rest do not start. */
12614
13203
  cancel(jobId) {
12615
13204
  const job = this.jobs.get(jobId);
12616
13205
  if (!job || job.state !== "running") return false;
@@ -13488,6 +14077,104 @@ function sleep$1(ms) {
13488
14077
  });
13489
14078
  }
13490
14079
  //#endregion
14080
+ //#region src/builtins/device-manager/wireable-enum-catalog.ts
14081
+ /**
14082
+ * Per-device value catalogs for wireable fields (`status.fieldEnums` on a cap).
14083
+ *
14084
+ * A status field such as `error.code` or `event-emitter.lastEvent.eventType` is a
14085
+ * plain string in the schema, but the device's integration DECLARES the closed set
14086
+ * of values at runtime (`error.listFaultTypes`, the event vocabulary). This module
14087
+ * asks the device's own provider and returns the values the editor offers as a
14088
+ * dropdown. A read that fails answers `null` — the caller leaves `enumValues`
14089
+ * absent (free text stays) and logs; it is never an empty list (D393, D315).
14090
+ */
14091
+ var RecordSchema = z.record(z.string(), z.unknown());
14092
+ function isProviderShape(value) {
14093
+ return typeof value === "object" && value !== null;
14094
+ }
14095
+ function listOf(answer, source) {
14096
+ const record = RecordSchema.safeParse(answer);
14097
+ if (!record.success) return null;
14098
+ const list = z.array(RecordSchema).safeParse(record.data[source.listKey]);
14099
+ if (!list.success) return null;
14100
+ const values = [];
14101
+ for (const entry of list.data) {
14102
+ const value = entry[source.valueKey];
14103
+ if (typeof value !== "string") return null;
14104
+ if (!values.includes(value)) values.push(value);
14105
+ }
14106
+ return values;
14107
+ }
14108
+ async function readAnswer(provider, source, deviceId) {
14109
+ const fn = provider[source.from === "method" ? source.method : "getStatus"];
14110
+ if (typeof fn !== "function") return void 0;
14111
+ return await Reflect.apply(fn, provider, [{ deviceId }]);
14112
+ }
14113
+ var TIMED_OUT = Symbol("catalog-read-timed-out");
14114
+ async function raceBudget(work, budgetMs) {
14115
+ let timer;
14116
+ const deadline = new Promise((resolve) => {
14117
+ timer = setTimeout(() => resolve(TIMED_OUT), budgetMs);
14118
+ timer.unref?.();
14119
+ });
14120
+ try {
14121
+ return await Promise.race([work, deadline]);
14122
+ } finally {
14123
+ if (timer !== void 0) clearTimeout(timer);
14124
+ }
14125
+ }
14126
+ /**
14127
+ * The device's declared values for one field, or `null` when there are none to
14128
+ * offer. A provider without the catalog, a cold (null) slice or an empty catalog
14129
+ * is a quiet absence; a thrown read, a timeout or a malformed answer is warned
14130
+ * with the device tag. Either way the field stays free text.
14131
+ */
14132
+ async function readFieldCatalog(read) {
14133
+ const { registry, logger, capName, deviceId, path, source, budgetMs } = read;
14134
+ try {
14135
+ const provider = registry.getProviderForDevice(capName, deviceId);
14136
+ if (!isProviderShape(provider)) return null;
14137
+ const answer = await raceBudget(readAnswer(provider, source, deviceId), budgetMs);
14138
+ if (answer === TIMED_OUT) {
14139
+ logger.warn("wireable field catalog: read timed out, field stays free text", {
14140
+ tags: { deviceId },
14141
+ meta: {
14142
+ deviceId,
14143
+ capName,
14144
+ path,
14145
+ budgetMs
14146
+ }
14147
+ });
14148
+ return null;
14149
+ }
14150
+ if (answer === void 0 || answer === null) return null;
14151
+ const values = listOf(answer, source);
14152
+ if (values === null) {
14153
+ logger.warn("wireable field catalog: answer has an unexpected shape", {
14154
+ tags: { deviceId },
14155
+ meta: {
14156
+ deviceId,
14157
+ capName,
14158
+ path
14159
+ }
14160
+ });
14161
+ return null;
14162
+ }
14163
+ return values.length > 0 ? values : null;
14164
+ } catch (err) {
14165
+ logger.warn("wireable field catalog: read failed, field stays free text", {
14166
+ tags: { deviceId },
14167
+ meta: {
14168
+ deviceId,
14169
+ capName,
14170
+ path,
14171
+ error: err instanceof Error ? err.message : String(err)
14172
+ }
14173
+ });
14174
+ return null;
14175
+ }
14176
+ }
14177
+ //#endregion
13491
14178
  //#region src/builtins/device-manager/device-aggregation-merge.ts
13492
14179
  /**
13493
14180
  * Pure aggregator-merge + field-tagging helpers for the device-manager
@@ -13657,11 +14344,11 @@ function mergeAggregates(parts) {
13657
14344
  * per-row path (`connection.password`, `rows[].pin`) is not mapped onto a form
13658
14345
  * field and keeps the driver's hydration.
13659
14346
  */
13660
- function isRecord$3(value) {
14347
+ function isRecord$4(value) {
13661
14348
  return typeof value === "object" && value !== null && !Array.isArray(value);
13662
14349
  }
13663
14350
  function isConfigFieldWithValue(field) {
13664
- if (!isRecord$3(field)) return false;
14351
+ if (!isRecord$4(field)) return false;
13665
14352
  return typeof field.type === "string" && typeof field.key === "string" && "value" in field;
13666
14353
  }
13667
14354
  /** The declared paths that name a top-level config key. */
@@ -13669,7 +14356,7 @@ function topLevelKeys(paths) {
13669
14356
  return new Set(paths.filter((p) => p.length > 0 && !p.includes(".") && !p.includes("[")));
13670
14357
  }
13671
14358
  function viewField(field, stored, declared) {
13672
- if (!isRecord$3(field)) return field;
14359
+ if (!isRecord$4(field)) return field;
13673
14360
  const nested = field["fields"];
13674
14361
  if (Array.isArray(nested)) return {
13675
14362
  ...field,
@@ -13678,7 +14365,7 @@ function viewField(field, stored, declared) {
13678
14365
  const tabs = field["tabs"];
13679
14366
  if (Array.isArray(tabs)) return {
13680
14367
  ...field,
13681
- tabs: tabs.map((tab) => isRecord$3(tab) && Array.isArray(tab["fields"]) ? {
14368
+ tabs: tabs.map((tab) => isRecord$4(tab) && Array.isArray(tab["fields"]) ? {
13682
14369
  ...tab,
13683
14370
  fields: tab["fields"].map((f) => viewField(f, stored, declared))
13684
14371
  } : tab)
@@ -13787,7 +14474,7 @@ function isDeclaredCollectionCap(capName) {
13787
14474
  function isDeclaredNonWrapperCap(capName) {
13788
14475
  return DECLARED_NON_WRAPPER_CAPS.has(capName);
13789
14476
  }
13790
- function isRecord$2(value) {
14477
+ function isRecord$3(value) {
13791
14478
  return typeof value === "object" && value !== null && !Array.isArray(value);
13792
14479
  }
13793
14480
  /** A persisted activation of a wrapper on a cap that has none (see module docblock). */
@@ -13830,12 +14517,12 @@ var StaleWrapperActivations = class {
13830
14517
  if (this.checked) return;
13831
14518
  this.checked = true;
13832
14519
  const devices = store.deviceBindings;
13833
- if (!isRecord$2(devices)) return;
14520
+ if (!isRecord$3(devices)) return;
13834
14521
  for (const [deviceKey, perDevice] of Object.entries(devices)) {
13835
14522
  const deviceId = Number(deviceKey);
13836
- if (!Number.isInteger(deviceId) || !isRecord$2(perDevice)) continue;
14523
+ if (!Number.isInteger(deviceId) || !isRecord$3(perDevice)) continue;
13837
14524
  for (const [capName, row] of Object.entries(perDevice)) {
13838
- const wrapperAddonId = isRecord$2(row) ? row["wrapperAddonId"] : void 0;
14525
+ const wrapperAddonId = isRecord$3(row) ? row["wrapperAddonId"] : void 0;
13839
14526
  if (typeof wrapperAddonId === "string" && isDeclaredNonWrapperCap(capName)) this.report(deviceId, capName, wrapperAddonId);
13840
14527
  }
13841
14528
  }
@@ -15488,6 +16175,7 @@ async function readDeviceConfigs(pctx, deviceIds) {
15488
16175
  return pctx.settings.readDeviceStoreBatch(deviceIds);
15489
16176
  }
15490
16177
  async function listAll(pctx, input) {
16178
+ await pctx.freshTagNames();
15491
16179
  const ownerFilter = Reflect.get(input, "addonId");
15492
16180
  if (ownerFilter !== void 0 && (typeof ownerFilter !== "string" || ownerFilter.length === 0)) throw new Error(`deviceManager.listAll: addonId must be a non-empty string or be omitted — got ${JSON.stringify(ownerFilter)}. An owner filter that is present but empty is never widened to every device. On an addon context the id is \`ctx.id\`; there is no \`ctx.addonId\`.`);
15493
16181
  const callerAddonId = pctx.metaStore.rows.censusArmed ? extractCallerAddonId(input) : void 0;
@@ -15575,6 +16263,7 @@ async function listAll(pctx, input) {
15575
16263
  }
15576
16264
  async function getDevice(pctx, input) {
15577
16265
  const { deviceId } = input;
16266
+ await pctx.freshTagNames();
15578
16267
  if (pctx.registry) {
15579
16268
  const found = resolveDeviceById(pctx.registry, deviceId);
15580
16269
  if (found) {
@@ -17169,6 +17858,36 @@ function wireableEntryForDef(capName, def) {
17169
17858
  };
17170
17859
  }
17171
17860
  /**
17861
+ * Fill `enumValues` of the fields the cap declares a per-device catalog for
17862
+ * (`status.fieldEnums`) from the device's own provider. A failed or empty read
17863
+ * leaves the field untouched (free text), never an empty list.
17864
+ */
17865
+ async function withDeclaredCatalogs(deps, registry, deviceId, entry, def) {
17866
+ const declared = def.status?.fieldEnums;
17867
+ if (!declared) return entry;
17868
+ const fields = await Promise.all(entry.fields.map(async (field) => {
17869
+ const source = declared[field.path];
17870
+ if (!source || field.item === true) return field;
17871
+ const values = await readFieldCatalog({
17872
+ registry,
17873
+ logger: deps.ctx.logger,
17874
+ capName: entry.cap,
17875
+ deviceId,
17876
+ path: field.path,
17877
+ source,
17878
+ budgetMs: CONTRIBUTION_BUDGET_MS
17879
+ });
17880
+ return values === null ? field : {
17881
+ ...field,
17882
+ enumValues: values
17883
+ };
17884
+ }));
17885
+ return {
17886
+ ...entry,
17887
+ fields
17888
+ };
17889
+ }
17890
+ /**
17172
17891
  * Per-device wireable-field catalog — the domain status fields a device's
17173
17892
  * bound caps expose, for the operator's cross-device wiring UI. Binding-driven:
17174
17893
  * walks `getBindings(deviceId)`, skips wrapper caps (their status schemas are
@@ -17189,14 +17908,19 @@ async function getWireableFields(deps, input) {
17189
17908
  const { entries } = await getBindings(deps.bindingsDeps, { deviceId });
17190
17909
  const seen = /* @__PURE__ */ new Set();
17191
17910
  const caps = [];
17911
+ const pending = [];
17192
17912
  for (const entry of entries) {
17193
17913
  if (seen.has(entry.capName)) continue;
17194
17914
  seen.add(entry.capName);
17195
17915
  const def = reg.getDefinition(entry.capName);
17196
17916
  if (!def || def.kind === "wrapper") continue;
17197
17917
  const wireable = wireableEntryForDef(entry.capName, def);
17198
- if (wireable) caps.push(wireable);
17918
+ if (wireable) pending.push({
17919
+ wireable,
17920
+ def
17921
+ });
17199
17922
  }
17923
+ caps.push(...await Promise.all(pending.map(({ wireable, def }) => withDeclaredCatalogs(deps, reg, deviceId, wireable, def))));
17200
17924
  if (input.includeSynthesizable === true) {
17201
17925
  const deviceType = (await deps.bindingsDeps.rows.get(deviceId))?.meta.type;
17202
17926
  if (deviceType !== void 0) for (const def of ALL_CAPABILITY_DEFINITIONS) {
@@ -17394,8 +18118,9 @@ async function searchDevices(deps, input) {
17394
18118
  let compatibleTotal = 0;
17395
18119
  let hiddenIncompatible = 0;
17396
18120
  const filters = input.filters;
18121
+ const locationFilter = filters?.locations?.map((value) => deps.roomNameOf?.(value) ?? value);
17397
18122
  for (const c of textPass) {
17398
- const okLocation = matches(filters?.locations, c.device.location);
18123
+ const okLocation = matches(locationFilter, c.device.location);
17399
18124
  const okIntegration = matches(filters?.integrationIds, c.integrationId);
17400
18125
  const okType = matches(filters?.types, c.device.type);
17401
18126
  if (c.compatible) {
@@ -17728,7 +18453,7 @@ async function setWrapperActive(deps, input) {
17728
18453
  }
17729
18454
  });
17730
18455
  }
17731
- function isRecord$1(value) {
18456
+ function isRecord$2(value) {
17732
18457
  return typeof value === "object" && value !== null && !Array.isArray(value);
17733
18458
  }
17734
18459
  /** The key of this addon's store that holds every wrapper activation. */
@@ -17768,19 +18493,19 @@ async function readWrapperActivation(deps, query) {
17768
18493
  error: "the store holds no deviceBindings row — an empty snapshot is not evidence of an unbind"
17769
18494
  };
17770
18495
  const deviceBindings = read.value;
17771
- if (!isRecord$1(deviceBindings)) return {
18496
+ if (!isRecord$2(deviceBindings)) return {
17772
18497
  kind: "failed",
17773
18498
  error: "stored deviceBindings is not a map"
17774
18499
  };
17775
18500
  const perDevice = deviceBindings[String(query.deviceId)];
17776
18501
  if (perDevice === void 0) return { kind: "missing" };
17777
- if (!isRecord$1(perDevice)) return {
18502
+ if (!isRecord$2(perDevice)) return {
17778
18503
  kind: "failed",
17779
18504
  error: `stored bindings of device ${query.deviceId} are not a map`
17780
18505
  };
17781
18506
  const activation = perDevice[query.capName];
17782
18507
  if (activation === void 0) return { kind: "missing" };
17783
- if (!isRecord$1(activation)) return {
18508
+ if (!isRecord$2(activation)) return {
17784
18509
  kind: "failed",
17785
18510
  error: `stored "${query.capName}" activation is not a record`
17786
18511
  };
@@ -18604,11 +19329,39 @@ async function loadDeviceConfigWithSecrets(ctx, input) {
18604
19329
  });
18605
19330
  return value;
18606
19331
  }
18607
- //#endregion
18608
- //#region src/builtins/device-manager/device-removal-hooks.ts
18609
19332
  /**
18610
- * device-manager's side of `device-removal-hook` (D865): tell every implementer
18611
- * a device was deleted, and answer the admin question "which stored data belongs
19333
+ * The CREATE write reaches the door before the device class exists, so the
19334
+ * paths its schema declares secret are not known yet and the blob lands raw.
19335
+ * The first registration brings those paths: move every declared TOP-LEVEL
19336
+ * secret still raw (a non-empty string, not a marker) into the keychain.
19337
+ * Only the first registration of a row — this completes the create write; a
19338
+ * re-registration of an older row converts nothing (no silent migration).
19339
+ * Returns the converted path names (never values).
19340
+ */
19341
+ async function secureRawDeclaredSecrets(deps, input) {
19342
+ if (ownerSecrets(deps.ctx, input.ownerAddonId) === null) return [];
19343
+ const stored = await deps.readStored();
19344
+ const rawKeys = input.secretPaths.filter((path) => {
19345
+ if (path.includes(".") || path.includes("[")) return false;
19346
+ const value = stored[path];
19347
+ return typeof value === "string" && value.length > 0;
19348
+ });
19349
+ if (rawKeys.length === 0) return [];
19350
+ const patch = Object.fromEntries(rawKeys.map((key) => [key, stored[key]]));
19351
+ await persistDeviceConfigWithSecrets(deps, {
19352
+ deviceId: input.deviceId,
19353
+ ownerAddonId: input.ownerAddonId,
19354
+ data: patch,
19355
+ secretPaths: rawKeys,
19356
+ operatorWrite: true
19357
+ });
19358
+ return rawKeys;
19359
+ }
19360
+ //#endregion
19361
+ //#region src/builtins/device-manager/device-removal-hooks.ts
19362
+ /**
19363
+ * device-manager's side of `device-removal-hook` (D865): tell every implementer
19364
+ * a device was deleted, and answer the admin question "which stored data belongs
18612
19365
  * to devices that no longer exist?".
18613
19366
  *
18614
19367
  * Two entry points, one rule: **an implementer is told to delete only on a
@@ -18883,7 +19636,7 @@ function nearestLocatedAncestor(byId, startParentId) {
18883
19636
  visited.add(cursor);
18884
19637
  const ancestor = byId.get(cursor);
18885
19638
  if (!ancestor) return null;
18886
- if (ancestor.location !== null) return ancestor;
19639
+ if (ancestor.locationId !== void 0 && ancestor.locationId !== null) return ancestor;
18887
19640
  cursor = ancestor.parentDeviceId;
18888
19641
  }
18889
19642
  return null;
@@ -18913,15 +19666,16 @@ function planNullLocationFills(rows) {
18913
19666
  const byId = new Map(rows.map((r) => [r.id, r]));
18914
19667
  const plan = [];
18915
19668
  for (const row of rows) {
18916
- if (row.location !== null) continue;
19669
+ if (row.locationId !== void 0 && row.locationId !== null) continue;
18917
19670
  if (row.parentDeviceId === null) continue;
18918
19671
  const hit = nearestLocatedAncestor(byId, row.parentDeviceId);
18919
19672
  if (hit === null) continue;
18920
19673
  if (hit.type !== DeviceType$1.Container) continue;
18921
- if (hit.location === null) continue;
19674
+ if (hit.locationId === void 0 || hit.locationId === null) continue;
18922
19675
  plan.push({
18923
19676
  id: row.id,
18924
19677
  location: hit.location,
19678
+ locationId: hit.locationId,
18925
19679
  ancestorId: hit.id
18926
19680
  });
18927
19681
  }
@@ -18946,7 +19700,14 @@ async function resolveInheritedLocation(rows, parentDeviceId) {
18946
19700
  visited.add(cursor);
18947
19701
  const ancestor = await rows.get(cursor);
18948
19702
  if (ancestor === null) return null;
18949
- if (ancestor.meta.location !== null) return ancestor.meta.type === DeviceType$1.Container ? ancestor.meta.location : null;
19703
+ const locationId = ancestor.meta.locationId ?? null;
19704
+ if (locationId !== null) {
19705
+ if (ancestor.meta.type !== DeviceType$1.Container) return null;
19706
+ return {
19707
+ locationId,
19708
+ location: ancestor.meta.location
19709
+ };
19710
+ }
18950
19711
  cursor = ancestor.meta.parentDeviceId;
18951
19712
  }
18952
19713
  return null;
@@ -18981,8 +19742,8 @@ async function runLocationBackfillAtBoot(pctx, bootRows) {
18981
19742
  const plan = planNullLocationFills((await pctx.metaStore.rows.listAll()).map((r) => r.meta));
18982
19743
  for (const fill of plan) try {
18983
19744
  const current = await pctx.metaStore.rows.get(fill.id);
18984
- if (current === null || current.meta.location !== null) continue;
18985
- await pctx.metaStore.rows.patch(fill.id, { location: fill.location });
19745
+ if (current === null || (current.meta.locationId ?? null) !== null) continue;
19746
+ await pctx.metaStore.rows.patch(fill.id, { locationId: fill.locationId });
18986
19747
  patched.push(fill);
18987
19748
  } catch (err) {
18988
19749
  failed.push({
@@ -19195,8 +19956,9 @@ async function migrateDevice$1(deps, input) {
19195
19956
  alarmPartialMigration(deps, ids, "swapIds", err);
19196
19957
  throw err;
19197
19958
  }
19959
+ let secretScopes;
19198
19960
  try {
19199
- await deps.swapHardwareState(sourceId, targetId);
19961
+ secretScopes = await deps.swapHardwareState(sourceId, targetId);
19200
19962
  } catch (err) {
19201
19963
  alarmPartialMigration(deps, ids, "swapHardwareState", err);
19202
19964
  throw err;
@@ -19222,7 +19984,8 @@ async function migrateDevice$1(deps, input) {
19222
19984
  targetId,
19223
19985
  switches: [...down, ...up],
19224
19986
  sourceStillLive,
19225
- swapped: true
19987
+ swapped: true,
19988
+ secretScopes
19226
19989
  };
19227
19990
  }
19228
19991
  //#endregion
@@ -19259,6 +20022,15 @@ async function migrateDevice$1(deps, input) {
19259
20022
  * stream-profile assignment (the live authority is the stream broker's own
19260
20023
  * map — see `StreamsTab.tsx`, which stopped writing it), and either copy
19261
20024
  * names stream ids of the wrong hardware after a swap.
20025
+ * - A secret marker inside the swapped config names the keychain scope of ONE
20026
+ * number (`secret://<owner>/device/<id>/<field>`; the ref is the AAD of the
20027
+ * ciphertext). Swapping the marker alone left each number pointing at the
20028
+ * other's scope, so removing either device purged the secret the other still
20029
+ * used (D1093, live 2026-11-23). The configs swap with their markers
20030
+ * unchanged (each still reads its value), then `repairCrossedSecretScopes`
20031
+ * brings every value under the number whose config holds it, through staged
20032
+ * copies, so a crash at any step is finished by a re-run of the repair.
20033
+ * - The location (room) is role state and stays on the number (`swapIds`).
19262
20034
  * - The runtime-state blobs (`__device-state:<id>` — battery snapshot, sleep
19263
20035
  * flag, feature probe) SWAP wholesale: every slice mirrors the box — never
19264
20036
  * while either carries `$owned` (D663): the migration is refused first
@@ -19384,11 +20156,21 @@ function splitConfig(config) {
19384
20156
  * incident this module exists to prevent, and it must never be reported as a
19385
20157
  * success.
19386
20158
  */
19387
- async function swapHardwareState(settings, sourceId, targetId) {
20159
+ async function swapHardwareState(settings, sourceId, targetId, secrets) {
19388
20160
  const sourceConfig = await settings.readDeviceStore(sourceId);
19389
20161
  const targetConfig = await settings.readDeviceStore(targetId);
20162
+ const crossed = [{
20163
+ deviceId: sourceId,
20164
+ markers: crossedIn(sourceConfig, targetId)
20165
+ }, {
20166
+ deviceId: targetId,
20167
+ markers: crossedIn(targetConfig, sourceId)
20168
+ }].filter((c) => c.markers > 0);
20169
+ if (crossed.length > 0) throw new Error(new SecretScopesCrossedError(sourceId, targetId, crossed).message);
19390
20170
  const source = splitConfig(sourceConfig);
19391
20171
  const target = splitConfig(targetConfig);
20172
+ const marked = hasDeviceMarkers(source.hardware, sourceId, targetId) || hasDeviceMarkers(target.hardware, sourceId, targetId);
20173
+ if (secrets === void 0 && marked) throw new Error(`keychain door unavailable - devices ${sourceId} and ${targetId} hold keychain secrets and the migration cannot move them; nothing was changed`);
19392
20174
  await settings.clearDeviceStore(sourceId);
19393
20175
  await settings.writeDeviceStore(sourceId, {
19394
20176
  ...target.hardware,
@@ -19403,14 +20185,216 @@ async function swapHardwareState(settings, sourceId, targetId) {
19403
20185
  const targetRuntimeState = await settings.readDeviceRuntimeState(targetId);
19404
20186
  await settings.writeDeviceRuntimeState(sourceId, targetRuntimeState);
19405
20187
  await settings.writeDeviceRuntimeState(targetId, sourceRuntimeState);
20188
+ let secretScopes = {
20189
+ exchanged: false,
20190
+ markersRepointed: 0,
20191
+ refsAtSource: [],
20192
+ refsAtTarget: []
20193
+ };
20194
+ if (marked) try {
20195
+ const repaired = await repairCrossedSecretScopes(settings, secrets, sourceId, targetId, true);
20196
+ secretScopes = {
20197
+ exchanged: repaired.outcome === "repaired",
20198
+ markersRepointed: repaired.markersRepointedAtA + repaired.markersRepointedAtB,
20199
+ refsAtSource: repaired.refsNowAtA,
20200
+ refsAtTarget: repaired.refsNowAtB
20201
+ };
20202
+ } catch (err) {
20203
+ throw new Error(`migration: configs swapped but the secrets are not yet under their own numbers (${err instanceof Error ? err.message : String(err)}); every marker still reads its value - run deviceManager.repairMigrationSecrets { deviceA: ${sourceId}, deviceB: ${targetId}, apply: true }`, { cause: err });
20204
+ }
19406
20205
  return {
19407
20206
  runtimeStateNowAtSource: targetRuntimeState,
19408
20207
  runtimeStateNowAtTarget: sourceRuntimeState,
19409
20208
  hardwareKeysToSource: Object.keys(target.hardware).toSorted(),
19410
20209
  hardwareKeysToTarget: Object.keys(source.hardware).toSorted(),
19411
20210
  roleKeysKeptAtSource: Object.keys(source.role).toSorted(),
19412
- roleKeysKeptAtTarget: Object.keys(target.role).toSorted()
20211
+ roleKeysKeptAtTarget: Object.keys(target.role).toSorted(),
20212
+ secretScopes
20213
+ };
20214
+ }
20215
+ /** The suffix of the staging copy a repair keeps while a value changes scope. */
20216
+ var REPAIR_STAGING_SUFFIX = "~repair";
20217
+ function refWithin(parts, deviceId, fieldPath) {
20218
+ return buildSecretRef({
20219
+ ...parts,
20220
+ scope: {
20221
+ kind: "device",
20222
+ deviceId
20223
+ },
20224
+ fieldPath
20225
+ });
20226
+ }
20227
+ /**
20228
+ * The markers of `config` (the config of `ownId`) the repair must move: those
20229
+ * naming `otherId`'s scope, and the staging copies of an interrupted run.
20230
+ */
20231
+ function repairMarkers(config, ownId, otherId) {
20232
+ const found = [];
20233
+ for (const current of collectMarkerRefs(config)) {
20234
+ const parts = parseSecretRef(current);
20235
+ if (parts === null || parts.scope.kind !== "device") continue;
20236
+ const staged = parts.fieldPath.endsWith(REPAIR_STAGING_SUFFIX);
20237
+ if (!(parts.scope.deviceId === otherId || staged && parts.scope.deviceId === ownId)) continue;
20238
+ const fieldPath = staged ? parts.fieldPath.slice(0, -7) : parts.fieldPath;
20239
+ found.push({
20240
+ current,
20241
+ staging: staged ? current : refWithin(parts, ownId, `${fieldPath}${REPAIR_STAGING_SUFFIX}`),
20242
+ dest: refWithin(parts, ownId, fieldPath),
20243
+ owner: parts.owner,
20244
+ staged
20245
+ });
20246
+ }
20247
+ return found;
20248
+ }
20249
+ /**
20250
+ * Repair a pair a migration left with CROSSED secrets (it ran before the
20251
+ * secrets followed the config): a number's config carries markers naming the
20252
+ * OTHER number's keychain scope, so removing either device would purge the
20253
+ * secret the other still reads. Each such marker's value is brought under the
20254
+ * number whose config holds it.
20255
+ *
20256
+ * The configs ARE the state machine, so a crash at any step is re-run to the
20257
+ * right end state — never a double exchange, never a value lost:
20258
+ * 1. stage: copy each value to a staging ref in its own number's scope
20259
+ * (idempotent puts; the originals are untouched);
20260
+ * 2. point both configs at the staging refs — from here every marker reads a
20261
+ * value that is not about to be overwritten;
20262
+ * 3. put each value at its end ref (idempotent: the source is the staging ref);
20263
+ * 4. point both configs at the end refs;
20264
+ * 5. delete the staging refs and any original no config names any more.
20265
+ * A re-run reads each marker's CURRENT ref, so a marker already at a staging
20266
+ * or end ref continues from there. One-sided pairs and a pair where only some
20267
+ * fields are crossed work the same way, field by field.
20268
+ *
20269
+ * Idempotent: a pair with no marker to move is left alone. `apply: false` is
20270
+ * the dry run: counts only. A missing keychain door with markers to move THROWS.
20271
+ */
20272
+ async function repairCrossedSecretScopes(settings, secrets, deviceA, deviceB, apply) {
20273
+ const configA = await settings.readDeviceStore(deviceA);
20274
+ const configB = await settings.readDeviceStore(deviceB);
20275
+ const markersA = repairMarkers(configA, deviceA, deviceB);
20276
+ const markersB = repairMarkers(configB, deviceB, deviceA);
20277
+ const counts = {
20278
+ markersRepointedAtA: markersA.length,
20279
+ markersRepointedAtB: markersB.length
20280
+ };
20281
+ if (markersA.length === 0 && markersB.length === 0) return {
20282
+ outcome: "nothing-to-repair",
20283
+ ...counts,
20284
+ refsNowAtA: [],
20285
+ refsNowAtB: []
20286
+ };
20287
+ if (secrets === void 0) throw new Error(`repairMigrationSecrets: no keychain door on this node — devices ${deviceA} and ${deviceB} hold markers that must move; nothing was changed`);
20288
+ if (!apply) return {
20289
+ outcome: "would-repair",
20290
+ ...counts,
20291
+ refsNowAtA: [],
20292
+ refsNowAtB: []
20293
+ };
20294
+ const all = [...markersA, ...markersB];
20295
+ const valueOf = async (owner, ref) => {
20296
+ const answer = (await secrets.forOwner(owner).resolve([ref]))[ref];
20297
+ if (answer?.kind === "value") return answer.value;
20298
+ throw new Error(`repairMigrationSecrets: ${ref} cannot be read (${answer?.kind ?? "no answer"}); nothing was changed`);
20299
+ };
20300
+ const rewritten = (pick) => {
20301
+ const mapOf = (markers) => {
20302
+ const byCurrent = new Map(markers.map((m) => [m.current, pick(m)]));
20303
+ return (ref) => byCurrent.get(ref);
20304
+ };
20305
+ return [rewriteMarkerRefs(configA, mapOf(markersA)), rewriteMarkerRefs(configB, mapOf(markersB))];
20306
+ };
20307
+ const writeBoth = async (pick) => {
20308
+ const [nextA, nextB] = rewritten(pick);
20309
+ await settings.writeDeviceStore(deviceA, nextA);
20310
+ await settings.writeDeviceStore(deviceB, nextB);
20311
+ };
20312
+ for (const m of all) if (!m.staged) await secrets.forOwner(m.owner).put(m.staging, await valueOf(m.owner, m.current));
20313
+ await writeBoth((m) => m.staging);
20314
+ for (const m of all) await secrets.forOwner(m.owner).put(m.dest, await valueOf(m.owner, m.staging));
20315
+ await writeBoth((m) => m.dest);
20316
+ const finalRefs = new Set(rewritten((m) => m.dest).flatMap(collectMarkerRefs));
20317
+ for (const m of all) {
20318
+ const stale = [m.staging, ...m.staged || finalRefs.has(m.current) ? [] : [m.current]];
20319
+ await secrets.forOwner(m.owner).delete(stale);
20320
+ }
20321
+ for (const ref of finalRefs) {
20322
+ const parts = parseSecretRef(ref);
20323
+ if (parts === null || parts.scope.kind !== "device") continue;
20324
+ const strays = [deviceA, deviceB].map((id) => refWithin(parts, id, `${parts.fieldPath.replace(/~repair$/, "")}${REPAIR_STAGING_SUFFIX}`)).filter((stray) => !finalRefs.has(stray));
20325
+ await secrets.forOwner(parts.owner).delete(strays);
20326
+ }
20327
+ return {
20328
+ outcome: "repaired",
20329
+ ...counts,
20330
+ refsNowAtA: markersA.map((m) => m.dest),
20331
+ refsNowAtB: markersB.map((m) => m.dest)
20332
+ };
20333
+ }
20334
+ /**
20335
+ * The refusal of a migration over a pair whose configs hold markers naming the
20336
+ * OTHER number's keychain scope (an earlier migration crossed them): swapping
20337
+ * again would mix the passwords. Nothing moved; run the repair first.
20338
+ */
20339
+ var SecretScopesCrossedError = class extends MigrationRefusedError {
20340
+ sourceId;
20341
+ targetId;
20342
+ crossed;
20343
+ constructor(sourceId, targetId, crossed) {
20344
+ super(`secret-scopes-crossed: migration ${sourceId} → ${targetId} refused: ${crossed.map((c) => `device ${c.deviceId} holds ${c.markers} secret marker(s) naming the other number's keychain scope`).join("; ")} — run deviceManager.repairMigrationSecrets first (nothing moved)`);
20345
+ this.sourceId = sourceId;
20346
+ this.targetId = targetId;
20347
+ this.crossed = crossed;
20348
+ this.name = "SecretScopesCrossedError";
20349
+ }
20350
+ };
20351
+ /** True when `config` holds a marker in the keychain scope of device `a` or `b`. */
20352
+ function hasDeviceMarkers(config, a, b) {
20353
+ return collectMarkerRefs(config).some((ref) => {
20354
+ const parts = parseSecretRef(ref);
20355
+ return parts !== null && parts.scope.kind === "device" && (parts.scope.deviceId === a || parts.scope.deviceId === b);
20356
+ });
20357
+ }
20358
+ function crossedIn(config, otherId) {
20359
+ return collectMarkerRefs(config).filter((ref) => {
20360
+ const parts = parseSecretRef(ref);
20361
+ return parts !== null && parts.scope.kind === "device" && parts.scope.deviceId === otherId;
20362
+ }).length;
20363
+ }
20364
+ /**
20365
+ * Refuse a migration when either config already names the other number's
20366
+ * keychain scope. Read from the stored configs (D49: an unreadable config
20367
+ * throws, never reads as "not crossed").
20368
+ */
20369
+ async function assertNoCrossedSecretScopes(settings, sourceId, targetId) {
20370
+ const crossed = [{
20371
+ deviceId: sourceId,
20372
+ markers: crossedIn(await settings.readDeviceStore(sourceId), targetId)
20373
+ }, {
20374
+ deviceId: targetId,
20375
+ markers: crossedIn(await settings.readDeviceStore(targetId), sourceId)
20376
+ }].filter((c) => c.markers > 0);
20377
+ if (crossed.length > 0) throw new SecretScopesCrossedError(sourceId, targetId, crossed);
20378
+ }
20379
+ /** Every secret marker's ref in a config, at any depth. */
20380
+ function collectMarkerRefs(value) {
20381
+ if (Array.isArray(value)) return value.flatMap(collectMarkerRefs);
20382
+ if (isSecretMarker(value)) return [value.$secret];
20383
+ if (isRecord$1(value)) return Object.values(value).flatMap(collectMarkerRefs);
20384
+ return [];
20385
+ }
20386
+ /** A copy of `value` whose markers name `map(ref)` where it answers (others untouched). */
20387
+ function rewriteMarkerRefs(value, map) {
20388
+ const walk = (node) => {
20389
+ if (Array.isArray(node)) return node.map(walk);
20390
+ if (isSecretMarker(node)) return makeSecretMarker(map(node.$secret) ?? node.$secret);
20391
+ if (isRecord$1(node)) return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, walk(v)]));
20392
+ return node;
19413
20393
  };
20394
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, walk(v)]));
20395
+ }
20396
+ function isRecord$1(value) {
20397
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19414
20398
  }
19415
20399
  //#endregion
19416
20400
  //#region src/builtins/device-manager/migrate-reload.ts
@@ -19459,6 +20443,274 @@ async function reloadMigratedDevices(pctx, targets) {
19459
20443
  }));
19460
20444
  }
19461
20445
  //#endregion
20446
+ //#region src/builtins/device-manager/room-actions.ts
20447
+ /**
20448
+ * Rooms and site zones as records with an id (D1089).
20449
+ *
20450
+ * The entity methods (`ensureRoom`, `listRooms`, `updateRoom`, `deleteRoom`) are
20451
+ * the model: a rename, a new icon or a new description is ONE write to ONE
20452
+ * `rooms` record, and no device is rewritten (a device meta carries only
20453
+ * `locationId`; its `location` name is derived at read). A delete clears the
20454
+ * references in one operation.
20455
+ *
20456
+ * Everything else here — `listLocations`, `addLocation`, `removeLocation`,
20457
+ * `renameLocation`, the icon / description maps, the site-zone methods and
20458
+ * `setLocationZone` — is a thin SHIM over those, answering the same shapes as
20459
+ * before so the admin UI and the viewer keep working until they move to the ids.
20460
+ * A shim is removed once nothing calls it (D1089).
20461
+ */
20462
+ /** Room record → the wire shape. */
20463
+ function toRoom(entity) {
20464
+ return entity;
20465
+ }
20466
+ function requireName(name, code, what) {
20467
+ const trimmed = name.trim();
20468
+ if (trimmed.length === 0) throw userError(code, void 0, `[device-manager] ${what}: name must be non-empty`);
20469
+ return trimmed;
20470
+ }
20471
+ /** Drop a field when the patch says `null`, keep it when absent, set it otherwise. */
20472
+ function applied(patch, current) {
20473
+ if (patch === void 0) return current;
20474
+ if (patch === null) return void 0;
20475
+ return patch;
20476
+ }
20477
+ function emitLocationChanged(pctx, deviceId, value) {
20478
+ pctx.host.ctx.eventBus.emit({
20479
+ id: randomUUID(),
20480
+ timestamp: /* @__PURE__ */ new Date(),
20481
+ source: {
20482
+ type: "device",
20483
+ id: deviceId
20484
+ },
20485
+ category: EventCategory$1.DeviceMetaChanged,
20486
+ data: {
20487
+ deviceId,
20488
+ field: "location",
20489
+ value
20490
+ }
20491
+ });
20492
+ }
20493
+ /** The ids of every device whose room is `roomId`. */
20494
+ async function devicesInRoom(pctx, roomId) {
20495
+ return (await pctx.metaStore.rows.listAll()).filter((row) => row.meta.locationId === roomId).map((row) => row.meta.id);
20496
+ }
20497
+ async function ensureRoom(pctx, input) {
20498
+ const name = requireName(input.name, "system.location-name-required", "ensureRoom");
20499
+ return toRoom(await pctx.rooms.rooms.ensure(name, {}));
20500
+ }
20501
+ async function listRooms(pctx) {
20502
+ return pctx.rooms.rooms.list().map(toRoom);
20503
+ }
20504
+ async function updateRoom(pctx, input) {
20505
+ const { id, patch } = input;
20506
+ const before = pctx.rooms.rooms.get(id);
20507
+ let updated;
20508
+ try {
20509
+ updated = await pctx.rooms.rooms.update(id, (current) => {
20510
+ return {
20511
+ name: patch.name ?? current.name,
20512
+ icon: applied(patch.icon, current.icon),
20513
+ description: applied(patch.description, current.description),
20514
+ zoneId: applied(patch.zoneId, current.zoneId),
20515
+ colour: applied(patch.colour, current.colour),
20516
+ order: applied(patch.order, current.order)
20517
+ };
20518
+ });
20519
+ } catch (err) {
20520
+ if (err instanceof EntityNotFoundError) throw userError("system.room-not-found", void 0, `[device-manager] room not found: ${id}`);
20521
+ if (err instanceof EntityNameTakenError) throw userError("system.room-name-taken", void 0, `[device-manager] ${err.message}`);
20522
+ throw err;
20523
+ }
20524
+ if (before !== null && before.name !== updated.name) for (const deviceId of await devicesInRoom(pctx, id)) emitLocationChanged(pctx, deviceId, updated.name);
20525
+ return toRoom(updated);
20526
+ }
20527
+ async function deleteRoom(pctx, input) {
20528
+ if (!await pctx.rooms.rooms.delete(input.id)) return { cleared: 0 };
20529
+ const cleared = await pctx.metaStore.withMetaWriteLock(async () => {
20530
+ const out = [];
20531
+ for (const row of await pctx.metaStore.rows.listAll()) {
20532
+ if (row.meta.locationId !== input.id) continue;
20533
+ await pctx.metaStore.rows.patch(row.meta.id, { locationId: null });
20534
+ out.push(row.meta.id);
20535
+ }
20536
+ return out;
20537
+ });
20538
+ for (const deviceId of cleared) emitLocationChanged(pctx, deviceId, null);
20539
+ return { cleared: cleared.length };
20540
+ }
20541
+ /**
20542
+ * The id a write names: `locationId` wins, else `location` (text) is resolved
20543
+ * through `ensureRoom`. `undefined` = the caller named neither, `null` = clear.
20544
+ */
20545
+ async function resolveRoomId(pctx, input) {
20546
+ if (input.locationId !== void 0) {
20547
+ if (input.locationId !== null && pctx.rooms.rooms.get(input.locationId) === null) throw userError("system.room-not-found", void 0, `[device-manager] room not found: ${input.locationId}`);
20548
+ return input.locationId;
20549
+ }
20550
+ if (input.location === void 0) return void 0;
20551
+ if (input.location === null || input.location.trim().length === 0) return null;
20552
+ return (await pctx.rooms.rooms.ensure(input.location.trim(), {})).id;
20553
+ }
20554
+ async function listLocations(pctx) {
20555
+ return pctx.rooms.rooms.list().map((room) => room.name).toSorted((a, b) => a.localeCompare(b, void 0, { sensitivity: "base" }));
20556
+ }
20557
+ async function addLocation(pctx, input) {
20558
+ const name = requireName(input.name, "system.location-name-required", "addLocation");
20559
+ await pctx.rooms.rooms.ensure(name, {});
20560
+ }
20561
+ async function removeLocation(pctx, input) {
20562
+ const room = pctx.rooms.rooms.findByName(input.name);
20563
+ if (room === null) return;
20564
+ if (input.cascade === true) {
20565
+ await deleteRoom(pctx, { id: room.id });
20566
+ return;
20567
+ }
20568
+ if ((await devicesInRoom(pctx, room.id)).length > 0) {
20569
+ await updateRoom(pctx, {
20570
+ id: room.id,
20571
+ patch: {
20572
+ icon: null,
20573
+ description: null,
20574
+ zoneId: null
20575
+ }
20576
+ });
20577
+ return;
20578
+ }
20579
+ await pctx.rooms.rooms.delete(room.id);
20580
+ }
20581
+ async function renameLocation(pctx, input) {
20582
+ const from = requireName(input.from, "system.location-name-required", "renameLocation");
20583
+ const to = requireName(input.to, "system.location-name-required", "renameLocation");
20584
+ const source = pctx.rooms.rooms.findByName(from);
20585
+ if (source === null) return { moved: 0 };
20586
+ const target = pctx.rooms.rooms.findByName(to);
20587
+ if (target === null || target.id === source.id) {
20588
+ await updateRoom(pctx, {
20589
+ id: source.id,
20590
+ patch: { name: to }
20591
+ });
20592
+ return { moved: (await devicesInRoom(pctx, source.id)).length };
20593
+ }
20594
+ const moved = await pctx.metaStore.withMetaWriteLock(async () => {
20595
+ const out = [];
20596
+ for (const row of await pctx.metaStore.rows.listAll()) {
20597
+ if (row.meta.locationId !== source.id) continue;
20598
+ await pctx.metaStore.rows.patch(row.meta.id, { locationId: target.id });
20599
+ out.push(row.meta.id);
20600
+ }
20601
+ return out;
20602
+ });
20603
+ await pctx.rooms.rooms.delete(source.id);
20604
+ for (const deviceId of moved) emitLocationChanged(pctx, deviceId, target.name);
20605
+ return { moved: moved.length };
20606
+ }
20607
+ async function listLocationIcons(pctx) {
20608
+ return pctx.rooms.rooms.list().flatMap((room) => room.icon === void 0 ? [] : [{
20609
+ locationKey: entityNameKey(room.name),
20610
+ icon: room.icon
20611
+ }]).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20612
+ }
20613
+ async function setLocationIcon(pctx, input) {
20614
+ const name = requireName(input.location, "system.location-required", "setLocationIcon");
20615
+ const existing = pctx.rooms.rooms.findByName(name);
20616
+ if (existing === null && input.icon === null) return;
20617
+ const room = existing ?? await pctx.rooms.rooms.ensure(name, {});
20618
+ const icon = input.icon;
20619
+ await updateRoom(pctx, {
20620
+ id: room.id,
20621
+ patch: { icon }
20622
+ });
20623
+ }
20624
+ async function listLocationDescriptions(pctx) {
20625
+ return pctx.rooms.rooms.list().flatMap((room) => room.description === void 0 ? [] : [{
20626
+ locationKey: entityNameKey(room.name),
20627
+ description: room.description
20628
+ }]).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20629
+ }
20630
+ async function setLocationDescription(pctx, input) {
20631
+ const name = requireName(input.location, "system.location-required", "setLocationDescription");
20632
+ const text = input.description === null ? "" : input.description.trim();
20633
+ const existing = pctx.rooms.rooms.findByName(name);
20634
+ if (existing === null && text.length === 0) return;
20635
+ await updateRoom(pctx, {
20636
+ id: (existing ?? await pctx.rooms.rooms.ensure(name, {})).id,
20637
+ patch: { description: text.length === 0 ? null : text }
20638
+ });
20639
+ }
20640
+ function zoneFolded(zone) {
20641
+ return entityNameKey(zone.name);
20642
+ }
20643
+ async function listSiteZones(pctx) {
20644
+ const rooms = pctx.rooms.rooms.list();
20645
+ return pctx.rooms.zones.list().map((zone) => ({
20646
+ zoneKey: zoneFolded(zone),
20647
+ label: zone.name,
20648
+ icon: zone.icon ?? null,
20649
+ locationKeys: rooms.filter((room) => room.zoneId === zone.id).map((room) => entityNameKey(room.name)).toSorted((a, b) => a.localeCompare(b))
20650
+ })).toSorted((a, b) => a.zoneKey.localeCompare(b.zoneKey));
20651
+ }
20652
+ async function setSiteZone(pctx, input) {
20653
+ const label = requireName(input.name, "system.site-zone-name-required", "setSiteZone");
20654
+ const zone = await pctx.rooms.zones.ensure(label, {});
20655
+ await pctx.rooms.zones.update(zone.id, (current) => {
20656
+ const next = { name: label };
20657
+ const icon = input.icon === void 0 ? current.icon : input.icon === null ? void 0 : input.icon;
20658
+ if (icon !== void 0) next.icon = icon;
20659
+ return next;
20660
+ });
20661
+ }
20662
+ /** Clear `zoneId` on every room that names `zoneId`; one record write per room. */
20663
+ async function detachRooms(pctx, zoneId, to) {
20664
+ for (const room of pctx.rooms.rooms.list()) {
20665
+ if (room.zoneId !== zoneId) continue;
20666
+ await updateRoom(pctx, {
20667
+ id: room.id,
20668
+ patch: { zoneId: to }
20669
+ });
20670
+ }
20671
+ }
20672
+ async function removeSiteZone(pctx, input) {
20673
+ const zone = pctx.rooms.zones.findByName(input.name);
20674
+ if (zone === null) return;
20675
+ await detachRooms(pctx, zone.id, null);
20676
+ await pctx.rooms.zones.delete(zone.id);
20677
+ }
20678
+ async function renameSiteZone(pctx, input) {
20679
+ const to = requireName(input.to, "system.site-zone-name-required", "renameSiteZone");
20680
+ const source = pctx.rooms.zones.findByName(input.from);
20681
+ if (source === null) return;
20682
+ const target = pctx.rooms.zones.findByName(to);
20683
+ if (target === null || target.id === source.id) {
20684
+ await pctx.rooms.zones.update(source.id, (current) => ({
20685
+ ...current,
20686
+ name: to
20687
+ }));
20688
+ return;
20689
+ }
20690
+ await detachRooms(pctx, source.id, target.id);
20691
+ await pctx.rooms.zones.delete(source.id);
20692
+ }
20693
+ async function setLocationZone(pctx, input) {
20694
+ const name = requireName(input.location, "system.location-required", "setLocationZone");
20695
+ if (input.zone === null) {
20696
+ const existing = pctx.rooms.rooms.findByName(name);
20697
+ if (existing === null || existing.zoneId === void 0) return;
20698
+ await updateRoom(pctx, {
20699
+ id: existing.id,
20700
+ patch: { zoneId: null }
20701
+ });
20702
+ return;
20703
+ }
20704
+ const zoneName = requireName(input.zone, "system.site-zone-name-required", "setLocationZone");
20705
+ const zone = await pctx.rooms.zones.ensure(zoneName, {});
20706
+ const room = await pctx.rooms.rooms.ensure(name, {});
20707
+ if (room.zoneId === zone.id) return;
20708
+ await updateRoom(pctx, {
20709
+ id: room.id,
20710
+ patch: { zoneId: zone.id }
20711
+ });
20712
+ }
20713
+ //#endregion
19462
20714
  //#region src/builtins/device-manager/device-meta-actions.ts
19463
20715
  /**
19464
20716
  * Device meta-mutation + persistence actions for the device-manager addon —
@@ -19534,6 +20786,7 @@ async function allocateDeviceId(pctx, input) {
19534
20786
  type: "generic",
19535
20787
  name: stableId,
19536
20788
  location: null,
20789
+ locationId: null,
19537
20790
  disabled: false,
19538
20791
  parentDeviceId: null,
19539
20792
  id
@@ -19628,7 +20881,16 @@ async function migrateDevice(pctx, input) {
19628
20881
  assertNoFieldClaims: async (a, b) => {
19629
20882
  try {
19630
20883
  await assertNoFieldClaims(pctx.settings, a, b);
20884
+ await assertNoCrossedSecretScopes(pctx.settings, a, b);
19631
20885
  } catch (err) {
20886
+ if (err instanceof SecretScopesCrossedError) for (const c of err.crossed) ctx.logger.warn("migrateDevice refused: secret scopes crossed", {
20887
+ tags: { deviceId: c.deviceId },
20888
+ meta: {
20889
+ sourceId: a,
20890
+ targetId: b,
20891
+ markers: c.markers
20892
+ }
20893
+ });
19632
20894
  if (err instanceof FieldClaimsBlockMigrationError) for (const blocked of err.blocked) ctx.logger.warn("migrateDevice refused: fields claimed by a customization", {
19633
20895
  tags: { deviceId: blocked.deviceId },
19634
20896
  meta: {
@@ -19641,7 +20903,8 @@ async function migrateDevice(pctx, input) {
19641
20903
  }
19642
20904
  },
19643
20905
  swapHardwareState: async (a, b) => {
19644
- const swapped = await swapHardwareState(pctx.settings, a, b);
20906
+ const forOwner = pctx.host.ctx.secrets?.forOwner;
20907
+ const swapped = await swapHardwareState(pctx.settings, a, b, forOwner === void 0 || forOwner === null ? void 0 : { forOwner });
19645
20908
  pctx.host.seedMirror(a, pctx.host.withResetSessionProbe(swapped.runtimeStateNowAtSource), "replace");
19646
20909
  pctx.host.seedMirror(b, pctx.host.withResetSessionProbe(swapped.runtimeStateNowAtTarget), "replace");
19647
20910
  ctx.logger.info("migration: hardware-scoped device state swapped", {
@@ -19652,9 +20915,11 @@ async function migrateDevice(pctx, input) {
19652
20915
  hardwareKeysToSource: swapped.hardwareKeysToSource,
19653
20916
  hardwareKeysToTarget: swapped.hardwareKeysToTarget,
19654
20917
  roleKeysKeptAtSource: swapped.roleKeysKeptAtSource,
19655
- roleKeysKeptAtTarget: swapped.roleKeysKeptAtTarget
20918
+ roleKeysKeptAtTarget: swapped.roleKeysKeptAtTarget,
20919
+ secretScopes: swapped.secretScopes
19656
20920
  }
19657
20921
  });
20922
+ return swapped.secretScopes;
19658
20923
  },
19659
20924
  forgetStreamState: async (deviceId) => {
19660
20925
  await ctx.api.streamBroker.forgetDeviceHardware.mutate({ deviceId });
@@ -19738,10 +21003,10 @@ async function registerDevice(pctx, input) {
19738
21003
  deviceType: type,
19739
21004
  features: settledFeatures
19740
21005
  });
19741
- const priorLocation = existingMeta?.location ?? null;
21006
+ const priorLocationId = existingMeta?.locationId ?? null;
19742
21007
  const resolvedParentId = parentDeviceId ?? null;
19743
21008
  const parentChanged = existingMeta !== void 0 && (existingMeta.parentDeviceId ?? null) !== resolvedParentId;
19744
- const inherited = priorLocation === null && resolvedParentId !== null && (isFirst || parentChanged) ? await resolveInheritedLocation(pctx.metaStore.rows, resolvedParentId) : null;
21009
+ const inherited = priorLocationId === null && resolvedParentId !== null && (isFirst || parentChanged) ? await resolveInheritedLocation(pctx.metaStore.rows, resolvedParentId) : null;
19745
21010
  await pctx.metaStore.rows.upsertRegistration({
19746
21011
  deviceId: id,
19747
21012
  addonId,
@@ -19749,7 +21014,7 @@ async function registerDevice(pctx, input) {
19749
21014
  type,
19750
21015
  name: resolvedName,
19751
21016
  userNamed: wasUserNamed,
19752
- location: priorLocation ?? inherited,
21017
+ locationId: priorLocationId ?? inherited?.locationId ?? null,
19753
21018
  disabled: existingMeta?.disabled ?? false,
19754
21019
  parentDeviceId: resolvedParentId,
19755
21020
  registered: true,
@@ -19765,7 +21030,7 @@ async function registerDevice(pctx, input) {
19765
21030
  if (inherited !== null) for (const descendant of await collectDescendants(pctx.metaStore, id)) {
19766
21031
  if (descendant.location !== null) continue;
19767
21032
  try {
19768
- await pctx.metaStore.rows.patch(descendant.id, { location: inherited });
21033
+ await pctx.metaStore.rows.patch(descendant.id, { locationId: inherited.locationId });
19769
21034
  descendantsFilled.push(descendant.id);
19770
21035
  } catch (err) {
19771
21036
  descendantsFailed.push({
@@ -19779,7 +21044,7 @@ async function registerDevice(pctx, input) {
19779
21044
  storedFeatures: settledFeatures,
19780
21045
  exportFingerprint: fingerprint,
19781
21046
  fingerprintChanged: existingMeta?.exportFingerprint !== fingerprint,
19782
- inheritedLocation: inherited,
21047
+ inheritedLocation: inherited?.location ?? null,
19783
21048
  inheritedDescendantIds: descendantsFilled,
19784
21049
  inheritFailed: descendantsFailed,
19785
21050
  filledRole: roleToFill
@@ -19838,6 +21103,27 @@ async function registerDevice(pctx, input) {
19838
21103
  }
19839
21104
  });
19840
21105
  }
21106
+ const declaredSecretPaths = input.secretConfigPaths ?? [];
21107
+ if (isFirstRegistration && declaredSecretPaths.length > 0) try {
21108
+ const converted = await secureRawDeclaredSecrets({
21109
+ ctx: pctx.host.ctx,
21110
+ readStored: () => pctx.settings.readDeviceStore(id),
21111
+ write: (patch) => pctx.settings.writeDeviceStore(id, patch)
21112
+ }, {
21113
+ deviceId: id,
21114
+ ownerAddonId: addonId,
21115
+ secretPaths: declaredSecretPaths
21116
+ });
21117
+ if (converted.length > 0) pctx.host.ctx.logger.info("registerDevice: secured raw secret fields from the create write", {
21118
+ tags: { deviceId: id },
21119
+ meta: { paths: [...converted] }
21120
+ });
21121
+ } catch (err) {
21122
+ pctx.host.ctx.logger.warn("registerDevice: could not secure raw secret fields from the create write", {
21123
+ tags: { deviceId: id },
21124
+ meta: { error: err instanceof Error ? err.message : String(err) }
21125
+ });
21126
+ }
19841
21127
  if (isFirstRegistration) pctx.host.ctx.eventBus.emit({
19842
21128
  id: randomUUID(),
19843
21129
  timestamp: /* @__PURE__ */ new Date(),
@@ -20024,8 +21310,38 @@ function removalSteps(pctx, deviceId, providerAddonId, deletedAt) {
20024
21310
  })
20025
21311
  ];
20026
21312
  }
21313
+ /**
21314
+ * The rows that belong to `deviceId` and cannot outlive it: its accessory
21315
+ * children (`parentDeviceId === id`). A row that merely LINKS to it
21316
+ * (`linkDeviceId`: an operator-picked link, or an entity of another integration
21317
+ * adopted under its own container) is a device of its own and stays.
21318
+ */
21319
+ async function ownedRowIds(pctx, deviceId) {
21320
+ return (await pctx.metaStore.rows.listByParent(deviceId)).map((row) => row.meta.id).filter((id) => id !== deviceId);
21321
+ }
21322
+ /**
21323
+ * Removing a device removes what it owns (an accessory child never outlives its
21324
+ * parent: a Reolink siren row survived its camera with a dangling
21325
+ * `parentDeviceId`). Each child goes through the same tombstoned removal, so
21326
+ * its data stores, its removal hooks and its identity fence are the parent's.
21327
+ */
20027
21328
  async function removeDevice(pctx, input) {
20028
- const { deviceId } = input;
21329
+ await removeDeviceTree(pctx, input.deviceId, /* @__PURE__ */ new Set());
21330
+ }
21331
+ async function removeDeviceTree(pctx, deviceId, seen) {
21332
+ if (seen.has(deviceId)) return;
21333
+ seen.add(deviceId);
21334
+ const ownedIds = await ownedRowIds(pctx, deviceId);
21335
+ await removeOneDevice(pctx, deviceId);
21336
+ for (const childId of ownedIds) {
21337
+ pctx.host.ctx.logger.info("removed device: cascading to an owned child", {
21338
+ tags: { deviceId: childId },
21339
+ meta: { parentDeviceId: deviceId }
21340
+ });
21341
+ await removeDeviceTree(pctx, childId, seen);
21342
+ }
21343
+ }
21344
+ async function removeOneDevice(pctx, deviceId) {
20029
21345
  const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
20030
21346
  if (!persisted) return;
20031
21347
  const { addonId, stableId, meta: persistedMeta } = persisted;
@@ -20292,15 +21608,18 @@ async function collectDescendants(metaStore, rootId) {
20292
21608
  * consumers (the linked-devices picker, which suggests by location) see exactly what landed.
20293
21609
  */
20294
21610
  async function setLocation(pctx, input) {
20295
- const { deviceId, location } = input;
21611
+ const { deviceId } = input;
21612
+ const locationId = await resolveRoomId(pctx, input);
21613
+ if (locationId === void 0) throw new Error("[device-manager] setLocation: name `location` or `locationId`");
21614
+ const location = pctx.rooms.nameOf(locationId);
20296
21615
  const cascaded = [];
20297
21616
  const failed = [];
20298
21617
  await pctx.metaStore.withMetaWriteLock(async () => {
20299
21618
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setLocation: unknown device id=${deviceId}`);
20300
- await pctx.metaStore.rows.patch(deviceId, { location });
21619
+ await pctx.metaStore.rows.patch(deviceId, { locationId });
20301
21620
  const descendants = await collectDescendants(pctx.metaStore, deviceId);
20302
21621
  for (const descendant of descendants) try {
20303
- await pctx.metaStore.rows.patch(descendant.id, { location });
21622
+ await pctx.metaStore.rows.patch(descendant.id, { locationId });
20304
21623
  cascaded.push(descendant.id);
20305
21624
  } catch (err) {
20306
21625
  failed.push({
@@ -20354,10 +21673,24 @@ async function setLocation(pctx, input) {
20354
21673
  }
20355
21674
  });
20356
21675
  }
20357
- /** The tags a write stores: normalised, `null` (the column's absent form) when none are left. */
20358
- function storedTags(tags) {
20359
- const normalized = normalizeTags(tags);
20360
- return normalized.length === 0 ? null : normalized;
21676
+ /** The current names of tag ids; an id with no tag record is left out, never shown raw. */
21677
+ function tagNamesOf(pctx, ids) {
21678
+ if (ids === null) return null;
21679
+ return ids.flatMap((id) => {
21680
+ const name = pctx.tagNameOf(id);
21681
+ return name === null ? [] : [name];
21682
+ });
21683
+ }
21684
+ /**
21685
+ * The tag ids a write names: `tagIds` wins, else `tags` (text) is resolved through
21686
+ * `ensureTag` (D1089, accepted for one release). `[]` stays `[]`: the operator cleared
21687
+ * them, and `null` would let the kept names of an older row read back as tags again.
21688
+ */
21689
+ async function resolveTagIds(pctx, input) {
21690
+ if (input.tagIds !== void 0) return [...new Set(input.tagIds)];
21691
+ const names = normalizeTags(input.tags ?? []);
21692
+ if (names.length === 0) return [];
21693
+ return [...new Set(await pctx.ensureTagIds(names))];
20361
21694
  }
20362
21695
  /**
20363
21696
  * Replace the operator tags of one device (D1054). Normalised on write; `[]`
@@ -20366,10 +21699,11 @@ function storedTags(tags) {
20366
21699
  */
20367
21700
  async function setTags(pctx, input) {
20368
21701
  const { deviceId } = input;
20369
- const tags = storedTags(input.tags);
21702
+ const tagIds = await resolveTagIds(pctx, input);
21703
+ const tags = tagNamesOf(pctx, tagIds);
20370
21704
  await pctx.metaStore.withMetaWriteLock(async () => {
20371
21705
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setTags: unknown device id=${deviceId}`);
20372
- await pctx.metaStore.rows.patch(deviceId, { tags });
21706
+ await pctx.metaStore.rows.patch(deviceId, { tagIds });
20373
21707
  });
20374
21708
  pctx.host.ctx.eventBus.emit({
20375
21709
  id: randomUUID(),
@@ -20661,12 +21995,14 @@ async function setRoleDisplayDefaults(pctx, input) {
20661
21995
  */
20662
21996
  async function applyInitialMeta(pctx, input) {
20663
21997
  const { deviceId, name, location, tags, type, integrationId, linkDeviceId, role } = input;
21998
+ const locationId = location === void 0 && input.locationId === void 0 ? void 0 : await resolveRoomId(pctx, input);
21999
+ const tagIds = tags === void 0 && input.tagIds === void 0 ? void 0 : await resolveTagIds(pctx, input);
20664
22000
  await pctx.metaStore.withMetaWriteLock(async () => {
20665
22001
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] applyInitialMeta: unknown device id=${deviceId}`);
20666
22002
  await pctx.metaStore.rows.patch(deviceId, {
20667
22003
  ...name !== void 0 ? { name } : {},
20668
- ...location !== void 0 ? { location } : {},
20669
- ...tags !== void 0 ? { tags: storedTags(tags) } : {},
22004
+ ...locationId !== void 0 ? { locationId } : {},
22005
+ ...tagIds !== void 0 ? { tagIds } : {},
20670
22006
  ...type !== void 0 ? { type } : {},
20671
22007
  ...integrationId !== void 0 ? { integrationId } : {},
20672
22008
  ...linkDeviceId !== void 0 ? { linkDeviceId } : {},
@@ -20690,8 +22026,8 @@ async function applyInitialMeta(pctx, input) {
20690
22026
  });
20691
22027
  };
20692
22028
  if (name !== void 0) emitMetaChanged("name", name);
20693
- if (location !== void 0) emitMetaChanged("location", location);
20694
- if (tags !== void 0) emitMetaChanged("tags", storedTags(tags) ?? []);
22029
+ if (locationId !== void 0) emitMetaChanged("location", pctx.rooms.nameOf(locationId));
22030
+ if (tagIds !== void 0) emitMetaChanged("tags", tagNamesOf(pctx, tagIds) ?? []);
20695
22031
  if (type !== void 0) emitMetaChanged("type", type);
20696
22032
  if (integrationId !== void 0) emitMetaChanged("integrationId", integrationId);
20697
22033
  if (linkDeviceId !== void 0) emitMetaChanged("linkDeviceId", linkDeviceId);
@@ -20803,480 +22139,109 @@ async function loadRuntimeState(pctx, input) {
20803
22139
  return splitRuntimeBlob(pctx.host.seedMirrorFromRow(deviceId, data, pctx.settings)).native;
20804
22140
  }
20805
22141
  /**
20806
- * Union of (1) operator-curated location registry and (2) labels
20807
- * currently in use on persisted devices. Case-insensitive
20808
- * dedupe (preserves the first-seen casing). Sorted
20809
- * case-insensitively for stable UI. Drives the Device Info
20810
- * location autocomplete.
20811
- */
20812
- async function listLocations(pctx) {
20813
- const locations = (await pctx.metaStore.readStore()).locations ?? [];
20814
- const seen = /* @__PURE__ */ new Map();
20815
- const consider = (raw) => {
20816
- if (typeof raw !== "string") return;
20817
- const trimmed = raw.trim();
20818
- if (trimmed.length === 0) return;
20819
- const key = trimmed.toLowerCase();
20820
- if (!seen.has(key)) seen.set(key, trimmed);
20821
- };
20822
- for (const label of locations) consider(label);
20823
- for (const row of await pctx.metaStore.rows.listAll()) consider(row.meta.location);
20824
- return [...seen.values()].toSorted((a, b) => a.localeCompare(b, void 0, { sensitivity: "base" }));
20825
- }
20826
- /**
20827
- * Add a label to the curated location registry. Idempotent:
20828
- * existing entries (case-insensitive match) are silently kept.
20829
- * Empty / whitespace-only inputs throw — operators must supply a
20830
- * meaningful label.
20831
- */
20832
- async function addLocation(pctx, input) {
20833
- const trimmed = input.name.trim();
20834
- if (trimmed.length === 0) throw userError("system.location-name-required", void 0, "[device-manager] addLocation: name must be non-empty");
20835
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20836
- const current = (await pctx.metaStore.readStore()).locations ?? [];
20837
- if (current.some((l) => l.toLowerCase() === trimmed.toLowerCase())) return;
20838
- await pctx.settings.writeAddonStore({ locations: [...current, trimmed] });
20839
- });
20840
- }
20841
- /**
20842
- * Every location that carries an icon, as `(locationKey, icon)` pairs.
20843
- *
20844
- * ADDITIVE beside `listLocations`, which still answers `string[]` — the
20845
- * autocomplete, the HA adoption import and the recorder all read a list of
20846
- * LABELS and a shape change there would break every one of them. A surface
20847
- * that wants icons asks for them and joins on `locationIconKey`.
20848
- *
20849
- * Returns only what was actually stored. A location with no assignment is
20850
- * ABSENT, never `map-pin`: the fallback belongs to the renderer
20851
- * (`resolveIconKey`), and folding it in here would make "the operator
20852
- * picked the pin" indistinguishable from "the operator picked nothing" —
20853
- * which is the difference an icon picker has to draw.
20854
- */
20855
- async function listLocationIcons(pctx) {
20856
- const icons = (await pctx.metaStore.readStore()).locationIcons ?? {};
20857
- return Object.entries(icons).map(([locationKey, icon]) => ({
20858
- locationKey,
20859
- icon
20860
- })).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20861
- }
20862
- /**
20863
- * Set (or clear) the icon of a location label.
20864
- *
20865
- * Keyed on `locationIconKey` — trimmed + lower-cased, the equality the
20866
- * registry matches on everywhere — so a case-only rename keeps the icon and
20867
- * two spellings of one room can never carry two different icons.
20868
- *
20869
- * The label need NOT be registered: `setLocation` accepts a free-form string
20870
- * and `listLocations` folds in whatever devices carry, so requiring
20871
- * registration here would leave exactly the ad-hoc rooms unable to have an
20872
- * icon. An empty label throws — there is no room to name.
20873
- *
20874
- * Same read-modify-write and same lock as `addLocation`: the map is one key of
20875
- * the addon store, and `writeAddonStore` re-inserts the whole key range, so an
20876
- * unordered write carries a stale copy of every other key.
22142
+ * `deviceManager.repairMigrationSecrets` — the live repair for a pair a
22143
+ * migration left with crossed keychain scopes (see `repairCrossedSecretScopes`).
22144
+ * Under the meta write lock the migration itself ran under: a config write
22145
+ * racing it would read the half this repair is moving. The running devices
22146
+ * keep their loaded config until the next reload.
20877
22147
  */
20878
- async function setLocationIcon(pctx, input) {
20879
- const trimmed = input.location.trim();
20880
- if (trimmed.length === 0) throw userError("system.location-required", void 0, "[device-manager] setLocationIcon: location must be non-empty");
20881
- const key = locationIconKey(trimmed);
20882
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20883
- const icons = (await pctx.metaStore.readStore()).locationIcons ?? {};
20884
- if (input.icon === null) {
20885
- if (!(key in icons)) return;
20886
- const { [key]: _cleared, ...kept } = icons;
20887
- await pctx.settings.writeAddonStore({ locationIcons: kept });
20888
- return;
20889
- }
20890
- if (icons[key] === input.icon) return;
20891
- await pctx.settings.writeAddonStore({ locationIcons: {
20892
- ...icons,
20893
- [key]: input.icon
20894
- } });
20895
- });
20896
- }
20897
- /**
20898
- * Every location that carries a description, sorted by key.
20899
- *
20900
- * Only what was WRITTEN — a location with no description is absent, and the
20901
- * digest then tells the model the location name alone, exactly as it did
20902
- * before descriptions existed.
20903
- */
20904
- async function listLocationDescriptions(pctx) {
20905
- const descriptions = (await pctx.metaStore.readStore()).locationDescriptions ?? {};
20906
- return Object.entries(descriptions).map(([locationKey, description]) => ({
20907
- locationKey,
20908
- description
20909
- })).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20910
- }
20911
- /**
20912
- * Set (or clear) a location's description.
20913
- *
20914
- * A BLANK description clears, exactly as `null` does: an empty line handed to
20915
- * a vision model costs attention and says nothing, so the two must not be
20916
- * different states. The label is folded with `locationIconKey` — the same key
20917
- * the icon uses, which is the whole point of this living here.
20918
- *
20919
- * Same read-modify-write and same lock as `setLocationIcon`; `writeAddonStore`
20920
- * re-inserts the whole key range, so an unordered write carries a stale copy
20921
- * of every other key.
20922
- */
20923
- async function setLocationDescription(pctx, input) {
20924
- const trimmed = input.location.trim();
20925
- if (trimmed.length === 0) throw new Error("[device-manager] setLocationDescription: location must be non-empty");
20926
- const key = locationIconKey(trimmed);
20927
- const text = input.description === null ? "" : input.description.trim();
20928
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20929
- const descriptions = (await pctx.metaStore.readStore()).locationDescriptions ?? {};
20930
- if (text.length === 0) {
20931
- if (!(key in descriptions)) return;
20932
- const { [key]: _cleared, ...kept } = descriptions;
20933
- await pctx.settings.writeAddonStore({ locationDescriptions: kept });
20934
- return;
22148
+ async function repairMigrationSecrets(pctx, input) {
22149
+ const { deviceA, deviceB, apply } = input;
22150
+ const ctx = pctx.host.ctx;
22151
+ const forOwner = ctx.secrets?.forOwner ?? null;
22152
+ const report = await pctx.metaStore.withMetaWriteLock(() => repairCrossedSecretScopes(pctx.settings, forOwner === null ? void 0 : { forOwner }, deviceA, deviceB, apply));
22153
+ for (const deviceId of [deviceA, deviceB]) ctx.logger.info("repairMigrationSecrets", {
22154
+ tags: { deviceId },
22155
+ meta: {
22156
+ deviceA,
22157
+ deviceB,
22158
+ apply,
22159
+ outcome: report.outcome
20935
22160
  }
20936
- if (descriptions[key] === text) return;
20937
- await pctx.settings.writeAddonStore({ locationDescriptions: {
20938
- ...descriptions,
20939
- [key]: text
20940
- } });
20941
- });
20942
- }
20943
- /**
20944
- * Every site zone, with its rooms, sorted by key.
20945
- *
20946
- * Membership is inverted HERE rather than stored both ways: the store keeps
20947
- * `location → zone`, which is what makes "one zone per room" structural, and a
20948
- * second copy keyed the other way is a second thing that can disagree with the
20949
- * first.
20950
- */
20951
- async function listSiteZones(pctx) {
20952
- const store = await pctx.metaStore.readStore();
20953
- const zones = store.siteZones ?? {};
20954
- const membership = store.locationZones ?? {};
20955
- const rooms = /* @__PURE__ */ new Map();
20956
- for (const [locationKey, zoneKey] of Object.entries(membership)) {
20957
- const list = rooms.get(zoneKey);
20958
- if (list === void 0) rooms.set(zoneKey, [locationKey]);
20959
- else list.push(locationKey);
20960
- }
20961
- return Object.entries(zones).map(([zoneKey, record]) => ({
20962
- zoneKey,
20963
- label: record.label,
20964
- icon: record.icon ?? null,
20965
- locationKeys: (rooms.get(zoneKey) ?? []).toSorted((a, b) => a.localeCompare(b))
20966
- })).toSorted((a, b) => a.zoneKey.localeCompare(b.zoneKey));
20967
- }
20968
- /**
20969
- * Create a zone, or set the icon of one that already exists.
20970
- *
20971
- * `icon: null` clears the icon and KEEPS the zone. Conflating the two would
20972
- * make a mis-click on "no icon" delete every room's membership — the icon is a
20973
- * decoration and the grouping is the data.
20974
- *
20975
- * `icon` OMITTED leaves whatever icon is there: creating a zone from a screen
20976
- * with no picker must not silently clear the glyph a previous screen set.
20977
- */
20978
- async function setSiteZone(pctx, input) {
20979
- const label = input.name.trim();
20980
- if (label.length === 0) throw userError("system.site-zone-name-required", void 0, "[device-manager] setSiteZone: name must be non-empty");
20981
- const key = siteZoneKey(label);
20982
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20983
- const zones = (await pctx.metaStore.readStore()).siteZones ?? {};
20984
- const existing = zones[key];
20985
- const icon = input.icon === void 0 ? existing?.icon : input.icon === null ? void 0 : input.icon;
20986
- const next = icon === void 0 ? { label } : {
20987
- label,
20988
- icon
20989
- };
20990
- if (existing?.label === next.label && existing.icon === next.icon) return;
20991
- await pctx.settings.writeAddonStore({ siteZones: {
20992
- ...zones,
20993
- [key]: next
20994
- } });
20995
- });
20996
- }
20997
- /**
20998
- * Delete a zone. Its LOCATIONS survive, unattached.
20999
- *
21000
- * Deleting a grouping must never delete what was grouped — the rooms exist
21001
- * independently and the devices in them were never touched to begin with.
21002
- */
21003
- async function removeSiteZone(pctx, input) {
21004
- const key = siteZoneKey(input.name);
21005
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21006
- const store = await pctx.metaStore.readStore();
21007
- const zones = store.siteZones ?? {};
21008
- const membership = store.locationZones ?? {};
21009
- const hadZone = key in zones;
21010
- const orphaned = Object.entries(membership).filter(([, zoneKey]) => zoneKey === key);
21011
- if (!hadZone && orphaned.length === 0) return;
21012
- const { [key]: _dropped, ...keptZones } = zones;
21013
- const keptMembership = Object.fromEntries(Object.entries(membership).filter(([, zoneKey]) => zoneKey !== key));
21014
- await pctx.settings.writeAddonStore({
21015
- ...hadZone ? { siteZones: keptZones } : {},
21016
- ...orphaned.length > 0 ? { locationZones: keptMembership } : {}
21017
- });
21018
- });
21019
- }
21020
- /**
21021
- * Rename a zone, carrying its icon AND every room in it.
21022
- *
21023
- * It exists so that renaming is not delete-then-recreate, which drops both.
21024
- * A rename onto an existing zone MERGES: the target keeps its own icon and the
21025
- * rooms are unioned, the same rule `renameLocation` follows.
21026
- */
21027
- async function renameSiteZone(pctx, input) {
21028
- const toLabel = input.to.trim();
21029
- if (toLabel.length === 0) throw new Error("[device-manager] renameSiteZone: target name must be non-empty");
21030
- const fromKey = siteZoneKey(input.from);
21031
- const toKey = siteZoneKey(toLabel);
21032
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21033
- const store = await pctx.metaStore.readStore();
21034
- const zones = store.siteZones ?? {};
21035
- const moved = zones[fromKey];
21036
- if (moved === void 0) return;
21037
- const { [fromKey]: _dropped, ...rest } = zones;
21038
- const target = rest[toKey];
21039
- const nextZones = {
21040
- ...rest,
21041
- [toKey]: target ?? (moved.icon === void 0 ? { label: toLabel } : {
21042
- label: toLabel,
21043
- icon: moved.icon
21044
- })
21045
- };
21046
- const membership = store.locationZones ?? {};
21047
- const nextMembership = Object.fromEntries(Object.entries(membership).map(([locationKey, zoneKey]) => [locationKey, zoneKey === fromKey ? toKey : zoneKey]));
21048
- await pctx.settings.writeAddonStore({
21049
- siteZones: nextZones,
21050
- locationZones: nextMembership
21051
- });
21052
22161
  });
22162
+ return report;
21053
22163
  }
22164
+ //#endregion
22165
+ //#region src/builtins/device-manager/room-store.ts
21054
22166
  /**
21055
- * Put a location in a zone, or take it out with `zone: null`.
22167
+ * The rooms and site zones of the property, as records with an id (D1089).
21056
22168
  *
21057
- * ONE slot per location, so a second call moves the room rather than listing it
21058
- * twice. The zone is created if it does not exist — a screen that assigns
21059
- * before creating is a normal order, and refusing it would be the only place in
21060
- * this registry that demands registration first.
22169
+ * `rooms` and `zones` are record kinds the device manager owns; a device meta
22170
+ * carries `locationId`, a room carries `zoneId`. The store keeps both in memory
22171
+ * once read — a device read resolves a room name through {@link RoomStore.nameOf}
22172
+ * without a query, and an unknown id reads as unset.
21061
22173
  */
21062
- async function setLocationZone(pctx, input) {
21063
- const location = input.location.trim();
21064
- if (location.length === 0) throw new Error("[device-manager] setLocationZone: location must be non-empty");
21065
- const locationKey = locationIconKey(location);
21066
- const label = input.zone === null ? null : input.zone.trim();
21067
- if (label !== null && label.length === 0) throw new Error("[device-manager] setLocationZone: zone must be non-empty or null");
21068
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21069
- const store = await pctx.metaStore.readStore();
21070
- const membership = store.locationZones ?? {};
21071
- if (label === null) {
21072
- if (!(locationKey in membership)) return;
21073
- const { [locationKey]: _cleared, ...kept } = membership;
21074
- await pctx.settings.writeAddonStore({ locationZones: kept });
21075
- return;
21076
- }
21077
- const zoneKey = siteZoneKey(label);
21078
- const zones = store.siteZones ?? {};
21079
- const needsZone = !(zoneKey in zones);
21080
- if (membership[locationKey] === zoneKey && !needsZone) return;
21081
- await pctx.settings.writeAddonStore({
21082
- ...needsZone ? { siteZones: {
21083
- ...zones,
21084
- [zoneKey]: { label }
21085
- } } : {},
21086
- locationZones: {
21087
- ...membership,
21088
- [locationKey]: zoneKey
22174
+ var RoomStore = class RoomStore {
22175
+ rooms;
22176
+ zones;
22177
+ constructor(rooms, zones) {
22178
+ this.rooms = rooms;
22179
+ this.zones = zones;
22180
+ }
22181
+ static of(records) {
22182
+ return new RoomStore(new NamedEntityStore("room", records.kind(deviceManagerRecordKinds.rooms), (body) => RoomBodySchema.parse(body)), new NamedEntityStore("zone", records.kind(deviceManagerRecordKinds.zones), (body) => ZoneBodySchema.parse(body)));
22183
+ }
22184
+ async load() {
22185
+ await this.rooms.load();
22186
+ await this.zones.load();
22187
+ }
22188
+ /** The current name of room `id`; `null` when unset or unknown. */
22189
+ nameOf(id) {
22190
+ return this.rooms.nameOf(id);
22191
+ }
22192
+ };
22193
+ var TagNames = class {
22194
+ source;
22195
+ logger;
22196
+ now;
22197
+ names = /* @__PURE__ */ new Map();
22198
+ refreshedAt = 0;
22199
+ inFlight = null;
22200
+ constructor(source, logger, now = Date.now) {
22201
+ this.source = source;
22202
+ this.logger = logger;
22203
+ this.now = now;
22204
+ }
22205
+ nameOf(id) {
22206
+ return this.names.get(id) ?? null;
22207
+ }
22208
+ /** Revalidate when older than the window. A failed read keeps the last answer. */
22209
+ async fresh() {
22210
+ if (this.source === null) return;
22211
+ if (this.now() - this.refreshedAt < 5e3) return;
22212
+ await this.refresh();
22213
+ }
22214
+ async refresh() {
22215
+ const source = this.source;
22216
+ if (source === null) return;
22217
+ if (this.inFlight !== null) return this.inFlight;
22218
+ const run = (async () => {
22219
+ try {
22220
+ const tags = await source.list();
22221
+ this.names = new Map(tags.map((tag) => [tag.id, tag.name]));
22222
+ this.refreshedAt = this.now();
22223
+ } catch (err) {
22224
+ this.logger.warn("tag names not refreshed — keeping the last answer", { meta: { error: errMsg$1(err) } });
22225
+ } finally {
22226
+ this.inFlight = null;
21089
22227
  }
21090
- });
21091
- });
21092
- }
21093
- /**
21094
- * Move a location's zone membership from one key to another, for
21095
- * `renameLocation`. Same shape as the icon and description movers.
21096
- */
21097
- function renameLocationZone(membership, fromKey, toKey) {
21098
- const moved = membership[fromKey];
21099
- if (moved === void 0) return null;
21100
- if (fromKey === toKey) return null;
21101
- const { [fromKey]: _dropped, ...rest } = membership;
21102
- return toKey in rest ? rest : {
21103
- ...rest,
21104
- [toKey]: moved
21105
- };
21106
- }
21107
- /**
21108
- * Move a location's description from one key to another, for `renameLocation`.
21109
- *
21110
- * Identical rule to {@link renameLocationIcon}, deliberately: a merge keeps the
21111
- * TARGET's description, because renaming "Sala" into "Hall" moves devices
21112
- * into Hall and does not re-describe it. Split from the icon mover only
21113
- * because the value types differ; if one ever changes, the other must.
21114
- */
21115
- function renameLocationDescription(descriptions, fromKey, toKey) {
21116
- const moved = descriptions[fromKey];
21117
- if (moved === void 0) return null;
21118
- if (fromKey === toKey) return null;
21119
- const { [fromKey]: _dropped, ...rest } = descriptions;
21120
- return toKey in rest ? rest : {
21121
- ...rest,
21122
- [toKey]: moved
21123
- };
21124
- }
21125
- /**
21126
- * Move a location's icon from one key to another, for `renameLocation`.
21127
- *
21128
- * Returns `null` when NOTHING changes, so the caller can leave the key out of
21129
- * its `writeAddonStore` patch instead of re-writing an identical map.
21130
- *
21131
- * A rename onto a room that already has an icon is a MERGE, and the surviving
21132
- * room keeps its own: the operator renaming "Sala" into "Hall" is moving
21133
- * devices into Hall, not restyling it. The source key is dropped either way.
21134
- * Pure — builds a new record, mutates nothing.
21135
- */
21136
- function renameLocationIcon(icons, fromKey, toKey) {
21137
- const moved = icons[fromKey];
21138
- if (moved === void 0) return null;
21139
- if (fromKey === toKey) return null;
21140
- const { [fromKey]: _dropped, ...rest } = icons;
21141
- return toKey in rest ? rest : {
21142
- ...rest,
21143
- [toKey]: moved
21144
- };
21145
- }
21146
- /**
21147
- * Remove a label from the curated registry. Match is
21148
- * case-insensitive. Devices that still reference this label keep
21149
- * their `meta.location` value (the registry is a suggestion
21150
- * list, not a foreign key) — pass `cascade: true` to also clear
21151
- * `setLocation` on every device that referenced this exact
21152
- * label. Cascade only matches case-insensitively + trimmed, same
21153
- * as the registry equality check.
21154
- */
21155
- /**
21156
- * Rename a room in ONE server operation: the registry label in place, then
21157
- * every device that carried it.
21158
- *
21159
- * The lock order is the one `removeLocation` documents and must not be
21160
- * "simplified": the registry edit takes the addon-store lock and RELEASES it
21161
- * before the cascade takes the meta lock. Holding both, in that order, is the
21162
- * reverse of `allocateNextDeviceId`'s meta ⊃ addon-store nesting — the pair
21163
- * that deadlocks.
21164
- *
21165
- * Validation happens BEFORE either lock. A rename that throws halfway is the
21166
- * exact failure this function exists to remove, so an empty target must be
21167
- * refused while nothing has been written yet.
21168
- */
21169
- async function renameLocation(pctx, input) {
21170
- const from = input.from.trim();
21171
- const to = input.to.trim();
21172
- if (from.length === 0) throw new Error("[device-manager] renameLocation: `from` must be non-empty");
21173
- if (to.length === 0) throw new Error("[device-manager] renameLocation: `to` must be non-empty");
21174
- const fromKey = from.toLowerCase();
21175
- const toKey = to.toLowerCase();
21176
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21177
- const store = await pctx.metaStore.readStore();
21178
- const current = store.locations ?? [];
21179
- const registered = current.some((l) => l.trim().toLowerCase() === fromKey);
21180
- const movedIcons = renameLocationIcon(store.locationIcons ?? {}, fromKey, toKey);
21181
- const movedDescriptions = renameLocationDescription(store.locationDescriptions ?? {}, fromKey, toKey);
21182
- const movedZones = renameLocationZone(store.locationZones ?? {}, fromKey, toKey);
21183
- if (!registered && movedIcons === null && movedDescriptions === null && movedZones === null) return;
21184
- const kept = current.filter((l) => {
21185
- const key = l.trim().toLowerCase();
21186
- return key !== fromKey && key !== toKey;
21187
- });
21188
- await pctx.settings.writeAddonStore({
21189
- ...registered ? { locations: [...kept, to] } : {},
21190
- ...movedIcons !== null ? { locationIcons: movedIcons } : {},
21191
- ...movedDescriptions !== null ? { locationDescriptions: movedDescriptions } : {},
21192
- ...movedZones !== null ? { locationZones: movedZones } : {}
21193
- });
21194
- });
21195
- const moved = await pctx.metaStore.withMetaWriteLock(async () => {
21196
- const out = [];
21197
- for (const row of await pctx.metaStore.rows.listAll()) {
21198
- const location = row.meta.location;
21199
- if (typeof location !== "string") continue;
21200
- if (location.trim().toLowerCase() !== fromKey) continue;
21201
- await pctx.metaStore.rows.patch(row.meta.id, { location: to });
21202
- out.push(row.meta.id);
21203
- }
21204
- return out;
21205
- });
21206
- for (const deviceId of moved) pctx.host.ctx.eventBus.emit({
21207
- id: randomUUID(),
21208
- timestamp: /* @__PURE__ */ new Date(),
21209
- source: {
21210
- type: "device",
21211
- id: deviceId
21212
- },
21213
- category: EventCategory$1.DeviceMetaChanged,
21214
- data: {
21215
- deviceId,
21216
- field: "location",
21217
- value: to
21218
- }
21219
- });
21220
- pctx.host.ctx.logger.info("renameLocation: room renamed", { meta: {
21221
- from,
21222
- to,
21223
- moved: moved.length
21224
- } });
21225
- return { moved: moved.length };
21226
- }
21227
- async function removeLocation(pctx, input) {
21228
- const trimmed = input.name.trim();
21229
- if (trimmed.length === 0) return;
21230
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21231
- const store = await pctx.metaStore.readStore();
21232
- const current = store.locations ?? [];
21233
- const key = locationIconKey(trimmed);
21234
- const remaining = current.filter((l) => l.toLowerCase() !== key);
21235
- const droppedLabel = remaining.length !== current.length;
21236
- const icons = store.locationIcons ?? {};
21237
- const droppedIcon = key in icons;
21238
- const descriptions = store.locationDescriptions ?? {};
21239
- const droppedDescription = key in descriptions;
21240
- const membership = store.locationZones ?? {};
21241
- const droppedZone = key in membership;
21242
- if (!droppedLabel && !droppedIcon && !droppedDescription && !droppedZone) return;
21243
- const { [key]: _removedIcon, ...keptIcons } = icons;
21244
- const { [key]: _removedDescription, ...keptDescriptions } = descriptions;
21245
- const { [key]: _removedZone, ...keptMembership } = membership;
21246
- await pctx.settings.writeAddonStore({
21247
- ...droppedLabel ? { locations: remaining } : {},
21248
- ...droppedIcon ? { locationIcons: keptIcons } : {},
21249
- ...droppedDescription ? { locationDescriptions: keptDescriptions } : {},
21250
- ...droppedZone ? { locationZones: keptMembership } : {}
21251
- });
21252
- });
21253
- if (input.cascade !== true) return;
21254
- const cleared = await pctx.metaStore.withMetaWriteLock(async () => {
21255
- const out = [];
21256
- for (const row of await pctx.metaStore.rows.listAll()) {
21257
- const location = row.meta.location;
21258
- if (typeof location !== "string") continue;
21259
- if (location.trim().toLowerCase() !== trimmed.toLowerCase()) continue;
21260
- await pctx.metaStore.rows.patch(row.meta.id, { location: null });
21261
- out.push(row.meta.id);
21262
- }
21263
- return out;
21264
- });
21265
- for (const deviceId of cleared) pctx.host.ctx.eventBus.emit({
21266
- id: randomUUID(),
21267
- timestamp: /* @__PURE__ */ new Date(),
21268
- source: {
21269
- type: "device",
21270
- id: deviceId
21271
- },
21272
- category: EventCategory$1.DeviceMetaChanged,
21273
- data: {
21274
- deviceId,
21275
- field: "location",
21276
- value: null
22228
+ })();
22229
+ this.inFlight = run;
22230
+ return run;
22231
+ }
22232
+ /** Resolve text names to ids through `ensureTag`; a name no tag cap can mint is left out. */
22233
+ async ensureIds(names) {
22234
+ const source = this.source;
22235
+ if (source === null) return [];
22236
+ const ids = [];
22237
+ for (const name of names) {
22238
+ const tag = await source.ensure(name);
22239
+ ids.push(tag.id);
21277
22240
  }
21278
- });
21279
- }
22241
+ await this.refresh();
22242
+ return ids;
22243
+ }
22244
+ };
21280
22245
  //#endregion
21281
22246
  //#region src/builtins/device-manager/device-identifiers-action.ts
21282
22247
  /**
@@ -21726,7 +22691,6 @@ var IdentityLinkReconciler = class {
21726
22691
  };
21727
22692
  //#endregion
21728
22693
  //#region src/builtins/device-manager/identity-links-store.ts
21729
- var import_read_all_rows = require_read_all_rows();
21730
22694
  var IdentityLinksStore = class IdentityLinksStore {
21731
22695
  kind;
21732
22696
  links = null;
@@ -22810,130 +23774,6 @@ var DeviceTemplateActions = class {
22810
23774
  }
22811
23775
  };
22812
23776
  //#endregion
22813
- //#region src/builtins/device-manager/device-meta-types.ts
22814
- /**
22815
- * Decode the raw `ctx.settings.readAddonStore()` record into {@link AddonStore}.
22816
- *
22817
- * A field of the wrong shape reads as ABSENT rather than being trusted through
22818
- * a cast: the store is JSON on disk and a hand-edit or a partial restore must
22819
- * cost the caller its default, never a downstream `TypeError`.
22820
- */
22821
- function decodeAddonStore(raw) {
22822
- const nextDeviceId = raw["nextDeviceId"];
22823
- const locations = raw["locations"];
22824
- const roleDisplayDefaults = raw["roleDisplayDefaults"];
22825
- const locationIcons = decodeLocationIcons(raw["locationIcons"]);
22826
- const locationDescriptions = decodeLocationDescriptions(raw["locationDescriptions"]);
22827
- const siteZones = decodeSiteZones(raw["siteZones"]);
22828
- const locationZones = decodeStringMap(raw["locationZones"]);
22829
- return {
22830
- ...typeof nextDeviceId === "number" && Number.isFinite(nextDeviceId) ? { nextDeviceId } : {},
22831
- ...Array.isArray(locations) ? { locations: locations.filter((l) => typeof l === "string") } : {},
22832
- ...isRoleDisplayDefaults(roleDisplayDefaults) ? { roleDisplayDefaults } : {},
22833
- ...locationIcons !== null ? { locationIcons } : {},
22834
- ...locationDescriptions !== null ? { locationDescriptions } : {},
22835
- ...siteZones !== null ? { siteZones } : {},
22836
- ...locationZones !== null ? { locationZones } : {}
22837
- };
22838
- }
22839
- /**
22840
- * Decode the `locationIcons` map, dropping every entry whose value is not a
22841
- * member of the closed vocabulary.
22842
- *
22843
- * Dropping, not passing through: the icon's whole point is that both surfaces
22844
- * can draw it, and an id from a hand-edit or a newer hub is exactly the value
22845
- * that draws nothing. Absent reads as "no icon chosen", which every renderer
22846
- * already degrades to the fallback pin. Returns `null` when the key itself is
22847
- * absent or of the wrong shape, so the field stays OMITTED rather than being
22848
- * written back as an empty object.
22849
- */
22850
- function decodeLocationIcons(raw) {
22851
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22852
- const out = {};
22853
- for (const [key, value] of Object.entries(raw)) {
22854
- const icon = canonicalIconKey(value);
22855
- if (icon === void 0) continue;
22856
- out[key] = icon;
22857
- }
22858
- return out;
22859
- }
22860
- /**
22861
- * Decode the `locationDescriptions` map, dropping every entry that is not a
22862
- * non-blank string.
22863
- *
22864
- * Same posture as the icons: a blank description and a missing one are the
22865
- * same instruction to every reader, and storing the first would send an empty
22866
- * line to a vision model. Over-long text is TRUNCATED rather than dropped —
22867
- * losing the whole description because a hand-edit ran long is a worse answer
22868
- * than losing its tail.
22869
- */
22870
- function decodeLocationDescriptions(raw) {
22871
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22872
- const out = {};
22873
- for (const [key, value] of Object.entries(raw)) {
22874
- if (typeof value !== "string") continue;
22875
- const text = value.trim();
22876
- if (text.length === 0) continue;
22877
- out[key] = text.slice(0, 400);
22878
- }
22879
- return out;
22880
- }
22881
- /**
22882
- * Decode the zone registry, dropping any entry without a usable label.
22883
- *
22884
- * A zone whose label did not survive a hand-edit cannot be shown or renamed —
22885
- * it would be a row the operator can see the effects of and never name. An
22886
- * icon outside the vocabulary is dropped on its own, leaving the zone: losing
22887
- * a glyph is a smaller loss than losing the grouping.
22888
- */
22889
- function decodeSiteZones(raw) {
22890
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22891
- const out = {};
22892
- for (const [key, value] of Object.entries(raw)) {
22893
- if (value === null || typeof value !== "object" || Array.isArray(value)) continue;
22894
- const rec = value;
22895
- const label = typeof rec["label"] === "string" ? rec["label"].trim() : "";
22896
- if (label.length === 0) continue;
22897
- const icon = canonicalIconKey(rec["icon"]);
22898
- out[key] = icon === void 0 ? { label } : {
22899
- label,
22900
- icon
22901
- };
22902
- }
22903
- return out;
22904
- }
22905
- /** Decode a plain `string → string` map, dropping anything else. */
22906
- function decodeStringMap(raw) {
22907
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22908
- const out = {};
22909
- for (const [key, value] of Object.entries(raw)) {
22910
- if (typeof value !== "string" || value.trim().length === 0) continue;
22911
- out[key] = value;
22912
- }
22913
- return out;
22914
- }
22915
- function isRoleDisplayDefaults(value) {
22916
- return value !== null && typeof value === "object" && !Array.isArray(value);
22917
- }
22918
- //#endregion
22919
- //#region src/builtins/device-manager/write-lock.ts
22920
- function createWriteLock() {
22921
- let chain = Promise.resolve();
22922
- return async (fn) => {
22923
- const previous = chain;
22924
- let release = () => {};
22925
- chain = new Promise((resolve) => {
22926
- release = resolve;
22927
- });
22928
- try {
22929
- await previous.catch(() => {});
22930
- return await fn();
22931
- } finally {
22932
- release();
22933
- }
22934
- };
22935
- }
22936
- //#endregion
22937
23777
  //#region src/builtins/device-manager/device-meta-store.ts
22938
23778
  var DeviceMetaStore = class {
22939
23779
  settings;
@@ -26650,16 +27490,20 @@ var REMOVAL_RETRY_DELAYS_MS = [
26650
27490
  12e4,
26651
27491
  6e5
26652
27492
  ];
26653
- async function attempt(steps) {
27493
+ async function attempt(steps, concurrent) {
26654
27494
  const counts = {};
26655
27495
  const failed = [];
26656
27496
  const errors = {};
26657
- for (const step of steps) try {
26658
- counts[step.store] = await step.run();
26659
- } catch (err) {
26660
- failed.push(step);
26661
- errors[step.store] = errMsg$1(err);
26662
- }
27497
+ const runOne = async (step) => {
27498
+ try {
27499
+ counts[step.store] = await step.run();
27500
+ } catch (err) {
27501
+ failed.push(step);
27502
+ errors[step.store] = errMsg$1(err);
27503
+ }
27504
+ };
27505
+ if (concurrent) await Promise.all(steps.map(runOne));
27506
+ else for (const step of steps) await runOne(step);
26663
27507
  return {
26664
27508
  counts,
26665
27509
  failed,
@@ -26668,6 +27512,7 @@ async function attempt(steps) {
26668
27512
  }
26669
27513
  function createRemovalCleanup(opts) {
26670
27514
  const label = opts.label ?? "device removal cleanup";
27515
+ const concurrent = opts.concurrent ?? false;
26671
27516
  const delays = opts.retryDelaysMs ?? REMOVAL_RETRY_DELAYS_MS;
26672
27517
  const setTimer = opts.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
26673
27518
  const clearTimer = opts.clearTimer ?? ((handle) => clearTimeout(handle));
@@ -26694,7 +27539,7 @@ function createRemovalCleanup(opts) {
26694
27539
  pending.add(handle);
26695
27540
  };
26696
27541
  const retry = async (deviceId, steps, retryIndex) => {
26697
- const result = await attempt(steps);
27542
+ const result = await attempt(steps, concurrent);
26698
27543
  opts.logger.info(`${label} retried`, {
26699
27544
  tags: { deviceId },
26700
27545
  meta: {
@@ -26707,7 +27552,7 @@ function createRemovalCleanup(opts) {
26707
27552
  };
26708
27553
  return {
26709
27554
  async run(deviceId, steps) {
26710
- const result = await attempt(steps);
27555
+ const result = await attempt(steps, concurrent);
26711
27556
  const failedStores = result.failed.map((s) => s.store);
26712
27557
  const meta = {
26713
27558
  counts: result.counts,
@@ -27119,6 +27964,7 @@ var DeviceManagerAddon = class extends BaseAddon {
27119
27964
  return /* @__PURE__ */ new Map();
27120
27965
  }
27121
27966
  },
27967
+ roomNameOf: (value) => pctx.rooms.nameOf(value),
27122
27968
  logger: this.ctx.logger
27123
27969
  }, input);
27124
27970
  }
@@ -27177,6 +28023,24 @@ var DeviceManagerAddon = class extends BaseAddon {
27177
28023
  const records = this.ctx.records;
27178
28024
  if (records === void 0) throw new Error("[device-manager] ctx.records is required on the hub");
27179
28025
  await records.declare(deviceManagerRecordKinds);
28026
+ await this.runMigrations(defineAddonMigrations(ROOMS_AND_TAGS_MIGRATIONS, deviceManagerMigrationPorts({
28027
+ readStoredKey: (key) => this.readStoredGlobalKey(key),
28028
+ rows: deviceRows,
28029
+ rooms: records.kind(deviceManagerRecordKinds.rooms),
28030
+ zones: records.kind(deviceManagerRecordKinds.zones),
28031
+ report: (message, meta) => this.ctx.logger.info(message, { meta })
28032
+ })));
28033
+ const rooms = RoomStore.of(records);
28034
+ await rooms.load();
28035
+ const tagApi = this.ctx.api?.tags;
28036
+ const tagNames = new TagNames(tagApi === void 0 ? null : {
28037
+ list: () => tagApi.listTags.query({}),
28038
+ ensure: (name) => tagApi.ensureTag.mutate({ name })
28039
+ }, this.ctx.logger.child("tag-names"));
28040
+ deviceRows.setDerivedNames({
28041
+ room: (id) => rooms.nameOf(id),
28042
+ tag: (id) => tagNames.nameOf(id)
28043
+ });
27180
28044
  const tombstones = DeviceTombstoneStore.of(records, this.ctx.logger.child("tombstones"));
27181
28045
  const identityLinksStore = IdentityLinksStore.of(records);
27182
28046
  await identityLinksStore.load();
@@ -27281,6 +28145,10 @@ var DeviceManagerAddon = class extends BaseAddon {
27281
28145
  const templates = this.makeTemplateActions();
27282
28146
  const pctx = {
27283
28147
  host: this.providerHost,
28148
+ rooms,
28149
+ freshTagNames: () => tagNames.fresh(),
28150
+ tagNameOf: (id) => tagNames.nameOf(id),
28151
+ ensureTagIds: (names) => tagNames.ensureIds(names),
27284
28152
  metaStore,
27285
28153
  settings,
27286
28154
  registry,
@@ -27326,11 +28194,29 @@ var DeviceManagerAddon = class extends BaseAddon {
27326
28194
  } catch (err) {
27327
28195
  this.ctx.logger.warn("linked-devices manual backfill failed — auto links are NOT materialised", { meta: { error: errMsg$1(err) } });
27328
28196
  }
28197
+ try {
28198
+ await this.runMigrations(defineAddonMigrations(ORPHAN_CHILDREN_MIGRATIONS, {
28199
+ listRows: async () => (await deviceRows.listAll()).map((row) => ({
28200
+ id: row.meta.id,
28201
+ parentDeviceId: row.meta.parentDeviceId
28202
+ })),
28203
+ rowLimit: DEVICE_ROWS_FLEET_LIMIT,
28204
+ removeDevice: (deviceId) => removeDevice(pctx, { deviceId }),
28205
+ summary: (counts) => this.ctx.logger.info("device-manager: orphan children found", { meta: counts }),
28206
+ info: (message, deviceId, parentDeviceId) => this.ctx.logger.info(message, {
28207
+ tags: { deviceId },
28208
+ meta: { parentDeviceId }
28209
+ })
28210
+ }));
28211
+ } catch (err) {
28212
+ this.ctx.logger.warn("orphan-children migration failed — rows stay as they are", { meta: { error: errMsg$1(err) } });
28213
+ }
27329
28214
  const provider = {
27330
28215
  resolveDeviceOwnerSync: (deviceId) => resolveDeviceOwnerSync(pctx, deviceId),
27331
28216
  resolveNativeCapOwnerSync: (capName, deviceId) => resolveNativeCapOwnerSync(pctx, capName, deviceId),
27332
28217
  allocateDeviceId: (input) => allocateDeviceId(pctx, input),
27333
28218
  migrateDevice: (input) => migrateDevice(pctx, input),
28219
+ repairMigrationSecrets: (input) => repairMigrationSecrets(pctx, input),
27334
28220
  registerDevice: (input) => registerDevice(pctx, input),
27335
28221
  removeDevice: (input) => removeDevice(pctx, input),
27336
28222
  listDeletedSince: ({ sinceMs }) => tombstones.listSince(sinceMs),
@@ -27376,6 +28262,10 @@ var DeviceManagerAddon = class extends BaseAddon {
27376
28262
  setMetadata: (input) => setMetadata(pctx, input),
27377
28263
  setDisabled: (input) => setDisabled(pctx, input),
27378
28264
  loadRuntimeState: (input) => loadRuntimeState(pctx, input),
28265
+ ensureRoom: (input) => ensureRoom(pctx, input),
28266
+ listRooms: () => listRooms(pctx),
28267
+ updateRoom: (input) => updateRoom(pctx, input),
28268
+ deleteRoom: (input) => deleteRoom(pctx, input),
27379
28269
  listLocations: () => listLocations(pctx),
27380
28270
  addLocation: (input) => addLocation(pctx, input),
27381
28271
  removeLocation: (input) => removeLocation(pctx, input),
@@ -27595,7 +28485,8 @@ var DeviceManagerAddon = class extends BaseAddon {
27595
28485
  get removalHooksCleanup() {
27596
28486
  if (this.removalHooksCleanupImpl === null) this.removalHooksCleanupImpl = createRemovalCleanup({
27597
28487
  logger: this.ctx.logger,
27598
- label: "device removal hooks"
28488
+ label: "device removal hooks",
28489
+ concurrent: true
27599
28490
  });
27600
28491
  return this.removalHooksCleanupImpl;
27601
28492
  }