@camstack/server 1.2.898 → 1.2.900

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 (120) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/api/trpc/cap-router-runtime.js +1 -0
  3. package/dist/api/trpc/generated-cap-mounts.js +2 -1
  4. package/dist/api/trpc/generated-cap-routers.js +1944 -1870
  5. package/dist/core/addon/hub-addon-api.js +1 -0
  6. package/dist/core/moleculer/moleculer.service.js +1 -0
  7. package/package.json +10 -15
  8. package/system/dist/addon-runner.js +111 -8
  9. package/system/dist/addon-runner.mjs +111 -8
  10. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  11. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  12. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  13. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  14. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  15. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  16. package/system/dist/builtins/autotrack/index.js +1 -1
  17. package/system/dist/builtins/autotrack/index.mjs +1 -1
  18. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  19. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  20. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  21. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  22. package/system/dist/builtins/camera-grid/index.js +1 -1
  23. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  24. package/system/dist/builtins/composer/composer.addon.js +4 -4
  25. package/system/dist/builtins/composer/composer.addon.mjs +4 -4
  26. package/system/dist/builtins/console-logging/index.js +1 -1
  27. package/system/dist/builtins/console-logging/index.mjs +1 -1
  28. package/system/dist/builtins/core-blocks/composition-api.d.ts +37 -1
  29. package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +14 -0
  30. package/system/dist/builtins/core-blocks/core-blocks.addon.js +516 -7
  31. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +516 -7
  32. package/system/dist/builtins/core-blocks/link-contributions.d.ts +85 -0
  33. package/system/dist/builtins/core-blocks/power-source-service.d.ts +25 -1
  34. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  35. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  36. package/system/dist/builtins/device-manager/command-holds.d.ts +2 -0
  37. package/system/dist/builtins/device-manager/device-identifiers-action.d.ts +8 -0
  38. package/system/dist/builtins/device-manager/device-identity-index.d.ts +56 -2
  39. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +1 -0
  40. package/system/dist/builtins/device-manager/device-manager.addon.js +1329 -84
  41. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1316 -84
  42. package/system/dist/builtins/device-manager/device-meta-types.d.ts +9 -1
  43. package/system/dist/builtins/device-manager/device-provider-context.d.ts +3 -0
  44. package/system/dist/builtins/device-manager/device-row-store.d.ts +4 -2
  45. package/system/dist/builtins/device-manager/device-state-mirror.d.ts +7 -0
  46. package/system/dist/builtins/device-manager/identity-link-reconciler.d.ts +66 -0
  47. package/system/dist/builtins/device-manager/identity-links-store.d.ts +22 -0
  48. package/system/dist/builtins/device-manager/record-kinds.d.ts +2 -1
  49. package/system/dist/builtins/device-manager/state-refresh-scheduler.d.ts +92 -0
  50. package/system/dist/builtins/device-manager/state-refresh-wiring.d.ts +23 -0
  51. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  52. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  53. package/system/dist/builtins/keychain/index.js +4 -4
  54. package/system/dist/builtins/keychain/index.mjs +4 -4
  55. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  56. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  57. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  58. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  59. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  60. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  61. package/system/dist/builtins/loki-logging/index.js +1 -1
  62. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  63. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  64. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  65. package/system/dist/builtins/platform-probe/index.js +1 -1
  66. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  67. package/system/dist/builtins/record-entries/index.js +1 -1
  68. package/system/dist/builtins/record-entries/index.mjs +1 -1
  69. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  70. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  71. package/system/dist/builtins/snapshot/index.js +1 -1
  72. package/system/dist/builtins/snapshot/index.mjs +1 -1
  73. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  74. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  75. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  76. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  77. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  78. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  79. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  80. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  81. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  82. package/system/dist/builtins/system-config/system-config.addon.mjs +284 -284
  83. package/system/dist/builtins/winston-logging/index.js +1 -1
  84. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  85. package/system/dist/{capture-engine-BWS0KTbm.js → capture-engine-B3csK2sW.js} +1 -1
  86. package/system/dist/{capture-engine-DBQDaDxJ.mjs → capture-engine-CCAzcezv.mjs} +1 -1
  87. package/system/dist/{composition-sources-CGUWmf-T.mjs → composition-sources-BX7u-Hdf.mjs} +1 -1
  88. package/system/dist/{composition-sources-CDOW1dnY.js → composition-sources-Bkbk5Oh5.js} +1 -1
  89. package/system/dist/{constants-BwrRoq-j.js → constants-BqxCksdV.js} +1 -1
  90. package/system/dist/{constants-BmrLkwZs.mjs → constants-_bOm_ae5.mjs} +1 -1
  91. package/system/dist/{device-ca-BGgZXEto.mjs → device-ca-DRqN1P5Y.mjs} +1 -1
  92. package/system/dist/{device-ca-DiuwWyZY.js → device-ca-KNx_DazP.js} +1 -1
  93. package/system/dist/{dist-CCd8IeIU.js → dist-BNrIzdrJ.js} +514 -7
  94. package/system/dist/{dist-D7t8wLTF.mjs → dist-S-zGcCEr.mjs} +455 -8
  95. package/system/dist/file-host-worker.js +1 -1
  96. package/system/dist/file-host-worker.mjs +1 -1
  97. package/system/dist/{hub-identity-BohJeqdO.mjs → hub-identity-DSdbZxeR.mjs} +1 -1
  98. package/system/dist/{hub-identity-G_ZdyPpc.js → hub-identity-pN0LtUhx.js} +1 -1
  99. package/system/dist/{hub-mdns-ciao-CKD4EgkG.js → hub-mdns-ciao-GafEbDm8.js} +2 -2
  100. package/system/dist/{hub-mdns-ciao-D5RxSMrH.mjs → hub-mdns-ciao-wAcv5VBY.mjs} +2 -2
  101. package/system/dist/index.js +59 -12
  102. package/system/dist/index.mjs +55 -14
  103. package/system/dist/kernel/cap-router-builder.d.ts +7 -0
  104. package/system/dist/kernel/command-follow-up.d.ts +33 -0
  105. package/system/dist/kernel/command-observation.d.ts +3 -0
  106. package/system/dist/kernel/index.d.ts +3 -0
  107. package/system/dist/kernel/moleculer/child-cap-descriptors.d.ts +3 -1
  108. package/system/dist/kernel/moleculer/device-cap-proxy.d.ts +2 -1
  109. package/system/dist/kernel/state-refresh-policies.d.ts +53 -0
  110. package/system/dist/kernel/transport/child-cap-protocol.d.ts +6 -1
  111. package/system/dist/kernel/transport/local-child-registry.d.ts +14 -0
  112. package/system/dist/{legacy-integration-rows-door-Rm9JmIsl.mjs → legacy-integration-rows-door--186Wij_.mjs} +1 -1
  113. package/system/dist/{legacy-integration-rows-door-BgCl68ek.js → legacy-integration-rows-door-B1swGb0r.js} +1 -1
  114. package/system/dist/{rename-composition-block-DNO3mNEO.mjs → rename-composition-block-Cf5syiM4.mjs} +1 -1
  115. package/system/dist/{rename-composition-block-2Z2ED7Og.js → rename-composition-block-gJ_4GdHr.js} +1 -1
  116. package/system/dist/{restore-archive-2L5TymvF.mjs → restore-archive-D7UwwT1L.mjs} +82 -82
  117. package/system/dist/{restore-archive-CZkQO8t3.js → restore-archive-DXi9iBay.js} +1 -1
  118. package/system/dist/{wal-maintenance-YjDJ73Qd.js → wal-maintenance-BA9XNPvt.js} +0 -0
  119. package/system/dist/{wal-maintenance-BMYe_n18.mjs → wal-maintenance-s3KdED98.mjs} +0 -0
  120. package/system/package.json +1 -1
@@ -1,7 +1,7 @@
1
- import { A as ConditionMirror, Ao as sameIdentifiers, Br as deviceExtensionCapability, Dl as isCommand$1, Dr as createDeviceExtensionProvider, Ds as workloadCapability, Ea as normalizeUnit, Fo as searchRank, Fr as defineExtensionSlotProvider, Gc as SECRET_CLEAR, Go as siteZoneKey, Hr as deviceManagerCapability, Hs as capAppliesToDeviceKind, Il as isSecretMarker, It as MINUTES_PER_DAY, J as DEVICE_TEMPLATE_FILTERS, Jr as deviceStatusCapability, Ki as isWorkloadSettled, Ll as isSecretMarkerLike, Ml as isKeychainStoredField, Na as parseStreamParamsFormPatch, On as WORKLOAD_TRANSITION_CATEGORY, Oo as runtimeFieldUnit, Os as workloadTransition, Pl as isSecretClear, Q as DEVICE_TEMPLATE_VALUES_CAP, Qa as reconcileReportedFeatures, Qn as buildStreamParamsConfigSchema, Qr as enumerateSchemaFields, R as DAY_NAMES, Ta as normalizeTags, Ti as identifierStrength, To as resolveTemplateRef, U as DEVICE_IDENTIFIER_KEYS, Ur as deviceOffersActions, Vi as isKernelDerivedFeature, Vs as canonicalStoredDeviceType, X as DEVICE_TEMPLATE_MAX_OUTPUT, Xi as legacyAutoLinkIds, Y as DEVICE_TEMPLATE_MAX_LENGTH, Zc as WELL_KNOWN_TAB_MAP, Zl as resolveSecretMarkers, Zr as enumerateItemArrayFields, _l as defineRecordKinds, _u as EventCategory$1, at as DeviceTombstoneSchema, au as toSecretFieldView, cu as vocabActionIdFor, eu as secretTreeFromPaths, fu as DeviceFeature, gi as formatMinutes, hc as BaseAddon, hu as errMsg$1, il as auditedFields, it as DeviceStatusSchema, kl as isDeviceConfigCap, kn as WorkloadStateSchema, ko as runtimeStatePolicyFor, ll as collectZodSecretPaths$1, ln as STREAM_PROFILE_META, ma as mergeIdentifiers, mu as DeviceType$1, na as locationIconKey, nc as implementedMethodsOf$1, nr as canonicalIconKey, nt as DeviceIdentifiersSchema, oi as extractSourceInfoFromMetadata, or as checkDeviceAlias, ot as DiscoveryProposalBodySchema, ou as transformSecretWrite, po as resolveCommandHold, pu as DeviceRole, qr as deviceStateCapability, ri as expandContainer, ru as sleep$2, s as ALL_CAPABILITY_DEFINITIONS, su as userError, ul as commandEffect, ut as ExportNameRefusedError, vt as FieldClaimModeSchema, x as CAP_NAMES_WITH_STATUS, xl as expandCapMethods$1, y as CAMERA_SWITCH_ORDER, yi as generateDeviceAlias, yt as FieldClaimSchema, zi as isEmptyIdentifiers, zo as settleDeviceFeatures } from "../../dist-D7t8wLTF.mjs";
1
+ import { $ as DEVICE_TEMPLATE_VALUES_CAP, $r as deviceStatusCapability, Bo as sameIdentifiers, Br as defineExtensionSlotProvider, Bt as MINUTES_PER_DAY, C as COMMAND_BURST_OFFSETS_MS, Co as resolveCommandHold, Cu as DeviceRole, Dl as defineRecordKinds, Du as EventCategory$1, Fa as normalizeUnit, Fo as resolveTemplateRef, Go as searchRank, Gr as deviceExtensionCapability, Ha as parseStreamParamsFormPatch, Hl as isKeychainStoredField, Jr as deviceOffersActions, Kl as isSecretMarker, Ll as isCommand$1, Ls as workloadCapability, Mi as identityLinkId, Mr as createDeviceExtensionProvider, Mt as IdentityLinkBodySchema, Ni as identityLinkSidesRefusal, Nn as WORKLOAD_TRANSITION_CATEGORY, Pa as normalizeTags, Pn as WorkloadStateSchema, Qr as deviceStateCapability, Qs as capAppliesToDeviceKind, Ro as runtimeFieldUnit, Rs as workloadTransition, Sa as mergeIdentifiers, Si as formatMinutes, Su as DeviceFeature, Tc as BaseAddon, Ti as generateDeviceAlias, Tu as errMsg$1, W as DEVICE_IDENTIFIER_KEYS, Wl as isSecretClear, X as DEVICE_TEMPLATE_MAX_LENGTH, Y as DEVICE_TEMPLATE_FILTERS, Yi as isKernelDerivedFeature, Yo as settleDeviceFeatures, Z as DEVICE_TEMPLATE_MAX_OUTPUT, Zs as canonicalStoredDeviceType, Zt as PUSH_CONFIRM_WINDOW_MS, _u as userError, bl as commandEffect, bt as FieldClaimModeSchema, ct as DiscoveryProposalBodySchema, dr as checkDeviceAlias, ea as isWorkloadSettled, fc as implementedMethodsOf$1, fi as extractSourceInfoFromMetadata, ft as ExportNameRefusedError, gu as transformSecretWrite, hu as toSecretFieldView, ia as legacyAutoLinkIds, ii as enumerateSchemaFields, it as DeviceIdentifiersSchema, j as ConditionMirror, ji as identifierStrength, jl as expandCapMethods$1, li as expandContainer, ml as auditedFields, mn as STREAM_PROFILE_META, ot as DeviceStatusSchema, pu as sleep$2, qi as isEmptyIdentifiers, ql as isSecretMarkerLike, qr as deviceManagerCapability, ri as enumerateItemArrayFields, rr as buildStreamParamsConfigSchema, rt as DeviceIdentifierKeySchema, s as ALL_CAPABILITY_DEFINITIONS, sl as WELL_KNOWN_TAB_MAP, so as reconcileReportedFeatures, sr as canonicalIconKey, st as DeviceTombstoneSchema, su as resolveSecretMarkers, ti as effectiveRefreshIntervalMs, tl as SECRET_CLEAR, ts as siteZoneKey, ua as locationIconKey, uu as secretTreeFromPaths, vu as vocabActionIdFor, wu as DeviceType$1, x as CAP_NAMES_WITH_STATUS, xt as FieldClaimSchema, y as CAMERA_SWITCH_ORDER, yl as collectZodSecretPaths$1, z as DAY_NAMES, zl as isDeviceConfigCap, zo as runtimeStatePolicyFor } from "../../dist-S-zGcCEr.mjs";
2
2
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
3
3
  import { a as redactLogText, i as redactLogMeta, n as isSecretArgumentKey } from "../../log-redactor-XLDrPzOi.mjs";
4
- import { n as renameCompositionBlock, t as composedBlockIdOf } from "../../rename-composition-block-DNO3mNEO.mjs";
4
+ import { n as renameCompositionBlock, t as composedBlockIdOf } from "../../rename-composition-block-Cf5syiM4.mjs";
5
5
  import { t as prefixRange } from "../../prefix-range-Dl0znowN.mjs";
6
6
  import { t as loadPrefixed } from "../../prefix-walk-DAOBSyH1.mjs";
7
7
  import { n as purgeRetiredSettingsRows } from "../../retired-settings-keys-u6xQA6r7.mjs";
@@ -479,7 +479,8 @@ function toDeviceInfo(addonId, device, metadata = null, metaRow = null) {
479
479
  ...metaRow?.primaryChildPreference !== void 0 ? { primaryChildPreference: metaRow.primaryChildPreference } : {},
480
480
  ...metaRow?.tags !== void 0 ? { tags: metaRow.tags } : {},
481
481
  ...metaRow?.display !== void 0 ? { display: metaRow.display } : {},
482
- ...metaRow?.identifiers !== void 0 ? { identifiers: metaRow.identifiers } : {}
482
+ ...metaRow?.identifiers !== void 0 ? { identifiers: metaRow.identifiers } : {},
483
+ ...metaRow?.attachedIdentifiers !== void 0 ? { attachedIdentifiers: metaRow.attachedIdentifiers } : {}
483
484
  };
484
485
  }
485
486
  function resolveDeviceById(registry, deviceId) {
@@ -3064,6 +3065,7 @@ async function listAll(pctx, input) {
3064
3065
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3065
3066
  ...m.display !== void 0 ? { display: m.display } : {},
3066
3067
  ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3068
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {},
3067
3069
  ...(() => {
3068
3070
  if (slim) return {};
3069
3071
  const si = projectSourceInfo(persistedConfig ?? {}, stableId, aid, metadata);
@@ -3118,6 +3120,7 @@ async function getDevice(pctx, input) {
3118
3120
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3119
3121
  ...m.display !== void 0 ? { display: m.display } : {},
3120
3122
  ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3123
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {},
3121
3124
  ...sourceInfoGetDevice !== void 0 ? { sourceInfo: sourceInfoGetDevice } : {}
3122
3125
  };
3123
3126
  }
@@ -3199,6 +3202,7 @@ function projectChildren(pctx, parentDeviceId, ownerAddonId, childRows, liveChil
3199
3202
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3200
3203
  ...m.display !== void 0 ? { display: m.display } : {},
3201
3204
  ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3205
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {},
3202
3206
  ...sourceInfoChild !== void 0 ? { sourceInfo: sourceInfoChild } : {}
3203
3207
  });
3204
3208
  }
@@ -7495,6 +7499,10 @@ function removalSteps(pctx, deviceId, providerAddonId, deletedAt) {
7495
7499
  return (await purge(deviceId)).length;
7496
7500
  }
7497
7501
  },
7502
+ {
7503
+ store: "identity-links",
7504
+ run: async () => pctx.identityLinks === void 0 ? 0 : pctx.identityLinks.removeDevice(deviceId)
7505
+ },
7498
7506
  {
7499
7507
  store: "device-config",
7500
7508
  run: async () => {
@@ -7643,7 +7651,8 @@ async function loadMeta(pctx, input) {
7643
7651
  ...m.integrationId !== void 0 ? { integrationId: m.integrationId } : {},
7644
7652
  ...m.linkDeviceId !== void 0 ? { linkDeviceId: m.linkDeviceId } : {},
7645
7653
  ...m.role !== void 0 ? { role: m.role } : {},
7646
- ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {}
7654
+ ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
7655
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {}
7647
7656
  };
7648
7657
  }
7649
7658
  /**
@@ -8832,20 +8841,41 @@ function stampedCaller(input) {
8832
8841
  const raw = Reflect.get(Object(input), "callerAddonId");
8833
8842
  return typeof raw === "string" && raw.length > 0 ? raw : null;
8834
8843
  }
8844
+ var METHOD_OF = {
8845
+ identifiers: "setIdentifiers",
8846
+ attachedIdentifiers: "setAttachedIdentifiers"
8847
+ };
8835
8848
  async function setIdentifiers(pctx, input) {
8849
+ return writeDeclaredIdentity(pctx, input, "identifiers");
8850
+ }
8851
+ /**
8852
+ * `device-manager.setAttachedIdentifiers` (D1063): the identity of the device at
8853
+ * the far end of this device's physical link. Same owner check, normalisation
8854
+ * and merge as {@link setIdentifiers}, its own column.
8855
+ */
8856
+ async function setAttachedIdentifiers(pctx, input) {
8857
+ return writeDeclaredIdentity(pctx, input, "attachedIdentifiers");
8858
+ }
8859
+ /** The unread keys the merged declaration still holds, sorted: kept, not seen now. */
8860
+ function retainedKeys(merged, unread) {
8861
+ if (merged === null) return [];
8862
+ return [...new Set(unread)].filter((key) => merged[key] !== void 0).sort();
8863
+ }
8864
+ async function writeDeclaredIdentity(pctx, input, column) {
8865
+ const method = METHOD_OF[column];
8836
8866
  const { deviceId } = input;
8837
8867
  const logger = pctx.host.ctx.logger;
8838
8868
  const caller = stampedCaller(input);
8839
8869
  const parsed = DeviceIdentifiersSchema.nullable().safeParse(input.identifiers);
8840
8870
  if (!parsed.success) {
8841
- logger.warn("setIdentifiers refused — the declaration is not in its normalised form", {
8871
+ logger.warn(`${method} refused — the declaration is not in its normalised form`, {
8842
8872
  tags: { deviceId },
8843
8873
  meta: {
8844
8874
  caller,
8845
8875
  issues: parsed.error.issues.map((i) => i.path.join("."))
8846
8876
  }
8847
8877
  });
8848
- throw new SetIdentifiersRefusedError("invalid", `[device-manager] setIdentifiers: device ${deviceId} — declaration not normalised (use normaliseIdentifiers)`);
8878
+ throw new SetIdentifiersRefusedError("invalid", `[device-manager] ${method}: device ${deviceId} — declaration not normalised (use normaliseIdentifiers)`);
8849
8879
  }
8850
8880
  const next = parsed.data === null || isEmptyIdentifiers(parsed.data) ? null : parsed.data;
8851
8881
  const outcome = await pctx.metaStore.withMetaWriteLock(async () => {
@@ -8855,25 +8885,39 @@ async function setIdentifiers(pctx, input) {
8855
8885
  kind: "not-owner",
8856
8886
  owner: persisted.addonId
8857
8887
  };
8858
- const stored = persisted.meta.identifiers ?? null;
8888
+ const stored = persisted.meta[column] ?? null;
8859
8889
  const merged = mergeIdentifiers(stored, next, input.unread ?? []);
8860
- if (sameIdentifiers(stored, merged)) return { kind: "unchanged" };
8861
- await pctx.metaStore.rows.patch(deviceId, { identifiers: merged });
8890
+ if (column === "identifiers") {
8891
+ if (sameIdentifiers(stored, merged)) return { kind: "unchanged" };
8892
+ await pctx.metaStore.rows.patch(deviceId, { identifiers: merged });
8893
+ return {
8894
+ kind: "written",
8895
+ value: merged
8896
+ };
8897
+ }
8898
+ const retained = retainedKeys(merged, input.unread ?? []);
8899
+ const storedRetained = persisted.meta.attachedRetained ?? [];
8900
+ const sameRetained = retained.join(",") === storedRetained.join(",");
8901
+ if (sameIdentifiers(stored, merged) && sameRetained) return { kind: "unchanged" };
8902
+ await pctx.metaStore.rows.patch(deviceId, {
8903
+ attachedIdentifiers: merged,
8904
+ attachedRetained: retained.length === 0 ? null : retained
8905
+ });
8862
8906
  return {
8863
8907
  kind: "written",
8864
8908
  value: merged
8865
8909
  };
8866
8910
  });
8867
- if (outcome.kind === "unknown-device") throw new SetIdentifiersRefusedError("unknown-device", `[device-manager] setIdentifiers: unknown device id=${deviceId}`);
8911
+ if (outcome.kind === "unknown-device") throw new SetIdentifiersRefusedError("unknown-device", `[device-manager] ${method}: unknown device id=${deviceId}`);
8868
8912
  if (outcome.kind === "not-owner") {
8869
- logger.warn("setIdentifiers refused — only the owning provider declares identifiers", {
8913
+ logger.warn(`${method} refused — only the owning provider declares identifiers`, {
8870
8914
  tags: { deviceId },
8871
8915
  meta: {
8872
8916
  caller,
8873
8917
  owner: outcome.owner
8874
8918
  }
8875
8919
  });
8876
- throw new SetIdentifiersRefusedError("not-owner", `[device-manager] setIdentifiers: device ${deviceId} belongs to ${outcome.owner}; caller ${caller ?? "(unstamped)"} may not declare its identifiers`);
8920
+ throw new SetIdentifiersRefusedError("not-owner", `[device-manager] ${method}: device ${deviceId} belongs to ${outcome.owner}; caller ${caller ?? "(unstamped)"} may not declare its identifiers`);
8877
8921
  }
8878
8922
  if (outcome.kind === "unchanged") return;
8879
8923
  pctx.host.ctx.eventBus.emit({
@@ -8886,12 +8930,395 @@ async function setIdentifiers(pctx, input) {
8886
8930
  category: EventCategory$1.DeviceMetaChanged,
8887
8931
  data: {
8888
8932
  deviceId,
8889
- field: "identifiers",
8933
+ field: column,
8890
8934
  value: outcome.value
8891
8935
  }
8892
8936
  });
8893
8937
  }
8894
8938
  //#endregion
8939
+ //#region src/builtins/device-manager/identity-link-reconciler.ts
8940
+ /**
8941
+ * Turns the identity index's link candidates into `identity-links` records
8942
+ * (D1063), and serves the operator's decisions on them.
8943
+ *
8944
+ * | Situation | Result |
8945
+ * | ------------------------------------------- | ---------------------------------------------- |
8946
+ * | `auto` candidate, no row | `linked` / `auto`, `identity-link.created` |
8947
+ * | `proposal` candidate, no row | `proposed`, no event |
8948
+ * | `proposed` row, candidate now `auto` | `linked` / `auto`, created |
8949
+ * | `dismissed` row | stays dismissed: nothing re-proposes it |
8950
+ * | `linked`/`auto` row, evidence gone | row deleted, `identity-link.lost` evidence-gone |
8951
+ * | `linked`/`operator` row, evidence gone | kept, flagged `evidenceGone`, `lost` evidence-gone |
8952
+ * | `linked`/`operator` flagged, evidence back | flag cleared, `identity-link.created` |
8953
+ * | `proposed` row, evidence gone | row deleted, no event (it never linked) |
8954
+ *
8955
+ * "Evidence gone" is judged from the PERSISTED identifiers, which already keep
8956
+ * an unread value (D49): a camera rebooting, a port that read no client this
8957
+ * poll, change nothing. A flagged operator link never acts: `power-source`
8958
+ * refuses through it and core-blocks withdraws its contribution, so a fresh link
8959
+ * on another port can contribute. It waits for the operator (Unlink) or for its
8960
+ * evidence to return. A link whose side has no row right now is left alone —
8961
+ * a removed device is the `identity-links` removal step's, never a guess here.
8962
+ *
8963
+ * Runs after the seed and on every identity change the index reports,
8964
+ * coalesced: a pass already queued absorbs the next request. No timer. Every
8965
+ * write — a pass, an operator decision, a removal — runs on one chain.
8966
+ */
8967
+ var NOT_LOADED = "the identity links have not been read yet";
8968
+ function sameEvidence(x, y) {
8969
+ return JSON.stringify(x) === JSON.stringify(y);
8970
+ }
8971
+ function sameSide(x, y) {
8972
+ return x.deviceId === y.deviceId && x.addonId === y.addonId && x.stableId === y.stableId;
8973
+ }
8974
+ function payloadOf(link, reason) {
8975
+ return {
8976
+ linkId: link.id,
8977
+ kind: link.kind,
8978
+ aDeviceId: link.a.deviceId,
8979
+ bDeviceId: link.b.deviceId,
8980
+ origin: link.origin,
8981
+ ...reason !== void 0 ? { reason } : {}
8982
+ };
8983
+ }
8984
+ var IdentityLinkReconciler = class {
8985
+ deps;
8986
+ tail = Promise.resolve();
8987
+ passQueued = false;
8988
+ now;
8989
+ constructor(deps) {
8990
+ this.deps = deps;
8991
+ this.now = deps.now ?? (() => Date.now());
8992
+ }
8993
+ /** Queue one pass; a pass already queued (not started) absorbs this request. */
8994
+ requestPass() {
8995
+ if (this.passQueued) return;
8996
+ this.passQueued = true;
8997
+ this.serialized(async () => {
8998
+ this.passQueued = false;
8999
+ await this.pass();
9000
+ }).catch((err) => {
9001
+ this.deps.logger.warn("identity-link pass failed — the next identity change retries", { meta: { error: errMsg$1(err) } });
9002
+ });
9003
+ }
9004
+ /** Resolves when every queued write has run (tests, boot). */
9005
+ async settled() {
9006
+ await this.serialized(async () => void 0);
9007
+ }
9008
+ list(deviceId) {
9009
+ const links = this.deps.store.list();
9010
+ if (links === null) return {
9011
+ status: "not-loaded",
9012
+ reason: NOT_LOADED
9013
+ };
9014
+ return {
9015
+ status: "answered",
9016
+ links: [...deviceId === void 0 ? links : links.filter((l) => l.a.deviceId === deviceId || l.b.deviceId === deviceId)].sort((x, y) => x.id.localeCompare(y.id))
9017
+ };
9018
+ }
9019
+ confirm(linkId) {
9020
+ return this.decide(linkId, "proposed", async (link) => {
9021
+ const next = {
9022
+ ...link,
9023
+ state: "linked",
9024
+ origin: "operator",
9025
+ decidedAt: this.now()
9026
+ };
9027
+ await this.deps.store.put(next);
9028
+ this.log("identity link confirmed by the operator", next);
9029
+ this.deps.emit(EventCategory$1.IdentityLinkCreated, payloadOf(next));
9030
+ return next;
9031
+ });
9032
+ }
9033
+ dismiss(linkId) {
9034
+ return this.decide(linkId, "proposed", async (link) => {
9035
+ const next = this.dismissed(link);
9036
+ await this.deps.store.put(next);
9037
+ this.log("identity link proposal dismissed by the operator", next);
9038
+ return next;
9039
+ });
9040
+ }
9041
+ unlink(linkId) {
9042
+ return this.decide(linkId, "linked", async (link) => {
9043
+ const next = this.dismissed(link);
9044
+ await this.deps.store.put(next);
9045
+ this.log("identity link unlinked by the operator", next);
9046
+ this.deps.emit(EventCategory$1.IdentityLinkLost, payloadOf(next, "operator-unlinked"));
9047
+ return next;
9048
+ });
9049
+ }
9050
+ /** The `identity-links` removal step (D864): every link naming the device goes. */
9051
+ removeDevice(deviceId) {
9052
+ return this.serialized(async () => {
9053
+ const links = this.deps.store.list();
9054
+ if (links === null) throw new Error(NOT_LOADED);
9055
+ let removed = 0;
9056
+ for (const link of links) {
9057
+ if (link.a.deviceId !== deviceId && link.b.deviceId !== deviceId) continue;
9058
+ await this.deps.store.delete(link.id);
9059
+ removed += 1;
9060
+ if (link.state === "linked") {
9061
+ this.log("identity link lost — a side was removed", link, deviceId);
9062
+ this.deps.emit(EventCategory$1.IdentityLinkLost, payloadOf(link, "device-removed"));
9063
+ }
9064
+ }
9065
+ return removed;
9066
+ });
9067
+ }
9068
+ /** One pass over every candidate and every stored link. */
9069
+ async pass() {
9070
+ const answer = this.deps.candidates();
9071
+ const links = this.deps.store.list();
9072
+ if (answer.status !== "answered" || links === null) return;
9073
+ const byId = new Map(links.map((l) => [l.id, l]));
9074
+ const seen = /* @__PURE__ */ new Set();
9075
+ for (const candidate of answer.candidates) {
9076
+ const id = identityLinkId(candidate.kind, candidate.a, candidate.b);
9077
+ if (seen.has(id)) continue;
9078
+ seen.add(id);
9079
+ await this.applyCandidate(id, candidate, byId.get(id) ?? null);
9080
+ }
9081
+ for (const link of links) {
9082
+ if (seen.has(link.id)) continue;
9083
+ const aId = answer.deviceIdOf(link.a.addonId, link.a.stableId);
9084
+ const bId = answer.deviceIdOf(link.b.addonId, link.b.stableId);
9085
+ if (aId === null || bId === null) continue;
9086
+ await this.applyEvidenceGone(link);
9087
+ }
9088
+ }
9089
+ async applyCandidate(id, candidate, stored) {
9090
+ if (identityLinkSidesRefusal(candidate.kind, candidate.aRole) !== null) {
9091
+ this.deps.logger.debug("identity candidate skipped — the attaching side has the wrong role", {
9092
+ tags: { deviceId: candidate.a.deviceId },
9093
+ meta: {
9094
+ kind: candidate.kind,
9095
+ role: candidate.aRole,
9096
+ other: candidate.b.deviceId
9097
+ }
9098
+ });
9099
+ return;
9100
+ }
9101
+ if (stored === null) {
9102
+ const auto = candidate.confidence === "auto";
9103
+ const link = {
9104
+ id,
9105
+ kind: candidate.kind,
9106
+ a: candidate.a,
9107
+ b: candidate.b,
9108
+ state: auto ? "linked" : "proposed",
9109
+ origin: "auto",
9110
+ evidence: candidate.keys,
9111
+ createdAt: this.now(),
9112
+ ...auto ? { decidedAt: this.now() } : {}
9113
+ };
9114
+ await this.deps.store.put(link);
9115
+ this.log(auto ? "identity link created on strong evidence" : "identity link proposed", link);
9116
+ if (auto) this.deps.emit(EventCategory$1.IdentityLinkCreated, payloadOf(link));
9117
+ return;
9118
+ }
9119
+ if (stored.state === "dismissed") return;
9120
+ const upgrade = stored.state === "proposed" && candidate.confidence === "auto";
9121
+ const moved = !sameSide(stored.a, candidate.a) || !sameSide(stored.b, candidate.b) || !sameEvidence(stored.evidence, candidate.keys) || stored.evidenceGone === true;
9122
+ if (!upgrade && !moved) return;
9123
+ const returned = stored.state === "linked" && stored.evidenceGone === true;
9124
+ const { evidenceGone: _dropped, ...rest } = stored;
9125
+ const next = {
9126
+ ...rest,
9127
+ a: candidate.a,
9128
+ b: candidate.b,
9129
+ evidence: candidate.keys,
9130
+ ...upgrade ? {
9131
+ state: "linked",
9132
+ origin: "auto",
9133
+ decidedAt: this.now()
9134
+ } : {}
9135
+ };
9136
+ await this.deps.store.put(next);
9137
+ if (upgrade) {
9138
+ this.log("identity link created — the proposal now has strong evidence", next);
9139
+ this.deps.emit(EventCategory$1.IdentityLinkCreated, payloadOf(next));
9140
+ }
9141
+ if (returned) {
9142
+ this.log("identity link acts again — the evidence of a confirmed link is back", next);
9143
+ this.deps.emit(EventCategory$1.IdentityLinkCreated, payloadOf(next));
9144
+ }
9145
+ }
9146
+ async applyEvidenceGone(link) {
9147
+ if (link.state === "dismissed") return;
9148
+ if (link.state === "proposed") {
9149
+ await this.deps.store.delete(link.id);
9150
+ this.log("identity link proposal withdrawn — its evidence is gone", link);
9151
+ return;
9152
+ }
9153
+ if (link.origin === "operator") {
9154
+ if (link.evidenceGone === true) return;
9155
+ await this.deps.store.put({
9156
+ ...link,
9157
+ evidenceGone: true
9158
+ });
9159
+ this.warn("identity link no longer acts — confirmed by the operator, but its evidence is gone; Unlink it, or it acts again when the evidence returns", link);
9160
+ this.deps.emit(EventCategory$1.IdentityLinkLost, payloadOf(link, "evidence-gone"));
9161
+ return;
9162
+ }
9163
+ await this.deps.store.delete(link.id);
9164
+ this.log("identity link lost — its evidence is gone", link);
9165
+ this.deps.emit(EventCategory$1.IdentityLinkLost, payloadOf(link, "evidence-gone"));
9166
+ }
9167
+ dismissed(link) {
9168
+ return {
9169
+ ...link,
9170
+ state: "dismissed",
9171
+ origin: "operator",
9172
+ decidedAt: this.now()
9173
+ };
9174
+ }
9175
+ decide(linkId, from, apply) {
9176
+ return this.serialized(async () => {
9177
+ if (!this.deps.store.isLoaded()) return {
9178
+ ok: false,
9179
+ reason: "not-loaded",
9180
+ message: NOT_LOADED
9181
+ };
9182
+ const link = this.deps.store.get(linkId);
9183
+ if (link === null) return {
9184
+ ok: false,
9185
+ reason: "unknown-link",
9186
+ message: `no identity link ${linkId}`
9187
+ };
9188
+ if (link.state !== from) return {
9189
+ ok: false,
9190
+ reason: "wrong-state",
9191
+ message: `identity link ${linkId} is ${link.state}, not ${from}`
9192
+ };
9193
+ return {
9194
+ ok: true,
9195
+ link: await apply(link)
9196
+ };
9197
+ });
9198
+ }
9199
+ /** One line per side, so each camera's log carries it (`tags.deviceId`). */
9200
+ log(message, link, only) {
9201
+ this.lines("info", message, link, only);
9202
+ }
9203
+ warn(message, link) {
9204
+ this.lines("warn", message, link);
9205
+ }
9206
+ lines(level, message, link, only) {
9207
+ for (const side of [link.a, link.b]) {
9208
+ if (only !== void 0 && side.deviceId === only) continue;
9209
+ this.deps.logger[level](message, {
9210
+ tags: { deviceId: side.deviceId },
9211
+ meta: {
9212
+ linkId: link.id,
9213
+ kind: link.kind,
9214
+ state: link.state,
9215
+ origin: link.origin,
9216
+ other: side === link.a ? link.b.deviceId : link.a.deviceId,
9217
+ evidence: link.evidence.map((k) => k.key)
9218
+ }
9219
+ });
9220
+ }
9221
+ }
9222
+ serialized(write) {
9223
+ const run = this.tail.then(write, write);
9224
+ this.tail = run.then(() => void 0, () => void 0);
9225
+ return run;
9226
+ }
9227
+ };
9228
+ //#endregion
9229
+ //#region src/builtins/device-manager/record-kinds.ts
9230
+ var import_read_all_rows = require_read_all_rows();
9231
+ var _deviceManagerRecordKinds = defineRecordKinds({
9232
+ tombstones: {
9233
+ schema: DeviceTombstoneSchema.omit({ deviceId: true }),
9234
+ class: "ledger",
9235
+ writeTrigger: "`removeDevice` records one row per deleted device after the device row is gone; re-record keeps the earlier `deletedAt`",
9236
+ device: "none",
9237
+ at: "required",
9238
+ indexes: [{
9239
+ name: "deleted_at",
9240
+ fields: ["deletedAt"]
9241
+ }],
9242
+ retention: {
9243
+ owner: "device-manager",
9244
+ reason: "90 days (`DEVICE_TOMBSTONE_RETENTION_MS`), pruned whenever a tombstone is written or the list is read"
9245
+ }
9246
+ },
9247
+ "discovery-proposals": {
9248
+ schema: DiscoveryProposalBodySchema,
9249
+ class: "config",
9250
+ writeTrigger: "the passive listener and the 30-minute sweep of `local-network` re-see a device (`lastSeenAt` and `at` move); `dismissDiscoveryProposal` sets `dismissed`",
9251
+ device: "none",
9252
+ at: "required",
9253
+ indexes: [{
9254
+ name: "last_seen_at",
9255
+ fields: ["lastSeenAt"]
9256
+ }],
9257
+ retention: {
9258
+ ttlMs: 2160 * 60 * 60 * 1e3,
9259
+ from: "at"
9260
+ }
9261
+ },
9262
+ "identity-links": {
9263
+ schema: IdentityLinkBodySchema,
9264
+ class: "config",
9265
+ writeTrigger: "the identity-link reconciler sees a candidate appear, upgrade or lose its evidence; the operator confirms, dismisses or unlinks (D1063)",
9266
+ device: "none",
9267
+ at: "none",
9268
+ indexes: [{
9269
+ name: "a_device",
9270
+ fields: ["a.deviceId"]
9271
+ }, {
9272
+ name: "b_device",
9273
+ fields: ["b.deviceId"]
9274
+ }],
9275
+ retention: { none: "a link lives as long as both its devices; a dismissal is sticky (operator intent)" }
9276
+ }
9277
+ });
9278
+ var deviceManagerRecordKinds = _deviceManagerRecordKinds;
9279
+ _deviceManagerRecordKinds.tombstones;
9280
+ //#endregion
9281
+ //#region src/builtins/device-manager/identity-links-store.ts
9282
+ var IdentityLinksStore = class IdentityLinksStore {
9283
+ kind;
9284
+ links = null;
9285
+ constructor(kind) {
9286
+ this.kind = kind;
9287
+ }
9288
+ static of(records) {
9289
+ return new IdentityLinksStore(records.kind(deviceManagerRecordKinds["identity-links"]));
9290
+ }
9291
+ async load() {
9292
+ const rows = await (0, import_read_all_rows.readAllRows)(this.kind);
9293
+ this.links = new Map(rows.map((row) => [row.id, {
9294
+ id: row.id,
9295
+ ...row.data
9296
+ }]));
9297
+ }
9298
+ isLoaded() {
9299
+ return this.links !== null;
9300
+ }
9301
+ /** Every link; `null` until loaded. */
9302
+ list() {
9303
+ return this.links === null ? null : [...this.links.values()];
9304
+ }
9305
+ get(id) {
9306
+ return this.links?.get(id) ?? null;
9307
+ }
9308
+ async put(link) {
9309
+ const { id, ...data } = link;
9310
+ await this.kind.put({
9311
+ id,
9312
+ data
9313
+ });
9314
+ this.links?.set(id, link);
9315
+ }
9316
+ async delete(id) {
9317
+ await this.kind.delete(id);
9318
+ this.links?.delete(id);
9319
+ }
9320
+ };
9321
+ //#endregion
8895
9322
  //#region src/builtins/device-manager/device-identity-index.ts
8896
9323
  /**
8897
9324
  * The identifier INDEX (planning#593): identifier key → devices, so the
@@ -8913,7 +9340,13 @@ async function setIdentifiers(pctx, input) {
8913
9340
  * write that lands while the snapshot is in flight is buffered and replayed over
8914
9341
  * it, so the seed can never roll a newer write back.
8915
9342
  *
8916
- * Read-only: it finds candidates, it links nothing (that is step 3).
9343
+ * It finds candidates and links nothing itself: the `IdentityLinkReconciler`
9344
+ * (D1063) turns {@link linkCandidates} into link records, and is told of every
9345
+ * change that can move a candidate through {@link onIdentityChanged}.
9346
+ *
9347
+ * Beside the same-device pairs it pairs a device's `attachedIdentifiers` — the
9348
+ * far end of its physical link, a PoE port's wired client — with another
9349
+ * device's `identifiers`, graded by the same {@link classifyIdentityMatch}.
8917
9350
  */
8918
9351
  /** The `kind=value` keys of one declaration. */
8919
9352
  function keysOf(identifiers) {
@@ -8952,6 +9385,18 @@ function sideOf(d) {
8952
9385
  integrationId: d.integrationId
8953
9386
  };
8954
9387
  }
9388
+ function linkSideOf(d) {
9389
+ return {
9390
+ addonId: d.addonId,
9391
+ stableId: d.stableId,
9392
+ deviceId: d.deviceId
9393
+ };
9394
+ }
9395
+ /** The keys both declarations carry, ordered by key then value. */
9396
+ function sharedKeys(x, y) {
9397
+ const yKeys = new Set(keysOf(y));
9398
+ return keysOf(x).filter((k) => yKeys.has(k)).map(parseKey).filter((k) => k !== null).sort(compareKeys);
9399
+ }
8955
9400
  function compareKeys(x, y) {
8956
9401
  if (x.key !== y.key) return x.key < y.key ? -1 : 1;
8957
9402
  return x.value < y.value ? -1 : x.value > y.value ? 1 : 0;
@@ -8981,6 +9426,9 @@ function classifyIdentityMatch(keys) {
8981
9426
  var DeviceIdentityIndex = class {
8982
9427
  devices = /* @__PURE__ */ new Map();
8983
9428
  byKey = /* @__PURE__ */ new Map();
9429
+ listeners = /* @__PURE__ */ new Set();
9430
+ /** True while {@link seed} replays rows: one notification follows, not one per row. */
9431
+ seeding = false;
8984
9432
  /** `null` once seeded; until then, the writes to replay over the snapshot. */
8985
9433
  pending = [];
8986
9434
  /** Load from a fleet snapshot, then replay every write that landed meanwhile. */
@@ -8989,17 +9437,37 @@ var DeviceIdentityIndex = class {
8989
9437
  this.pending = null;
8990
9438
  this.devices.clear();
8991
9439
  this.byKey.clear();
8992
- for (const row of rows) this.rowWritten(row.meta);
8993
- for (const write of buffered) write(this);
9440
+ this.seeding = true;
9441
+ try {
9442
+ for (const row of rows) this.rowWritten(row.meta);
9443
+ for (const write of buffered) write(this);
9444
+ } finally {
9445
+ this.seeding = false;
9446
+ }
9447
+ this.changed();
9448
+ }
9449
+ /**
9450
+ * Called after every change that can move a candidate (identifiers, attached
9451
+ * identifiers, role, integration, a row written or removed) and after the
9452
+ * seed. Synchronous: the listener schedules its own work.
9453
+ */
9454
+ onIdentityChanged(listener) {
9455
+ this.listeners.add(listener);
9456
+ return () => this.listeners.delete(listener);
8994
9457
  }
8995
9458
  rowWritten(meta) {
8996
9459
  if (this.buffer((i) => i.rowWritten(meta))) return;
8997
9460
  this.put({
8998
9461
  deviceId: meta.id,
8999
9462
  addonId: meta.addonId,
9463
+ stableId: meta.stableId,
9000
9464
  integrationId: meta.integrationId ?? null,
9001
- identifiers: meta.identifiers ?? null
9465
+ role: meta.role ?? null,
9466
+ identifiers: meta.identifiers ?? null,
9467
+ attachedIdentifiers: meta.attachedIdentifiers ?? null,
9468
+ attachedRetained: meta.attachedRetained ?? []
9002
9469
  });
9470
+ this.changed();
9003
9471
  }
9004
9472
  registrationWritten(row) {
9005
9473
  if (this.buffer((i) => i.registrationWritten(row))) return;
@@ -9007,24 +9475,117 @@ var DeviceIdentityIndex = class {
9007
9475
  this.put({
9008
9476
  deviceId: row.deviceId,
9009
9477
  addonId: row.addonId,
9478
+ stableId: row.stableId,
9010
9479
  integrationId: existing?.integrationId ?? null,
9011
- identifiers: existing?.identifiers ?? null
9480
+ role: existing?.role ?? null,
9481
+ identifiers: existing?.identifiers ?? null,
9482
+ attachedIdentifiers: existing?.attachedIdentifiers ?? null,
9483
+ attachedRetained: existing?.attachedRetained ?? []
9012
9484
  });
9485
+ if (existing === void 0 || existing.stableId !== row.stableId) this.changed();
9013
9486
  }
9014
9487
  rowPatched(deviceId, patch) {
9015
- if (patch.identifiers === void 0 && patch.integrationId === void 0) return;
9488
+ if (patch.identifiers === void 0 && patch.attachedIdentifiers === void 0 && patch.attachedRetained === void 0 && patch.integrationId === void 0 && patch.role === void 0) return;
9016
9489
  if (this.buffer((i) => i.rowPatched(deviceId, patch))) return;
9017
9490
  const existing = this.devices.get(deviceId);
9018
9491
  if (existing === void 0) return;
9019
9492
  this.put({
9020
9493
  ...existing,
9021
9494
  ...patch.identifiers !== void 0 ? { identifiers: patch.identifiers } : {},
9022
- ...patch.integrationId !== void 0 ? { integrationId: patch.integrationId } : {}
9495
+ ...patch.attachedIdentifiers !== void 0 ? { attachedIdentifiers: patch.attachedIdentifiers } : {},
9496
+ ...patch.attachedRetained !== void 0 ? { attachedRetained: patch.attachedRetained ?? [] } : {},
9497
+ ...patch.integrationId !== void 0 ? { integrationId: patch.integrationId } : {},
9498
+ ...patch.role !== void 0 ? { role: patch.role } : {}
9023
9499
  });
9500
+ this.changed();
9024
9501
  }
9025
9502
  rowRemoved(deviceId) {
9026
9503
  if (this.buffer((i) => i.rowRemoved(deviceId))) return;
9027
9504
  this.drop(deviceId);
9505
+ this.changed();
9506
+ }
9507
+ /**
9508
+ * Every pair a link could be made of (D1063): the same-device pairs of
9509
+ * {@link candidates}, plus each device's attached identifiers paired with
9510
+ * another integration's device identifiers (`poe-power`).
9511
+ *
9512
+ * One link per port: when a port's attached keys reach several devices, or a
9513
+ * device is reached by several ports, every one of those attached pairs is
9514
+ * graded a `proposal` at most — the operator picks.
9515
+ *
9516
+ * Freshness first: a pair whose shared keys the port only RETAINS (declared
9517
+ * unread — no client now, D49) is no candidate when another port FRESHLY
9518
+ * reports the same device. A camera moved from port 7 to port 9 is port 9's;
9519
+ * port 7's auto link loses its evidence. Two fresh reports stay proposals.
9520
+ */
9521
+ linkCandidates() {
9522
+ const same = this.candidates();
9523
+ if (same.status !== "answered") return { status: "unknown" };
9524
+ const out = [];
9525
+ for (const pair of same.pairs) {
9526
+ const a = this.devices.get(pair.a.deviceId);
9527
+ const b = this.devices.get(pair.b.deviceId);
9528
+ if (a === void 0 || b === void 0) continue;
9529
+ out.push({
9530
+ kind: "same-device",
9531
+ a: linkSideOf(a),
9532
+ b: linkSideOf(b),
9533
+ aRole: a.role,
9534
+ keys: pair.keys,
9535
+ confidence: pair.confidence
9536
+ });
9537
+ }
9538
+ out.push(...this.attachedPairs());
9539
+ const byRef = /* @__PURE__ */ new Map();
9540
+ for (const d of this.devices.values()) byRef.set(`${d.addonId}/${d.stableId}`, d.deviceId);
9541
+ return {
9542
+ status: "answered",
9543
+ candidates: out,
9544
+ deviceIdOf: (addonId, stableId) => byRef.get(`${addonId}/${stableId}`) ?? null
9545
+ };
9546
+ }
9547
+ attachedPairs() {
9548
+ const all = [];
9549
+ for (const port of this.devices.values()) {
9550
+ if (port.attachedIdentifiers === null) continue;
9551
+ const reached = /* @__PURE__ */ new Set();
9552
+ for (const key of keysOf(port.attachedIdentifiers)) for (const id of this.byKey.get(key) ?? []) reached.add(id);
9553
+ for (const id of [...reached].sort((x, y) => x - y)) {
9554
+ const target = this.devices.get(id);
9555
+ if (target === void 0 || id === port.deviceId || sameIntegration(port, target)) continue;
9556
+ const keys = sharedKeys(port.attachedIdentifiers, target.identifiers);
9557
+ const confidence = classifyIdentityMatch(keys);
9558
+ if (confidence === null) continue;
9559
+ const retained = new Set(port.attachedRetained);
9560
+ all.push({
9561
+ pair: {
9562
+ kind: "poe-power",
9563
+ a: linkSideOf(port),
9564
+ b: linkSideOf(target),
9565
+ aRole: port.role,
9566
+ keys,
9567
+ confidence
9568
+ },
9569
+ fresh: keys.some((k) => !retained.has(k.key))
9570
+ });
9571
+ }
9572
+ }
9573
+ const freshlyReached = new Set(all.filter((p) => p.fresh).map((p) => p.pair.b.deviceId));
9574
+ const pairs = all.filter((p) => p.fresh || !freshlyReached.has(p.pair.b.deviceId)).map((p) => p.pair);
9575
+ const perPort = /* @__PURE__ */ new Map();
9576
+ const perTarget = /* @__PURE__ */ new Map();
9577
+ for (const p of pairs) {
9578
+ perPort.set(p.a.deviceId, (perPort.get(p.a.deviceId) ?? 0) + 1);
9579
+ perTarget.set(p.b.deviceId, (perTarget.get(p.b.deviceId) ?? 0) + 1);
9580
+ }
9581
+ return pairs.map((p) => (perPort.get(p.a.deviceId) ?? 0) > 1 || (perTarget.get(p.b.deviceId) ?? 0) > 1 ? {
9582
+ ...p,
9583
+ confidence: "proposal"
9584
+ } : p);
9585
+ }
9586
+ changed() {
9587
+ if (this.pending !== null || this.seeding) return;
9588
+ for (const listener of this.listeners) listener();
9028
9589
  }
9029
9590
  /**
9030
9591
  * Every cross-integration candidate pair, graded by `classifyIdentityMatch`,
@@ -9062,8 +9623,7 @@ var DeviceIdentityIndex = class {
9062
9623
  const a = this.devices.get(idA);
9063
9624
  const b = this.devices.get(idB);
9064
9625
  if (a === void 0 || b === void 0 || sameIntegration(a, b)) return null;
9065
- const bKeys = new Set(keysOf(b.identifiers));
9066
- const keys = keysOf(a.identifiers).filter((k) => bKeys.has(k)).map(parseKey).filter((k) => k !== null).sort(compareKeys);
9626
+ const keys = sharedKeys(a.identifiers, b.identifiers);
9067
9627
  const confidence = classifyIdentityMatch(keys);
9068
9628
  return confidence === null ? null : {
9069
9629
  a: sideOf(a),
@@ -10030,43 +10590,6 @@ var DeviceMetaStore = class {
10030
10590
  });
10031
10591
  };
10032
10592
  //#endregion
10033
- //#region src/builtins/device-manager/record-kinds.ts
10034
- var import_read_all_rows = require_read_all_rows();
10035
- var _deviceManagerRecordKinds = defineRecordKinds({
10036
- tombstones: {
10037
- schema: DeviceTombstoneSchema.omit({ deviceId: true }),
10038
- class: "ledger",
10039
- writeTrigger: "`removeDevice` records one row per deleted device after the device row is gone; re-record keeps the earlier `deletedAt`",
10040
- device: "none",
10041
- at: "required",
10042
- indexes: [{
10043
- name: "deleted_at",
10044
- fields: ["deletedAt"]
10045
- }],
10046
- retention: {
10047
- owner: "device-manager",
10048
- reason: "90 days (`DEVICE_TOMBSTONE_RETENTION_MS`), pruned whenever a tombstone is written or the list is read"
10049
- }
10050
- },
10051
- "discovery-proposals": {
10052
- schema: DiscoveryProposalBodySchema,
10053
- class: "config",
10054
- writeTrigger: "the passive listener and the 30-minute sweep of `local-network` re-see a device (`lastSeenAt` and `at` move); `dismissDiscoveryProposal` sets `dismissed`",
10055
- device: "none",
10056
- at: "required",
10057
- indexes: [{
10058
- name: "last_seen_at",
10059
- fields: ["lastSeenAt"]
10060
- }],
10061
- retention: {
10062
- ttlMs: 2160 * 60 * 60 * 1e3,
10063
- from: "at"
10064
- }
10065
- }
10066
- });
10067
- var deviceManagerRecordKinds = _deviceManagerRecordKinds;
10068
- _deviceManagerRecordKinds.tombstones;
10069
- //#endregion
10070
10593
  //#region src/builtins/device-manager/device-tombstone-store.ts
10071
10594
  /**
10072
10595
  * The tombstones of deleted devices (D865) — `tombstones` record kind (phase 4).
@@ -10641,6 +11164,14 @@ var DEVICE_ROWS_COLUMNS = [
10641
11164
  {
10642
11165
  name: "identifiers",
10643
11166
  type: "JSON"
11167
+ },
11168
+ {
11169
+ name: "attachedIdentifiers",
11170
+ type: "JSON"
11171
+ },
11172
+ {
11173
+ name: "attachedRetained",
11174
+ type: "JSON"
10644
11175
  }
10645
11176
  ];
10646
11177
  /**
@@ -10761,6 +11292,8 @@ function decodeDeviceRow(data) {
10761
11292
  const rawDisplay = data["display"];
10762
11293
  const rawMetadata = data["metadata"];
10763
11294
  const identifiers = DeviceIdentifiersSchema.safeParse(data["identifiers"]);
11295
+ const attachedIdentifiers = DeviceIdentifiersSchema.safeParse(data["attachedIdentifiers"]);
11296
+ const attachedRetained = DeviceIdentifierKeySchema.array().min(1).safeParse(data["attachedRetained"]);
10764
11297
  return {
10765
11298
  meta: {
10766
11299
  id: deviceId,
@@ -10783,7 +11316,9 @@ function decodeDeviceRow(data) {
10783
11316
  ...primaryChildPreference !== void 0 ? { primaryChildPreference } : {},
10784
11317
  ...role !== void 0 ? { role } : {},
10785
11318
  ...isPlainObject$1(rawDisplay) ? { display: toDisplayOverride(rawDisplay) } : {},
10786
- ...identifiers.success ? { identifiers: identifiers.data } : {}
11319
+ ...identifiers.success ? { identifiers: identifiers.data } : {},
11320
+ ...attachedIdentifiers.success ? { attachedIdentifiers: attachedIdentifiers.data } : {},
11321
+ ...attachedRetained.success ? { attachedRetained: attachedRetained.data } : {}
10787
11322
  },
10788
11323
  metadata: isPlainObject$1(rawMetadata) ? rawMetadata : null,
10789
11324
  registered: readBoolean(data["registered"]) ?? false
@@ -10830,7 +11365,9 @@ function encodeDeviceRow(meta, extra = {}) {
10830
11365
  primaryChildPreference: meta.primaryChildPreference === void 0 ? null : [...meta.primaryChildPreference],
10831
11366
  role: meta.role ?? null,
10832
11367
  display: meta.display ?? null,
10833
- identifiers: meta.identifiers ?? null
11368
+ identifiers: meta.identifiers ?? null,
11369
+ attachedIdentifiers: meta.attachedIdentifiers ?? null,
11370
+ attachedRetained: meta.attachedRetained === void 0 ? null : [...meta.attachedRetained]
10834
11371
  };
10835
11372
  if (extra.metadata !== void 0) row["metadata"] = extra.metadata;
10836
11373
  return row;
@@ -11391,7 +11928,7 @@ function createDeviceStateClaimMethods(deps) {
11391
11928
  meta: {
11392
11929
  cap: capName,
11393
11930
  owner,
11394
- error: errorMessage$3(err)
11931
+ error: errorMessage$4(err)
11395
11932
  }
11396
11933
  });
11397
11934
  throw err;
@@ -11436,13 +11973,13 @@ function createDeviceStateClaimMethods(deps) {
11436
11973
  meta: {
11437
11974
  cap: key.capName,
11438
11975
  refusal: code,
11439
- error: errorMessage$3(err)
11976
+ error: errorMessage$4(err)
11440
11977
  }
11441
11978
  });
11442
11979
  }
11443
11980
  }
11444
11981
  }
11445
- function errorMessage$3(err) {
11982
+ function errorMessage$4(err) {
11446
11983
  return err instanceof Error ? err.message : String(err);
11447
11984
  }
11448
11985
  //#endregion
@@ -11720,7 +12257,7 @@ var RuntimeStateRowUnreadError = class extends Error {
11720
12257
  };
11721
12258
  var ROW_UNREAD_REFUSAL_MESSAGE = "runtime-state row write refused — the row could not be read first, nothing written";
11722
12259
  var ROW_DROPS_CAPS_MESSAGE = "runtime-state row write DROPS caps the stored row holds";
11723
- function errorMessage$2(err) {
12260
+ function errorMessage$3(err) {
11724
12261
  return err instanceof Error ? err.message : String(err);
11725
12262
  }
11726
12263
  /**
@@ -11888,7 +12425,7 @@ var MirrorRowWriter = class MirrorRowWriter {
11888
12425
  tags: { deviceId },
11889
12426
  meta: {
11890
12427
  path,
11891
- error: errorMessage$2(err)
12428
+ error: errorMessage$3(err)
11892
12429
  }
11893
12430
  });
11894
12431
  }
@@ -11970,7 +12507,7 @@ var MirrorRowWriter = class MirrorRowWriter {
11970
12507
  slot.lastWriteFailed = true;
11971
12508
  this.deps.logger.warn("writeDeviceRuntimeState failed", {
11972
12509
  tags: { deviceId },
11973
- meta: { error: errorMessage$2(err) }
12510
+ meta: { error: errorMessage$3(err) }
11974
12511
  });
11975
12512
  }
11976
12513
  }
@@ -12045,7 +12582,7 @@ var MirrorRowWriter = class MirrorRowWriter {
12045
12582
  try {
12046
12583
  await this.serialiseWrite(deviceId, () => this.writeRow(deviceId, settings, blob, "drain"));
12047
12584
  } catch (err) {
12048
- this.refuseDrain(deviceId, `the pending runtime-state write failed: ${errorMessage$2(err)}`, err);
12585
+ this.refuseDrain(deviceId, `the pending runtime-state write failed: ${errorMessage$3(err)}`, err);
12049
12586
  }
12050
12587
  }
12051
12588
  /** A drain that cannot vouch for the row: still owed (re-armed on release), logged, refused. */
@@ -12246,6 +12783,11 @@ var CommandHolds = class {
12246
12783
  isHolding(deviceId, capName) {
12247
12784
  return (this.held.get(deviceId)?.get(capName)?.size ?? 0) > 0;
12248
12785
  }
12786
+ /** Is any field of any cap of the device still held? (D1062: the command burst stops when this is false.) */
12787
+ isHoldingDevice(deviceId) {
12788
+ for (const fields of this.held.get(deviceId)?.values() ?? []) if (fields.size > 0) return true;
12789
+ return false;
12790
+ }
12249
12791
  /** Forget a removed device's holds. */
12250
12792
  clearDevice(deviceId) {
12251
12793
  this.held.delete(deviceId);
@@ -12318,13 +12860,14 @@ var CommandHolds = class {
12318
12860
  */
12319
12861
  var RUNNING_STATE_CAP = "running-state";
12320
12862
  var SEED_REFUSAL_MESSAGE = "runtime-state row unreadable — native write refused until it reads";
12321
- function errorMessage$1(err) {
12863
+ function errorMessage$2(err) {
12322
12864
  return err instanceof Error ? err.message : String(err);
12323
12865
  }
12324
12866
  var DeviceStateMirror = class {
12325
12867
  ctx;
12326
12868
  policyFor;
12327
12869
  transitionTap = null;
12870
+ reportTap = null;
12328
12871
  /**
12329
12872
  * Hub-side mirror of every device's cap-keyed NATIVE runtime state — what the
12330
12873
  * provider wrote. Key: deviceId. Value: per-cap slice map. Empty by default —
@@ -12385,6 +12928,10 @@ var DeviceStateMirror = class {
12385
12928
  setTransitionTap(tap) {
12386
12929
  this.transitionTap = tap;
12387
12930
  }
12931
+ /** Set once by the device-manager: told of every native slice reported, before the no-change check (D1062). */
12932
+ setReportTap(tap) {
12933
+ this.reportTap = tap;
12934
+ }
12388
12935
  /**
12389
12936
  * Hold what a command leads to: the effective slice shows it at once (and
12390
12937
  * `DeviceStateChanged` carries it), the stored, persisted and recorded slice
@@ -12397,6 +12944,10 @@ var DeviceStateMirror = class {
12397
12944
  releaseCommand(token, reason) {
12398
12945
  this.holds.release(token, reason);
12399
12946
  }
12947
+ /** Whether any command hold on the device is still unconfirmed (D1062). */
12948
+ isHoldingDevice(deviceId) {
12949
+ return this.holds.isHoldingDevice(deviceId);
12950
+ }
12400
12951
  /** Stop the hold timers (shutdown). */
12401
12952
  disposeHolds() {
12402
12953
  this.holds.dispose();
@@ -12421,6 +12972,7 @@ var DeviceStateMirror = class {
12421
12972
  * a SQLite commit.
12422
12973
  */
12423
12974
  applySingleCapUpdate(deviceId, capName, slice) {
12975
+ this.reportTap?.(deviceId, capName);
12424
12976
  let perCap = this.stateMirror.get(deviceId);
12425
12977
  if (!perCap) {
12426
12978
  perCap = /* @__PURE__ */ new Map();
@@ -12686,7 +13238,7 @@ var DeviceStateMirror = class {
12686
13238
  await this.ensureRowRead(deviceId, settings);
12687
13239
  return null;
12688
13240
  } catch (err) {
12689
- return refused("row-unreadable", `device ${deviceId}: ${errorMessage$1(err)}`);
13241
+ return refused("row-unreadable", `device ${deviceId}: ${errorMessage$2(err)}`);
12690
13242
  }
12691
13243
  }
12692
13244
  readRowOnce(deviceId, settings) {
@@ -12700,7 +13252,7 @@ var DeviceStateMirror = class {
12700
13252
  this.seedRefusalLogged.add(deviceId);
12701
13253
  this.ctx.logger.warn(SEED_REFUSAL_MESSAGE, {
12702
13254
  tags: { deviceId },
12703
- meta: { error: errorMessage$1(err) }
13255
+ meta: { error: errorMessage$2(err) }
12704
13256
  });
12705
13257
  }
12706
13258
  throw err;
@@ -12734,7 +13286,7 @@ var DeviceStateMirror = class {
12734
13286
  meta: {
12735
13287
  cap: op.cap,
12736
13288
  owner: op.owner,
12737
- error: errorMessage$1(err)
13289
+ error: errorMessage$2(err)
12738
13290
  }
12739
13291
  };
12740
13292
  if (rollback()) {
@@ -13105,6 +13657,93 @@ function pipeReducer(prev, fn) {
13105
13657
  return fn(prev);
13106
13658
  }
13107
13659
  //#endregion
13660
+ //#region src/kernel/command-follow-up.ts
13661
+ /**
13662
+ * The command follow-up (D1062): the work a device command waits for before
13663
+ * its caller hears the answer.
13664
+ *
13665
+ * The D1022 seams that observe a command (the hub tRPC mount, the UDS parent,
13666
+ * an in-process hub addon's `ctx.api`) also await this hook once the
13667
+ * provider's call settled — the hub's state-refresh scheduler re-reads the
13668
+ * device there, so the command returns after the real state was pushed.
13669
+ *
13670
+ * Unlike the observation (telemetry, D8) this one is awaited, but it is never
13671
+ * a gate: a follow-up that throws is swallowed here, and the call's own result
13672
+ * or error is what the caller gets. Cost when nothing is registered: one
13673
+ * undefined check (D181).
13674
+ */
13675
+ /** The one follow-up of this process (the hub's device-manager installs it). */
13676
+ var CommandFollowUpRegistry = class {
13677
+ handler = null;
13678
+ /** Install (or, with `null`, remove) the follow-up. Returns the uninstall. */
13679
+ set(handler) {
13680
+ this.handler = handler;
13681
+ return () => {
13682
+ if (this.handler === handler) this.handler = null;
13683
+ };
13684
+ }
13685
+ /** Run the follow-up for a settled command. Never throws. */
13686
+ async run(target, outcome) {
13687
+ const handler = this.handler;
13688
+ if (handler === null) return;
13689
+ try {
13690
+ await handler(target, outcome);
13691
+ } catch {}
13692
+ }
13693
+ };
13694
+ var registry$3;
13695
+ /** The process-wide registry. */
13696
+ function getCommandFollowUpRegistry() {
13697
+ registry$3 ??= new CommandFollowUpRegistry();
13698
+ return registry$3;
13699
+ }
13700
+ /** Test seam: forget the handler. */
13701
+ function __resetCommandFollowUpRegistryForTests() {
13702
+ registry$3 = void 0;
13703
+ }
13704
+ /** The target of a call when it is a device command naming a device, else `null`. */
13705
+ function commandFollowUpTarget(capName, method, deviceId) {
13706
+ if (deviceId === void 0 || !Number.isInteger(deviceId)) return null;
13707
+ if (!isCommand(capName, method)) return null;
13708
+ return {
13709
+ deviceId,
13710
+ capName,
13711
+ method
13712
+ };
13713
+ }
13714
+ /** The `deviceId` an args object names, or `undefined`. */
13715
+ function deviceIdOfArgs(args) {
13716
+ if (args === null || typeof args !== "object" || Array.isArray(args)) return void 0;
13717
+ const deviceId = Reflect.get(args, "deviceId");
13718
+ return typeof deviceId === "number" && Number.isInteger(deviceId) ? deviceId : void 0;
13719
+ }
13720
+ /**
13721
+ * Await `result`, then the follow-up, then answer with `result` — its value, or
13722
+ * its error rethrown. Without a follow-up or a target, `result` is returned
13723
+ * untouched.
13724
+ */
13725
+ function withCommandFollowUp(followUp, target, result) {
13726
+ if (followUp === void 0 || target === null) return result;
13727
+ return settleThenFollowUp(followUp, target, result);
13728
+ }
13729
+ async function settleThenFollowUp(followUp, target, result) {
13730
+ let value;
13731
+ try {
13732
+ value = await result;
13733
+ } catch (err) {
13734
+ await runCommandFollowUp(followUp, target, "failed");
13735
+ throw err;
13736
+ }
13737
+ await runCommandFollowUp(followUp, target, "ok");
13738
+ return value;
13739
+ }
13740
+ /** Run `followUp` for a settled command, swallowing its failure. */
13741
+ async function runCommandFollowUp(followUp, target, outcome) {
13742
+ try {
13743
+ await followUp(target, outcome);
13744
+ } catch {}
13745
+ }
13746
+ //#endregion
13108
13747
  //#region src/kernel/command-observation.ts
13109
13748
  /** Fan-out of command observations to the subscribers of this process. */
13110
13749
  var CommandObserverRegistry = class {
@@ -13125,15 +13764,15 @@ var CommandObserverRegistry = class {
13125
13764
  } catch {}
13126
13765
  }
13127
13766
  };
13128
- var registry$1;
13767
+ var registry$2;
13129
13768
  /** The process-wide registry. */
13130
13769
  function getCommandObserverRegistry() {
13131
- registry$1 ??= new CommandObserverRegistry();
13132
- return registry$1;
13770
+ registry$2 ??= new CommandObserverRegistry();
13771
+ return registry$2;
13133
13772
  }
13134
13773
  /** Test seam: forget every subscriber. */
13135
13774
  function __resetCommandObserverRegistryForTests() {
13136
- registry$1 = void 0;
13775
+ registry$2 = void 0;
13137
13776
  }
13138
13777
  function isRecord(value) {
13139
13778
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -13244,18 +13883,45 @@ function commandObserverLink(options) {
13244
13883
  actor: addonCommandActor(options.callerAddonId, readCommandOrigin(op.context)),
13245
13884
  outcome
13246
13885
  });
13886
+ const target = commandFollowUpTarget(capName, method, deviceIdOfArgs(op.input));
13887
+ const followUp = options.followUp;
13888
+ if (followUp === void 0 || target === null) {
13889
+ const sub = downstream.subscribe({
13890
+ next: (value) => observer.next(value),
13891
+ error: (err) => {
13892
+ settled.reject(err);
13893
+ observer.error(err);
13894
+ },
13895
+ complete: () => {
13896
+ settled.resolve();
13897
+ observer.complete();
13898
+ }
13899
+ });
13900
+ return () => sub.unsubscribe();
13901
+ }
13902
+ const answered = [];
13903
+ let closed = false;
13247
13904
  const sub = downstream.subscribe({
13248
- next: (value) => observer.next(value),
13905
+ next: (value) => void answered.push(value),
13249
13906
  error: (err) => {
13250
13907
  settled.reject(err);
13251
- observer.error(err);
13908
+ runCommandFollowUp(followUp, target, "failed").then(() => {
13909
+ if (!closed) observer.error(err);
13910
+ });
13252
13911
  },
13253
13912
  complete: () => {
13254
13913
  settled.resolve();
13255
- observer.complete();
13914
+ runCommandFollowUp(followUp, target, "ok").then(() => {
13915
+ if (closed) return;
13916
+ for (const value of answered) observer.next(value);
13917
+ observer.complete();
13918
+ });
13256
13919
  }
13257
13920
  });
13258
- return () => sub.unsubscribe();
13921
+ return () => {
13922
+ closed = true;
13923
+ sub.unsubscribe();
13924
+ };
13259
13925
  });
13260
13926
  };
13261
13927
  }
@@ -13369,11 +14035,11 @@ var CommandHoldOverrideRegistry = class {
13369
14035
  }
13370
14036
  }
13371
14037
  };
13372
- var registry;
14038
+ var registry$1;
13373
14039
  /** The process-wide registry. */
13374
14040
  function getCommandHoldOverrideRegistry() {
13375
- registry ??= new CommandHoldOverrideRegistry();
13376
- return registry;
14041
+ registry$1 ??= new CommandHoldOverrideRegistry();
14042
+ return registry$1;
13377
14043
  }
13378
14044
  //#endregion
13379
14045
  //#region src/builtins/device-manager/command-holds-wiring.ts
@@ -13417,6 +14083,525 @@ function startCommandHolds(deps) {
13417
14083
  deps.mirror.disposeHolds();
13418
14084
  };
13419
14085
  }
14086
+ //#endregion
14087
+ //#region src/kernel/state-refresh-policies.ts
14088
+ /** The cap a policy is stated on. */
14089
+ var STATE_REFRESH_CAP = "device-state-refresh";
14090
+ /** The source key of an in-process registration. */
14091
+ var IN_PROCESS_REFRESH_SOURCE = "in-process";
14092
+ /** The source key of a forked child's registrations. */
14093
+ function childRefreshSource(childId) {
14094
+ return `child:${childId}`;
14095
+ }
14096
+ /** The policies a child's cap descriptors carry, one entry per device. */
14097
+ function childStateRefreshEntries(childId, caps) {
14098
+ const out = [];
14099
+ for (const cap of caps) {
14100
+ if (cap.capName !== "device-state-refresh") continue;
14101
+ if (cap.deviceId === void 0 || cap.stateRefresh === void 0) continue;
14102
+ out.push({
14103
+ deviceId: cap.deviceId,
14104
+ addonId: cap.addonId ?? childId,
14105
+ policy: cap.stateRefresh
14106
+ });
14107
+ }
14108
+ return out;
14109
+ }
14110
+ var StateRefreshPolicyRegistry = class {
14111
+ bySource = /* @__PURE__ */ new Map();
14112
+ listeners = /* @__PURE__ */ new Set();
14113
+ /** Record (or replace) one device's policy from `source`. */
14114
+ set(source, entry) {
14115
+ const perSource = new Map(this.bySource.get(source) ?? []);
14116
+ perSource.set(entry.deviceId, entry);
14117
+ this.bySource.set(source, perSource);
14118
+ this.changed();
14119
+ }
14120
+ /** Forget one device's policy from `source`. */
14121
+ delete(source, deviceId) {
14122
+ const perSource = this.bySource.get(source);
14123
+ if (perSource === void 0 || !perSource.has(deviceId)) return;
14124
+ const next = new Map(perSource);
14125
+ next.delete(deviceId);
14126
+ if (next.size === 0) this.bySource.delete(source);
14127
+ else this.bySource.set(source, next);
14128
+ this.changed();
14129
+ }
14130
+ /** Replace everything `source` reported with `entries` (an empty list forgets the source). */
14131
+ replaceSource(source, entries) {
14132
+ const had = this.bySource.has(source);
14133
+ if (entries.length === 0) {
14134
+ this.bySource.delete(source);
14135
+ if (had) this.changed();
14136
+ return;
14137
+ }
14138
+ this.bySource.set(source, new Map(entries.map((e) => [e.deviceId, e])));
14139
+ this.changed();
14140
+ }
14141
+ /** Every device's policy (a device registered by two sources keeps the first). */
14142
+ entries() {
14143
+ const seen = /* @__PURE__ */ new Map();
14144
+ for (const perSource of this.bySource.values()) for (const entry of perSource.values()) if (!seen.has(entry.deviceId)) seen.set(entry.deviceId, entry);
14145
+ return [...seen.values()];
14146
+ }
14147
+ /** One device's policy, or `undefined` when its provider did not migrate. */
14148
+ get(deviceId) {
14149
+ for (const perSource of this.bySource.values()) {
14150
+ const found = perSource.get(deviceId);
14151
+ if (found !== void 0) return found;
14152
+ }
14153
+ }
14154
+ subscribe(listener) {
14155
+ this.listeners.add(listener);
14156
+ return () => {
14157
+ this.listeners.delete(listener);
14158
+ };
14159
+ }
14160
+ changed() {
14161
+ for (const listener of this.listeners) try {
14162
+ listener();
14163
+ } catch {}
14164
+ }
14165
+ };
14166
+ var registry;
14167
+ /** The process-wide registry. */
14168
+ function getStateRefreshPolicyRegistry() {
14169
+ registry ??= new StateRefreshPolicyRegistry();
14170
+ return registry;
14171
+ }
14172
+ /** Test seam: forget every policy. */
14173
+ function __resetStateRefreshPolicyRegistryForTests() {
14174
+ registry = void 0;
14175
+ }
14176
+ //#endregion
14177
+ //#region src/builtins/device-manager/state-refresh-scheduler.ts
14178
+ /**
14179
+ * The state-refresh scheduler (D1062, amending D224): the core decides WHEN a
14180
+ * migrated provider re-reads a device; the provider only knows HOW.
14181
+ *
14182
+ * The policy each provider declared on its `device-state-refresh`
14183
+ * registration (`StateRefreshPolicyRegistry`) drives it. Devices are grouped
14184
+ * per integration instance (`addonId::integrationId`):
14185
+ *
14186
+ * - cadence: `effectiveRefreshIntervalMs` — the declared minimum, slowed (never
14187
+ * sped up) by the integration's own setting, no idle back-off;
14188
+ * `push: 'full'` is never scheduled. A batching integration (`batch: true`)
14189
+ * has ONE schedule for the group — one due time, one read of every device
14190
+ * per interval; a device that registers later joins the group's next tick.
14191
+ * A non-batching integration keeps one schedule per device;
14192
+ * - command (`onCommand`, awaited by the D1022 seams): a polled device is read
14193
+ * at once and the command returns after it, then read again at ~3 s and
14194
+ * ~10 s while a D1061 hold on it is still pending; a push device waits
14195
+ * `PUSH_CONFIRM_WINDOW_MS` for the confirming push and reads once if none
14196
+ * came. These reads are per device and never move a batched group's schedule;
14197
+ * - push health: silence past `heartbeatMs` reads the integration, asks it to
14198
+ * resubscribe and reads again; a new `connectionEpoch` reads everything.
14199
+ *
14200
+ * Reads of one device are serialized: each starts after the previous one on
14201
+ * that device ended. A scheduled tick that finds its last read still running
14202
+ * is skipped (debug line); a command waits for the read in flight at most
14203
+ * `COMMAND_WAIT_BOUND_MS`, then reads its own device (debug line). A refresh
14204
+ * failure is a warn line per device and never fails a command.
14205
+ */
14206
+ /** The longest a command waits for a read already in flight on its device. */
14207
+ var COMMAND_WAIT_BOUND_MS = 5e3;
14208
+ function groupKeyOf(entry) {
14209
+ return `${entry.addonId}::${entry.policy.integrationId}`;
14210
+ }
14211
+ function errorMessage$1(err) {
14212
+ return err instanceof Error ? err.message : String(err);
14213
+ }
14214
+ var StateRefreshScheduler = class {
14215
+ deps;
14216
+ devices = /* @__PURE__ */ new Map();
14217
+ groups = /* @__PURE__ */ new Map();
14218
+ unsubscribe;
14219
+ disposed = false;
14220
+ constructor(deps) {
14221
+ this.deps = deps;
14222
+ this.unsubscribe = deps.policies.subscribe(() => this.reconcile());
14223
+ this.reconcile();
14224
+ }
14225
+ /** The command follow-up (awaited by the D1022 seams; never throws). */
14226
+ onCommand = async (target, outcome) => {
14227
+ const device = this.devices.get(target.deviceId);
14228
+ if (device === void 0 || this.disposed) return;
14229
+ device.lastCommandAt = Date.now();
14230
+ this.cancelFollowUps(device);
14231
+ const { policy } = device.entry;
14232
+ if (policy.push !== "none") {
14233
+ this.armPushWindow(target.deviceId, device);
14234
+ return;
14235
+ }
14236
+ this.deps.logger.debug("state refresh after command", {
14237
+ tags: { deviceId: target.deviceId },
14238
+ meta: {
14239
+ capName: target.capName,
14240
+ method: target.method,
14241
+ outcome
14242
+ }
14243
+ });
14244
+ await this.runRefresh([target.deviceId], "command", COMMAND_WAIT_BOUND_MS);
14245
+ if (!policy.batch) {
14246
+ device.dueAt = Date.now() + effectiveRefreshIntervalMs(policy);
14247
+ this.armSchedule(groupKeyOf(device.entry));
14248
+ }
14249
+ this.armBurst(target.deviceId, device);
14250
+ };
14251
+ /** A state report reached the mirror for `deviceId` (push or read). */
14252
+ onReport(deviceId) {
14253
+ const device = this.devices.get(deviceId);
14254
+ if (device === void 0) return;
14255
+ const now = Date.now();
14256
+ device.lastReportAt = now;
14257
+ const group = this.groups.get(groupKeyOf(device.entry));
14258
+ if (group !== void 0) group.lastReportAt = now;
14259
+ }
14260
+ dispose() {
14261
+ this.disposed = true;
14262
+ this.unsubscribe();
14263
+ for (const device of this.devices.values()) this.cancelFollowUps(device);
14264
+ for (const group of this.groups.values()) this.clearGroupTimers(group);
14265
+ this.devices.clear();
14266
+ this.groups.clear();
14267
+ }
14268
+ reconcile() {
14269
+ if (this.disposed) return;
14270
+ const now = Date.now();
14271
+ const current = new Map(this.deps.policies.entries().map((e) => [e.deviceId, e]));
14272
+ for (const [deviceId, device] of this.devices) {
14273
+ if (current.has(deviceId)) continue;
14274
+ this.cancelFollowUps(device);
14275
+ this.devices.delete(deviceId);
14276
+ }
14277
+ const reconnected = /* @__PURE__ */ new Set();
14278
+ for (const entry of current.values()) {
14279
+ const existing = this.devices.get(entry.deviceId);
14280
+ const interval = effectiveRefreshIntervalMs(entry.policy);
14281
+ if (existing === void 0) this.devices.set(entry.deviceId, {
14282
+ entry,
14283
+ dueAt: now + interval,
14284
+ lastReportAt: now,
14285
+ lastCommandAt: 0,
14286
+ inFlight: null,
14287
+ scheduledInFlight: null,
14288
+ burst: [],
14289
+ pushWindow: null
14290
+ });
14291
+ else {
14292
+ if (effectiveRefreshIntervalMs(existing.entry.policy) !== interval) existing.dueAt = now + interval;
14293
+ existing.entry = entry;
14294
+ }
14295
+ if (this.noteEpoch(entry)) reconnected.add(groupKeyOf(entry));
14296
+ }
14297
+ this.rebuildGroups(now);
14298
+ for (const key of reconnected) {
14299
+ this.deps.logger.info("state refresh: integration reconnected, reading every device", { meta: { group: key } });
14300
+ this.refreshGroup(key, "schedule");
14301
+ }
14302
+ }
14303
+ /** Track the group's connection epoch; `true` when it moved past a known one. */
14304
+ noteEpoch(entry) {
14305
+ const epoch = entry.policy.connectionEpoch;
14306
+ if (epoch === void 0) return false;
14307
+ const key = groupKeyOf(entry);
14308
+ const group = this.groups.get(key);
14309
+ if (group === void 0) return false;
14310
+ const previous = group.epoch;
14311
+ if (previous === void 0 || epoch > previous) group.epoch = epoch;
14312
+ return previous !== void 0 && epoch > previous;
14313
+ }
14314
+ rebuildGroups(now) {
14315
+ const members = /* @__PURE__ */ new Map();
14316
+ for (const [deviceId, device] of this.devices) {
14317
+ const key = groupKeyOf(device.entry);
14318
+ const set = members.get(key) ?? /* @__PURE__ */ new Set();
14319
+ set.add(deviceId);
14320
+ members.set(key, set);
14321
+ }
14322
+ for (const [key, group] of this.groups) {
14323
+ if (members.has(key)) continue;
14324
+ this.clearGroupTimers(group);
14325
+ this.groups.delete(key);
14326
+ }
14327
+ for (const [key, devices] of members) {
14328
+ const existing = this.groups.get(key);
14329
+ if (existing === void 0) {
14330
+ const first = this.devices.get([...devices][0] ?? -1);
14331
+ const intervalMs = first === void 0 ? 0 : effectiveRefreshIntervalMs(first.entry.policy);
14332
+ this.groups.set(key, {
14333
+ key,
14334
+ devices,
14335
+ dueAt: now + intervalMs,
14336
+ intervalMs,
14337
+ scheduleTimer: null,
14338
+ heartbeatTimer: null,
14339
+ lastReportAt: now,
14340
+ epoch: first?.entry.policy.connectionEpoch
14341
+ });
14342
+ } else {
14343
+ existing.devices = devices;
14344
+ const policy = this.groupPolicy(existing);
14345
+ const intervalMs = policy === void 0 ? 0 : effectiveRefreshIntervalMs(policy);
14346
+ if (intervalMs !== existing.intervalMs) {
14347
+ existing.intervalMs = intervalMs;
14348
+ existing.dueAt = now + intervalMs;
14349
+ }
14350
+ }
14351
+ this.armSchedule(key);
14352
+ this.armHeartbeat(key);
14353
+ }
14354
+ }
14355
+ groupPolicy(group) {
14356
+ for (const deviceId of group.devices) {
14357
+ const device = this.devices.get(deviceId);
14358
+ if (device !== void 0) return device.entry.policy;
14359
+ }
14360
+ }
14361
+ armSchedule(key) {
14362
+ const group = this.groups.get(key);
14363
+ if (group === void 0 || this.disposed) return;
14364
+ if (group.scheduleTimer !== null) clearTimeout(group.scheduleTimer);
14365
+ group.scheduleTimer = null;
14366
+ const policy = this.groupPolicy(group);
14367
+ if (policy === void 0 || policy.push === "full") return;
14368
+ let earliest = Number.POSITIVE_INFINITY;
14369
+ if (policy.batch) earliest = group.dueAt;
14370
+ else for (const deviceId of group.devices) {
14371
+ const device = this.devices.get(deviceId);
14372
+ if (device !== void 0) earliest = Math.min(earliest, device.dueAt);
14373
+ }
14374
+ if (!Number.isFinite(earliest)) return;
14375
+ group.scheduleTimer = setTimeout(() => this.tick(key), Math.max(0, earliest - Date.now()));
14376
+ }
14377
+ tick(key) {
14378
+ const group = this.groups.get(key);
14379
+ if (group === void 0 || this.disposed) return;
14380
+ group.scheduleTimer = null;
14381
+ const policy = this.groupPolicy(group);
14382
+ if (policy?.batch === true) this.tickBatched(group, policy);
14383
+ else this.tickPerDevice(group);
14384
+ this.armSchedule(key);
14385
+ }
14386
+ /** One read of the whole group per interval, unless the last one still runs. */
14387
+ tickBatched(group, policy) {
14388
+ const now = Date.now();
14389
+ if (group.dueAt > now) return;
14390
+ group.dueAt = now + effectiveRefreshIntervalMs(policy);
14391
+ const ids = [...group.devices].filter((id) => this.devices.has(id));
14392
+ const running = ids.filter((id) => (this.devices.get(id)?.scheduledInFlight ?? null) !== null);
14393
+ if (running.length > 0) {
14394
+ for (const deviceId of running) this.logSkippedTick(deviceId);
14395
+ return;
14396
+ }
14397
+ if (ids.length > 0) this.runScheduled(ids);
14398
+ }
14399
+ tickPerDevice(group) {
14400
+ const now = Date.now();
14401
+ const due = [];
14402
+ for (const deviceId of group.devices) {
14403
+ const device = this.devices.get(deviceId);
14404
+ if (device === void 0 || device.dueAt > now) continue;
14405
+ device.dueAt = now + effectiveRefreshIntervalMs(device.entry.policy);
14406
+ if (device.inFlight !== null) {
14407
+ this.logSkippedTick(deviceId);
14408
+ continue;
14409
+ }
14410
+ due.push(deviceId);
14411
+ }
14412
+ for (const deviceId of due) this.runScheduled([deviceId]);
14413
+ }
14414
+ logSkippedTick(deviceId) {
14415
+ this.deps.logger.debug("state refresh skipped: a refresh is still in flight", { tags: { deviceId } });
14416
+ }
14417
+ /** A scheduled read, remembered on each device until it settles. */
14418
+ async runScheduled(deviceIds) {
14419
+ const run = this.runRefresh(deviceIds, "schedule");
14420
+ for (const deviceId of deviceIds) {
14421
+ const device = this.devices.get(deviceId);
14422
+ if (device !== void 0) device.scheduledInFlight = run;
14423
+ }
14424
+ await run;
14425
+ for (const deviceId of deviceIds) {
14426
+ const device = this.devices.get(deviceId);
14427
+ if (device !== void 0 && device.scheduledInFlight === run) device.scheduledInFlight = null;
14428
+ }
14429
+ }
14430
+ armBurst(deviceId, device) {
14431
+ if (!this.deps.holdsPending(deviceId)) return;
14432
+ const timers = [];
14433
+ let stopped = false;
14434
+ for (const offset of COMMAND_BURST_OFFSETS_MS) timers.push(setTimeout(() => {
14435
+ if (stopped || this.disposed) return;
14436
+ if (!this.deps.holdsPending(deviceId)) {
14437
+ stopped = true;
14438
+ this.deps.logger.debug("state refresh burst stopped: the command is confirmed", { tags: { deviceId } });
14439
+ return;
14440
+ }
14441
+ if (device.inFlight !== null) {
14442
+ this.deps.logger.debug("state refresh burst skipped: a refresh is still in flight", { tags: { deviceId } });
14443
+ return;
14444
+ }
14445
+ this.runRefresh([deviceId], "burst");
14446
+ }, offset));
14447
+ device.burst = timers;
14448
+ }
14449
+ armPushWindow(deviceId, device) {
14450
+ const commandAt = device.lastCommandAt;
14451
+ device.pushWindow = setTimeout(() => {
14452
+ device.pushWindow = null;
14453
+ if (this.disposed) return;
14454
+ if (device.lastReportAt > commandAt && !this.deps.holdsPending(deviceId)) {
14455
+ this.deps.logger.debug("state refresh not needed: the push confirmed the command", { tags: { deviceId } });
14456
+ return;
14457
+ }
14458
+ this.deps.logger.debug("state refresh: no confirming push within the window", {
14459
+ tags: { deviceId },
14460
+ meta: { windowMs: PUSH_CONFIRM_WINDOW_MS }
14461
+ });
14462
+ if (device.inFlight !== null) return;
14463
+ this.runRefresh([deviceId], "command");
14464
+ }, PUSH_CONFIRM_WINDOW_MS);
14465
+ }
14466
+ cancelFollowUps(device) {
14467
+ for (const timer of device.burst) clearTimeout(timer);
14468
+ device.burst = [];
14469
+ if (device.pushWindow !== null) clearTimeout(device.pushWindow);
14470
+ device.pushWindow = null;
14471
+ }
14472
+ armHeartbeat(key) {
14473
+ const group = this.groups.get(key);
14474
+ if (group === void 0 || this.disposed) return;
14475
+ if (group.heartbeatTimer !== null) clearTimeout(group.heartbeatTimer);
14476
+ group.heartbeatTimer = null;
14477
+ const policy = this.groupPolicy(group);
14478
+ if (policy === void 0 || policy.push === "none" || policy.heartbeatMs === void 0) return;
14479
+ const heartbeatMs = policy.heartbeatMs;
14480
+ const wait = Math.max(0, group.lastReportAt + heartbeatMs - Date.now());
14481
+ group.heartbeatTimer = setTimeout(() => {
14482
+ group.heartbeatTimer = null;
14483
+ if (this.disposed) return;
14484
+ if (Date.now() - group.lastReportAt >= heartbeatMs) this.onSilence(key, heartbeatMs);
14485
+ else this.armHeartbeat(key);
14486
+ }, wait);
14487
+ }
14488
+ async onSilence(key, heartbeatMs) {
14489
+ const group = this.groups.get(key);
14490
+ if (group === void 0) return;
14491
+ group.lastReportAt = Date.now();
14492
+ for (const deviceId of group.devices) this.deps.logger.warn("state refresh: no push within the heartbeat, reading and resubscribing", {
14493
+ tags: { deviceId },
14494
+ meta: { heartbeatMs }
14495
+ });
14496
+ await this.refreshGroup(key, "schedule");
14497
+ const route = [...group.devices][0];
14498
+ if (route !== void 0) try {
14499
+ await this.deps.resubscribe(route);
14500
+ } catch (err) {
14501
+ this.deps.logger.warn("state refresh: resubscribe failed", {
14502
+ tags: { deviceId: route },
14503
+ meta: { error: errorMessage$1(err) }
14504
+ });
14505
+ }
14506
+ await this.refreshGroup(key, "schedule");
14507
+ this.armHeartbeat(key);
14508
+ }
14509
+ async refreshGroup(key, reason) {
14510
+ const group = this.groups.get(key);
14511
+ if (group === void 0) return;
14512
+ const ids = [...group.devices].filter((id) => this.devices.has(id));
14513
+ if (ids.length > 0) await this.refreshDevices(ids, reason);
14514
+ }
14515
+ /** One call for a batching integration, else one per device. */
14516
+ async refreshDevices(deviceIds, reason) {
14517
+ if (this.devices.get(deviceIds[0] ?? -1)?.entry.policy.batch === true) {
14518
+ await this.runRefresh(deviceIds, reason);
14519
+ return;
14520
+ }
14521
+ await Promise.all(deviceIds.map((id) => this.runRefresh([id], reason)));
14522
+ }
14523
+ /**
14524
+ * Read `deviceIds` once every read already queued on them ended — or, with
14525
+ * `waitBoundMs`, once that long passed (a debug line per device that was
14526
+ * still busy). The read becomes the devices' new tail.
14527
+ */
14528
+ async runRefresh(deviceIds, reason, waitBoundMs) {
14529
+ const route = deviceIds[0];
14530
+ if (route === void 0) return;
14531
+ const busy = [];
14532
+ const prior = [];
14533
+ for (const deviceId of deviceIds) {
14534
+ const tail = this.devices.get(deviceId)?.inFlight;
14535
+ if (tail === null || tail === void 0) continue;
14536
+ busy.push(deviceId);
14537
+ prior.push(tail);
14538
+ }
14539
+ const settled = this.afterPrior(prior, busy, waitBoundMs).then(() => this.deps.refresh(route, deviceIds, reason)).catch((err) => {
14540
+ for (const deviceId of deviceIds) this.deps.logger.warn("state refresh failed", {
14541
+ tags: { deviceId },
14542
+ meta: {
14543
+ reason,
14544
+ error: errorMessage$1(err)
14545
+ }
14546
+ });
14547
+ }).finally(() => {
14548
+ for (const deviceId of deviceIds) {
14549
+ const device = this.devices.get(deviceId);
14550
+ if (device !== void 0 && device.inFlight === settled) device.inFlight = null;
14551
+ }
14552
+ });
14553
+ for (const deviceId of deviceIds) {
14554
+ const device = this.devices.get(deviceId);
14555
+ if (device !== void 0) device.inFlight = settled;
14556
+ }
14557
+ await settled;
14558
+ }
14559
+ /** Resolves when every `prior` read ended, or after `waitBoundMs` (logged per busy device). */
14560
+ async afterPrior(prior, busy, waitBoundMs) {
14561
+ if (prior.length === 0) return;
14562
+ const all = Promise.all(prior).then(() => true);
14563
+ if (waitBoundMs === void 0) {
14564
+ await all;
14565
+ return;
14566
+ }
14567
+ let timer;
14568
+ const bound = new Promise((resolve) => {
14569
+ timer = setTimeout(() => resolve(false), waitBoundMs);
14570
+ });
14571
+ const ended = await Promise.race([all, bound]);
14572
+ if (timer !== void 0) clearTimeout(timer);
14573
+ if (ended) return;
14574
+ for (const deviceId of busy) this.deps.logger.debug("state refresh: stopped waiting for the read in flight", {
14575
+ tags: { deviceId },
14576
+ meta: { waitedMs: waitBoundMs }
14577
+ });
14578
+ }
14579
+ clearGroupTimers(group) {
14580
+ if (group.scheduleTimer !== null) clearTimeout(group.scheduleTimer);
14581
+ if (group.heartbeatTimer !== null) clearTimeout(group.heartbeatTimer);
14582
+ group.scheduleTimer = null;
14583
+ group.heartbeatTimer = null;
14584
+ }
14585
+ };
14586
+ //#endregion
14587
+ //#region src/builtins/device-manager/state-refresh-wiring.ts
14588
+ /** Start the scheduler; returns the stop. */
14589
+ function startStateRefresh(deps) {
14590
+ const scheduler = new StateRefreshScheduler({
14591
+ policies: deps.policies ?? getStateRefreshPolicyRegistry(),
14592
+ logger: deps.logger,
14593
+ holdsPending: (deviceId) => deps.mirror.isHoldingDevice(deviceId),
14594
+ refresh: deps.refresh,
14595
+ resubscribe: deps.resubscribe
14596
+ });
14597
+ deps.mirror.setReportTap((deviceId) => scheduler.onReport(deviceId));
14598
+ const uninstall = getCommandFollowUpRegistry().set(scheduler.onCommand);
14599
+ return () => {
14600
+ uninstall();
14601
+ deps.mirror.setReportTap(null);
14602
+ scheduler.dispose();
14603
+ };
14604
+ }
13420
14605
  var REDACTED = "***";
13421
14606
  var ROUTING_KEYS = new Set([
13422
14607
  "deviceId",
@@ -14337,6 +15522,7 @@ var DeviceManagerAddon = class extends BaseAddon {
14337
15522
  transitions = null;
14338
15523
  /** Unsubscribes the command hold (D1061). */
14339
15524
  stopCommandHolds = null;
15525
+ stopStateRefresh = null;
14340
15526
  /**
14341
15527
  * Removes the claimed-status overlay this addon installed on the capability
14342
15528
  * registry (D663, S3): `getStatus` of a claimed cap answers the mirror for
@@ -14663,6 +15849,23 @@ var DeviceManagerAddon = class extends BaseAddon {
14663
15849
  if (records === void 0) throw new Error("[device-manager] ctx.records is required on the hub");
14664
15850
  await records.declare(deviceManagerRecordKinds);
14665
15851
  const tombstones = DeviceTombstoneStore.of(records, this.ctx.logger.child("tombstones"));
15852
+ const identityLinksStore = IdentityLinksStore.of(records);
15853
+ await identityLinksStore.load();
15854
+ const identityLinks = new IdentityLinkReconciler({
15855
+ candidates: () => identityIndex.linkCandidates(),
15856
+ store: identityLinksStore,
15857
+ emit: (category, payload) => this.ctx.eventBus.emit({
15858
+ id: randomUUID(),
15859
+ timestamp: /* @__PURE__ */ new Date(),
15860
+ source: {
15861
+ type: "device",
15862
+ id: payload.bDeviceId
15863
+ },
15864
+ category,
15865
+ data: { ...payload }
15866
+ }),
15867
+ logger: this.ctx.logger.child("identity-links")
15868
+ });
14666
15869
  const discoveryProposals = new DiscoveryProposalService({
14667
15870
  store: DiscoveryProposalStore.of(records),
14668
15871
  orchestrator: this.discoveryDeps(),
@@ -14687,6 +15890,24 @@ var DeviceManagerAddon = class extends BaseAddon {
14687
15890
  mirror: stateMirror,
14688
15891
  logger: this.ctx.logger.child("command-holds")
14689
15892
  });
15893
+ this.stopStateRefresh = startStateRefresh({
15894
+ mirror: stateMirror,
15895
+ logger: this.ctx.logger.child("state-refresh"),
15896
+ refresh: async (deviceId, deviceIds, reason) => {
15897
+ const api = this.ctx.api;
15898
+ if (api === void 0) throw new Error("ctx.api not ready");
15899
+ await api.deviceStateRefresh.refresh.mutate({
15900
+ deviceId,
15901
+ deviceIds: [...deviceIds],
15902
+ reason
15903
+ });
15904
+ },
15905
+ resubscribe: async (deviceId) => {
15906
+ const api = this.ctx.api;
15907
+ if (api === void 0) throw new Error("ctx.api not ready");
15908
+ await api.deviceStateRefresh.resubscribe.mutate({ deviceId });
15909
+ }
15910
+ });
14690
15911
  this.transitions = startDeviceTransitions({
14691
15912
  mirror: stateMirror,
14692
15913
  logger: this.ctx.logger.child("transitions"),
@@ -14724,6 +15945,9 @@ var DeviceManagerAddon = class extends BaseAddon {
14724
15945
  const bootRows = await deviceRows.listAll();
14725
15946
  for (const row of bootRows) idToAddonId.set(row.meta.id, row.meta.addonId);
14726
15947
  identityIndex.seed(bootRows);
15948
+ for (const gone of await tombstones.listSince(0)) await identityLinks.removeDevice(gone.deviceId);
15949
+ identityIndex.onIdentityChanged(() => identityLinks.requestPass());
15950
+ identityLinks.requestPass();
14727
15951
  const stampIntegrationId$1 = (deviceId, integrationId) => stampIntegrationId(metaStore, this.ctx, deviceId, integrationId);
14728
15952
  const templates = this.makeTemplateActions();
14729
15953
  const pctx = {
@@ -14736,6 +15960,7 @@ var DeviceManagerAddon = class extends BaseAddon {
14736
15960
  removalFence: this.removalFence,
14737
15961
  removalCleanup: this.removalCleanup,
14738
15962
  tombstones,
15963
+ identityLinks,
14739
15964
  removalHooks: {
14740
15965
  api: this.ctx.api,
14741
15966
  logger: this.ctx.logger,
@@ -14810,6 +16035,11 @@ var DeviceManagerAddon = class extends BaseAddon {
14810
16035
  setDisplay: (input) => setDisplay(pctx, input),
14811
16036
  setIdentifiers: (input) => setIdentifiers(pctx, input),
14812
16037
  listIdentityCandidates: async () => identityIndex.candidates(),
16038
+ setAttachedIdentifiers: (input) => setAttachedIdentifiers(pctx, input),
16039
+ listIdentityLinks: async (input) => identityLinks.list(input?.deviceId),
16040
+ confirmIdentityLink: ({ linkId }) => identityLinks.confirm(linkId),
16041
+ dismissIdentityLink: ({ linkId }) => identityLinks.dismiss(linkId),
16042
+ unlinkIdentity: ({ linkId }) => identityLinks.unlink(linkId),
14813
16043
  getRoleDisplayDefaults: (input) => getRoleDisplayDefaults(pctx, input),
14814
16044
  setRoleDisplayDefaults: (input) => setRoleDisplayDefaults(pctx, input),
14815
16045
  applyInitialMeta: (input) => applyInitialMeta(pctx, input),
@@ -15085,6 +16315,8 @@ var DeviceManagerAddon = class extends BaseAddon {
15085
16315
  this.templateActions = null;
15086
16316
  await this.transitions?.stop();
15087
16317
  this.transitions = null;
16318
+ this.stopStateRefresh?.();
16319
+ this.stopStateRefresh = null;
15088
16320
  this.stopCommandHolds?.();
15089
16321
  this.stopCommandHolds = null;
15090
16322
  this.removalCleanupImpl?.dispose();
@@ -15101,4 +16333,4 @@ var DeviceManagerAddon = class extends BaseAddon {
15101
16333
  }
15102
16334
  };
15103
16335
  //#endregion
15104
- export { DeviceManagerAddon, DeviceManagerAddon as default, CommandObserverRegistry as a, commandActorFromContext as c, reportCommand as d, runObservedCommand as f, setWrapperActive as g, readDeviceOrThrow as h, getCommandHoldOverrideRegistry as i, commandObserverLink as l, createDeviceSettingsStore as m, mergeAggregates, childCommandHoldEntries as n, __resetCommandObserverRegistryForTests as o, observable as p, childHoldSource as r, addonCommandActor as s, IN_PROCESS_HOLD_SOURCE as t, getCommandObserverRegistry as u };
16336
+ export { deviceIdOfArgs as C, createDeviceSettingsStore as D, DeviceManagerAddon, DeviceManagerAddon as default, observable as E, readDeviceOrThrow as O, commandFollowUpTarget as S, withCommandFollowUp as T, getCommandObserverRegistry as _, childRefreshSource as a, CommandFollowUpRegistry as b, IN_PROCESS_HOLD_SOURCE as c, getCommandHoldOverrideRegistry as d, CommandObserverRegistry as f, commandObserverLink as g, commandActorFromContext as h, __resetStateRefreshPolicyRegistryForTests as i, setWrapperActive as k, childCommandHoldEntries as l, addonCommandActor as m, mergeAggregates, STATE_REFRESH_CAP as n, childStateRefreshEntries as o, __resetCommandObserverRegistryForTests as p, StateRefreshPolicyRegistry as r, getStateRefreshPolicyRegistry as s, IN_PROCESS_REFRESH_SOURCE as t, childHoldSource as u, reportCommand as v, getCommandFollowUpRegistry as w, __resetCommandFollowUpRegistryForTests as x, runObservedCommand as y };