@camstack/server 1.2.897 → 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 (114) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/api/trpc/cap-router-runtime.js +1 -0
  3. package/dist/api/trpc/generated-cap-mounts.js +2 -1
  4. package/dist/api/trpc/generated-cap-routers.js +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 +11 -10
  8. package/system/dist/addon-runner.js +207 -13
  9. package/system/dist/addon-runner.mjs +207 -13
  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 +14 -11
  25. package/system/dist/builtins/composer/composer.addon.mjs +11 -8
  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 +170 -14
  29. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +169 -13
  30. package/system/dist/builtins/core-blocks/migrations/automation-confirmed-view.d.ts +23 -0
  31. package/system/dist/builtins/core-blocks/migrations/index.d.ts +1 -0
  32. package/system/dist/builtins/core-blocks/migrations/pump-cycle-split.d.ts +1 -0
  33. package/system/dist/builtins/device-history/device-history.addon.js +10 -9
  34. package/system/dist/builtins/device-history/device-history.addon.mjs +10 -9
  35. package/system/dist/builtins/device-manager/command-holds-wiring.d.ts +22 -0
  36. package/system/dist/builtins/device-manager/command-holds.d.ts +77 -0
  37. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +3 -0
  38. package/system/dist/builtins/device-manager/device-manager.addon.js +1078 -41
  39. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1062 -42
  40. package/system/dist/builtins/device-manager/device-state-mirror.d.ts +42 -9
  41. package/system/dist/builtins/device-manager/state-refresh-scheduler.d.ts +92 -0
  42. package/system/dist/builtins/device-manager/state-refresh-wiring.d.ts +23 -0
  43. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  44. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  45. package/system/dist/builtins/keychain/index.js +4 -4
  46. package/system/dist/builtins/keychain/index.mjs +4 -4
  47. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  48. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  49. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  50. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  51. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  52. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  53. package/system/dist/builtins/loki-logging/index.js +1 -1
  54. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  55. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  56. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  57. package/system/dist/builtins/platform-probe/index.js +1 -1
  58. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  59. package/system/dist/builtins/record-entries/index.js +1 -1
  60. package/system/dist/builtins/record-entries/index.mjs +1 -1
  61. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  62. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  63. package/system/dist/builtins/shared/device-state-changed.d.ts +8 -0
  64. package/system/dist/builtins/snapshot/index.js +1 -1
  65. package/system/dist/builtins/snapshot/index.mjs +1 -1
  66. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  67. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  68. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  69. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  70. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  71. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  72. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  73. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  74. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  75. package/system/dist/builtins/system-config/system-config.addon.mjs +284 -284
  76. package/system/dist/builtins/winston-logging/index.js +1 -1
  77. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  78. package/system/dist/{capture-engine-Bjgs__i9.mjs → capture-engine-BcD6iCZM.mjs} +37 -2
  79. package/system/dist/{capture-engine-D1rjl2dW.js → capture-engine-LHKTf-nM.js} +48 -1
  80. package/system/dist/{composition-sources-B727nlA0.mjs → composition-sources-C3ARJk2g.mjs} +2 -21
  81. package/system/dist/{composition-sources-CF2-u58e.js → composition-sources-DNUDbuXy.js} +1 -32
  82. package/system/dist/{constants-DaR1SUh7.js → constants-dL8fl9aI.js} +1 -1
  83. package/system/dist/{constants-BF309c_I.mjs → constants-er38mZOb.mjs} +1 -1
  84. package/system/dist/{device-ca-DT1hYtdW.mjs → device-ca-Ccz5olgH.mjs} +1 -1
  85. package/system/dist/{device-ca-BqcX5_f2.js → device-ca-KWa6uJRU.js} +1 -1
  86. package/system/dist/{dist-DorY_sjS.mjs → dist-DBanWvHF.mjs} +819 -54
  87. package/system/dist/{dist-BoEy9sm9.js → dist-DEAjZE_-.js} +848 -53
  88. package/system/dist/file-host-worker.js +1 -1
  89. package/system/dist/file-host-worker.mjs +1 -1
  90. package/system/dist/{hub-identity-CZ0nE3GK.mjs → hub-identity-CVv79TVO.mjs} +1 -1
  91. package/system/dist/{hub-identity-DH1rxUMD.js → hub-identity-Dy8ZSUuq.js} +1 -1
  92. package/system/dist/{hub-mdns-ciao-N0nL34fx.js → hub-mdns-ciao-C_XjO7YI.js} +2 -2
  93. package/system/dist/{hub-mdns-ciao-7HK57Vtx.mjs → hub-mdns-ciao-DtmIyWDL.mjs} +2 -2
  94. package/system/dist/index.js +96 -17
  95. package/system/dist/index.mjs +92 -19
  96. package/system/dist/kernel/cap-router-builder.d.ts +7 -0
  97. package/system/dist/kernel/command-follow-up.d.ts +33 -0
  98. package/system/dist/kernel/command-hold-overrides.d.ts +42 -0
  99. package/system/dist/kernel/command-observation.d.ts +3 -0
  100. package/system/dist/kernel/index.d.ts +3 -0
  101. package/system/dist/kernel/moleculer/child-cap-descriptors.d.ts +5 -0
  102. package/system/dist/kernel/moleculer/device-cap-proxy.d.ts +3 -1
  103. package/system/dist/kernel/state-refresh-policies.d.ts +53 -0
  104. package/system/dist/kernel/transport/child-cap-protocol.d.ts +11 -1
  105. package/system/dist/kernel/transport/local-child-registry.d.ts +14 -0
  106. package/system/dist/{legacy-integration-rows-door-CdAQlIvv.mjs → legacy-integration-rows-door-BL8T4lya.mjs} +1 -1
  107. package/system/dist/{legacy-integration-rows-door-BTfeULYt.js → legacy-integration-rows-door-DPInWtE6.js} +1 -1
  108. package/system/dist/{rename-composition-block-B1x-yK5U.js → rename-composition-block-BxzETYOf.js} +1 -1
  109. package/system/dist/{rename-composition-block-CIQjxBUa.mjs → rename-composition-block-Dgo-9-Ts.mjs} +1 -1
  110. package/system/dist/{restore-archive-Bj_gYmE9.mjs → restore-archive-BUtuNTe1.mjs} +82 -82
  111. package/system/dist/{restore-archive-B086o8pL.js → restore-archive-Zvx9sHZP.js} +1 -1
  112. package/system/dist/{wal-maintenance-MVIyxmu7.js → wal-maintenance-DS2IKwtK.js} +0 -0
  113. package/system/dist/{wal-maintenance-Dgfmi-Ao.mjs → wal-maintenance-cASt_sYy.mjs} +0 -0
  114. package/system/package.json +1 -1
@@ -1,7 +1,7 @@
1
- import { A as ConditionMirror, Al as isKeychainStoredField, Bi as isKernelDerivedFeature, Bs as capAppliesToDeviceKind, Co as resolveTemplateRef, Dl as isDeviceConfigCap, Dn as WORKLOAD_TRANSITION_CATEGORY, Do as runtimeStatePolicyFor, Eo as runtimeFieldUnit, Er as createDeviceExtensionProvider, Es as workloadTransition, Fl as isSecretMarkerLike, Gi as isWorkloadSettled, Hr as deviceOffersActions, It as MINUTES_PER_DAY, J as DEVICE_TEMPLATE_FILTERS, Kr as deviceStateCapability, Lo as settleDeviceFeatures, Ma as parseStreamParamsFormPatch, Ml as isSecretClear, No as searchRank, On as WorkloadStateSchema, Oo as sameIdentifiers, Pl as isSecretMarker, Pr as defineExtensionSlotProvider, Q as DEVICE_TEMPLATE_VALUES_CAP, Ql as secretTreeFromPaths, R as DAY_NAMES, Ri as isEmptyIdentifiers, Ta as normalizeUnit, Tl as isCommand$1, Ts as workloadCapability, U as DEVICE_IDENTIFIER_KEYS, Uc as SECRET_CLEAR, Uo as siteZoneKey, Vr as deviceManagerCapability, X as DEVICE_TEMPLATE_MAX_OUTPUT, Xr as enumerateItemArrayFields, Y as DEVICE_TEMPLATE_MAX_LENGTH, Yc as WELL_KNOWN_TAB_MAP, Yi as legacyAutoLinkIds, Yl as resolveSecretMarkers, Za as reconcileReportedFeatures, Zn as buildStreamParamsConfigSchema, Zr as enumerateSchemaFields, ai as extractSourceInfoFromMetadata, ar as checkDeviceAlias, at as DeviceTombstoneSchema, au as userError, cl as commandEffect, cn as STREAM_PROFILE_META, du as DeviceRole, ec as implementedMethodsOf$1, fu as DeviceType$1, hi as formatMinutes, hl as defineRecordKinds, hu as EventCategory$1, it as DeviceStatusSchema, iu as transformSecretWrite, ni as expandContainer, nl as auditedFields, nt as DeviceIdentifiersSchema, ot as DiscoveryProposalBodySchema, ou as vocabActionIdFor, pa as mergeIdentifiers, pc as BaseAddon, pu as errMsg$1, qr as deviceStatusCapability, ru as toSecretFieldView, s as ALL_CAPABILITY_DEFINITIONS, sl as collectZodSecretPaths$1, ta as locationIconKey, tr as canonicalIconKey, tu as sleep$2, ut as ExportNameRefusedError, uu as DeviceFeature, vi as generateDeviceAlias, vt as FieldClaimModeSchema, wa as normalizeTags, wi as identifierStrength, x as CAP_NAMES_WITH_STATUS, y as CAMERA_SWITCH_ORDER, yl as expandCapMethods$1, yt as FieldClaimSchema, zr as deviceExtensionCapability, zs as canonicalStoredDeviceType } from "../../dist-DorY_sjS.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-CIQjxBUa.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. */
@@ -12090,6 +12090,206 @@ var MirrorRowWriter = class MirrorRowWriter {
12090
12090
  }
12091
12091
  };
12092
12092
  //#endregion
12093
+ //#region src/builtins/device-manager/command-holds.ts
12094
+ function same(a, b) {
12095
+ return Object.is(a, b);
12096
+ }
12097
+ /** Does `reading` confirm `held`: equal, or a number within its tolerance? */
12098
+ function confirms(reading, held, tolerance) {
12099
+ if (same(reading, held)) return true;
12100
+ if (typeof reading !== "number" || typeof held !== "number" || tolerance <= 0) return false;
12101
+ return Math.abs(reading - held) <= tolerance + 1e-9;
12102
+ }
12103
+ function judge(reading, held) {
12104
+ if (confirms(reading, held.value, held.tolerance)) return "confirmed";
12105
+ if (held.stale.some((v) => same(v, reading))) return "stale";
12106
+ return "device-answered";
12107
+ }
12108
+ var CommandHolds = class {
12109
+ deps;
12110
+ /** device → cap → field → held value. */
12111
+ held = /* @__PURE__ */ new Map();
12112
+ armings = /* @__PURE__ */ new Map();
12113
+ seq = 0;
12114
+ constructor(deps) {
12115
+ this.deps = deps;
12116
+ }
12117
+ /**
12118
+ * Hold what a command leads to. A field the slice already holds is not held
12119
+ * (and a standing hold on it is dropped: the newer command wins). Returns the
12120
+ * token that `release` takes, or `null` when nothing is held.
12121
+ */
12122
+ arm(request) {
12123
+ const base = this.deps.baseSlice(request.deviceId, request.capName);
12124
+ if (base === null) {
12125
+ this.deps.logger.debug("command hold: the cap has no slice yet — nothing held", {
12126
+ tags: { deviceId: request.deviceId },
12127
+ meta: {
12128
+ cap: request.capName,
12129
+ method: request.method
12130
+ }
12131
+ });
12132
+ return null;
12133
+ }
12134
+ this.seq += 1;
12135
+ const token = this.seq;
12136
+ const fields = this.fieldsOf(request.deviceId, request.capName);
12137
+ let changed = false;
12138
+ let holding = false;
12139
+ for (const effect of request.effects) {
12140
+ const standing = fields.get(effect.field);
12141
+ const tolerance = effect.tolerance ?? 0;
12142
+ const reported = Object.hasOwn(base, effect.field) ? base[effect.field] : void 0;
12143
+ if (Object.hasOwn(base, effect.field) && confirms(reported, effect.value, tolerance)) {
12144
+ if (standing !== void 0) {
12145
+ fields.delete(effect.field);
12146
+ changed = true;
12147
+ }
12148
+ continue;
12149
+ }
12150
+ if (standing === void 0 || !same(standing.value, effect.value)) changed = true;
12151
+ const stale = standing === void 0 ? [reported] : [...standing.stale, standing.value];
12152
+ fields.set(effect.field, {
12153
+ value: effect.value,
12154
+ tolerance,
12155
+ stale,
12156
+ token
12157
+ });
12158
+ holding = true;
12159
+ }
12160
+ this.dropEmpty(request.deviceId, request.capName);
12161
+ this.forgetStaleArmings();
12162
+ if (holding) {
12163
+ const timer = setTimeout(() => this.release(token, "unconfirmed"), request.holdMs);
12164
+ timer.unref?.();
12165
+ this.armings.set(token, {
12166
+ token,
12167
+ deviceId: request.deviceId,
12168
+ capName: request.capName,
12169
+ method: request.method,
12170
+ holdMs: request.holdMs,
12171
+ timer
12172
+ });
12173
+ }
12174
+ if (changed) this.deps.reemit(request.deviceId, request.capName);
12175
+ return holding ? token : null;
12176
+ }
12177
+ /** End what `token` still holds — refused at once, or unconfirmed at the limit. */
12178
+ release(token, reason) {
12179
+ const arming = this.armings.get(token);
12180
+ if (arming === void 0) return;
12181
+ this.armings.delete(token);
12182
+ clearTimeout(arming.timer);
12183
+ const fields = this.held.get(arming.deviceId)?.get(arming.capName);
12184
+ if (fields === void 0) return;
12185
+ const dropped = [];
12186
+ for (const [field, held] of fields) {
12187
+ if (held.token !== token) continue;
12188
+ fields.delete(field);
12189
+ dropped.push(field);
12190
+ }
12191
+ if (dropped.length === 0) return;
12192
+ this.dropEmpty(arming.deviceId, arming.capName);
12193
+ const tags = { deviceId: arming.deviceId };
12194
+ const meta = {
12195
+ cap: arming.capName,
12196
+ method: arming.method,
12197
+ fields: dropped
12198
+ };
12199
+ if (reason === "unconfirmed" && arming.holdMs <= 1e4) this.deps.logger.debug("one-shot command hold ended", {
12200
+ tags,
12201
+ meta
12202
+ });
12203
+ else if (reason === "unconfirmed") this.deps.logger.warn("command hold reverted: the device did not confirm in time", {
12204
+ tags,
12205
+ meta
12206
+ });
12207
+ else this.deps.logger.info("command hold rolled back: the command was refused", {
12208
+ tags,
12209
+ meta
12210
+ });
12211
+ this.deps.reemit(arming.deviceId, arming.capName);
12212
+ }
12213
+ /**
12214
+ * The slice under the hold moved: keep each held field it still reports
12215
+ * stale, drop the ones it confirms or answers otherwise.
12216
+ */
12217
+ settle(deviceId, capName, base) {
12218
+ const fields = this.held.get(deviceId)?.get(capName);
12219
+ if (fields === void 0) return;
12220
+ for (const [field, held] of fields) {
12221
+ if (!Object.hasOwn(base, field)) continue;
12222
+ const reading = judge(base[field], held);
12223
+ if (reading === "stale") continue;
12224
+ fields.delete(field);
12225
+ if (reading === "device-answered") this.deps.logger.debug("command hold released: the device answered otherwise", {
12226
+ tags: { deviceId },
12227
+ meta: {
12228
+ cap: capName,
12229
+ field,
12230
+ reason: reading
12231
+ }
12232
+ });
12233
+ }
12234
+ this.dropEmpty(deviceId, capName);
12235
+ this.forgetStaleArmings();
12236
+ }
12237
+ /** `base` with the held values over it; `base` itself when nothing is held. */
12238
+ overlay(deviceId, capName, base) {
12239
+ const fields = this.held.get(deviceId)?.get(capName);
12240
+ if (fields === void 0 || fields.size === 0) return base;
12241
+ const out = { ...base };
12242
+ for (const [field, held] of fields) out[field] = held.value;
12243
+ return out;
12244
+ }
12245
+ /** Is any field of the cap held? */
12246
+ isHolding(deviceId, capName) {
12247
+ return (this.held.get(deviceId)?.get(capName)?.size ?? 0) > 0;
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
+ }
12254
+ /** Forget a removed device's holds. */
12255
+ clearDevice(deviceId) {
12256
+ this.held.delete(deviceId);
12257
+ for (const [token, arming] of this.armings) {
12258
+ if (arming.deviceId !== deviceId) continue;
12259
+ clearTimeout(arming.timer);
12260
+ this.armings.delete(token);
12261
+ }
12262
+ }
12263
+ /** Stop every timer (shutdown). */
12264
+ dispose() {
12265
+ for (const arming of this.armings.values()) clearTimeout(arming.timer);
12266
+ this.armings.clear();
12267
+ this.held.clear();
12268
+ }
12269
+ fieldsOf(deviceId, capName) {
12270
+ const perCap = this.held.get(deviceId) ?? /* @__PURE__ */ new Map();
12271
+ this.held.set(deviceId, perCap);
12272
+ const fields = perCap.get(capName) ?? /* @__PURE__ */ new Map();
12273
+ perCap.set(capName, fields);
12274
+ return fields;
12275
+ }
12276
+ dropEmpty(deviceId, capName) {
12277
+ const perCap = this.held.get(deviceId);
12278
+ if (perCap === void 0) return;
12279
+ if ((perCap.get(capName)?.size ?? 0) === 0) perCap.delete(capName);
12280
+ if (perCap.size === 0) this.held.delete(deviceId);
12281
+ }
12282
+ /** An arming whose fields were all confirmed or replaced holds nothing: stop its timer. */
12283
+ forgetStaleArmings() {
12284
+ for (const [token, arming] of this.armings) {
12285
+ const fields = this.held.get(arming.deviceId)?.get(arming.capName);
12286
+ if (fields !== void 0 && [...fields.values()].some((f) => f.token === token)) continue;
12287
+ clearTimeout(arming.timer);
12288
+ this.armings.delete(token);
12289
+ }
12290
+ }
12291
+ };
12292
+ //#endregion
12093
12293
  //#region src/builtins/device-manager/device-state-mirror.ts
12094
12294
  /**
12095
12295
  * Hub-side runtime-state mirror for the device-manager addon.
@@ -12123,13 +12323,14 @@ var MirrorRowWriter = class MirrorRowWriter {
12123
12323
  */
12124
12324
  var RUNNING_STATE_CAP = "running-state";
12125
12325
  var SEED_REFUSAL_MESSAGE = "runtime-state row unreadable — native write refused until it reads";
12126
- function errorMessage$1(err) {
12326
+ function errorMessage$2(err) {
12127
12327
  return err instanceof Error ? err.message : String(err);
12128
12328
  }
12129
12329
  var DeviceStateMirror = class {
12130
12330
  ctx;
12131
12331
  policyFor;
12132
12332
  transitionTap = null;
12333
+ reportTap = null;
12133
12334
  /**
12134
12335
  * Hub-side mirror of every device's cap-keyed NATIVE runtime state — what the
12135
12336
  * provider wrote. Key: deviceId. Value: per-cap slice map. Empty by default —
@@ -12138,6 +12339,8 @@ var DeviceStateMirror = class {
12138
12339
  stateMirror = /* @__PURE__ */ new Map();
12139
12340
  /** The claims and the merged view of every claimed cap (D663). */
12140
12341
  claims;
12342
+ /** Commanded values shown before the device confirms them (D1061). Memory only. */
12343
+ holds;
12141
12344
  /**
12142
12345
  * Devices whose CLAIMS are known: the row was read, or a loaded claims index
12143
12346
  * vouched that it names none (D447). This is a READ-path fact — what a
@@ -12168,6 +12371,14 @@ var DeviceStateMirror = class {
12168
12371
  schemaFor,
12169
12372
  emitSlice: (deviceId, capName, slice) => this.emitStateChanged(deviceId, capName, slice)
12170
12373
  });
12374
+ this.holds = new CommandHolds({
12375
+ logger: ctx.logger,
12376
+ baseSlice: (deviceId, capName) => this.baseSlice(deviceId, capName),
12377
+ reemit: (deviceId, capName) => {
12378
+ const base = this.baseSlice(deviceId, capName);
12379
+ if (base !== null) this.emitStateChanged(deviceId, capName, { ...base });
12380
+ }
12381
+ });
12171
12382
  this.writer = new MirrorRowWriter({
12172
12383
  logger: ctx.logger,
12173
12384
  policyFor,
@@ -12180,6 +12391,30 @@ var DeviceStateMirror = class {
12180
12391
  setTransitionTap(tap) {
12181
12392
  this.transitionTap = tap;
12182
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
+ }
12398
+ /**
12399
+ * Hold what a command leads to: the effective slice shows it at once (and
12400
+ * `DeviceStateChanged` carries it), the stored, persisted and recorded slice
12401
+ * does not change. Returns the token {@link releaseCommand} takes, or `null`.
12402
+ */
12403
+ holdCommand(request) {
12404
+ return this.holds.arm(request);
12405
+ }
12406
+ /** End a command's hold: refused (rolled back at once) or unconfirmed (at the limit). */
12407
+ releaseCommand(token, reason) {
12408
+ this.holds.release(token, reason);
12409
+ }
12410
+ /** Whether any command hold on the device is still unconfirmed (D1062). */
12411
+ isHoldingDevice(deviceId) {
12412
+ return this.holds.isHoldingDevice(deviceId);
12413
+ }
12414
+ /** Stop the hold timers (shutdown). */
12415
+ disposeHolds() {
12416
+ this.holds.dispose();
12417
+ }
12183
12418
  /** The native slice the mirror holds for `capName`, as a read-only view. */
12184
12419
  currentSlice(deviceId, capName) {
12185
12420
  return this.stateMirror.get(deviceId)?.get(capName);
@@ -12200,6 +12435,7 @@ var DeviceStateMirror = class {
12200
12435
  * a SQLite commit.
12201
12436
  */
12202
12437
  applySingleCapUpdate(deviceId, capName, slice) {
12438
+ this.reportTap?.(deviceId, capName);
12203
12439
  let perCap = this.stateMirror.get(deviceId);
12204
12440
  if (!perCap) {
12205
12441
  perCap = /* @__PURE__ */ new Map();
@@ -12392,6 +12628,7 @@ var DeviceStateMirror = class {
12392
12628
  await this.seeding.get(deviceId)?.catch(() => void 0);
12393
12629
  await this.writer.forget(deviceId);
12394
12630
  this.stateMirror.delete(deviceId);
12631
+ this.holds.clearDevice(deviceId);
12395
12632
  this.workloadTransitions.forget(deviceId);
12396
12633
  this.claims.clearDevice(deviceId);
12397
12634
  this.seeded.delete(deviceId);
@@ -12464,7 +12701,7 @@ var DeviceStateMirror = class {
12464
12701
  await this.ensureRowRead(deviceId, settings);
12465
12702
  return null;
12466
12703
  } catch (err) {
12467
- return refused("row-unreadable", `device ${deviceId}: ${errorMessage$1(err)}`);
12704
+ return refused("row-unreadable", `device ${deviceId}: ${errorMessage$2(err)}`);
12468
12705
  }
12469
12706
  }
12470
12707
  readRowOnce(deviceId, settings) {
@@ -12478,7 +12715,7 @@ var DeviceStateMirror = class {
12478
12715
  this.seedRefusalLogged.add(deviceId);
12479
12716
  this.ctx.logger.warn(SEED_REFUSAL_MESSAGE, {
12480
12717
  tags: { deviceId },
12481
- meta: { error: errorMessage$1(err) }
12718
+ meta: { error: errorMessage$2(err) }
12482
12719
  });
12483
12720
  }
12484
12721
  throw err;
@@ -12512,7 +12749,7 @@ var DeviceStateMirror = class {
12512
12749
  meta: {
12513
12750
  cap: op.cap,
12514
12751
  owner: op.owner,
12515
- error: errorMessage$1(err)
12752
+ error: errorMessage$2(err)
12516
12753
  }
12517
12754
  };
12518
12755
  if (rollback()) {
@@ -12683,25 +12920,33 @@ var DeviceStateMirror = class {
12683
12920
  if (!raw) return true;
12684
12921
  return (typeof raw.lastProbedAt === "number" ? raw.lastProbedAt : 0) > 0;
12685
12922
  }
12686
- /** The EFFECTIVE slices of a device: native for an unclaimed cap, the merge
12687
- * for a claimed one (a held cap is not reported). */
12688
- snapshotForDevice(deviceId) {
12923
+ /** The slices of a device: native for an unclaimed cap, the merge for a
12924
+ * claimed one (a held cap is not reported) — and, in the `effective` view,
12925
+ * a commanded value over either (D1061). */
12926
+ snapshotForDevice(deviceId, view = "effective") {
12689
12927
  const out = {};
12690
12928
  for (const [k, v] of this.stateMirror.get(deviceId) ?? []) {
12691
12929
  if (this.claims.isClaimed(deviceId, k)) continue;
12692
- out[k] = { ...v };
12930
+ out[k] = this.viewOf(deviceId, k, v, view);
12693
12931
  }
12694
- for (const [k, v] of this.claims.visibleCaps(deviceId)) out[k] = { ...v };
12932
+ for (const [k, v] of this.claims.visibleCaps(deviceId)) out[k] = this.viewOf(deviceId, k, v, view);
12695
12933
  return out;
12696
12934
  }
12697
- /** One cap's EFFECTIVE slice, cloned. Null when the device has never written
12935
+ /** One cap's slice in `view`, cloned. Null when the device has never written
12698
12936
  * it — callers read that as "the cap has no state", never as an empty slice —
12699
12937
  * and null while a claim holds it. */
12700
- capSlice(deviceId, cap) {
12938
+ capSlice(deviceId, cap, view = "effective") {
12939
+ const base = this.baseSlice(deviceId, cap);
12940
+ return base === null ? null : this.viewOf(deviceId, cap, base, view);
12941
+ }
12942
+ /** What the device reported for the cap, or the claim's merge — never a hold. Not cloned. */
12943
+ baseSlice(deviceId, cap) {
12701
12944
  const visible = this.claims.visible(deviceId, cap);
12702
- if (visible !== void 0) return visible ? { ...visible } : null;
12703
- const raw = this.stateMirror.get(deviceId)?.get(cap);
12704
- return raw ? { ...raw } : null;
12945
+ if (visible !== void 0) return visible ? visible : null;
12946
+ return this.stateMirror.get(deviceId)?.get(cap) ?? null;
12947
+ }
12948
+ viewOf(deviceId, cap, base, view) {
12949
+ return view === "confirmed" ? { ...base } : { ...this.holds.overlay(deviceId, cap, base) };
12705
12950
  }
12706
12951
  /** The device's NATIVE slices — what the row stores under the cap names. */
12707
12952
  nativeSnapshotForDevice(deviceId) {
@@ -12713,10 +12958,10 @@ var DeviceStateMirror = class {
12713
12958
  }
12714
12959
  /** Whole-system mirror dump. Backs `deviceState.getAllSnapshots` — one
12715
12960
  * round-trip for a warm boot instead of N per-device calls. */
12716
- allSnapshots() {
12961
+ allSnapshots(view = "effective") {
12717
12962
  const out = {};
12718
12963
  const deviceIds = new Set([...this.stateMirror.keys(), ...this.claims.deviceIds()]);
12719
- for (const deviceId of deviceIds) out[String(deviceId)] = this.snapshotForDevice(deviceId);
12964
+ for (const deviceId of deviceIds) out[String(deviceId)] = this.snapshotForDevice(deviceId, view);
12720
12965
  return out;
12721
12966
  }
12722
12967
  /**
@@ -12745,17 +12990,21 @@ var DeviceStateMirror = class {
12745
12990
  }
12746
12991
  /** Remember a restored running bit so the first public merge does not emit a flip. */
12747
12992
  seedRunningFlip(deviceId) {
12748
- const slice = this.capSlice(deviceId, RUNNING_STATE_CAP);
12993
+ const slice = this.capSlice(deviceId, RUNNING_STATE_CAP, "confirmed");
12749
12994
  if (slice === null) return;
12750
12995
  const running = slice["running"];
12751
12996
  this.runningFlip.seed(deviceId, running === true || running === false ? running : null);
12752
12997
  }
12753
12998
  /**
12754
- * The PUBLIC event: exactly `{ deviceId, capName, slice }` for every device,
12755
- * claimed or not. The native shadow never rides here (D224) — see
12756
- * `emitNativeShadow`.
12999
+ * The PUBLIC event: `{ deviceId, capName, slice }` for every device, claimed
13000
+ * or not; `slice` is the EFFECTIVE slice. While a command hold changes it
13001
+ * (D1061), `confirmed` carries the slice without the hold — what history,
13002
+ * automations and the edge detectors below read. The native shadow of a
13003
+ * claim never rides here (D224) — see `emitNativeShadow`.
12757
13004
  */
12758
13005
  emitStateChanged(deviceId, capName, slice) {
13006
+ this.holds.settle(deviceId, capName, slice);
13007
+ const effective = this.holds.overlay(deviceId, capName, slice);
12759
13008
  if (capName === RUNNING_STATE_CAP) {
12760
13009
  const flip = this.runningFlip.note(deviceId, slice);
12761
13010
  if (flip !== null) this.ctx.eventBus.emit({
@@ -12782,10 +13031,15 @@ var DeviceStateMirror = class {
12782
13031
  id: deviceId
12783
13032
  },
12784
13033
  category: EventCategory$1.DeviceStateChanged,
12785
- data: {
13034
+ data: effective === slice ? {
12786
13035
  deviceId,
12787
13036
  capName,
12788
13037
  slice
13038
+ } : {
13039
+ deviceId,
13040
+ capName,
13041
+ slice: { ...effective },
13042
+ confirmed: slice
12789
13043
  }
12790
13044
  });
12791
13045
  }
@@ -12866,6 +13120,93 @@ function pipeReducer(prev, fn) {
12866
13120
  return fn(prev);
12867
13121
  }
12868
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
12869
13210
  //#region src/kernel/command-observation.ts
12870
13211
  /** Fan-out of command observations to the subscribers of this process. */
12871
13212
  var CommandObserverRegistry = class {
@@ -12886,15 +13227,15 @@ var CommandObserverRegistry = class {
12886
13227
  } catch {}
12887
13228
  }
12888
13229
  };
12889
- var registry;
13230
+ var registry$2;
12890
13231
  /** The process-wide registry. */
12891
13232
  function getCommandObserverRegistry() {
12892
- registry ??= new CommandObserverRegistry();
12893
- return registry;
13233
+ registry$2 ??= new CommandObserverRegistry();
13234
+ return registry$2;
12894
13235
  }
12895
13236
  /** Test seam: forget every subscriber. */
12896
13237
  function __resetCommandObserverRegistryForTests() {
12897
- registry = void 0;
13238
+ registry$2 = void 0;
12898
13239
  }
12899
13240
  function isRecord(value) {
12900
13241
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -13005,18 +13346,45 @@ function commandObserverLink(options) {
13005
13346
  actor: addonCommandActor(options.callerAddonId, readCommandOrigin(op.context)),
13006
13347
  outcome
13007
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;
13008
13367
  const sub = downstream.subscribe({
13009
- next: (value) => observer.next(value),
13368
+ next: (value) => void answered.push(value),
13010
13369
  error: (err) => {
13011
13370
  settled.reject(err);
13012
- observer.error(err);
13371
+ runCommandFollowUp(followUp, target, "failed").then(() => {
13372
+ if (!closed) observer.error(err);
13373
+ });
13013
13374
  },
13014
13375
  complete: () => {
13015
13376
  settled.resolve();
13016
- 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
+ });
13017
13382
  }
13018
13383
  });
13019
- return () => sub.unsubscribe();
13384
+ return () => {
13385
+ closed = true;
13386
+ sub.unsubscribe();
13387
+ };
13020
13388
  });
13021
13389
  };
13022
13390
  }
@@ -13074,6 +13442,629 @@ function runObservedCommand(sink, facts, call) {
13074
13442
  throw err;
13075
13443
  }
13076
13444
  }
13445
+ //#endregion
13446
+ //#region src/kernel/command-hold-overrides.ts
13447
+ /** The source key of an in-process registration. */
13448
+ var IN_PROCESS_HOLD_SOURCE = "in-process";
13449
+ /** The source key of a forked child's registrations. */
13450
+ function childHoldSource(childId) {
13451
+ return `child:${childId}`;
13452
+ }
13453
+ /** The options a child's cap descriptors carry, one entry per device cap. */
13454
+ function childCommandHoldEntries(caps) {
13455
+ const out = [];
13456
+ for (const cap of caps) {
13457
+ if (cap.deviceId === void 0 || cap.commandHolds === void 0) continue;
13458
+ out.push({
13459
+ deviceId: cap.deviceId,
13460
+ capName: cap.capName,
13461
+ commands: cap.commandHolds
13462
+ });
13463
+ }
13464
+ return out;
13465
+ }
13466
+ function keyOf$1(deviceId, capName) {
13467
+ return `${deviceId}|${capName}`;
13468
+ }
13469
+ var CommandHoldOverrideRegistry = class {
13470
+ bySource = /* @__PURE__ */ new Map();
13471
+ /** Record (or replace) one device cap's options from `source`. */
13472
+ set(source, entry) {
13473
+ const perSource = this.bySource.get(source) ?? /* @__PURE__ */ new Map();
13474
+ perSource.set(keyOf$1(entry.deviceId, entry.capName), entry.commands);
13475
+ this.bySource.set(source, perSource);
13476
+ }
13477
+ /** Forget one device cap's options from `source`. */
13478
+ delete(source, deviceId, capName) {
13479
+ const perSource = this.bySource.get(source);
13480
+ if (perSource === void 0) return;
13481
+ perSource.delete(keyOf$1(deviceId, capName));
13482
+ if (perSource.size === 0) this.bySource.delete(source);
13483
+ }
13484
+ /** Replace everything `source` reported with `entries` (an empty list forgets the source). */
13485
+ replaceSource(source, entries) {
13486
+ if (entries.length === 0) {
13487
+ this.bySource.delete(source);
13488
+ return;
13489
+ }
13490
+ this.bySource.set(source, new Map(entries.map((e) => [keyOf$1(e.deviceId, e.capName), e.commands])));
13491
+ }
13492
+ /** The options for a device cap, from whichever source registered it; `undefined` = default. */
13493
+ get(deviceId, capName) {
13494
+ const key = keyOf$1(deviceId, capName);
13495
+ for (const perSource of this.bySource.values()) {
13496
+ const found = perSource.get(key);
13497
+ if (found !== void 0) return found;
13498
+ }
13499
+ }
13500
+ };
13501
+ var registry$1;
13502
+ /** The process-wide registry. */
13503
+ function getCommandHoldOverrideRegistry() {
13504
+ registry$1 ??= new CommandHoldOverrideRegistry();
13505
+ return registry$1;
13506
+ }
13507
+ //#endregion
13508
+ //#region src/builtins/device-manager/command-holds-wiring.ts
13509
+ /**
13510
+ * Arms the command hold (D1061) from the D1022 command seams.
13511
+ *
13512
+ * Every device command the hub sees — its tRPC mount, the UDS parent for a
13513
+ * forked addon's `ctx.api`, an in-process addon's `ctx.api` — reaches the
13514
+ * process-wide observer registry BEFORE the call runs. Here each one resolves
13515
+ * what it leads to (the vocabulary's effects under the provider's option) on
13516
+ * the slice the device last reported, and the mirror holds it; a refused call
13517
+ * rolls the hold back at once.
13518
+ *
13519
+ * Telemetry in, never a gate (D8): a throw here costs the hold, never the call.
13520
+ */
13521
+ /** Subscribe the hold to the command observations; returns the unsubscribe. */
13522
+ function startCommandHolds(deps) {
13523
+ const optionsFor = deps.optionsFor ?? ((deviceId, capName) => getCommandHoldOverrideRegistry().get(deviceId, capName));
13524
+ const unsubscribe = getCommandObserverRegistry().subscribe((obs) => {
13525
+ try {
13526
+ const current = deps.mirror.capSlice(obs.deviceId, obs.capName, "confirmed") ?? void 0;
13527
+ const shown = deps.mirror.capSlice(obs.deviceId, obs.capName) ?? void 0;
13528
+ const option = optionsFor(obs.deviceId, obs.capName)?.[obs.method];
13529
+ const hold = resolveCommandHold(obs.capName, obs.method, obs.args, current, option, shown);
13530
+ if (hold === null) return;
13531
+ const token = deps.mirror.holdCommand({
13532
+ deviceId: obs.deviceId,
13533
+ capName: obs.capName,
13534
+ method: obs.method,
13535
+ effects: hold.effects,
13536
+ holdMs: hold.holdMs
13537
+ });
13538
+ if (token === null) return;
13539
+ obs.outcome?.catch(() => deps.mirror.releaseCommand(token, "refused"));
13540
+ } catch (err) {
13541
+ deps.logger.error(`command hold: arming ${obs.capName}.${obs.method} failed: ${err instanceof Error ? err.message : String(err)}`, { tags: { deviceId: obs.deviceId } });
13542
+ }
13543
+ });
13544
+ return () => {
13545
+ unsubscribe();
13546
+ deps.mirror.disposeHolds();
13547
+ };
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
+ }
13077
14068
  var REDACTED = "***";
13078
14069
  var ROUTING_KEYS = new Set([
13079
14070
  "deviceId",
@@ -13992,6 +14983,9 @@ var DeviceManagerAddon = class extends BaseAddon {
13992
14983
  stateMirrorImpl = null;
13993
14984
  /** The transition audit (D1022): command + mirror correlation, shipped to device-history. */
13994
14985
  transitions = null;
14986
+ /** Unsubscribes the command hold (D1061). */
14987
+ stopCommandHolds = null;
14988
+ stopStateRefresh = null;
13995
14989
  /**
13996
14990
  * Removes the claimed-status overlay this addon installed on the capability
13997
14991
  * registry (D663, S3): `getStatus` of a claimed cap answers the mirror for
@@ -14338,6 +15332,28 @@ var DeviceManagerAddon = class extends BaseAddon {
14338
15332
  const metaStore = new DeviceMetaStore(settings, registry, deviceRows, this.addonStoreWriteLock);
14339
15333
  this.stateMirrorImpl = new DeviceStateMirror(this.ctx);
14340
15334
  const stateMirror = this.stateMirrorImpl;
15335
+ this.stopCommandHolds = startCommandHolds({
15336
+ mirror: stateMirror,
15337
+ logger: this.ctx.logger.child("command-holds")
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
+ });
14341
15357
  this.transitions = startDeviceTransitions({
14342
15358
  mirror: stateMirror,
14343
15359
  logger: this.ctx.logger.child("transitions"),
@@ -14632,13 +15648,13 @@ var DeviceManagerAddon = class extends BaseAddon {
14632
15648
  return stateMirror.snapshotForDevice(input.deviceId);
14633
15649
  },
14634
15650
  getCapSlice: async (input) => {
14635
- return stateMirror.capSlice(input.deviceId, input.capName);
15651
+ return stateMirror.capSlice(input.deviceId, input.capName, input.confirmed === true ? "confirmed" : "effective");
14636
15652
  },
14637
15653
  getNativeCapSlice: async (input) => {
14638
15654
  return stateMirror.nativeSlice(input.deviceId, input.capName);
14639
15655
  },
14640
- getAllSnapshots: async () => {
14641
- return stateMirror.allSnapshots();
15656
+ getAllSnapshots: async (input) => {
15657
+ return stateMirror.allSnapshots(input?.confirmed === true ? "confirmed" : "effective");
14642
15658
  },
14643
15659
  setCapSlice: async (input) => {
14644
15660
  const { deviceId, capName, slice } = input;
@@ -14736,6 +15752,10 @@ var DeviceManagerAddon = class extends BaseAddon {
14736
15752
  this.templateActions = null;
14737
15753
  await this.transitions?.stop();
14738
15754
  this.transitions = null;
15755
+ this.stopStateRefresh?.();
15756
+ this.stopStateRefresh = null;
15757
+ this.stopCommandHolds?.();
15758
+ this.stopCommandHolds = null;
14739
15759
  this.removalCleanupImpl?.dispose();
14740
15760
  this.removalCleanupImpl = null;
14741
15761
  this.removalHooksCleanupImpl?.dispose();
@@ -14750,4 +15770,4 @@ var DeviceManagerAddon = class extends BaseAddon {
14750
15770
  }
14751
15771
  };
14752
15772
  //#endregion
14753
- export { DeviceManagerAddon, DeviceManagerAddon as default, commandObserverLink as a, runObservedCommand as c, readDeviceOrThrow as d, setWrapperActive as f, commandActorFromContext as i, observable as l, mergeAggregates, __resetCommandObserverRegistryForTests as n, getCommandObserverRegistry as o, addonCommandActor as r, reportCommand as s, CommandObserverRegistry as t, createDeviceSettingsStore 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 };