@camstack/server 1.2.899 → 1.2.900

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 +6 -0
  2. package/dist/api/trpc/generated-cap-routers.js +50 -0
  3. package/package.json +10 -9
  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 +3 -3
  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-D7UwwT1L.mjs} +1 -1
  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,7 +1,7 @@
1
- import { $a as readRecipeLiteral, $c as VocabActionError, $n as buildHeroModel, Ai as integrationInstancesCapability, Ao as runSteps, Ar as customKeyOfRole, B as DEFAULT_HOLD_OVERRIDE, Ba as planComposition, Bs as HelperMemberSchema, Cl as entryBody, Cn as TagNameSchema, Cr as coreBlockAddonId, D as CORE_BLOCK_ADDON_PREFIX, Da as normalizeCoreBlockWrite, Do as resolveStepArgs, Dr as coreBlocksCapability, Ds as weekdayOfLocalDate, E as CORE_BLOCKS_ADDON_ID, Ea as normalizeActionUnits, Ei as heroLayoutCapability, En as TemplateKindSchema, Er as coreBlockSourceKind, Fn as addonIdOfActionId, Fs as DAY_MS, Ha as powerSourceActuatorConflicts, Hc as RecordIntegrationInstances, Hn as appendTrace, Ht as NcTaggedRuleKindSchema, Ir as defaultTagColorId, Js as composedDeviceStableId, Ka as prepareRecipeUnits, Ma as occurrenceOn, Mn as actionSourceCapability, Ms as zoneOnlySite, N as CoreBlockSchema, Nn as actionWaitTotalMs, Ns as COMPOSER_ADDON_ID, Oa as normalizeTags, Ot as IDLE_ACTION_STATUS, Pn as actionsCapability, Po as schedulersCapability, Ps as CompositionSchema, Qs as compositionSourceKey, Ri as isBuiltinTemplateId, Ss as validateSchedulerInput, T as COMPOSER_RUNNER_ID, Ta as nextTimeBoundaryInMs, Ti as hasTimeLeaves, Tn as TagsFieldSchema, To as resolveRemoteSource, Tr as coreBlockIdFromAddonId, Ua as powerSourceCapability, Ui as isInternalActionId, Us as canonicalStoredBlockTarget, Vl as isSecretRefOwnedBy, Wa as powerSourceLinkOfComposition, Wn as assertStepsOffered, Xa as projectDeviceRow, Xi as kebabToCamel, Xn as buildCapabilityLookup, Yn as buildActionSteps, Ys as compositionFeatureEnabled, Za as proposeRunningThreshold, Zo as stableIdMapOf, Zt as PowerSourceInfoSchema, _ as BUILTIN_REMOTE_COMPONENTS, _l as defineAddonMigrations, _n as SetOscillationAxisInputSchema, _o as resolveCoreBlockEntry, _r as compileScalarOverride, _s as toTimings, _u as DeviceType$1, ao as reexpandAutomationInstance, ar as canonicalStoredStepTargets, bl as defineRecordKinds, br as compositionSourceRefs, bs as validateComposition, bu as EventCategory$1, c as ActionError, cn as RunningStateStatusSchema, co as remoteSourceSteps, ct as EMPTY_AUTOMATION_STATE, d as ActionTargetResolver, dl as collectSecretMarkerRefs, do as replaceRecipeLiteral, ds as templateCapability, du as vocabActionIdFor, eo as readStoredRemoteConfig, eu as resolveSecretMarkers, f as ActionVariableSchema, fn as SWITCH_DEFAULT_OPTIONS, fo as replacedFieldKeys, fr as collectDeviceTemplates, fs as timedRunCapability, ft as FAN_CAPTURE_FIELDS, fu as vocabCall, g as BUILTIN_AUTOMATION_TEMPLATES, gi as findChannelSource, gs as timedRunSeconds, gt as FanControlStatusSchema, gu as DeviceRole, h as AutomationTemplatePayloadSchema, hs as timedRunQuickRun, ic as historyRetentionFromSettings, ii as evaluateWhenTree, iu as secretTreeFromSchema, j as ConditionMirror, ji as internalActionId, ki as instanceCodeHash, kl as hydrateSchema, kt as INTERNAL_ACTION_PREFIX, l as ActionMinDelaySecSchema, lo as removeFromTags, ls as tagKey, lt as EMPTY_REMOTE_ASSUMED_STATE, lu as transformSecretWrite, m as AutomationStateDocSchema, ml as commandOrigin$1, mn as SchedulerSchema, ms as timedRunMaxIn, mt as FAN_OSCILLATION_AXIS_SETTABLE, n as ACTION_TARGET_INVALIDATION_EVENTS, nt as DeclaredDevices, on as RemoteAssumedStateSchema, oo as remoteCapability, or as capUnitResolver, pi as fanPresetsCapability, pn as SchedulerError, po as resolveActionVariables, pr as collectWhenMirrorSources, ps as timedRunLimitOf, pt as FAN_OSCILLATION_AXES, qa as problemsBlockSave, qo as siteFor, qs as composedDeviceRef, ra as localDateOf, rc as helperMembers, ri as evaluateStepCondition, rn as REMOTE_MEDIA_COMMANDS, s as ALL_CAPABILITY_DEFINITIONS, sa as lockDoorLinkOfComposition, sn as RemoteLayoutPayloadSchema, so as remoteLayoutComponentsCapability, tl as actionEffect, tn as QuantityUnitError, tr as builtinAutomationTemplate, tu as ruleFireOfClaim, u as ActionStepSchema, ui as fanAxisPath, uo as renameInTags, ur as checkTemplatePayload, us as tagsCapability, ut as EMPTY_REMOTE_CONFIG, vc as BaseAddon, vo as resolveCoreBlockFiles, vt as FanPresetSchema, vu as errMsg$1, wa as nextOccurrence, wn as TagStyleSchema, wr as coreBlockComposition, xi as generateAutomationBlock, xr as compositionUnionReads, yl as defineEntryKind, yo as resolveHeroLayout, zl as isSecretMarker, zo as seedInstanceOnce, zr as describeComposableCaps, zt as MediaPlayerStatusSchema } from "../../dist-DBanWvHF.mjs";
1
+ import { $a as problemsBlockSave, $n as buildCapabilityLookup, Aa as nextOccurrence, Al as entryBody, Ar as coreBlocksCapability, At as IDLE_ACTION_STATUS, B as DEFAULT_HOLD_OVERRIDE, Bs as COMPOSER_ADDON_ID, Ca as mergeScalarTarget, Cr as compositionSourceRefs, Cs as timedRunSeconds, Cu as DeviceRole, D as CORE_BLOCK_ADDON_PREFIX, Dl as defineRecordKinds, Dn as TagStyleSchema, Dr as coreBlockComposition, Ds as validateComposition, Du as EventCategory$1, E as CORE_BLOCKS_ADDON_ID, El as defineEntryKind, En as TagNameSchema, Eo as resolveHeroLayout, Er as coreBlockAddonId, Fi as integrationInstancesCapability, Fn as actionSourceCapability, Gn as appendTrace, Gt as NcTaggedRuleKindSchema, Hr as describeComposableCaps, Hs as DAY_MS, Ht as MediaPlayerStatusSchema, Ii as internalActionId, Il as hydrateSchema, In as actionWaitTotalMs, Ja as powerSourceActuatorConflicts, Ji as isInternalActionId, Jl as isSecretRefOwnedBy, Ka as planComposition, Kl as isSecretMarker, Ko as seedInstanceOnce, Ln as actionsCapability, Lo as runSteps, Ma as normalizeActionUnits, Mo as resolveRemoteSource, N as CoreBlockSchema, Na as normalizeCoreBlockWrite, Nr as customKeyOfRole, Oi as hasTimeLeaves, On as TagsFieldSchema, Or as coreBlockIdFromAddonId, Pa as normalizeTags, Pi as instanceCodeHash, Po as resolveStepArgs, Ps as weekdayOfLocalDate, Qa as prepareRecipeUnits, Qn as buildActionSteps, Ra as occurrenceOn, Rn as addonIdOfActionId, Ss as timedRunQuickRun, T as COMPOSER_RUNNER_ID, Tc as BaseAddon, To as resolveCoreBlockFiles, Tu as errMsg$1, Ui as isBuiltinTemplateId, Vo as schedulersCapability, Vs as CompositionSchema, Xa as powerSourceLinkOfComposition, Xs as canonicalStoredBlockTarget, Ya as powerSourceCapability, Yc as RecordIntegrationInstances, _ as BUILTIN_REMOTE_COMPONENTS, _n as SchedulerSchema, _o as renameInTags, _s as tagsCapability, _t as FanControlStatusSchema, ac as compositionSourceKey, ao as readRecipeLiteral, bn as SetOscillationAxisInputSchema, bo as resolveActionVariables, br as compileScalarOverride, bs as timedRunLimitOf, c as ActionError, ca as localDateOf, cl as actionEffect, cr as canonicalStoredStepTargets, cu as ruleFireOfClaim, d as ActionTargetResolver, dc as historyRetentionFromSettings, dn as RunningStateStatusSchema, do as reexpandAutomationInstance, dt as EMPTY_REMOTE_CONFIG, du as secretTreeFromSchema, ec as composedDeviceRef, en as PowerSourceInfoSchema, es as siteFor, f as ActionVariableSchema, fa as lockDoorLinkOfComposition, fo as remoteCapability, g as BUILTIN_AUTOMATION_TEMPLATES, gi as fanPresetsCapability, gn as SchedulerError, go as removeScalarTarget, gr as collectWhenMirrorSources, gs as tagKey, gu as transformSecretWrite, h as AutomationTemplatePayloadSchema, hn as SWITCH_DEFAULT_OPTIONS, ho as removeFromTags, hr as collectDeviceTemplates, ht as FAN_OSCILLATION_AXIS_SETTABLE, in as QuantityUnitError, ir as builtinAutomationTemplate, is as stableIdMapOf, j as ConditionMirror, ja as nextTimeBoundaryInMs, jt as INTERNAL_ACTION_PREFIX, ki as heroLayoutCapability, kn as TemplateKindSchema, kr as coreBlockSourceKind, ks as validateSchedulerInput, kt as IDENTITY_LINK_KINDS, l as ActionMinDelaySecSchema, ln as RemoteAssumedStateSchema, lr as capUnitResolver, lt as EMPTY_AUTOMATION_STATE, m as AutomationStateDocSchema, mo as remoteSourceSteps, mt as FAN_OSCILLATION_AXES, n as ACTION_TARGET_INVALIDATION_EVENTS, nc as compositionFeatureEnabled, no as projectDeviceRow, nr as buildHeroModel, nt as DeclaredDevices, oi as evaluateStepCondition, ol as VocabActionError, on as REMOTE_MEDIA_COMMANDS, oo as readStoredRemoteConfig, pi as fanAxisPath, po as remoteLayoutComponentsCapability, pr as checkTemplatePayload, pt as FAN_CAPTURE_FIELDS, qn as assertStepsOffered, qs as HelperMemberSchema, ro as proposeRunningThreshold, s as ALL_CAPABILITY_DEFINITIONS, si as evaluateWhenTree, su as resolveSecretMarkers, ta as kebabToCamel, tc as composedDeviceStableId, u as ActionStepSchema, uc as helperMembers, un as RemoteLayoutPayloadSchema, ut as EMPTY_REMOTE_ASSUMED_STATE, vl as collectSecretMarkerRefs, vo as replaceRecipeLiteral, vs as templateCapability, vu as vocabActionIdFor, wi as generateAutomationBlock, wl as defineAddonMigrations, wo as resolveCoreBlockEntry, wr as compositionUnionReads, ws as toTimings, wu as DeviceType$1, xl as commandOrigin$1, xs as timedRunMaxIn, yi as findChannelSource, yo as replacedFieldKeys, ys as timedRunCapability, yt as FanPresetSchema, yu as vocabCall, zr as defaultTagColorId, zs as zoneOnlySite } from "../../dist-S-zGcCEr.mjs";
2
2
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
3
- import { i as capSeriesKey, m as parseConfirmedStateChanged, p as isRecord$1 } from "../../capture-engine-BcD6iCZM.mjs";
4
- import { t as describeCompositionSources } from "../../composition-sources-C3ARJk2g.mjs";
3
+ import { i as capSeriesKey, m as parseConfirmedStateChanged, p as isRecord$1 } from "../../capture-engine-CCAzcezv.mjs";
4
+ import { t as describeCompositionSources } from "../../composition-sources-BX7u-Hdf.mjs";
5
5
  import { t as prefixRange } from "../../prefix-range-Dl0znowN.mjs";
6
6
  import { n as unwrapStoredValue, t as loadPrefixed } from "../../prefix-walk-DAOBSyH1.mjs";
7
7
  import { n as readCurrentCommandOrigin } from "../../cap-call-scope-Bic6Ekfw.mjs";
@@ -4262,6 +4262,15 @@ function buildActionsRuntime(deps) {
4262
4262
  * switched on or off: power on / off are refused as `not-settable`, and `getStatus`
4263
4263
  * says so (`switchSettable`) for the surfaces that withdraw them.
4264
4264
  *
4265
+ * A power source an identity link contributed (`contributedBy`, D1063) is
4266
+ * checked against that link at the point of use: the link is read over RPC
4267
+ * before every action, and one that is no longer `linked`, or now names another
4268
+ * port, refuses as `link-lost` and asks core-blocks to reconcile the
4269
+ * contributions. A read that fails, or links not loaded yet, refuse as
4270
+ * `link-unknown` — cutting power is destructive work (D49). A stamp alone is
4271
+ * never proof the port still feeds this device: the event that withdraws it
4272
+ * may have been dropped (D11).
4273
+ *
4265
4274
  * Every refusal is a typed result with its reason, logged with the device tag.
4266
4275
  */
4267
4276
  /** `switch.getOptions` FAILED (not absent): what the switch can do is unknown. */
@@ -4468,6 +4477,10 @@ var PowerSourceService = class {
4468
4477
  reason: "switch-is-actuator",
4469
4478
  message: `the linked switch ${link.switch.stableId} is one of this device's own switches, not its supply`
4470
4479
  };
4480
+ if (link.contributedBy !== void 0) {
4481
+ const refused = await this.checkContributingLink(deviceId, link, link.contributedBy.linkId);
4482
+ if (refused !== null) return refused;
4483
+ }
4471
4484
  const switchDevice = await this.deps.devices.find(link.switch).catch(() => null);
4472
4485
  if (switchDevice === null) return {
4473
4486
  kind: "refused",
@@ -4492,6 +4505,38 @@ var PowerSourceService = class {
4492
4505
  }
4493
4506
  };
4494
4507
  }
4508
+ /**
4509
+ * The identity link that contributed this power source, read now: null when it is
4510
+ * still `linked`, its evidence still holds, and its source side is the switch the
4511
+ * feature reads. An operator-confirmed link whose evidence is gone (`evidenceGone`)
4512
+ * is refused as `link-lost`: the port may now feed another device (D1063).
4513
+ */
4514
+ async checkContributingLink(deviceId, link, linkId) {
4515
+ let read;
4516
+ try {
4517
+ read = await this.deps.links.read();
4518
+ } catch (err) {
4519
+ return {
4520
+ kind: "refused",
4521
+ reason: "link-unknown",
4522
+ message: `the identity link ${linkId} that contributed this power source could not be read (${errorText$3(err)})`
4523
+ };
4524
+ }
4525
+ if (read.status !== "answered") return {
4526
+ kind: "refused",
4527
+ reason: "link-unknown",
4528
+ message: `the identity links are not loaded yet (${read.reason}); not acting through link ${linkId}`
4529
+ };
4530
+ const current = read.links.find((l) => l.id === linkId);
4531
+ const contribution = current ? IDENTITY_LINK_KINDS[current.kind].contributions.find((c) => c.cap === "power-source") : void 0;
4532
+ if (current !== void 0 && current.state === "linked" && current.evidenceGone !== true && contribution !== void 0 && compositionSourceKey(current[contribution.source]) === compositionSourceKey(link.switch)) return null;
4533
+ this.deps.links.lost(deviceId);
4534
+ return {
4535
+ kind: "refused",
4536
+ reason: "link-lost",
4537
+ 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}`
4538
+ };
4539
+ }
4495
4540
  /** The stored link of the device `deviceId`, read from the customizations now. */
4496
4541
  async linkOf(deviceId) {
4497
4542
  return (await this.storedLinkOf(deviceId))?.link ?? null;
@@ -9159,7 +9204,57 @@ function bucketStep(point) {
9159
9204
  * A customization of an existing device (D663) has no name of its own: the
9160
9205
  * server derives it (`customizationBlockName`), refuses one the client sends,
9161
9206
  * and never lets it move to another device. One per device, by block id (S2).
9207
+ *
9208
+ * A feature an identity link contributed (`contributedBy`, D1063) is switched
9209
+ * off by the operator, never removed: an update that drops one is refused as
9210
+ * `link-contribution-removed`, except the identity-link reconciler's own write
9211
+ * (`linkReconcilerCaller()`), which is how a contribution is withdrawn. Every
9212
+ * other write of a customization asks for a link pass (`compositionWritten`).
9213
+ */
9214
+ /** The `caller.userId` of the identity-link reconciler's own writes (D1063). */
9215
+ var IDENTITY_LINKS_USER_ID = "identity-links";
9216
+ /**
9217
+ * The reconciler's callers, by object identity. The gate is this set, never the
9218
+ * `userId` string: a `caller` that arrived over the wire (a forked addon's
9219
+ * `ctx.api` args reach the provider as sent) is a different object, whatever it
9220
+ * names, so it can never pass as the reconciler.
9221
+ */
9222
+ var LINK_RECONCILER_CALLERS = /* @__PURE__ */ new WeakSet();
9223
+ /** A caller that IS the identity-link reconciler — mint it in-process only. */
9224
+ function linkReconcilerCaller() {
9225
+ const caller = {
9226
+ userId: IDENTITY_LINKS_USER_ID,
9227
+ isAdmin: true
9228
+ };
9229
+ LINK_RECONCILER_CALLERS.add(caller);
9230
+ return caller;
9231
+ }
9232
+ function isLinkReconciler(writer) {
9233
+ return writer !== void 0 && LINK_RECONCILER_CALLERS.has(writer);
9234
+ }
9235
+ /** An update named an `updatedAt` the stored block no longer has: reload and re-apply. */
9236
+ var CompositionChangedError = class extends Error {
9237
+ blockId;
9238
+ constructor(blockId, name, storedUpdatedAt, expectedUpdatedAt) {
9239
+ super(`core-blocks: the composition "${name}" changed since you read it: stored updatedAt ${storedUpdatedAt}, yours ${expectedUpdatedAt} — reload and re-apply your edit`);
9240
+ this.name = "CompositionChangedError";
9241
+ this.blockId = blockId;
9242
+ }
9243
+ };
9244
+ /** The features of a composition an identity link contributed. */
9245
+ function linkContributedFeatures(composition) {
9246
+ return (composition?.features ?? []).flatMap((f) => f.kind === "fields" && f.contributedBy !== void 0 ? [f] : []);
9247
+ }
9248
+ /**
9249
+ * Why a block cannot be deleted: it holds features identity links contributed
9250
+ * (`link-contribution-removed`, D1063). Null when it can.
9162
9251
  */
9252
+ function linkContributionDeleteRefusal(block) {
9253
+ const stamped = linkContributedFeatures(block === null ? null : coreBlockComposition(block));
9254
+ if (stamped.length === 0) return null;
9255
+ const named = stamped.map((f) => `${f.cap} (device link ${f.contributedBy?.linkId ?? ""})`);
9256
+ 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`;
9257
+ }
9163
9258
  var NOT_LOADED_REASON = "core_blocks has not loaded yet";
9164
9259
  function writeQueue() {
9165
9260
  let tail = Promise.resolve();
@@ -9183,7 +9278,73 @@ function refuseIfChanged(deps, blockId, expectedUpdatedAt) {
9183
9278
  storedUpdatedAt: stored.updatedAt,
9184
9279
  expectedUpdatedAt
9185
9280
  } });
9186
- 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`);
9281
+ throw new CompositionChangedError(blockId, stored.name, stored.updatedAt, expectedUpdatedAt);
9282
+ }
9283
+ /**
9284
+ * An update that drops a link-contributed feature is refused (D1063): the
9285
+ * operator's off-switch is `enabled: false`. The reconciler's own write is how a
9286
+ * contribution is withdrawn, so it passes.
9287
+ */
9288
+ function refuseLinkContributionRemoval(deps, blockId, next, writer) {
9289
+ if (next === void 0 || isLinkReconciler(writer)) return;
9290
+ const stored = deps.store.get(blockId);
9291
+ if (stored === null) return;
9292
+ const kept = new Set(next.features.map((f) => f.cap));
9293
+ const removed = linkContributedFeatures(coreBlockComposition(stored)).filter((f) => !kept.has(f.cap));
9294
+ if (removed.length === 0) return;
9295
+ refuse(deps, {
9296
+ name: stored.name,
9297
+ blockId
9298
+ }, {
9299
+ ok: false,
9300
+ problems: removed.map((f) => ({
9301
+ code: "link-contribution-removed",
9302
+ path: `features.${f.cap}`,
9303
+ message: `${f.cap} was added by the device link ${f.contributedBy?.linkId ?? ""} — switch it off instead; unlink the device to take it away`
9304
+ })),
9305
+ fields: [],
9306
+ features: [],
9307
+ events: []
9308
+ }, []);
9309
+ }
9310
+ /**
9311
+ * The reconciler taking back what it stamped, and nothing else (D1063): the
9312
+ * composition is unchanged apart from its features (target and helper
9313
+ * included), every stored feature the operator wrote survives verbatim, and
9314
+ * every other kept feature is a stored one or an unstamped remainder of a
9315
+ * stamped one — a subset of its fields, with the same values. Removing features
9316
+ * cannot create a conflict, and a withdrawal must land on a customization whose
9317
+ * host was removed — which the store judge refuses as `target-missing` — so it
9318
+ * is not judged.
9319
+ */
9320
+ function isStampWithdrawal(stored, next, writer) {
9321
+ if (!isLinkReconciler(writer) || stored === null) return false;
9322
+ if (JSON.stringify({
9323
+ ...stored,
9324
+ features: []
9325
+ }) !== JSON.stringify({
9326
+ ...next,
9327
+ features: []
9328
+ })) return false;
9329
+ const stamped = linkContributedFeatures(stored);
9330
+ if (stamped.length === 0) return false;
9331
+ const storedKeys = new Set(stored.features.map((f) => JSON.stringify(f)));
9332
+ const nextKeys = new Set(next.features.map((f) => JSON.stringify(f)));
9333
+ const operatorKept = stored.features.every((f) => f.kind === "fields" && f.contributedBy !== void 0 || nextKeys.has(JSON.stringify(f)));
9334
+ const nothingAdded = next.features.every((f) => storedKeys.has(JSON.stringify(f)) || f.kind === "fields" && f.contributedBy === void 0 && stamped.some((from) => isRemainderOf(f, from)));
9335
+ return operatorKept && nothingAdded && next.features.length <= stored.features.length;
9336
+ }
9337
+ /** `kept` is `stamped` without its stamp, cut down to some of its fields, each unchanged. */
9338
+ function isRemainderOf(kept, stamped) {
9339
+ const { contributedBy: _stamp, fields: stampedFields, ...stampedRest } = stamped;
9340
+ const { fields: keptFields, ...keptRest } = kept;
9341
+ if (JSON.stringify(keptRest) !== JSON.stringify(stampedRest)) return false;
9342
+ return Object.entries(keptFields).every(([path, value]) => Object.hasOwn(stampedFields, path) && JSON.stringify(stampedFields[path]) === JSON.stringify(value));
9343
+ }
9344
+ function noteWritten(deps, composition, writer) {
9345
+ if (composition === null || composition.target.kind !== "existing") return;
9346
+ if (writer === void 0 || isLinkReconciler(writer)) return;
9347
+ deps.compositionWritten?.(composition.target.device, writer);
9187
9348
  }
9188
9349
  /** The device a composition writes, when it is an EXISTING one; null for a new device. */
9189
9350
  function existingTarget(composition) {
@@ -9417,26 +9578,30 @@ function buildCompositionApi(deps) {
9417
9578
  name: created.name,
9418
9579
  by: caller.userId
9419
9580
  } });
9581
+ noteWritten(deps, block.composition, caller);
9420
9582
  deps.convergeSoon();
9421
9583
  return { block: created };
9422
9584
  }),
9423
9585
  updateComposition: ({ blockId, expectedUpdatedAt, block, caller }) => serialized(async () => {
9424
9586
  refuseIfChanged(deps, blockId, expectedUpdatedAt);
9587
+ refuseLinkContributionRemoval(deps, blockId, block.composition, caller);
9425
9588
  await refuseRetarget(deps, blockId, block);
9426
- if (block.composition !== void 0) {
9589
+ const previous = deps.store.get(blockId);
9590
+ const withdrawal = block.composition !== void 0 && isStampWithdrawal(previous === null ? null : coreBlockComposition(previous), block.composition, caller);
9591
+ if (block.composition !== void 0 && !withdrawal) {
9427
9592
  const judged = await validateAgainstStore(deps, block.composition, blockId);
9428
9593
  if (!judged.validation.ok && problemsBlockSave(judged.validation.problems)) refuse(deps, {
9429
9594
  name: block.name ?? blockId,
9430
9595
  blockId
9431
9596
  }, judged.validation, judged.memberDeviceIds);
9432
9597
  }
9433
- const previous = deps.store.get(blockId);
9434
9598
  const updated = await deps.store.updateComposition(blockId, block);
9435
9599
  await followComposedRename(deps, previous, block.name);
9436
9600
  deps.logger.info("composition updated", { meta: {
9437
9601
  blockId,
9438
9602
  by: caller?.userId ?? "system"
9439
9603
  } });
9604
+ noteWritten(deps, coreBlockComposition(updated), caller);
9440
9605
  if (block.composition !== void 0) {
9441
9606
  const unreleased = (await deps.convergeForClaims()).filter((claim) => claim.owner === blockId);
9442
9607
  if (unreleased.length > 0) {
@@ -9512,6 +9677,257 @@ function buildCompositionApi(deps) {
9512
9677
  listComposableCaps: async ({ deviceType }) => ({ caps: [...describeComposableCaps(deps.capabilityDefinitions, deviceType)] })
9513
9678
  };
9514
9679
  }
9680
+ function refOf(side) {
9681
+ return {
9682
+ addonId: side.addonId,
9683
+ stableId: side.stableId
9684
+ };
9685
+ }
9686
+ function fieldsFeature(feature) {
9687
+ return feature.kind === "fields" ? feature : null;
9688
+ }
9689
+ /** Compile one contribution as the Customize editor would, then stamp it. */
9690
+ function compileContribution(owed, host) {
9691
+ const out = compileScalarOverride({
9692
+ draft: {
9693
+ kind: "scalar",
9694
+ cap: owed.contribution.cap,
9695
+ targetId: owed.contribution.targetId,
9696
+ source: {
9697
+ ...owed.source,
9698
+ cap: owed.contribution.sourceCap,
9699
+ fieldPath: owed.contribution.sourceField
9700
+ },
9701
+ transform: { kind: "identity" }
9702
+ },
9703
+ device: host,
9704
+ apply: "add",
9705
+ sourceValueKind: "boolean",
9706
+ changedAtField: null,
9707
+ sourceUnit: null
9708
+ });
9709
+ if (!out.ok) return null;
9710
+ return {
9711
+ ...out.value,
9712
+ contributedBy: { linkId: owed.link.id }
9713
+ };
9714
+ }
9715
+ var LinkContributionReconciler = class {
9716
+ ports;
9717
+ tail = Promise.resolve();
9718
+ passQueued = false;
9719
+ answered = false;
9720
+ constructor(ports) {
9721
+ this.ports = ports;
9722
+ }
9723
+ /** True once a pass has read the links — until then a device registration asks again. */
9724
+ hasAnswered() {
9725
+ return this.answered;
9726
+ }
9727
+ requestPass() {
9728
+ if (this.passQueued) return;
9729
+ this.passQueued = true;
9730
+ this.serialized(async () => {
9731
+ this.passQueued = false;
9732
+ await this.pass();
9733
+ }).catch((err) => {
9734
+ this.ports.logger.warn("identity-link contributions: pass failed — the next link event retries", { meta: { error: errMsg$1(err) } });
9735
+ });
9736
+ }
9737
+ async settled() {
9738
+ await this.serialized(async () => void 0);
9739
+ }
9740
+ async pass() {
9741
+ const read = await this.ports.listLinks();
9742
+ const blocks = this.ports.blocks();
9743
+ if (read.status !== "answered" || blocks === null) return;
9744
+ this.answered = true;
9745
+ const plans = /* @__PURE__ */ new Map();
9746
+ for (const link of read.links) {
9747
+ if (link.state !== "linked" || link.evidenceGone === true) continue;
9748
+ for (const contribution of IDENTITY_LINK_KINDS[link.kind].contributions) {
9749
+ const hostSide = link[contribution.host];
9750
+ const host = refOf(hostSide);
9751
+ const key = compositionSourceKey(host);
9752
+ const plan = plans.get(key) ?? {
9753
+ host,
9754
+ hostDeviceId: hostSide.deviceId,
9755
+ owed: []
9756
+ };
9757
+ plan.owed.push({
9758
+ link,
9759
+ contribution,
9760
+ hostDeviceId: hostSide.deviceId,
9761
+ source: refOf(link[contribution.source])
9762
+ });
9763
+ plans.set(key, plan);
9764
+ }
9765
+ }
9766
+ for (const block of blocks) {
9767
+ const composition = coreBlockComposition(block);
9768
+ if (composition === null || composition.target.kind !== "existing") continue;
9769
+ const stamped = composition.features.some((f) => fieldsFeature(f)?.contributedBy !== void 0);
9770
+ const host = composition.target.device;
9771
+ const key = compositionSourceKey(host);
9772
+ if (stamped && !plans.has(key)) plans.set(key, {
9773
+ host,
9774
+ hostDeviceId: await this.hostIdOf(host, read.links),
9775
+ owed: []
9776
+ });
9777
+ }
9778
+ for (const plan of plans.values()) await this.reconcileWithRetry(plan, blocks);
9779
+ }
9780
+ /**
9781
+ * The id of a host whose stamps go: from a link that still names it (a
9782
+ * dismissed one), else from the device listing.
9783
+ */
9784
+ async hostIdOf(host, links) {
9785
+ const key = compositionSourceKey(host);
9786
+ for (const link of links) for (const contribution of IDENTITY_LINK_KINDS[link.kind].contributions) {
9787
+ const side = link[contribution.host];
9788
+ if (compositionSourceKey(refOf(side)) === key) return side.deviceId;
9789
+ }
9790
+ return this.ports.deviceIdOf(host).catch(() => null);
9791
+ }
9792
+ async reconcileWithRetry(plan, first) {
9793
+ const tags = plan.hostDeviceId === null ? {} : { tags: { deviceId: plan.hostDeviceId } };
9794
+ const host = compositionSourceKey(plan.host);
9795
+ for (let attempt = 1; attempt <= 3; attempt++) {
9796
+ const blocks = attempt === 1 ? first : this.ports.blocks();
9797
+ if (blocks === null) return;
9798
+ try {
9799
+ await this.reconcileHost(plan, blocks);
9800
+ return;
9801
+ } catch (err) {
9802
+ if (!(err instanceof CompositionChangedError)) {
9803
+ this.ports.logger.warn("identity-link contributions: host not reconciled", {
9804
+ ...tags,
9805
+ meta: {
9806
+ host,
9807
+ error: errMsg$1(err)
9808
+ }
9809
+ });
9810
+ return;
9811
+ }
9812
+ }
9813
+ }
9814
+ 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`, {
9815
+ ...tags,
9816
+ meta: {
9817
+ host,
9818
+ attempts: 3
9819
+ }
9820
+ });
9821
+ }
9822
+ async reconcileHost(plan, blocks) {
9823
+ const key = compositionSourceKey(plan.host);
9824
+ const block = blocks.find((b) => {
9825
+ const c = coreBlockComposition(b);
9826
+ return c !== null && c.target.kind === "existing" && compositionSourceKey(c.target.device) === key;
9827
+ }) ?? null;
9828
+ const composition = block === null ? null : coreBlockComposition(block);
9829
+ const before = composition?.features ?? [];
9830
+ const owedIds = new Set(plan.owed.map((o) => o.link.id));
9831
+ let features = [];
9832
+ for (const feature of before) {
9833
+ const fields = fieldsFeature(feature);
9834
+ const stamp = fields?.contributedBy;
9835
+ if (fields === null || stamp === void 0 || owedIds.has(stamp.linkId)) {
9836
+ features.push(feature);
9837
+ continue;
9838
+ }
9839
+ const kept = removeScalarTarget(fields, fields.cap, this.targetIdOfStamp(fields));
9840
+ if (kept !== null) features.push(kept);
9841
+ this.ports.logger.info("identity-link contribution withdrawn — its link is gone", {
9842
+ ...plan.hostDeviceId === null ? {} : { tags: { deviceId: plan.hostDeviceId } },
9843
+ meta: {
9844
+ cap: fields.cap,
9845
+ linkId: stamp.linkId,
9846
+ host: key
9847
+ }
9848
+ });
9849
+ }
9850
+ let bound = null;
9851
+ for (const owed of plan.owed) {
9852
+ const cap = owed.contribution.cap;
9853
+ const index = features.findIndex((f) => fieldsFeature(f)?.cap === cap);
9854
+ const found = index < 0 ? void 0 : features[index];
9855
+ const current = found === void 0 ? null : fieldsFeature(found);
9856
+ const compiled = compileContribution(owed, plan.host);
9857
+ if (compiled === null) {
9858
+ this.skip(owed, "the contribution does not compile against the Customize catalog");
9859
+ continue;
9860
+ }
9861
+ if (current === null) {
9862
+ bound ??= await this.ports.boundCaps(owed.hostDeviceId);
9863
+ if (bound.includes(cap)) {
9864
+ this.skip(owed, "the device serves this capability natively (D944)");
9865
+ continue;
9866
+ }
9867
+ features = [...features, compiled];
9868
+ this.log("identity-link contribution added", owed);
9869
+ continue;
9870
+ }
9871
+ const stamp = current.contributedBy;
9872
+ if (stamp === void 0) {
9873
+ this.skip(owed, "the operator already set this target in Customize");
9874
+ continue;
9875
+ }
9876
+ if (stamp.linkId !== owed.link.id) {
9877
+ this.skip(owed, `another link (${stamp.linkId}) already contributes this capability`);
9878
+ continue;
9879
+ }
9880
+ const merged = mergeScalarTarget(current, compiled, cap, owed.contribution.targetId);
9881
+ const refreshed = current.enabled === void 0 ? merged : {
9882
+ ...merged,
9883
+ enabled: current.enabled
9884
+ };
9885
+ if (JSON.stringify(refreshed) === JSON.stringify(current)) continue;
9886
+ features = features.map((f, i) => i === index ? refreshed : f);
9887
+ this.log("identity-link contribution refreshed", owed);
9888
+ }
9889
+ if (JSON.stringify(features) === JSON.stringify(before)) return;
9890
+ if (block === null || composition === null) {
9891
+ await this.ports.create(plan.host, features);
9892
+ return;
9893
+ }
9894
+ await this.ports.update(block, {
9895
+ ...composition,
9896
+ features
9897
+ });
9898
+ }
9899
+ /** The target a stamped feature carries: the kind table names it. */
9900
+ targetIdOfStamp(feature) {
9901
+ for (const spec of Object.values(IDENTITY_LINK_KINDS)) {
9902
+ const hit = spec.contributions.find((c) => c.cap === feature.cap);
9903
+ if (hit !== void 0) return hit.targetId;
9904
+ }
9905
+ return "";
9906
+ }
9907
+ skip(owed, reason) {
9908
+ this.ports.logger.info(`identity-link contribution skipped — ${reason}`, {
9909
+ tags: { deviceId: owed.hostDeviceId },
9910
+ meta: {
9911
+ cap: owed.contribution.cap,
9912
+ linkId: owed.link.id
9913
+ }
9914
+ });
9915
+ }
9916
+ log(message, owed) {
9917
+ this.ports.logger.info(message, {
9918
+ tags: { deviceId: owed.hostDeviceId },
9919
+ meta: {
9920
+ cap: owed.contribution.cap,
9921
+ linkId: owed.link.id
9922
+ }
9923
+ });
9924
+ }
9925
+ serialized(write) {
9926
+ const run = this.tail.then(write, write);
9927
+ this.tail = run.then(() => void 0, () => void 0);
9928
+ return run;
9929
+ }
9930
+ };
9515
9931
  //#endregion
9516
9932
  //#region src/builtins/core-blocks/sync-composed-device-name.ts
9517
9933
  /**
@@ -10033,6 +10449,10 @@ var CoreBlocksAddon = class extends BaseAddon {
10033
10449
  powerSource = null;
10034
10450
  /** The timed-run provider (D993); its deadline timer is cancelled on shutdown. */
10035
10451
  timedRun = null;
10452
+ /** ONE composition API per process: its write queue is what keeps two saves from judging each other stale. */
10453
+ compositionApi = null;
10454
+ /** The identity-link contributions (D1063); armed at boot. */
10455
+ linkContributions = null;
10036
10456
  disposed = false;
10037
10457
  /** Seeds the lock door gate from the hub mirror; run at startup and when a composition changes. */
10038
10458
  seedLockDoorGate = () => void 0;
@@ -10107,6 +10527,7 @@ var CoreBlocksAddon = class extends BaseAddon {
10107
10527
  });
10108
10528
  this.supervisor = this.buildSupervisor();
10109
10529
  this.supervisor?.start(CONVERGE_INTERVAL_MS);
10530
+ this.armLinkContributions();
10110
10531
  this.ctx.logger.info("core-blocks ready", { meta: {
10111
10532
  blocks: this.store.list().length,
10112
10533
  compile: this.transpiler !== null,
@@ -10210,6 +10631,14 @@ var CoreBlocksAddon = class extends BaseAddon {
10210
10631
  const service = new PowerSourceService({
10211
10632
  blocks: () => this.store?.list() ?? [],
10212
10633
  devices: this.powerSourceDevices(),
10634
+ links: {
10635
+ read: async () => {
10636
+ const api = this.ctx.api;
10637
+ if (!api) throw new Error("core-blocks: no ctx.api on this node — identity links cannot be read");
10638
+ return api.deviceManager.listIdentityLinks.query({});
10639
+ },
10640
+ lost: () => this.linkContributions?.requestPass()
10641
+ },
10213
10642
  scheduler: timeoutScheduler,
10214
10643
  logger: this.ctx.logger.child("power-source")
10215
10644
  });
@@ -10669,6 +11098,19 @@ var CoreBlocksAddon = class extends BaseAddon {
10669
11098
  },
10670
11099
  delete: async ({ blockId }) => {
10671
11100
  const existing = this.requireStore().get(blockId);
11101
+ const linkRefusal = linkContributionDeleteRefusal(existing);
11102
+ if (linkRefusal !== null) {
11103
+ const target = existing === null ? null : coreBlockComposition(existing)?.target;
11104
+ const deviceId = target?.kind === "existing" ? await this.deviceIdOfRef(target.device).catch(() => null) : null;
11105
+ this.ctx.logger.warn("core block delete refused: it holds device-link contributions", {
11106
+ ...deviceId === null ? {} : { tags: { deviceId } },
11107
+ meta: {
11108
+ blockId,
11109
+ reason: linkRefusal
11110
+ }
11111
+ });
11112
+ throw new Error(linkRefusal);
11113
+ }
10672
11114
  const composition = existing !== null && coreBlockComposition(existing) !== null;
10673
11115
  await this.requireStore().delete(blockId);
10674
11116
  await this.requirePrefs().delete(blockId);
@@ -10758,9 +11200,75 @@ var CoreBlocksAddon = class extends BaseAddon {
10758
11200
  })) };
10759
11201
  },
10760
11202
  ...this.requireActions().runsApi,
10761
- ...this.buildCompositionApi()
11203
+ ...this.sharedCompositionApi()
10762
11204
  };
10763
11205
  }
11206
+ sharedCompositionApi() {
11207
+ this.compositionApi ??= this.buildCompositionApi();
11208
+ return this.compositionApi;
11209
+ }
11210
+ /** The device id of a composition target ref; null when no row carries it. */
11211
+ async deviceIdOfRef(ref) {
11212
+ const api = this.ctx.api;
11213
+ if (!api) throw new Error("core-blocks: no ctx.api on this node — the device cannot be resolved");
11214
+ return (await api.deviceManager.listAll.query({
11215
+ addonId: ref.addonId,
11216
+ projection: "slim"
11217
+ })).find((r) => r.stableId === ref.stableId)?.id ?? null;
11218
+ }
11219
+ /**
11220
+ * The Customize features identity links contribute (D1063). A pass runs on
11221
+ * every `identity-link.created` / `.lost`, once now, and — until a pass has
11222
+ * read the links (device-manager answers only once it has booted) — on each
11223
+ * device registration. No timer.
11224
+ */
11225
+ armLinkContributions() {
11226
+ const requireApi = () => {
11227
+ const api = this.ctx.api;
11228
+ if (!api) throw new Error("core-blocks: no ctx.api on this node — identity links cannot be read");
11229
+ return api;
11230
+ };
11231
+ const compositions = this.sharedCompositionApi();
11232
+ const store = this.requireStore();
11233
+ const caller = linkReconcilerCaller();
11234
+ const links = new LinkContributionReconciler({
11235
+ listLinks: () => requireApi().deviceManager.listIdentityLinks.query({}),
11236
+ deviceIdOf: (ref) => this.deviceIdOfRef(ref),
11237
+ boundCaps: async (deviceId) => (await requireApi().deviceManager.getBindings.query({ deviceId })).entries.map((e) => e.capName),
11238
+ blocks: () => store.isLoaded() ? store.list() : null,
11239
+ create: async (host, features) => {
11240
+ await compositions.createComposition({
11241
+ block: {
11242
+ enabled: true,
11243
+ composition: {
11244
+ target: {
11245
+ kind: "existing",
11246
+ device: host
11247
+ },
11248
+ features: [...features]
11249
+ }
11250
+ },
11251
+ caller
11252
+ });
11253
+ },
11254
+ update: async (block, composition) => {
11255
+ await compositions.updateComposition({
11256
+ blockId: block.id,
11257
+ expectedUpdatedAt: block.updatedAt,
11258
+ block: { composition },
11259
+ caller
11260
+ });
11261
+ },
11262
+ logger: this.ctx.logger.child("identity-links")
11263
+ });
11264
+ this.subscribe({ category: EventCategory$1.IdentityLinkCreated }, () => links.requestPass());
11265
+ this.subscribe({ category: EventCategory$1.IdentityLinkLost }, () => links.requestPass());
11266
+ this.subscribe({ category: EventCategory$1.DeviceRegistered }, () => {
11267
+ if (!links.hasAnswered()) links.requestPass();
11268
+ });
11269
+ this.linkContributions = links;
11270
+ links.requestPass();
11271
+ }
10764
11272
  /**
10765
11273
  * The composition methods (D659), flat. Sources and existing targets are read
10766
11274
  * over `ctx.api` at SAVE time — one slim listing per owning addon, one binding
@@ -10804,6 +11312,7 @@ var CoreBlocksAddon = class extends BaseAddon {
10804
11312
  this.convergeSoon();
10805
11313
  this.seedLockDoorGate();
10806
11314
  },
11315
+ compositionWritten: () => this.linkContributions?.requestPass(),
10807
11316
  convergeForClaims: () => {
10808
11317
  if (this.supervisor === null) return Promise.reject(/* @__PURE__ */ new Error("core-blocks: no block supervisor runs on this node — claims cannot be released"));
10809
11318
  return this.supervisor.convergeForClaims();