@camstack/server 1.2.899 → 1.2.901

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 (100) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/api/trpc/generated-cap-routers.js +50 -0
  3. package/package.json +11 -10
  4. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  5. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  6. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  7. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  8. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  9. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  10. package/system/dist/builtins/autotrack/index.js +1 -1
  11. package/system/dist/builtins/autotrack/index.mjs +1 -1
  12. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  13. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  14. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  15. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  16. package/system/dist/builtins/camera-grid/index.js +1 -1
  17. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  18. package/system/dist/builtins/composer/composer.addon.js +4 -4
  19. package/system/dist/builtins/composer/composer.addon.mjs +4 -4
  20. package/system/dist/builtins/console-logging/index.js +1 -1
  21. package/system/dist/builtins/console-logging/index.mjs +1 -1
  22. package/system/dist/builtins/core-blocks/composition-api.d.ts +37 -1
  23. package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +14 -0
  24. package/system/dist/builtins/core-blocks/core-blocks.addon.js +516 -7
  25. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +516 -7
  26. package/system/dist/builtins/core-blocks/link-contributions.d.ts +85 -0
  27. package/system/dist/builtins/core-blocks/power-source-service.d.ts +25 -1
  28. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  29. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  30. package/system/dist/builtins/device-manager/device-identifiers-action.d.ts +8 -0
  31. package/system/dist/builtins/device-manager/device-identity-index.d.ts +56 -2
  32. package/system/dist/builtins/device-manager/device-manager.addon.js +625 -62
  33. package/system/dist/builtins/device-manager/device-manager.addon.mjs +624 -61
  34. package/system/dist/builtins/device-manager/device-meta-types.d.ts +9 -1
  35. package/system/dist/builtins/device-manager/device-provider-context.d.ts +3 -0
  36. package/system/dist/builtins/device-manager/device-row-store.d.ts +4 -2
  37. package/system/dist/builtins/device-manager/identity-link-reconciler.d.ts +66 -0
  38. package/system/dist/builtins/device-manager/identity-links-store.d.ts +22 -0
  39. package/system/dist/builtins/device-manager/record-kinds.d.ts +2 -1
  40. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  41. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  42. package/system/dist/builtins/keychain/index.js +4 -4
  43. package/system/dist/builtins/keychain/index.mjs +4 -4
  44. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  45. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  46. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  47. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  48. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  49. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  50. package/system/dist/builtins/loki-logging/index.js +1 -1
  51. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  52. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  53. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  54. package/system/dist/builtins/platform-probe/index.js +1 -1
  55. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  56. package/system/dist/builtins/record-entries/index.js +1 -1
  57. package/system/dist/builtins/record-entries/index.mjs +1 -1
  58. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  59. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  60. package/system/dist/builtins/snapshot/index.js +1 -1
  61. package/system/dist/builtins/snapshot/index.mjs +1 -1
  62. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  63. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  64. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  65. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  66. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  67. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  68. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  69. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  70. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  71. package/system/dist/builtins/system-config/system-config.addon.mjs +284 -284
  72. package/system/dist/builtins/winston-logging/index.js +1 -1
  73. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  74. package/system/dist/{capture-engine-LHKTf-nM.js → capture-engine-B3csK2sW.js} +1 -1
  75. package/system/dist/{capture-engine-BcD6iCZM.mjs → capture-engine-CCAzcezv.mjs} +1 -1
  76. package/system/dist/{composition-sources-C3ARJk2g.mjs → composition-sources-BX7u-Hdf.mjs} +1 -1
  77. package/system/dist/{composition-sources-DNUDbuXy.js → composition-sources-Bkbk5Oh5.js} +1 -1
  78. package/system/dist/{constants-dL8fl9aI.js → constants-BqxCksdV.js} +1 -1
  79. package/system/dist/{constants-er38mZOb.mjs → constants-_bOm_ae5.mjs} +1 -1
  80. package/system/dist/{device-ca-Ccz5olgH.mjs → device-ca-DRqN1P5Y.mjs} +1 -1
  81. package/system/dist/{device-ca-KWa6uJRU.js → device-ca-KNx_DazP.js} +1 -1
  82. package/system/dist/{dist-DEAjZE_-.js → dist-BNrIzdrJ.js} +351 -7
  83. package/system/dist/{dist-DBanWvHF.mjs → dist-S-zGcCEr.mjs} +310 -8
  84. package/system/dist/file-host-worker.js +1 -1
  85. package/system/dist/file-host-worker.mjs +1 -1
  86. package/system/dist/{hub-identity-CVv79TVO.mjs → hub-identity-DSdbZxeR.mjs} +1 -1
  87. package/system/dist/{hub-identity-Dy8ZSUuq.js → hub-identity-pN0LtUhx.js} +1 -1
  88. package/system/dist/{hub-mdns-ciao-C_XjO7YI.js → hub-mdns-ciao-GafEbDm8.js} +2 -2
  89. package/system/dist/{hub-mdns-ciao-DtmIyWDL.mjs → hub-mdns-ciao-wAcv5VBY.mjs} +2 -2
  90. package/system/dist/index.js +8 -8
  91. package/system/dist/index.mjs +8 -8
  92. package/system/dist/{legacy-integration-rows-door-BL8T4lya.mjs → legacy-integration-rows-door--186Wij_.mjs} +1 -1
  93. package/system/dist/{legacy-integration-rows-door-DPInWtE6.js → legacy-integration-rows-door-B1swGb0r.js} +1 -1
  94. package/system/dist/{rename-composition-block-Dgo-9-Ts.mjs → rename-composition-block-Cf5syiM4.mjs} +1 -1
  95. package/system/dist/{rename-composition-block-BxzETYOf.js → rename-composition-block-gJ_4GdHr.js} +1 -1
  96. package/system/dist/{restore-archive-BUtuNTe1.mjs → restore-archive-DScscuGI.mjs} +82 -82
  97. package/system/dist/{restore-archive-Zvx9sHZP.js → restore-archive-DXi9iBay.js} +1 -1
  98. package/system/dist/{wal-maintenance-DS2IKwtK.js → wal-maintenance-BA9XNPvt.js} +0 -0
  99. package/system/dist/{wal-maintenance-cASt_sYy.mjs → wal-maintenance-s3KdED98.mjs} +0 -0
  100. package/system/package.json +1 -1
@@ -1,9 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_chunk = require("../../chunk-Cek0wNdY.js");
3
- const require_dist = require("../../dist-DEAjZE_-.js");
3
+ const require_dist = require("../../dist-BNrIzdrJ.js");
4
4
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
5
- const require_capture_engine = require("../../capture-engine-LHKTf-nM.js");
6
- const require_composition_sources = require("../../composition-sources-DNUDbuXy.js");
5
+ const require_capture_engine = require("../../capture-engine-B3csK2sW.js");
6
+ const require_composition_sources = require("../../composition-sources-Bkbk5Oh5.js");
7
7
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
8
8
  const require_prefix_walk = require("../../prefix-walk-Dv6MLZlM.js");
9
9
  const require_cap_call_scope = require("../../cap-call-scope-8eiugfLl.js");
@@ -4268,6 +4268,15 @@ function buildActionsRuntime(deps) {
4268
4268
  * switched on or off: power on / off are refused as `not-settable`, and `getStatus`
4269
4269
  * says so (`switchSettable`) for the surfaces that withdraw them.
4270
4270
  *
4271
+ * A power source an identity link contributed (`contributedBy`, D1063) is
4272
+ * checked against that link at the point of use: the link is read over RPC
4273
+ * before every action, and one that is no longer `linked`, or now names another
4274
+ * port, refuses as `link-lost` and asks core-blocks to reconcile the
4275
+ * contributions. A read that fails, or links not loaded yet, refuse as
4276
+ * `link-unknown` — cutting power is destructive work (D49). A stamp alone is
4277
+ * never proof the port still feeds this device: the event that withdraws it
4278
+ * may have been dropped (D11).
4279
+ *
4271
4280
  * Every refusal is a typed result with its reason, logged with the device tag.
4272
4281
  */
4273
4282
  /** `switch.getOptions` FAILED (not absent): what the switch can do is unknown. */
@@ -4474,6 +4483,10 @@ var PowerSourceService = class {
4474
4483
  reason: "switch-is-actuator",
4475
4484
  message: `the linked switch ${link.switch.stableId} is one of this device's own switches, not its supply`
4476
4485
  };
4486
+ if (link.contributedBy !== void 0) {
4487
+ const refused = await this.checkContributingLink(deviceId, link, link.contributedBy.linkId);
4488
+ if (refused !== null) return refused;
4489
+ }
4477
4490
  const switchDevice = await this.deps.devices.find(link.switch).catch(() => null);
4478
4491
  if (switchDevice === null) return {
4479
4492
  kind: "refused",
@@ -4498,6 +4511,38 @@ var PowerSourceService = class {
4498
4511
  }
4499
4512
  };
4500
4513
  }
4514
+ /**
4515
+ * The identity link that contributed this power source, read now: null when it is
4516
+ * still `linked`, its evidence still holds, and its source side is the switch the
4517
+ * feature reads. An operator-confirmed link whose evidence is gone (`evidenceGone`)
4518
+ * is refused as `link-lost`: the port may now feed another device (D1063).
4519
+ */
4520
+ async checkContributingLink(deviceId, link, linkId) {
4521
+ let read;
4522
+ try {
4523
+ read = await this.deps.links.read();
4524
+ } catch (err) {
4525
+ return {
4526
+ kind: "refused",
4527
+ reason: "link-unknown",
4528
+ message: `the identity link ${linkId} that contributed this power source could not be read (${errorText$3(err)})`
4529
+ };
4530
+ }
4531
+ if (read.status !== "answered") return {
4532
+ kind: "refused",
4533
+ reason: "link-unknown",
4534
+ message: `the identity links are not loaded yet (${read.reason}); not acting through link ${linkId}`
4535
+ };
4536
+ const current = read.links.find((l) => l.id === linkId);
4537
+ const contribution = current ? require_dist.IDENTITY_LINK_KINDS[current.kind].contributions.find((c) => c.cap === "power-source") : void 0;
4538
+ if (current !== void 0 && current.state === "linked" && current.evidenceGone !== true && contribution !== void 0 && require_dist.compositionSourceKey(current[contribution.source]) === require_dist.compositionSourceKey(link.switch)) return null;
4539
+ this.deps.links.lost(deviceId);
4540
+ return {
4541
+ kind: "refused",
4542
+ reason: "link-lost",
4543
+ message: current === void 0 ? `the identity link ${linkId} that contributed this power source is gone` : current.state === "linked" && current.evidenceGone === true ? `the identity link ${linkId} was confirmed by the operator but its evidence is gone — ${link.switch.stableId} may feed another device now; unlink it, or it acts again when the evidence returns` : `the identity link ${linkId} is ${current.state} and no longer feeds this device from ${link.switch.stableId}`
4544
+ };
4545
+ }
4501
4546
  /** The stored link of the device `deviceId`, read from the customizations now. */
4502
4547
  async linkOf(deviceId) {
4503
4548
  return (await this.storedLinkOf(deviceId))?.link ?? null;
@@ -9175,7 +9220,57 @@ function bucketStep(point) {
9175
9220
  * A customization of an existing device (D663) has no name of its own: the
9176
9221
  * server derives it (`customizationBlockName`), refuses one the client sends,
9177
9222
  * and never lets it move to another device. One per device, by block id (S2).
9223
+ *
9224
+ * A feature an identity link contributed (`contributedBy`, D1063) is switched
9225
+ * off by the operator, never removed: an update that drops one is refused as
9226
+ * `link-contribution-removed`, except the identity-link reconciler's own write
9227
+ * (`linkReconcilerCaller()`), which is how a contribution is withdrawn. Every
9228
+ * other write of a customization asks for a link pass (`compositionWritten`).
9229
+ */
9230
+ /** The `caller.userId` of the identity-link reconciler's own writes (D1063). */
9231
+ var IDENTITY_LINKS_USER_ID = "identity-links";
9232
+ /**
9233
+ * The reconciler's callers, by object identity. The gate is this set, never the
9234
+ * `userId` string: a `caller` that arrived over the wire (a forked addon's
9235
+ * `ctx.api` args reach the provider as sent) is a different object, whatever it
9236
+ * names, so it can never pass as the reconciler.
9237
+ */
9238
+ var LINK_RECONCILER_CALLERS = /* @__PURE__ */ new WeakSet();
9239
+ /** A caller that IS the identity-link reconciler — mint it in-process only. */
9240
+ function linkReconcilerCaller() {
9241
+ const caller = {
9242
+ userId: IDENTITY_LINKS_USER_ID,
9243
+ isAdmin: true
9244
+ };
9245
+ LINK_RECONCILER_CALLERS.add(caller);
9246
+ return caller;
9247
+ }
9248
+ function isLinkReconciler(writer) {
9249
+ return writer !== void 0 && LINK_RECONCILER_CALLERS.has(writer);
9250
+ }
9251
+ /** An update named an `updatedAt` the stored block no longer has: reload and re-apply. */
9252
+ var CompositionChangedError = class extends Error {
9253
+ blockId;
9254
+ constructor(blockId, name, storedUpdatedAt, expectedUpdatedAt) {
9255
+ super(`core-blocks: the composition "${name}" changed since you read it: stored updatedAt ${storedUpdatedAt}, yours ${expectedUpdatedAt} — reload and re-apply your edit`);
9256
+ this.name = "CompositionChangedError";
9257
+ this.blockId = blockId;
9258
+ }
9259
+ };
9260
+ /** The features of a composition an identity link contributed. */
9261
+ function linkContributedFeatures(composition) {
9262
+ return (composition?.features ?? []).flatMap((f) => f.kind === "fields" && f.contributedBy !== void 0 ? [f] : []);
9263
+ }
9264
+ /**
9265
+ * Why a block cannot be deleted: it holds features identity links contributed
9266
+ * (`link-contribution-removed`, D1063). Null when it can.
9178
9267
  */
9268
+ function linkContributionDeleteRefusal(block) {
9269
+ const stamped = linkContributedFeatures(block === null ? null : require_dist.coreBlockComposition(block));
9270
+ if (stamped.length === 0) return null;
9271
+ const named = stamped.map((f) => `${f.cap} (device link ${f.contributedBy?.linkId ?? ""})`);
9272
+ return `core-blocks: "${block?.name ?? ""}" was not deleted [link-contribution-removed] — ${named.join(", ")} added by a device link; switch it off instead, or unlink the device to take it away`;
9273
+ }
9179
9274
  var NOT_LOADED_REASON = "core_blocks has not loaded yet";
9180
9275
  function writeQueue() {
9181
9276
  let tail = Promise.resolve();
@@ -9199,7 +9294,73 @@ function refuseIfChanged(deps, blockId, expectedUpdatedAt) {
9199
9294
  storedUpdatedAt: stored.updatedAt,
9200
9295
  expectedUpdatedAt
9201
9296
  } });
9202
- throw new Error(`core-blocks: the composition "${stored.name}" changed since you read it: stored updatedAt ${stored.updatedAt}, yours ${expectedUpdatedAt} — reload and re-apply your edit`);
9297
+ throw new CompositionChangedError(blockId, stored.name, stored.updatedAt, expectedUpdatedAt);
9298
+ }
9299
+ /**
9300
+ * An update that drops a link-contributed feature is refused (D1063): the
9301
+ * operator's off-switch is `enabled: false`. The reconciler's own write is how a
9302
+ * contribution is withdrawn, so it passes.
9303
+ */
9304
+ function refuseLinkContributionRemoval(deps, blockId, next, writer) {
9305
+ if (next === void 0 || isLinkReconciler(writer)) return;
9306
+ const stored = deps.store.get(blockId);
9307
+ if (stored === null) return;
9308
+ const kept = new Set(next.features.map((f) => f.cap));
9309
+ const removed = linkContributedFeatures(require_dist.coreBlockComposition(stored)).filter((f) => !kept.has(f.cap));
9310
+ if (removed.length === 0) return;
9311
+ refuse(deps, {
9312
+ name: stored.name,
9313
+ blockId
9314
+ }, {
9315
+ ok: false,
9316
+ problems: removed.map((f) => ({
9317
+ code: "link-contribution-removed",
9318
+ path: `features.${f.cap}`,
9319
+ message: `${f.cap} was added by the device link ${f.contributedBy?.linkId ?? ""} — switch it off instead; unlink the device to take it away`
9320
+ })),
9321
+ fields: [],
9322
+ features: [],
9323
+ events: []
9324
+ }, []);
9325
+ }
9326
+ /**
9327
+ * The reconciler taking back what it stamped, and nothing else (D1063): the
9328
+ * composition is unchanged apart from its features (target and helper
9329
+ * included), every stored feature the operator wrote survives verbatim, and
9330
+ * every other kept feature is a stored one or an unstamped remainder of a
9331
+ * stamped one — a subset of its fields, with the same values. Removing features
9332
+ * cannot create a conflict, and a withdrawal must land on a customization whose
9333
+ * host was removed — which the store judge refuses as `target-missing` — so it
9334
+ * is not judged.
9335
+ */
9336
+ function isStampWithdrawal(stored, next, writer) {
9337
+ if (!isLinkReconciler(writer) || stored === null) return false;
9338
+ if (JSON.stringify({
9339
+ ...stored,
9340
+ features: []
9341
+ }) !== JSON.stringify({
9342
+ ...next,
9343
+ features: []
9344
+ })) return false;
9345
+ const stamped = linkContributedFeatures(stored);
9346
+ if (stamped.length === 0) return false;
9347
+ const storedKeys = new Set(stored.features.map((f) => JSON.stringify(f)));
9348
+ const nextKeys = new Set(next.features.map((f) => JSON.stringify(f)));
9349
+ const operatorKept = stored.features.every((f) => f.kind === "fields" && f.contributedBy !== void 0 || nextKeys.has(JSON.stringify(f)));
9350
+ const nothingAdded = next.features.every((f) => storedKeys.has(JSON.stringify(f)) || f.kind === "fields" && f.contributedBy === void 0 && stamped.some((from) => isRemainderOf(f, from)));
9351
+ return operatorKept && nothingAdded && next.features.length <= stored.features.length;
9352
+ }
9353
+ /** `kept` is `stamped` without its stamp, cut down to some of its fields, each unchanged. */
9354
+ function isRemainderOf(kept, stamped) {
9355
+ const { contributedBy: _stamp, fields: stampedFields, ...stampedRest } = stamped;
9356
+ const { fields: keptFields, ...keptRest } = kept;
9357
+ if (JSON.stringify(keptRest) !== JSON.stringify(stampedRest)) return false;
9358
+ return Object.entries(keptFields).every(([path, value]) => Object.hasOwn(stampedFields, path) && JSON.stringify(stampedFields[path]) === JSON.stringify(value));
9359
+ }
9360
+ function noteWritten(deps, composition, writer) {
9361
+ if (composition === null || composition.target.kind !== "existing") return;
9362
+ if (writer === void 0 || isLinkReconciler(writer)) return;
9363
+ deps.compositionWritten?.(composition.target.device, writer);
9203
9364
  }
9204
9365
  /** The device a composition writes, when it is an EXISTING one; null for a new device. */
9205
9366
  function existingTarget(composition) {
@@ -9433,26 +9594,30 @@ function buildCompositionApi(deps) {
9433
9594
  name: created.name,
9434
9595
  by: caller.userId
9435
9596
  } });
9597
+ noteWritten(deps, block.composition, caller);
9436
9598
  deps.convergeSoon();
9437
9599
  return { block: created };
9438
9600
  }),
9439
9601
  updateComposition: ({ blockId, expectedUpdatedAt, block, caller }) => serialized(async () => {
9440
9602
  refuseIfChanged(deps, blockId, expectedUpdatedAt);
9603
+ refuseLinkContributionRemoval(deps, blockId, block.composition, caller);
9441
9604
  await refuseRetarget(deps, blockId, block);
9442
- if (block.composition !== void 0) {
9605
+ const previous = deps.store.get(blockId);
9606
+ const withdrawal = block.composition !== void 0 && isStampWithdrawal(previous === null ? null : require_dist.coreBlockComposition(previous), block.composition, caller);
9607
+ if (block.composition !== void 0 && !withdrawal) {
9443
9608
  const judged = await validateAgainstStore(deps, block.composition, blockId);
9444
9609
  if (!judged.validation.ok && require_dist.problemsBlockSave(judged.validation.problems)) refuse(deps, {
9445
9610
  name: block.name ?? blockId,
9446
9611
  blockId
9447
9612
  }, judged.validation, judged.memberDeviceIds);
9448
9613
  }
9449
- const previous = deps.store.get(blockId);
9450
9614
  const updated = await deps.store.updateComposition(blockId, block);
9451
9615
  await followComposedRename(deps, previous, block.name);
9452
9616
  deps.logger.info("composition updated", { meta: {
9453
9617
  blockId,
9454
9618
  by: caller?.userId ?? "system"
9455
9619
  } });
9620
+ noteWritten(deps, require_dist.coreBlockComposition(updated), caller);
9456
9621
  if (block.composition !== void 0) {
9457
9622
  const unreleased = (await deps.convergeForClaims()).filter((claim) => claim.owner === blockId);
9458
9623
  if (unreleased.length > 0) {
@@ -9528,6 +9693,257 @@ function buildCompositionApi(deps) {
9528
9693
  listComposableCaps: async ({ deviceType }) => ({ caps: [...require_dist.describeComposableCaps(deps.capabilityDefinitions, deviceType)] })
9529
9694
  };
9530
9695
  }
9696
+ function refOf(side) {
9697
+ return {
9698
+ addonId: side.addonId,
9699
+ stableId: side.stableId
9700
+ };
9701
+ }
9702
+ function fieldsFeature(feature) {
9703
+ return feature.kind === "fields" ? feature : null;
9704
+ }
9705
+ /** Compile one contribution as the Customize editor would, then stamp it. */
9706
+ function compileContribution(owed, host) {
9707
+ const out = require_dist.compileScalarOverride({
9708
+ draft: {
9709
+ kind: "scalar",
9710
+ cap: owed.contribution.cap,
9711
+ targetId: owed.contribution.targetId,
9712
+ source: {
9713
+ ...owed.source,
9714
+ cap: owed.contribution.sourceCap,
9715
+ fieldPath: owed.contribution.sourceField
9716
+ },
9717
+ transform: { kind: "identity" }
9718
+ },
9719
+ device: host,
9720
+ apply: "add",
9721
+ sourceValueKind: "boolean",
9722
+ changedAtField: null,
9723
+ sourceUnit: null
9724
+ });
9725
+ if (!out.ok) return null;
9726
+ return {
9727
+ ...out.value,
9728
+ contributedBy: { linkId: owed.link.id }
9729
+ };
9730
+ }
9731
+ var LinkContributionReconciler = class {
9732
+ ports;
9733
+ tail = Promise.resolve();
9734
+ passQueued = false;
9735
+ answered = false;
9736
+ constructor(ports) {
9737
+ this.ports = ports;
9738
+ }
9739
+ /** True once a pass has read the links — until then a device registration asks again. */
9740
+ hasAnswered() {
9741
+ return this.answered;
9742
+ }
9743
+ requestPass() {
9744
+ if (this.passQueued) return;
9745
+ this.passQueued = true;
9746
+ this.serialized(async () => {
9747
+ this.passQueued = false;
9748
+ await this.pass();
9749
+ }).catch((err) => {
9750
+ this.ports.logger.warn("identity-link contributions: pass failed — the next link event retries", { meta: { error: require_dist.errMsg(err) } });
9751
+ });
9752
+ }
9753
+ async settled() {
9754
+ await this.serialized(async () => void 0);
9755
+ }
9756
+ async pass() {
9757
+ const read = await this.ports.listLinks();
9758
+ const blocks = this.ports.blocks();
9759
+ if (read.status !== "answered" || blocks === null) return;
9760
+ this.answered = true;
9761
+ const plans = /* @__PURE__ */ new Map();
9762
+ for (const link of read.links) {
9763
+ if (link.state !== "linked" || link.evidenceGone === true) continue;
9764
+ for (const contribution of require_dist.IDENTITY_LINK_KINDS[link.kind].contributions) {
9765
+ const hostSide = link[contribution.host];
9766
+ const host = refOf(hostSide);
9767
+ const key = require_dist.compositionSourceKey(host);
9768
+ const plan = plans.get(key) ?? {
9769
+ host,
9770
+ hostDeviceId: hostSide.deviceId,
9771
+ owed: []
9772
+ };
9773
+ plan.owed.push({
9774
+ link,
9775
+ contribution,
9776
+ hostDeviceId: hostSide.deviceId,
9777
+ source: refOf(link[contribution.source])
9778
+ });
9779
+ plans.set(key, plan);
9780
+ }
9781
+ }
9782
+ for (const block of blocks) {
9783
+ const composition = require_dist.coreBlockComposition(block);
9784
+ if (composition === null || composition.target.kind !== "existing") continue;
9785
+ const stamped = composition.features.some((f) => fieldsFeature(f)?.contributedBy !== void 0);
9786
+ const host = composition.target.device;
9787
+ const key = require_dist.compositionSourceKey(host);
9788
+ if (stamped && !plans.has(key)) plans.set(key, {
9789
+ host,
9790
+ hostDeviceId: await this.hostIdOf(host, read.links),
9791
+ owed: []
9792
+ });
9793
+ }
9794
+ for (const plan of plans.values()) await this.reconcileWithRetry(plan, blocks);
9795
+ }
9796
+ /**
9797
+ * The id of a host whose stamps go: from a link that still names it (a
9798
+ * dismissed one), else from the device listing.
9799
+ */
9800
+ async hostIdOf(host, links) {
9801
+ const key = require_dist.compositionSourceKey(host);
9802
+ for (const link of links) for (const contribution of require_dist.IDENTITY_LINK_KINDS[link.kind].contributions) {
9803
+ const side = link[contribution.host];
9804
+ if (require_dist.compositionSourceKey(refOf(side)) === key) return side.deviceId;
9805
+ }
9806
+ return this.ports.deviceIdOf(host).catch(() => null);
9807
+ }
9808
+ async reconcileWithRetry(plan, first) {
9809
+ const tags = plan.hostDeviceId === null ? {} : { tags: { deviceId: plan.hostDeviceId } };
9810
+ const host = require_dist.compositionSourceKey(plan.host);
9811
+ for (let attempt = 1; attempt <= 3; attempt++) {
9812
+ const blocks = attempt === 1 ? first : this.ports.blocks();
9813
+ if (blocks === null) return;
9814
+ try {
9815
+ await this.reconcileHost(plan, blocks);
9816
+ return;
9817
+ } catch (err) {
9818
+ if (!(err instanceof CompositionChangedError)) {
9819
+ this.ports.logger.warn("identity-link contributions: host not reconciled", {
9820
+ ...tags,
9821
+ meta: {
9822
+ host,
9823
+ error: require_dist.errMsg(err)
9824
+ }
9825
+ });
9826
+ return;
9827
+ }
9828
+ }
9829
+ }
9830
+ this.ports.logger.warn(`identity-link contributions: host not reconciled — its customization changed under 3 writes in a row; the next link event or customization write retries`, {
9831
+ ...tags,
9832
+ meta: {
9833
+ host,
9834
+ attempts: 3
9835
+ }
9836
+ });
9837
+ }
9838
+ async reconcileHost(plan, blocks) {
9839
+ const key = require_dist.compositionSourceKey(plan.host);
9840
+ const block = blocks.find((b) => {
9841
+ const c = require_dist.coreBlockComposition(b);
9842
+ return c !== null && c.target.kind === "existing" && require_dist.compositionSourceKey(c.target.device) === key;
9843
+ }) ?? null;
9844
+ const composition = block === null ? null : require_dist.coreBlockComposition(block);
9845
+ const before = composition?.features ?? [];
9846
+ const owedIds = new Set(plan.owed.map((o) => o.link.id));
9847
+ let features = [];
9848
+ for (const feature of before) {
9849
+ const fields = fieldsFeature(feature);
9850
+ const stamp = fields?.contributedBy;
9851
+ if (fields === null || stamp === void 0 || owedIds.has(stamp.linkId)) {
9852
+ features.push(feature);
9853
+ continue;
9854
+ }
9855
+ const kept = require_dist.removeScalarTarget(fields, fields.cap, this.targetIdOfStamp(fields));
9856
+ if (kept !== null) features.push(kept);
9857
+ this.ports.logger.info("identity-link contribution withdrawn — its link is gone", {
9858
+ ...plan.hostDeviceId === null ? {} : { tags: { deviceId: plan.hostDeviceId } },
9859
+ meta: {
9860
+ cap: fields.cap,
9861
+ linkId: stamp.linkId,
9862
+ host: key
9863
+ }
9864
+ });
9865
+ }
9866
+ let bound = null;
9867
+ for (const owed of plan.owed) {
9868
+ const cap = owed.contribution.cap;
9869
+ const index = features.findIndex((f) => fieldsFeature(f)?.cap === cap);
9870
+ const found = index < 0 ? void 0 : features[index];
9871
+ const current = found === void 0 ? null : fieldsFeature(found);
9872
+ const compiled = compileContribution(owed, plan.host);
9873
+ if (compiled === null) {
9874
+ this.skip(owed, "the contribution does not compile against the Customize catalog");
9875
+ continue;
9876
+ }
9877
+ if (current === null) {
9878
+ bound ??= await this.ports.boundCaps(owed.hostDeviceId);
9879
+ if (bound.includes(cap)) {
9880
+ this.skip(owed, "the device serves this capability natively (D944)");
9881
+ continue;
9882
+ }
9883
+ features = [...features, compiled];
9884
+ this.log("identity-link contribution added", owed);
9885
+ continue;
9886
+ }
9887
+ const stamp = current.contributedBy;
9888
+ if (stamp === void 0) {
9889
+ this.skip(owed, "the operator already set this target in Customize");
9890
+ continue;
9891
+ }
9892
+ if (stamp.linkId !== owed.link.id) {
9893
+ this.skip(owed, `another link (${stamp.linkId}) already contributes this capability`);
9894
+ continue;
9895
+ }
9896
+ const merged = require_dist.mergeScalarTarget(current, compiled, cap, owed.contribution.targetId);
9897
+ const refreshed = current.enabled === void 0 ? merged : {
9898
+ ...merged,
9899
+ enabled: current.enabled
9900
+ };
9901
+ if (JSON.stringify(refreshed) === JSON.stringify(current)) continue;
9902
+ features = features.map((f, i) => i === index ? refreshed : f);
9903
+ this.log("identity-link contribution refreshed", owed);
9904
+ }
9905
+ if (JSON.stringify(features) === JSON.stringify(before)) return;
9906
+ if (block === null || composition === null) {
9907
+ await this.ports.create(plan.host, features);
9908
+ return;
9909
+ }
9910
+ await this.ports.update(block, {
9911
+ ...composition,
9912
+ features
9913
+ });
9914
+ }
9915
+ /** The target a stamped feature carries: the kind table names it. */
9916
+ targetIdOfStamp(feature) {
9917
+ for (const spec of Object.values(require_dist.IDENTITY_LINK_KINDS)) {
9918
+ const hit = spec.contributions.find((c) => c.cap === feature.cap);
9919
+ if (hit !== void 0) return hit.targetId;
9920
+ }
9921
+ return "";
9922
+ }
9923
+ skip(owed, reason) {
9924
+ this.ports.logger.info(`identity-link contribution skipped — ${reason}`, {
9925
+ tags: { deviceId: owed.hostDeviceId },
9926
+ meta: {
9927
+ cap: owed.contribution.cap,
9928
+ linkId: owed.link.id
9929
+ }
9930
+ });
9931
+ }
9932
+ log(message, owed) {
9933
+ this.ports.logger.info(message, {
9934
+ tags: { deviceId: owed.hostDeviceId },
9935
+ meta: {
9936
+ cap: owed.contribution.cap,
9937
+ linkId: owed.link.id
9938
+ }
9939
+ });
9940
+ }
9941
+ serialized(write) {
9942
+ const run = this.tail.then(write, write);
9943
+ this.tail = run.then(() => void 0, () => void 0);
9944
+ return run;
9945
+ }
9946
+ };
9531
9947
  //#endregion
9532
9948
  //#region src/builtins/core-blocks/sync-composed-device-name.ts
9533
9949
  /**
@@ -10049,6 +10465,10 @@ var CoreBlocksAddon = class extends require_dist.BaseAddon {
10049
10465
  powerSource = null;
10050
10466
  /** The timed-run provider (D993); its deadline timer is cancelled on shutdown. */
10051
10467
  timedRun = null;
10468
+ /** ONE composition API per process: its write queue is what keeps two saves from judging each other stale. */
10469
+ compositionApi = null;
10470
+ /** The identity-link contributions (D1063); armed at boot. */
10471
+ linkContributions = null;
10052
10472
  disposed = false;
10053
10473
  /** Seeds the lock door gate from the hub mirror; run at startup and when a composition changes. */
10054
10474
  seedLockDoorGate = () => void 0;
@@ -10123,6 +10543,7 @@ var CoreBlocksAddon = class extends require_dist.BaseAddon {
10123
10543
  });
10124
10544
  this.supervisor = this.buildSupervisor();
10125
10545
  this.supervisor?.start(CONVERGE_INTERVAL_MS);
10546
+ this.armLinkContributions();
10126
10547
  this.ctx.logger.info("core-blocks ready", { meta: {
10127
10548
  blocks: this.store.list().length,
10128
10549
  compile: this.transpiler !== null,
@@ -10226,6 +10647,14 @@ var CoreBlocksAddon = class extends require_dist.BaseAddon {
10226
10647
  const service = new PowerSourceService({
10227
10648
  blocks: () => this.store?.list() ?? [],
10228
10649
  devices: this.powerSourceDevices(),
10650
+ links: {
10651
+ read: async () => {
10652
+ const api = this.ctx.api;
10653
+ if (!api) throw new Error("core-blocks: no ctx.api on this node — identity links cannot be read");
10654
+ return api.deviceManager.listIdentityLinks.query({});
10655
+ },
10656
+ lost: () => this.linkContributions?.requestPass()
10657
+ },
10229
10658
  scheduler: timeoutScheduler,
10230
10659
  logger: this.ctx.logger.child("power-source")
10231
10660
  });
@@ -10685,6 +11114,19 @@ var CoreBlocksAddon = class extends require_dist.BaseAddon {
10685
11114
  },
10686
11115
  delete: async ({ blockId }) => {
10687
11116
  const existing = this.requireStore().get(blockId);
11117
+ const linkRefusal = linkContributionDeleteRefusal(existing);
11118
+ if (linkRefusal !== null) {
11119
+ const target = existing === null ? null : require_dist.coreBlockComposition(existing)?.target;
11120
+ const deviceId = target?.kind === "existing" ? await this.deviceIdOfRef(target.device).catch(() => null) : null;
11121
+ this.ctx.logger.warn("core block delete refused: it holds device-link contributions", {
11122
+ ...deviceId === null ? {} : { tags: { deviceId } },
11123
+ meta: {
11124
+ blockId,
11125
+ reason: linkRefusal
11126
+ }
11127
+ });
11128
+ throw new Error(linkRefusal);
11129
+ }
10688
11130
  const composition = existing !== null && require_dist.coreBlockComposition(existing) !== null;
10689
11131
  await this.requireStore().delete(blockId);
10690
11132
  await this.requirePrefs().delete(blockId);
@@ -10774,9 +11216,75 @@ var CoreBlocksAddon = class extends require_dist.BaseAddon {
10774
11216
  })) };
10775
11217
  },
10776
11218
  ...this.requireActions().runsApi,
10777
- ...this.buildCompositionApi()
11219
+ ...this.sharedCompositionApi()
10778
11220
  };
10779
11221
  }
11222
+ sharedCompositionApi() {
11223
+ this.compositionApi ??= this.buildCompositionApi();
11224
+ return this.compositionApi;
11225
+ }
11226
+ /** The device id of a composition target ref; null when no row carries it. */
11227
+ async deviceIdOfRef(ref) {
11228
+ const api = this.ctx.api;
11229
+ if (!api) throw new Error("core-blocks: no ctx.api on this node — the device cannot be resolved");
11230
+ return (await api.deviceManager.listAll.query({
11231
+ addonId: ref.addonId,
11232
+ projection: "slim"
11233
+ })).find((r) => r.stableId === ref.stableId)?.id ?? null;
11234
+ }
11235
+ /**
11236
+ * The Customize features identity links contribute (D1063). A pass runs on
11237
+ * every `identity-link.created` / `.lost`, once now, and — until a pass has
11238
+ * read the links (device-manager answers only once it has booted) — on each
11239
+ * device registration. No timer.
11240
+ */
11241
+ armLinkContributions() {
11242
+ const requireApi = () => {
11243
+ const api = this.ctx.api;
11244
+ if (!api) throw new Error("core-blocks: no ctx.api on this node — identity links cannot be read");
11245
+ return api;
11246
+ };
11247
+ const compositions = this.sharedCompositionApi();
11248
+ const store = this.requireStore();
11249
+ const caller = linkReconcilerCaller();
11250
+ const links = new LinkContributionReconciler({
11251
+ listLinks: () => requireApi().deviceManager.listIdentityLinks.query({}),
11252
+ deviceIdOf: (ref) => this.deviceIdOfRef(ref),
11253
+ boundCaps: async (deviceId) => (await requireApi().deviceManager.getBindings.query({ deviceId })).entries.map((e) => e.capName),
11254
+ blocks: () => store.isLoaded() ? store.list() : null,
11255
+ create: async (host, features) => {
11256
+ await compositions.createComposition({
11257
+ block: {
11258
+ enabled: true,
11259
+ composition: {
11260
+ target: {
11261
+ kind: "existing",
11262
+ device: host
11263
+ },
11264
+ features: [...features]
11265
+ }
11266
+ },
11267
+ caller
11268
+ });
11269
+ },
11270
+ update: async (block, composition) => {
11271
+ await compositions.updateComposition({
11272
+ blockId: block.id,
11273
+ expectedUpdatedAt: block.updatedAt,
11274
+ block: { composition },
11275
+ caller
11276
+ });
11277
+ },
11278
+ logger: this.ctx.logger.child("identity-links")
11279
+ });
11280
+ this.subscribe({ category: require_dist.EventCategory.IdentityLinkCreated }, () => links.requestPass());
11281
+ this.subscribe({ category: require_dist.EventCategory.IdentityLinkLost }, () => links.requestPass());
11282
+ this.subscribe({ category: require_dist.EventCategory.DeviceRegistered }, () => {
11283
+ if (!links.hasAnswered()) links.requestPass();
11284
+ });
11285
+ this.linkContributions = links;
11286
+ links.requestPass();
11287
+ }
10780
11288
  /**
10781
11289
  * The composition methods (D659), flat. Sources and existing targets are read
10782
11290
  * over `ctx.api` at SAVE time — one slim listing per owning addon, one binding
@@ -10820,6 +11328,7 @@ var CoreBlocksAddon = class extends require_dist.BaseAddon {
10820
11328
  this.convergeSoon();
10821
11329
  this.seedLockDoorGate();
10822
11330
  },
11331
+ compositionWritten: () => this.linkContributions?.requestPass(),
10823
11332
  convergeForClaims: () => {
10824
11333
  if (this.supervisor === null) return Promise.reject(/* @__PURE__ */ new Error("core-blocks: no block supervisor runs on this node — claims cannot be released"));
10825
11334
  return this.supervisor.convergeForClaims();