@camstack/server 1.2.898 → 1.2.899

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 (108) hide show
  1. package/CHANGELOG.md +6 -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 +1894 -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 +8 -14
  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/core-blocks.addon.js +3 -3
  29. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +3 -3
  30. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  31. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  32. package/system/dist/builtins/device-manager/command-holds.d.ts +2 -0
  33. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +1 -0
  34. package/system/dist/builtins/device-manager/device-manager.addon.js +706 -24
  35. package/system/dist/builtins/device-manager/device-manager.addon.mjs +694 -25
  36. package/system/dist/builtins/device-manager/device-state-mirror.d.ts +7 -0
  37. package/system/dist/builtins/device-manager/state-refresh-scheduler.d.ts +92 -0
  38. package/system/dist/builtins/device-manager/state-refresh-wiring.d.ts +23 -0
  39. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  40. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  41. package/system/dist/builtins/keychain/index.js +4 -4
  42. package/system/dist/builtins/keychain/index.mjs +4 -4
  43. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  44. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  45. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  46. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  47. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  48. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  49. package/system/dist/builtins/loki-logging/index.js +1 -1
  50. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  51. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  52. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  53. package/system/dist/builtins/platform-probe/index.js +1 -1
  54. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  55. package/system/dist/builtins/record-entries/index.js +1 -1
  56. package/system/dist/builtins/record-entries/index.mjs +1 -1
  57. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  58. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  59. package/system/dist/builtins/snapshot/index.js +1 -1
  60. package/system/dist/builtins/snapshot/index.mjs +1 -1
  61. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  62. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  63. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  64. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  65. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  66. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  67. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  68. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  69. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  70. package/system/dist/builtins/system-config/system-config.addon.mjs +284 -284
  71. package/system/dist/builtins/winston-logging/index.js +1 -1
  72. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  73. package/system/dist/{capture-engine-DBQDaDxJ.mjs → capture-engine-BcD6iCZM.mjs} +1 -1
  74. package/system/dist/{capture-engine-BWS0KTbm.js → capture-engine-LHKTf-nM.js} +1 -1
  75. package/system/dist/{composition-sources-CGUWmf-T.mjs → composition-sources-C3ARJk2g.mjs} +1 -1
  76. package/system/dist/{composition-sources-CDOW1dnY.js → composition-sources-DNUDbuXy.js} +1 -1
  77. package/system/dist/{constants-BwrRoq-j.js → constants-dL8fl9aI.js} +1 -1
  78. package/system/dist/{constants-BmrLkwZs.mjs → constants-er38mZOb.mjs} +1 -1
  79. package/system/dist/{device-ca-BGgZXEto.mjs → device-ca-Ccz5olgH.mjs} +1 -1
  80. package/system/dist/{device-ca-DiuwWyZY.js → device-ca-KWa6uJRU.js} +1 -1
  81. package/system/dist/{dist-D7t8wLTF.mjs → dist-DBanWvHF.mjs} +147 -2
  82. package/system/dist/{dist-CCd8IeIU.js → dist-DEAjZE_-.js} +164 -1
  83. package/system/dist/file-host-worker.js +1 -1
  84. package/system/dist/file-host-worker.mjs +1 -1
  85. package/system/dist/{hub-identity-BohJeqdO.mjs → hub-identity-CVv79TVO.mjs} +1 -1
  86. package/system/dist/{hub-identity-G_ZdyPpc.js → hub-identity-Dy8ZSUuq.js} +1 -1
  87. package/system/dist/{hub-mdns-ciao-CKD4EgkG.js → hub-mdns-ciao-C_XjO7YI.js} +2 -2
  88. package/system/dist/{hub-mdns-ciao-D5RxSMrH.mjs → hub-mdns-ciao-DtmIyWDL.mjs} +2 -2
  89. package/system/dist/index.js +59 -12
  90. package/system/dist/index.mjs +55 -14
  91. package/system/dist/kernel/cap-router-builder.d.ts +7 -0
  92. package/system/dist/kernel/command-follow-up.d.ts +33 -0
  93. package/system/dist/kernel/command-observation.d.ts +3 -0
  94. package/system/dist/kernel/index.d.ts +3 -0
  95. package/system/dist/kernel/moleculer/child-cap-descriptors.d.ts +3 -1
  96. package/system/dist/kernel/moleculer/device-cap-proxy.d.ts +2 -1
  97. package/system/dist/kernel/state-refresh-policies.d.ts +53 -0
  98. package/system/dist/kernel/transport/child-cap-protocol.d.ts +6 -1
  99. package/system/dist/kernel/transport/local-child-registry.d.ts +14 -0
  100. package/system/dist/{legacy-integration-rows-door-Rm9JmIsl.mjs → legacy-integration-rows-door-BL8T4lya.mjs} +1 -1
  101. package/system/dist/{legacy-integration-rows-door-BgCl68ek.js → legacy-integration-rows-door-DPInWtE6.js} +1 -1
  102. package/system/dist/{rename-composition-block-2Z2ED7Og.js → rename-composition-block-BxzETYOf.js} +1 -1
  103. package/system/dist/{rename-composition-block-DNO3mNEO.mjs → rename-composition-block-Dgo-9-Ts.mjs} +1 -1
  104. package/system/dist/{restore-archive-2L5TymvF.mjs → restore-archive-BUtuNTe1.mjs} +82 -82
  105. package/system/dist/{restore-archive-CZkQO8t3.js → restore-archive-Zvx9sHZP.js} +1 -1
  106. package/system/dist/{wal-maintenance-YjDJ73Qd.js → wal-maintenance-DS2IKwtK.js} +0 -0
  107. package/system/dist/{wal-maintenance-BMYe_n18.mjs → wal-maintenance-cASt_sYy.mjs} +0 -0
  108. 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-DEAjZE_-.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-BxzETYOf.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");
@@ -11398,7 +11398,7 @@ function createDeviceStateClaimMethods(deps) {
11398
11398
  meta: {
11399
11399
  cap: capName,
11400
11400
  owner,
11401
- error: errorMessage$3(err)
11401
+ error: errorMessage$4(err)
11402
11402
  }
11403
11403
  });
11404
11404
  throw err;
@@ -11443,13 +11443,13 @@ function createDeviceStateClaimMethods(deps) {
11443
11443
  meta: {
11444
11444
  cap: key.capName,
11445
11445
  refusal: code,
11446
- error: errorMessage$3(err)
11446
+ error: errorMessage$4(err)
11447
11447
  }
11448
11448
  });
11449
11449
  }
11450
11450
  }
11451
11451
  }
11452
- function errorMessage$3(err) {
11452
+ function errorMessage$4(err) {
11453
11453
  return err instanceof Error ? err.message : String(err);
11454
11454
  }
11455
11455
  //#endregion
@@ -11727,7 +11727,7 @@ var RuntimeStateRowUnreadError = class extends Error {
11727
11727
  };
11728
11728
  var ROW_UNREAD_REFUSAL_MESSAGE = "runtime-state row write refused — the row could not be read first, nothing written";
11729
11729
  var ROW_DROPS_CAPS_MESSAGE = "runtime-state row write DROPS caps the stored row holds";
11730
- function errorMessage$2(err) {
11730
+ function errorMessage$3(err) {
11731
11731
  return err instanceof Error ? err.message : String(err);
11732
11732
  }
11733
11733
  /**
@@ -11895,7 +11895,7 @@ var MirrorRowWriter = class MirrorRowWriter {
11895
11895
  tags: { deviceId },
11896
11896
  meta: {
11897
11897
  path,
11898
- error: errorMessage$2(err)
11898
+ error: errorMessage$3(err)
11899
11899
  }
11900
11900
  });
11901
11901
  }
@@ -11977,7 +11977,7 @@ var MirrorRowWriter = class MirrorRowWriter {
11977
11977
  slot.lastWriteFailed = true;
11978
11978
  this.deps.logger.warn("writeDeviceRuntimeState failed", {
11979
11979
  tags: { deviceId },
11980
- meta: { error: errorMessage$2(err) }
11980
+ meta: { error: errorMessage$3(err) }
11981
11981
  });
11982
11982
  }
11983
11983
  }
@@ -12052,7 +12052,7 @@ var MirrorRowWriter = class MirrorRowWriter {
12052
12052
  try {
12053
12053
  await this.serialiseWrite(deviceId, () => this.writeRow(deviceId, settings, blob, "drain"));
12054
12054
  } catch (err) {
12055
- this.refuseDrain(deviceId, `the pending runtime-state write failed: ${errorMessage$2(err)}`, err);
12055
+ this.refuseDrain(deviceId, `the pending runtime-state write failed: ${errorMessage$3(err)}`, err);
12056
12056
  }
12057
12057
  }
12058
12058
  /** A drain that cannot vouch for the row: still owed (re-armed on release), logged, refused. */
@@ -12253,6 +12253,11 @@ var CommandHolds = class {
12253
12253
  isHolding(deviceId, capName) {
12254
12254
  return (this.held.get(deviceId)?.get(capName)?.size ?? 0) > 0;
12255
12255
  }
12256
+ /** Is any field of any cap of the device still held? (D1062: the command burst stops when this is false.) */
12257
+ isHoldingDevice(deviceId) {
12258
+ for (const fields of this.held.get(deviceId)?.values() ?? []) if (fields.size > 0) return true;
12259
+ return false;
12260
+ }
12256
12261
  /** Forget a removed device's holds. */
12257
12262
  clearDevice(deviceId) {
12258
12263
  this.held.delete(deviceId);
@@ -12325,13 +12330,14 @@ var CommandHolds = class {
12325
12330
  */
12326
12331
  var RUNNING_STATE_CAP = "running-state";
12327
12332
  var SEED_REFUSAL_MESSAGE = "runtime-state row unreadable — native write refused until it reads";
12328
- function errorMessage$1(err) {
12333
+ function errorMessage$2(err) {
12329
12334
  return err instanceof Error ? err.message : String(err);
12330
12335
  }
12331
12336
  var DeviceStateMirror = class {
12332
12337
  ctx;
12333
12338
  policyFor;
12334
12339
  transitionTap = null;
12340
+ reportTap = null;
12335
12341
  /**
12336
12342
  * Hub-side mirror of every device's cap-keyed NATIVE runtime state — what the
12337
12343
  * provider wrote. Key: deviceId. Value: per-cap slice map. Empty by default —
@@ -12392,6 +12398,10 @@ var DeviceStateMirror = class {
12392
12398
  setTransitionTap(tap) {
12393
12399
  this.transitionTap = tap;
12394
12400
  }
12401
+ /** Set once by the device-manager: told of every native slice reported, before the no-change check (D1062). */
12402
+ setReportTap(tap) {
12403
+ this.reportTap = tap;
12404
+ }
12395
12405
  /**
12396
12406
  * Hold what a command leads to: the effective slice shows it at once (and
12397
12407
  * `DeviceStateChanged` carries it), the stored, persisted and recorded slice
@@ -12404,6 +12414,10 @@ var DeviceStateMirror = class {
12404
12414
  releaseCommand(token, reason) {
12405
12415
  this.holds.release(token, reason);
12406
12416
  }
12417
+ /** Whether any command hold on the device is still unconfirmed (D1062). */
12418
+ isHoldingDevice(deviceId) {
12419
+ return this.holds.isHoldingDevice(deviceId);
12420
+ }
12407
12421
  /** Stop the hold timers (shutdown). */
12408
12422
  disposeHolds() {
12409
12423
  this.holds.dispose();
@@ -12428,6 +12442,7 @@ var DeviceStateMirror = class {
12428
12442
  * a SQLite commit.
12429
12443
  */
12430
12444
  applySingleCapUpdate(deviceId, capName, slice) {
12445
+ this.reportTap?.(deviceId, capName);
12431
12446
  let perCap = this.stateMirror.get(deviceId);
12432
12447
  if (!perCap) {
12433
12448
  perCap = /* @__PURE__ */ new Map();
@@ -12693,7 +12708,7 @@ var DeviceStateMirror = class {
12693
12708
  await this.ensureRowRead(deviceId, settings);
12694
12709
  return null;
12695
12710
  } catch (err) {
12696
- return refused("row-unreadable", `device ${deviceId}: ${errorMessage$1(err)}`);
12711
+ return refused("row-unreadable", `device ${deviceId}: ${errorMessage$2(err)}`);
12697
12712
  }
12698
12713
  }
12699
12714
  readRowOnce(deviceId, settings) {
@@ -12707,7 +12722,7 @@ var DeviceStateMirror = class {
12707
12722
  this.seedRefusalLogged.add(deviceId);
12708
12723
  this.ctx.logger.warn(SEED_REFUSAL_MESSAGE, {
12709
12724
  tags: { deviceId },
12710
- meta: { error: errorMessage$1(err) }
12725
+ meta: { error: errorMessage$2(err) }
12711
12726
  });
12712
12727
  }
12713
12728
  throw err;
@@ -12741,7 +12756,7 @@ var DeviceStateMirror = class {
12741
12756
  meta: {
12742
12757
  cap: op.cap,
12743
12758
  owner: op.owner,
12744
- error: errorMessage$1(err)
12759
+ error: errorMessage$2(err)
12745
12760
  }
12746
12761
  };
12747
12762
  if (rollback()) {
@@ -13112,6 +13127,93 @@ function pipeReducer(prev, fn) {
13112
13127
  return fn(prev);
13113
13128
  }
13114
13129
  //#endregion
13130
+ //#region src/kernel/command-follow-up.ts
13131
+ /**
13132
+ * The command follow-up (D1062): the work a device command waits for before
13133
+ * its caller hears the answer.
13134
+ *
13135
+ * The D1022 seams that observe a command (the hub tRPC mount, the UDS parent,
13136
+ * an in-process hub addon's `ctx.api`) also await this hook once the
13137
+ * provider's call settled — the hub's state-refresh scheduler re-reads the
13138
+ * device there, so the command returns after the real state was pushed.
13139
+ *
13140
+ * Unlike the observation (telemetry, D8) this one is awaited, but it is never
13141
+ * a gate: a follow-up that throws is swallowed here, and the call's own result
13142
+ * or error is what the caller gets. Cost when nothing is registered: one
13143
+ * undefined check (D181).
13144
+ */
13145
+ /** The one follow-up of this process (the hub's device-manager installs it). */
13146
+ var CommandFollowUpRegistry = class {
13147
+ handler = null;
13148
+ /** Install (or, with `null`, remove) the follow-up. Returns the uninstall. */
13149
+ set(handler) {
13150
+ this.handler = handler;
13151
+ return () => {
13152
+ if (this.handler === handler) this.handler = null;
13153
+ };
13154
+ }
13155
+ /** Run the follow-up for a settled command. Never throws. */
13156
+ async run(target, outcome) {
13157
+ const handler = this.handler;
13158
+ if (handler === null) return;
13159
+ try {
13160
+ await handler(target, outcome);
13161
+ } catch {}
13162
+ }
13163
+ };
13164
+ var registry$3;
13165
+ /** The process-wide registry. */
13166
+ function getCommandFollowUpRegistry() {
13167
+ registry$3 ??= new CommandFollowUpRegistry();
13168
+ return registry$3;
13169
+ }
13170
+ /** Test seam: forget the handler. */
13171
+ function __resetCommandFollowUpRegistryForTests() {
13172
+ registry$3 = void 0;
13173
+ }
13174
+ /** The target of a call when it is a device command naming a device, else `null`. */
13175
+ function commandFollowUpTarget(capName, method, deviceId) {
13176
+ if (deviceId === void 0 || !Number.isInteger(deviceId)) return null;
13177
+ if (!(0, _camstack_types_addon.isCommand)(capName, method)) return null;
13178
+ return {
13179
+ deviceId,
13180
+ capName,
13181
+ method
13182
+ };
13183
+ }
13184
+ /** The `deviceId` an args object names, or `undefined`. */
13185
+ function deviceIdOfArgs(args) {
13186
+ if (args === null || typeof args !== "object" || Array.isArray(args)) return void 0;
13187
+ const deviceId = Reflect.get(args, "deviceId");
13188
+ return typeof deviceId === "number" && Number.isInteger(deviceId) ? deviceId : void 0;
13189
+ }
13190
+ /**
13191
+ * Await `result`, then the follow-up, then answer with `result` — its value, or
13192
+ * its error rethrown. Without a follow-up or a target, `result` is returned
13193
+ * untouched.
13194
+ */
13195
+ function withCommandFollowUp(followUp, target, result) {
13196
+ if (followUp === void 0 || target === null) return result;
13197
+ return settleThenFollowUp(followUp, target, result);
13198
+ }
13199
+ async function settleThenFollowUp(followUp, target, result) {
13200
+ let value;
13201
+ try {
13202
+ value = await result;
13203
+ } catch (err) {
13204
+ await runCommandFollowUp(followUp, target, "failed");
13205
+ throw err;
13206
+ }
13207
+ await runCommandFollowUp(followUp, target, "ok");
13208
+ return value;
13209
+ }
13210
+ /** Run `followUp` for a settled command, swallowing its failure. */
13211
+ async function runCommandFollowUp(followUp, target, outcome) {
13212
+ try {
13213
+ await followUp(target, outcome);
13214
+ } catch {}
13215
+ }
13216
+ //#endregion
13115
13217
  //#region src/kernel/command-observation.ts
13116
13218
  /** Fan-out of command observations to the subscribers of this process. */
13117
13219
  var CommandObserverRegistry = class {
@@ -13132,15 +13234,15 @@ var CommandObserverRegistry = class {
13132
13234
  } catch {}
13133
13235
  }
13134
13236
  };
13135
- var registry$1;
13237
+ var registry$2;
13136
13238
  /** The process-wide registry. */
13137
13239
  function getCommandObserverRegistry() {
13138
- registry$1 ??= new CommandObserverRegistry();
13139
- return registry$1;
13240
+ registry$2 ??= new CommandObserverRegistry();
13241
+ return registry$2;
13140
13242
  }
13141
13243
  /** Test seam: forget every subscriber. */
13142
13244
  function __resetCommandObserverRegistryForTests() {
13143
- registry$1 = void 0;
13245
+ registry$2 = void 0;
13144
13246
  }
13145
13247
  function isRecord(value) {
13146
13248
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -13251,18 +13353,45 @@ function commandObserverLink(options) {
13251
13353
  actor: addonCommandActor(options.callerAddonId, (0, _camstack_types_addon.readCommandOrigin)(op.context)),
13252
13354
  outcome
13253
13355
  });
13356
+ const target = commandFollowUpTarget(capName, method, deviceIdOfArgs(op.input));
13357
+ const followUp = options.followUp;
13358
+ if (followUp === void 0 || target === null) {
13359
+ const sub = downstream.subscribe({
13360
+ next: (value) => observer.next(value),
13361
+ error: (err) => {
13362
+ settled.reject(err);
13363
+ observer.error(err);
13364
+ },
13365
+ complete: () => {
13366
+ settled.resolve();
13367
+ observer.complete();
13368
+ }
13369
+ });
13370
+ return () => sub.unsubscribe();
13371
+ }
13372
+ const answered = [];
13373
+ let closed = false;
13254
13374
  const sub = downstream.subscribe({
13255
- next: (value) => observer.next(value),
13375
+ next: (value) => void answered.push(value),
13256
13376
  error: (err) => {
13257
13377
  settled.reject(err);
13258
- observer.error(err);
13378
+ runCommandFollowUp(followUp, target, "failed").then(() => {
13379
+ if (!closed) observer.error(err);
13380
+ });
13259
13381
  },
13260
13382
  complete: () => {
13261
13383
  settled.resolve();
13262
- observer.complete();
13384
+ runCommandFollowUp(followUp, target, "ok").then(() => {
13385
+ if (closed) return;
13386
+ for (const value of answered) observer.next(value);
13387
+ observer.complete();
13388
+ });
13263
13389
  }
13264
13390
  });
13265
- return () => sub.unsubscribe();
13391
+ return () => {
13392
+ closed = true;
13393
+ sub.unsubscribe();
13394
+ };
13266
13395
  });
13267
13396
  };
13268
13397
  }
@@ -13376,11 +13505,11 @@ var CommandHoldOverrideRegistry = class {
13376
13505
  }
13377
13506
  }
13378
13507
  };
13379
- var registry;
13508
+ var registry$1;
13380
13509
  /** The process-wide registry. */
13381
13510
  function getCommandHoldOverrideRegistry() {
13382
- registry ??= new CommandHoldOverrideRegistry();
13383
- return registry;
13511
+ registry$1 ??= new CommandHoldOverrideRegistry();
13512
+ return registry$1;
13384
13513
  }
13385
13514
  //#endregion
13386
13515
  //#region src/builtins/device-manager/command-holds-wiring.ts
@@ -13424,6 +13553,525 @@ function startCommandHolds(deps) {
13424
13553
  deps.mirror.disposeHolds();
13425
13554
  };
13426
13555
  }
13556
+ //#endregion
13557
+ //#region src/kernel/state-refresh-policies.ts
13558
+ /** The cap a policy is stated on. */
13559
+ var STATE_REFRESH_CAP = "device-state-refresh";
13560
+ /** The source key of an in-process registration. */
13561
+ var IN_PROCESS_REFRESH_SOURCE = "in-process";
13562
+ /** The source key of a forked child's registrations. */
13563
+ function childRefreshSource(childId) {
13564
+ return `child:${childId}`;
13565
+ }
13566
+ /** The policies a child's cap descriptors carry, one entry per device. */
13567
+ function childStateRefreshEntries(childId, caps) {
13568
+ const out = [];
13569
+ for (const cap of caps) {
13570
+ if (cap.capName !== "device-state-refresh") continue;
13571
+ if (cap.deviceId === void 0 || cap.stateRefresh === void 0) continue;
13572
+ out.push({
13573
+ deviceId: cap.deviceId,
13574
+ addonId: cap.addonId ?? childId,
13575
+ policy: cap.stateRefresh
13576
+ });
13577
+ }
13578
+ return out;
13579
+ }
13580
+ var StateRefreshPolicyRegistry = class {
13581
+ bySource = /* @__PURE__ */ new Map();
13582
+ listeners = /* @__PURE__ */ new Set();
13583
+ /** Record (or replace) one device's policy from `source`. */
13584
+ set(source, entry) {
13585
+ const perSource = new Map(this.bySource.get(source) ?? []);
13586
+ perSource.set(entry.deviceId, entry);
13587
+ this.bySource.set(source, perSource);
13588
+ this.changed();
13589
+ }
13590
+ /** Forget one device's policy from `source`. */
13591
+ delete(source, deviceId) {
13592
+ const perSource = this.bySource.get(source);
13593
+ if (perSource === void 0 || !perSource.has(deviceId)) return;
13594
+ const next = new Map(perSource);
13595
+ next.delete(deviceId);
13596
+ if (next.size === 0) this.bySource.delete(source);
13597
+ else this.bySource.set(source, next);
13598
+ this.changed();
13599
+ }
13600
+ /** Replace everything `source` reported with `entries` (an empty list forgets the source). */
13601
+ replaceSource(source, entries) {
13602
+ const had = this.bySource.has(source);
13603
+ if (entries.length === 0) {
13604
+ this.bySource.delete(source);
13605
+ if (had) this.changed();
13606
+ return;
13607
+ }
13608
+ this.bySource.set(source, new Map(entries.map((e) => [e.deviceId, e])));
13609
+ this.changed();
13610
+ }
13611
+ /** Every device's policy (a device registered by two sources keeps the first). */
13612
+ entries() {
13613
+ const seen = /* @__PURE__ */ new Map();
13614
+ for (const perSource of this.bySource.values()) for (const entry of perSource.values()) if (!seen.has(entry.deviceId)) seen.set(entry.deviceId, entry);
13615
+ return [...seen.values()];
13616
+ }
13617
+ /** One device's policy, or `undefined` when its provider did not migrate. */
13618
+ get(deviceId) {
13619
+ for (const perSource of this.bySource.values()) {
13620
+ const found = perSource.get(deviceId);
13621
+ if (found !== void 0) return found;
13622
+ }
13623
+ }
13624
+ subscribe(listener) {
13625
+ this.listeners.add(listener);
13626
+ return () => {
13627
+ this.listeners.delete(listener);
13628
+ };
13629
+ }
13630
+ changed() {
13631
+ for (const listener of this.listeners) try {
13632
+ listener();
13633
+ } catch {}
13634
+ }
13635
+ };
13636
+ var registry;
13637
+ /** The process-wide registry. */
13638
+ function getStateRefreshPolicyRegistry() {
13639
+ registry ??= new StateRefreshPolicyRegistry();
13640
+ return registry;
13641
+ }
13642
+ /** Test seam: forget every policy. */
13643
+ function __resetStateRefreshPolicyRegistryForTests() {
13644
+ registry = void 0;
13645
+ }
13646
+ //#endregion
13647
+ //#region src/builtins/device-manager/state-refresh-scheduler.ts
13648
+ /**
13649
+ * The state-refresh scheduler (D1062, amending D224): the core decides WHEN a
13650
+ * migrated provider re-reads a device; the provider only knows HOW.
13651
+ *
13652
+ * The policy each provider declared on its `device-state-refresh`
13653
+ * registration (`StateRefreshPolicyRegistry`) drives it. Devices are grouped
13654
+ * per integration instance (`addonId::integrationId`):
13655
+ *
13656
+ * - cadence: `effectiveRefreshIntervalMs` — the declared minimum, slowed (never
13657
+ * sped up) by the integration's own setting, no idle back-off;
13658
+ * `push: 'full'` is never scheduled. A batching integration (`batch: true`)
13659
+ * has ONE schedule for the group — one due time, one read of every device
13660
+ * per interval; a device that registers later joins the group's next tick.
13661
+ * A non-batching integration keeps one schedule per device;
13662
+ * - command (`onCommand`, awaited by the D1022 seams): a polled device is read
13663
+ * at once and the command returns after it, then read again at ~3 s and
13664
+ * ~10 s while a D1061 hold on it is still pending; a push device waits
13665
+ * `PUSH_CONFIRM_WINDOW_MS` for the confirming push and reads once if none
13666
+ * came. These reads are per device and never move a batched group's schedule;
13667
+ * - push health: silence past `heartbeatMs` reads the integration, asks it to
13668
+ * resubscribe and reads again; a new `connectionEpoch` reads everything.
13669
+ *
13670
+ * Reads of one device are serialized: each starts after the previous one on
13671
+ * that device ended. A scheduled tick that finds its last read still running
13672
+ * is skipped (debug line); a command waits for the read in flight at most
13673
+ * `COMMAND_WAIT_BOUND_MS`, then reads its own device (debug line). A refresh
13674
+ * failure is a warn line per device and never fails a command.
13675
+ */
13676
+ /** The longest a command waits for a read already in flight on its device. */
13677
+ var COMMAND_WAIT_BOUND_MS = 5e3;
13678
+ function groupKeyOf(entry) {
13679
+ return `${entry.addonId}::${entry.policy.integrationId}`;
13680
+ }
13681
+ function errorMessage$1(err) {
13682
+ return err instanceof Error ? err.message : String(err);
13683
+ }
13684
+ var StateRefreshScheduler = class {
13685
+ deps;
13686
+ devices = /* @__PURE__ */ new Map();
13687
+ groups = /* @__PURE__ */ new Map();
13688
+ unsubscribe;
13689
+ disposed = false;
13690
+ constructor(deps) {
13691
+ this.deps = deps;
13692
+ this.unsubscribe = deps.policies.subscribe(() => this.reconcile());
13693
+ this.reconcile();
13694
+ }
13695
+ /** The command follow-up (awaited by the D1022 seams; never throws). */
13696
+ onCommand = async (target, outcome) => {
13697
+ const device = this.devices.get(target.deviceId);
13698
+ if (device === void 0 || this.disposed) return;
13699
+ device.lastCommandAt = Date.now();
13700
+ this.cancelFollowUps(device);
13701
+ const { policy } = device.entry;
13702
+ if (policy.push !== "none") {
13703
+ this.armPushWindow(target.deviceId, device);
13704
+ return;
13705
+ }
13706
+ this.deps.logger.debug("state refresh after command", {
13707
+ tags: { deviceId: target.deviceId },
13708
+ meta: {
13709
+ capName: target.capName,
13710
+ method: target.method,
13711
+ outcome
13712
+ }
13713
+ });
13714
+ await this.runRefresh([target.deviceId], "command", COMMAND_WAIT_BOUND_MS);
13715
+ if (!policy.batch) {
13716
+ device.dueAt = Date.now() + require_dist.effectiveRefreshIntervalMs(policy);
13717
+ this.armSchedule(groupKeyOf(device.entry));
13718
+ }
13719
+ this.armBurst(target.deviceId, device);
13720
+ };
13721
+ /** A state report reached the mirror for `deviceId` (push or read). */
13722
+ onReport(deviceId) {
13723
+ const device = this.devices.get(deviceId);
13724
+ if (device === void 0) return;
13725
+ const now = Date.now();
13726
+ device.lastReportAt = now;
13727
+ const group = this.groups.get(groupKeyOf(device.entry));
13728
+ if (group !== void 0) group.lastReportAt = now;
13729
+ }
13730
+ dispose() {
13731
+ this.disposed = true;
13732
+ this.unsubscribe();
13733
+ for (const device of this.devices.values()) this.cancelFollowUps(device);
13734
+ for (const group of this.groups.values()) this.clearGroupTimers(group);
13735
+ this.devices.clear();
13736
+ this.groups.clear();
13737
+ }
13738
+ reconcile() {
13739
+ if (this.disposed) return;
13740
+ const now = Date.now();
13741
+ const current = new Map(this.deps.policies.entries().map((e) => [e.deviceId, e]));
13742
+ for (const [deviceId, device] of this.devices) {
13743
+ if (current.has(deviceId)) continue;
13744
+ this.cancelFollowUps(device);
13745
+ this.devices.delete(deviceId);
13746
+ }
13747
+ const reconnected = /* @__PURE__ */ new Set();
13748
+ for (const entry of current.values()) {
13749
+ const existing = this.devices.get(entry.deviceId);
13750
+ const interval = require_dist.effectiveRefreshIntervalMs(entry.policy);
13751
+ if (existing === void 0) this.devices.set(entry.deviceId, {
13752
+ entry,
13753
+ dueAt: now + interval,
13754
+ lastReportAt: now,
13755
+ lastCommandAt: 0,
13756
+ inFlight: null,
13757
+ scheduledInFlight: null,
13758
+ burst: [],
13759
+ pushWindow: null
13760
+ });
13761
+ else {
13762
+ if (require_dist.effectiveRefreshIntervalMs(existing.entry.policy) !== interval) existing.dueAt = now + interval;
13763
+ existing.entry = entry;
13764
+ }
13765
+ if (this.noteEpoch(entry)) reconnected.add(groupKeyOf(entry));
13766
+ }
13767
+ this.rebuildGroups(now);
13768
+ for (const key of reconnected) {
13769
+ this.deps.logger.info("state refresh: integration reconnected, reading every device", { meta: { group: key } });
13770
+ this.refreshGroup(key, "schedule");
13771
+ }
13772
+ }
13773
+ /** Track the group's connection epoch; `true` when it moved past a known one. */
13774
+ noteEpoch(entry) {
13775
+ const epoch = entry.policy.connectionEpoch;
13776
+ if (epoch === void 0) return false;
13777
+ const key = groupKeyOf(entry);
13778
+ const group = this.groups.get(key);
13779
+ if (group === void 0) return false;
13780
+ const previous = group.epoch;
13781
+ if (previous === void 0 || epoch > previous) group.epoch = epoch;
13782
+ return previous !== void 0 && epoch > previous;
13783
+ }
13784
+ rebuildGroups(now) {
13785
+ const members = /* @__PURE__ */ new Map();
13786
+ for (const [deviceId, device] of this.devices) {
13787
+ const key = groupKeyOf(device.entry);
13788
+ const set = members.get(key) ?? /* @__PURE__ */ new Set();
13789
+ set.add(deviceId);
13790
+ members.set(key, set);
13791
+ }
13792
+ for (const [key, group] of this.groups) {
13793
+ if (members.has(key)) continue;
13794
+ this.clearGroupTimers(group);
13795
+ this.groups.delete(key);
13796
+ }
13797
+ for (const [key, devices] of members) {
13798
+ const existing = this.groups.get(key);
13799
+ if (existing === void 0) {
13800
+ const first = this.devices.get([...devices][0] ?? -1);
13801
+ const intervalMs = first === void 0 ? 0 : require_dist.effectiveRefreshIntervalMs(first.entry.policy);
13802
+ this.groups.set(key, {
13803
+ key,
13804
+ devices,
13805
+ dueAt: now + intervalMs,
13806
+ intervalMs,
13807
+ scheduleTimer: null,
13808
+ heartbeatTimer: null,
13809
+ lastReportAt: now,
13810
+ epoch: first?.entry.policy.connectionEpoch
13811
+ });
13812
+ } else {
13813
+ existing.devices = devices;
13814
+ const policy = this.groupPolicy(existing);
13815
+ const intervalMs = policy === void 0 ? 0 : require_dist.effectiveRefreshIntervalMs(policy);
13816
+ if (intervalMs !== existing.intervalMs) {
13817
+ existing.intervalMs = intervalMs;
13818
+ existing.dueAt = now + intervalMs;
13819
+ }
13820
+ }
13821
+ this.armSchedule(key);
13822
+ this.armHeartbeat(key);
13823
+ }
13824
+ }
13825
+ groupPolicy(group) {
13826
+ for (const deviceId of group.devices) {
13827
+ const device = this.devices.get(deviceId);
13828
+ if (device !== void 0) return device.entry.policy;
13829
+ }
13830
+ }
13831
+ armSchedule(key) {
13832
+ const group = this.groups.get(key);
13833
+ if (group === void 0 || this.disposed) return;
13834
+ if (group.scheduleTimer !== null) clearTimeout(group.scheduleTimer);
13835
+ group.scheduleTimer = null;
13836
+ const policy = this.groupPolicy(group);
13837
+ if (policy === void 0 || policy.push === "full") return;
13838
+ let earliest = Number.POSITIVE_INFINITY;
13839
+ if (policy.batch) earliest = group.dueAt;
13840
+ else for (const deviceId of group.devices) {
13841
+ const device = this.devices.get(deviceId);
13842
+ if (device !== void 0) earliest = Math.min(earliest, device.dueAt);
13843
+ }
13844
+ if (!Number.isFinite(earliest)) return;
13845
+ group.scheduleTimer = setTimeout(() => this.tick(key), Math.max(0, earliest - Date.now()));
13846
+ }
13847
+ tick(key) {
13848
+ const group = this.groups.get(key);
13849
+ if (group === void 0 || this.disposed) return;
13850
+ group.scheduleTimer = null;
13851
+ const policy = this.groupPolicy(group);
13852
+ if (policy?.batch === true) this.tickBatched(group, policy);
13853
+ else this.tickPerDevice(group);
13854
+ this.armSchedule(key);
13855
+ }
13856
+ /** One read of the whole group per interval, unless the last one still runs. */
13857
+ tickBatched(group, policy) {
13858
+ const now = Date.now();
13859
+ if (group.dueAt > now) return;
13860
+ group.dueAt = now + require_dist.effectiveRefreshIntervalMs(policy);
13861
+ const ids = [...group.devices].filter((id) => this.devices.has(id));
13862
+ const running = ids.filter((id) => (this.devices.get(id)?.scheduledInFlight ?? null) !== null);
13863
+ if (running.length > 0) {
13864
+ for (const deviceId of running) this.logSkippedTick(deviceId);
13865
+ return;
13866
+ }
13867
+ if (ids.length > 0) this.runScheduled(ids);
13868
+ }
13869
+ tickPerDevice(group) {
13870
+ const now = Date.now();
13871
+ const due = [];
13872
+ for (const deviceId of group.devices) {
13873
+ const device = this.devices.get(deviceId);
13874
+ if (device === void 0 || device.dueAt > now) continue;
13875
+ device.dueAt = now + require_dist.effectiveRefreshIntervalMs(device.entry.policy);
13876
+ if (device.inFlight !== null) {
13877
+ this.logSkippedTick(deviceId);
13878
+ continue;
13879
+ }
13880
+ due.push(deviceId);
13881
+ }
13882
+ for (const deviceId of due) this.runScheduled([deviceId]);
13883
+ }
13884
+ logSkippedTick(deviceId) {
13885
+ this.deps.logger.debug("state refresh skipped: a refresh is still in flight", { tags: { deviceId } });
13886
+ }
13887
+ /** A scheduled read, remembered on each device until it settles. */
13888
+ async runScheduled(deviceIds) {
13889
+ const run = this.runRefresh(deviceIds, "schedule");
13890
+ for (const deviceId of deviceIds) {
13891
+ const device = this.devices.get(deviceId);
13892
+ if (device !== void 0) device.scheduledInFlight = run;
13893
+ }
13894
+ await run;
13895
+ for (const deviceId of deviceIds) {
13896
+ const device = this.devices.get(deviceId);
13897
+ if (device !== void 0 && device.scheduledInFlight === run) device.scheduledInFlight = null;
13898
+ }
13899
+ }
13900
+ armBurst(deviceId, device) {
13901
+ if (!this.deps.holdsPending(deviceId)) return;
13902
+ const timers = [];
13903
+ let stopped = false;
13904
+ for (const offset of require_dist.COMMAND_BURST_OFFSETS_MS) timers.push(setTimeout(() => {
13905
+ if (stopped || this.disposed) return;
13906
+ if (!this.deps.holdsPending(deviceId)) {
13907
+ stopped = true;
13908
+ this.deps.logger.debug("state refresh burst stopped: the command is confirmed", { tags: { deviceId } });
13909
+ return;
13910
+ }
13911
+ if (device.inFlight !== null) {
13912
+ this.deps.logger.debug("state refresh burst skipped: a refresh is still in flight", { tags: { deviceId } });
13913
+ return;
13914
+ }
13915
+ this.runRefresh([deviceId], "burst");
13916
+ }, offset));
13917
+ device.burst = timers;
13918
+ }
13919
+ armPushWindow(deviceId, device) {
13920
+ const commandAt = device.lastCommandAt;
13921
+ device.pushWindow = setTimeout(() => {
13922
+ device.pushWindow = null;
13923
+ if (this.disposed) return;
13924
+ if (device.lastReportAt > commandAt && !this.deps.holdsPending(deviceId)) {
13925
+ this.deps.logger.debug("state refresh not needed: the push confirmed the command", { tags: { deviceId } });
13926
+ return;
13927
+ }
13928
+ this.deps.logger.debug("state refresh: no confirming push within the window", {
13929
+ tags: { deviceId },
13930
+ meta: { windowMs: require_dist.PUSH_CONFIRM_WINDOW_MS }
13931
+ });
13932
+ if (device.inFlight !== null) return;
13933
+ this.runRefresh([deviceId], "command");
13934
+ }, require_dist.PUSH_CONFIRM_WINDOW_MS);
13935
+ }
13936
+ cancelFollowUps(device) {
13937
+ for (const timer of device.burst) clearTimeout(timer);
13938
+ device.burst = [];
13939
+ if (device.pushWindow !== null) clearTimeout(device.pushWindow);
13940
+ device.pushWindow = null;
13941
+ }
13942
+ armHeartbeat(key) {
13943
+ const group = this.groups.get(key);
13944
+ if (group === void 0 || this.disposed) return;
13945
+ if (group.heartbeatTimer !== null) clearTimeout(group.heartbeatTimer);
13946
+ group.heartbeatTimer = null;
13947
+ const policy = this.groupPolicy(group);
13948
+ if (policy === void 0 || policy.push === "none" || policy.heartbeatMs === void 0) return;
13949
+ const heartbeatMs = policy.heartbeatMs;
13950
+ const wait = Math.max(0, group.lastReportAt + heartbeatMs - Date.now());
13951
+ group.heartbeatTimer = setTimeout(() => {
13952
+ group.heartbeatTimer = null;
13953
+ if (this.disposed) return;
13954
+ if (Date.now() - group.lastReportAt >= heartbeatMs) this.onSilence(key, heartbeatMs);
13955
+ else this.armHeartbeat(key);
13956
+ }, wait);
13957
+ }
13958
+ async onSilence(key, heartbeatMs) {
13959
+ const group = this.groups.get(key);
13960
+ if (group === void 0) return;
13961
+ group.lastReportAt = Date.now();
13962
+ for (const deviceId of group.devices) this.deps.logger.warn("state refresh: no push within the heartbeat, reading and resubscribing", {
13963
+ tags: { deviceId },
13964
+ meta: { heartbeatMs }
13965
+ });
13966
+ await this.refreshGroup(key, "schedule");
13967
+ const route = [...group.devices][0];
13968
+ if (route !== void 0) try {
13969
+ await this.deps.resubscribe(route);
13970
+ } catch (err) {
13971
+ this.deps.logger.warn("state refresh: resubscribe failed", {
13972
+ tags: { deviceId: route },
13973
+ meta: { error: errorMessage$1(err) }
13974
+ });
13975
+ }
13976
+ await this.refreshGroup(key, "schedule");
13977
+ this.armHeartbeat(key);
13978
+ }
13979
+ async refreshGroup(key, reason) {
13980
+ const group = this.groups.get(key);
13981
+ if (group === void 0) return;
13982
+ const ids = [...group.devices].filter((id) => this.devices.has(id));
13983
+ if (ids.length > 0) await this.refreshDevices(ids, reason);
13984
+ }
13985
+ /** One call for a batching integration, else one per device. */
13986
+ async refreshDevices(deviceIds, reason) {
13987
+ if (this.devices.get(deviceIds[0] ?? -1)?.entry.policy.batch === true) {
13988
+ await this.runRefresh(deviceIds, reason);
13989
+ return;
13990
+ }
13991
+ await Promise.all(deviceIds.map((id) => this.runRefresh([id], reason)));
13992
+ }
13993
+ /**
13994
+ * Read `deviceIds` once every read already queued on them ended — or, with
13995
+ * `waitBoundMs`, once that long passed (a debug line per device that was
13996
+ * still busy). The read becomes the devices' new tail.
13997
+ */
13998
+ async runRefresh(deviceIds, reason, waitBoundMs) {
13999
+ const route = deviceIds[0];
14000
+ if (route === void 0) return;
14001
+ const busy = [];
14002
+ const prior = [];
14003
+ for (const deviceId of deviceIds) {
14004
+ const tail = this.devices.get(deviceId)?.inFlight;
14005
+ if (tail === null || tail === void 0) continue;
14006
+ busy.push(deviceId);
14007
+ prior.push(tail);
14008
+ }
14009
+ const settled = this.afterPrior(prior, busy, waitBoundMs).then(() => this.deps.refresh(route, deviceIds, reason)).catch((err) => {
14010
+ for (const deviceId of deviceIds) this.deps.logger.warn("state refresh failed", {
14011
+ tags: { deviceId },
14012
+ meta: {
14013
+ reason,
14014
+ error: errorMessage$1(err)
14015
+ }
14016
+ });
14017
+ }).finally(() => {
14018
+ for (const deviceId of deviceIds) {
14019
+ const device = this.devices.get(deviceId);
14020
+ if (device !== void 0 && device.inFlight === settled) device.inFlight = null;
14021
+ }
14022
+ });
14023
+ for (const deviceId of deviceIds) {
14024
+ const device = this.devices.get(deviceId);
14025
+ if (device !== void 0) device.inFlight = settled;
14026
+ }
14027
+ await settled;
14028
+ }
14029
+ /** Resolves when every `prior` read ended, or after `waitBoundMs` (logged per busy device). */
14030
+ async afterPrior(prior, busy, waitBoundMs) {
14031
+ if (prior.length === 0) return;
14032
+ const all = Promise.all(prior).then(() => true);
14033
+ if (waitBoundMs === void 0) {
14034
+ await all;
14035
+ return;
14036
+ }
14037
+ let timer;
14038
+ const bound = new Promise((resolve) => {
14039
+ timer = setTimeout(() => resolve(false), waitBoundMs);
14040
+ });
14041
+ const ended = await Promise.race([all, bound]);
14042
+ if (timer !== void 0) clearTimeout(timer);
14043
+ if (ended) return;
14044
+ for (const deviceId of busy) this.deps.logger.debug("state refresh: stopped waiting for the read in flight", {
14045
+ tags: { deviceId },
14046
+ meta: { waitedMs: waitBoundMs }
14047
+ });
14048
+ }
14049
+ clearGroupTimers(group) {
14050
+ if (group.scheduleTimer !== null) clearTimeout(group.scheduleTimer);
14051
+ if (group.heartbeatTimer !== null) clearTimeout(group.heartbeatTimer);
14052
+ group.scheduleTimer = null;
14053
+ group.heartbeatTimer = null;
14054
+ }
14055
+ };
14056
+ //#endregion
14057
+ //#region src/builtins/device-manager/state-refresh-wiring.ts
14058
+ /** Start the scheduler; returns the stop. */
14059
+ function startStateRefresh(deps) {
14060
+ const scheduler = new StateRefreshScheduler({
14061
+ policies: deps.policies ?? getStateRefreshPolicyRegistry(),
14062
+ logger: deps.logger,
14063
+ holdsPending: (deviceId) => deps.mirror.isHoldingDevice(deviceId),
14064
+ refresh: deps.refresh,
14065
+ resubscribe: deps.resubscribe
14066
+ });
14067
+ deps.mirror.setReportTap((deviceId) => scheduler.onReport(deviceId));
14068
+ const uninstall = getCommandFollowUpRegistry().set(scheduler.onCommand);
14069
+ return () => {
14070
+ uninstall();
14071
+ deps.mirror.setReportTap(null);
14072
+ scheduler.dispose();
14073
+ };
14074
+ }
13427
14075
  var REDACTED = "***";
13428
14076
  var ROUTING_KEYS = new Set([
13429
14077
  "deviceId",
@@ -14344,6 +14992,7 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
14344
14992
  transitions = null;
14345
14993
  /** Unsubscribes the command hold (D1061). */
14346
14994
  stopCommandHolds = null;
14995
+ stopStateRefresh = null;
14347
14996
  /**
14348
14997
  * Removes the claimed-status overlay this addon installed on the capability
14349
14998
  * registry (D663, S3): `getStatus` of a claimed cap answers the mirror for
@@ -14694,6 +15343,24 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
14694
15343
  mirror: stateMirror,
14695
15344
  logger: this.ctx.logger.child("command-holds")
14696
15345
  });
15346
+ this.stopStateRefresh = startStateRefresh({
15347
+ mirror: stateMirror,
15348
+ logger: this.ctx.logger.child("state-refresh"),
15349
+ refresh: async (deviceId, deviceIds, reason) => {
15350
+ const api = this.ctx.api;
15351
+ if (api === void 0) throw new Error("ctx.api not ready");
15352
+ await api.deviceStateRefresh.refresh.mutate({
15353
+ deviceId,
15354
+ deviceIds: [...deviceIds],
15355
+ reason
15356
+ });
15357
+ },
15358
+ resubscribe: async (deviceId) => {
15359
+ const api = this.ctx.api;
15360
+ if (api === void 0) throw new Error("ctx.api not ready");
15361
+ await api.deviceStateRefresh.resubscribe.mutate({ deviceId });
15362
+ }
15363
+ });
14697
15364
  this.transitions = startDeviceTransitions({
14698
15365
  mirror: stateMirror,
14699
15366
  logger: this.ctx.logger.child("transitions"),
@@ -15092,6 +15759,8 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
15092
15759
  this.templateActions = null;
15093
15760
  await this.transitions?.stop();
15094
15761
  this.transitions = null;
15762
+ this.stopStateRefresh?.();
15763
+ this.stopStateRefresh = null;
15095
15764
  this.stopCommandHolds?.();
15096
15765
  this.stopCommandHolds = null;
15097
15766
  this.removalCleanupImpl?.dispose();
@@ -15108,22 +15777,35 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
15108
15777
  }
15109
15778
  };
15110
15779
  //#endregion
15780
+ exports.CommandFollowUpRegistry = CommandFollowUpRegistry;
15111
15781
  exports.CommandObserverRegistry = CommandObserverRegistry;
15112
15782
  exports.DeviceManagerAddon = DeviceManagerAddon;
15113
15783
  exports.default = DeviceManagerAddon;
15114
15784
  exports.IN_PROCESS_HOLD_SOURCE = IN_PROCESS_HOLD_SOURCE;
15785
+ exports.IN_PROCESS_REFRESH_SOURCE = IN_PROCESS_REFRESH_SOURCE;
15786
+ exports.STATE_REFRESH_CAP = STATE_REFRESH_CAP;
15787
+ exports.StateRefreshPolicyRegistry = StateRefreshPolicyRegistry;
15788
+ exports.__resetCommandFollowUpRegistryForTests = __resetCommandFollowUpRegistryForTests;
15115
15789
  exports.__resetCommandObserverRegistryForTests = __resetCommandObserverRegistryForTests;
15790
+ exports.__resetStateRefreshPolicyRegistryForTests = __resetStateRefreshPolicyRegistryForTests;
15116
15791
  exports.addonCommandActor = addonCommandActor;
15117
15792
  exports.childCommandHoldEntries = childCommandHoldEntries;
15118
15793
  exports.childHoldSource = childHoldSource;
15794
+ exports.childRefreshSource = childRefreshSource;
15795
+ exports.childStateRefreshEntries = childStateRefreshEntries;
15119
15796
  exports.commandActorFromContext = commandActorFromContext;
15797
+ exports.commandFollowUpTarget = commandFollowUpTarget;
15120
15798
  exports.commandObserverLink = commandObserverLink;
15121
15799
  exports.createDeviceSettingsStore = createDeviceSettingsStore;
15800
+ exports.deviceIdOfArgs = deviceIdOfArgs;
15801
+ exports.getCommandFollowUpRegistry = getCommandFollowUpRegistry;
15122
15802
  exports.getCommandHoldOverrideRegistry = getCommandHoldOverrideRegistry;
15123
15803
  exports.getCommandObserverRegistry = getCommandObserverRegistry;
15804
+ exports.getStateRefreshPolicyRegistry = getStateRefreshPolicyRegistry;
15124
15805
  exports.mergeAggregates = mergeAggregates;
15125
15806
  exports.observable = observable;
15126
15807
  exports.readDeviceOrThrow = readDeviceOrThrow;
15127
15808
  exports.reportCommand = reportCommand;
15128
15809
  exports.runObservedCommand = runObservedCommand;
15129
15810
  exports.setWrapperActive = setWrapperActive;
15811
+ exports.withCommandFollowUp = withCommandFollowUp;