@camstack/server 1.2.825 → 1.2.827

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 (105) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/api/trpc/generated-cap-routers.js +257 -40
  3. package/dist/core/addon/addon-registry.service.js +3 -0
  4. package/package.json +41 -12
  5. package/system/dist/addon-runner.js +19 -2
  6. package/system/dist/addon-runner.mjs +19 -2
  7. package/system/dist/{agent-https-BBO2OtNH.mjs → agent-https-BSxTUzKT.mjs} +1 -1
  8. package/system/dist/{agent-https-B2nqARmj.js → agent-https-BlLVD9hG.js} +1 -1
  9. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  10. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  11. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  12. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  13. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  14. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  15. package/system/dist/builtins/autotrack/index.js +1 -1
  16. package/system/dist/builtins/autotrack/index.mjs +1 -1
  17. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  18. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  19. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  20. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  21. package/system/dist/builtins/camera-grid/index.js +1 -1
  22. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  23. package/system/dist/builtins/composer/composer.addon.js +4 -4
  24. package/system/dist/builtins/composer/composer.addon.mjs +4 -4
  25. package/system/dist/builtins/console-logging/index.js +1 -1
  26. package/system/dist/builtins/console-logging/index.mjs +1 -1
  27. package/system/dist/builtins/core-blocks/core-blocks.addon.js +3 -3
  28. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +3 -3
  29. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  30. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  31. package/system/dist/builtins/device-manager/device-bindings-store.d.ts +7 -4
  32. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +2 -0
  33. package/system/dist/builtins/device-manager/device-manager.addon.js +269 -25
  34. package/system/dist/builtins/device-manager/device-manager.addon.mjs +269 -25
  35. package/system/dist/builtins/device-manager/device-meta-actions.d.ts +11 -1
  36. package/system/dist/builtins/device-manager/device-projection.d.ts +7 -0
  37. package/system/dist/builtins/device-manager/device-template/mirror-resolver.d.ts +2 -0
  38. package/system/dist/builtins/device-manager/device-template/template-filters.d.ts +13 -0
  39. package/system/dist/builtins/device-manager/device-template/template-host.d.ts +11 -3
  40. package/system/dist/builtins/device-manager/device-template-actions.d.ts +1 -0
  41. package/system/dist/builtins/device-manager/feature-deriver.d.ts +61 -0
  42. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  43. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  44. package/system/dist/builtins/keychain/index.js +4 -4
  45. package/system/dist/builtins/keychain/index.mjs +4 -4
  46. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  47. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  48. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  49. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  50. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  51. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  52. package/system/dist/builtins/loki-logging/index.js +1 -1
  53. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  54. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  55. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  56. package/system/dist/builtins/platform-probe/index.js +1 -1
  57. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  58. package/system/dist/builtins/record-entries/index.js +1 -1
  59. package/system/dist/builtins/record-entries/index.mjs +1 -1
  60. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  61. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  62. package/system/dist/builtins/snapshot/index.js +1 -1
  63. package/system/dist/builtins/snapshot/index.mjs +1 -1
  64. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  65. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  66. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  67. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  68. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  69. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  70. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  71. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  72. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  73. package/system/dist/builtins/system-config/system-config.addon.mjs +3 -3
  74. package/system/dist/builtins/winston-logging/index.js +1 -1
  75. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  76. package/system/dist/{capture-engine-DP4HbT3W.js → capture-engine-1A7HAX3x.js} +1 -1
  77. package/system/dist/{capture-engine-C-rHYVFq.mjs → capture-engine-B0yQx6hA.mjs} +1 -1
  78. package/system/dist/{composition-sources-CM9c_jAj.js → composition-sources-BzM19ASO.js} +1 -1
  79. package/system/dist/{composition-sources-CL9JFN4y.mjs → composition-sources-CyJ0d6Sc.mjs} +1 -1
  80. package/system/dist/{constants-DzGFnCKZ.mjs → constants-B_FLEjP_.mjs} +1 -1
  81. package/system/dist/{constants-jk7JccZ0.js → constants-DSO4ZEO3.js} +1 -1
  82. package/system/dist/{device-ca-DZ_OQiCc.mjs → device-ca-CveuNCHp.mjs} +1 -1
  83. package/system/dist/{device-ca-B7_R5WJh.js → device-ca-DLTDsonl.js} +1 -1
  84. package/system/dist/device-template-worker.js +61 -1
  85. package/system/dist/device-template-worker.mjs +61 -1
  86. package/system/dist/{dist-BgRMQHuL.mjs → dist-CIyyHwVx.mjs} +373 -175
  87. package/system/dist/{dist-BpTL3uNe.js → dist-DhbzVygm.js} +408 -174
  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-mdns-ciao-DIcBingB.mjs → hub-mdns-ciao-CQdCUsrI.mjs} +2 -2
  91. package/system/dist/{hub-mdns-ciao-DPUaYAD3.js → hub-mdns-ciao-C_ITDs0-.js} +2 -2
  92. package/system/dist/index.js +26 -9
  93. package/system/dist/index.mjs +27 -10
  94. package/system/dist/kernel/moleculer/migration-api-facade.d.ts +3 -1
  95. package/system/dist/{legacy-integration-rows-door-DYNePgj4.js → legacy-integration-rows-door-D_tfRhsx.js} +1 -1
  96. package/system/dist/{legacy-integration-rows-door-1GnkpMgH.mjs → legacy-integration-rows-door-tX6Qktxd.mjs} +1 -1
  97. package/system/dist/{rename-composition-block-Cp0_nwAI.mjs → rename-composition-block-COaMxshT.mjs} +1 -1
  98. package/system/dist/{rename-composition-block-Dn2z4fnA.js → rename-composition-block-DNhbAonr.js} +1 -1
  99. package/system/dist/{restore-archive-B3FEpUfz.mjs → restore-archive-BMqp_hMT.mjs} +1 -1
  100. package/system/dist/{restore-archive-BGa5pdp9.js → restore-archive-Dbzuv5hK.js} +1 -1
  101. package/system/dist/{template-protocol-CTP4eAo_.js → template-protocol-DRZ4cm95.js} +4 -1
  102. package/system/dist/{template-protocol-BmMM5VBf.mjs → template-protocol-D_6uVHKs.mjs} +4 -1
  103. package/system/dist/{wal-maintenance-GWFxnSnE.js → wal-maintenance-CWODOTsa.js} +0 -0
  104. package/system/dist/{wal-maintenance-BLWLlVfF.mjs → wal-maintenance-ITsLGvFA.mjs} +0 -0
  105. package/system/package.json +1 -1
@@ -3,14 +3,14 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-BpTL3uNe.js");
6
+ const require_dist = require("../../dist-DhbzVygm.js");
7
7
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
8
8
  const require_log_redactor = require("../../log-redactor-BhIEMaG9.js");
9
- const require_rename_composition_block = require("../../rename-composition-block-Dn2z4fnA.js");
9
+ const require_rename_composition_block = require("../../rename-composition-block-DNhbAonr.js");
10
10
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
11
11
  const require_prefix_walk = require("../../prefix-walk-Dv6MLZlM.js");
12
12
  const require_retired_settings_keys = require("../../retired-settings-keys-C8nOOr5H.js");
13
- const require_template_protocol = require("../../template-protocol-CTP4eAo_.js");
13
+ const require_template_protocol = require("../../template-protocol-DRZ4cm95.js");
14
14
  const require_dns_wire = require("../../dns-wire-B1BvF9Ao.js");
15
15
  let zod = require("zod");
16
16
  let node_crypto = require("node:crypto");
@@ -358,6 +358,18 @@ function persistedFeatures(features) {
358
358
  return out;
359
359
  }
360
360
  /**
361
+ * The features a device is shown with (#459). The kernel owns the `derived`
362
+ * ones, and the row is where it keeps them, so they come from the row; a
363
+ * driver's own list (the live array, or the row when the live one is empty)
364
+ * decides only the rest. Without a row the live list is all there is.
365
+ */
366
+ function projectedFeatures(live, persisted) {
367
+ if (persisted === void 0) return persistedFeatures(live);
368
+ const driverOwned = (live.length > 0 ? live : persisted).filter((value) => !require_dist.isKernelDerivedFeature(value));
369
+ const kernelOwned = persisted.filter((value) => require_dist.isKernelDerivedFeature(value));
370
+ return persistedFeatures([...new Set([...driverOwned, ...kernelOwned])]);
371
+ }
372
+ /**
361
373
  * Infer `isCamera` from a persisted DeviceType.
362
374
  *
363
375
  * Live projection uses method presence (`getStreamSources` via
@@ -435,7 +447,7 @@ function toDeviceInfo(addonId, device, metadata = null, metaRow = null) {
435
447
  role: device.role ?? null,
436
448
  online: device.online,
437
449
  probed,
438
- features: device.features.length > 0 ? [...device.features] : persistedFeatures(metaRow?.features),
450
+ features: projectedFeatures(device.features, metaRow?.features),
439
451
  isCamera: isCameraDevice(device),
440
452
  config: configValues,
441
453
  ...liveSecretConfigPaths(device),
@@ -1328,7 +1340,7 @@ var StaleWrapperActivations = class {
1328
1340
  function wireRemoteNativeCapSync(ctx, remoteNativeCaps) {
1329
1341
  const localNodeId = ctx.kernel.localNodeId ?? "hub";
1330
1342
  ctx.eventBus.subscribe({ category: require_dist.EventCategory.DeviceBindingsChanged }, (event) => {
1331
- const { deviceId, capName, reason, addonId, nodeId } = event.data;
1343
+ const { deviceId, capName, reason, addonId, nodeId, implementedMethods } = event.data;
1332
1344
  if (nodeId === localNodeId) return;
1333
1345
  if (reason === "native-registered") {
1334
1346
  let perDevice = remoteNativeCaps.get(deviceId);
@@ -1350,7 +1362,8 @@ function wireRemoteNativeCapSync(ctx, remoteNativeCaps) {
1350
1362
  }
1351
1363
  perDevice.set(capName, {
1352
1364
  addonId,
1353
- nodeId
1365
+ nodeId,
1366
+ ...implementedMethods !== void 0 ? { implementedMethods } : {}
1354
1367
  });
1355
1368
  } else if (reason === "native-unregistered") {
1356
1369
  const perDevice = remoteNativeCaps.get(deviceId);
@@ -1650,12 +1663,14 @@ async function resolveBindingsForDevice(deps, deviceId, row, pass) {
1650
1663
  if (deps.capabilityRegistry) for (const capName of deps.capabilityRegistry.getNativeCapsForDevice(deviceId)) {
1651
1664
  if (seenCaps.has(capName)) continue;
1652
1665
  const nativeAddonId = deps.capabilityRegistry.getNativeAddonId(capName, deviceId) ?? "";
1666
+ const implementedMethods = localImplementedMethods(deps, capName, deviceId);
1653
1667
  entries.push({
1654
1668
  capName,
1655
1669
  kind: "native",
1656
1670
  providerAddonId: nativeAddonId,
1657
1671
  providerNodeId: deps.ctx.kernel.localNodeId ?? "hub",
1658
- nativeAddonId
1672
+ nativeAddonId,
1673
+ ...implementedMethods !== void 0 ? { implementedMethods } : {}
1659
1674
  });
1660
1675
  seenCaps.add(capName);
1661
1676
  }
@@ -1667,7 +1682,8 @@ async function resolveBindingsForDevice(deps, deviceId, row, pass) {
1667
1682
  kind: "native",
1668
1683
  providerAddonId: info.addonId,
1669
1684
  providerNodeId: toRoutableProviderNodeId(info.nodeId),
1670
- nativeAddonId: info.addonId
1685
+ nativeAddonId: info.addonId,
1686
+ ...info.implementedMethods !== void 0 ? { implementedMethods: info.implementedMethods } : {}
1671
1687
  });
1672
1688
  seenCaps.add(capName);
1673
1689
  }
@@ -1779,6 +1795,19 @@ async function listDeviceIdsByCaps(deps, input) {
1779
1795
  const wanted = new Set(input.capNames);
1780
1796
  return (await getAllBindings(deps)).filter((row) => row.entries.some((entry) => wanted.has(entry.capName))).map((row) => row.deviceId);
1781
1797
  }
1798
+ /**
1799
+ * The methods a HUB-LOCAL native provider object implements, read off the
1800
+ * object registered for `(cap, device)`; `undefined` when it cannot be said
1801
+ * (no definition, no provider), which the derivation reads as "all".
1802
+ */
1803
+ function localImplementedMethods(deps, capName, deviceId) {
1804
+ const registry = deps.capabilityRegistry;
1805
+ if (registry === void 0) return void 0;
1806
+ const definition = registry.getDefinition(capName);
1807
+ const provider = registry.getNativeProvider(capName, deviceId);
1808
+ if (definition === void 0 || provider === null) return void 0;
1809
+ return require_dist.implementedMethodsOf(Object.keys(definition.methods), provider);
1810
+ }
1782
1811
  //#endregion
1783
1812
  //#region src/builtins/device-manager/day-night-config-schema.ts
1784
1813
  var MODE_LABELS = {
@@ -4843,6 +4872,114 @@ var DeviceEventPropagator = class {
4843
4872
  }
4844
4873
  };
4845
4874
  //#endregion
4875
+ //#region src/builtins/device-manager/feature-deriver.ts
4876
+ /**
4877
+ * Keeps each device's persisted features equal to what its bindings imply (#459).
4878
+ *
4879
+ * Event-driven AND reconciled: `DeviceBindingsChanged` is telemetry and may be
4880
+ * dropped (D8/D49), so {@link reconcileAll} runs at boot and a missed event
4881
+ * costs only until the next one. There are no timers and no retries. A read
4882
+ * that fails changes nothing: the stored features stay as they were, because a
4883
+ * feature set derived from an empty answer would strip every feature of a
4884
+ * device the registry merely could not describe yet (D49). The same holds for
4885
+ * an answer that does not carry the device's own provider ONLINE: wrapper
4886
+ * entries alone, or natives cached for an agent that went offline, mean
4887
+ * "unknown", never "absent" (D315, {@link nativeProviderOnline}).
4888
+ *
4889
+ * Writes for one device run one after another and a burst collapses into the
4890
+ * run already waiting, so a worker registering twenty caps costs two settles.
4891
+ */
4892
+ var FeatureDeriver = class {
4893
+ deps;
4894
+ tails = /* @__PURE__ */ new Map();
4895
+ queued = /* @__PURE__ */ new Set();
4896
+ constructor(deps) {
4897
+ this.deps = deps;
4898
+ }
4899
+ /** A binding of `deviceId` changed (or may have): settle it after the settles already queued. */
4900
+ onBindingsChanged(deviceId) {
4901
+ if (this.queued.has(deviceId)) return this.tails.get(deviceId) ?? Promise.resolve();
4902
+ this.queued.add(deviceId);
4903
+ const next = (this.tails.get(deviceId) ?? Promise.resolve()).then(async () => {
4904
+ this.queued.delete(deviceId);
4905
+ await this.settleOne(deviceId);
4906
+ });
4907
+ this.tails.set(deviceId, next);
4908
+ next.finally(() => {
4909
+ if (this.tails.get(deviceId) === next) this.tails.delete(deviceId);
4910
+ });
4911
+ return next;
4912
+ }
4913
+ /** Boot reconcile: settle every device from one fleet read. Returns how many moved. */
4914
+ async reconcileAll() {
4915
+ let all;
4916
+ try {
4917
+ all = await this.deps.allBindings();
4918
+ } catch (err) {
4919
+ this.deps.logger.warn("feature reconcile skipped — the fleet bindings could not be read", { meta: { error: err instanceof Error ? err.message : String(err) } });
4920
+ return 0;
4921
+ }
4922
+ let moved = 0;
4923
+ for (const { deviceId, entries } of all) if (await this.applyOne(deviceId, entries)) moved += 1;
4924
+ this.deps.logger.info("feature reconcile done", { meta: {
4925
+ devices: all.length,
4926
+ moved
4927
+ } });
4928
+ return moved;
4929
+ }
4930
+ async settleOne(deviceId) {
4931
+ let entries;
4932
+ try {
4933
+ entries = await this.deps.bindingsOf(deviceId);
4934
+ } catch (err) {
4935
+ this.deps.logger.warn("feature derive skipped — bindings could not be read", {
4936
+ tags: { deviceId },
4937
+ meta: { error: err instanceof Error ? err.message : String(err) }
4938
+ });
4939
+ return;
4940
+ }
4941
+ await this.applyOne(deviceId, entries);
4942
+ }
4943
+ async applyOne(deviceId, entries) {
4944
+ if (!nativeProviderOnline(entries, this.deps.nodeOnline)) {
4945
+ this.deps.logger.debug("feature derive deferred — the device provider is not online", {
4946
+ tags: { deviceId },
4947
+ meta: { entries: entries.length }
4948
+ });
4949
+ return false;
4950
+ }
4951
+ try {
4952
+ return await this.deps.apply(deviceId, entries);
4953
+ } catch (err) {
4954
+ this.deps.logger.warn("feature derive failed — stored features left as they were", {
4955
+ tags: { deviceId },
4956
+ meta: { error: err instanceof Error ? err.message : String(err) }
4957
+ });
4958
+ return false;
4959
+ }
4960
+ }
4961
+ };
4962
+ /**
4963
+ * True when the device's own provider serves at least one of its caps and
4964
+ * every node it serves them from is online. A native cap is registered only
4965
+ * by the process the device lives in, so its `providerNodeId` is where the
4966
+ * device runs. This is a liveness question, not routing (D13 untouched).
4967
+ *
4968
+ * A device whose own provider serves NO cap (wrapper-only, or a native it
4969
+ * only decorates) never derives, on purpose: with no native of its own,
4970
+ * nothing can say a feature is absent, so its declared features stay.
4971
+ */
4972
+ function nativeProviderOnline(entries, nodeOnline) {
4973
+ const served = entries.filter((entry) => entry.nativeAddonId.length > 0 && entry.providerAddonId === entry.nativeAddonId);
4974
+ return served.length > 0 && served.every((entry) => nodeOnline(entry.providerNodeId));
4975
+ }
4976
+ /** Feed the deriver from the bus; returns the unsubscribe. */
4977
+ function subscribeFeatureDeriver(eventBus, deriver) {
4978
+ return eventBus.subscribe({ category: require_dist.EventCategory.DeviceBindingsChanged }, (event) => {
4979
+ deriver.onBindingsChanged(event.data.deviceId);
4980
+ });
4981
+ }
4982
+ //#endregion
4846
4983
  //#region src/builtins/device-manager/device-extension-linked-slot.ts
4847
4984
  /** The routing prefix of this owner's `slotRef`s. */
4848
4985
  var DEVICE_MANAGER_EXTENSION_SOURCE = "device-manager";
@@ -6582,17 +6719,18 @@ async function registerDevice(pctx, input) {
6582
6719
  throw new Error(`[device-manager] registerDevice: device ${id} (${addonId}/${stableId}) was removed — refusing to resurrect it`);
6583
6720
  }
6584
6721
  if (Array.isArray(input.secretConfigPaths)) pctx.secretConfigPaths.set(id, input.secretConfigPaths);
6585
- const { isFirstRegistration, exportFingerprint, fingerprintChanged, inheritedLocation, inheritedDescendantIds, inheritFailed } = await pctx.metaStore.withMetaWriteLock(async () => {
6722
+ const { isFirstRegistration, exportFingerprint, fingerprintChanged, storedFeatures, inheritedLocation, inheritedDescendantIds, inheritFailed } = await pctx.metaStore.withMetaWriteLock(async () => {
6586
6723
  const existingRow = await pctx.metaStore.rows.get(id);
6587
6724
  const existingMeta = existingRow?.meta;
6588
6725
  const wasRegistered = existingRow?.registered ?? false;
6589
6726
  const wasUserNamed = existingMeta?.userNamed ?? (existingMeta !== void 0 && existingMeta.name !== stableId);
6590
6727
  const resolvedName = wasUserNamed && existingMeta !== void 0 ? existingMeta.name : name;
6591
6728
  const isFirst = !existingMeta || !wasRegistered;
6729
+ const settledFeatures = require_dist.reconcileReportedFeatures(existingMeta?.features, featuresArr);
6592
6730
  const fingerprint = (0, _camstack_types_node.canonicalDeviceFingerprint)({
6593
6731
  deviceId: id,
6594
6732
  deviceType: type,
6595
- features: featuresArr
6733
+ features: settledFeatures
6596
6734
  });
6597
6735
  const priorLocation = existingMeta?.location ?? null;
6598
6736
  const resolvedParentId = parentDeviceId ?? null;
@@ -6609,7 +6747,7 @@ async function registerDevice(pctx, input) {
6609
6747
  disabled: existingMeta?.disabled ?? false,
6610
6748
  parentDeviceId: resolvedParentId,
6611
6749
  registered: true,
6612
- features: featuresArr,
6750
+ features: settledFeatures,
6613
6751
  exportFingerprint: fingerprint
6614
6752
  });
6615
6753
  if (existingMeta?.alias === void 0) await pctx.metaStore.rows.patch(id, { alias: await freeAliasFor(pctx.metaStore.rows, resolvedName, id, await readReservedAliases(pctx)) });
@@ -6629,6 +6767,7 @@ async function registerDevice(pctx, input) {
6629
6767
  }
6630
6768
  return {
6631
6769
  isFirstRegistration: isFirst,
6770
+ storedFeatures: settledFeatures,
6632
6771
  exportFingerprint: fingerprint,
6633
6772
  fingerprintChanged: existingMeta?.exportFingerprint !== fingerprint,
6634
6773
  inheritedLocation: inherited,
@@ -6697,7 +6836,7 @@ async function registerDevice(pctx, input) {
6697
6836
  name: name.length > 0 ? name : stableId,
6698
6837
  providerId: addonId,
6699
6838
  parentDeviceId: parentDeviceId ?? null,
6700
- features: featuresArr
6839
+ features: storedFeatures
6701
6840
  }
6702
6841
  });
6703
6842
  if (isFirstRegistration || fingerprintChanged) pctx.host.ctx.eventBus.emit({
@@ -6716,6 +6855,61 @@ async function registerDevice(pctx, input) {
6716
6855
  });
6717
6856
  }
6718
6857
  /**
6858
+ * Re-derive a device's features from its bindings and persist them when they
6859
+ * moved (#459). The settle runs INSIDE the meta write lock against the row as
6860
+ * it is there, so a concurrent `registerDevice` cannot land between the read
6861
+ * and the write. A row that does not exist is left alone (a binding event can
6862
+ * outlive the device), and an unchanged set writes nothing and announces
6863
+ * nothing. A changed one stamps the new fingerprint and, like `registerDevice`,
6864
+ * emits `DeviceProvisioned` so exporters reconcile with one delta.
6865
+ */
6866
+ async function applyDerivedFeatures(pctx, deviceId, entries) {
6867
+ const outcome = await pctx.metaStore.withMetaWriteLock(async () => {
6868
+ const row = await pctx.metaStore.rows.get(deviceId);
6869
+ if (row === null || !row.registered) return null;
6870
+ const settled = require_dist.settleDeviceFeatures(entries, row.meta.features ?? []);
6871
+ const stored = row.meta.features ?? [];
6872
+ if (settled.length === stored.length && settled.every((value, i) => value === stored[i])) return null;
6873
+ const fingerprint = (0, _camstack_types_node.canonicalDeviceFingerprint)({
6874
+ deviceId,
6875
+ deviceType: row.meta.type,
6876
+ features: settled
6877
+ });
6878
+ await pctx.metaStore.rows.patch(deviceId, {
6879
+ features: settled,
6880
+ exportFingerprint: fingerprint
6881
+ });
6882
+ return {
6883
+ fingerprint,
6884
+ features: settled,
6885
+ previous: stored
6886
+ };
6887
+ });
6888
+ if (outcome === null) return false;
6889
+ pctx.host.ctx.logger.info("device features re-derived from bindings", {
6890
+ tags: { deviceId },
6891
+ meta: {
6892
+ from: outcome.previous,
6893
+ to: outcome.features
6894
+ }
6895
+ });
6896
+ pctx.host.ctx.eventBus.emit({
6897
+ id: (0, node_crypto.randomUUID)(),
6898
+ timestamp: /* @__PURE__ */ new Date(),
6899
+ source: {
6900
+ type: "device",
6901
+ id: deviceId
6902
+ },
6903
+ category: require_dist.EventCategory.DeviceProvisioned,
6904
+ data: {
6905
+ deviceId,
6906
+ fingerprint: outcome.fingerprint,
6907
+ generation: Date.now()
6908
+ }
6909
+ });
6910
+ return true;
6911
+ }
6912
+ /**
6719
6913
  * The stores device-manager (or the keychain, for secrets) keeps for a device.
6720
6914
  * Another addon's own per-device data is cleaned by that addon, off
6721
6915
  * `DeviceUnregistered` — the kernel never reaches into its tables (D864).
@@ -8064,7 +8258,7 @@ function mirrorTemplateResolver(mirror, devices, unitOf) {
8064
8258
  return { viewOf(alias) {
8065
8259
  const device = byAlias.get(alias);
8066
8260
  if (device === void 0) return void 0;
8067
- const slices = {};
8261
+ const slices = { ...device.values };
8068
8262
  for (const cap of device.caps) {
8069
8263
  const slice = mirror.sliceOf(device.deviceId, cap);
8070
8264
  if (slice !== void 0) slices[cap] = slice;
@@ -8101,7 +8295,7 @@ var DeviceTemplateHost = class {
8101
8295
  * restriction (an admin, a system run). A restricted caller gets the same
8102
8296
  * answer for an alias that does not exist and one it may not see.
8103
8297
  */
8104
- async check(source, allowed) {
8298
+ async check(source, allowed, thisDevice) {
8105
8299
  const analysis = this.deps.renderer.validate(source);
8106
8300
  if (!analysis.ok) return {
8107
8301
  ok: false,
@@ -8109,31 +8303,47 @@ var DeviceTemplateHost = class {
8109
8303
  message: analysis.refusal.message
8110
8304
  };
8111
8305
  const aliases = [];
8112
- for (const alias of new Set(analysis.refs.map((ref) => ref.alias))) {
8113
- const row = await this.deps.findByAlias(alias);
8306
+ const named = analysis.refs.filter((ref) => ref.alias !== "now");
8307
+ for (const alias of new Set(named.map((ref) => ref.alias))) {
8308
+ const row = await this.rowOf(alias, thisDevice);
8114
8309
  aliases.push({
8115
8310
  alias,
8116
8311
  deviceId: row === null ? null : row.deviceId,
8117
8312
  allowed: allowed === void 0 || row !== null && allowed.has(row.deviceId),
8118
- row
8313
+ row,
8314
+ reads: [...new Set(named.filter((ref) => ref.alias === alias).map((ref) => ref.path.map(String).join(".")))].filter((read) => read !== "")
8119
8315
  });
8120
8316
  }
8121
8317
  return {
8122
8318
  ok: true,
8123
- aliases
8319
+ aliases,
8320
+ readsClock: analysis.refs.some((ref) => ref.alias === "now")
8124
8321
  };
8125
8322
  }
8323
+ /** `camera` is the device the render is for when the call names one; every other alias is a device's own. */
8324
+ async rowOf(alias, thisDevice) {
8325
+ if (alias === "camera" && thisDevice !== void 0) {
8326
+ const row = await this.deps.findById(thisDevice.deviceId);
8327
+ return row === null ? null : {
8328
+ ...row,
8329
+ alias
8330
+ };
8331
+ }
8332
+ return this.deps.findByAlias(alias);
8333
+ }
8126
8334
  /** Render every template; answers are index-aligned with the questions. */
8127
- async render(sources, allowed) {
8128
- const checks = await Promise.all(sources.map((source) => this.check(source, allowed)));
8335
+ async render(sources, allowed, thisDevice) {
8336
+ const checks = await Promise.all(sources.map((source) => this.check(source, allowed, thisDevice)));
8129
8337
  const rows = /* @__PURE__ */ new Map();
8130
8338
  for (const check of checks) {
8131
8339
  if (!check.ok) continue;
8132
8340
  for (const use of check.aliases) {
8133
8341
  if (!use.allowed || use.row === null || rows.has(use.alias)) continue;
8342
+ const caps = await this.deps.capsOf(use.row.deviceId);
8134
8343
  rows.set(use.alias, {
8135
8344
  ...use.row,
8136
- caps: await this.deps.capsOf(use.row.deviceId)
8345
+ caps,
8346
+ ...use.alias === "camera" && thisDevice?.values !== void 0 ? { values: { [require_dist.DEVICE_TEMPLATE_VALUES_CAP]: thisDevice.values } } : {}
8137
8347
  });
8138
8348
  }
8139
8349
  }
@@ -8411,6 +8621,14 @@ var DeviceTemplateRenderer = class {
8411
8621
  const tree = new ContextTree();
8412
8622
  const resolvedFor = /* @__PURE__ */ new Map();
8413
8623
  for (const ref of analysis.refs) {
8624
+ if (ref.alias === "now") {
8625
+ if (ref.path.length === 0) tree.place(ref.alias, [], this.now());
8626
+ else trace.push({
8627
+ ref: refText(ref),
8628
+ reason: "unknown-field"
8629
+ });
8630
+ continue;
8631
+ }
8414
8632
  const view = resolver.viewOf(ref.alias);
8415
8633
  if (view === void 0) {
8416
8634
  trace.push({
@@ -8618,6 +8836,7 @@ var DeviceTemplateActions = class {
8618
8836
  this.host = new DeviceTemplateHost({
8619
8837
  renderer: this.renderer,
8620
8838
  findByAlias: this.deps.findByAlias,
8839
+ findById: this.deps.findById,
8621
8840
  capsOf: this.deps.capsOf,
8622
8841
  fetchSlice: this.deps.fetchSlice,
8623
8842
  unitOf: baseUnitOfRuntimeField,
@@ -8628,21 +8847,23 @@ var DeviceTemplateActions = class {
8628
8847
  }
8629
8848
  async render(input) {
8630
8849
  const allowed = input.allowedDeviceIds === void 0 ? void 0 : new Set(input.allowedDeviceIds);
8631
- return { results: await this.hostOf().render(input.templates, allowed) };
8850
+ return { results: await this.hostOf().render(input.templates, allowed, input.thisDevice) };
8632
8851
  }
8633
8852
  async check(input) {
8634
8853
  const allowed = input.allowedDeviceIds === void 0 ? void 0 : new Set(input.allowedDeviceIds);
8635
8854
  const host = this.hostOf();
8636
8855
  const results = [];
8637
8856
  for (const source of input.templates) {
8638
- const check = await host.check(source, allowed);
8857
+ const check = await host.check(source, allowed, input.thisDevice);
8639
8858
  results.push(check.ok ? {
8640
8859
  ok: true,
8641
8860
  aliases: check.aliases.map((use) => ({
8642
8861
  alias: use.alias,
8643
8862
  deviceId: use.deviceId,
8644
- allowed: use.allowed
8645
- }))
8863
+ allowed: use.allowed,
8864
+ reads: [...use.reads]
8865
+ })),
8866
+ readsClock: check.readsClock
8646
8867
  } : {
8647
8868
  ok: false,
8648
8869
  refusal: {
@@ -12554,6 +12775,8 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
12554
12775
  * populated. Stopped in `onShutdown`.
12555
12776
  */
12556
12777
  propagator = null;
12778
+ /** Stops the bindings → features subscription; run in `onShutdown`. */
12779
+ unsubscribeFeatureDeriver = null;
12557
12780
  /**
12558
12781
  * Hub-side mirror of every device's cap-keyed runtime state.
12559
12782
  * Populated whenever any caller writes via `deviceState.setCapSlice`
@@ -13177,6 +13400,15 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
13177
13400
  migrationInFlight: (deviceId) => pctx.migrationGuard.isInFlight(deviceId)
13178
13401
  })
13179
13402
  };
13403
+ const featureDeriver = new FeatureDeriver({
13404
+ bindingsOf: async (deviceId) => (await getBindings(this.bindingsDeps, { deviceId })).entries,
13405
+ allBindings: () => getAllBindings(this.bindingsDeps),
13406
+ apply: (deviceId, entries) => applyDerivedFeatures(pctx, deviceId, entries),
13407
+ nodeOnline: (nodeId) => nodeId === (this.ctx.kernel.localNodeId ?? "hub") || (this.ctx.kernel.isNodeRegistered?.(nodeId) ?? false),
13408
+ logger: this.ctx.logger.child("features")
13409
+ });
13410
+ this.unsubscribeFeatureDeriver = subscribeFeatureDeriver(this.ctx.eventBus, featureDeriver);
13411
+ featureDeriver.reconcileAll();
13180
13412
  return [
13181
13413
  {
13182
13414
  capability: require_dist.deviceManagerCapability,
@@ -13221,6 +13453,16 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
13221
13453
  alias
13222
13454
  };
13223
13455
  },
13456
+ findById: async (deviceId) => {
13457
+ const row = await this.deviceRows?.get(deviceId);
13458
+ if (row === void 0 || row === null) return null;
13459
+ return {
13460
+ deviceId: row.meta.id,
13461
+ addonId: row.meta.addonId,
13462
+ stableId: row.meta.stableId,
13463
+ alias: row.meta.alias ?? ""
13464
+ };
13465
+ },
13224
13466
  capsOf: async (deviceId) => (await this.getBindings({ deviceId })).entries.map((entry) => entry.capName),
13225
13467
  fetchSlice: async (deviceId, cap) => {
13226
13468
  const api = this.ctx.api;
@@ -13245,6 +13487,8 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
13245
13487
  this.removalHooksCleanupImpl = null;
13246
13488
  this.propagator?.stop();
13247
13489
  this.propagator = null;
13490
+ this.unsubscribeFeatureDeriver?.();
13491
+ this.unsubscribeFeatureDeriver = null;
13248
13492
  this.uninstallStatusOverlay?.();
13249
13493
  this.uninstallStatusOverlay = null;
13250
13494
  await this.stateMirrorImpl?.flushPendingWrites(this.ctx.settings);