@camstack/server 1.2.820 → 1.2.822

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-mounts.js +3 -1
  3. package/dist/api/trpc/generated-cap-routers.js +1863 -1697
  4. package/package.json +10 -24
  5. package/system/dist/{agent-https-XHjvcSEq.mjs → agent-https-C4yxMErF.mjs} +1 -1
  6. package/system/dist/{agent-https-CbysxRlV.js → agent-https-SGBI0xP8.js} +1 -1
  7. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  8. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  9. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  10. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  11. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  12. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  13. package/system/dist/builtins/autotrack/index.js +1 -1
  14. package/system/dist/builtins/autotrack/index.mjs +1 -1
  15. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  16. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  17. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  18. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  19. package/system/dist/builtins/camera-grid/index.js +1 -1
  20. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  21. package/system/dist/builtins/composer/composer.addon.js +3 -3
  22. package/system/dist/builtins/composer/composer.addon.mjs +3 -3
  23. package/system/dist/builtins/console-logging/index.js +1 -1
  24. package/system/dist/builtins/console-logging/index.mjs +1 -1
  25. package/system/dist/builtins/core-blocks/actions-service.d.ts +16 -0
  26. package/system/dist/builtins/core-blocks/core-blocks.addon.js +158 -9
  27. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +158 -9
  28. package/system/dist/builtins/core-blocks/device-template-door.d.ts +25 -0
  29. package/system/dist/builtins/core-blocks/fan-presets-service.d.ts +5 -0
  30. package/system/dist/builtins/core-blocks/hero-layout-service.d.ts +2 -0
  31. package/system/dist/builtins/core-blocks/scheduler/scheduler-engine.d.ts +5 -0
  32. package/system/dist/builtins/core-blocks/step-condition-door.d.ts +19 -0
  33. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  34. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  35. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +7 -0
  36. package/system/dist/builtins/device-manager/device-manager.addon.js +655 -2
  37. package/system/dist/builtins/device-manager/device-manager.addon.mjs +653 -1
  38. package/system/dist/builtins/device-manager/device-template/template-host.d.ts +60 -0
  39. package/system/dist/builtins/device-manager/device-template-actions.d.ts +33 -0
  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 +2 -2
  49. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  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 +9 -9
  71. package/system/dist/builtins/system-config/system-config.addon.mjs +6 -6
  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-CKtkENOg.js → capture-engine-6MVUyUry.js} +1 -1
  75. package/system/dist/{capture-engine-WSpdP-gE.mjs → capture-engine-BSjE-CQA.mjs} +1 -1
  76. package/system/dist/{composition-sources-6Qx72gmK.js → composition-sources-BBAOXZdC.js} +1 -1
  77. package/system/dist/{composition-sources-Dr6uwBGw.mjs → composition-sources-C8T9DRbZ.mjs} +1 -1
  78. package/system/dist/{constants-URzk8siY.mjs → constants-CReG6K4k.mjs} +1 -1
  79. package/system/dist/{constants-BchSDmTD.js → constants-v0g9--wN.js} +1 -1
  80. package/system/dist/{device-ca-kANxsBE5.js → device-ca-BFcBTfff.js} +1 -1
  81. package/system/dist/{device-ca-Bu1E5Vgr.mjs → device-ca-cX8qUs2s.mjs} +1 -1
  82. package/system/dist/device-template-worker.js +5 -7032
  83. package/system/dist/device-template-worker.mjs +1 -7026
  84. package/system/dist/{dist-R_mOSFtH.js → dist-C2czR9xK.js} +2077 -167
  85. package/system/dist/{dist-C0Df8iJl.mjs → dist-DjBZ1HhF.mjs} +2036 -168
  86. package/system/dist/file-host-worker.js +1 -1
  87. package/system/dist/file-host-worker.mjs +1 -1
  88. package/system/dist/{hub-mdns-ciao-pxgLcmqO.mjs → hub-mdns-ciao-Cnr8xiSd.mjs} +2 -2
  89. package/system/dist/{hub-mdns-ciao-2AZ3ucDO.js → hub-mdns-ciao-CpCleue0.js} +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-Cj58BS60.mjs → legacy-integration-rows-door-CGajkVPh.mjs} +1 -1
  93. package/system/dist/{legacy-integration-rows-door-g4CeLJ9g.js → legacy-integration-rows-door-DhW6mPZj.js} +1 -1
  94. package/system/dist/{restore-archive-CAh7u-rY.js → restore-archive-BLab80kx.js} +7 -7
  95. package/system/dist/{restore-archive-Bd7fgVo8.mjs → restore-archive-eA7L58KT.mjs} +8 -8
  96. package/system/dist/template-protocol-BmMM5VBf.mjs +7033 -0
  97. package/system/dist/template-protocol-CTP4eAo_.js +7059 -0
  98. package/system/dist/{wal-maintenance-DMf2oEQ-.mjs → wal-maintenance-DeBxoOFh.mjs} +0 -0
  99. package/system/dist/{wal-maintenance--0liHBxL.js → wal-maintenance-DhnSF7K-.js} +0 -0
  100. package/system/package.json +1 -1
@@ -1,7 +1,7 @@
1
- import { $ as EMPTY_AUTOMATION_STATE, $a as templateCapability, $n as coreBlocksCapability, $o as BaseAddon, $s as defineEntryKind, A as ControlStatusSchema, Ai as nextOccurrence, An as buildHeroModel, Ao as composedDeviceRef, Bo as helperMembers, Bt as REMOTE_MEDIA_COMMANDS, C as CORE_BLOCKS_ADDON_ID, Cs as RecordIntegrationInstances, Dn as buildCapabilityLookup, Ea as runSteps, En as buildActionSteps, Eo as HelperMemberSchema, Fn as capUnitResolver, Fo as compositionSourceKey, Fr as findChannelSource, Fs as actionEffect, Gr as internalActionId, Gs as collectSecretMarkerRefs, Gt as RunningStateStatusSchema, Ha as stableIdMapOf, Hc as transformSecretWrite, J as DeclaredDevices, Jc as DeviceType$1, Ji as powerSourceCapability, Js as commandOrigin, Ki as planComposition, Lc as secretTreeFromSchema, Ma as seedInstanceOnce, Mi as normalizeCapStep, Mr as fanPresetsCapability, Ni as normalizeCoreBlockWrite, O as ConditionMirror, Oa as schedulersCapability, Pc as resolveSecretMarkers, Pi as normalizeStepTargets, Pt as PowerSourceInfoSchema, Qn as coreBlockSourceKind, R as DEFAULT_HOLD_OVERRIDE, Ra as siteFor, Ri as occurrenceOn, Rt as QuantityUnitError, S as COMPOSER_RUNNER_ID, Sa as resolveRemoteSource, Tr as evaluateWhenTree, Tt as MediaPlayerStatusSchema, Ur as heroLayoutCapability, Ut as RemoteAssumedStateSchema, Vn as collectWhenMirrorSources, Vo as historyRetentionFromSettings, Wc as vocabActionIdFor, Wn as compileScalarOverride, Wr as integrationInstancesCapability, Wt as RemoteLayoutPayloadSchema, Xn as coreBlockComposition, Xt as SchedulerSchema, Yc as errMsg$1, Yi as powerSourceLinkOfComposition, Yn as coreBlockAddonId, Yt as SchedulerError, Zc as EventCategory$1, Zi as problemsBlockSave, Zn as coreBlockIdFromAddonId, Zs as defineAddonMigrations, ai as kebabToCamel, an as TemplateKindSchema, ao as toTimings, bo as CompositionSchema, c as ActionError, ca as remoteLayoutComponentsCapability, co as validateComposition, d as ActionVariableSchema, da as resolveActionVariables, di as localDateOf, dn as actionsCapability, ea as projectDeviceRow, ec as defineRecordKinds, ei as isInternalActionId, eo as timedRunCapability, et as EMPTY_REMOTE_ASSUMED_STATE, fn as addonIdOfActionId, ga as resolveHeroLayout, gt as INTERNAL_ACTION_PREFIX, ha as resolveCoreBlockFiles, hi as lockDoorLinkOfComposition, ho as weekdayOfLocalDate, ht as IDLE_ACTION_STATUS, in as SwitchStatusSchema, io as timedRunSeconds, it as FanControlStatusSchema, j as CoreBlockSchema, ji as normalizeActionUnits, l as ActionStepSchema, la as remoteSourceSteps, lc as hydrateSchema, ln as actionSourceCapability, m as BUILTIN_REMOTE_COMPONENTS, ma as resolveCoreBlockEntry, n as ACTION_TARGET_INVALIDATION_EVENTS, no as timedRunMaxIn, nr as customKeyOfRole, nt as FAN_CAPTURE_FIELDS, ot as FanPresetSchema, p as AutomationStateDocSchema, qn as compositionSourceRefs, ra as readStoredRemoteConfig, rc as entryBody, ro as timedRunQuickRun, s as ALL_CAPABILITY_DEFINITIONS, sa as remoteCapability, ta as proposeRunningThreshold, to as timedRunLimitOf, tt as EMPTY_REMOTE_CONFIG, u as ActionTargetResolver, ua as replacedFieldKeys, un as actionWaitTotalMs, uo as validateSchedulerInput, ur as describeComposableCaps, vo as zoneOnlySite, w as CORE_BLOCK_ADDON_PREFIX, wa as resolveStepArgs, xc as isSecretRefOwnedBy, xo as DAY_MS, yc as isSecretMarker, yn as appendTrace, zn as checkTemplatePayload } from "../../dist-C0Df8iJl.mjs";
1
+ import { $i as powerSourceCapability, $n as coreBlockAddonId, $t as SchedulerSchema, A as ControlStatusSchema, An as buildCapabilityLookup, Ar as evaluateWhenTree, As as RecordIntegrationInstances, Br as findChannelSource, C as CORE_BLOCKS_ADDON_ID, Da as resolveRemoteSource, Do as CompositionSchema, Ec as isSecretMarker, Fa as schedulersCapability, Fi as nextOccurrence, Ga as siteFor, Gn as collectWhenMirrorSources, Hn as checkTemplatePayload, Ho as compositionSourceKey, Hs as actionEffect, Ii as normalizeActionUnits, Jn as compileScalarOverride, Jo as historyRetentionFromSettings, Jr as heroLayoutCapability, Jt as RunningStateStatusSchema, Kt as RemoteAssumedStateSchema, Li as normalizeCapStep, Lo as composedDeviceRef, Lr as fanPresetsCapability, Lt as PowerSourceInfoSchema, Ma as runSteps, Nn as buildHeroModel, No as HelperMemberSchema, O as ConditionMirror, Oc as isSecretRefOwnedBy, Oo as DAY_MS, Ot as MediaPlayerStatusSchema, Qs as collectSecretMarkerRefs, Qt as SchedulerError, R as DEFAULT_HOLD_OVERRIDE, Ri as normalizeCoreBlockWrite, Rn as capUnitResolver, S as COMPOSER_RUNNER_ID, Sn as appendTrace, So as weekdayOfLocalDate, To as zoneOnlySite, Ui as occurrenceOn, Ut as REMOTE_MEDIA_COMMANDS, Vc as resolveSecretMarkers, Vt as QuantityUnitError, Wc as secretTreeFromSchema, Wn as collectDeviceTemplates, Xr as internalActionId, Ya as stableIdMapOf, Yc as transformSecretWrite, Yr as integrationInstancesCapability, Z as DeclaredDevices, Zc as vocabActionIdFor, Zi as planComposition, Zn as compositionSourceRefs, _o as validateSchedulerInput, aa as projectDeviceRow, ai as isInternalActionId, at as FAN_CAPTURE_FIELDS, ba as resolveCoreBlockFiles, bi as lockDoorLinkOfComposition, c as ActionError, ca as readStoredRemoteConfig, cn as TemplateKindSchema, co as timedRunLimitOf, d as ActionVariableSchema, do as timedRunSeconds, ea as powerSourceLinkOfComposition, er as coreBlockComposition, fa as remoteCapability, fn as actionSourceCapability, fo as toTimings, ga as resolveActionVariables, gc as hydrateSchema, gi as localDateOf, ha as replacedFieldKeys, hn as addonIdOfActionId, ho as validateComposition, ic as defineAddonMigrations, il as EventCategory$1, it as EMPTY_REMOTE_CONFIG, j as CoreBlockSchema, ka as resolveStepArgs, kn as buildActionSteps, kr as evaluateStepCondition, l as ActionStepSchema, lo as timedRunMaxIn, lt as FanPresetSchema, m as BUILTIN_REMOTE_COMPONENTS, ma as remoteSourceSteps, mn as actionsCapability, mr as describeComposableCaps, n as ACTION_TARGET_INVALIDATION_EVENTS, na as problemsBlockSave, nl as errMsg$1, nr as coreBlockSourceKind, nt as EMPTY_AUTOMATION_STATE, oa as proposeRunningThreshold, oc as defineEntryKind, oo as templateCapability, or as customKeyOfRole, os as BaseAddon, p as AutomationStateDocSchema, pa as remoteLayoutComponentsCapability, pn as actionWaitTotalMs, qo as helperMembers, qt as RemoteLayoutPayloadSchema, rr as coreBlocksCapability, rt as EMPTY_REMOTE_ASSUMED_STATE, s as ALL_CAPABILITY_DEFINITIONS, sc as defineRecordKinds, sn as SwitchStatusSchema, so as timedRunCapability, st as FanControlStatusSchema, tc as commandOrigin, tl as DeviceType$1, tr as coreBlockIdFromAddonId, u as ActionTargetResolver, uc as entryBody, ui as kebabToCamel, uo as timedRunQuickRun, vt as IDLE_ACTION_STATUS, w as CORE_BLOCK_ADDON_PREFIX, xa as resolveHeroLayout, ya as resolveCoreBlockEntry, yt as INTERNAL_ACTION_PREFIX, za as seedInstanceOnce, zi as normalizeStepTargets } from "../../dist-DjBZ1HhF.mjs";
2
2
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
3
- import { i as parseDeviceStateChanged, r as isRecord$1, t as describeCompositionSources } from "../../composition-sources-Dr6uwBGw.mjs";
4
- import { i as capSeriesKey } from "../../capture-engine-WSpdP-gE.mjs";
3
+ import { i as parseDeviceStateChanged, r as isRecord$1, t as describeCompositionSources } from "../../composition-sources-C8T9DRbZ.mjs";
4
+ import { i as capSeriesKey } from "../../capture-engine-BSjE-CQA.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 { createRequire } from "node:module";
@@ -2780,6 +2780,75 @@ var ADDON_MIGRATIONS = [
2780
2780
  }
2781
2781
  ];
2782
2782
  //#endregion
2783
+ //#region src/builtins/core-blocks/device-template-door.ts
2784
+ function templateDoorOver(api) {
2785
+ const need = () => {
2786
+ const current = api();
2787
+ if (current === void 0) throw new Error("no ctx.api on this node — templates cannot be rendered");
2788
+ return current;
2789
+ };
2790
+ return {
2791
+ render: async (templates, allowedDeviceIds) => {
2792
+ return (await need().deviceManager.renderDeviceTemplates.query({
2793
+ templates: [...templates],
2794
+ ...allowedDeviceIds === void 0 ? {} : { allowedDeviceIds: [...allowedDeviceIds] }
2795
+ })).results;
2796
+ },
2797
+ check: async (templates, allowedDeviceIds) => {
2798
+ return (await need().deviceManager.checkDeviceTemplates.query({
2799
+ templates: [...templates],
2800
+ ...allowedDeviceIds === void 0 ? {} : { allowedDeviceIds: [...allowedDeviceIds] }
2801
+ })).results;
2802
+ }
2803
+ };
2804
+ }
2805
+ /** The renderer a step run is given, bound to the devices its caller may read (`undefined` = all). */
2806
+ function stepRenderer(door, allowedDeviceIds) {
2807
+ if (door === void 0) return void 0;
2808
+ return (templates) => door.render(templates, allowedDeviceIds);
2809
+ }
2810
+ //#endregion
2811
+ //#region src/builtins/core-blocks/step-condition-door.ts
2812
+ /**
2813
+ * The core-blocks side of a conditional step (#472): a step's `if` is read on a
2814
+ * mirror filled over `ctx.api` (`deviceState.getCapSlice`), the same state
2815
+ * every other consumer of the ONE `when` tree reads. A run on behalf of a
2816
+ * non-admin may only branch on devices that caller can see — a branch is an
2817
+ * answer, and an out-of-scope answer is a leak — so a tree naming any other
2818
+ * device (or a stable id, which cannot be proven) reads `unknown`: neither side
2819
+ * runs, and the trace says why.
2820
+ */
2821
+ function conditionDoorOver(api) {
2822
+ return (readable) => async (when) => {
2823
+ const current = api();
2824
+ if (current === void 0) return {
2825
+ result: "unknown",
2826
+ reason: "this node has no ctx.api to read state through"
2827
+ };
2828
+ if (readable !== void 0) {
2829
+ if (collectWhenMirrorSources(when).filter((source) => source.kind === "stable" || !readable.includes(source.deviceId)).length > 0) return {
2830
+ result: "unknown",
2831
+ reason: "the condition reads a device this caller was not proven to see"
2832
+ };
2833
+ }
2834
+ return evaluateStepCondition(when, {
2835
+ fetchSlice: (deviceId, cap) => current.deviceState.getCapSlice.query({
2836
+ deviceId,
2837
+ capName: cap
2838
+ }),
2839
+ fetchStableIds: async () => stableIdMapOf(await current.deviceManager.listAll.query({}))
2840
+ });
2841
+ };
2842
+ }
2843
+ /** The evaluator a step run is given; `undefined` when the consumer has no door. */
2844
+ function stepConditionEvaluator(door, readable) {
2845
+ return door === void 0 ? void 0 : door(readable);
2846
+ }
2847
+ /** The `evaluateCondition` dep of a step run, or nothing (a guarded step then reads `unknown`). */
2848
+ function conditionDeps(evaluator) {
2849
+ return evaluator === void 0 ? {} : { evaluateCondition: evaluator };
2850
+ }
2851
+ //#endregion
2783
2852
  //#region src/builtins/core-blocks/runs-ledger.ts
2784
2853
  /**
2785
2854
  * The hub's runs ledger: what each automation block and each Action run DID.
@@ -2983,6 +3052,8 @@ var ActionsService = class {
2983
3052
  newRunId;
2984
3053
  units;
2985
3054
  targets;
3055
+ templates;
3056
+ conditions;
2986
3057
  running = /* @__PURE__ */ new Map();
2987
3058
  maxRunMs;
2988
3059
  stopGraceMs;
@@ -2999,6 +3070,8 @@ var ActionsService = class {
2999
3070
  this.stopGraceMs = deps.stopGraceMs ?? STOP_GRACE_MS;
3000
3071
  this.units = deps.units ?? capUnitResolver(ALL_CAPABILITY_DEFINITIONS);
3001
3072
  this.targets = new ActionTargetResolver(deps.directory, deps.logger);
3073
+ this.templates = deps.templates;
3074
+ this.conditions = deps.conditions;
3002
3075
  }
3003
3076
  /** One-shot at boot: stored steps written before D983 are rewritten to the target shape. */
3004
3077
  async migrateTargets() {
@@ -3080,12 +3153,37 @@ var ActionsService = class {
3080
3153
  });
3081
3154
  throw new ActionError("not-linked", reason);
3082
3155
  }
3156
+ /**
3157
+ * The devices a run's templates may read. An admin (or an in-process block)
3158
+ * reads any (`undefined`); a non-admin only the camera the scope gate proved
3159
+ * it may see — fail-closed, because the gate proves nothing about any other.
3160
+ */
3161
+ readableDevices(input) {
3162
+ if (input.caller === void 0 || input.caller.isAdmin) return void 0;
3163
+ return input.deviceId === void 0 ? [] : [input.deviceId];
3164
+ }
3165
+ /** A non-admin run is refused up front when a template names a device outside `readable`. */
3166
+ async checkTemplateScope(entry, readable, deviceId) {
3167
+ if (readable === void 0 || entry.source !== "internal" || this.templates === void 0) return;
3168
+ const templates = collectDeviceTemplates(entry.steps ?? []);
3169
+ if (templates.length === 0) return;
3170
+ const outside = (await this.templates.check(templates, readable)).flatMap((c) => c.ok ? c.aliases.filter((a) => !a.allowed) : []);
3171
+ if (outside.length === 0) return;
3172
+ const reason = `a template names ${[...new Set(outside.map((a) => a.alias))].join(", ")}, which this caller was not proven to see`;
3173
+ this.logger.warn(`action run refused — ${reason}`, {
3174
+ ...deviceId === void 0 ? {} : { tags: { deviceId } },
3175
+ meta: { actionId: entry.id }
3176
+ });
3177
+ throw new ActionError("template-scope", reason);
3178
+ }
3083
3179
  async run(input) {
3084
3180
  await this.authorize(input.caller, input.actionId, input.deviceId, "run");
3085
3181
  const entry = await this.find(input.actionId);
3086
3182
  if (entry === null) throw new ActionError("not-found", `no action "${input.actionId}"`);
3087
3183
  const resolved = resolveActionVariables(entry.variables, input.variables);
3088
3184
  if (!resolved.ok) throw new ActionError("invalid-variables", resolved.error);
3185
+ const readable = this.readableDevices(input);
3186
+ await this.checkTemplateScope(entry, readable, input.deviceId);
3089
3187
  const runId = this.newRunId();
3090
3188
  const startedAt = this.now();
3091
3189
  const trigger = this.triggerOf(input, resolved.values);
@@ -3130,7 +3228,7 @@ var ActionsService = class {
3130
3228
  lastRunAt: startedAt,
3131
3229
  lastError: null
3132
3230
  });
3133
- const done = this.execute(entry, resolved.values, runId, startedAt, trigger, token);
3231
+ const done = this.execute(entry, resolved.values, runId, startedAt, trigger, token, readable);
3134
3232
  if (input.wait === true) return done;
3135
3233
  return {
3136
3234
  runId,
@@ -3151,13 +3249,13 @@ var ActionsService = class {
3151
3249
  };
3152
3250
  }
3153
3251
  /** Never rejects: a run's failure is its outcome. */
3154
- async execute(entry, values, runId, startedAt, trigger, token) {
3252
+ async execute(entry, values, runId, startedAt, trigger, token, readable) {
3155
3253
  let outcome = "failed";
3156
3254
  let steps = [];
3157
3255
  let message;
3158
3256
  const deadline = this.armDeadline(entry.id, runId, token);
3159
3257
  try {
3160
- const running = runSteps(this.runnableFor(entry, values, token, runId), {
3258
+ const running = runSteps(this.runnableFor(entry, values, token, runId, readable), {
3161
3259
  pathPrefix: "steps",
3162
3260
  isAborted: () => token.aborted,
3163
3261
  abortReason: "the run was stopped",
@@ -3172,6 +3270,17 @@ var ActionsService = class {
3172
3270
  error: failure.message
3173
3271
  }
3174
3272
  });
3273
+ },
3274
+ onGuardUnknown: (skipped) => {
3275
+ this.logger.warn("action step skipped — its condition could not be read", {
3276
+ ...skipped.deviceId === void 0 ? {} : { tags: { deviceId: skipped.deviceId } },
3277
+ meta: {
3278
+ actionId: entry.id,
3279
+ runId,
3280
+ step: skipped.index,
3281
+ reason: skipped.reason
3282
+ }
3283
+ });
3175
3284
  }
3176
3285
  });
3177
3286
  const result = await Promise.race([running, deadline.expired]);
@@ -3261,7 +3370,7 @@ var ActionsService = class {
3261
3370
  }
3262
3371
  };
3263
3372
  }
3264
- runnableFor(entry, values, token, runId) {
3373
+ runnableFor(entry, values, token, runId, readable) {
3265
3374
  if (entry.source === "internal") return buildActionSteps(entry.steps ?? [], values, {
3266
3375
  invokeCap: (call) => this.invokeCap({
3267
3376
  ...call,
@@ -3274,6 +3383,8 @@ var ActionsService = class {
3274
3383
  sleep: (ms) => token.sleep(ms),
3275
3384
  resolveTarget: (target, actionId, vars, origin) => this.targets.resolve(target, actionId, vars, origin),
3276
3385
  owner: entry.id,
3386
+ renderTemplates: stepRenderer(this.templates, readable),
3387
+ ...conditionDeps(stepConditionEvaluator(this.conditions, readable)),
3277
3388
  onMissingVar: (name) => this.logger.warn("action template referenced a variable that was never set", { meta: {
3278
3389
  actionId: entry.id,
3279
3390
  variable: name
@@ -3753,6 +3864,8 @@ function buildActionsRuntime(deps) {
3753
3864
  sources: sourcesOver(deps.api),
3754
3865
  directory: deps.directory ?? directoryOver(deps.api),
3755
3866
  invokeCap: invokeCapOver(deps.api),
3867
+ templates: templateDoorOver(deps.api),
3868
+ conditions: conditionDoorOver(deps.api),
3756
3869
  emit: (event) => deps.eventBus.emit({
3757
3870
  id: randomUUID(),
3758
3871
  timestamp: /* @__PURE__ */ new Date(),
@@ -5253,6 +5366,8 @@ var SchedulerEngine = class {
5253
5366
  }),
5254
5367
  resolveTarget: (target, actionId, v, origin) => this.deps.targets.resolve(target, actionId, v, origin),
5255
5368
  owner: `scheduler:${scheduler.id}`,
5369
+ renderTemplates: stepRenderer(this.deps.templates),
5370
+ ...conditionDeps(stepConditionEvaluator(this.deps.conditions)),
5256
5371
  onMissingVar: () => void 0
5257
5372
  }), {
5258
5373
  pathPrefix: "steps",
@@ -5268,6 +5383,16 @@ var SchedulerEngine = class {
5268
5383
  error: failure.message
5269
5384
  }
5270
5385
  });
5386
+ },
5387
+ onGuardUnknown: (skipped) => {
5388
+ this.deps.logger.warn("scheduler edge step skipped — its condition could not be read", {
5389
+ ...skipped.deviceId === void 0 ? {} : { tags: { deviceId: skipped.deviceId } },
5390
+ meta: {
5391
+ ...vars,
5392
+ step: skipped.index,
5393
+ reason: skipped.reason
5394
+ }
5395
+ });
5271
5396
  }
5272
5397
  });
5273
5398
  steps = result.steps;
@@ -5703,6 +5828,8 @@ function buildSchedulersRuntime(deps) {
5703
5828
  store,
5704
5829
  host,
5705
5830
  targets,
5831
+ templates: templateDoorOver(deps.api),
5832
+ conditions: conditionDoorOver(deps.api),
5706
5833
  logger: deps.logger.child("engine"),
5707
5834
  record: (schedulerId, trace) => deps.ledger.report(schedulerOwner(schedulerId), {
5708
5835
  trace,
@@ -5820,7 +5947,8 @@ var HeroLayoutService = class {
5820
5947
  type: device.type,
5821
5948
  role: device.role,
5822
5949
  name: device.name,
5823
- online: device.online
5950
+ online: device.online,
5951
+ integration: device.integration ?? null
5824
5952
  },
5825
5953
  caps: [...bound.filter((cap) => cap !== REMOTE_CAP), REMOTE_CAP],
5826
5954
  features: device.features,
@@ -7372,6 +7500,8 @@ var FanPresetsService = class {
7372
7500
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
7373
7501
  resolveTarget: async (target) => ({ deviceIds: target.kind === "devices" ? target.ids : [] }),
7374
7502
  owner: `fan-preset:${deviceId}/${presetId}`,
7503
+ renderTemplates: stepRenderer(this.deps.templates, [deviceId]),
7504
+ ...conditionDeps(stepConditionEvaluator(this.deps.conditions, [deviceId])),
7375
7505
  onMissingVar: () => void 0
7376
7506
  }), {
7377
7507
  pathPrefix: "steps",
@@ -7388,6 +7518,17 @@ var FanPresetsService = class {
7388
7518
  error: failure.message
7389
7519
  }
7390
7520
  });
7521
+ },
7522
+ onGuardUnknown: (skipped) => {
7523
+ this.deps.logger.warn("fan preset step skipped — its condition could not be read", {
7524
+ tags: { deviceId: skipped.deviceId ?? deviceId },
7525
+ meta: {
7526
+ fanDeviceId: deviceId,
7527
+ presetId,
7528
+ step: skipped.index,
7529
+ reason: skipped.reason
7530
+ }
7531
+ });
7391
7532
  }
7392
7533
  });
7393
7534
  const steps = result.steps.map((trace, index) => ({
@@ -7729,6 +7870,8 @@ function buildFanPresetsRuntime(deps) {
7729
7870
  devices,
7730
7871
  readings: fanPresetsReadingsOver(deps.api, deps.logger.child("fan-presets")),
7731
7872
  invoke: invokeCapOver(deps.api),
7873
+ templates: templateDoorOver(deps.api),
7874
+ conditions: conditionDoorOver(deps.api),
7732
7875
  logger: deps.logger.child("fan-presets")
7733
7876
  });
7734
7877
  return {
@@ -8707,7 +8850,8 @@ var CoreBlocksAddon = class extends BaseAddon {
8707
8850
  role: found.role ?? null,
8708
8851
  name: found.name,
8709
8852
  online: found.online,
8710
- features: found.features
8853
+ features: found.features,
8854
+ integration: manufacturerOf(found.metadata)
8711
8855
  };
8712
8856
  },
8713
8857
  caps: async (deviceId) => (await requireApi().deviceManager.getBindings.query({ deviceId })).entries.map((e) => e.capName),
@@ -9357,5 +9501,10 @@ async function loadTranspiler(logger) {
9357
9501
  return null;
9358
9502
  }
9359
9503
  }
9504
+ /** The manufacturer a driver recorded in the device's identity blob, or `null`. */
9505
+ function manufacturerOf(metadata) {
9506
+ const value = metadata?.["manufacturer"];
9507
+ return typeof value === "string" && value.trim() !== "" ? value : null;
9508
+ }
9360
9509
  //#endregion
9361
9510
  export { CoreBlocksAddon, BlockSettingsStore as a, readUnscopedAddonSettings as c, BlockSupervisor as d, BLOCK_ADDON_PREFIX as f, removeBlockPackage as g, materializeBlock as h, loadBlockTypeDefs as i, CORE_BLOCKS_COLLECTION as l, blockIdFromAddonId as m, CoreBlockStore as n, clearNodeSettings as o, blockAddonId as p, compileBlock as r, createAddonSettingsStore as s, extractSettingsSchema as t, CORE_BLOCK_SETTINGS_COLLECTION as u };
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The core-blocks side of the ONE door to the device template renderer
3
+ * (D1021): `device-manager.renderDeviceTemplates` over `ctx.api`. An action, a
4
+ * scheduler point and a fan preset all render through this; none owns a copy of
5
+ * the renderer or of the state it reads.
6
+ */
7
+ import type { AddonApi, DeviceTemplateRender, DeviceTemplateRefusal, RenderStepTemplates } from "@camstack/types";
8
+ export type TemplateCheckResult = {
9
+ readonly ok: true;
10
+ readonly aliases: readonly {
11
+ readonly alias: string;
12
+ readonly deviceId: number | null;
13
+ readonly allowed: boolean;
14
+ }[];
15
+ } | {
16
+ readonly ok: false;
17
+ readonly refusal: DeviceTemplateRefusal;
18
+ };
19
+ export interface DeviceTemplateDoor {
20
+ render(templates: readonly string[], allowedDeviceIds?: readonly number[]): Promise<readonly DeviceTemplateRender[]>;
21
+ check(templates: readonly string[], allowedDeviceIds?: readonly number[]): Promise<readonly TemplateCheckResult[]>;
22
+ }
23
+ export declare function templateDoorOver(api: () => AddonApi | undefined): DeviceTemplateDoor;
24
+ /** The renderer a step run is given, bound to the devices its caller may read (`undefined` = all). */
25
+ export declare function stepRenderer(door: DeviceTemplateDoor | undefined, allowedDeviceIds?: readonly number[]): RenderStepTemplates | undefined;
@@ -17,6 +17,8 @@
17
17
  * and named, never written as 0 (D393).
18
18
  */
19
19
  import { type CapCall, type ControlStatus, type FanControlStatus, type FanPreset, type IFanPresetsProvider, type IScopedLogger, type SwitchStatus, DeviceType } from "@camstack/types";
20
+ import { type DeviceTemplateDoor } from "./device-template-door.js";
21
+ import { type StepConditionDoor } from "./step-condition-door.js";
20
22
  /** The per-device store the presets live in. */
21
23
  export interface FanPresetsStore {
22
24
  read(deviceId: number): Promise<readonly FanPreset[]>;
@@ -47,6 +49,9 @@ export interface FanPresetsServiceDeps {
47
49
  invoke(call: CapCall): Promise<void>;
48
50
  readonly logger: IScopedLogger;
49
51
  readonly now?: () => number;
52
+ /** The device template renderer (D1021); a templated step fails where there is none. */
53
+ readonly templates?: DeviceTemplateDoor;
54
+ readonly conditions?: StepConditionDoor;
50
55
  }
51
56
  type SetResult = Awaited<ReturnType<IFanPresetsProvider["setPresets"]>>;
52
57
  type ApplyResult = Awaited<ReturnType<IFanPresetsProvider["applyPreset"]>>;
@@ -16,6 +16,8 @@ export interface HeroDeviceFacts {
16
16
  readonly name: string;
17
17
  readonly online: boolean;
18
18
  readonly features: readonly string[];
19
+ /** The brand or integration name the device comes from, when it is known. */
20
+ readonly integration?: string | null;
19
21
  }
20
22
  /** The reads the service needs; the addon wires them to `ctx.api`. */
21
23
  export interface HeroLayoutReader {
@@ -1,4 +1,6 @@
1
1
  import { type ActionTargetResolver, type AutomationRunTrace, type IScopedLogger, type SchedulerStatus } from "@camstack/types";
2
+ import { type DeviceTemplateDoor } from "../device-template-door.js";
3
+ import { type StepConditionDoor } from "../step-condition-door.js";
2
4
  import type { SchedulersStore } from "./scheduler-store.js";
3
5
  import { type StateTruth } from "./scheduler-timeline.js";
4
6
  import { type SchedulerClock, type SchedulerHost } from "./scheduler-types.js";
@@ -25,6 +27,9 @@ export interface SchedulerEngineDeps {
25
27
  readonly clock?: SchedulerClock;
26
28
  readonly settleMs?: number;
27
29
  readonly newRunId?: () => string;
30
+ /** The device template renderer (D1021); a templated step fails where there is none. */
31
+ readonly templates?: DeviceTemplateDoor;
32
+ readonly conditions?: StepConditionDoor;
28
33
  }
29
34
  export declare class SchedulerEngine {
30
35
  private readonly deps;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The core-blocks side of a conditional step (#472): a step's `if` is read on a
3
+ * mirror filled over `ctx.api` (`deviceState.getCapSlice`), the same state
4
+ * every other consumer of the ONE `when` tree reads. A run on behalf of a
5
+ * non-admin may only branch on devices that caller can see — a branch is an
6
+ * answer, and an out-of-scope answer is a leak — so a tree naming any other
7
+ * device (or a stable id, which cannot be proven) reads `unknown`: neither side
8
+ * runs, and the trace says why.
9
+ */
10
+ import { type AddonApi, type EvaluateStepCondition } from "@camstack/types";
11
+ /** Builds the evaluator for one run, bound to the devices its caller may read (`undefined` = all). */
12
+ export type StepConditionDoor = (readable?: readonly number[]) => EvaluateStepCondition;
13
+ export declare function conditionDoorOver(api: () => AddonApi | undefined): StepConditionDoor;
14
+ /** The evaluator a step run is given; `undefined` when the consumer has no door. */
15
+ export declare function stepConditionEvaluator(door: StepConditionDoor | undefined, readable?: readonly number[]): EvaluateStepCondition | undefined;
16
+ /** The `evaluateCondition` dep of a step run, or nothing (a guarded step then reads `unknown`). */
17
+ export declare function conditionDeps(evaluator: EvaluateStepCondition | undefined): {
18
+ readonly evaluateCondition?: EvaluateStepCondition;
19
+ };
@@ -3,8 +3,8 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-R_mOSFtH.js");
7
- const require_capture_engine = require("../../capture-engine-CKtkENOg.js");
6
+ const require_dist = require("../../dist-C2czR9xK.js");
7
+ const require_capture_engine = require("../../capture-engine-6MVUyUry.js");
8
8
  const require_retention = require("../../retention-BcOSL6b9.js");
9
9
  let node_crypto = require("node:crypto");
10
10
  //#region src/builtins/device-history/capture/point-writer.ts
@@ -1,5 +1,5 @@
1
- import { $o as BaseAddon, Es as RecordTooLargeError, Jc as DeviceType, Qo as wattMillisecondsToKwh, V as DEVICE_HISTORY_ENERGY_KEY, Y as DeviceRunSchema, Zc as EventCategory, _r as deviceRunsCapability, bn as armRemovalReconcile, br as deviceTransitionsCapability, cc as historyUnitFor, dt as HISTORY_ITEM_CATALOG, ec as defineRecordKinds, gc as isReadingQuantity, gr as deviceRemovalHookCapability, mr as deviceHistoryCapability, nc as emitReadiness, os as DeviceTransitionSchema, us as InvalidRecordError, ut as HISTORY_CATALOG } from "../../dist-C0Df8iJl.mjs";
2
- import { a as catalogMetrics, c as DeviceDirectory, d as identityOf, f as subjectIdOf, i as capSeriesKey, l as isRealDeviceType, n as CaptureEngine, o as readPath, r as capItemSeriesKey, s as readUnit, t as CAP_KEY_PREFIX, u as SeriesRegistry } from "../../capture-engine-WSpdP-gE.mjs";
1
+ import { Cc as isReadingQuantity, Cn as armRemovalReconcile, Ns as RecordTooLargeError, Q as DeviceRunSchema, V as DEVICE_HISTORY_ENERGY_KEY, _s as InvalidRecordError, as as wattMillisecondsToKwh, br as deviceRemovalHookCapability, hc as historyUnitFor, il as EventCategory, lc as emitReadiness, mt as HISTORY_ITEM_CATALOG, os as BaseAddon, ps as DeviceTransitionSchema, pt as HISTORY_CATALOG, sc as defineRecordKinds, tl as DeviceType, vr as deviceHistoryCapability, wr as deviceTransitionsCapability, xr as deviceRunsCapability } from "../../dist-DjBZ1HhF.mjs";
2
+ import { a as catalogMetrics, c as DeviceDirectory, d as identityOf, f as subjectIdOf, i as capSeriesKey, l as isRealDeviceType, n as CaptureEngine, o as readPath, r as capItemSeriesKey, s as readUnit, t as CAP_KEY_PREFIX, u as SeriesRegistry } from "../../capture-engine-BSjE-CQA.mjs";
3
3
  import { a as FIVE_MINUTES_MS, c as bucketEndOf, i as DAY_MS, l as bucketStartOf, n as RetentionJob, o as HOUR_MS, r as DepartureTracker, s as ROLLUP_GRACE_MS, t as DEFAULT_RETENTION, u as floorTo } from "../../retention-CUOVI1p7.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  //#region src/builtins/device-history/capture/point-writer.ts
@@ -99,6 +99,7 @@ export declare class DeviceManagerAddon extends BaseAddon {
99
99
  private readonly removalFence;
100
100
  /** Store-by-store clean-up of a removed device, with a bounded retry (D864). */
101
101
  private removalCleanupImpl;
102
+ private templateActions;
102
103
  private removalHooksCleanupImpl;
103
104
  /** Declared secret config paths per device, as last registered (D783). */
104
105
  private readonly secretConfigPaths;
@@ -231,6 +232,12 @@ export declare class DeviceManagerAddon extends BaseAddon {
231
232
  protected onInitialize(): Promise<ProviderRegistration[] | void>;
232
233
  private get removalCleanup();
233
234
  private get removalHooksCleanup();
235
+ /**
236
+ * The template actions read device rows (alias), bindings (caps) and the
237
+ * runtime-state slices (`device-state`) — all through what this addon already
238
+ * owns. Built once per boot;
239
+ */
240
+ private makeTemplateActions;
234
241
  protected onShutdown(): Promise<void>;
235
242
  }
236
243
  export default DeviceManagerAddon;