@camstack/server 1.2.810 → 1.2.812

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 (116) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/api/trpc/cap-router-runtime.js +3 -0
  3. package/dist/api/trpc/generated-cap-mounts.js +3 -1
  4. package/dist/api/trpc/generated-cap-routers.js +1869 -1789
  5. package/dist/core/addon/hub-addon-api.js +8 -1
  6. package/dist/core/moleculer/moleculer.service.js +3 -0
  7. package/package.json +9 -42
  8. package/system/dist/addon-runner.js +4 -1
  9. package/system/dist/addon-runner.mjs +5 -2
  10. package/system/dist/{agent-https-B5cYxyQW.mjs → agent-https-CyEBY3RB.mjs} +1 -1
  11. package/system/dist/{agent-https-C0QE8tXs.js → agent-https-a3mE4PW4.js} +1 -1
  12. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  13. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  14. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  15. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  16. package/system/dist/builtins/alerts/alerts.addon.js +3 -101
  17. package/system/dist/builtins/alerts/alerts.addon.mjs +40 -134
  18. package/system/dist/builtins/autotrack/index.js +1 -1
  19. package/system/dist/builtins/autotrack/index.mjs +1 -1
  20. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  21. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  22. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  23. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  24. package/system/dist/builtins/camera-grid/index.js +1 -1
  25. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  26. package/system/dist/builtins/composer/composer.addon.js +6 -5
  27. package/system/dist/builtins/composer/composer.addon.mjs +6 -5
  28. package/system/dist/builtins/console-logging/index.js +1 -1
  29. package/system/dist/builtins/console-logging/index.mjs +1 -1
  30. package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +2 -0
  31. package/system/dist/builtins/core-blocks/core-blocks.addon.js +358 -32
  32. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +361 -35
  33. package/system/dist/builtins/core-blocks/hero-layout-service.d.ts +42 -0
  34. package/system/dist/builtins/core-blocks/remote-call-redirect.d.ts +1 -1
  35. package/system/dist/builtins/core-blocks/remote-service.d.ts +38 -0
  36. package/system/dist/builtins/device-history/device-history.addon.d.ts +5 -0
  37. package/system/dist/builtins/device-history/device-history.addon.js +357 -18
  38. package/system/dist/builtins/device-history/device-history.addon.mjs +357 -18
  39. package/system/dist/builtins/device-history/retention/retention.d.ts +14 -1
  40. package/system/dist/builtins/device-history/transitions/device-transitions-record-kinds.d.ts +14 -0
  41. package/system/dist/builtins/device-history/transitions/transitions-service.d.ts +80 -0
  42. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +2 -0
  43. package/system/dist/builtins/device-manager/device-manager.addon.js +712 -18
  44. package/system/dist/builtins/device-manager/device-manager.addon.mjs +780 -95
  45. package/system/dist/builtins/device-manager/device-state-mirror.d.ts +7 -0
  46. package/system/dist/builtins/device-manager/transitions/command-args.d.ts +4 -0
  47. package/system/dist/builtins/device-manager/transitions/transition-correlator.d.ts +68 -0
  48. package/system/dist/builtins/device-manager/transitions/transitions-sender.d.ts +37 -0
  49. package/system/dist/builtins/device-manager/transitions/transitions-wiring.d.ts +25 -0
  50. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  51. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  52. package/system/dist/builtins/keychain/index.js +4 -4
  53. package/system/dist/builtins/keychain/index.mjs +4 -4
  54. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  55. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  56. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  57. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  58. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  59. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  60. package/system/dist/builtins/loki-logging/index.js +1 -1
  61. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  62. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  63. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  64. package/system/dist/builtins/platform-probe/index.js +1 -1
  65. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  66. package/system/dist/builtins/record-entries/index.js +1 -1
  67. package/system/dist/builtins/record-entries/index.mjs +1 -1
  68. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  69. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  70. package/system/dist/builtins/snapshot/index.js +1 -1
  71. package/system/dist/builtins/snapshot/index.mjs +1 -1
  72. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  73. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  74. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  75. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  76. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  77. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  78. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  79. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  80. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  81. package/system/dist/builtins/system-config/system-config.addon.mjs +284 -284
  82. package/system/dist/builtins/winston-logging/index.js +1 -1
  83. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  84. package/system/dist/{capture-engine-DHvJXvuV.js → capture-engine-BO9mSlY-.js} +1 -1
  85. package/system/dist/{capture-engine-Ci4GwgjQ.mjs → capture-engine-ByF-6AFH.mjs} +1 -1
  86. package/system/dist/{composition-sources-CXJ0SzYJ.mjs → composition-sources-AziMFo7T.mjs} +1 -1
  87. package/system/dist/{composition-sources-B-WY9L7z.js → composition-sources-BMJUPUh2.js} +1 -1
  88. package/system/dist/{constants-DAuOjW5K.mjs → constants-CTikgsC_.mjs} +1 -1
  89. package/system/dist/{constants-DnJ2vuC7.js → constants-CjRlgRlu.js} +1 -1
  90. package/system/dist/{device-ca-D0HejZGK.mjs → device-ca-CNRlFqFC.mjs} +1 -1
  91. package/system/dist/{device-ca-BRpXm-B0.js → device-ca-Dxl6kVcJ.js} +1 -1
  92. package/system/dist/{dist-BLxWQm_m.mjs → dist-BPq13Y8j.mjs} +17392 -15506
  93. package/system/dist/{dist-DZQowBDF.js → dist-CkJnelZr.js} +17463 -15511
  94. package/system/dist/file-host-worker.js +1 -1
  95. package/system/dist/file-host-worker.mjs +1 -1
  96. package/system/dist/{hub-mdns-ciao-BJx5WmFx.mjs → hub-mdns-ciao-CrjItezp.mjs} +2 -2
  97. package/system/dist/{hub-mdns-ciao-ClSuN_QT.js → hub-mdns-ciao-Cx6yJBl9.js} +2 -2
  98. package/system/dist/index.js +67 -75
  99. package/system/dist/index.mjs +53 -68
  100. package/system/dist/kernel/cap-router-builder.d.ts +9 -0
  101. package/system/dist/kernel/command-observation.d.ts +76 -0
  102. package/system/dist/kernel/index.d.ts +2 -0
  103. package/system/dist/kernel/transport/child-cap-protocol.d.ts +10 -1
  104. package/system/dist/kernel/transport/local-child-registry.d.ts +15 -0
  105. package/system/dist/{legacy-integration-rows-door-BiNKE2zW.js → legacy-integration-rows-door-CKM-LxvL.js} +1 -1
  106. package/system/dist/{legacy-integration-rows-door-CN84_M7B.mjs → legacy-integration-rows-door-Dxcqwc-w.mjs} +1 -1
  107. package/system/dist/log-redactor-BhIEMaG9.js +149 -0
  108. package/system/dist/log-redactor-XLDrPzOi.mjs +120 -0
  109. package/system/dist/logging/log-redactor.d.ts +2 -0
  110. package/system/dist/{restore-archive-Co1yYMV3.js → restore-archive-BQWOdGAB.js} +1 -1
  111. package/system/dist/{restore-archive-gLW5oc1w.mjs → restore-archive-r3zTdLKr.mjs} +82 -82
  112. package/system/dist/{retention-BNONb5X_.js → retention-BcOSL6b9.js} +33 -2
  113. package/system/dist/{retention-B9l9TnGE.mjs → retention-CUOVI1p7.mjs} +33 -2
  114. package/system/dist/{wal-maintenance-BQaIM_cY.js → wal-maintenance-CiCgL4Hp.js} +0 -0
  115. package/system/dist/{wal-maintenance-Zji_8sLK.mjs → wal-maintenance-zJ4-ORo6.mjs} +0 -0
  116. package/system/package.json +7 -1
@@ -3,8 +3,9 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-DZQowBDF.js");
6
+ const require_dist = require("../../dist-CkJnelZr.js");
7
7
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
8
+ const require_log_redactor = require("../../log-redactor-BhIEMaG9.js");
8
9
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
9
10
  const require_prefix_walk = require("../../prefix-walk-Dv6MLZlM.js");
10
11
  const require_retired_settings_keys = require("../../retired-settings-keys-C8nOOr5H.js");
@@ -12,6 +13,7 @@ const require_dns_wire = require("../../dns-wire-B1BvF9Ao.js");
12
13
  let zod = require("zod");
13
14
  let node_crypto = require("node:crypto");
14
15
  let _camstack_types_node = require("@camstack/types/node");
16
+ let _camstack_types_addon = require("@camstack/types/addon");
15
17
  //#region src/builtins/device-manager/adoption-job-engine.ts
16
18
  /** How many finished jobs are kept per (addonId, integrationId). */
17
19
  var JOB_HISTORY = 20;
@@ -1100,11 +1102,11 @@ function mergeAggregates(parts) {
1100
1102
  * per-row path (`connection.password`, `rows[].pin`) is not mapped onto a form
1101
1103
  * field and keeps the driver's hydration.
1102
1104
  */
1103
- function isRecord$2(value) {
1105
+ function isRecord$3(value) {
1104
1106
  return typeof value === "object" && value !== null && !Array.isArray(value);
1105
1107
  }
1106
1108
  function isConfigFieldWithValue(field) {
1107
- if (!isRecord$2(field)) return false;
1109
+ if (!isRecord$3(field)) return false;
1108
1110
  return typeof field.type === "string" && typeof field.key === "string" && "value" in field;
1109
1111
  }
1110
1112
  /** The declared paths that name a top-level config key. */
@@ -1112,7 +1114,7 @@ function topLevelKeys(paths) {
1112
1114
  return new Set(paths.filter((p) => p.length > 0 && !p.includes(".") && !p.includes("[")));
1113
1115
  }
1114
1116
  function viewField(field, stored, declared) {
1115
- if (!isRecord$2(field)) return field;
1117
+ if (!isRecord$3(field)) return field;
1116
1118
  const nested = field["fields"];
1117
1119
  if (Array.isArray(nested)) return {
1118
1120
  ...field,
@@ -1121,7 +1123,7 @@ function viewField(field, stored, declared) {
1121
1123
  const tabs = field["tabs"];
1122
1124
  if (Array.isArray(tabs)) return {
1123
1125
  ...field,
1124
- tabs: tabs.map((tab) => isRecord$2(tab) && Array.isArray(tab["fields"]) ? {
1126
+ tabs: tabs.map((tab) => isRecord$3(tab) && Array.isArray(tab["fields"]) ? {
1125
1127
  ...tab,
1126
1128
  fields: tab["fields"].map((f) => viewField(f, stored, declared))
1127
1129
  } : tab)
@@ -1230,7 +1232,7 @@ function isDeclaredCollectionCap(capName) {
1230
1232
  function isDeclaredNonWrapperCap(capName) {
1231
1233
  return DECLARED_NON_WRAPPER_CAPS.has(capName);
1232
1234
  }
1233
- function isRecord$1(value) {
1235
+ function isRecord$2(value) {
1234
1236
  return typeof value === "object" && value !== null && !Array.isArray(value);
1235
1237
  }
1236
1238
  /** A persisted activation of a wrapper on a cap that has none (see module docblock). */
@@ -1273,12 +1275,12 @@ var StaleWrapperActivations = class {
1273
1275
  if (this.checked) return;
1274
1276
  this.checked = true;
1275
1277
  const devices = store.deviceBindings;
1276
- if (!isRecord$1(devices)) return;
1278
+ if (!isRecord$2(devices)) return;
1277
1279
  for (const [deviceKey, perDevice] of Object.entries(devices)) {
1278
1280
  const deviceId = Number(deviceKey);
1279
- if (!Number.isInteger(deviceId) || !isRecord$1(perDevice)) continue;
1281
+ if (!Number.isInteger(deviceId) || !isRecord$2(perDevice)) continue;
1280
1282
  for (const [capName, row] of Object.entries(perDevice)) {
1281
- const wrapperAddonId = isRecord$1(row) ? row["wrapperAddonId"] : void 0;
1283
+ const wrapperAddonId = isRecord$2(row) ? row["wrapperAddonId"] : void 0;
1282
1284
  if (typeof wrapperAddonId === "string" && isDeclaredNonWrapperCap(capName)) this.report(deviceId, capName, wrapperAddonId);
1283
1285
  }
1284
1286
  }
@@ -4658,7 +4660,7 @@ async function setWrapperActive(deps, input) {
4658
4660
  }
4659
4661
  });
4660
4662
  }
4661
- function isRecord(value) {
4663
+ function isRecord$1(value) {
4662
4664
  return typeof value === "object" && value !== null && !Array.isArray(value);
4663
4665
  }
4664
4666
  /** The key of this addon's store that holds every wrapper activation. */
@@ -4698,19 +4700,19 @@ async function readWrapperActivation(deps, query) {
4698
4700
  error: "the store holds no deviceBindings row — an empty snapshot is not evidence of an unbind"
4699
4701
  };
4700
4702
  const deviceBindings = read.value;
4701
- if (!isRecord(deviceBindings)) return {
4703
+ if (!isRecord$1(deviceBindings)) return {
4702
4704
  kind: "failed",
4703
4705
  error: "stored deviceBindings is not a map"
4704
4706
  };
4705
4707
  const perDevice = deviceBindings[String(query.deviceId)];
4706
4708
  if (perDevice === void 0) return { kind: "missing" };
4707
- if (!isRecord(perDevice)) return {
4709
+ if (!isRecord$1(perDevice)) return {
4708
4710
  kind: "failed",
4709
4711
  error: `stored bindings of device ${query.deviceId} are not a map`
4710
4712
  };
4711
4713
  const activation = perDevice[query.capName];
4712
4714
  if (activation === void 0) return { kind: "missing" };
4713
- if (!isRecord(activation)) return {
4715
+ if (!isRecord$1(activation)) return {
4714
4716
  kind: "failed",
4715
4717
  error: `stored "${query.capName}" activation is not a record`
4716
4718
  };
@@ -8849,7 +8851,7 @@ function deviceRowBackendOf(client) {
8849
8851
  count: (input) => client.count.query(input)
8850
8852
  };
8851
8853
  }
8852
- function isPlainObject(value) {
8854
+ function isPlainObject$1(value) {
8853
8855
  return value !== null && typeof value === "object" && !Array.isArray(value);
8854
8856
  }
8855
8857
  function readString(value) {
@@ -8916,9 +8918,9 @@ function decodeDeviceRow(data) {
8916
8918
  ...primaryChildEntityId !== void 0 ? { primaryChildEntityId } : {},
8917
8919
  ...isChildLayout(rawChildLayout) ? { childLayout: rawChildLayout } : {},
8918
8920
  ...role !== void 0 ? { role } : {},
8919
- ...isPlainObject(rawDisplay) ? { display: toDisplayOverride(rawDisplay) } : {}
8921
+ ...isPlainObject$1(rawDisplay) ? { display: toDisplayOverride(rawDisplay) } : {}
8920
8922
  },
8921
- metadata: isPlainObject(rawMetadata) ? rawMetadata : null,
8923
+ metadata: isPlainObject$1(rawMetadata) ? rawMetadata : null,
8922
8924
  registered: readBoolean(data["registered"]) ?? false
8923
8925
  };
8924
8926
  }
@@ -9037,7 +9039,7 @@ var DeviceRowStore = class {
9037
9039
  collection: DEVICE_ROWS_COLLECTION,
9038
9040
  key: String(deviceId)
9039
9041
  });
9040
- if (!isPlainObject(raw)) return null;
9042
+ if (!isPlainObject$1(raw)) return null;
9041
9043
  const decoded = decodeDeviceRow(raw);
9042
9044
  if (decoded === null) {
9043
9045
  this.logger.warn("device row skipped — identity fields missing", { tags: { deviceId } });
@@ -10119,6 +10121,7 @@ function errorMessage$1(err) {
10119
10121
  var DeviceStateMirror = class {
10120
10122
  ctx;
10121
10123
  policyFor;
10124
+ transitionTap = null;
10122
10125
  /**
10123
10126
  * Hub-side mirror of every device's cap-keyed NATIVE runtime state — what the
10124
10127
  * provider wrote. Key: deviceId. Value: per-cap slice map. Empty by default —
@@ -10164,6 +10167,14 @@ var DeviceStateMirror = class {
10164
10167
  readRowFirst: (deviceId, settings) => this.ensureRowRead(deviceId, settings)
10165
10168
  });
10166
10169
  }
10170
+ /** Set once by the device-manager: told, after the mirror stored it, of every native slice that actually changed (D1022). */
10171
+ setTransitionTap(tap) {
10172
+ this.transitionTap = tap;
10173
+ }
10174
+ /** The native slice the mirror holds for `capName`, as a read-only view. */
10175
+ currentSlice(deviceId, capName) {
10176
+ return this.stateMirror.get(deviceId)?.get(capName);
10177
+ }
10167
10178
  /**
10168
10179
  * Single-cap mirror update — diff against the current mirror,
10169
10180
  * persist the new slice in-memory, emit `DeviceStateChanged` for
@@ -10188,6 +10199,7 @@ var DeviceStateMirror = class {
10188
10199
  const prior = perCap.get(capName);
10189
10200
  if (prior && shallowEqual(prior, slice)) return false;
10190
10201
  perCap.set(capName, { ...slice });
10202
+ this.transitionTap?.(deviceId, capName, prior, slice);
10191
10203
  const claim = this.claims.claim(deviceId, capName);
10192
10204
  if (claim) {
10193
10205
  if (claim.mode === "replace") this.emitNativeShadow(deviceId, capName, { ...slice });
@@ -10732,6 +10744,663 @@ var DeviceStateMirror = class {
10732
10744
  }
10733
10745
  };
10734
10746
  //#endregion
10747
+ //#region ../../node_modules/@trpc/server/dist/observable-UMO3vUa_.mjs
10748
+ /** @public */
10749
+ function observable(subscribe) {
10750
+ const self = {
10751
+ subscribe(observer) {
10752
+ let teardownRef = null;
10753
+ let isDone = false;
10754
+ let unsubscribed = false;
10755
+ let teardownImmediately = false;
10756
+ function unsubscribe() {
10757
+ if (teardownRef === null) {
10758
+ teardownImmediately = true;
10759
+ return;
10760
+ }
10761
+ if (unsubscribed) return;
10762
+ unsubscribed = true;
10763
+ if (typeof teardownRef === "function") teardownRef();
10764
+ else if (teardownRef) teardownRef.unsubscribe();
10765
+ }
10766
+ teardownRef = subscribe({
10767
+ next(value) {
10768
+ var _observer$next;
10769
+ if (isDone) return;
10770
+ (_observer$next = observer.next) === null || _observer$next === void 0 || _observer$next.call(observer, value);
10771
+ },
10772
+ error(err) {
10773
+ var _observer$error;
10774
+ if (isDone) return;
10775
+ isDone = true;
10776
+ (_observer$error = observer.error) === null || _observer$error === void 0 || _observer$error.call(observer, err);
10777
+ unsubscribe();
10778
+ },
10779
+ complete() {
10780
+ var _observer$complete;
10781
+ if (isDone) return;
10782
+ isDone = true;
10783
+ (_observer$complete = observer.complete) === null || _observer$complete === void 0 || _observer$complete.call(observer);
10784
+ unsubscribe();
10785
+ }
10786
+ });
10787
+ if (teardownImmediately) unsubscribe();
10788
+ return { unsubscribe };
10789
+ },
10790
+ pipe(...operations) {
10791
+ return operations.reduce(pipeReducer, self);
10792
+ }
10793
+ };
10794
+ return self;
10795
+ }
10796
+ function pipeReducer(prev, fn) {
10797
+ return fn(prev);
10798
+ }
10799
+ //#endregion
10800
+ //#region src/kernel/command-observation.ts
10801
+ /** Fan-out of command observations to the subscribers of this process. */
10802
+ var CommandObserverRegistry = class {
10803
+ observers = /* @__PURE__ */ new Set();
10804
+ subscribe(observer) {
10805
+ this.observers.add(observer);
10806
+ return () => {
10807
+ this.observers.delete(observer);
10808
+ };
10809
+ }
10810
+ /** How many observers are subscribed (a node that audits nothing has none). */
10811
+ observerCount() {
10812
+ return this.observers.size;
10813
+ }
10814
+ observe(obs) {
10815
+ for (const observer of this.observers) try {
10816
+ observer(obs);
10817
+ } catch {}
10818
+ }
10819
+ };
10820
+ var registry;
10821
+ /** The process-wide registry. */
10822
+ function getCommandObserverRegistry() {
10823
+ registry ??= new CommandObserverRegistry();
10824
+ return registry;
10825
+ }
10826
+ /** Test seam: forget every subscriber. */
10827
+ function __resetCommandObserverRegistryForTests() {
10828
+ registry = void 0;
10829
+ }
10830
+ function isRecord(value) {
10831
+ return value !== null && typeof value === "object" && !Array.isArray(value);
10832
+ }
10833
+ /**
10834
+ * Build the observation for a call, or `null` when it is not a device
10835
+ * command: not a vocabulary action, or its arguments name no device.
10836
+ */
10837
+ function buildCommandObservation(call, at) {
10838
+ if (!(0, _camstack_types_addon.isCommand)(call.capName, call.method)) return null;
10839
+ if (!isRecord(call.args)) return null;
10840
+ const deviceId = call.args["deviceId"];
10841
+ if (typeof deviceId !== "number" || !Number.isInteger(deviceId)) return null;
10842
+ return {
10843
+ deviceId,
10844
+ capName: call.capName,
10845
+ method: call.method,
10846
+ args: call.args,
10847
+ actor: call.actor,
10848
+ at,
10849
+ ...call.outcome !== void 0 ? { outcome: call.outcome } : {}
10850
+ };
10851
+ }
10852
+ /** Report a call to `sink` when it is a device command. Never throws. */
10853
+ function reportCommand(sink, call, now = Date.now) {
10854
+ if (sink === void 0) return;
10855
+ try {
10856
+ const obs = buildCommandObservation(call, now());
10857
+ if (obs !== null) sink(obs);
10858
+ } catch {}
10859
+ }
10860
+ /**
10861
+ * The actor of a command an ADDON issued. The addon id is the transport stamp.
10862
+ * An origin claim adds the detail of why (an action run, a scheduler); it never
10863
+ * changes who the caller is.
10864
+ */
10865
+ function addonCommandActor(addonId, origin, nodeId) {
10866
+ if (origin === void 0) return {
10867
+ kind: "addon",
10868
+ addonId,
10869
+ ...nodeId !== void 0 ? { nodeId } : {}
10870
+ };
10871
+ if (origin.kind === "action") return {
10872
+ kind: "action",
10873
+ addonId,
10874
+ actionId: origin.actionId,
10875
+ runId: origin.runId,
10876
+ ...origin.automationId !== void 0 ? { automationId: origin.automationId } : {}
10877
+ };
10878
+ return {
10879
+ kind: "scheduler",
10880
+ addonId,
10881
+ schedulerId: origin.schedulerId
10882
+ };
10883
+ }
10884
+ function deferred() {
10885
+ let resolve = () => void 0;
10886
+ let reject = () => void 0;
10887
+ return {
10888
+ promise: new Promise((res, rej) => {
10889
+ resolve = () => res();
10890
+ reject = rej;
10891
+ }),
10892
+ resolve,
10893
+ reject
10894
+ };
10895
+ }
10896
+ function kebab(name) {
10897
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
10898
+ }
10899
+ /**
10900
+ * A tRPC link for an in-process hub addon's `ctx.api`: it reports the addon's
10901
+ * device commands (the actor is the addon the client belongs to, with the origin
10902
+ * claim of the call) and passes every call through untouched.
10903
+ */
10904
+ function commandObserverLink(options) {
10905
+ return () => ({ op, next }) => {
10906
+ if (op.type !== "mutation") return next(op);
10907
+ const dot = op.path.indexOf(".");
10908
+ if (dot < 0) return next(op);
10909
+ const capName = kebab(op.path.slice(0, dot));
10910
+ const method = op.path.slice(dot + 1);
10911
+ if (!(0, _camstack_types_addon.isCommand)(capName, method)) return next(op);
10912
+ const downstream = next(op);
10913
+ return observable((observer) => {
10914
+ const settled = deferred();
10915
+ const outcome = settled.promise;
10916
+ outcome.catch(() => void 0);
10917
+ reportCommand(options.sink, {
10918
+ capName,
10919
+ method,
10920
+ args: op.input,
10921
+ actor: addonCommandActor(options.callerAddonId, (0, _camstack_types_addon.readCommandOrigin)(op.context)),
10922
+ outcome
10923
+ });
10924
+ const sub = downstream.subscribe({
10925
+ next: (value) => observer.next(value),
10926
+ error: (err) => {
10927
+ settled.reject(err);
10928
+ observer.error(err);
10929
+ },
10930
+ complete: () => {
10931
+ settled.resolve();
10932
+ observer.complete();
10933
+ }
10934
+ });
10935
+ return () => sub.unsubscribe();
10936
+ });
10937
+ };
10938
+ }
10939
+ function credentialOf(user) {
10940
+ const tag = Reflect.get(user, "auditTag");
10941
+ if (tag === "session" || tag === "token" || tag === "integration") return tag;
10942
+ return Reflect.get(user, "isApiKey") === true ? "token" : "session";
10943
+ }
10944
+ /**
10945
+ * Who a hub tRPC call is from, read from the request context by narrowing (the
10946
+ * kernel cannot import the server's context type). A context with no HTTP
10947
+ * request behind it is a mesh peer: a node. Anything without a principal is
10948
+ * unknown (`null`) and the call is not reported with a made-up actor.
10949
+ */
10950
+ function commandActorFromContext(ctx) {
10951
+ if (ctx === null || typeof ctx !== "object") return null;
10952
+ const user = Reflect.get(ctx, "user");
10953
+ if (user === null || typeof user !== "object") return null;
10954
+ const id = Reflect.get(user, "id");
10955
+ if (typeof id !== "string" || id.length === 0) return null;
10956
+ if (Reflect.get(ctx, "req") === void 0) return {
10957
+ kind: "node",
10958
+ nodeId: id
10959
+ };
10960
+ const username = Reflect.get(user, "username");
10961
+ const credentialId = Reflect.get(user, "credentialId");
10962
+ return {
10963
+ kind: "user",
10964
+ userId: id,
10965
+ username: typeof username === "string" ? username : id,
10966
+ credential: credentialOf(user),
10967
+ ...typeof credentialId === "string" ? { credentialId } : {}
10968
+ };
10969
+ }
10970
+ /**
10971
+ * Report a command BEFORE it runs, with an outcome that settles when the call
10972
+ * does: a provider that writes its slice synchronously must find the command
10973
+ * already pending. `call` is invoked here; its result (or throw) is returned
10974
+ * untouched.
10975
+ */
10976
+ function runObservedCommand(sink, facts, call) {
10977
+ if (sink === void 0 || !(0, _camstack_types_addon.isCommand)(facts.capName, facts.method)) return call();
10978
+ const settled = deferred();
10979
+ settled.promise.catch(() => void 0);
10980
+ reportCommand(sink, {
10981
+ ...facts,
10982
+ outcome: settled.promise
10983
+ });
10984
+ try {
10985
+ const result = call();
10986
+ Promise.resolve(result).then(() => settled.resolve(), settled.reject);
10987
+ return result;
10988
+ } catch (err) {
10989
+ settled.reject(err);
10990
+ throw err;
10991
+ }
10992
+ }
10993
+ var REDACTED = "***";
10994
+ var ROUTING_KEYS = new Set([
10995
+ "deviceId",
10996
+ "caller",
10997
+ "nodeId"
10998
+ ]);
10999
+ /** `rows[].token` -> key rows, each, key token. `applianceSecrets{}` -> key, values. */
11000
+ function parsePath(path) {
11001
+ const tokens = [];
11002
+ for (const m of path.matchAll(/\[\]|\{\}|[^.[\]{}]+/g)) {
11003
+ const t = m[0];
11004
+ tokens.push(t === "[]" ? { kind: "each" } : t === "{}" ? { kind: "values" } : {
11005
+ kind: "key",
11006
+ name: t
11007
+ });
11008
+ }
11009
+ return tokens;
11010
+ }
11011
+ function isPlainObject(value) {
11012
+ return value !== null && typeof value === "object" && !Array.isArray(value);
11013
+ }
11014
+ /** Replace what `tokens` reaches inside `value`; an object or array declared secret goes whole. */
11015
+ function redactAt(value, tokens) {
11016
+ const [head, ...rest] = tokens;
11017
+ if (head === void 0) return REDACTED;
11018
+ if (head.kind === "each") return Array.isArray(value) ? value.map((item) => redactAt(item, rest)) : value;
11019
+ if (!isPlainObject(value)) return value;
11020
+ if (head.kind === "values") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redactAt(v, rest)]));
11021
+ if (!Object.hasOwn(value, head.name)) return value;
11022
+ return {
11023
+ ...value,
11024
+ [head.name]: redactAt(value[head.name], rest)
11025
+ };
11026
+ }
11027
+ var WORD_NET_MAX_DEPTH = 8;
11028
+ /** The key-name net for values of ANY type, to a bounded depth. */
11029
+ function redactSecretKeys(value, depth) {
11030
+ if (depth >= WORD_NET_MAX_DEPTH) return value;
11031
+ if (Array.isArray(value)) return value.map((item) => redactSecretKeys(item, depth + 1));
11032
+ if (!isPlainObject(value)) return value;
11033
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, v !== null && v !== void 0 && require_log_redactor.isSecretArgumentKey(k) ? REDACTED : redactSecretKeys(v, depth + 1)]));
11034
+ }
11035
+ function createCommandArgsPreparer(inputFor) {
11036
+ const secretPaths = /* @__PURE__ */ new Map();
11037
+ const secretPathsOf = (capName, method) => {
11038
+ const id = `${capName}|${method}`;
11039
+ const known = secretPaths.get(id);
11040
+ if (known !== void 0) return known;
11041
+ const schema = inputFor(capName, method);
11042
+ const paths = schema === void 0 ? [] : require_dist.collectZodSecretPaths(schema).map(parsePath);
11043
+ secretPaths.set(id, paths);
11044
+ return paths;
11045
+ };
11046
+ return (capName, method, args) => {
11047
+ const kept = {};
11048
+ for (const [key, value] of Object.entries(args)) if (!ROUTING_KEYS.has(key)) kept[key] = value;
11049
+ let bag = kept;
11050
+ for (const path of secretPathsOf(capName, method)) bag = redactAt(bag, path);
11051
+ const named = redactSecretKeys(bag, 0);
11052
+ const out = isPlainObject(named) ? require_log_redactor.redactLogMeta(named) : {};
11053
+ if (JSON.stringify(out).length > 1024) return { _truncated: true };
11054
+ return isPlainObject(out) ? out : {};
11055
+ };
11056
+ }
11057
+ //#endregion
11058
+ //#region src/builtins/device-manager/transitions/transition-correlator.ts
11059
+ /**
11060
+ * The correlator of the device transition audit (D1022).
11061
+ *
11062
+ * A command (what the kernel saw leave its caller) and a slice change (what the
11063
+ * hub mirror saw land) are two facts about one event. This module pairs them:
11064
+ * a change of an audited field is attributed to the newest pending command whose
11065
+ * effect names that field and value, else to a command with no effect (toggle,
11066
+ * press), else to the device itself. A command whose target already held is
11067
+ * `already`; one that produced nothing inside its window is `unconfirmed`; one
11068
+ * the caller saw throw is `failed`.
11069
+ *
11070
+ * Pure and clock-injected. It reads memory only (D49): the pending ring and the
11071
+ * mirror's current slice. Nothing here does I/O, so a state write never waits on
11072
+ * the audit; what it produces is handed to `emit`, whose queue is bounded.
11073
+ */
11074
+ /** How long a command waits for the change it should cause. */
11075
+ var COMMAND_MATCH_WINDOW_MS = 3e4;
11076
+ /** Longest error text a row keeps. */
11077
+ var ERROR_MAX_CHARS = 300;
11078
+ function sameValue(a, b) {
11079
+ if (Object.is(a, b)) return true;
11080
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
11081
+ return JSON.stringify(a) === JSON.stringify(b);
11082
+ }
11083
+ /** A status value in the shape a transition stores: unknown is `null` (D393), an array is wrapped. */
11084
+ function toTransitionValue(value) {
11085
+ if (value === void 0 || value === null) return null;
11086
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
11087
+ if (Array.isArray(value)) return { items: value };
11088
+ if (typeof value === "object") return Object.fromEntries(Object.entries(value));
11089
+ return String(value);
11090
+ }
11091
+ var TransitionCorrelator = class {
11092
+ deps;
11093
+ pending = /* @__PURE__ */ new Map();
11094
+ seq = 0;
11095
+ deviceRows = /* @__PURE__ */ new Map();
11096
+ constructor(deps) {
11097
+ this.deps = deps;
11098
+ }
11099
+ /** A command left its caller. */
11100
+ recordCommand(obs) {
11101
+ const effect = require_dist.commandEffect(obs.capName, obs.method, obs.args);
11102
+ const current = this.deps.currentSlice(obs.deviceId, obs.capName);
11103
+ const fromAtCommand = effect === null ? null : toTransitionValue(current?.[effect.field]);
11104
+ const entry = {
11105
+ commandId: this.nextCommandId(obs),
11106
+ obs,
11107
+ effect,
11108
+ expiresAt: obs.at + COMMAND_MATCH_WINDOW_MS,
11109
+ fromAtCommand,
11110
+ settled: false
11111
+ };
11112
+ if (effect !== null && current !== void 0 && Object.hasOwn(current, effect.field) && sameValue(current[effect.field], effect.value)) {
11113
+ entry.settled = true;
11114
+ this.emit(entry, "already", effect.field, fromAtCommand, toTransitionValue(effect.value), null);
11115
+ return;
11116
+ }
11117
+ const key = this.keyOf(obs.deviceId, obs.capName);
11118
+ const ring = this.pending.get(key) ?? [];
11119
+ ring.push(entry);
11120
+ while (ring.length > 8) {
11121
+ const oldest = ring.shift();
11122
+ if (oldest !== void 0) this.expire(oldest);
11123
+ }
11124
+ this.pending.set(key, ring);
11125
+ obs.outcome?.catch((err) => this.fail(entry, err));
11126
+ }
11127
+ /** The mirror stored a new native slice for `capName` (the previous one, if any, is `prior`). */
11128
+ onSliceChange(deviceId, capName, prior, slice) {
11129
+ const fields = require_dist.auditedFields(capName);
11130
+ if (fields.size === 0) return;
11131
+ const now = this.deps.now();
11132
+ let claimed;
11133
+ for (const field of fields) {
11134
+ const hadBefore = prior !== void 0 && Object.hasOwn(prior, field);
11135
+ const has = Object.hasOwn(slice, field);
11136
+ if (!hadBefore && !has) continue;
11137
+ const before = hadBefore ? prior[field] : void 0;
11138
+ const after = has ? slice[field] : void 0;
11139
+ if (sameValue(before, after)) continue;
11140
+ claimed = this.attribute(deviceId, capName, field, toTransitionValue(before), toTransitionValue(after), now, claimed, prior === void 0);
11141
+ }
11142
+ }
11143
+ /** Expire every pending command past its window. Driven by the sender's tick. */
11144
+ sweep() {
11145
+ const now = this.deps.now();
11146
+ this.releaseDeviceRows(now);
11147
+ for (const [key, ring] of this.pending) {
11148
+ const live = [];
11149
+ for (const entry of ring) {
11150
+ if (entry.settled) continue;
11151
+ if (entry.expiresAt <= now) this.expire(entry);
11152
+ else live.push(entry);
11153
+ }
11154
+ if (live.length === 0) this.pending.delete(key);
11155
+ else this.pending.set(key, live);
11156
+ }
11157
+ }
11158
+ /** Commands still waiting, for a status read. */
11159
+ pendingCount() {
11160
+ let n = 0;
11161
+ for (const ring of this.pending.values()) n += ring.filter((e) => !e.settled).length;
11162
+ return n;
11163
+ }
11164
+ /** Forget a removed device's pending commands. */
11165
+ forgetDevice(deviceId) {
11166
+ const prefix = `${deviceId}|`;
11167
+ for (const key of [...this.deviceRows.keys()]) if (key.startsWith(prefix)) this.deviceRows.delete(key);
11168
+ for (const key of [...this.pending.keys()]) if (key.startsWith(prefix)) this.pending.delete(key);
11169
+ }
11170
+ attribute(deviceId, capName, field, from, to, now, claimedByThisWrite, firstSlice) {
11171
+ const key = this.keyOf(deviceId, capName);
11172
+ const ring = this.pending.get(key);
11173
+ const live = (ring ?? []).filter((e) => !e.settled && e.expiresAt > now);
11174
+ const matched = [...live].reverse().find((e) => e.effect !== null && e.effect.field === field && sameValue(e.effect.value, to)) ?? claimedByThisWrite ?? [...live].reverse().find((e) => e.effect === null);
11175
+ if (matched === void 0) {
11176
+ if (firstSlice) return void 0;
11177
+ this.emitDevice(deviceId, capName, field, from, to, now);
11178
+ return;
11179
+ }
11180
+ matched.settled = true;
11181
+ this.emit(matched, "confirmed", field, from, to, now - matched.obs.at);
11182
+ if (ring !== void 0) {
11183
+ const rest = ring.filter((e) => !e.settled);
11184
+ if (rest.length === 0) this.pending.delete(key);
11185
+ else this.pending.set(key, rest);
11186
+ }
11187
+ return matched;
11188
+ }
11189
+ expire(entry) {
11190
+ if (entry.settled) return;
11191
+ entry.settled = true;
11192
+ const field = entry.effect?.field ?? "*";
11193
+ this.emit(entry, "unconfirmed", field, entry.fromAtCommand, entry.fromAtCommand, null);
11194
+ }
11195
+ fail(entry, err) {
11196
+ if (entry.settled) return;
11197
+ entry.settled = true;
11198
+ const message = err instanceof Error ? err.message : String(err);
11199
+ const field = entry.effect?.field ?? "*";
11200
+ this.emit(entry, "failed", field, entry.fromAtCommand, entry.fromAtCommand, null, message);
11201
+ }
11202
+ emit(entry, outcome, field, from, to, matchedAfterMs, error) {
11203
+ const { obs } = entry;
11204
+ const at = this.deps.now();
11205
+ this.deps.emit({
11206
+ id: this.nextId(obs.deviceId, at),
11207
+ deviceId: obs.deviceId,
11208
+ at,
11209
+ capName: obs.capName,
11210
+ field,
11211
+ from,
11212
+ to,
11213
+ outcome,
11214
+ actor: obs.actor,
11215
+ command: {
11216
+ commandId: entry.commandId,
11217
+ method: obs.method,
11218
+ args: this.deps.prepareArgs(obs.capName, obs.method, obs.args),
11219
+ requestedAt: obs.at,
11220
+ matchedAfterMs,
11221
+ ...error !== void 0 ? { error: require_log_redactor.redactLogText(error).slice(0, ERROR_MAX_CHARS) } : {}
11222
+ }
11223
+ });
11224
+ }
11225
+ /** A change nobody asked for, bounded per field (see {@link DEVICE_ROW_WINDOW_MS}). */
11226
+ emitDevice(deviceId, capName, field, from, to, at) {
11227
+ const key = `${deviceId}|${capName}|${field}`;
11228
+ const window = this.deviceRows.get(key);
11229
+ if (window === void 0 || at - window.lastEmitAt >= 1e4) {
11230
+ if (window?.held !== void 0 && !sameValue(window.held.from, window.held.to)) this.writeDevice(deviceId, capName, field, window.held.from, window.held.to, window.held.at);
11231
+ this.writeDevice(deviceId, capName, field, from, to, at);
11232
+ this.deviceRows.set(key, {
11233
+ deviceId,
11234
+ capName,
11235
+ field,
11236
+ lastEmitAt: at
11237
+ });
11238
+ return;
11239
+ }
11240
+ window.held = {
11241
+ from: window.held?.from ?? from,
11242
+ to,
11243
+ at
11244
+ };
11245
+ }
11246
+ writeDevice(deviceId, capName, field, from, to, at) {
11247
+ this.deps.emit({
11248
+ id: this.nextId(deviceId, at),
11249
+ deviceId,
11250
+ at,
11251
+ capName,
11252
+ field,
11253
+ from,
11254
+ to,
11255
+ outcome: "device",
11256
+ actor: { kind: "device" }
11257
+ });
11258
+ }
11259
+ /** Release coalesced device rows whose window has closed; forget windows nothing is held in. */
11260
+ releaseDeviceRows(now) {
11261
+ for (const [key, window] of this.deviceRows) {
11262
+ if (now - window.lastEmitAt < 1e4) continue;
11263
+ const held = window.held;
11264
+ this.deviceRows.delete(key);
11265
+ if (held === void 0 || sameValue(held.from, held.to)) continue;
11266
+ this.writeDevice(window.deviceId, window.capName, window.field, held.from, held.to, held.at);
11267
+ this.deviceRows.set(key, {
11268
+ ...window,
11269
+ held: void 0,
11270
+ lastEmitAt: now
11271
+ });
11272
+ }
11273
+ }
11274
+ keyOf(deviceId, capName) {
11275
+ return `${deviceId}|${capName}`;
11276
+ }
11277
+ nextId(deviceId, at) {
11278
+ this.seq += 1;
11279
+ return `${deviceId}:${at}:${this.seq}`;
11280
+ }
11281
+ nextCommandId(obs) {
11282
+ this.seq += 1;
11283
+ return `${obs.deviceId}:${obs.at}:c${this.seq}`;
11284
+ }
11285
+ };
11286
+ var DROP_LOG_DEVICES_MAX = 10;
11287
+ var TransitionSender = class {
11288
+ deps;
11289
+ queue = [];
11290
+ flushing = false;
11291
+ failing = false;
11292
+ max;
11293
+ constructor(deps) {
11294
+ this.deps = deps;
11295
+ this.max = deps.maxQueued ?? 1e4;
11296
+ }
11297
+ queued() {
11298
+ return this.queue.length;
11299
+ }
11300
+ /**
11301
+ * Give up on what is still queued (shutdown): say how much, and for which devices, then clear.
11302
+ * Rows are telemetry (D8), but a hole in the audit is never silent.
11303
+ */
11304
+ abandon() {
11305
+ if (this.queue.length === 0) return;
11306
+ const dropped = this.queue.splice(0);
11307
+ this.reportDropped(dropped, "abandoned at shutdown");
11308
+ }
11309
+ enqueue(row) {
11310
+ this.queue.push(row);
11311
+ const over = this.queue.length - this.max;
11312
+ if (over <= 0) return;
11313
+ this.reportDropped(this.queue.splice(0, over), `queue over ${this.max}, oldest dropped`);
11314
+ }
11315
+ reportDropped(dropped, why) {
11316
+ const devices = [...new Set(dropped.map((t) => t.deviceId))];
11317
+ this.deps.logger.error(`device-transitions ${why}: ${dropped.length} transition(s) across ${devices.length} device(s) lost`);
11318
+ for (const deviceId of devices.slice(0, DROP_LOG_DEVICES_MAX)) this.deps.logger.error("device-transitions dropped transitions for this device", { tags: { deviceId } });
11319
+ }
11320
+ async flush() {
11321
+ if (this.flushing) return;
11322
+ this.flushing = true;
11323
+ try {
11324
+ while (this.queue.length > 0) {
11325
+ const batch = this.queue.slice(0, 500);
11326
+ try {
11327
+ await this.deps.send(batch);
11328
+ } catch (err) {
11329
+ if (!this.failing) {
11330
+ this.failing = true;
11331
+ this.deps.logger.error(`device-transitions flush failed, ${this.queue.length} queued: ${err instanceof Error ? err.message : String(err)}`);
11332
+ }
11333
+ return;
11334
+ }
11335
+ this.failing = false;
11336
+ this.queue.splice(0, batch.length);
11337
+ }
11338
+ } finally {
11339
+ this.flushing = false;
11340
+ }
11341
+ }
11342
+ };
11343
+ //#endregion
11344
+ //#region src/builtins/device-manager/transitions/transitions-wiring.ts
11345
+ /**
11346
+ * Starts the hub's device-transition audit (D1022): command observations and
11347
+ * mirror slice changes meet in the correlator, its rows ride a bounded queue to
11348
+ * device-history. Everything here is best-effort telemetry (D8): a failure
11349
+ * costs rows, never a command or a mirror write.
11350
+ */
11351
+ var TRANSITIONS_FLUSH_INTERVAL_MS = 2e3;
11352
+ var realTicker = (fn, ms) => {
11353
+ const handle = setInterval(fn, ms);
11354
+ return () => clearInterval(handle);
11355
+ };
11356
+ function inputFor(capName, method) {
11357
+ const def = require_dist.ALL_CAPABILITY_DEFINITIONS.find((d) => d.name === capName);
11358
+ return def === void 0 ? void 0 : require_dist.expandCapMethods(def)[method]?.input;
11359
+ }
11360
+ function startDeviceTransitions(deps) {
11361
+ const now = deps.now ?? Date.now;
11362
+ const ticker = deps.ticker ?? realTicker;
11363
+ const sender = new TransitionSender({
11364
+ send: (batch) => deps.record(batch),
11365
+ logger: deps.logger
11366
+ });
11367
+ const correlator = new TransitionCorrelator({
11368
+ now,
11369
+ currentSlice: (deviceId, capName) => deps.mirror.currentSlice(deviceId, capName),
11370
+ emit: (row) => sender.enqueue(row),
11371
+ prepareArgs: createCommandArgsPreparer(inputFor)
11372
+ });
11373
+ deps.mirror.setTransitionTap((deviceId, capName, prior, slice) => {
11374
+ try {
11375
+ correlator.onSliceChange(deviceId, capName, prior, slice);
11376
+ } catch (err) {
11377
+ deps.logger.error(`device-transitions: correlating a ${capName} change failed: ${err instanceof Error ? err.message : String(err)}`, { tags: { deviceId } });
11378
+ }
11379
+ });
11380
+ const unsubscribe = getCommandObserverRegistry().subscribe((obs) => {
11381
+ if (!require_dist.isCommand(obs.capName, obs.method)) return;
11382
+ try {
11383
+ correlator.recordCommand(obs);
11384
+ } catch (err) {
11385
+ deps.logger.error(`device-transitions: recording a ${obs.capName}.${obs.method} command failed: ${err instanceof Error ? err.message : String(err)}`, { tags: { deviceId: obs.deviceId } });
11386
+ }
11387
+ });
11388
+ const stopTicker = ticker(() => {
11389
+ correlator.sweep();
11390
+ sender.flush();
11391
+ }, TRANSITIONS_FLUSH_INTERVAL_MS);
11392
+ return {
11393
+ forgetDevice: (deviceId) => correlator.forgetDevice(deviceId),
11394
+ stop: async () => {
11395
+ unsubscribe();
11396
+ deps.mirror.setTransitionTap(null);
11397
+ stopTicker();
11398
+ await sender.flush();
11399
+ sender.abandon();
11400
+ }
11401
+ };
11402
+ }
11403
+ //#endregion
10735
11404
  //#region src/builtins/device-manager/field-claims-index.ts
10736
11405
  /** The addon-store key the index lives under. */
10737
11406
  var FIELD_CLAIMS_INDEX_KEY = "field-claims-index";
@@ -11187,6 +11856,8 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
11187
11856
  * `ctx`); `null` before initialise / when `ctx.settings` is absent.
11188
11857
  */
11189
11858
  stateMirrorImpl = null;
11859
+ /** The transition audit (D1022): command + mirror correlation, shipped to device-history. */
11860
+ transitions = null;
11190
11861
  /**
11191
11862
  * Removes the claimed-status overlay this addon installed on the capability
11192
11863
  * registry (D663, S3): `getStatus` of a claimed cap answers the mirror for
@@ -11272,7 +11943,10 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
11272
11943
  },
11273
11944
  holdMirrorWrites: (deviceIds, settings) => this.stateMirror.holdDiskWrites(deviceIds, settings),
11274
11945
  mirrorOwnedCaps: (deviceId) => this.stateMirror.ownedCaps(deviceId),
11275
- forgetMirrorDevice: (deviceId) => this.stateMirror.forgetDevice(deviceId),
11946
+ forgetMirrorDevice: (deviceId) => {
11947
+ this.transitions?.forgetDevice(deviceId);
11948
+ return this.stateMirror.forgetDevice(deviceId);
11949
+ },
11276
11950
  resolveDeviceOnline: (deviceId, fallbackOnline) => this.stateMirror.resolveDeviceOnline(deviceId, fallbackOnline),
11277
11951
  resolveDeviceProbed: (deviceId) => this.stateMirror.resolveDeviceProbed(deviceId),
11278
11952
  waitDeviceProvider: (addonId, timeoutMs) => this.waitDeviceProvider(addonId, timeoutMs),
@@ -11487,6 +12161,15 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
11487
12161
  const metaStore = new DeviceMetaStore(settings, registry, deviceRows, this.addonStoreWriteLock);
11488
12162
  this.stateMirrorImpl = new DeviceStateMirror(this.ctx);
11489
12163
  const stateMirror = this.stateMirrorImpl;
12164
+ this.transitions = startDeviceTransitions({
12165
+ mirror: stateMirror,
12166
+ logger: this.ctx.logger.child("transitions"),
12167
+ record: async (transitions) => {
12168
+ const api = this.ctx.api;
12169
+ if (api === void 0) throw new Error("ctx.api not ready");
12170
+ await api.deviceTransitions.record.mutate({ transitions: [...transitions] });
12171
+ }
12172
+ });
11490
12173
  this.fieldClaimsImpl = new FieldClaimsIndex({
11491
12174
  logger: this.ctx.logger.child("claims-index"),
11492
12175
  withAddonStoreWriteLock: this.addonStoreWriteLock
@@ -11803,6 +12486,8 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
11803
12486
  return this.removalHooksCleanupImpl;
11804
12487
  }
11805
12488
  async onShutdown() {
12489
+ await this.transitions?.stop();
12490
+ this.transitions = null;
11806
12491
  this.removalCleanupImpl?.dispose();
11807
12492
  this.removalCleanupImpl = null;
11808
12493
  this.removalHooksCleanupImpl?.dispose();
@@ -11815,9 +12500,18 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
11815
12500
  }
11816
12501
  };
11817
12502
  //#endregion
12503
+ exports.CommandObserverRegistry = CommandObserverRegistry;
11818
12504
  exports.DeviceManagerAddon = DeviceManagerAddon;
11819
12505
  exports.default = DeviceManagerAddon;
12506
+ exports.__resetCommandObserverRegistryForTests = __resetCommandObserverRegistryForTests;
12507
+ exports.addonCommandActor = addonCommandActor;
12508
+ exports.commandActorFromContext = commandActorFromContext;
12509
+ exports.commandObserverLink = commandObserverLink;
11820
12510
  exports.createDeviceSettingsStore = createDeviceSettingsStore;
12511
+ exports.getCommandObserverRegistry = getCommandObserverRegistry;
11821
12512
  exports.mergeAggregates = mergeAggregates;
12513
+ exports.observable = observable;
11822
12514
  exports.readDeviceOrThrow = readDeviceOrThrow;
12515
+ exports.reportCommand = reportCommand;
12516
+ exports.runObservedCommand = runObservedCommand;
11823
12517
  exports.setWrapperActive = setWrapperActive;