@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
@@ -3,10 +3,10 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-CCd8IeIU.js");
6
+ const require_dist = require("../../dist-BNrIzdrJ.js");
7
7
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
8
8
  const require_log_redactor = require("../../log-redactor-BhIEMaG9.js");
9
- const require_rename_composition_block = require("../../rename-composition-block-2Z2ED7Og.js");
9
+ const require_rename_composition_block = require("../../rename-composition-block-gJ_4GdHr.js");
10
10
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
11
11
  const require_prefix_walk = require("../../prefix-walk-Dv6MLZlM.js");
12
12
  const require_retired_settings_keys = require("../../retired-settings-keys-C8nOOr5H.js");
@@ -485,7 +485,8 @@ function toDeviceInfo(addonId, device, metadata = null, metaRow = null) {
485
485
  ...metaRow?.primaryChildPreference !== void 0 ? { primaryChildPreference: metaRow.primaryChildPreference } : {},
486
486
  ...metaRow?.tags !== void 0 ? { tags: metaRow.tags } : {},
487
487
  ...metaRow?.display !== void 0 ? { display: metaRow.display } : {},
488
- ...metaRow?.identifiers !== void 0 ? { identifiers: metaRow.identifiers } : {}
488
+ ...metaRow?.identifiers !== void 0 ? { identifiers: metaRow.identifiers } : {},
489
+ ...metaRow?.attachedIdentifiers !== void 0 ? { attachedIdentifiers: metaRow.attachedIdentifiers } : {}
489
490
  };
490
491
  }
491
492
  function resolveDeviceById(registry, deviceId) {
@@ -3070,6 +3071,7 @@ async function listAll(pctx, input) {
3070
3071
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3071
3072
  ...m.display !== void 0 ? { display: m.display } : {},
3072
3073
  ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3074
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {},
3073
3075
  ...(() => {
3074
3076
  if (slim) return {};
3075
3077
  const si = projectSourceInfo(persistedConfig ?? {}, stableId, aid, metadata);
@@ -3124,6 +3126,7 @@ async function getDevice(pctx, input) {
3124
3126
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3125
3127
  ...m.display !== void 0 ? { display: m.display } : {},
3126
3128
  ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3129
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {},
3127
3130
  ...sourceInfoGetDevice !== void 0 ? { sourceInfo: sourceInfoGetDevice } : {}
3128
3131
  };
3129
3132
  }
@@ -3205,6 +3208,7 @@ function projectChildren(pctx, parentDeviceId, ownerAddonId, childRows, liveChil
3205
3208
  ...m.tags !== void 0 ? { tags: m.tags } : {},
3206
3209
  ...m.display !== void 0 ? { display: m.display } : {},
3207
3210
  ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
3211
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {},
3208
3212
  ...sourceInfoChild !== void 0 ? { sourceInfo: sourceInfoChild } : {}
3209
3213
  });
3210
3214
  }
@@ -7501,6 +7505,10 @@ function removalSteps(pctx, deviceId, providerAddonId, deletedAt) {
7501
7505
  return (await purge(deviceId)).length;
7502
7506
  }
7503
7507
  },
7508
+ {
7509
+ store: "identity-links",
7510
+ run: async () => pctx.identityLinks === void 0 ? 0 : pctx.identityLinks.removeDevice(deviceId)
7511
+ },
7504
7512
  {
7505
7513
  store: "device-config",
7506
7514
  run: async () => {
@@ -7649,7 +7657,8 @@ async function loadMeta(pctx, input) {
7649
7657
  ...m.integrationId !== void 0 ? { integrationId: m.integrationId } : {},
7650
7658
  ...m.linkDeviceId !== void 0 ? { linkDeviceId: m.linkDeviceId } : {},
7651
7659
  ...m.role !== void 0 ? { role: m.role } : {},
7652
- ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {}
7660
+ ...m.identifiers !== void 0 ? { identifiers: m.identifiers } : {},
7661
+ ...m.attachedIdentifiers !== void 0 ? { attachedIdentifiers: m.attachedIdentifiers } : {}
7653
7662
  };
7654
7663
  }
7655
7664
  /**
@@ -8838,20 +8847,41 @@ function stampedCaller(input) {
8838
8847
  const raw = Reflect.get(Object(input), "callerAddonId");
8839
8848
  return typeof raw === "string" && raw.length > 0 ? raw : null;
8840
8849
  }
8850
+ var METHOD_OF = {
8851
+ identifiers: "setIdentifiers",
8852
+ attachedIdentifiers: "setAttachedIdentifiers"
8853
+ };
8841
8854
  async function setIdentifiers(pctx, input) {
8855
+ return writeDeclaredIdentity(pctx, input, "identifiers");
8856
+ }
8857
+ /**
8858
+ * `device-manager.setAttachedIdentifiers` (D1063): the identity of the device at
8859
+ * the far end of this device's physical link. Same owner check, normalisation
8860
+ * and merge as {@link setIdentifiers}, its own column.
8861
+ */
8862
+ async function setAttachedIdentifiers(pctx, input) {
8863
+ return writeDeclaredIdentity(pctx, input, "attachedIdentifiers");
8864
+ }
8865
+ /** The unread keys the merged declaration still holds, sorted: kept, not seen now. */
8866
+ function retainedKeys(merged, unread) {
8867
+ if (merged === null) return [];
8868
+ return [...new Set(unread)].filter((key) => merged[key] !== void 0).sort();
8869
+ }
8870
+ async function writeDeclaredIdentity(pctx, input, column) {
8871
+ const method = METHOD_OF[column];
8842
8872
  const { deviceId } = input;
8843
8873
  const logger = pctx.host.ctx.logger;
8844
8874
  const caller = stampedCaller(input);
8845
8875
  const parsed = require_dist.DeviceIdentifiersSchema.nullable().safeParse(input.identifiers);
8846
8876
  if (!parsed.success) {
8847
- logger.warn("setIdentifiers refused — the declaration is not in its normalised form", {
8877
+ logger.warn(`${method} refused — the declaration is not in its normalised form`, {
8848
8878
  tags: { deviceId },
8849
8879
  meta: {
8850
8880
  caller,
8851
8881
  issues: parsed.error.issues.map((i) => i.path.join("."))
8852
8882
  }
8853
8883
  });
8854
- throw new SetIdentifiersRefusedError("invalid", `[device-manager] setIdentifiers: device ${deviceId} — declaration not normalised (use normaliseIdentifiers)`);
8884
+ throw new SetIdentifiersRefusedError("invalid", `[device-manager] ${method}: device ${deviceId} — declaration not normalised (use normaliseIdentifiers)`);
8855
8885
  }
8856
8886
  const next = parsed.data === null || require_dist.isEmptyIdentifiers(parsed.data) ? null : parsed.data;
8857
8887
  const outcome = await pctx.metaStore.withMetaWriteLock(async () => {
@@ -8861,25 +8891,39 @@ async function setIdentifiers(pctx, input) {
8861
8891
  kind: "not-owner",
8862
8892
  owner: persisted.addonId
8863
8893
  };
8864
- const stored = persisted.meta.identifiers ?? null;
8894
+ const stored = persisted.meta[column] ?? null;
8865
8895
  const merged = require_dist.mergeIdentifiers(stored, next, input.unread ?? []);
8866
- if (require_dist.sameIdentifiers(stored, merged)) return { kind: "unchanged" };
8867
- await pctx.metaStore.rows.patch(deviceId, { identifiers: merged });
8896
+ if (column === "identifiers") {
8897
+ if (require_dist.sameIdentifiers(stored, merged)) return { kind: "unchanged" };
8898
+ await pctx.metaStore.rows.patch(deviceId, { identifiers: merged });
8899
+ return {
8900
+ kind: "written",
8901
+ value: merged
8902
+ };
8903
+ }
8904
+ const retained = retainedKeys(merged, input.unread ?? []);
8905
+ const storedRetained = persisted.meta.attachedRetained ?? [];
8906
+ const sameRetained = retained.join(",") === storedRetained.join(",");
8907
+ if (require_dist.sameIdentifiers(stored, merged) && sameRetained) return { kind: "unchanged" };
8908
+ await pctx.metaStore.rows.patch(deviceId, {
8909
+ attachedIdentifiers: merged,
8910
+ attachedRetained: retained.length === 0 ? null : retained
8911
+ });
8868
8912
  return {
8869
8913
  kind: "written",
8870
8914
  value: merged
8871
8915
  };
8872
8916
  });
8873
- if (outcome.kind === "unknown-device") throw new SetIdentifiersRefusedError("unknown-device", `[device-manager] setIdentifiers: unknown device id=${deviceId}`);
8917
+ if (outcome.kind === "unknown-device") throw new SetIdentifiersRefusedError("unknown-device", `[device-manager] ${method}: unknown device id=${deviceId}`);
8874
8918
  if (outcome.kind === "not-owner") {
8875
- logger.warn("setIdentifiers refused — only the owning provider declares identifiers", {
8919
+ logger.warn(`${method} refused — only the owning provider declares identifiers`, {
8876
8920
  tags: { deviceId },
8877
8921
  meta: {
8878
8922
  caller,
8879
8923
  owner: outcome.owner
8880
8924
  }
8881
8925
  });
8882
- throw new SetIdentifiersRefusedError("not-owner", `[device-manager] setIdentifiers: device ${deviceId} belongs to ${outcome.owner}; caller ${caller ?? "(unstamped)"} may not declare its identifiers`);
8926
+ throw new SetIdentifiersRefusedError("not-owner", `[device-manager] ${method}: device ${deviceId} belongs to ${outcome.owner}; caller ${caller ?? "(unstamped)"} may not declare its identifiers`);
8883
8927
  }
8884
8928
  if (outcome.kind === "unchanged") return;
8885
8929
  pctx.host.ctx.eventBus.emit({
@@ -8892,12 +8936,396 @@ async function setIdentifiers(pctx, input) {
8892
8936
  category: require_dist.EventCategory.DeviceMetaChanged,
8893
8937
  data: {
8894
8938
  deviceId,
8895
- field: "identifiers",
8939
+ field: column,
8896
8940
  value: outcome.value
8897
8941
  }
8898
8942
  });
8899
8943
  }
8900
8944
  //#endregion
8945
+ //#region src/builtins/device-manager/identity-link-reconciler.ts
8946
+ /**
8947
+ * Turns the identity index's link candidates into `identity-links` records
8948
+ * (D1063), and serves the operator's decisions on them.
8949
+ *
8950
+ * | Situation | Result |
8951
+ * | ------------------------------------------- | ---------------------------------------------- |
8952
+ * | `auto` candidate, no row | `linked` / `auto`, `identity-link.created` |
8953
+ * | `proposal` candidate, no row | `proposed`, no event |
8954
+ * | `proposed` row, candidate now `auto` | `linked` / `auto`, created |
8955
+ * | `dismissed` row | stays dismissed: nothing re-proposes it |
8956
+ * | `linked`/`auto` row, evidence gone | row deleted, `identity-link.lost` evidence-gone |
8957
+ * | `linked`/`operator` row, evidence gone | kept, flagged `evidenceGone`, `lost` evidence-gone |
8958
+ * | `linked`/`operator` flagged, evidence back | flag cleared, `identity-link.created` |
8959
+ * | `proposed` row, evidence gone | row deleted, no event (it never linked) |
8960
+ *
8961
+ * "Evidence gone" is judged from the PERSISTED identifiers, which already keep
8962
+ * an unread value (D49): a camera rebooting, a port that read no client this
8963
+ * poll, change nothing. A flagged operator link never acts: `power-source`
8964
+ * refuses through it and core-blocks withdraws its contribution, so a fresh link
8965
+ * on another port can contribute. It waits for the operator (Unlink) or for its
8966
+ * evidence to return. A link whose side has no row right now is left alone —
8967
+ * a removed device is the `identity-links` removal step's, never a guess here.
8968
+ *
8969
+ * Runs after the seed and on every identity change the index reports,
8970
+ * coalesced: a pass already queued absorbs the next request. No timer. Every
8971
+ * write — a pass, an operator decision, a removal — runs on one chain.
8972
+ */
8973
+ var NOT_LOADED = "the identity links have not been read yet";
8974
+ function sameEvidence(x, y) {
8975
+ return JSON.stringify(x) === JSON.stringify(y);
8976
+ }
8977
+ function sameSide(x, y) {
8978
+ return x.deviceId === y.deviceId && x.addonId === y.addonId && x.stableId === y.stableId;
8979
+ }
8980
+ function payloadOf(link, reason) {
8981
+ return {
8982
+ linkId: link.id,
8983
+ kind: link.kind,
8984
+ aDeviceId: link.a.deviceId,
8985
+ bDeviceId: link.b.deviceId,
8986
+ origin: link.origin,
8987
+ ...reason !== void 0 ? { reason } : {}
8988
+ };
8989
+ }
8990
+ var IdentityLinkReconciler = class {
8991
+ deps;
8992
+ tail = Promise.resolve();
8993
+ passQueued = false;
8994
+ now;
8995
+ constructor(deps) {
8996
+ this.deps = deps;
8997
+ this.now = deps.now ?? (() => Date.now());
8998
+ }
8999
+ /** Queue one pass; a pass already queued (not started) absorbs this request. */
9000
+ requestPass() {
9001
+ if (this.passQueued) return;
9002
+ this.passQueued = true;
9003
+ this.serialized(async () => {
9004
+ this.passQueued = false;
9005
+ await this.pass();
9006
+ }).catch((err) => {
9007
+ this.deps.logger.warn("identity-link pass failed — the next identity change retries", { meta: { error: require_dist.errMsg(err) } });
9008
+ });
9009
+ }
9010
+ /** Resolves when every queued write has run (tests, boot). */
9011
+ async settled() {
9012
+ await this.serialized(async () => void 0);
9013
+ }
9014
+ list(deviceId) {
9015
+ const links = this.deps.store.list();
9016
+ if (links === null) return {
9017
+ status: "not-loaded",
9018
+ reason: NOT_LOADED
9019
+ };
9020
+ return {
9021
+ status: "answered",
9022
+ links: [...deviceId === void 0 ? links : links.filter((l) => l.a.deviceId === deviceId || l.b.deviceId === deviceId)].sort((x, y) => x.id.localeCompare(y.id))
9023
+ };
9024
+ }
9025
+ confirm(linkId) {
9026
+ return this.decide(linkId, "proposed", async (link) => {
9027
+ const next = {
9028
+ ...link,
9029
+ state: "linked",
9030
+ origin: "operator",
9031
+ decidedAt: this.now()
9032
+ };
9033
+ await this.deps.store.put(next);
9034
+ this.log("identity link confirmed by the operator", next);
9035
+ this.deps.emit(require_dist.EventCategory.IdentityLinkCreated, payloadOf(next));
9036
+ return next;
9037
+ });
9038
+ }
9039
+ dismiss(linkId) {
9040
+ return this.decide(linkId, "proposed", async (link) => {
9041
+ const next = this.dismissed(link);
9042
+ await this.deps.store.put(next);
9043
+ this.log("identity link proposal dismissed by the operator", next);
9044
+ return next;
9045
+ });
9046
+ }
9047
+ unlink(linkId) {
9048
+ return this.decide(linkId, "linked", async (link) => {
9049
+ const next = this.dismissed(link);
9050
+ await this.deps.store.put(next);
9051
+ this.log("identity link unlinked by the operator", next);
9052
+ this.deps.emit(require_dist.EventCategory.IdentityLinkLost, payloadOf(next, "operator-unlinked"));
9053
+ return next;
9054
+ });
9055
+ }
9056
+ /** The `identity-links` removal step (D864): every link naming the device goes. */
9057
+ removeDevice(deviceId) {
9058
+ return this.serialized(async () => {
9059
+ const links = this.deps.store.list();
9060
+ if (links === null) throw new Error(NOT_LOADED);
9061
+ let removed = 0;
9062
+ for (const link of links) {
9063
+ if (link.a.deviceId !== deviceId && link.b.deviceId !== deviceId) continue;
9064
+ await this.deps.store.delete(link.id);
9065
+ removed += 1;
9066
+ if (link.state === "linked") {
9067
+ this.log("identity link lost — a side was removed", link, deviceId);
9068
+ this.deps.emit(require_dist.EventCategory.IdentityLinkLost, payloadOf(link, "device-removed"));
9069
+ }
9070
+ }
9071
+ return removed;
9072
+ });
9073
+ }
9074
+ /** One pass over every candidate and every stored link. */
9075
+ async pass() {
9076
+ const answer = this.deps.candidates();
9077
+ const links = this.deps.store.list();
9078
+ if (answer.status !== "answered" || links === null) return;
9079
+ const byId = new Map(links.map((l) => [l.id, l]));
9080
+ const seen = /* @__PURE__ */ new Set();
9081
+ for (const candidate of answer.candidates) {
9082
+ const id = require_dist.identityLinkId(candidate.kind, candidate.a, candidate.b);
9083
+ if (seen.has(id)) continue;
9084
+ seen.add(id);
9085
+ await this.applyCandidate(id, candidate, byId.get(id) ?? null);
9086
+ }
9087
+ for (const link of links) {
9088
+ if (seen.has(link.id)) continue;
9089
+ const aId = answer.deviceIdOf(link.a.addonId, link.a.stableId);
9090
+ const bId = answer.deviceIdOf(link.b.addonId, link.b.stableId);
9091
+ if (aId === null || bId === null) continue;
9092
+ await this.applyEvidenceGone(link);
9093
+ }
9094
+ }
9095
+ async applyCandidate(id, candidate, stored) {
9096
+ if (require_dist.identityLinkSidesRefusal(candidate.kind, candidate.aRole) !== null) {
9097
+ this.deps.logger.debug("identity candidate skipped — the attaching side has the wrong role", {
9098
+ tags: { deviceId: candidate.a.deviceId },
9099
+ meta: {
9100
+ kind: candidate.kind,
9101
+ role: candidate.aRole,
9102
+ other: candidate.b.deviceId
9103
+ }
9104
+ });
9105
+ return;
9106
+ }
9107
+ if (stored === null) {
9108
+ const auto = candidate.confidence === "auto";
9109
+ const link = {
9110
+ id,
9111
+ kind: candidate.kind,
9112
+ a: candidate.a,
9113
+ b: candidate.b,
9114
+ state: auto ? "linked" : "proposed",
9115
+ origin: "auto",
9116
+ evidence: candidate.keys,
9117
+ createdAt: this.now(),
9118
+ ...auto ? { decidedAt: this.now() } : {}
9119
+ };
9120
+ await this.deps.store.put(link);
9121
+ this.log(auto ? "identity link created on strong evidence" : "identity link proposed", link);
9122
+ if (auto) this.deps.emit(require_dist.EventCategory.IdentityLinkCreated, payloadOf(link));
9123
+ return;
9124
+ }
9125
+ if (stored.state === "dismissed") return;
9126
+ const upgrade = stored.state === "proposed" && candidate.confidence === "auto";
9127
+ const moved = !sameSide(stored.a, candidate.a) || !sameSide(stored.b, candidate.b) || !sameEvidence(stored.evidence, candidate.keys) || stored.evidenceGone === true;
9128
+ if (!upgrade && !moved) return;
9129
+ const returned = stored.state === "linked" && stored.evidenceGone === true;
9130
+ const { evidenceGone: _dropped, ...rest } = stored;
9131
+ const next = {
9132
+ ...rest,
9133
+ a: candidate.a,
9134
+ b: candidate.b,
9135
+ evidence: candidate.keys,
9136
+ ...upgrade ? {
9137
+ state: "linked",
9138
+ origin: "auto",
9139
+ decidedAt: this.now()
9140
+ } : {}
9141
+ };
9142
+ await this.deps.store.put(next);
9143
+ if (upgrade) {
9144
+ this.log("identity link created — the proposal now has strong evidence", next);
9145
+ this.deps.emit(require_dist.EventCategory.IdentityLinkCreated, payloadOf(next));
9146
+ }
9147
+ if (returned) {
9148
+ this.log("identity link acts again — the evidence of a confirmed link is back", next);
9149
+ this.deps.emit(require_dist.EventCategory.IdentityLinkCreated, payloadOf(next));
9150
+ }
9151
+ }
9152
+ async applyEvidenceGone(link) {
9153
+ if (link.state === "dismissed") return;
9154
+ if (link.state === "proposed") {
9155
+ await this.deps.store.delete(link.id);
9156
+ this.log("identity link proposal withdrawn — its evidence is gone", link);
9157
+ return;
9158
+ }
9159
+ if (link.origin === "operator") {
9160
+ if (link.evidenceGone === true) return;
9161
+ await this.deps.store.put({
9162
+ ...link,
9163
+ evidenceGone: true
9164
+ });
9165
+ 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);
9166
+ this.deps.emit(require_dist.EventCategory.IdentityLinkLost, payloadOf(link, "evidence-gone"));
9167
+ return;
9168
+ }
9169
+ await this.deps.store.delete(link.id);
9170
+ this.log("identity link lost — its evidence is gone", link);
9171
+ this.deps.emit(require_dist.EventCategory.IdentityLinkLost, payloadOf(link, "evidence-gone"));
9172
+ }
9173
+ dismissed(link) {
9174
+ return {
9175
+ ...link,
9176
+ state: "dismissed",
9177
+ origin: "operator",
9178
+ decidedAt: this.now()
9179
+ };
9180
+ }
9181
+ decide(linkId, from, apply) {
9182
+ return this.serialized(async () => {
9183
+ if (!this.deps.store.isLoaded()) return {
9184
+ ok: false,
9185
+ reason: "not-loaded",
9186
+ message: NOT_LOADED
9187
+ };
9188
+ const link = this.deps.store.get(linkId);
9189
+ if (link === null) return {
9190
+ ok: false,
9191
+ reason: "unknown-link",
9192
+ message: `no identity link ${linkId}`
9193
+ };
9194
+ if (link.state !== from) return {
9195
+ ok: false,
9196
+ reason: "wrong-state",
9197
+ message: `identity link ${linkId} is ${link.state}, not ${from}`
9198
+ };
9199
+ return {
9200
+ ok: true,
9201
+ link: await apply(link)
9202
+ };
9203
+ });
9204
+ }
9205
+ /** One line per side, so each camera's log carries it (`tags.deviceId`). */
9206
+ log(message, link, only) {
9207
+ this.lines("info", message, link, only);
9208
+ }
9209
+ warn(message, link) {
9210
+ this.lines("warn", message, link);
9211
+ }
9212
+ lines(level, message, link, only) {
9213
+ for (const side of [link.a, link.b]) {
9214
+ if (only !== void 0 && side.deviceId === only) continue;
9215
+ this.deps.logger[level](message, {
9216
+ tags: { deviceId: side.deviceId },
9217
+ meta: {
9218
+ linkId: link.id,
9219
+ kind: link.kind,
9220
+ state: link.state,
9221
+ origin: link.origin,
9222
+ other: side === link.a ? link.b.deviceId : link.a.deviceId,
9223
+ evidence: link.evidence.map((k) => k.key)
9224
+ }
9225
+ });
9226
+ }
9227
+ }
9228
+ serialized(write) {
9229
+ const run = this.tail.then(write, write);
9230
+ this.tail = run.then(() => void 0, () => void 0);
9231
+ return run;
9232
+ }
9233
+ };
9234
+ //#endregion
9235
+ //#region src/builtins/device-manager/record-kinds.ts
9236
+ var import_read_all_rows = require_read_all_rows$1.require_read_all_rows();
9237
+ var DeviceTombstoneBodySchema = require_dist.DeviceTombstoneSchema.omit({ deviceId: true });
9238
+ var _deviceManagerRecordKinds = require_dist.defineRecordKinds({
9239
+ tombstones: {
9240
+ schema: DeviceTombstoneBodySchema,
9241
+ class: "ledger",
9242
+ writeTrigger: "`removeDevice` records one row per deleted device after the device row is gone; re-record keeps the earlier `deletedAt`",
9243
+ device: "none",
9244
+ at: "required",
9245
+ indexes: [{
9246
+ name: "deleted_at",
9247
+ fields: ["deletedAt"]
9248
+ }],
9249
+ retention: {
9250
+ owner: "device-manager",
9251
+ reason: "90 days (`DEVICE_TOMBSTONE_RETENTION_MS`), pruned whenever a tombstone is written or the list is read"
9252
+ }
9253
+ },
9254
+ "discovery-proposals": {
9255
+ schema: require_dist.DiscoveryProposalBodySchema,
9256
+ class: "config",
9257
+ writeTrigger: "the passive listener and the 30-minute sweep of `local-network` re-see a device (`lastSeenAt` and `at` move); `dismissDiscoveryProposal` sets `dismissed`",
9258
+ device: "none",
9259
+ at: "required",
9260
+ indexes: [{
9261
+ name: "last_seen_at",
9262
+ fields: ["lastSeenAt"]
9263
+ }],
9264
+ retention: {
9265
+ ttlMs: 2160 * 60 * 60 * 1e3,
9266
+ from: "at"
9267
+ }
9268
+ },
9269
+ "identity-links": {
9270
+ schema: require_dist.IdentityLinkBodySchema,
9271
+ class: "config",
9272
+ writeTrigger: "the identity-link reconciler sees a candidate appear, upgrade or lose its evidence; the operator confirms, dismisses or unlinks (D1063)",
9273
+ device: "none",
9274
+ at: "none",
9275
+ indexes: [{
9276
+ name: "a_device",
9277
+ fields: ["a.deviceId"]
9278
+ }, {
9279
+ name: "b_device",
9280
+ fields: ["b.deviceId"]
9281
+ }],
9282
+ retention: { none: "a link lives as long as both its devices; a dismissal is sticky (operator intent)" }
9283
+ }
9284
+ });
9285
+ var deviceManagerRecordKinds = _deviceManagerRecordKinds;
9286
+ _deviceManagerRecordKinds.tombstones;
9287
+ //#endregion
9288
+ //#region src/builtins/device-manager/identity-links-store.ts
9289
+ var IdentityLinksStore = class IdentityLinksStore {
9290
+ kind;
9291
+ links = null;
9292
+ constructor(kind) {
9293
+ this.kind = kind;
9294
+ }
9295
+ static of(records) {
9296
+ return new IdentityLinksStore(records.kind(deviceManagerRecordKinds["identity-links"]));
9297
+ }
9298
+ async load() {
9299
+ const rows = await (0, import_read_all_rows.readAllRows)(this.kind);
9300
+ this.links = new Map(rows.map((row) => [row.id, {
9301
+ id: row.id,
9302
+ ...row.data
9303
+ }]));
9304
+ }
9305
+ isLoaded() {
9306
+ return this.links !== null;
9307
+ }
9308
+ /** Every link; `null` until loaded. */
9309
+ list() {
9310
+ return this.links === null ? null : [...this.links.values()];
9311
+ }
9312
+ get(id) {
9313
+ return this.links?.get(id) ?? null;
9314
+ }
9315
+ async put(link) {
9316
+ const { id, ...data } = link;
9317
+ await this.kind.put({
9318
+ id,
9319
+ data
9320
+ });
9321
+ this.links?.set(id, link);
9322
+ }
9323
+ async delete(id) {
9324
+ await this.kind.delete(id);
9325
+ this.links?.delete(id);
9326
+ }
9327
+ };
9328
+ //#endregion
8901
9329
  //#region src/builtins/device-manager/device-identity-index.ts
8902
9330
  /**
8903
9331
  * The identifier INDEX (planning#593): identifier key → devices, so the
@@ -8919,7 +9347,13 @@ async function setIdentifiers(pctx, input) {
8919
9347
  * write that lands while the snapshot is in flight is buffered and replayed over
8920
9348
  * it, so the seed can never roll a newer write back.
8921
9349
  *
8922
- * Read-only: it finds candidates, it links nothing (that is step 3).
9350
+ * It finds candidates and links nothing itself: the `IdentityLinkReconciler`
9351
+ * (D1063) turns {@link linkCandidates} into link records, and is told of every
9352
+ * change that can move a candidate through {@link onIdentityChanged}.
9353
+ *
9354
+ * Beside the same-device pairs it pairs a device's `attachedIdentifiers` — the
9355
+ * far end of its physical link, a PoE port's wired client — with another
9356
+ * device's `identifiers`, graded by the same {@link classifyIdentityMatch}.
8923
9357
  */
8924
9358
  /** The `kind=value` keys of one declaration. */
8925
9359
  function keysOf(identifiers) {
@@ -8958,6 +9392,18 @@ function sideOf(d) {
8958
9392
  integrationId: d.integrationId
8959
9393
  };
8960
9394
  }
9395
+ function linkSideOf(d) {
9396
+ return {
9397
+ addonId: d.addonId,
9398
+ stableId: d.stableId,
9399
+ deviceId: d.deviceId
9400
+ };
9401
+ }
9402
+ /** The keys both declarations carry, ordered by key then value. */
9403
+ function sharedKeys(x, y) {
9404
+ const yKeys = new Set(keysOf(y));
9405
+ return keysOf(x).filter((k) => yKeys.has(k)).map(parseKey).filter((k) => k !== null).sort(compareKeys);
9406
+ }
8961
9407
  function compareKeys(x, y) {
8962
9408
  if (x.key !== y.key) return x.key < y.key ? -1 : 1;
8963
9409
  return x.value < y.value ? -1 : x.value > y.value ? 1 : 0;
@@ -8987,6 +9433,9 @@ function classifyIdentityMatch(keys) {
8987
9433
  var DeviceIdentityIndex = class {
8988
9434
  devices = /* @__PURE__ */ new Map();
8989
9435
  byKey = /* @__PURE__ */ new Map();
9436
+ listeners = /* @__PURE__ */ new Set();
9437
+ /** True while {@link seed} replays rows: one notification follows, not one per row. */
9438
+ seeding = false;
8990
9439
  /** `null` once seeded; until then, the writes to replay over the snapshot. */
8991
9440
  pending = [];
8992
9441
  /** Load from a fleet snapshot, then replay every write that landed meanwhile. */
@@ -8995,17 +9444,37 @@ var DeviceIdentityIndex = class {
8995
9444
  this.pending = null;
8996
9445
  this.devices.clear();
8997
9446
  this.byKey.clear();
8998
- for (const row of rows) this.rowWritten(row.meta);
8999
- for (const write of buffered) write(this);
9447
+ this.seeding = true;
9448
+ try {
9449
+ for (const row of rows) this.rowWritten(row.meta);
9450
+ for (const write of buffered) write(this);
9451
+ } finally {
9452
+ this.seeding = false;
9453
+ }
9454
+ this.changed();
9455
+ }
9456
+ /**
9457
+ * Called after every change that can move a candidate (identifiers, attached
9458
+ * identifiers, role, integration, a row written or removed) and after the
9459
+ * seed. Synchronous: the listener schedules its own work.
9460
+ */
9461
+ onIdentityChanged(listener) {
9462
+ this.listeners.add(listener);
9463
+ return () => this.listeners.delete(listener);
9000
9464
  }
9001
9465
  rowWritten(meta) {
9002
9466
  if (this.buffer((i) => i.rowWritten(meta))) return;
9003
9467
  this.put({
9004
9468
  deviceId: meta.id,
9005
9469
  addonId: meta.addonId,
9470
+ stableId: meta.stableId,
9006
9471
  integrationId: meta.integrationId ?? null,
9007
- identifiers: meta.identifiers ?? null
9472
+ role: meta.role ?? null,
9473
+ identifiers: meta.identifiers ?? null,
9474
+ attachedIdentifiers: meta.attachedIdentifiers ?? null,
9475
+ attachedRetained: meta.attachedRetained ?? []
9008
9476
  });
9477
+ this.changed();
9009
9478
  }
9010
9479
  registrationWritten(row) {
9011
9480
  if (this.buffer((i) => i.registrationWritten(row))) return;
@@ -9013,24 +9482,117 @@ var DeviceIdentityIndex = class {
9013
9482
  this.put({
9014
9483
  deviceId: row.deviceId,
9015
9484
  addonId: row.addonId,
9485
+ stableId: row.stableId,
9016
9486
  integrationId: existing?.integrationId ?? null,
9017
- identifiers: existing?.identifiers ?? null
9487
+ role: existing?.role ?? null,
9488
+ identifiers: existing?.identifiers ?? null,
9489
+ attachedIdentifiers: existing?.attachedIdentifiers ?? null,
9490
+ attachedRetained: existing?.attachedRetained ?? []
9018
9491
  });
9492
+ if (existing === void 0 || existing.stableId !== row.stableId) this.changed();
9019
9493
  }
9020
9494
  rowPatched(deviceId, patch) {
9021
- if (patch.identifiers === void 0 && patch.integrationId === void 0) return;
9495
+ if (patch.identifiers === void 0 && patch.attachedIdentifiers === void 0 && patch.attachedRetained === void 0 && patch.integrationId === void 0 && patch.role === void 0) return;
9022
9496
  if (this.buffer((i) => i.rowPatched(deviceId, patch))) return;
9023
9497
  const existing = this.devices.get(deviceId);
9024
9498
  if (existing === void 0) return;
9025
9499
  this.put({
9026
9500
  ...existing,
9027
9501
  ...patch.identifiers !== void 0 ? { identifiers: patch.identifiers } : {},
9028
- ...patch.integrationId !== void 0 ? { integrationId: patch.integrationId } : {}
9502
+ ...patch.attachedIdentifiers !== void 0 ? { attachedIdentifiers: patch.attachedIdentifiers } : {},
9503
+ ...patch.attachedRetained !== void 0 ? { attachedRetained: patch.attachedRetained ?? [] } : {},
9504
+ ...patch.integrationId !== void 0 ? { integrationId: patch.integrationId } : {},
9505
+ ...patch.role !== void 0 ? { role: patch.role } : {}
9029
9506
  });
9507
+ this.changed();
9030
9508
  }
9031
9509
  rowRemoved(deviceId) {
9032
9510
  if (this.buffer((i) => i.rowRemoved(deviceId))) return;
9033
9511
  this.drop(deviceId);
9512
+ this.changed();
9513
+ }
9514
+ /**
9515
+ * Every pair a link could be made of (D1063): the same-device pairs of
9516
+ * {@link candidates}, plus each device's attached identifiers paired with
9517
+ * another integration's device identifiers (`poe-power`).
9518
+ *
9519
+ * One link per port: when a port's attached keys reach several devices, or a
9520
+ * device is reached by several ports, every one of those attached pairs is
9521
+ * graded a `proposal` at most — the operator picks.
9522
+ *
9523
+ * Freshness first: a pair whose shared keys the port only RETAINS (declared
9524
+ * unread — no client now, D49) is no candidate when another port FRESHLY
9525
+ * reports the same device. A camera moved from port 7 to port 9 is port 9's;
9526
+ * port 7's auto link loses its evidence. Two fresh reports stay proposals.
9527
+ */
9528
+ linkCandidates() {
9529
+ const same = this.candidates();
9530
+ if (same.status !== "answered") return { status: "unknown" };
9531
+ const out = [];
9532
+ for (const pair of same.pairs) {
9533
+ const a = this.devices.get(pair.a.deviceId);
9534
+ const b = this.devices.get(pair.b.deviceId);
9535
+ if (a === void 0 || b === void 0) continue;
9536
+ out.push({
9537
+ kind: "same-device",
9538
+ a: linkSideOf(a),
9539
+ b: linkSideOf(b),
9540
+ aRole: a.role,
9541
+ keys: pair.keys,
9542
+ confidence: pair.confidence
9543
+ });
9544
+ }
9545
+ out.push(...this.attachedPairs());
9546
+ const byRef = /* @__PURE__ */ new Map();
9547
+ for (const d of this.devices.values()) byRef.set(`${d.addonId}/${d.stableId}`, d.deviceId);
9548
+ return {
9549
+ status: "answered",
9550
+ candidates: out,
9551
+ deviceIdOf: (addonId, stableId) => byRef.get(`${addonId}/${stableId}`) ?? null
9552
+ };
9553
+ }
9554
+ attachedPairs() {
9555
+ const all = [];
9556
+ for (const port of this.devices.values()) {
9557
+ if (port.attachedIdentifiers === null) continue;
9558
+ const reached = /* @__PURE__ */ new Set();
9559
+ for (const key of keysOf(port.attachedIdentifiers)) for (const id of this.byKey.get(key) ?? []) reached.add(id);
9560
+ for (const id of [...reached].sort((x, y) => x - y)) {
9561
+ const target = this.devices.get(id);
9562
+ if (target === void 0 || id === port.deviceId || sameIntegration(port, target)) continue;
9563
+ const keys = sharedKeys(port.attachedIdentifiers, target.identifiers);
9564
+ const confidence = classifyIdentityMatch(keys);
9565
+ if (confidence === null) continue;
9566
+ const retained = new Set(port.attachedRetained);
9567
+ all.push({
9568
+ pair: {
9569
+ kind: "poe-power",
9570
+ a: linkSideOf(port),
9571
+ b: linkSideOf(target),
9572
+ aRole: port.role,
9573
+ keys,
9574
+ confidence
9575
+ },
9576
+ fresh: keys.some((k) => !retained.has(k.key))
9577
+ });
9578
+ }
9579
+ }
9580
+ const freshlyReached = new Set(all.filter((p) => p.fresh).map((p) => p.pair.b.deviceId));
9581
+ const pairs = all.filter((p) => p.fresh || !freshlyReached.has(p.pair.b.deviceId)).map((p) => p.pair);
9582
+ const perPort = /* @__PURE__ */ new Map();
9583
+ const perTarget = /* @__PURE__ */ new Map();
9584
+ for (const p of pairs) {
9585
+ perPort.set(p.a.deviceId, (perPort.get(p.a.deviceId) ?? 0) + 1);
9586
+ perTarget.set(p.b.deviceId, (perTarget.get(p.b.deviceId) ?? 0) + 1);
9587
+ }
9588
+ return pairs.map((p) => (perPort.get(p.a.deviceId) ?? 0) > 1 || (perTarget.get(p.b.deviceId) ?? 0) > 1 ? {
9589
+ ...p,
9590
+ confidence: "proposal"
9591
+ } : p);
9592
+ }
9593
+ changed() {
9594
+ if (this.pending !== null || this.seeding) return;
9595
+ for (const listener of this.listeners) listener();
9034
9596
  }
9035
9597
  /**
9036
9598
  * Every cross-integration candidate pair, graded by `classifyIdentityMatch`,
@@ -9068,8 +9630,7 @@ var DeviceIdentityIndex = class {
9068
9630
  const a = this.devices.get(idA);
9069
9631
  const b = this.devices.get(idB);
9070
9632
  if (a === void 0 || b === void 0 || sameIntegration(a, b)) return null;
9071
- const bKeys = new Set(keysOf(b.identifiers));
9072
- const keys = keysOf(a.identifiers).filter((k) => bKeys.has(k)).map(parseKey).filter((k) => k !== null).sort(compareKeys);
9633
+ const keys = sharedKeys(a.identifiers, b.identifiers);
9073
9634
  const confidence = classifyIdentityMatch(keys);
9074
9635
  return confidence === null ? null : {
9075
9636
  a: sideOf(a),
@@ -10036,44 +10597,6 @@ var DeviceMetaStore = class {
10036
10597
  });
10037
10598
  };
10038
10599
  //#endregion
10039
- //#region src/builtins/device-manager/record-kinds.ts
10040
- var import_read_all_rows = require_read_all_rows$1.require_read_all_rows();
10041
- var DeviceTombstoneBodySchema = require_dist.DeviceTombstoneSchema.omit({ deviceId: true });
10042
- var _deviceManagerRecordKinds = require_dist.defineRecordKinds({
10043
- tombstones: {
10044
- schema: DeviceTombstoneBodySchema,
10045
- class: "ledger",
10046
- writeTrigger: "`removeDevice` records one row per deleted device after the device row is gone; re-record keeps the earlier `deletedAt`",
10047
- device: "none",
10048
- at: "required",
10049
- indexes: [{
10050
- name: "deleted_at",
10051
- fields: ["deletedAt"]
10052
- }],
10053
- retention: {
10054
- owner: "device-manager",
10055
- reason: "90 days (`DEVICE_TOMBSTONE_RETENTION_MS`), pruned whenever a tombstone is written or the list is read"
10056
- }
10057
- },
10058
- "discovery-proposals": {
10059
- schema: require_dist.DiscoveryProposalBodySchema,
10060
- class: "config",
10061
- writeTrigger: "the passive listener and the 30-minute sweep of `local-network` re-see a device (`lastSeenAt` and `at` move); `dismissDiscoveryProposal` sets `dismissed`",
10062
- device: "none",
10063
- at: "required",
10064
- indexes: [{
10065
- name: "last_seen_at",
10066
- fields: ["lastSeenAt"]
10067
- }],
10068
- retention: {
10069
- ttlMs: 2160 * 60 * 60 * 1e3,
10070
- from: "at"
10071
- }
10072
- }
10073
- });
10074
- var deviceManagerRecordKinds = _deviceManagerRecordKinds;
10075
- _deviceManagerRecordKinds.tombstones;
10076
- //#endregion
10077
10600
  //#region src/builtins/device-manager/device-tombstone-store.ts
10078
10601
  /**
10079
10602
  * The tombstones of deleted devices (D865) — `tombstones` record kind (phase 4).
@@ -10648,6 +11171,14 @@ var DEVICE_ROWS_COLUMNS = [
10648
11171
  {
10649
11172
  name: "identifiers",
10650
11173
  type: "JSON"
11174
+ },
11175
+ {
11176
+ name: "attachedIdentifiers",
11177
+ type: "JSON"
11178
+ },
11179
+ {
11180
+ name: "attachedRetained",
11181
+ type: "JSON"
10651
11182
  }
10652
11183
  ];
10653
11184
  /**
@@ -10768,6 +11299,8 @@ function decodeDeviceRow(data) {
10768
11299
  const rawDisplay = data["display"];
10769
11300
  const rawMetadata = data["metadata"];
10770
11301
  const identifiers = require_dist.DeviceIdentifiersSchema.safeParse(data["identifiers"]);
11302
+ const attachedIdentifiers = require_dist.DeviceIdentifiersSchema.safeParse(data["attachedIdentifiers"]);
11303
+ const attachedRetained = require_dist.DeviceIdentifierKeySchema.array().min(1).safeParse(data["attachedRetained"]);
10771
11304
  return {
10772
11305
  meta: {
10773
11306
  id: deviceId,
@@ -10790,7 +11323,9 @@ function decodeDeviceRow(data) {
10790
11323
  ...primaryChildPreference !== void 0 ? { primaryChildPreference } : {},
10791
11324
  ...role !== void 0 ? { role } : {},
10792
11325
  ...isPlainObject$1(rawDisplay) ? { display: toDisplayOverride(rawDisplay) } : {},
10793
- ...identifiers.success ? { identifiers: identifiers.data } : {}
11326
+ ...identifiers.success ? { identifiers: identifiers.data } : {},
11327
+ ...attachedIdentifiers.success ? { attachedIdentifiers: attachedIdentifiers.data } : {},
11328
+ ...attachedRetained.success ? { attachedRetained: attachedRetained.data } : {}
10794
11329
  },
10795
11330
  metadata: isPlainObject$1(rawMetadata) ? rawMetadata : null,
10796
11331
  registered: readBoolean(data["registered"]) ?? false
@@ -10837,7 +11372,9 @@ function encodeDeviceRow(meta, extra = {}) {
10837
11372
  primaryChildPreference: meta.primaryChildPreference === void 0 ? null : [...meta.primaryChildPreference],
10838
11373
  role: meta.role ?? null,
10839
11374
  display: meta.display ?? null,
10840
- identifiers: meta.identifiers ?? null
11375
+ identifiers: meta.identifiers ?? null,
11376
+ attachedIdentifiers: meta.attachedIdentifiers ?? null,
11377
+ attachedRetained: meta.attachedRetained === void 0 ? null : [...meta.attachedRetained]
10841
11378
  };
10842
11379
  if (extra.metadata !== void 0) row["metadata"] = extra.metadata;
10843
11380
  return row;
@@ -11398,7 +11935,7 @@ function createDeviceStateClaimMethods(deps) {
11398
11935
  meta: {
11399
11936
  cap: capName,
11400
11937
  owner,
11401
- error: errorMessage$3(err)
11938
+ error: errorMessage$4(err)
11402
11939
  }
11403
11940
  });
11404
11941
  throw err;
@@ -11443,13 +11980,13 @@ function createDeviceStateClaimMethods(deps) {
11443
11980
  meta: {
11444
11981
  cap: key.capName,
11445
11982
  refusal: code,
11446
- error: errorMessage$3(err)
11983
+ error: errorMessage$4(err)
11447
11984
  }
11448
11985
  });
11449
11986
  }
11450
11987
  }
11451
11988
  }
11452
- function errorMessage$3(err) {
11989
+ function errorMessage$4(err) {
11453
11990
  return err instanceof Error ? err.message : String(err);
11454
11991
  }
11455
11992
  //#endregion
@@ -11727,7 +12264,7 @@ var RuntimeStateRowUnreadError = class extends Error {
11727
12264
  };
11728
12265
  var ROW_UNREAD_REFUSAL_MESSAGE = "runtime-state row write refused — the row could not be read first, nothing written";
11729
12266
  var ROW_DROPS_CAPS_MESSAGE = "runtime-state row write DROPS caps the stored row holds";
11730
- function errorMessage$2(err) {
12267
+ function errorMessage$3(err) {
11731
12268
  return err instanceof Error ? err.message : String(err);
11732
12269
  }
11733
12270
  /**
@@ -11895,7 +12432,7 @@ var MirrorRowWriter = class MirrorRowWriter {
11895
12432
  tags: { deviceId },
11896
12433
  meta: {
11897
12434
  path,
11898
- error: errorMessage$2(err)
12435
+ error: errorMessage$3(err)
11899
12436
  }
11900
12437
  });
11901
12438
  }
@@ -11977,7 +12514,7 @@ var MirrorRowWriter = class MirrorRowWriter {
11977
12514
  slot.lastWriteFailed = true;
11978
12515
  this.deps.logger.warn("writeDeviceRuntimeState failed", {
11979
12516
  tags: { deviceId },
11980
- meta: { error: errorMessage$2(err) }
12517
+ meta: { error: errorMessage$3(err) }
11981
12518
  });
11982
12519
  }
11983
12520
  }
@@ -12052,7 +12589,7 @@ var MirrorRowWriter = class MirrorRowWriter {
12052
12589
  try {
12053
12590
  await this.serialiseWrite(deviceId, () => this.writeRow(deviceId, settings, blob, "drain"));
12054
12591
  } catch (err) {
12055
- this.refuseDrain(deviceId, `the pending runtime-state write failed: ${errorMessage$2(err)}`, err);
12592
+ this.refuseDrain(deviceId, `the pending runtime-state write failed: ${errorMessage$3(err)}`, err);
12056
12593
  }
12057
12594
  }
12058
12595
  /** A drain that cannot vouch for the row: still owed (re-armed on release), logged, refused. */
@@ -12253,6 +12790,11 @@ var CommandHolds = class {
12253
12790
  isHolding(deviceId, capName) {
12254
12791
  return (this.held.get(deviceId)?.get(capName)?.size ?? 0) > 0;
12255
12792
  }
12793
+ /** Is any field of any cap of the device still held? (D1062: the command burst stops when this is false.) */
12794
+ isHoldingDevice(deviceId) {
12795
+ for (const fields of this.held.get(deviceId)?.values() ?? []) if (fields.size > 0) return true;
12796
+ return false;
12797
+ }
12256
12798
  /** Forget a removed device's holds. */
12257
12799
  clearDevice(deviceId) {
12258
12800
  this.held.delete(deviceId);
@@ -12325,13 +12867,14 @@ var CommandHolds = class {
12325
12867
  */
12326
12868
  var RUNNING_STATE_CAP = "running-state";
12327
12869
  var SEED_REFUSAL_MESSAGE = "runtime-state row unreadable — native write refused until it reads";
12328
- function errorMessage$1(err) {
12870
+ function errorMessage$2(err) {
12329
12871
  return err instanceof Error ? err.message : String(err);
12330
12872
  }
12331
12873
  var DeviceStateMirror = class {
12332
12874
  ctx;
12333
12875
  policyFor;
12334
12876
  transitionTap = null;
12877
+ reportTap = null;
12335
12878
  /**
12336
12879
  * Hub-side mirror of every device's cap-keyed NATIVE runtime state — what the
12337
12880
  * provider wrote. Key: deviceId. Value: per-cap slice map. Empty by default —
@@ -12392,6 +12935,10 @@ var DeviceStateMirror = class {
12392
12935
  setTransitionTap(tap) {
12393
12936
  this.transitionTap = tap;
12394
12937
  }
12938
+ /** Set once by the device-manager: told of every native slice reported, before the no-change check (D1062). */
12939
+ setReportTap(tap) {
12940
+ this.reportTap = tap;
12941
+ }
12395
12942
  /**
12396
12943
  * Hold what a command leads to: the effective slice shows it at once (and
12397
12944
  * `DeviceStateChanged` carries it), the stored, persisted and recorded slice
@@ -12404,6 +12951,10 @@ var DeviceStateMirror = class {
12404
12951
  releaseCommand(token, reason) {
12405
12952
  this.holds.release(token, reason);
12406
12953
  }
12954
+ /** Whether any command hold on the device is still unconfirmed (D1062). */
12955
+ isHoldingDevice(deviceId) {
12956
+ return this.holds.isHoldingDevice(deviceId);
12957
+ }
12407
12958
  /** Stop the hold timers (shutdown). */
12408
12959
  disposeHolds() {
12409
12960
  this.holds.dispose();
@@ -12428,6 +12979,7 @@ var DeviceStateMirror = class {
12428
12979
  * a SQLite commit.
12429
12980
  */
12430
12981
  applySingleCapUpdate(deviceId, capName, slice) {
12982
+ this.reportTap?.(deviceId, capName);
12431
12983
  let perCap = this.stateMirror.get(deviceId);
12432
12984
  if (!perCap) {
12433
12985
  perCap = /* @__PURE__ */ new Map();
@@ -12693,7 +13245,7 @@ var DeviceStateMirror = class {
12693
13245
  await this.ensureRowRead(deviceId, settings);
12694
13246
  return null;
12695
13247
  } catch (err) {
12696
- return refused("row-unreadable", `device ${deviceId}: ${errorMessage$1(err)}`);
13248
+ return refused("row-unreadable", `device ${deviceId}: ${errorMessage$2(err)}`);
12697
13249
  }
12698
13250
  }
12699
13251
  readRowOnce(deviceId, settings) {
@@ -12707,7 +13259,7 @@ var DeviceStateMirror = class {
12707
13259
  this.seedRefusalLogged.add(deviceId);
12708
13260
  this.ctx.logger.warn(SEED_REFUSAL_MESSAGE, {
12709
13261
  tags: { deviceId },
12710
- meta: { error: errorMessage$1(err) }
13262
+ meta: { error: errorMessage$2(err) }
12711
13263
  });
12712
13264
  }
12713
13265
  throw err;
@@ -12741,7 +13293,7 @@ var DeviceStateMirror = class {
12741
13293
  meta: {
12742
13294
  cap: op.cap,
12743
13295
  owner: op.owner,
12744
- error: errorMessage$1(err)
13296
+ error: errorMessage$2(err)
12745
13297
  }
12746
13298
  };
12747
13299
  if (rollback()) {
@@ -13112,6 +13664,93 @@ function pipeReducer(prev, fn) {
13112
13664
  return fn(prev);
13113
13665
  }
13114
13666
  //#endregion
13667
+ //#region src/kernel/command-follow-up.ts
13668
+ /**
13669
+ * The command follow-up (D1062): the work a device command waits for before
13670
+ * its caller hears the answer.
13671
+ *
13672
+ * The D1022 seams that observe a command (the hub tRPC mount, the UDS parent,
13673
+ * an in-process hub addon's `ctx.api`) also await this hook once the
13674
+ * provider's call settled — the hub's state-refresh scheduler re-reads the
13675
+ * device there, so the command returns after the real state was pushed.
13676
+ *
13677
+ * Unlike the observation (telemetry, D8) this one is awaited, but it is never
13678
+ * a gate: a follow-up that throws is swallowed here, and the call's own result
13679
+ * or error is what the caller gets. Cost when nothing is registered: one
13680
+ * undefined check (D181).
13681
+ */
13682
+ /** The one follow-up of this process (the hub's device-manager installs it). */
13683
+ var CommandFollowUpRegistry = class {
13684
+ handler = null;
13685
+ /** Install (or, with `null`, remove) the follow-up. Returns the uninstall. */
13686
+ set(handler) {
13687
+ this.handler = handler;
13688
+ return () => {
13689
+ if (this.handler === handler) this.handler = null;
13690
+ };
13691
+ }
13692
+ /** Run the follow-up for a settled command. Never throws. */
13693
+ async run(target, outcome) {
13694
+ const handler = this.handler;
13695
+ if (handler === null) return;
13696
+ try {
13697
+ await handler(target, outcome);
13698
+ } catch {}
13699
+ }
13700
+ };
13701
+ var registry$3;
13702
+ /** The process-wide registry. */
13703
+ function getCommandFollowUpRegistry() {
13704
+ registry$3 ??= new CommandFollowUpRegistry();
13705
+ return registry$3;
13706
+ }
13707
+ /** Test seam: forget the handler. */
13708
+ function __resetCommandFollowUpRegistryForTests() {
13709
+ registry$3 = void 0;
13710
+ }
13711
+ /** The target of a call when it is a device command naming a device, else `null`. */
13712
+ function commandFollowUpTarget(capName, method, deviceId) {
13713
+ if (deviceId === void 0 || !Number.isInteger(deviceId)) return null;
13714
+ if (!(0, _camstack_types_addon.isCommand)(capName, method)) return null;
13715
+ return {
13716
+ deviceId,
13717
+ capName,
13718
+ method
13719
+ };
13720
+ }
13721
+ /** The `deviceId` an args object names, or `undefined`. */
13722
+ function deviceIdOfArgs(args) {
13723
+ if (args === null || typeof args !== "object" || Array.isArray(args)) return void 0;
13724
+ const deviceId = Reflect.get(args, "deviceId");
13725
+ return typeof deviceId === "number" && Number.isInteger(deviceId) ? deviceId : void 0;
13726
+ }
13727
+ /**
13728
+ * Await `result`, then the follow-up, then answer with `result` — its value, or
13729
+ * its error rethrown. Without a follow-up or a target, `result` is returned
13730
+ * untouched.
13731
+ */
13732
+ function withCommandFollowUp(followUp, target, result) {
13733
+ if (followUp === void 0 || target === null) return result;
13734
+ return settleThenFollowUp(followUp, target, result);
13735
+ }
13736
+ async function settleThenFollowUp(followUp, target, result) {
13737
+ let value;
13738
+ try {
13739
+ value = await result;
13740
+ } catch (err) {
13741
+ await runCommandFollowUp(followUp, target, "failed");
13742
+ throw err;
13743
+ }
13744
+ await runCommandFollowUp(followUp, target, "ok");
13745
+ return value;
13746
+ }
13747
+ /** Run `followUp` for a settled command, swallowing its failure. */
13748
+ async function runCommandFollowUp(followUp, target, outcome) {
13749
+ try {
13750
+ await followUp(target, outcome);
13751
+ } catch {}
13752
+ }
13753
+ //#endregion
13115
13754
  //#region src/kernel/command-observation.ts
13116
13755
  /** Fan-out of command observations to the subscribers of this process. */
13117
13756
  var CommandObserverRegistry = class {
@@ -13132,15 +13771,15 @@ var CommandObserverRegistry = class {
13132
13771
  } catch {}
13133
13772
  }
13134
13773
  };
13135
- var registry$1;
13774
+ var registry$2;
13136
13775
  /** The process-wide registry. */
13137
13776
  function getCommandObserverRegistry() {
13138
- registry$1 ??= new CommandObserverRegistry();
13139
- return registry$1;
13777
+ registry$2 ??= new CommandObserverRegistry();
13778
+ return registry$2;
13140
13779
  }
13141
13780
  /** Test seam: forget every subscriber. */
13142
13781
  function __resetCommandObserverRegistryForTests() {
13143
- registry$1 = void 0;
13782
+ registry$2 = void 0;
13144
13783
  }
13145
13784
  function isRecord(value) {
13146
13785
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -13251,18 +13890,45 @@ function commandObserverLink(options) {
13251
13890
  actor: addonCommandActor(options.callerAddonId, (0, _camstack_types_addon.readCommandOrigin)(op.context)),
13252
13891
  outcome
13253
13892
  });
13893
+ const target = commandFollowUpTarget(capName, method, deviceIdOfArgs(op.input));
13894
+ const followUp = options.followUp;
13895
+ if (followUp === void 0 || target === null) {
13896
+ const sub = downstream.subscribe({
13897
+ next: (value) => observer.next(value),
13898
+ error: (err) => {
13899
+ settled.reject(err);
13900
+ observer.error(err);
13901
+ },
13902
+ complete: () => {
13903
+ settled.resolve();
13904
+ observer.complete();
13905
+ }
13906
+ });
13907
+ return () => sub.unsubscribe();
13908
+ }
13909
+ const answered = [];
13910
+ let closed = false;
13254
13911
  const sub = downstream.subscribe({
13255
- next: (value) => observer.next(value),
13912
+ next: (value) => void answered.push(value),
13256
13913
  error: (err) => {
13257
13914
  settled.reject(err);
13258
- observer.error(err);
13915
+ runCommandFollowUp(followUp, target, "failed").then(() => {
13916
+ if (!closed) observer.error(err);
13917
+ });
13259
13918
  },
13260
13919
  complete: () => {
13261
13920
  settled.resolve();
13262
- observer.complete();
13921
+ runCommandFollowUp(followUp, target, "ok").then(() => {
13922
+ if (closed) return;
13923
+ for (const value of answered) observer.next(value);
13924
+ observer.complete();
13925
+ });
13263
13926
  }
13264
13927
  });
13265
- return () => sub.unsubscribe();
13928
+ return () => {
13929
+ closed = true;
13930
+ sub.unsubscribe();
13931
+ };
13266
13932
  });
13267
13933
  };
13268
13934
  }
@@ -13376,11 +14042,11 @@ var CommandHoldOverrideRegistry = class {
13376
14042
  }
13377
14043
  }
13378
14044
  };
13379
- var registry;
14045
+ var registry$1;
13380
14046
  /** The process-wide registry. */
13381
14047
  function getCommandHoldOverrideRegistry() {
13382
- registry ??= new CommandHoldOverrideRegistry();
13383
- return registry;
14048
+ registry$1 ??= new CommandHoldOverrideRegistry();
14049
+ return registry$1;
13384
14050
  }
13385
14051
  //#endregion
13386
14052
  //#region src/builtins/device-manager/command-holds-wiring.ts
@@ -13424,6 +14090,525 @@ function startCommandHolds(deps) {
13424
14090
  deps.mirror.disposeHolds();
13425
14091
  };
13426
14092
  }
14093
+ //#endregion
14094
+ //#region src/kernel/state-refresh-policies.ts
14095
+ /** The cap a policy is stated on. */
14096
+ var STATE_REFRESH_CAP = "device-state-refresh";
14097
+ /** The source key of an in-process registration. */
14098
+ var IN_PROCESS_REFRESH_SOURCE = "in-process";
14099
+ /** The source key of a forked child's registrations. */
14100
+ function childRefreshSource(childId) {
14101
+ return `child:${childId}`;
14102
+ }
14103
+ /** The policies a child's cap descriptors carry, one entry per device. */
14104
+ function childStateRefreshEntries(childId, caps) {
14105
+ const out = [];
14106
+ for (const cap of caps) {
14107
+ if (cap.capName !== "device-state-refresh") continue;
14108
+ if (cap.deviceId === void 0 || cap.stateRefresh === void 0) continue;
14109
+ out.push({
14110
+ deviceId: cap.deviceId,
14111
+ addonId: cap.addonId ?? childId,
14112
+ policy: cap.stateRefresh
14113
+ });
14114
+ }
14115
+ return out;
14116
+ }
14117
+ var StateRefreshPolicyRegistry = class {
14118
+ bySource = /* @__PURE__ */ new Map();
14119
+ listeners = /* @__PURE__ */ new Set();
14120
+ /** Record (or replace) one device's policy from `source`. */
14121
+ set(source, entry) {
14122
+ const perSource = new Map(this.bySource.get(source) ?? []);
14123
+ perSource.set(entry.deviceId, entry);
14124
+ this.bySource.set(source, perSource);
14125
+ this.changed();
14126
+ }
14127
+ /** Forget one device's policy from `source`. */
14128
+ delete(source, deviceId) {
14129
+ const perSource = this.bySource.get(source);
14130
+ if (perSource === void 0 || !perSource.has(deviceId)) return;
14131
+ const next = new Map(perSource);
14132
+ next.delete(deviceId);
14133
+ if (next.size === 0) this.bySource.delete(source);
14134
+ else this.bySource.set(source, next);
14135
+ this.changed();
14136
+ }
14137
+ /** Replace everything `source` reported with `entries` (an empty list forgets the source). */
14138
+ replaceSource(source, entries) {
14139
+ const had = this.bySource.has(source);
14140
+ if (entries.length === 0) {
14141
+ this.bySource.delete(source);
14142
+ if (had) this.changed();
14143
+ return;
14144
+ }
14145
+ this.bySource.set(source, new Map(entries.map((e) => [e.deviceId, e])));
14146
+ this.changed();
14147
+ }
14148
+ /** Every device's policy (a device registered by two sources keeps the first). */
14149
+ entries() {
14150
+ const seen = /* @__PURE__ */ new Map();
14151
+ for (const perSource of this.bySource.values()) for (const entry of perSource.values()) if (!seen.has(entry.deviceId)) seen.set(entry.deviceId, entry);
14152
+ return [...seen.values()];
14153
+ }
14154
+ /** One device's policy, or `undefined` when its provider did not migrate. */
14155
+ get(deviceId) {
14156
+ for (const perSource of this.bySource.values()) {
14157
+ const found = perSource.get(deviceId);
14158
+ if (found !== void 0) return found;
14159
+ }
14160
+ }
14161
+ subscribe(listener) {
14162
+ this.listeners.add(listener);
14163
+ return () => {
14164
+ this.listeners.delete(listener);
14165
+ };
14166
+ }
14167
+ changed() {
14168
+ for (const listener of this.listeners) try {
14169
+ listener();
14170
+ } catch {}
14171
+ }
14172
+ };
14173
+ var registry;
14174
+ /** The process-wide registry. */
14175
+ function getStateRefreshPolicyRegistry() {
14176
+ registry ??= new StateRefreshPolicyRegistry();
14177
+ return registry;
14178
+ }
14179
+ /** Test seam: forget every policy. */
14180
+ function __resetStateRefreshPolicyRegistryForTests() {
14181
+ registry = void 0;
14182
+ }
14183
+ //#endregion
14184
+ //#region src/builtins/device-manager/state-refresh-scheduler.ts
14185
+ /**
14186
+ * The state-refresh scheduler (D1062, amending D224): the core decides WHEN a
14187
+ * migrated provider re-reads a device; the provider only knows HOW.
14188
+ *
14189
+ * The policy each provider declared on its `device-state-refresh`
14190
+ * registration (`StateRefreshPolicyRegistry`) drives it. Devices are grouped
14191
+ * per integration instance (`addonId::integrationId`):
14192
+ *
14193
+ * - cadence: `effectiveRefreshIntervalMs` — the declared minimum, slowed (never
14194
+ * sped up) by the integration's own setting, no idle back-off;
14195
+ * `push: 'full'` is never scheduled. A batching integration (`batch: true`)
14196
+ * has ONE schedule for the group — one due time, one read of every device
14197
+ * per interval; a device that registers later joins the group's next tick.
14198
+ * A non-batching integration keeps one schedule per device;
14199
+ * - command (`onCommand`, awaited by the D1022 seams): a polled device is read
14200
+ * at once and the command returns after it, then read again at ~3 s and
14201
+ * ~10 s while a D1061 hold on it is still pending; a push device waits
14202
+ * `PUSH_CONFIRM_WINDOW_MS` for the confirming push and reads once if none
14203
+ * came. These reads are per device and never move a batched group's schedule;
14204
+ * - push health: silence past `heartbeatMs` reads the integration, asks it to
14205
+ * resubscribe and reads again; a new `connectionEpoch` reads everything.
14206
+ *
14207
+ * Reads of one device are serialized: each starts after the previous one on
14208
+ * that device ended. A scheduled tick that finds its last read still running
14209
+ * is skipped (debug line); a command waits for the read in flight at most
14210
+ * `COMMAND_WAIT_BOUND_MS`, then reads its own device (debug line). A refresh
14211
+ * failure is a warn line per device and never fails a command.
14212
+ */
14213
+ /** The longest a command waits for a read already in flight on its device. */
14214
+ var COMMAND_WAIT_BOUND_MS = 5e3;
14215
+ function groupKeyOf(entry) {
14216
+ return `${entry.addonId}::${entry.policy.integrationId}`;
14217
+ }
14218
+ function errorMessage$1(err) {
14219
+ return err instanceof Error ? err.message : String(err);
14220
+ }
14221
+ var StateRefreshScheduler = class {
14222
+ deps;
14223
+ devices = /* @__PURE__ */ new Map();
14224
+ groups = /* @__PURE__ */ new Map();
14225
+ unsubscribe;
14226
+ disposed = false;
14227
+ constructor(deps) {
14228
+ this.deps = deps;
14229
+ this.unsubscribe = deps.policies.subscribe(() => this.reconcile());
14230
+ this.reconcile();
14231
+ }
14232
+ /** The command follow-up (awaited by the D1022 seams; never throws). */
14233
+ onCommand = async (target, outcome) => {
14234
+ const device = this.devices.get(target.deviceId);
14235
+ if (device === void 0 || this.disposed) return;
14236
+ device.lastCommandAt = Date.now();
14237
+ this.cancelFollowUps(device);
14238
+ const { policy } = device.entry;
14239
+ if (policy.push !== "none") {
14240
+ this.armPushWindow(target.deviceId, device);
14241
+ return;
14242
+ }
14243
+ this.deps.logger.debug("state refresh after command", {
14244
+ tags: { deviceId: target.deviceId },
14245
+ meta: {
14246
+ capName: target.capName,
14247
+ method: target.method,
14248
+ outcome
14249
+ }
14250
+ });
14251
+ await this.runRefresh([target.deviceId], "command", COMMAND_WAIT_BOUND_MS);
14252
+ if (!policy.batch) {
14253
+ device.dueAt = Date.now() + require_dist.effectiveRefreshIntervalMs(policy);
14254
+ this.armSchedule(groupKeyOf(device.entry));
14255
+ }
14256
+ this.armBurst(target.deviceId, device);
14257
+ };
14258
+ /** A state report reached the mirror for `deviceId` (push or read). */
14259
+ onReport(deviceId) {
14260
+ const device = this.devices.get(deviceId);
14261
+ if (device === void 0) return;
14262
+ const now = Date.now();
14263
+ device.lastReportAt = now;
14264
+ const group = this.groups.get(groupKeyOf(device.entry));
14265
+ if (group !== void 0) group.lastReportAt = now;
14266
+ }
14267
+ dispose() {
14268
+ this.disposed = true;
14269
+ this.unsubscribe();
14270
+ for (const device of this.devices.values()) this.cancelFollowUps(device);
14271
+ for (const group of this.groups.values()) this.clearGroupTimers(group);
14272
+ this.devices.clear();
14273
+ this.groups.clear();
14274
+ }
14275
+ reconcile() {
14276
+ if (this.disposed) return;
14277
+ const now = Date.now();
14278
+ const current = new Map(this.deps.policies.entries().map((e) => [e.deviceId, e]));
14279
+ for (const [deviceId, device] of this.devices) {
14280
+ if (current.has(deviceId)) continue;
14281
+ this.cancelFollowUps(device);
14282
+ this.devices.delete(deviceId);
14283
+ }
14284
+ const reconnected = /* @__PURE__ */ new Set();
14285
+ for (const entry of current.values()) {
14286
+ const existing = this.devices.get(entry.deviceId);
14287
+ const interval = require_dist.effectiveRefreshIntervalMs(entry.policy);
14288
+ if (existing === void 0) this.devices.set(entry.deviceId, {
14289
+ entry,
14290
+ dueAt: now + interval,
14291
+ lastReportAt: now,
14292
+ lastCommandAt: 0,
14293
+ inFlight: null,
14294
+ scheduledInFlight: null,
14295
+ burst: [],
14296
+ pushWindow: null
14297
+ });
14298
+ else {
14299
+ if (require_dist.effectiveRefreshIntervalMs(existing.entry.policy) !== interval) existing.dueAt = now + interval;
14300
+ existing.entry = entry;
14301
+ }
14302
+ if (this.noteEpoch(entry)) reconnected.add(groupKeyOf(entry));
14303
+ }
14304
+ this.rebuildGroups(now);
14305
+ for (const key of reconnected) {
14306
+ this.deps.logger.info("state refresh: integration reconnected, reading every device", { meta: { group: key } });
14307
+ this.refreshGroup(key, "schedule");
14308
+ }
14309
+ }
14310
+ /** Track the group's connection epoch; `true` when it moved past a known one. */
14311
+ noteEpoch(entry) {
14312
+ const epoch = entry.policy.connectionEpoch;
14313
+ if (epoch === void 0) return false;
14314
+ const key = groupKeyOf(entry);
14315
+ const group = this.groups.get(key);
14316
+ if (group === void 0) return false;
14317
+ const previous = group.epoch;
14318
+ if (previous === void 0 || epoch > previous) group.epoch = epoch;
14319
+ return previous !== void 0 && epoch > previous;
14320
+ }
14321
+ rebuildGroups(now) {
14322
+ const members = /* @__PURE__ */ new Map();
14323
+ for (const [deviceId, device] of this.devices) {
14324
+ const key = groupKeyOf(device.entry);
14325
+ const set = members.get(key) ?? /* @__PURE__ */ new Set();
14326
+ set.add(deviceId);
14327
+ members.set(key, set);
14328
+ }
14329
+ for (const [key, group] of this.groups) {
14330
+ if (members.has(key)) continue;
14331
+ this.clearGroupTimers(group);
14332
+ this.groups.delete(key);
14333
+ }
14334
+ for (const [key, devices] of members) {
14335
+ const existing = this.groups.get(key);
14336
+ if (existing === void 0) {
14337
+ const first = this.devices.get([...devices][0] ?? -1);
14338
+ const intervalMs = first === void 0 ? 0 : require_dist.effectiveRefreshIntervalMs(first.entry.policy);
14339
+ this.groups.set(key, {
14340
+ key,
14341
+ devices,
14342
+ dueAt: now + intervalMs,
14343
+ intervalMs,
14344
+ scheduleTimer: null,
14345
+ heartbeatTimer: null,
14346
+ lastReportAt: now,
14347
+ epoch: first?.entry.policy.connectionEpoch
14348
+ });
14349
+ } else {
14350
+ existing.devices = devices;
14351
+ const policy = this.groupPolicy(existing);
14352
+ const intervalMs = policy === void 0 ? 0 : require_dist.effectiveRefreshIntervalMs(policy);
14353
+ if (intervalMs !== existing.intervalMs) {
14354
+ existing.intervalMs = intervalMs;
14355
+ existing.dueAt = now + intervalMs;
14356
+ }
14357
+ }
14358
+ this.armSchedule(key);
14359
+ this.armHeartbeat(key);
14360
+ }
14361
+ }
14362
+ groupPolicy(group) {
14363
+ for (const deviceId of group.devices) {
14364
+ const device = this.devices.get(deviceId);
14365
+ if (device !== void 0) return device.entry.policy;
14366
+ }
14367
+ }
14368
+ armSchedule(key) {
14369
+ const group = this.groups.get(key);
14370
+ if (group === void 0 || this.disposed) return;
14371
+ if (group.scheduleTimer !== null) clearTimeout(group.scheduleTimer);
14372
+ group.scheduleTimer = null;
14373
+ const policy = this.groupPolicy(group);
14374
+ if (policy === void 0 || policy.push === "full") return;
14375
+ let earliest = Number.POSITIVE_INFINITY;
14376
+ if (policy.batch) earliest = group.dueAt;
14377
+ else for (const deviceId of group.devices) {
14378
+ const device = this.devices.get(deviceId);
14379
+ if (device !== void 0) earliest = Math.min(earliest, device.dueAt);
14380
+ }
14381
+ if (!Number.isFinite(earliest)) return;
14382
+ group.scheduleTimer = setTimeout(() => this.tick(key), Math.max(0, earliest - Date.now()));
14383
+ }
14384
+ tick(key) {
14385
+ const group = this.groups.get(key);
14386
+ if (group === void 0 || this.disposed) return;
14387
+ group.scheduleTimer = null;
14388
+ const policy = this.groupPolicy(group);
14389
+ if (policy?.batch === true) this.tickBatched(group, policy);
14390
+ else this.tickPerDevice(group);
14391
+ this.armSchedule(key);
14392
+ }
14393
+ /** One read of the whole group per interval, unless the last one still runs. */
14394
+ tickBatched(group, policy) {
14395
+ const now = Date.now();
14396
+ if (group.dueAt > now) return;
14397
+ group.dueAt = now + require_dist.effectiveRefreshIntervalMs(policy);
14398
+ const ids = [...group.devices].filter((id) => this.devices.has(id));
14399
+ const running = ids.filter((id) => (this.devices.get(id)?.scheduledInFlight ?? null) !== null);
14400
+ if (running.length > 0) {
14401
+ for (const deviceId of running) this.logSkippedTick(deviceId);
14402
+ return;
14403
+ }
14404
+ if (ids.length > 0) this.runScheduled(ids);
14405
+ }
14406
+ tickPerDevice(group) {
14407
+ const now = Date.now();
14408
+ const due = [];
14409
+ for (const deviceId of group.devices) {
14410
+ const device = this.devices.get(deviceId);
14411
+ if (device === void 0 || device.dueAt > now) continue;
14412
+ device.dueAt = now + require_dist.effectiveRefreshIntervalMs(device.entry.policy);
14413
+ if (device.inFlight !== null) {
14414
+ this.logSkippedTick(deviceId);
14415
+ continue;
14416
+ }
14417
+ due.push(deviceId);
14418
+ }
14419
+ for (const deviceId of due) this.runScheduled([deviceId]);
14420
+ }
14421
+ logSkippedTick(deviceId) {
14422
+ this.deps.logger.debug("state refresh skipped: a refresh is still in flight", { tags: { deviceId } });
14423
+ }
14424
+ /** A scheduled read, remembered on each device until it settles. */
14425
+ async runScheduled(deviceIds) {
14426
+ const run = this.runRefresh(deviceIds, "schedule");
14427
+ for (const deviceId of deviceIds) {
14428
+ const device = this.devices.get(deviceId);
14429
+ if (device !== void 0) device.scheduledInFlight = run;
14430
+ }
14431
+ await run;
14432
+ for (const deviceId of deviceIds) {
14433
+ const device = this.devices.get(deviceId);
14434
+ if (device !== void 0 && device.scheduledInFlight === run) device.scheduledInFlight = null;
14435
+ }
14436
+ }
14437
+ armBurst(deviceId, device) {
14438
+ if (!this.deps.holdsPending(deviceId)) return;
14439
+ const timers = [];
14440
+ let stopped = false;
14441
+ for (const offset of require_dist.COMMAND_BURST_OFFSETS_MS) timers.push(setTimeout(() => {
14442
+ if (stopped || this.disposed) return;
14443
+ if (!this.deps.holdsPending(deviceId)) {
14444
+ stopped = true;
14445
+ this.deps.logger.debug("state refresh burst stopped: the command is confirmed", { tags: { deviceId } });
14446
+ return;
14447
+ }
14448
+ if (device.inFlight !== null) {
14449
+ this.deps.logger.debug("state refresh burst skipped: a refresh is still in flight", { tags: { deviceId } });
14450
+ return;
14451
+ }
14452
+ this.runRefresh([deviceId], "burst");
14453
+ }, offset));
14454
+ device.burst = timers;
14455
+ }
14456
+ armPushWindow(deviceId, device) {
14457
+ const commandAt = device.lastCommandAt;
14458
+ device.pushWindow = setTimeout(() => {
14459
+ device.pushWindow = null;
14460
+ if (this.disposed) return;
14461
+ if (device.lastReportAt > commandAt && !this.deps.holdsPending(deviceId)) {
14462
+ this.deps.logger.debug("state refresh not needed: the push confirmed the command", { tags: { deviceId } });
14463
+ return;
14464
+ }
14465
+ this.deps.logger.debug("state refresh: no confirming push within the window", {
14466
+ tags: { deviceId },
14467
+ meta: { windowMs: require_dist.PUSH_CONFIRM_WINDOW_MS }
14468
+ });
14469
+ if (device.inFlight !== null) return;
14470
+ this.runRefresh([deviceId], "command");
14471
+ }, require_dist.PUSH_CONFIRM_WINDOW_MS);
14472
+ }
14473
+ cancelFollowUps(device) {
14474
+ for (const timer of device.burst) clearTimeout(timer);
14475
+ device.burst = [];
14476
+ if (device.pushWindow !== null) clearTimeout(device.pushWindow);
14477
+ device.pushWindow = null;
14478
+ }
14479
+ armHeartbeat(key) {
14480
+ const group = this.groups.get(key);
14481
+ if (group === void 0 || this.disposed) return;
14482
+ if (group.heartbeatTimer !== null) clearTimeout(group.heartbeatTimer);
14483
+ group.heartbeatTimer = null;
14484
+ const policy = this.groupPolicy(group);
14485
+ if (policy === void 0 || policy.push === "none" || policy.heartbeatMs === void 0) return;
14486
+ const heartbeatMs = policy.heartbeatMs;
14487
+ const wait = Math.max(0, group.lastReportAt + heartbeatMs - Date.now());
14488
+ group.heartbeatTimer = setTimeout(() => {
14489
+ group.heartbeatTimer = null;
14490
+ if (this.disposed) return;
14491
+ if (Date.now() - group.lastReportAt >= heartbeatMs) this.onSilence(key, heartbeatMs);
14492
+ else this.armHeartbeat(key);
14493
+ }, wait);
14494
+ }
14495
+ async onSilence(key, heartbeatMs) {
14496
+ const group = this.groups.get(key);
14497
+ if (group === void 0) return;
14498
+ group.lastReportAt = Date.now();
14499
+ for (const deviceId of group.devices) this.deps.logger.warn("state refresh: no push within the heartbeat, reading and resubscribing", {
14500
+ tags: { deviceId },
14501
+ meta: { heartbeatMs }
14502
+ });
14503
+ await this.refreshGroup(key, "schedule");
14504
+ const route = [...group.devices][0];
14505
+ if (route !== void 0) try {
14506
+ await this.deps.resubscribe(route);
14507
+ } catch (err) {
14508
+ this.deps.logger.warn("state refresh: resubscribe failed", {
14509
+ tags: { deviceId: route },
14510
+ meta: { error: errorMessage$1(err) }
14511
+ });
14512
+ }
14513
+ await this.refreshGroup(key, "schedule");
14514
+ this.armHeartbeat(key);
14515
+ }
14516
+ async refreshGroup(key, reason) {
14517
+ const group = this.groups.get(key);
14518
+ if (group === void 0) return;
14519
+ const ids = [...group.devices].filter((id) => this.devices.has(id));
14520
+ if (ids.length > 0) await this.refreshDevices(ids, reason);
14521
+ }
14522
+ /** One call for a batching integration, else one per device. */
14523
+ async refreshDevices(deviceIds, reason) {
14524
+ if (this.devices.get(deviceIds[0] ?? -1)?.entry.policy.batch === true) {
14525
+ await this.runRefresh(deviceIds, reason);
14526
+ return;
14527
+ }
14528
+ await Promise.all(deviceIds.map((id) => this.runRefresh([id], reason)));
14529
+ }
14530
+ /**
14531
+ * Read `deviceIds` once every read already queued on them ended — or, with
14532
+ * `waitBoundMs`, once that long passed (a debug line per device that was
14533
+ * still busy). The read becomes the devices' new tail.
14534
+ */
14535
+ async runRefresh(deviceIds, reason, waitBoundMs) {
14536
+ const route = deviceIds[0];
14537
+ if (route === void 0) return;
14538
+ const busy = [];
14539
+ const prior = [];
14540
+ for (const deviceId of deviceIds) {
14541
+ const tail = this.devices.get(deviceId)?.inFlight;
14542
+ if (tail === null || tail === void 0) continue;
14543
+ busy.push(deviceId);
14544
+ prior.push(tail);
14545
+ }
14546
+ const settled = this.afterPrior(prior, busy, waitBoundMs).then(() => this.deps.refresh(route, deviceIds, reason)).catch((err) => {
14547
+ for (const deviceId of deviceIds) this.deps.logger.warn("state refresh failed", {
14548
+ tags: { deviceId },
14549
+ meta: {
14550
+ reason,
14551
+ error: errorMessage$1(err)
14552
+ }
14553
+ });
14554
+ }).finally(() => {
14555
+ for (const deviceId of deviceIds) {
14556
+ const device = this.devices.get(deviceId);
14557
+ if (device !== void 0 && device.inFlight === settled) device.inFlight = null;
14558
+ }
14559
+ });
14560
+ for (const deviceId of deviceIds) {
14561
+ const device = this.devices.get(deviceId);
14562
+ if (device !== void 0) device.inFlight = settled;
14563
+ }
14564
+ await settled;
14565
+ }
14566
+ /** Resolves when every `prior` read ended, or after `waitBoundMs` (logged per busy device). */
14567
+ async afterPrior(prior, busy, waitBoundMs) {
14568
+ if (prior.length === 0) return;
14569
+ const all = Promise.all(prior).then(() => true);
14570
+ if (waitBoundMs === void 0) {
14571
+ await all;
14572
+ return;
14573
+ }
14574
+ let timer;
14575
+ const bound = new Promise((resolve) => {
14576
+ timer = setTimeout(() => resolve(false), waitBoundMs);
14577
+ });
14578
+ const ended = await Promise.race([all, bound]);
14579
+ if (timer !== void 0) clearTimeout(timer);
14580
+ if (ended) return;
14581
+ for (const deviceId of busy) this.deps.logger.debug("state refresh: stopped waiting for the read in flight", {
14582
+ tags: { deviceId },
14583
+ meta: { waitedMs: waitBoundMs }
14584
+ });
14585
+ }
14586
+ clearGroupTimers(group) {
14587
+ if (group.scheduleTimer !== null) clearTimeout(group.scheduleTimer);
14588
+ if (group.heartbeatTimer !== null) clearTimeout(group.heartbeatTimer);
14589
+ group.scheduleTimer = null;
14590
+ group.heartbeatTimer = null;
14591
+ }
14592
+ };
14593
+ //#endregion
14594
+ //#region src/builtins/device-manager/state-refresh-wiring.ts
14595
+ /** Start the scheduler; returns the stop. */
14596
+ function startStateRefresh(deps) {
14597
+ const scheduler = new StateRefreshScheduler({
14598
+ policies: deps.policies ?? getStateRefreshPolicyRegistry(),
14599
+ logger: deps.logger,
14600
+ holdsPending: (deviceId) => deps.mirror.isHoldingDevice(deviceId),
14601
+ refresh: deps.refresh,
14602
+ resubscribe: deps.resubscribe
14603
+ });
14604
+ deps.mirror.setReportTap((deviceId) => scheduler.onReport(deviceId));
14605
+ const uninstall = getCommandFollowUpRegistry().set(scheduler.onCommand);
14606
+ return () => {
14607
+ uninstall();
14608
+ deps.mirror.setReportTap(null);
14609
+ scheduler.dispose();
14610
+ };
14611
+ }
13427
14612
  var REDACTED = "***";
13428
14613
  var ROUTING_KEYS = new Set([
13429
14614
  "deviceId",
@@ -14344,6 +15529,7 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
14344
15529
  transitions = null;
14345
15530
  /** Unsubscribes the command hold (D1061). */
14346
15531
  stopCommandHolds = null;
15532
+ stopStateRefresh = null;
14347
15533
  /**
14348
15534
  * Removes the claimed-status overlay this addon installed on the capability
14349
15535
  * registry (D663, S3): `getStatus` of a claimed cap answers the mirror for
@@ -14670,6 +15856,23 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
14670
15856
  if (records === void 0) throw new Error("[device-manager] ctx.records is required on the hub");
14671
15857
  await records.declare(deviceManagerRecordKinds);
14672
15858
  const tombstones = DeviceTombstoneStore.of(records, this.ctx.logger.child("tombstones"));
15859
+ const identityLinksStore = IdentityLinksStore.of(records);
15860
+ await identityLinksStore.load();
15861
+ const identityLinks = new IdentityLinkReconciler({
15862
+ candidates: () => identityIndex.linkCandidates(),
15863
+ store: identityLinksStore,
15864
+ emit: (category, payload) => this.ctx.eventBus.emit({
15865
+ id: (0, node_crypto.randomUUID)(),
15866
+ timestamp: /* @__PURE__ */ new Date(),
15867
+ source: {
15868
+ type: "device",
15869
+ id: payload.bDeviceId
15870
+ },
15871
+ category,
15872
+ data: { ...payload }
15873
+ }),
15874
+ logger: this.ctx.logger.child("identity-links")
15875
+ });
14673
15876
  const discoveryProposals = new DiscoveryProposalService({
14674
15877
  store: DiscoveryProposalStore.of(records),
14675
15878
  orchestrator: this.discoveryDeps(),
@@ -14694,6 +15897,24 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
14694
15897
  mirror: stateMirror,
14695
15898
  logger: this.ctx.logger.child("command-holds")
14696
15899
  });
15900
+ this.stopStateRefresh = startStateRefresh({
15901
+ mirror: stateMirror,
15902
+ logger: this.ctx.logger.child("state-refresh"),
15903
+ refresh: async (deviceId, deviceIds, reason) => {
15904
+ const api = this.ctx.api;
15905
+ if (api === void 0) throw new Error("ctx.api not ready");
15906
+ await api.deviceStateRefresh.refresh.mutate({
15907
+ deviceId,
15908
+ deviceIds: [...deviceIds],
15909
+ reason
15910
+ });
15911
+ },
15912
+ resubscribe: async (deviceId) => {
15913
+ const api = this.ctx.api;
15914
+ if (api === void 0) throw new Error("ctx.api not ready");
15915
+ await api.deviceStateRefresh.resubscribe.mutate({ deviceId });
15916
+ }
15917
+ });
14697
15918
  this.transitions = startDeviceTransitions({
14698
15919
  mirror: stateMirror,
14699
15920
  logger: this.ctx.logger.child("transitions"),
@@ -14731,6 +15952,9 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
14731
15952
  const bootRows = await deviceRows.listAll();
14732
15953
  for (const row of bootRows) idToAddonId.set(row.meta.id, row.meta.addonId);
14733
15954
  identityIndex.seed(bootRows);
15955
+ for (const gone of await tombstones.listSince(0)) await identityLinks.removeDevice(gone.deviceId);
15956
+ identityIndex.onIdentityChanged(() => identityLinks.requestPass());
15957
+ identityLinks.requestPass();
14734
15958
  const stampIntegrationId$1 = (deviceId, integrationId) => stampIntegrationId(metaStore, this.ctx, deviceId, integrationId);
14735
15959
  const templates = this.makeTemplateActions();
14736
15960
  const pctx = {
@@ -14743,6 +15967,7 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
14743
15967
  removalFence: this.removalFence,
14744
15968
  removalCleanup: this.removalCleanup,
14745
15969
  tombstones,
15970
+ identityLinks,
14746
15971
  removalHooks: {
14747
15972
  api: this.ctx.api,
14748
15973
  logger: this.ctx.logger,
@@ -14817,6 +16042,11 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
14817
16042
  setDisplay: (input) => setDisplay(pctx, input),
14818
16043
  setIdentifiers: (input) => setIdentifiers(pctx, input),
14819
16044
  listIdentityCandidates: async () => identityIndex.candidates(),
16045
+ setAttachedIdentifiers: (input) => setAttachedIdentifiers(pctx, input),
16046
+ listIdentityLinks: async (input) => identityLinks.list(input?.deviceId),
16047
+ confirmIdentityLink: ({ linkId }) => identityLinks.confirm(linkId),
16048
+ dismissIdentityLink: ({ linkId }) => identityLinks.dismiss(linkId),
16049
+ unlinkIdentity: ({ linkId }) => identityLinks.unlink(linkId),
14820
16050
  getRoleDisplayDefaults: (input) => getRoleDisplayDefaults(pctx, input),
14821
16051
  setRoleDisplayDefaults: (input) => setRoleDisplayDefaults(pctx, input),
14822
16052
  applyInitialMeta: (input) => applyInitialMeta(pctx, input),
@@ -15092,6 +16322,8 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
15092
16322
  this.templateActions = null;
15093
16323
  await this.transitions?.stop();
15094
16324
  this.transitions = null;
16325
+ this.stopStateRefresh?.();
16326
+ this.stopStateRefresh = null;
15095
16327
  this.stopCommandHolds?.();
15096
16328
  this.stopCommandHolds = null;
15097
16329
  this.removalCleanupImpl?.dispose();
@@ -15108,22 +16340,35 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
15108
16340
  }
15109
16341
  };
15110
16342
  //#endregion
16343
+ exports.CommandFollowUpRegistry = CommandFollowUpRegistry;
15111
16344
  exports.CommandObserverRegistry = CommandObserverRegistry;
15112
16345
  exports.DeviceManagerAddon = DeviceManagerAddon;
15113
16346
  exports.default = DeviceManagerAddon;
15114
16347
  exports.IN_PROCESS_HOLD_SOURCE = IN_PROCESS_HOLD_SOURCE;
16348
+ exports.IN_PROCESS_REFRESH_SOURCE = IN_PROCESS_REFRESH_SOURCE;
16349
+ exports.STATE_REFRESH_CAP = STATE_REFRESH_CAP;
16350
+ exports.StateRefreshPolicyRegistry = StateRefreshPolicyRegistry;
16351
+ exports.__resetCommandFollowUpRegistryForTests = __resetCommandFollowUpRegistryForTests;
15115
16352
  exports.__resetCommandObserverRegistryForTests = __resetCommandObserverRegistryForTests;
16353
+ exports.__resetStateRefreshPolicyRegistryForTests = __resetStateRefreshPolicyRegistryForTests;
15116
16354
  exports.addonCommandActor = addonCommandActor;
15117
16355
  exports.childCommandHoldEntries = childCommandHoldEntries;
15118
16356
  exports.childHoldSource = childHoldSource;
16357
+ exports.childRefreshSource = childRefreshSource;
16358
+ exports.childStateRefreshEntries = childStateRefreshEntries;
15119
16359
  exports.commandActorFromContext = commandActorFromContext;
16360
+ exports.commandFollowUpTarget = commandFollowUpTarget;
15120
16361
  exports.commandObserverLink = commandObserverLink;
15121
16362
  exports.createDeviceSettingsStore = createDeviceSettingsStore;
16363
+ exports.deviceIdOfArgs = deviceIdOfArgs;
16364
+ exports.getCommandFollowUpRegistry = getCommandFollowUpRegistry;
15122
16365
  exports.getCommandHoldOverrideRegistry = getCommandHoldOverrideRegistry;
15123
16366
  exports.getCommandObserverRegistry = getCommandObserverRegistry;
16367
+ exports.getStateRefreshPolicyRegistry = getStateRefreshPolicyRegistry;
15124
16368
  exports.mergeAggregates = mergeAggregates;
15125
16369
  exports.observable = observable;
15126
16370
  exports.readDeviceOrThrow = readDeviceOrThrow;
15127
16371
  exports.reportCommand = reportCommand;
15128
16372
  exports.runObservedCommand = runObservedCommand;
15129
16373
  exports.setWrapperActive = setWrapperActive;
16374
+ exports.withCommandFollowUp = withCommandFollowUp;