@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
@@ -1,7 +1,7 @@
1
- import { A as ConditionMirror, Ao as sameIdentifiers, Br as deviceExtensionCapability, Dl as isCommand$1, Dr as createDeviceExtensionProvider, Ds as workloadCapability, Ea as normalizeUnit, Fo as searchRank, Fr as defineExtensionSlotProvider, Gc as SECRET_CLEAR, Go as siteZoneKey, Hr as deviceManagerCapability, Hs as capAppliesToDeviceKind, Il as isSecretMarker, It as MINUTES_PER_DAY, J as DEVICE_TEMPLATE_FILTERS, Jr as deviceStatusCapability, Ki as isWorkloadSettled, Ll as isSecretMarkerLike, Ml as isKeychainStoredField, Na as parseStreamParamsFormPatch, On as WORKLOAD_TRANSITION_CATEGORY, Oo as runtimeFieldUnit, Os as workloadTransition, Pl as isSecretClear, Q as DEVICE_TEMPLATE_VALUES_CAP, Qa as reconcileReportedFeatures, Qn as buildStreamParamsConfigSchema, Qr as enumerateSchemaFields, R as DAY_NAMES, Ta as normalizeTags, Ti as identifierStrength, To as resolveTemplateRef, U as DEVICE_IDENTIFIER_KEYS, Ur as deviceOffersActions, Vi as isKernelDerivedFeature, Vs as canonicalStoredDeviceType, X as DEVICE_TEMPLATE_MAX_OUTPUT, Xi as legacyAutoLinkIds, Y as DEVICE_TEMPLATE_MAX_LENGTH, Zc as WELL_KNOWN_TAB_MAP, Zl as resolveSecretMarkers, Zr as enumerateItemArrayFields, _l as defineRecordKinds, _u as EventCategory$1, at as DeviceTombstoneSchema, au as toSecretFieldView, cu as vocabActionIdFor, eu as secretTreeFromPaths, fu as DeviceFeature, gi as formatMinutes, hc as BaseAddon, hu as errMsg$1, il as auditedFields, it as DeviceStatusSchema, kl as isDeviceConfigCap, kn as WorkloadStateSchema, ko as runtimeStatePolicyFor, ll as collectZodSecretPaths$1, ln as STREAM_PROFILE_META, ma as mergeIdentifiers, mu as DeviceType$1, na as locationIconKey, nc as implementedMethodsOf$1, nr as canonicalIconKey, nt as DeviceIdentifiersSchema, oi as extractSourceInfoFromMetadata, or as checkDeviceAlias, ot as DiscoveryProposalBodySchema, ou as transformSecretWrite, po as resolveCommandHold, pu as DeviceRole, qr as deviceStateCapability, ri as expandContainer, ru as sleep$2, s as ALL_CAPABILITY_DEFINITIONS, su as userError, ul as commandEffect, ut as ExportNameRefusedError, vt as FieldClaimModeSchema, x as CAP_NAMES_WITH_STATUS, xl as expandCapMethods$1, y as CAMERA_SWITCH_ORDER, yi as generateDeviceAlias, yt as FieldClaimSchema, zi as isEmptyIdentifiers, zo as settleDeviceFeatures } from "../../dist-D7t8wLTF.mjs";
1
+ import { $ as DEVICE_TEMPLATE_VALUES_CAP, $i as legacyAutoLinkIds, Al as isCommand$1, An as WORKLOAD_TRANSITION_CATEGORY, As as workloadCapability, Bl as isSecretMarkerLike, C as COMMAND_BURST_OFFSETS_MS, Fl as isKeychainStoredField, Gr as deviceOffersActions, Gs as capAppliesToDeviceKind, Hi as isEmptyIdentifiers, Ho as settleDeviceFeatures, Hr as deviceExtensionCapability, Ia as parseStreamParamsFormPatch, Jc as SECRET_CLEAR, Jo as siteZoneKey, Jt as PUSH_CONFIRM_WINDOW_MS, Ll as isSecretClear, Lr as defineExtensionSlotProvider, Lt as MINUTES_PER_DAY, Ml as isDeviceConfigCap, Mo as runtimeStatePolicyFor, No as sameIdentifiers, Oa as normalizeTags, Oi as identifierStrength, Oo as resolveTemplateRef, Qr as effectiveRefreshIntervalMs, Ro as searchRank, Si as generateDeviceAlias, W as DEVICE_IDENTIFIER_KEYS, Wi as isKernelDerivedFeature, Wr as deviceManagerCapability, Ws as canonicalStoredDeviceType, X as DEVICE_TEMPLATE_MAX_LENGTH, Xr as deviceStatusCapability, Y as DEVICE_TEMPLATE_FILTERS, Yi as isWorkloadSettled, Yr as deviceStateCapability, Z as DEVICE_TEMPLATE_MAX_OUTPUT, _a as mergeIdentifiers, _u as DeviceType$1, aa as locationIconKey, ac as implementedMethodsOf$1, at as DeviceStatusSchema, bl as defineRecordKinds, bt as FieldClaimSchema, bu as EventCategory$1, cr as checkDeviceAlias, cu as toSecretFieldView, dn as STREAM_PROFILE_META, dt as ExportNameRefusedError, du as vocabActionIdFor, ei as enumerateItemArrayFields, el as WELL_KNOWN_TAB_MAP, er as buildStreamParamsConfigSchema, eu as resolveSecretMarkers, fl as collectZodSecretPaths$1, go as resolveCommandHold, gu as DeviceRole, hu as DeviceFeature, ir as canonicalIconKey, j as ConditionMirror, jn as WorkloadStateSchema, jo as runtimeFieldUnit, js as workloadTransition, ka as normalizeUnit, kr as createDeviceExtensionProvider, li as extractSourceInfoFromMetadata, lu as transformSecretWrite, oi as expandContainer, ot as DeviceTombstoneSchema, ou as sleep$2, pl as commandEffect, rt as DeviceIdentifiersSchema, ru as secretTreeFromPaths, s as ALL_CAPABILITY_DEFINITIONS, sl as auditedFields, st as DiscoveryProposalBodySchema, ti as enumerateSchemaFields, to as reconcileReportedFeatures, uu as userError, vc as BaseAddon, vu as errMsg$1, wl as expandCapMethods$1, x as CAP_NAMES_WITH_STATUS, y as CAMERA_SWITCH_ORDER, yi as formatMinutes, yt as FieldClaimModeSchema, z as DAY_NAMES, zl as isSecretMarker } from "../../dist-DBanWvHF.mjs";
2
2
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
3
3
  import { a as redactLogText, i as redactLogMeta, n as isSecretArgumentKey } from "../../log-redactor-XLDrPzOi.mjs";
4
- import { n as renameCompositionBlock, t as composedBlockIdOf } from "../../rename-composition-block-DNO3mNEO.mjs";
4
+ import { n as renameCompositionBlock, t as composedBlockIdOf } from "../../rename-composition-block-Dgo-9-Ts.mjs";
5
5
  import { t as prefixRange } from "../../prefix-range-Dl0znowN.mjs";
6
6
  import { t as loadPrefixed } from "../../prefix-walk-DAOBSyH1.mjs";
7
7
  import { n as purgeRetiredSettingsRows } from "../../retired-settings-keys-u6xQA6r7.mjs";
@@ -11391,7 +11391,7 @@ function createDeviceStateClaimMethods(deps) {
11391
11391
  meta: {
11392
11392
  cap: capName,
11393
11393
  owner,
11394
- error: errorMessage$3(err)
11394
+ error: errorMessage$4(err)
11395
11395
  }
11396
11396
  });
11397
11397
  throw err;
@@ -11436,13 +11436,13 @@ function createDeviceStateClaimMethods(deps) {
11436
11436
  meta: {
11437
11437
  cap: key.capName,
11438
11438
  refusal: code,
11439
- error: errorMessage$3(err)
11439
+ error: errorMessage$4(err)
11440
11440
  }
11441
11441
  });
11442
11442
  }
11443
11443
  }
11444
11444
  }
11445
- function errorMessage$3(err) {
11445
+ function errorMessage$4(err) {
11446
11446
  return err instanceof Error ? err.message : String(err);
11447
11447
  }
11448
11448
  //#endregion
@@ -11720,7 +11720,7 @@ var RuntimeStateRowUnreadError = class extends Error {
11720
11720
  };
11721
11721
  var ROW_UNREAD_REFUSAL_MESSAGE = "runtime-state row write refused — the row could not be read first, nothing written";
11722
11722
  var ROW_DROPS_CAPS_MESSAGE = "runtime-state row write DROPS caps the stored row holds";
11723
- function errorMessage$2(err) {
11723
+ function errorMessage$3(err) {
11724
11724
  return err instanceof Error ? err.message : String(err);
11725
11725
  }
11726
11726
  /**
@@ -11888,7 +11888,7 @@ var MirrorRowWriter = class MirrorRowWriter {
11888
11888
  tags: { deviceId },
11889
11889
  meta: {
11890
11890
  path,
11891
- error: errorMessage$2(err)
11891
+ error: errorMessage$3(err)
11892
11892
  }
11893
11893
  });
11894
11894
  }
@@ -11970,7 +11970,7 @@ var MirrorRowWriter = class MirrorRowWriter {
11970
11970
  slot.lastWriteFailed = true;
11971
11971
  this.deps.logger.warn("writeDeviceRuntimeState failed", {
11972
11972
  tags: { deviceId },
11973
- meta: { error: errorMessage$2(err) }
11973
+ meta: { error: errorMessage$3(err) }
11974
11974
  });
11975
11975
  }
11976
11976
  }
@@ -12045,7 +12045,7 @@ var MirrorRowWriter = class MirrorRowWriter {
12045
12045
  try {
12046
12046
  await this.serialiseWrite(deviceId, () => this.writeRow(deviceId, settings, blob, "drain"));
12047
12047
  } catch (err) {
12048
- this.refuseDrain(deviceId, `the pending runtime-state write failed: ${errorMessage$2(err)}`, err);
12048
+ this.refuseDrain(deviceId, `the pending runtime-state write failed: ${errorMessage$3(err)}`, err);
12049
12049
  }
12050
12050
  }
12051
12051
  /** A drain that cannot vouch for the row: still owed (re-armed on release), logged, refused. */
@@ -12246,6 +12246,11 @@ var CommandHolds = class {
12246
12246
  isHolding(deviceId, capName) {
12247
12247
  return (this.held.get(deviceId)?.get(capName)?.size ?? 0) > 0;
12248
12248
  }
12249
+ /** Is any field of any cap of the device still held? (D1062: the command burst stops when this is false.) */
12250
+ isHoldingDevice(deviceId) {
12251
+ for (const fields of this.held.get(deviceId)?.values() ?? []) if (fields.size > 0) return true;
12252
+ return false;
12253
+ }
12249
12254
  /** Forget a removed device's holds. */
12250
12255
  clearDevice(deviceId) {
12251
12256
  this.held.delete(deviceId);
@@ -12318,13 +12323,14 @@ var CommandHolds = class {
12318
12323
  */
12319
12324
  var RUNNING_STATE_CAP = "running-state";
12320
12325
  var SEED_REFUSAL_MESSAGE = "runtime-state row unreadable — native write refused until it reads";
12321
- function errorMessage$1(err) {
12326
+ function errorMessage$2(err) {
12322
12327
  return err instanceof Error ? err.message : String(err);
12323
12328
  }
12324
12329
  var DeviceStateMirror = class {
12325
12330
  ctx;
12326
12331
  policyFor;
12327
12332
  transitionTap = null;
12333
+ reportTap = null;
12328
12334
  /**
12329
12335
  * Hub-side mirror of every device's cap-keyed NATIVE runtime state — what the
12330
12336
  * provider wrote. Key: deviceId. Value: per-cap slice map. Empty by default —
@@ -12385,6 +12391,10 @@ var DeviceStateMirror = class {
12385
12391
  setTransitionTap(tap) {
12386
12392
  this.transitionTap = tap;
12387
12393
  }
12394
+ /** Set once by the device-manager: told of every native slice reported, before the no-change check (D1062). */
12395
+ setReportTap(tap) {
12396
+ this.reportTap = tap;
12397
+ }
12388
12398
  /**
12389
12399
  * Hold what a command leads to: the effective slice shows it at once (and
12390
12400
  * `DeviceStateChanged` carries it), the stored, persisted and recorded slice
@@ -12397,6 +12407,10 @@ var DeviceStateMirror = class {
12397
12407
  releaseCommand(token, reason) {
12398
12408
  this.holds.release(token, reason);
12399
12409
  }
12410
+ /** Whether any command hold on the device is still unconfirmed (D1062). */
12411
+ isHoldingDevice(deviceId) {
12412
+ return this.holds.isHoldingDevice(deviceId);
12413
+ }
12400
12414
  /** Stop the hold timers (shutdown). */
12401
12415
  disposeHolds() {
12402
12416
  this.holds.dispose();
@@ -12421,6 +12435,7 @@ var DeviceStateMirror = class {
12421
12435
  * a SQLite commit.
12422
12436
  */
12423
12437
  applySingleCapUpdate(deviceId, capName, slice) {
12438
+ this.reportTap?.(deviceId, capName);
12424
12439
  let perCap = this.stateMirror.get(deviceId);
12425
12440
  if (!perCap) {
12426
12441
  perCap = /* @__PURE__ */ new Map();
@@ -12686,7 +12701,7 @@ var DeviceStateMirror = class {
12686
12701
  await this.ensureRowRead(deviceId, settings);
12687
12702
  return null;
12688
12703
  } catch (err) {
12689
- return refused("row-unreadable", `device ${deviceId}: ${errorMessage$1(err)}`);
12704
+ return refused("row-unreadable", `device ${deviceId}: ${errorMessage$2(err)}`);
12690
12705
  }
12691
12706
  }
12692
12707
  readRowOnce(deviceId, settings) {
@@ -12700,7 +12715,7 @@ var DeviceStateMirror = class {
12700
12715
  this.seedRefusalLogged.add(deviceId);
12701
12716
  this.ctx.logger.warn(SEED_REFUSAL_MESSAGE, {
12702
12717
  tags: { deviceId },
12703
- meta: { error: errorMessage$1(err) }
12718
+ meta: { error: errorMessage$2(err) }
12704
12719
  });
12705
12720
  }
12706
12721
  throw err;
@@ -12734,7 +12749,7 @@ var DeviceStateMirror = class {
12734
12749
  meta: {
12735
12750
  cap: op.cap,
12736
12751
  owner: op.owner,
12737
- error: errorMessage$1(err)
12752
+ error: errorMessage$2(err)
12738
12753
  }
12739
12754
  };
12740
12755
  if (rollback()) {
@@ -13105,6 +13120,93 @@ function pipeReducer(prev, fn) {
13105
13120
  return fn(prev);
13106
13121
  }
13107
13122
  //#endregion
13123
+ //#region src/kernel/command-follow-up.ts
13124
+ /**
13125
+ * The command follow-up (D1062): the work a device command waits for before
13126
+ * its caller hears the answer.
13127
+ *
13128
+ * The D1022 seams that observe a command (the hub tRPC mount, the UDS parent,
13129
+ * an in-process hub addon's `ctx.api`) also await this hook once the
13130
+ * provider's call settled — the hub's state-refresh scheduler re-reads the
13131
+ * device there, so the command returns after the real state was pushed.
13132
+ *
13133
+ * Unlike the observation (telemetry, D8) this one is awaited, but it is never
13134
+ * a gate: a follow-up that throws is swallowed here, and the call's own result
13135
+ * or error is what the caller gets. Cost when nothing is registered: one
13136
+ * undefined check (D181).
13137
+ */
13138
+ /** The one follow-up of this process (the hub's device-manager installs it). */
13139
+ var CommandFollowUpRegistry = class {
13140
+ handler = null;
13141
+ /** Install (or, with `null`, remove) the follow-up. Returns the uninstall. */
13142
+ set(handler) {
13143
+ this.handler = handler;
13144
+ return () => {
13145
+ if (this.handler === handler) this.handler = null;
13146
+ };
13147
+ }
13148
+ /** Run the follow-up for a settled command. Never throws. */
13149
+ async run(target, outcome) {
13150
+ const handler = this.handler;
13151
+ if (handler === null) return;
13152
+ try {
13153
+ await handler(target, outcome);
13154
+ } catch {}
13155
+ }
13156
+ };
13157
+ var registry$3;
13158
+ /** The process-wide registry. */
13159
+ function getCommandFollowUpRegistry() {
13160
+ registry$3 ??= new CommandFollowUpRegistry();
13161
+ return registry$3;
13162
+ }
13163
+ /** Test seam: forget the handler. */
13164
+ function __resetCommandFollowUpRegistryForTests() {
13165
+ registry$3 = void 0;
13166
+ }
13167
+ /** The target of a call when it is a device command naming a device, else `null`. */
13168
+ function commandFollowUpTarget(capName, method, deviceId) {
13169
+ if (deviceId === void 0 || !Number.isInteger(deviceId)) return null;
13170
+ if (!isCommand(capName, method)) return null;
13171
+ return {
13172
+ deviceId,
13173
+ capName,
13174
+ method
13175
+ };
13176
+ }
13177
+ /** The `deviceId` an args object names, or `undefined`. */
13178
+ function deviceIdOfArgs(args) {
13179
+ if (args === null || typeof args !== "object" || Array.isArray(args)) return void 0;
13180
+ const deviceId = Reflect.get(args, "deviceId");
13181
+ return typeof deviceId === "number" && Number.isInteger(deviceId) ? deviceId : void 0;
13182
+ }
13183
+ /**
13184
+ * Await `result`, then the follow-up, then answer with `result` — its value, or
13185
+ * its error rethrown. Without a follow-up or a target, `result` is returned
13186
+ * untouched.
13187
+ */
13188
+ function withCommandFollowUp(followUp, target, result) {
13189
+ if (followUp === void 0 || target === null) return result;
13190
+ return settleThenFollowUp(followUp, target, result);
13191
+ }
13192
+ async function settleThenFollowUp(followUp, target, result) {
13193
+ let value;
13194
+ try {
13195
+ value = await result;
13196
+ } catch (err) {
13197
+ await runCommandFollowUp(followUp, target, "failed");
13198
+ throw err;
13199
+ }
13200
+ await runCommandFollowUp(followUp, target, "ok");
13201
+ return value;
13202
+ }
13203
+ /** Run `followUp` for a settled command, swallowing its failure. */
13204
+ async function runCommandFollowUp(followUp, target, outcome) {
13205
+ try {
13206
+ await followUp(target, outcome);
13207
+ } catch {}
13208
+ }
13209
+ //#endregion
13108
13210
  //#region src/kernel/command-observation.ts
13109
13211
  /** Fan-out of command observations to the subscribers of this process. */
13110
13212
  var CommandObserverRegistry = class {
@@ -13125,15 +13227,15 @@ var CommandObserverRegistry = class {
13125
13227
  } catch {}
13126
13228
  }
13127
13229
  };
13128
- var registry$1;
13230
+ var registry$2;
13129
13231
  /** The process-wide registry. */
13130
13232
  function getCommandObserverRegistry() {
13131
- registry$1 ??= new CommandObserverRegistry();
13132
- return registry$1;
13233
+ registry$2 ??= new CommandObserverRegistry();
13234
+ return registry$2;
13133
13235
  }
13134
13236
  /** Test seam: forget every subscriber. */
13135
13237
  function __resetCommandObserverRegistryForTests() {
13136
- registry$1 = void 0;
13238
+ registry$2 = void 0;
13137
13239
  }
13138
13240
  function isRecord(value) {
13139
13241
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -13244,18 +13346,45 @@ function commandObserverLink(options) {
13244
13346
  actor: addonCommandActor(options.callerAddonId, readCommandOrigin(op.context)),
13245
13347
  outcome
13246
13348
  });
13349
+ const target = commandFollowUpTarget(capName, method, deviceIdOfArgs(op.input));
13350
+ const followUp = options.followUp;
13351
+ if (followUp === void 0 || target === null) {
13352
+ const sub = downstream.subscribe({
13353
+ next: (value) => observer.next(value),
13354
+ error: (err) => {
13355
+ settled.reject(err);
13356
+ observer.error(err);
13357
+ },
13358
+ complete: () => {
13359
+ settled.resolve();
13360
+ observer.complete();
13361
+ }
13362
+ });
13363
+ return () => sub.unsubscribe();
13364
+ }
13365
+ const answered = [];
13366
+ let closed = false;
13247
13367
  const sub = downstream.subscribe({
13248
- next: (value) => observer.next(value),
13368
+ next: (value) => void answered.push(value),
13249
13369
  error: (err) => {
13250
13370
  settled.reject(err);
13251
- observer.error(err);
13371
+ runCommandFollowUp(followUp, target, "failed").then(() => {
13372
+ if (!closed) observer.error(err);
13373
+ });
13252
13374
  },
13253
13375
  complete: () => {
13254
13376
  settled.resolve();
13255
- observer.complete();
13377
+ runCommandFollowUp(followUp, target, "ok").then(() => {
13378
+ if (closed) return;
13379
+ for (const value of answered) observer.next(value);
13380
+ observer.complete();
13381
+ });
13256
13382
  }
13257
13383
  });
13258
- return () => sub.unsubscribe();
13384
+ return () => {
13385
+ closed = true;
13386
+ sub.unsubscribe();
13387
+ };
13259
13388
  });
13260
13389
  };
13261
13390
  }
@@ -13369,11 +13498,11 @@ var CommandHoldOverrideRegistry = class {
13369
13498
  }
13370
13499
  }
13371
13500
  };
13372
- var registry;
13501
+ var registry$1;
13373
13502
  /** The process-wide registry. */
13374
13503
  function getCommandHoldOverrideRegistry() {
13375
- registry ??= new CommandHoldOverrideRegistry();
13376
- return registry;
13504
+ registry$1 ??= new CommandHoldOverrideRegistry();
13505
+ return registry$1;
13377
13506
  }
13378
13507
  //#endregion
13379
13508
  //#region src/builtins/device-manager/command-holds-wiring.ts
@@ -13417,6 +13546,525 @@ function startCommandHolds(deps) {
13417
13546
  deps.mirror.disposeHolds();
13418
13547
  };
13419
13548
  }
13549
+ //#endregion
13550
+ //#region src/kernel/state-refresh-policies.ts
13551
+ /** The cap a policy is stated on. */
13552
+ var STATE_REFRESH_CAP = "device-state-refresh";
13553
+ /** The source key of an in-process registration. */
13554
+ var IN_PROCESS_REFRESH_SOURCE = "in-process";
13555
+ /** The source key of a forked child's registrations. */
13556
+ function childRefreshSource(childId) {
13557
+ return `child:${childId}`;
13558
+ }
13559
+ /** The policies a child's cap descriptors carry, one entry per device. */
13560
+ function childStateRefreshEntries(childId, caps) {
13561
+ const out = [];
13562
+ for (const cap of caps) {
13563
+ if (cap.capName !== "device-state-refresh") continue;
13564
+ if (cap.deviceId === void 0 || cap.stateRefresh === void 0) continue;
13565
+ out.push({
13566
+ deviceId: cap.deviceId,
13567
+ addonId: cap.addonId ?? childId,
13568
+ policy: cap.stateRefresh
13569
+ });
13570
+ }
13571
+ return out;
13572
+ }
13573
+ var StateRefreshPolicyRegistry = class {
13574
+ bySource = /* @__PURE__ */ new Map();
13575
+ listeners = /* @__PURE__ */ new Set();
13576
+ /** Record (or replace) one device's policy from `source`. */
13577
+ set(source, entry) {
13578
+ const perSource = new Map(this.bySource.get(source) ?? []);
13579
+ perSource.set(entry.deviceId, entry);
13580
+ this.bySource.set(source, perSource);
13581
+ this.changed();
13582
+ }
13583
+ /** Forget one device's policy from `source`. */
13584
+ delete(source, deviceId) {
13585
+ const perSource = this.bySource.get(source);
13586
+ if (perSource === void 0 || !perSource.has(deviceId)) return;
13587
+ const next = new Map(perSource);
13588
+ next.delete(deviceId);
13589
+ if (next.size === 0) this.bySource.delete(source);
13590
+ else this.bySource.set(source, next);
13591
+ this.changed();
13592
+ }
13593
+ /** Replace everything `source` reported with `entries` (an empty list forgets the source). */
13594
+ replaceSource(source, entries) {
13595
+ const had = this.bySource.has(source);
13596
+ if (entries.length === 0) {
13597
+ this.bySource.delete(source);
13598
+ if (had) this.changed();
13599
+ return;
13600
+ }
13601
+ this.bySource.set(source, new Map(entries.map((e) => [e.deviceId, e])));
13602
+ this.changed();
13603
+ }
13604
+ /** Every device's policy (a device registered by two sources keeps the first). */
13605
+ entries() {
13606
+ const seen = /* @__PURE__ */ new Map();
13607
+ for (const perSource of this.bySource.values()) for (const entry of perSource.values()) if (!seen.has(entry.deviceId)) seen.set(entry.deviceId, entry);
13608
+ return [...seen.values()];
13609
+ }
13610
+ /** One device's policy, or `undefined` when its provider did not migrate. */
13611
+ get(deviceId) {
13612
+ for (const perSource of this.bySource.values()) {
13613
+ const found = perSource.get(deviceId);
13614
+ if (found !== void 0) return found;
13615
+ }
13616
+ }
13617
+ subscribe(listener) {
13618
+ this.listeners.add(listener);
13619
+ return () => {
13620
+ this.listeners.delete(listener);
13621
+ };
13622
+ }
13623
+ changed() {
13624
+ for (const listener of this.listeners) try {
13625
+ listener();
13626
+ } catch {}
13627
+ }
13628
+ };
13629
+ var registry;
13630
+ /** The process-wide registry. */
13631
+ function getStateRefreshPolicyRegistry() {
13632
+ registry ??= new StateRefreshPolicyRegistry();
13633
+ return registry;
13634
+ }
13635
+ /** Test seam: forget every policy. */
13636
+ function __resetStateRefreshPolicyRegistryForTests() {
13637
+ registry = void 0;
13638
+ }
13639
+ //#endregion
13640
+ //#region src/builtins/device-manager/state-refresh-scheduler.ts
13641
+ /**
13642
+ * The state-refresh scheduler (D1062, amending D224): the core decides WHEN a
13643
+ * migrated provider re-reads a device; the provider only knows HOW.
13644
+ *
13645
+ * The policy each provider declared on its `device-state-refresh`
13646
+ * registration (`StateRefreshPolicyRegistry`) drives it. Devices are grouped
13647
+ * per integration instance (`addonId::integrationId`):
13648
+ *
13649
+ * - cadence: `effectiveRefreshIntervalMs` — the declared minimum, slowed (never
13650
+ * sped up) by the integration's own setting, no idle back-off;
13651
+ * `push: 'full'` is never scheduled. A batching integration (`batch: true`)
13652
+ * has ONE schedule for the group — one due time, one read of every device
13653
+ * per interval; a device that registers later joins the group's next tick.
13654
+ * A non-batching integration keeps one schedule per device;
13655
+ * - command (`onCommand`, awaited by the D1022 seams): a polled device is read
13656
+ * at once and the command returns after it, then read again at ~3 s and
13657
+ * ~10 s while a D1061 hold on it is still pending; a push device waits
13658
+ * `PUSH_CONFIRM_WINDOW_MS` for the confirming push and reads once if none
13659
+ * came. These reads are per device and never move a batched group's schedule;
13660
+ * - push health: silence past `heartbeatMs` reads the integration, asks it to
13661
+ * resubscribe and reads again; a new `connectionEpoch` reads everything.
13662
+ *
13663
+ * Reads of one device are serialized: each starts after the previous one on
13664
+ * that device ended. A scheduled tick that finds its last read still running
13665
+ * is skipped (debug line); a command waits for the read in flight at most
13666
+ * `COMMAND_WAIT_BOUND_MS`, then reads its own device (debug line). A refresh
13667
+ * failure is a warn line per device and never fails a command.
13668
+ */
13669
+ /** The longest a command waits for a read already in flight on its device. */
13670
+ var COMMAND_WAIT_BOUND_MS = 5e3;
13671
+ function groupKeyOf(entry) {
13672
+ return `${entry.addonId}::${entry.policy.integrationId}`;
13673
+ }
13674
+ function errorMessage$1(err) {
13675
+ return err instanceof Error ? err.message : String(err);
13676
+ }
13677
+ var StateRefreshScheduler = class {
13678
+ deps;
13679
+ devices = /* @__PURE__ */ new Map();
13680
+ groups = /* @__PURE__ */ new Map();
13681
+ unsubscribe;
13682
+ disposed = false;
13683
+ constructor(deps) {
13684
+ this.deps = deps;
13685
+ this.unsubscribe = deps.policies.subscribe(() => this.reconcile());
13686
+ this.reconcile();
13687
+ }
13688
+ /** The command follow-up (awaited by the D1022 seams; never throws). */
13689
+ onCommand = async (target, outcome) => {
13690
+ const device = this.devices.get(target.deviceId);
13691
+ if (device === void 0 || this.disposed) return;
13692
+ device.lastCommandAt = Date.now();
13693
+ this.cancelFollowUps(device);
13694
+ const { policy } = device.entry;
13695
+ if (policy.push !== "none") {
13696
+ this.armPushWindow(target.deviceId, device);
13697
+ return;
13698
+ }
13699
+ this.deps.logger.debug("state refresh after command", {
13700
+ tags: { deviceId: target.deviceId },
13701
+ meta: {
13702
+ capName: target.capName,
13703
+ method: target.method,
13704
+ outcome
13705
+ }
13706
+ });
13707
+ await this.runRefresh([target.deviceId], "command", COMMAND_WAIT_BOUND_MS);
13708
+ if (!policy.batch) {
13709
+ device.dueAt = Date.now() + effectiveRefreshIntervalMs(policy);
13710
+ this.armSchedule(groupKeyOf(device.entry));
13711
+ }
13712
+ this.armBurst(target.deviceId, device);
13713
+ };
13714
+ /** A state report reached the mirror for `deviceId` (push or read). */
13715
+ onReport(deviceId) {
13716
+ const device = this.devices.get(deviceId);
13717
+ if (device === void 0) return;
13718
+ const now = Date.now();
13719
+ device.lastReportAt = now;
13720
+ const group = this.groups.get(groupKeyOf(device.entry));
13721
+ if (group !== void 0) group.lastReportAt = now;
13722
+ }
13723
+ dispose() {
13724
+ this.disposed = true;
13725
+ this.unsubscribe();
13726
+ for (const device of this.devices.values()) this.cancelFollowUps(device);
13727
+ for (const group of this.groups.values()) this.clearGroupTimers(group);
13728
+ this.devices.clear();
13729
+ this.groups.clear();
13730
+ }
13731
+ reconcile() {
13732
+ if (this.disposed) return;
13733
+ const now = Date.now();
13734
+ const current = new Map(this.deps.policies.entries().map((e) => [e.deviceId, e]));
13735
+ for (const [deviceId, device] of this.devices) {
13736
+ if (current.has(deviceId)) continue;
13737
+ this.cancelFollowUps(device);
13738
+ this.devices.delete(deviceId);
13739
+ }
13740
+ const reconnected = /* @__PURE__ */ new Set();
13741
+ for (const entry of current.values()) {
13742
+ const existing = this.devices.get(entry.deviceId);
13743
+ const interval = effectiveRefreshIntervalMs(entry.policy);
13744
+ if (existing === void 0) this.devices.set(entry.deviceId, {
13745
+ entry,
13746
+ dueAt: now + interval,
13747
+ lastReportAt: now,
13748
+ lastCommandAt: 0,
13749
+ inFlight: null,
13750
+ scheduledInFlight: null,
13751
+ burst: [],
13752
+ pushWindow: null
13753
+ });
13754
+ else {
13755
+ if (effectiveRefreshIntervalMs(existing.entry.policy) !== interval) existing.dueAt = now + interval;
13756
+ existing.entry = entry;
13757
+ }
13758
+ if (this.noteEpoch(entry)) reconnected.add(groupKeyOf(entry));
13759
+ }
13760
+ this.rebuildGroups(now);
13761
+ for (const key of reconnected) {
13762
+ this.deps.logger.info("state refresh: integration reconnected, reading every device", { meta: { group: key } });
13763
+ this.refreshGroup(key, "schedule");
13764
+ }
13765
+ }
13766
+ /** Track the group's connection epoch; `true` when it moved past a known one. */
13767
+ noteEpoch(entry) {
13768
+ const epoch = entry.policy.connectionEpoch;
13769
+ if (epoch === void 0) return false;
13770
+ const key = groupKeyOf(entry);
13771
+ const group = this.groups.get(key);
13772
+ if (group === void 0) return false;
13773
+ const previous = group.epoch;
13774
+ if (previous === void 0 || epoch > previous) group.epoch = epoch;
13775
+ return previous !== void 0 && epoch > previous;
13776
+ }
13777
+ rebuildGroups(now) {
13778
+ const members = /* @__PURE__ */ new Map();
13779
+ for (const [deviceId, device] of this.devices) {
13780
+ const key = groupKeyOf(device.entry);
13781
+ const set = members.get(key) ?? /* @__PURE__ */ new Set();
13782
+ set.add(deviceId);
13783
+ members.set(key, set);
13784
+ }
13785
+ for (const [key, group] of this.groups) {
13786
+ if (members.has(key)) continue;
13787
+ this.clearGroupTimers(group);
13788
+ this.groups.delete(key);
13789
+ }
13790
+ for (const [key, devices] of members) {
13791
+ const existing = this.groups.get(key);
13792
+ if (existing === void 0) {
13793
+ const first = this.devices.get([...devices][0] ?? -1);
13794
+ const intervalMs = first === void 0 ? 0 : effectiveRefreshIntervalMs(first.entry.policy);
13795
+ this.groups.set(key, {
13796
+ key,
13797
+ devices,
13798
+ dueAt: now + intervalMs,
13799
+ intervalMs,
13800
+ scheduleTimer: null,
13801
+ heartbeatTimer: null,
13802
+ lastReportAt: now,
13803
+ epoch: first?.entry.policy.connectionEpoch
13804
+ });
13805
+ } else {
13806
+ existing.devices = devices;
13807
+ const policy = this.groupPolicy(existing);
13808
+ const intervalMs = policy === void 0 ? 0 : effectiveRefreshIntervalMs(policy);
13809
+ if (intervalMs !== existing.intervalMs) {
13810
+ existing.intervalMs = intervalMs;
13811
+ existing.dueAt = now + intervalMs;
13812
+ }
13813
+ }
13814
+ this.armSchedule(key);
13815
+ this.armHeartbeat(key);
13816
+ }
13817
+ }
13818
+ groupPolicy(group) {
13819
+ for (const deviceId of group.devices) {
13820
+ const device = this.devices.get(deviceId);
13821
+ if (device !== void 0) return device.entry.policy;
13822
+ }
13823
+ }
13824
+ armSchedule(key) {
13825
+ const group = this.groups.get(key);
13826
+ if (group === void 0 || this.disposed) return;
13827
+ if (group.scheduleTimer !== null) clearTimeout(group.scheduleTimer);
13828
+ group.scheduleTimer = null;
13829
+ const policy = this.groupPolicy(group);
13830
+ if (policy === void 0 || policy.push === "full") return;
13831
+ let earliest = Number.POSITIVE_INFINITY;
13832
+ if (policy.batch) earliest = group.dueAt;
13833
+ else for (const deviceId of group.devices) {
13834
+ const device = this.devices.get(deviceId);
13835
+ if (device !== void 0) earliest = Math.min(earliest, device.dueAt);
13836
+ }
13837
+ if (!Number.isFinite(earliest)) return;
13838
+ group.scheduleTimer = setTimeout(() => this.tick(key), Math.max(0, earliest - Date.now()));
13839
+ }
13840
+ tick(key) {
13841
+ const group = this.groups.get(key);
13842
+ if (group === void 0 || this.disposed) return;
13843
+ group.scheduleTimer = null;
13844
+ const policy = this.groupPolicy(group);
13845
+ if (policy?.batch === true) this.tickBatched(group, policy);
13846
+ else this.tickPerDevice(group);
13847
+ this.armSchedule(key);
13848
+ }
13849
+ /** One read of the whole group per interval, unless the last one still runs. */
13850
+ tickBatched(group, policy) {
13851
+ const now = Date.now();
13852
+ if (group.dueAt > now) return;
13853
+ group.dueAt = now + effectiveRefreshIntervalMs(policy);
13854
+ const ids = [...group.devices].filter((id) => this.devices.has(id));
13855
+ const running = ids.filter((id) => (this.devices.get(id)?.scheduledInFlight ?? null) !== null);
13856
+ if (running.length > 0) {
13857
+ for (const deviceId of running) this.logSkippedTick(deviceId);
13858
+ return;
13859
+ }
13860
+ if (ids.length > 0) this.runScheduled(ids);
13861
+ }
13862
+ tickPerDevice(group) {
13863
+ const now = Date.now();
13864
+ const due = [];
13865
+ for (const deviceId of group.devices) {
13866
+ const device = this.devices.get(deviceId);
13867
+ if (device === void 0 || device.dueAt > now) continue;
13868
+ device.dueAt = now + effectiveRefreshIntervalMs(device.entry.policy);
13869
+ if (device.inFlight !== null) {
13870
+ this.logSkippedTick(deviceId);
13871
+ continue;
13872
+ }
13873
+ due.push(deviceId);
13874
+ }
13875
+ for (const deviceId of due) this.runScheduled([deviceId]);
13876
+ }
13877
+ logSkippedTick(deviceId) {
13878
+ this.deps.logger.debug("state refresh skipped: a refresh is still in flight", { tags: { deviceId } });
13879
+ }
13880
+ /** A scheduled read, remembered on each device until it settles. */
13881
+ async runScheduled(deviceIds) {
13882
+ const run = this.runRefresh(deviceIds, "schedule");
13883
+ for (const deviceId of deviceIds) {
13884
+ const device = this.devices.get(deviceId);
13885
+ if (device !== void 0) device.scheduledInFlight = run;
13886
+ }
13887
+ await run;
13888
+ for (const deviceId of deviceIds) {
13889
+ const device = this.devices.get(deviceId);
13890
+ if (device !== void 0 && device.scheduledInFlight === run) device.scheduledInFlight = null;
13891
+ }
13892
+ }
13893
+ armBurst(deviceId, device) {
13894
+ if (!this.deps.holdsPending(deviceId)) return;
13895
+ const timers = [];
13896
+ let stopped = false;
13897
+ for (const offset of COMMAND_BURST_OFFSETS_MS) timers.push(setTimeout(() => {
13898
+ if (stopped || this.disposed) return;
13899
+ if (!this.deps.holdsPending(deviceId)) {
13900
+ stopped = true;
13901
+ this.deps.logger.debug("state refresh burst stopped: the command is confirmed", { tags: { deviceId } });
13902
+ return;
13903
+ }
13904
+ if (device.inFlight !== null) {
13905
+ this.deps.logger.debug("state refresh burst skipped: a refresh is still in flight", { tags: { deviceId } });
13906
+ return;
13907
+ }
13908
+ this.runRefresh([deviceId], "burst");
13909
+ }, offset));
13910
+ device.burst = timers;
13911
+ }
13912
+ armPushWindow(deviceId, device) {
13913
+ const commandAt = device.lastCommandAt;
13914
+ device.pushWindow = setTimeout(() => {
13915
+ device.pushWindow = null;
13916
+ if (this.disposed) return;
13917
+ if (device.lastReportAt > commandAt && !this.deps.holdsPending(deviceId)) {
13918
+ this.deps.logger.debug("state refresh not needed: the push confirmed the command", { tags: { deviceId } });
13919
+ return;
13920
+ }
13921
+ this.deps.logger.debug("state refresh: no confirming push within the window", {
13922
+ tags: { deviceId },
13923
+ meta: { windowMs: PUSH_CONFIRM_WINDOW_MS }
13924
+ });
13925
+ if (device.inFlight !== null) return;
13926
+ this.runRefresh([deviceId], "command");
13927
+ }, PUSH_CONFIRM_WINDOW_MS);
13928
+ }
13929
+ cancelFollowUps(device) {
13930
+ for (const timer of device.burst) clearTimeout(timer);
13931
+ device.burst = [];
13932
+ if (device.pushWindow !== null) clearTimeout(device.pushWindow);
13933
+ device.pushWindow = null;
13934
+ }
13935
+ armHeartbeat(key) {
13936
+ const group = this.groups.get(key);
13937
+ if (group === void 0 || this.disposed) return;
13938
+ if (group.heartbeatTimer !== null) clearTimeout(group.heartbeatTimer);
13939
+ group.heartbeatTimer = null;
13940
+ const policy = this.groupPolicy(group);
13941
+ if (policy === void 0 || policy.push === "none" || policy.heartbeatMs === void 0) return;
13942
+ const heartbeatMs = policy.heartbeatMs;
13943
+ const wait = Math.max(0, group.lastReportAt + heartbeatMs - Date.now());
13944
+ group.heartbeatTimer = setTimeout(() => {
13945
+ group.heartbeatTimer = null;
13946
+ if (this.disposed) return;
13947
+ if (Date.now() - group.lastReportAt >= heartbeatMs) this.onSilence(key, heartbeatMs);
13948
+ else this.armHeartbeat(key);
13949
+ }, wait);
13950
+ }
13951
+ async onSilence(key, heartbeatMs) {
13952
+ const group = this.groups.get(key);
13953
+ if (group === void 0) return;
13954
+ group.lastReportAt = Date.now();
13955
+ for (const deviceId of group.devices) this.deps.logger.warn("state refresh: no push within the heartbeat, reading and resubscribing", {
13956
+ tags: { deviceId },
13957
+ meta: { heartbeatMs }
13958
+ });
13959
+ await this.refreshGroup(key, "schedule");
13960
+ const route = [...group.devices][0];
13961
+ if (route !== void 0) try {
13962
+ await this.deps.resubscribe(route);
13963
+ } catch (err) {
13964
+ this.deps.logger.warn("state refresh: resubscribe failed", {
13965
+ tags: { deviceId: route },
13966
+ meta: { error: errorMessage$1(err) }
13967
+ });
13968
+ }
13969
+ await this.refreshGroup(key, "schedule");
13970
+ this.armHeartbeat(key);
13971
+ }
13972
+ async refreshGroup(key, reason) {
13973
+ const group = this.groups.get(key);
13974
+ if (group === void 0) return;
13975
+ const ids = [...group.devices].filter((id) => this.devices.has(id));
13976
+ if (ids.length > 0) await this.refreshDevices(ids, reason);
13977
+ }
13978
+ /** One call for a batching integration, else one per device. */
13979
+ async refreshDevices(deviceIds, reason) {
13980
+ if (this.devices.get(deviceIds[0] ?? -1)?.entry.policy.batch === true) {
13981
+ await this.runRefresh(deviceIds, reason);
13982
+ return;
13983
+ }
13984
+ await Promise.all(deviceIds.map((id) => this.runRefresh([id], reason)));
13985
+ }
13986
+ /**
13987
+ * Read `deviceIds` once every read already queued on them ended — or, with
13988
+ * `waitBoundMs`, once that long passed (a debug line per device that was
13989
+ * still busy). The read becomes the devices' new tail.
13990
+ */
13991
+ async runRefresh(deviceIds, reason, waitBoundMs) {
13992
+ const route = deviceIds[0];
13993
+ if (route === void 0) return;
13994
+ const busy = [];
13995
+ const prior = [];
13996
+ for (const deviceId of deviceIds) {
13997
+ const tail = this.devices.get(deviceId)?.inFlight;
13998
+ if (tail === null || tail === void 0) continue;
13999
+ busy.push(deviceId);
14000
+ prior.push(tail);
14001
+ }
14002
+ const settled = this.afterPrior(prior, busy, waitBoundMs).then(() => this.deps.refresh(route, deviceIds, reason)).catch((err) => {
14003
+ for (const deviceId of deviceIds) this.deps.logger.warn("state refresh failed", {
14004
+ tags: { deviceId },
14005
+ meta: {
14006
+ reason,
14007
+ error: errorMessage$1(err)
14008
+ }
14009
+ });
14010
+ }).finally(() => {
14011
+ for (const deviceId of deviceIds) {
14012
+ const device = this.devices.get(deviceId);
14013
+ if (device !== void 0 && device.inFlight === settled) device.inFlight = null;
14014
+ }
14015
+ });
14016
+ for (const deviceId of deviceIds) {
14017
+ const device = this.devices.get(deviceId);
14018
+ if (device !== void 0) device.inFlight = settled;
14019
+ }
14020
+ await settled;
14021
+ }
14022
+ /** Resolves when every `prior` read ended, or after `waitBoundMs` (logged per busy device). */
14023
+ async afterPrior(prior, busy, waitBoundMs) {
14024
+ if (prior.length === 0) return;
14025
+ const all = Promise.all(prior).then(() => true);
14026
+ if (waitBoundMs === void 0) {
14027
+ await all;
14028
+ return;
14029
+ }
14030
+ let timer;
14031
+ const bound = new Promise((resolve) => {
14032
+ timer = setTimeout(() => resolve(false), waitBoundMs);
14033
+ });
14034
+ const ended = await Promise.race([all, bound]);
14035
+ if (timer !== void 0) clearTimeout(timer);
14036
+ if (ended) return;
14037
+ for (const deviceId of busy) this.deps.logger.debug("state refresh: stopped waiting for the read in flight", {
14038
+ tags: { deviceId },
14039
+ meta: { waitedMs: waitBoundMs }
14040
+ });
14041
+ }
14042
+ clearGroupTimers(group) {
14043
+ if (group.scheduleTimer !== null) clearTimeout(group.scheduleTimer);
14044
+ if (group.heartbeatTimer !== null) clearTimeout(group.heartbeatTimer);
14045
+ group.scheduleTimer = null;
14046
+ group.heartbeatTimer = null;
14047
+ }
14048
+ };
14049
+ //#endregion
14050
+ //#region src/builtins/device-manager/state-refresh-wiring.ts
14051
+ /** Start the scheduler; returns the stop. */
14052
+ function startStateRefresh(deps) {
14053
+ const scheduler = new StateRefreshScheduler({
14054
+ policies: deps.policies ?? getStateRefreshPolicyRegistry(),
14055
+ logger: deps.logger,
14056
+ holdsPending: (deviceId) => deps.mirror.isHoldingDevice(deviceId),
14057
+ refresh: deps.refresh,
14058
+ resubscribe: deps.resubscribe
14059
+ });
14060
+ deps.mirror.setReportTap((deviceId) => scheduler.onReport(deviceId));
14061
+ const uninstall = getCommandFollowUpRegistry().set(scheduler.onCommand);
14062
+ return () => {
14063
+ uninstall();
14064
+ deps.mirror.setReportTap(null);
14065
+ scheduler.dispose();
14066
+ };
14067
+ }
13420
14068
  var REDACTED = "***";
13421
14069
  var ROUTING_KEYS = new Set([
13422
14070
  "deviceId",
@@ -14337,6 +14985,7 @@ var DeviceManagerAddon = class extends BaseAddon {
14337
14985
  transitions = null;
14338
14986
  /** Unsubscribes the command hold (D1061). */
14339
14987
  stopCommandHolds = null;
14988
+ stopStateRefresh = null;
14340
14989
  /**
14341
14990
  * Removes the claimed-status overlay this addon installed on the capability
14342
14991
  * registry (D663, S3): `getStatus` of a claimed cap answers the mirror for
@@ -14687,6 +15336,24 @@ var DeviceManagerAddon = class extends BaseAddon {
14687
15336
  mirror: stateMirror,
14688
15337
  logger: this.ctx.logger.child("command-holds")
14689
15338
  });
15339
+ this.stopStateRefresh = startStateRefresh({
15340
+ mirror: stateMirror,
15341
+ logger: this.ctx.logger.child("state-refresh"),
15342
+ refresh: async (deviceId, deviceIds, reason) => {
15343
+ const api = this.ctx.api;
15344
+ if (api === void 0) throw new Error("ctx.api not ready");
15345
+ await api.deviceStateRefresh.refresh.mutate({
15346
+ deviceId,
15347
+ deviceIds: [...deviceIds],
15348
+ reason
15349
+ });
15350
+ },
15351
+ resubscribe: async (deviceId) => {
15352
+ const api = this.ctx.api;
15353
+ if (api === void 0) throw new Error("ctx.api not ready");
15354
+ await api.deviceStateRefresh.resubscribe.mutate({ deviceId });
15355
+ }
15356
+ });
14690
15357
  this.transitions = startDeviceTransitions({
14691
15358
  mirror: stateMirror,
14692
15359
  logger: this.ctx.logger.child("transitions"),
@@ -15085,6 +15752,8 @@ var DeviceManagerAddon = class extends BaseAddon {
15085
15752
  this.templateActions = null;
15086
15753
  await this.transitions?.stop();
15087
15754
  this.transitions = null;
15755
+ this.stopStateRefresh?.();
15756
+ this.stopStateRefresh = null;
15088
15757
  this.stopCommandHolds?.();
15089
15758
  this.stopCommandHolds = null;
15090
15759
  this.removalCleanupImpl?.dispose();
@@ -15101,4 +15770,4 @@ var DeviceManagerAddon = class extends BaseAddon {
15101
15770
  }
15102
15771
  };
15103
15772
  //#endregion
15104
- export { DeviceManagerAddon, DeviceManagerAddon as default, CommandObserverRegistry as a, commandActorFromContext as c, reportCommand as d, runObservedCommand as f, setWrapperActive as g, readDeviceOrThrow as h, getCommandHoldOverrideRegistry as i, commandObserverLink as l, createDeviceSettingsStore as m, mergeAggregates, childCommandHoldEntries as n, __resetCommandObserverRegistryForTests as o, observable as p, childHoldSource as r, addonCommandActor as s, IN_PROCESS_HOLD_SOURCE as t, getCommandObserverRegistry as u };
15773
+ export { deviceIdOfArgs as C, createDeviceSettingsStore as D, DeviceManagerAddon, DeviceManagerAddon as default, observable as E, readDeviceOrThrow as O, commandFollowUpTarget as S, withCommandFollowUp as T, getCommandObserverRegistry as _, childRefreshSource as a, CommandFollowUpRegistry as b, IN_PROCESS_HOLD_SOURCE as c, getCommandHoldOverrideRegistry as d, CommandObserverRegistry as f, commandObserverLink as g, commandActorFromContext as h, __resetStateRefreshPolicyRegistryForTests as i, setWrapperActive as k, childCommandHoldEntries as l, addonCommandActor as m, mergeAggregates, STATE_REFRESH_CAP as n, childStateRefreshEntries as o, __resetCommandObserverRegistryForTests as p, StateRefreshPolicyRegistry as r, getStateRefreshPolicyRegistry as s, IN_PROCESS_REFRESH_SOURCE as t, childHoldSource as u, reportCommand as v, getCommandFollowUpRegistry as w, __resetCommandFollowUpRegistryForTests as x, runObservedCommand as y };