@camstack/server 1.2.929 → 1.2.930

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 (29) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/package.json +9 -11
  3. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  4. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  5. package/system/dist/builtins/composer/composer.addon.js +3 -3
  6. package/system/dist/builtins/composer/composer.addon.mjs +3 -3
  7. package/system/dist/builtins/core-blocks/actions-service.d.ts +18 -1
  8. package/system/dist/builtins/core-blocks/core-blocks.addon.js +986 -208
  9. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +985 -208
  10. package/system/dist/builtins/core-blocks/tcp-connect.d.ts +3 -0
  11. package/system/dist/builtins/core-notifier/core-notifier.addon.js +6 -487
  12. package/system/dist/builtins/core-notifier/core-notifier.addon.mjs +3 -484
  13. package/system/dist/builtins/device-manager/device-manager.addon.js +3 -3
  14. package/system/dist/builtins/device-manager/device-manager.addon.mjs +3 -3
  15. package/system/dist/{composition-sources-Caqv7O7z.mjs → composition-sources-BEUWn2s_.mjs} +1 -1
  16. package/system/dist/{composition-sources-CgnHjm8Q.js → composition-sources-acfR4hDq.js} +1 -1
  17. package/system/dist/{core-blocks.cap-LEMqVwxO.js → core-blocks.cap-BMeMCBrx.js} +37 -9
  18. package/system/dist/{core-blocks.cap-C6iKAZ-x.mjs → core-blocks.cap-BRPsLAij.mjs} +32 -10
  19. package/system/dist/index.js +2 -2
  20. package/system/dist/index.mjs +2 -2
  21. package/system/dist/{notification-rules.cap-B__YBgnG.js → notification-rules.cap-BDh0LDhV.js} +6 -0
  22. package/system/dist/{notification-rules.cap-D9ArZlwx.mjs → notification-rules.cap-DUmiMBQB.mjs} +1 -1
  23. package/system/dist/notification-targets-CRH-9Dy5.js +509 -0
  24. package/system/dist/notification-targets-DaNE-pIt.mjs +486 -0
  25. package/system/dist/{prefix-walk-DC0ljmbB.js → prefix-walk-BkMxoXpL.js} +1 -1
  26. package/system/dist/{prefix-walk-B4b2-9aK.mjs → prefix-walk-ifwg_ukx.mjs} +1 -1
  27. package/system/dist/{rename-composition-block-CcWLwVhG.js → rename-composition-block-BJsL58Ih.js} +121 -15
  28. package/system/dist/{rename-composition-block-7WIICIDq.mjs → rename-composition-block-OAtErZgq.mjs} +121 -15
  29. package/system/package.json +1 -1
@@ -1,8 +1,9 @@
1
1
  import { r as MotionStatusSchema } from "../../stream-catalog.cap-Bp7SkgIf.mjs";
2
2
  import { _ as hydrateSchema, a as isSecretRefOwnedBy, b as EventCategory$1, f as defineAddonMigrations, i as collectSecretMarkerRefs, l as RecordIntegrationInstances, o as resolveSecretMarkers, r as secretTreeFromSchema, s as transformSecretWrite, t as BaseAddon } from "../../base-addon-Md14i7pe.mjs";
3
3
  import { W as isSecretMarker, Z as errMsg$1 } from "../../scoped-settings-DVWUIP7Z.mjs";
4
- import { $ as RemoteLayoutPayloadSchema, $n as unitsForQuantity, $t as FanPresetSchema, A as TemplateKindSchema, At as measurementFitsRole, B as SmokeStatusSchema, Bn as AutomationControlStatusSchema, Bt as timedRunRemaining, C as WaterHeaterStatusSchema, Cn as ContactStatusSchema, Ct as projectDeviceRow, D as VacuumControlStatusSchema, Dn as COMPOSER_RUNNER_ID, Dt as contactMeasurement, Et as resolveHeroSceneId, F as TamperStatusSchema, Fn as CarbonMonoxideStatusSchema, Ft as TimedRunStatusSchema, G as hasOwnRunningPowerDefaults, Gt as GroupStatusSchema, H as schedulersCapability, Hn as AirQualitySensorStatusSchema, Ht as HeatingValveStatusSchema, I as tagsCapability, In as BrightnessStatusSchema, It as timedRunCapability, J as REMOTE_MEDIA_COMMANDS, K as runningPowerDefaultsFor, Kn as actionWaitTotalMs, L as SWITCH_DEFAULT_OPTIONS, Lt as timedRunLimitOf, M as AutomationTemplatePayloadSchema, Mn as ClimateControlStatusSchema, Mt as temperatureMeasurement, N as reexpandAutomationInstance, Nt as textMeasurement, O as UpdateStatusSchema, Ot as emptyMeasurement, P as TemperatureSensorStatusSchema, Pt as NOT_REPORTED, Q as RemoteAssumedStateSchema, Qn as baseUnitForQuantity, Qt as FAN_CAPTURE_FIELDS, R as SwitchStatusSchema, Rn as BinaryStatusSchema, Rt as timedRunMaxIn, S as WeatherStatusSchema, Sn as ControlStatusSchema, St as ROW_READING_FACT_IDS, T as ValveStatusSchema, Tn as ConsumablesStatusSchema, Tt as REMOTE_OPEN_ACTION_ID, Ut as HeatPumpStatusSchema, V as ScriptRunnerStatusSchema, Vn as AmbientLightSensorStatusSchema, Vt as timedRunSeconds, W as RunningStateStatusSchema, Wn as actionsCapability, Wt as heatPumpInstantCop, X as EMPTY_REMOTE_ASSUMED_STATE, Xn as normalizeActionUnits, Xt as GasStatusSchema, Y as remoteCapability, Yn as capUnitResolver, Yt as GroupActiveSchema, Z as EMPTY_REMOTE_CONFIG, Zn as normalizeRecipeUnits, Zt as FloodStatusSchema, _ as WorkloadStatusSchema, _t as LawnMowerControlStatusSchema, an as SetOscillationAxisInputSchema, ar as addonIdOfActionId, bn as CoverStatusSchema, bt as HumidifierStatusSchema, c as kebabToCamel, cn as EnumSensorStatusSchema, cr as resolveActionVariables, dn as DishwasherStatusSchema, dt as NumericSensorStatusSchema, en as fanPresetsCapability, er as ActionError, et as readStoredRemoteConfig, ft as NetworkLinkStatusSchema, ht as LockControlStatusSchema, ir as INTERNAL_ACTION_PREFIX, it as PowerMeterStatusSchema, j as checkTemplatePayload, jt as powerMeasurement, k as templateCapability, kn as ColorStatusSchema, kt as humidityMeasurement, ln as DoorbellStatusSchema, lr as EventEmitterStatusSchema, lt as PetFeederStatusSchema, m as ALL_CAPABILITY_DEFINITIONS, mt as MeterStatusSchema, nn as FAN_OSCILLATION_AXIS_SETTABLE, nr as ActionVariableSchema, nt as PressureSensorStatusSchema, on as fanAxisPath, or as internalActionId, ot as PetFountainStatusSchema, pt as MotionTriggerStatusSchema, q as remoteLayoutComponentsCapability, qn as actionSourceCapability, qt as GroupCommandsSchema, rn as FanControlStatusSchema, rr as IDLE_ACTION_STATUS, rt as PresenceStatusSchema, sr as isInternalActionId, t as composedBlockIdOf, tn as FAN_OSCILLATION_AXES, tr as ActionMinDelaySecSchema, tt as PumpCycleStatusSchema, un as DoNotDisturbStatusSchema, vt as ImageStatusSchema, w as VibrationStatusSchema, wt as HERO_SCENE_ROW_IDS, x as WeatherStationStatusSchema, xt as heroLayoutCapability, yt as HumiditySensorStatusSchema, zn as BatteryStatusSchema, zt as timedRunQuickRun } from "../../rename-composition-block-7WIICIDq.mjs";
5
- import { i as NcTaggedRuleKindSchema, o as AlarmPanelStatusSchema } from "../../notification-rules.cap-D9ArZlwx.mjs";
4
+ import { $ as RemoteLayoutPayloadSchema, $n as unitsForQuantity, $t as FanPresetSchema, A as TemplateKindSchema, At as measurementFitsRole, B as SmokeStatusSchema, Bn as AutomationControlStatusSchema, Bt as timedRunRemaining, C as WaterHeaterStatusSchema, Cn as ContactStatusSchema, Ct as projectDeviceRow, D as VacuumControlStatusSchema, Dn as COMPOSER_RUNNER_ID, Dt as contactMeasurement, Et as resolveHeroSceneId, F as TamperStatusSchema, Fn as CarbonMonoxideStatusSchema, Ft as TimedRunStatusSchema, G as hasOwnRunningPowerDefaults, Gt as GroupStatusSchema, H as schedulersCapability, Hn as AirQualitySensorStatusSchema, Ht as HeatingValveStatusSchema, I as tagsCapability, In as BrightnessStatusSchema, It as timedRunCapability, J as REMOTE_MEDIA_COMMANDS, K as runningPowerDefaultsFor, Kn as actionWaitTotalMs, L as SWITCH_DEFAULT_OPTIONS, Lt as timedRunLimitOf, M as AutomationTemplatePayloadSchema, Mn as ClimateControlStatusSchema, Mt as temperatureMeasurement, N as reexpandAutomationInstance, Nt as textMeasurement, O as UpdateStatusSchema, Ot as emptyMeasurement, P as TemperatureSensorStatusSchema, Pt as NOT_REPORTED, Q as RemoteAssumedStateSchema, Qn as baseUnitForQuantity, Qt as FAN_CAPTURE_FIELDS, R as SwitchStatusSchema, Rn as BinaryStatusSchema, Rt as timedRunMaxIn, S as WeatherStatusSchema, Sn as ControlStatusSchema, St as ROW_READING_FACT_IDS, T as ValveStatusSchema, Tn as ConsumablesStatusSchema, Tt as REMOTE_OPEN_ACTION_ID, Ut as HeatPumpStatusSchema, V as ScriptRunnerStatusSchema, Vn as AmbientLightSensorStatusSchema, Vt as timedRunSeconds, W as RunningStateStatusSchema, Wn as actionsCapability, Wt as heatPumpInstantCop, X as EMPTY_REMOTE_ASSUMED_STATE, Xn as normalizeActionUnits, Xt as GasStatusSchema, Y as remoteCapability, Yn as capUnitResolver, Yt as GroupActiveSchema, Z as EMPTY_REMOTE_CONFIG, Zn as normalizeRecipeUnits, Zt as FloodStatusSchema, _ as WorkloadStatusSchema, _t as LawnMowerControlStatusSchema, an as SetOscillationAxisInputSchema, ar as addonIdOfActionId, bn as CoverStatusSchema, bt as HumidifierStatusSchema, c as kebabToCamel, cn as EnumSensorStatusSchema, cr as resolveActionVariables, dn as DishwasherStatusSchema, dt as NumericSensorStatusSchema, en as fanPresetsCapability, er as ActionError, et as readStoredRemoteConfig, ft as NetworkLinkStatusSchema, ht as LockControlStatusSchema, ir as INTERNAL_ACTION_PREFIX, it as PowerMeterStatusSchema, j as checkTemplatePayload, jt as powerMeasurement, k as templateCapability, kn as ColorStatusSchema, kt as humidityMeasurement, ln as DoorbellStatusSchema, lr as EventEmitterStatusSchema, lt as PetFeederStatusSchema, m as ALL_CAPABILITY_DEFINITIONS, mt as MeterStatusSchema, nn as FAN_OSCILLATION_AXIS_SETTABLE, nr as ActionVariableSchema, nt as PressureSensorStatusSchema, on as fanAxisPath, or as internalActionId, ot as PetFountainStatusSchema, pt as MotionTriggerStatusSchema, q as remoteLayoutComponentsCapability, qn as actionSourceCapability, qt as GroupCommandsSchema, rn as FanControlStatusSchema, rr as IDLE_ACTION_STATUS, rt as PresenceStatusSchema, sr as isInternalActionId, t as composedBlockIdOf, tn as FAN_OSCILLATION_AXES, tr as ActionMinDelaySecSchema, tt as PumpCycleStatusSchema, un as DoNotDisturbStatusSchema, vt as ImageStatusSchema, w as VibrationStatusSchema, wt as HERO_SCENE_ROW_IDS, x as WeatherStationStatusSchema, xt as heroLayoutCapability, yt as HumiditySensorStatusSchema, zn as BatteryStatusSchema, zt as timedRunQuickRun } from "../../rename-composition-block-OAtErZgq.mjs";
5
+ import { r as listNotificationTargets } from "../../notification-targets-DaNE-pIt.mjs";
6
+ import { i as NcTaggedRuleKindSchema, o as AlarmPanelStatusSchema, u as NotificationSchema } from "../../notification-rules.cap-DUmiMBQB.mjs";
6
7
  import { s as defineRecordKinds } from "../../record-kind-ub6NXqfh.mjs";
7
8
  import { n as entryBody, t as defineEntryKind } from "../../entry-kind-D9MuVJCK.mjs";
8
9
  import { s as IDENTITY_LINK_KINDS } from "../../device-manager.cap-CFZSPfUh.mjs";
@@ -11,13 +12,13 @@ import { n as baseUnitOf } from "../../quantity-D3g5SxsZ.mjs";
11
12
  import { a as defaultTagColorId, c as renameInTags, i as TagsFieldSchema, l as tagKey, n as TagNameSchema, o as normalizeTags, r as TagStyleSchema, s as removeFromTags } from "../../tag-uZBAq6ox.mjs";
12
13
  import { n as DeviceRole, r as DeviceType$1, t as DeviceFeature } from "../../device-type-DgEvK3ch.mjs";
13
14
  import { r as isAirConditioner, t as canonicalStoredDeviceType } from "../../device-kind-BJ2pfsjw.mjs";
14
- import { $t as weekdayOfLocalDate, At as forEachLeaf, B as customKeyOfRole, Bt as QuantityUnitError, C as powerSourceCapability, F as findChannelSource, Ft as holdOf, L as remoteSourceSteps, Mt as isEventLeaf, Qt as siteFor, R as resolveRemoteSource, S as PowerSourceStateSchema, St as validateRecipeBounds, W as toTimings, Xt as nextOccurrence, Yt as localDateOf, Zt as occurrenceOn, _ as replacedFieldKeys, _t as AutomationRecipeSchema, a as coreBlockComposition, an as VocabActionError, at as buildStepArgsTrace, b as powerSourceLinkOfComposition, bt as stepConditionsOf, c as coreBlocksCapability, cn as assertDeviceOffers, d as resolveCoreBlockFiles, dn as vocabCall, en as zoneOnlySite, f as describeComposableCaps, ft as SchedulerSchema, g as planComposition, h as compositionUnionReads, ht as ActionStepSchema, i as coreBlockAddonId, in as canonicalStoredStepTargets, it as appendTrace, j as MediaPlayerStatusSchema, jt as hasEventLeaves, k as CAP_CUSTOMIZE_CATALOG, l as normalizeCoreBlockWrite, ln as findVocabAction, lt as SchedulerError, m as compositionSourceRefs, mt as validateSchedulerInput, n as CORE_BLOCK_ADDON_PREFIX, nn as ACTION_TARGET_INVALIDATION_EVENTS, nt as AutomationStateDocSchema, o as coreBlockIdFromAddonId, on as actionEffect, ot as DEFAULT_HOLD_OVERRIDE, p as buildCapabilityLookup, r as CoreBlockSchema, rn as ActionTargetResolver, rt as EMPTY_AUTOMATION_STATE, s as coreBlockSourceKind, t as CORE_BLOCKS_ADDON_ID, u as resolveCoreBlockEntry, un as vocabActionIdFor, v as validateComposition, vt as REPEAT_ITEM_VAR, x as PowerSourceInfoSchema, xt as stepGuardOf, y as powerSourceActuatorConflicts, yt as nestedStepsOf } from "../../core-blocks.cap-C6iKAZ-x.mjs";
15
+ import { $t as siteFor, B as customKeyOfRole, C as powerSourceCapability, Ct as validateRecipeBounds, F as findChannelSource, It as holdOf, L as remoteSourceSteps, Mt as hasEventLeaves, Nt as isEventLeaf, Pt as compareValues, Qt as occurrenceOn, R as resolveRemoteSource, S as PowerSourceStateSchema, St as stepGuardOf, Vt as QuantityUnitError, W as toTimings, Xt as localDateOf, Zt as nextOccurrence, _ as replacedFieldKeys, _t as AutomationRecipeSchema, a as coreBlockComposition, an as canonicalStoredStepTargets, at as buildStepArgsTrace, b as powerSourceLinkOfComposition, bt as nestedStepsOf, c as coreBlocksCapability, d as resolveCoreBlockFiles, dn as vocabActionIdFor, en as weekdayOfLocalDate, f as describeComposableCaps, fn as vocabCall, ft as SchedulerSchema, g as planComposition, h as compositionUnionReads, ht as ActionStepSchema, i as coreBlockAddonId, in as ActionTargetResolver, it as appendTrace, j as MediaPlayerStatusSchema, jt as forEachLeaf, k as CAP_CUSTOMIZE_CATALOG, l as normalizeCoreBlockWrite, ln as assertDeviceOffers, lt as SchedulerError, m as compositionSourceRefs, mt as validateSchedulerInput, n as CORE_BLOCK_ADDON_PREFIX, nt as AutomationStateDocSchema, o as coreBlockIdFromAddonId, on as VocabActionError, ot as DEFAULT_HOLD_OVERRIDE, p as buildCapabilityLookup, r as CoreBlockSchema, rn as ACTION_TARGET_INVALIDATION_EVENTS, rt as EMPTY_AUTOMATION_STATE, s as coreBlockSourceKind, sn as actionEffect, t as CORE_BLOCKS_ADDON_ID, tn as zoneOnlySite, u as resolveCoreBlockEntry, un as findVocabAction, v as validateComposition, vt as HTTP_TEXT_CAP, x as PowerSourceInfoSchema, xt as stepConditionsOf, y as powerSourceActuatorConflicts, yt as REPEAT_ITEM_VAR } from "../../core-blocks.cap-BRPsLAij.mjs";
15
16
  import { B as helperMembers, D as composedDeviceRef, E as canonicalStoredBlockTarget, N as compositionSourceKey, O as composedDeviceStableId, T as CompositionSchema, U as DAY_MS, Y as historyRetentionFromSettings, _t as evaluateDwell, k as compositionFeatureEnabled, x as COMPOSER_ADDON_ID, z as HelperMemberSchema } from "../../error.cap-CSM_SRfR.mjs";
16
- import { a as evaluateWhenTree, c as nextTimeBoundaryInMs, i as collectWhenMirrorSources, l as stableIdMapOf, n as unwrapStoredValue, o as hasHoldLeaves, r as ConditionMirror, s as hasTimeLeaves, t as loadPrefixed } from "../../prefix-walk-B4b2-9aK.mjs";
17
+ import { a as evaluateWhenTree, c as nextTimeBoundaryInMs, i as collectWhenMirrorSources, l as stableIdMapOf, n as unwrapStoredValue, o as hasHoldLeaves, r as ConditionMirror, s as hasTimeLeaves, t as loadPrefixed } from "../../prefix-walk-ifwg_ukx.mjs";
17
18
  import { t } from "../../l10n-Bu6aUvSY.mjs";
18
19
  import { t as integrationInstancesCapability } from "../../integration-instances.cap-Cl9O-k4h.mjs";
19
20
  import { t as commandOrigin$1 } from "../../cap-call-context-DNwdgGSQ.mjs";
20
- import { r as compileScalarOverride, t as describeCompositionSources } from "../../composition-sources-Caqv7O7z.mjs";
21
+ import { r as compileScalarOverride, t as describeCompositionSources } from "../../composition-sources-BEUWn2s_.mjs";
21
22
  import { r as seedInstanceOnce, t as DeclaredDevices } from "../../declared-device-CKERA1Hi.mjs";
22
23
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
23
24
  import { i as capSeriesKey, m as parseConfirmedStateChanged, p as isRecord$1 } from "../../capture-engine-DiwbjoWp.mjs";
@@ -27,6 +28,7 @@ import { createRequire } from "node:module";
27
28
  import { z } from "zod";
28
29
  import { randomUUID } from "node:crypto";
29
30
  import { customizationBlockName } from "@camstack/types/node";
31
+ import * as net from "node:net";
30
32
  import * as path$1 from "node:path";
31
33
  import { isCapMethodAbsent, nodeIdOfScopedKey } from "@camstack/types/addon";
32
34
  import * as fs from "node:fs/promises";
@@ -88,6 +90,26 @@ async function readGuard(guard) {
88
90
  };
89
91
  }
90
92
  }
93
+ /**
94
+ * What a loop's condition says about going on. A `while` goes on while it
95
+ * reads true, an `until` goes on while it reads false; `unknown` ends either,
96
+ * with the reason (D49): a loop never runs on a value it could not read.
97
+ */
98
+ function repeatCheck(by, verdict) {
99
+ if (verdict.result === "unknown") return {
100
+ go: false,
101
+ reason: `the condition could not be read: ${verdict.reason}`,
102
+ unknown: true
103
+ };
104
+ if (by === "while") return verdict.result === "true" ? { go: true } : {
105
+ go: false,
106
+ reason: "the condition is no longer true"
107
+ };
108
+ return verdict.result === "true" ? {
109
+ go: false,
110
+ reason: "the condition is true"
111
+ } : { go: true };
112
+ }
91
113
  /** A loop condition that throws ends the loop as unreadable, never a crash of the run. */
92
114
  async function readRepeatCheck(check, iteration) {
93
115
  if (check === void 0) return { go: true };
@@ -649,10 +671,6 @@ function commandStepMeta(target, actionId) {
649
671
  ...target.kind === "devices" && target.ids.length === 1 ? { deviceId: target.ids[0] } : {}
650
672
  };
651
673
  }
652
- function stepMetaOfAction(step) {
653
- if (step.kind === "wait") return { kind: "wait" };
654
- return commandStepMeta(step.target, step.actionId);
655
- }
656
674
  function isPlainRecord$2(value) {
657
675
  return value !== null && typeof value === "object" && !Array.isArray(value);
658
676
  }
@@ -690,75 +708,6 @@ async function runForDevices(deviceIds, scope, work, concurrency = 4) {
690
708
  const failed = outcomes.filter((o) => o.outcome === "error");
691
709
  if (failed.length > 0) throw new Error(`${failed.length} of ${outcomes.length} devices failed: ` + failed.slice(0, 3).map((f) => `${f.deviceId}: ${f.message ?? "failed"}`).join("; "));
692
710
  }
693
- /**
694
- * The runnable form of an internal Action's steps, bound to one run's
695
- * variables. Variables are substituted per step, at the moment it runs, so a
696
- * missing one fails THAT step (traced) and leaves the later ones not-run.
697
- */
698
- /** The guard and the else list of a step, bound to the run (#472); `{}` for an unguarded step. */
699
- function guardOf(step, vars, deps) {
700
- const when = step.if;
701
- if (when === void 0) return {};
702
- const evaluate = deps.evaluateCondition;
703
- return {
704
- guard: async () => evaluate === void 0 ? {
705
- result: "unknown",
706
- reason: "this consumer has no condition evaluator"
707
- } : evaluate(when),
708
- ...step.else === void 0 ? {} : { otherwise: buildActionSteps(step.else, vars, deps) }
709
- };
710
- }
711
- function buildActionSteps(steps, vars, deps) {
712
- return steps.map((step) => {
713
- const guarded = {
714
- ...guardOf(step, vars, deps),
715
- ...step.enabled === false ? { disabled: true } : {}
716
- };
717
- const meta = stepMetaOfAction(step);
718
- if (step.kind === "wait") return {
719
- meta,
720
- ...guarded,
721
- run: () => deps.sleep(step.seconds * 1e3)
722
- };
723
- return {
724
- meta,
725
- ...guarded,
726
- run: async (scope) => {
727
- vocabCall(step.actionId, void 0);
728
- const templated = await resolveStepArgsWithTemplates(step.args ?? {}, vars, deps.onMissingVar, deps.renderTemplates);
729
- if (templated.notes.length > 0) scope.setTemplateNotes(templated.notes);
730
- const args = isPlainRecord$2(templated.value) ? templated.value : {};
731
- const target = await deps.resolveTarget(step.target, step.actionId, vars, {
732
- actionId: step.actionId,
733
- owner: deps.owner
734
- });
735
- if (target.deviceIds.length === 0) {
736
- scope.markEmpty(target.emptyReason ?? "the target matched no device");
737
- return;
738
- }
739
- const call = vocabCall(step.actionId, args);
740
- scope.setArgs(args);
741
- const [only] = target.deviceIds;
742
- if (target.deviceIds.length === 1 && only !== void 0) {
743
- scope.setDeviceId(only);
744
- await deps.invokeCap({
745
- deviceId: only,
746
- cap: call.cap,
747
- method: call.method,
748
- args: call.args
749
- });
750
- return;
751
- }
752
- await runForDevices(target.deviceIds, scope, (deviceId) => deps.invokeCap({
753
- deviceId,
754
- cap: call.cap,
755
- method: call.method,
756
- args: call.args
757
- }));
758
- }
759
- };
760
- });
761
- }
762
711
  //#endregion
763
712
  //#region ../types/dist/esm/automation/recipe-literal.mjs
764
713
  /**
@@ -929,7 +878,7 @@ function triggerLeafVariables(kind) {
929
878
  * (D8: an event WAKES the evaluation, the reconcile guarantees it). */
930
879
  var RECONCILE_MS = 15e3;
931
880
  /** What a step trace shows before the step runs. */
932
- function stepMetaOf(action) {
881
+ function stepMetaOf$1(action) {
933
882
  switch (action.kind) {
934
883
  case "wait": return { kind: "wait" };
935
884
  case "code": return { kind: "code" };
@@ -1241,66 +1190,35 @@ function emitStepBody(action) {
1241
1190
  case "wait": return ` await sleep(${j(action.seconds * 1e3)})`;
1242
1191
  case "command": return ` await actuateTarget(scope, ${j(action.target)}, ${j(action.actionId)}, ${j(action.args ?? {})}, vars)`;
1243
1192
  case "action": return ` // an Action run, awaited: the step takes THAT run's outcome
1244
- const result = await ctx.api.actions.run.mutate({
1245
- actionId: ${j(action.actionId)},
1246
- variables: substituteVariables(${j(action.variables ?? {})}, vars),
1247
- wait: true,
1248
- origin: { blockId: BLOCK_ID ?? undefined },
1249
- })
1250
- if (result.outcome !== 'ran') {
1251
- throw new Error('action ' + ${j(action.actionId)} + ' ' + result.outcome + (result.message === undefined ? '' : ': ' + result.message))
1252
- }`;
1193
+ await runActionBody(${j(action)}, {
1194
+ ...env,
1195
+ run: (input) =>
1196
+ ctx.api.actions.run.mutate({
1197
+ actionId: input.actionId,
1198
+ variables: input.variables,
1199
+ wait: true,
1200
+ origin: { blockId: BLOCK_ID ?? undefined },
1201
+ }),
1202
+ })`;
1253
1203
  case "notify": return ` // a notification through one target: the one send path the exporters use
1254
- const sent = await sendToExportedTarget(ctx.api, ctx.logger, {
1255
- exporter: 'automation',
1256
- targetId: ${j(action.targetId)},
1257
- notification: {
1258
- body: String(substitute(${j(action.body)}, vars)),
1259
- ${action.title === void 0 ? "" : `title: String(substitute(${j(action.title)}, vars)),`}
1260
- },
1261
- })
1262
- if (sent.status === 'refused') throw new Error('notification target ' + sent.reason)
1263
- if (sent.status === 'failed') throw new Error('notification failed: ' + sent.message)`;
1204
+ await runNotifyBody(${j(action)}, {
1205
+ ...env,
1206
+ send: (input) =>
1207
+ sendToExportedTarget(ctx.api, ctx.logger, {
1208
+ exporter: 'automation',
1209
+ targetId: input.targetId,
1210
+ notification: { body: input.body, ...(input.title === undefined ? {} : { title: input.title }) },
1211
+ }),
1212
+ })`;
1264
1213
  case "probe": return ` // a TCP reachability probe: one measurement, an expectation, an optional retry window
1265
- const probed = await runProbeStep(
1266
- { connect: tcpConnect, now: () => Date.now(), sleep, isAborted: () => token.aborted },
1267
- {
1268
- host: String(substitute(${j(action.host)}, vars)),
1269
- port: ${j(action.port)},
1270
- timeoutSeconds: ${j(action.timeoutSeconds)},
1271
- ${action.expect === void 0 ? "" : `expect: ${j(action.expect)},`}
1272
- ${action.retryUntilSeconds === void 0 ? "" : `retryUntilSeconds: ${j(action.retryUntilSeconds)},`}
1273
- },
1274
- )
1275
- ${action.saveAs === void 0 ? "" : `Object.assign(vars, reachVars(${j(action.saveAs)}, probed.result))`}
1276
- scope.setAttempts(probed.attempts, probed.message)
1277
- ctx.logger.info('probe finished', { host: String(substitute(${j(action.host)}, vars)), port: ${j(action.port)}, met: probed.met, attempts: probed.attempts, rttMs: probed.result.rttMs })
1278
- if (!probed.met) throw new Error('probe: ' + probed.message)`;
1214
+ await runProbeBody(${j(action)}, scope, { ...env, connect: tcpConnect })`;
1279
1215
  case "http-request": return ` // an HTTP request: one measurement, an expectation, an optional retry window.
1280
1216
  // Header values and the body are never logged or traced.
1281
- const httpUrl = String(substitute(${j(action.url)}, vars))
1282
- scope.setArgs({ method: ${j(action.method)}, url: redactUrl(httpUrl) })
1283
- const startedHttp = Date.now()
1284
- const requested = await runHttpStep(
1285
- { fetch: globalThis.fetch, now: () => Date.now(), sleep, isAborted: () => token.aborted },
1286
- {
1287
- method: ${j(action.method)},
1288
- url: httpUrl,
1289
- timeoutSeconds: ${j(action.timeoutSeconds)},
1290
- ${action.headers === void 0 ? "" : `headers: substituteStrings(${j(action.headers)}, vars),`}
1291
- ${action.body === void 0 ? "" : `body: String(substitute(${j(action.body)}, vars)),`}
1292
- ${action.expect === void 0 ? "" : `expect: ${j(action.expect)},`}
1293
- ${action.retryUntilSeconds === void 0 ? "" : `retryUntilSeconds: ${j(action.retryUntilSeconds)},`}
1294
- },
1295
- )
1296
- ${action.saveAs === void 0 ? "" : `Object.assign(vars, reachVars(${j(action.saveAs)}, requested.result))`}
1297
- scope.setAttempts(requested.attempts, requested.message)
1298
- ctx.logger.info('http request finished', { method: ${j(action.method)}, url: redactUrl(httpUrl), status: requested.result.status, met: requested.met, attempts: requested.attempts, durationMs: Date.now() - startedHttp })
1299
- if (!requested.met) throw new Error('http request: ' + requested.message)`;
1217
+ await runHttpBody(${j(action)}, scope, { ...env, fetch: globalThis.fetch })`;
1300
1218
  case "stop": return ` // end the run here, on purpose: the steps after it are not-run with this reason
1301
1219
  scope.stop(String(substitute(${j(action.reason)}, vars)), ${j(action.outcome)})`;
1302
1220
  case "set": return ` // write the run's own bag, for the steps after this one — substitution only
1303
- Object.assign(vars, substituteVariables(${j(action.vars)}, vars))`;
1221
+ runSetBody(${j(action)}, env)`;
1304
1222
  case "code": return ` // inline code action — a fragment of THIS block, bundled by esbuild
1305
1223
  await (async () => {
1306
1224
  ${action.code.split("\n").map((line) => ` ${line}`).join("\n")}
@@ -1317,7 +1235,7 @@ function isNestedSite(site) {
1317
1235
  /** A list of steps under `path` (a branch, an else list, the steps of a repeat or a parallel). */
1318
1236
  function emitList(steps, path) {
1319
1237
  return steps.map((step, at) => emitStep(step, {
1320
- meta: j(stepMetaOf(step)),
1238
+ meta: j(stepMetaOf$1(step)),
1321
1239
  path: `${path}.${at}`
1322
1240
  })).join("\n");
1323
1241
  }
@@ -1360,52 +1278,22 @@ function wakeDevicesOf(when) {
1360
1278
  }
1361
1279
  /** A `wait-until` step: read the condition, wait for a wake, read again, until the timeout. */
1362
1280
  function emitWaitUntil(action, site) {
1363
- const onTimeout = action.onTimeout === "stop" ? `scope.stop(message, 'failed')` : "scope.markTimedOut(message)";
1364
1281
  return ` {
1365
1282
  meta: ${site.meta},
1366
1283
  run: async (scope) => {
1367
1284
  // woken by a report of one of its devices, by the reconcile tick, or by a restart
1368
- const waited = await waitUntil({
1285
+ await runWaitUntilBody(${j(action)}, scope, {
1286
+ ...env,
1369
1287
  read: () => evaluateCondition(${j(action.when)}, ${j(`${site.path}.when`)}, vars),
1370
- timeoutMs: ${j(action.timeoutS * 1e3)},
1371
- now: () => Date.now(),
1372
- isAborted: () => token.aborted,
1373
1288
  nextWake: (ms) => waitForWake(ms, token, ${j(wakeDevicesOf(action.when))}),
1374
- })
1375
- if (waited.result === 'timed-out') {
1376
- const message = waitTimedOutMessage(${j(action.timeoutS)}, waited.lastReason)
1377
- ctx.logger.info('wait-until timed out', { step: ${j(site.path)}, onTimeout: ${j(action.onTimeout)}, reason: waited.lastReason })
1378
- ${onTimeout}
1379
- }
1289
+ }, ${j(site.path)})
1380
1290
  },
1381
1291
  },`;
1382
1292
  }
1383
- /** How a `repeat` decides its iterations, as the fields of a RunnableRepeat. */
1293
+ /** How a `repeat` decides its iterations, as the fields of a RunnableRepeat: the shared `repeatLoopFields`. */
1384
1294
  function emitRepeatLoop(loop, site) {
1385
- switch (loop.by) {
1386
- case "count": return `limit: ${j(loop.count)}, limitIsTimeout: false,`;
1387
- case "forEach": return `// once per device: the device id is in vars.${REPEAT_ITEM_VAR} for the steps of that iteration
1388
- limit: ${j(loop.target.ids.length)}, limitIsTimeout: false,
1389
- ...(() => {
1390
- const ids = ${j(loop.target.ids)}
1391
- let outer: unknown
1392
- return {
1393
- before: async (iteration) => {
1394
- if (iteration === 0) outer = vars[${j(REPEAT_ITEM_VAR)}]
1395
- if (iteration < ids.length) vars[${j(REPEAT_ITEM_VAR)}] = ids[iteration]
1396
- else if (${j(isNestedSite(site))} && outer !== undefined) vars[${j(REPEAT_ITEM_VAR)}] = outer
1397
- return { go: true }
1398
- },
1399
- }
1400
- })(),`;
1401
- case "while":
1402
- case "until": {
1403
- const read = `repeatCheck(${j(loop.by)}, await evaluateCondition(${j(loop.when)}, ${j(`${site.path}.loop.when`)}, vars))`;
1404
- const pause = loop.waitS === void 0 ? "" : `\n between: () => sleep(${j(loop.waitS * 1e3)}),`;
1405
- return `limit: ${j(loop.maxIterations)}, limitIsTimeout: true,
1406
- ${loop.by === "while" ? "before" : "after"}: async () => ${read},${pause}`;
1407
- }
1408
- }
1295
+ const read = loop.by === "while" || loop.by === "until" ? `read: (when) => evaluateCondition(when, ${j(`${site.path}.loop.when`)}, vars)` : "read: async () => ({ result: 'unknown', reason: 'no condition' })";
1296
+ return `...repeatLoopFields(${j(loop)}, { ...env, ${read} }, ${j(isNestedSite(site))}),`;
1409
1297
  }
1410
1298
  /** One step, wherever it sits: a block step emits its own steps one level down, under its path. */
1411
1299
  function emitStep(action, site) {
@@ -1495,7 +1383,7 @@ function renderAutomationBlock(input) {
1495
1383
  if (boundsError !== null) throw new Error(`cannot generate an automation from an invalid recipe: ${boundsError}`);
1496
1384
  const { name, recipe } = input;
1497
1385
  const runMode = recipe.runMode ?? { mode: "single" };
1498
- const stepMeta = recipe.actions.map(stepMetaOf);
1386
+ const stepMeta = recipe.actions.map(stepMetaOf$1);
1499
1387
  const elseSteps = (a) => a.kind === "wait" || a.kind === "command" ? a.else ?? [] : [];
1500
1388
  const hasDomainTarget = recipe.actions.flatMap((a) => [
1501
1389
  a,
@@ -1523,6 +1411,7 @@ function renderAutomationBlock(input) {
1523
1411
  AutomationRunVerdict,
1524
1412
  AutomationWhen,
1525
1413
  AutomationStepTrace,
1414
+ BodyEnv,
1526
1415
  RunnableStep,
1527
1416
  StepScope,
1528
1417
  TimeSite,
@@ -1561,13 +1450,13 @@ import {
1561
1450
  vocabCall,
1562
1451
  evaluateStepCondition,
1563
1452
  runSteps,
1564
- runProbeStep,
1565
- runHttpStep,
1566
- redactUrl,
1567
- reachVars,
1568
- repeatCheck,
1569
- waitUntil,
1570
- waitTimedOutMessage,
1453
+ runProbeBody,
1454
+ runHttpBody,
1455
+ runActionBody,
1456
+ runNotifyBody,
1457
+ runSetBody,
1458
+ runWaitUntilBody,
1459
+ repeatLoopFields,
1571
1460
  siteFor,
1572
1461
  validateTimeSpecForSite,
1573
1462
  zoneOnlySite,
@@ -1991,14 +1880,6 @@ ${hasTime ? ` // a time-is leaf changes sides at a boundary with no device ev
1991
1880
  return resolveStepArgs(value, vars, warnMissingVar)
1992
1881
  }
1993
1882
 
1994
- /** Header values, substituted: the values are text, and are never logged. */
1995
- function substituteStrings(
1996
- raw: Record<string, string>,
1997
- vars: Record<string, unknown>,
1998
- ): Record<string, string> {
1999
- return Object.fromEntries(Object.entries(raw).map(([key, value]) => [key, String(substitute(value, vars))]))
2000
- }
2001
-
2002
1883
  /** Open a TCP connection and close it again: resolves when the port answered. */
2003
1884
  async function tcpConnect(host: string, port: number, timeoutMs: number): Promise<void> {
2004
1885
  const net = await import('node:net')
@@ -2015,21 +1896,6 @@ ${hasTime ? ` // a time-is leaf changes sides at a boundary with no device ev
2015
1896
  })
2016
1897
  }
2017
1898
 
2018
- /** The variables handed to an Action step, substituted and kept to primitives. */
2019
- function substituteVariables(
2020
- raw: Record<string, string | number | boolean>,
2021
- vars: Record<string, unknown>,
2022
- ): Record<string, string | number | boolean> {
2023
- const out: Record<string, string | number | boolean> = {}
2024
- for (const [key, value] of Object.entries(raw)) {
2025
- const resolved = substitute(value, vars)
2026
- if (typeof resolved === 'string' || typeof resolved === 'number' || typeof resolved === 'boolean') {
2027
- out[key] = resolved
2028
- }
2029
- }
2030
- return out
2031
- }
2032
-
2033
1899
  async function actuate(
2034
1900
  scope: StepScope,
2035
1901
  deviceId: number,
@@ -2077,6 +1943,15 @@ ${hasTime ? ` // a time-is leaf changes sides at a boundary with no device ev
2077
1943
  token: RunToken,
2078
1944
  ): Promise<{ steps: readonly AutomationStepTrace[]; failed: boolean }> {
2079
1945
  const sleep = (ms: number): Promise<void> => abortableSleep(ms, token)
1946
+ // what a step does when it runs is shared with an Action's runner (step-bodies.ts)
1947
+ const env: BodyEnv = {
1948
+ vars,
1949
+ substitute: (value) => substitute(value, vars),
1950
+ sleep,
1951
+ now: () => Date.now(),
1952
+ isAborted: () => token.aborted,
1953
+ info: (message, meta) => ctx.logger.info(message, meta),
1954
+ }
2080
1955
  const steps: RunnableStep[] = [
2081
1956
  ${recipe.actions.map((a, i) => emitAction(a, i)).join("\n")}
2082
1957
  ]
@@ -2364,7 +2239,7 @@ ${eventLeaves.map(({ leaf, path }) => emitLeaf(leaf, path)).join("\n\n")}
2364
2239
  * named devices' binding maps, never the fleet-wide capability list.
2365
2240
  */
2366
2241
  /** The steps directly under this one: its `else`, a block's body, every branch. */
2367
- function childrenOf(step) {
2242
+ function childrenOf$1(step) {
2368
2243
  switch (step.kind) {
2369
2244
  case "wait":
2370
2245
  case "command": return "else" in step ? step.else ?? [] : [];
@@ -2379,7 +2254,7 @@ function commandsIn(step) {
2379
2254
  return [...step.kind === "command" && step.target.kind === "devices" ? [{
2380
2255
  actionId: step.actionId,
2381
2256
  ids: step.target.ids
2382
- }] : [], ...childrenOf(step).flatMap(commandsIn)];
2257
+ }] : [], ...childrenOf$1(step).flatMap(commandsIn)];
2383
2258
  }
2384
2259
  /**
2385
2260
  * Refuse a step list naming a device that does not offer the step's action.
@@ -2423,6 +2298,738 @@ async function evaluateStepCondition(when, fetchers, now = Date.now, history, si
2423
2298
  };
2424
2299
  }
2425
2300
  //#endregion
2301
+ //#region ../types/dist/esm/automation/reach-steps.mjs
2302
+ /** Read at most `cap` bytes of a body, then cancel the stream: a huge answer is never held. */
2303
+ async function readCappedBody(response, cap) {
2304
+ if (response.body === void 0 || response.body === null) {
2305
+ const full = await response.text();
2306
+ return full.length > cap ? {
2307
+ text: full.slice(0, cap),
2308
+ truncated: true
2309
+ } : {
2310
+ text: full,
2311
+ truncated: false
2312
+ };
2313
+ }
2314
+ const reader = response.body.getReader();
2315
+ const chunks = [];
2316
+ let total = 0;
2317
+ let truncated = false;
2318
+ for (;;) {
2319
+ const { done, value } = await reader.read();
2320
+ if (done) break;
2321
+ if (value === void 0) continue;
2322
+ const room = cap - total;
2323
+ if (value.length > room) {
2324
+ chunks.push(value.subarray(0, room));
2325
+ total += room;
2326
+ truncated = true;
2327
+ await reader.cancel();
2328
+ break;
2329
+ }
2330
+ chunks.push(value);
2331
+ total += value.length;
2332
+ }
2333
+ const bytes = new Uint8Array(total);
2334
+ let at = 0;
2335
+ for (const chunk of chunks) {
2336
+ bytes.set(chunk, at);
2337
+ at += chunk.length;
2338
+ }
2339
+ return {
2340
+ text: new TextDecoder().decode(bytes),
2341
+ truncated
2342
+ };
2343
+ }
2344
+ /**
2345
+ * A URL as it may be logged or traced: the userinfo and every query value are
2346
+ * replaced by `***` (the keys stay). Text that is not a URL is returned as `***`.
2347
+ */
2348
+ function redactUrl(raw) {
2349
+ try {
2350
+ const u = new URL(raw);
2351
+ if (u.username !== "") u.username = "***";
2352
+ if (u.password !== "") u.password = "***";
2353
+ for (const key of [...u.searchParams.keys()]) u.searchParams.set(key, "***");
2354
+ return u.toString().replace(/%2A%2A%2A/g, "***");
2355
+ } catch {
2356
+ return "***";
2357
+ }
2358
+ }
2359
+ function errorText$5(err) {
2360
+ return err instanceof Error ? err.message : String(err);
2361
+ }
2362
+ /** A transport error names the URL it was given: show the redacted one, and no userinfo at all. */
2363
+ function scrubbedError(err, url) {
2364
+ return errorText$5(err).split(url).join(redactUrl(url)).replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@]*@/gi, "$1***@");
2365
+ }
2366
+ /**
2367
+ * Try, and while the expectation does not hold and the window is open, pause
2368
+ * {@link REACH_RETRY_INTERVAL_S} s and try again. Bounded twice: the window is
2369
+ * clamped to {@link REACH_RETRY_MAX_S}, and the pause is a constant.
2370
+ */
2371
+ async function retryUntilMet(clock, input) {
2372
+ const windowMs = Math.min(input.windowSeconds ?? 0, 600) * 1e3;
2373
+ const deadline = clock.now() + windowMs;
2374
+ const interval = 5 * 1e3;
2375
+ let attempts = 0;
2376
+ for (;;) {
2377
+ const result = await input.attempt();
2378
+ attempts += 1;
2379
+ const met = input.met(result);
2380
+ if (met || clock.isAborted()) return {
2381
+ result,
2382
+ met,
2383
+ attempts
2384
+ };
2385
+ const left = deadline - clock.now();
2386
+ if (left <= 0) return {
2387
+ result,
2388
+ met,
2389
+ attempts
2390
+ };
2391
+ await clock.sleep(Math.min(interval, left));
2392
+ if (clock.isAborted()) return {
2393
+ result,
2394
+ met,
2395
+ attempts
2396
+ };
2397
+ }
2398
+ }
2399
+ async function probeOnce(deps, input) {
2400
+ const startedAt = deps.now();
2401
+ try {
2402
+ await deps.connect(input.host, input.port, input.timeoutSeconds * 1e3);
2403
+ return {
2404
+ reachable: true,
2405
+ rttMs: Math.max(0, deps.now() - startedAt),
2406
+ error: null
2407
+ };
2408
+ } catch (err) {
2409
+ return {
2410
+ reachable: false,
2411
+ rttMs: null,
2412
+ error: errorText$5(err)
2413
+ };
2414
+ }
2415
+ }
2416
+ async function runProbeStep(deps, input) {
2417
+ const want = input.expect ?? "reachable";
2418
+ const run = await retryUntilMet(deps, {
2419
+ attempt: () => probeOnce(deps, input),
2420
+ met: (result) => result.reachable === (want === "reachable"),
2421
+ windowSeconds: input.retryUntilSeconds
2422
+ });
2423
+ const seen = run.result.reachable ? `reachable in ${String(run.result.rttMs)} ms` : `unreachable (${run.result.error ?? "no answer"})`;
2424
+ return {
2425
+ ...run,
2426
+ message: `${run.met ? "expected" : "wanted"} ${want}; after ${String(run.attempts)} attempt(s) ${seen}`
2427
+ };
2428
+ }
2429
+ function parseJson(text, truncated) {
2430
+ if (truncated) return null;
2431
+ try {
2432
+ return JSON.parse(text);
2433
+ } catch {
2434
+ return null;
2435
+ }
2436
+ }
2437
+ async function httpOnce(deps, input) {
2438
+ const controller = new AbortController();
2439
+ const timer = setTimeout(() => controller.abort(), input.timeoutSeconds * 1e3);
2440
+ try {
2441
+ const response = await deps.fetch(input.url, {
2442
+ method: input.method,
2443
+ ...input.headers === void 0 ? {} : { headers: { ...input.headers } },
2444
+ ...input.body === void 0 ? {} : { body: input.body },
2445
+ signal: controller.signal
2446
+ });
2447
+ const body = await readCappedBody(response, HTTP_TEXT_CAP);
2448
+ return {
2449
+ status: response.status,
2450
+ ok: response.status >= 200 && response.status < 300,
2451
+ json: parseJson(body.text, body.truncated),
2452
+ text: body.text,
2453
+ error: null
2454
+ };
2455
+ } catch (err) {
2456
+ return {
2457
+ status: null,
2458
+ ok: false,
2459
+ json: null,
2460
+ text: null,
2461
+ error: controller.signal.aborted ? `timed out after ${String(input.timeoutSeconds)} s` : scrubbedError(err, input.url)
2462
+ };
2463
+ } finally {
2464
+ clearTimeout(timer);
2465
+ }
2466
+ }
2467
+ /** The value at a dotted path of a parsed body; `undefined` when any step of the path is missing. */
2468
+ function readPath(root, path) {
2469
+ let at = root;
2470
+ for (const key of path.split(".")) {
2471
+ if (at === null || typeof at !== "object") return void 0;
2472
+ at = Reflect.get(at, key);
2473
+ }
2474
+ return at;
2475
+ }
2476
+ /**
2477
+ * Whether the answer is what the step wanted. No expectation: a 2xx. A field
2478
+ * that is not there is never "met" — not even for `ne` — because "absent" is
2479
+ * not an answer the operator compared against (D49).
2480
+ */
2481
+ function httpExpectationMet(result, expect) {
2482
+ if (result.status === null) return false;
2483
+ if (expect === void 0) return result.ok;
2484
+ if (expect.on === "status") return compareValues(result.status, expect.operator, expect.value);
2485
+ if (expect.fieldPath === void 0) return false;
2486
+ const actual = readPath(result.json, expect.fieldPath);
2487
+ if (actual === void 0) return false;
2488
+ return compareValues(actual, expect.operator, expect.value);
2489
+ }
2490
+ async function runHttpStep(deps, input) {
2491
+ const run = await retryUntilMet(deps, {
2492
+ attempt: () => httpOnce(deps, input),
2493
+ met: (result) => httpExpectationMet(result, input.expect),
2494
+ windowSeconds: input.retryUntilSeconds
2495
+ });
2496
+ const seen = run.result.status === null ? `no answer (${run.result.error ?? "unknown"})` : `status ${String(run.result.status)}`;
2497
+ return {
2498
+ ...run,
2499
+ message: `${run.met ? "expectation met" : "expectation not met"}; after ${String(run.attempts)} attempt(s) ${seen}`
2500
+ };
2501
+ }
2502
+ var FLAT_DEPTH_MAX = 4;
2503
+ var FLAT_KEYS_MAX = 60;
2504
+ function flatten(prefix, value, depth, out) {
2505
+ if (Object.keys(out).length >= FLAT_KEYS_MAX) return;
2506
+ if (value === null || value === void 0) out[prefix] = "";
2507
+ else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") out[prefix] = value;
2508
+ else if (typeof value === "object" && !Array.isArray(value) && depth < FLAT_DEPTH_MAX) for (const [key, inner] of Object.entries(value)) flatten(`${prefix}.${key}`, inner, depth + 1, out);
2509
+ }
2510
+ /**
2511
+ * What a step writes into the run's bag under `saveAs`: the result itself, and
2512
+ * its scalar fields flat (`ccu.reachable`, `r.json.sysInfo.addr`), because a
2513
+ * `{{vars.x.y}}` slot reads the flat key. A `null` reads as empty text there.
2514
+ */
2515
+ function reachVars(name, result) {
2516
+ const flat = {};
2517
+ for (const [key, value] of Object.entries(result)) {
2518
+ if (key === "text") continue;
2519
+ flatten(`${name}.${key}`, value, 0, flat);
2520
+ }
2521
+ return {
2522
+ [name]: result,
2523
+ ...flat
2524
+ };
2525
+ }
2526
+ //#endregion
2527
+ //#region ../types/dist/esm/automation/wait-until.mjs
2528
+ async function readSafely(read) {
2529
+ try {
2530
+ return await read();
2531
+ } catch (err) {
2532
+ return {
2533
+ result: "unknown",
2534
+ reason: err instanceof Error ? err.message : String(err)
2535
+ };
2536
+ }
2537
+ }
2538
+ async function waitUntil(input) {
2539
+ const startedAt = input.now();
2540
+ const deadline = startedAt + input.timeoutMs;
2541
+ for (;;) {
2542
+ const verdict = await readSafely(input.read);
2543
+ const waitedMs = input.now() - startedAt;
2544
+ if (input.isAborted()) return {
2545
+ result: "aborted",
2546
+ waitedMs
2547
+ };
2548
+ if (verdict.result === "true") return {
2549
+ result: "met",
2550
+ waitedMs
2551
+ };
2552
+ const remaining = deadline - input.now();
2553
+ if (remaining <= 0) return {
2554
+ result: "timed-out",
2555
+ waitedMs,
2556
+ lastReason: verdict.reason
2557
+ };
2558
+ await input.nextWake(remaining);
2559
+ if (input.isAborted()) return {
2560
+ result: "aborted",
2561
+ waitedMs: input.now() - startedAt
2562
+ };
2563
+ }
2564
+ }
2565
+ /** What the run trace says of a wait that ran out. */
2566
+ function waitTimedOutMessage(timeoutS, lastReason) {
2567
+ return `timed out after ${timeoutS} s: ${lastReason}`;
2568
+ }
2569
+ //#endregion
2570
+ //#region ../types/dist/esm/automation/step-bodies.mjs
2571
+ /**
2572
+ * What a plain step DOES when it runs — the semantics of probe, http-request,
2573
+ * wait-until, set, notify and action, in ONE place. Two consumers call them:
2574
+ * the runner of an Action (`buildActionSteps`) and the block an automation
2575
+ * compiles to (`emitStepBody` emits a call to the same function), so a step
2576
+ * kind cannot behave one way in an Action and another in an automation.
2577
+ *
2578
+ * Pure: everything impure (clock, fetch, a TCP connect, the log) arrives in
2579
+ * {@link BodyEnv}.
2580
+ */
2581
+ function textOf(env, value) {
2582
+ return String(env.substitute(value));
2583
+ }
2584
+ /** Header values, substituted: the values are text, and are never logged. */
2585
+ function substituteTexts(env, raw) {
2586
+ return Object.fromEntries(Object.entries(raw).map(([key, value]) => [key, textOf(env, value)]));
2587
+ }
2588
+ /** The variables handed to an Action step, substituted and kept to primitives. */
2589
+ function substituteRunVariables(env, raw) {
2590
+ const out = {};
2591
+ for (const [key, value] of Object.entries(raw)) {
2592
+ const resolved = env.substitute(value);
2593
+ if (typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean") out[key] = resolved;
2594
+ }
2595
+ return out;
2596
+ }
2597
+ /** A TCP reachability probe: one measurement, an expectation, an optional retry window. */
2598
+ async function runProbeBody(step, scope, env) {
2599
+ const host = textOf(env, step.host);
2600
+ const probed = await runProbeStep({
2601
+ connect: env.connect,
2602
+ now: env.now,
2603
+ sleep: env.sleep,
2604
+ isAborted: env.isAborted
2605
+ }, {
2606
+ host,
2607
+ port: step.port,
2608
+ timeoutSeconds: step.timeoutSeconds,
2609
+ ...step.expect === void 0 ? {} : { expect: step.expect },
2610
+ ...step.retryUntilSeconds === void 0 ? {} : { retryUntilSeconds: step.retryUntilSeconds }
2611
+ });
2612
+ if (step.saveAs !== void 0) Object.assign(env.vars, reachVars(step.saveAs, probed.result));
2613
+ scope.setAttempts(probed.attempts, probed.message);
2614
+ env.info("probe finished", {
2615
+ host,
2616
+ port: step.port,
2617
+ met: probed.met,
2618
+ attempts: probed.attempts,
2619
+ rttMs: probed.result.rttMs
2620
+ });
2621
+ if (!probed.met) throw new Error(`probe: ${probed.message}`);
2622
+ }
2623
+ /**
2624
+ * An HTTP request: one measurement, an expectation, an optional retry window.
2625
+ * Header values and the body are never logged or traced.
2626
+ */
2627
+ async function runHttpBody(step, scope, env) {
2628
+ const url = textOf(env, step.url);
2629
+ scope.setArgs({
2630
+ method: step.method,
2631
+ url: redactUrl(url)
2632
+ });
2633
+ const startedAt = env.now();
2634
+ const requested = await runHttpStep({
2635
+ fetch: env.fetch,
2636
+ now: env.now,
2637
+ sleep: env.sleep,
2638
+ isAborted: env.isAborted
2639
+ }, {
2640
+ method: step.method,
2641
+ url,
2642
+ timeoutSeconds: step.timeoutSeconds,
2643
+ ...step.headers === void 0 ? {} : { headers: substituteTexts(env, step.headers) },
2644
+ ...step.body === void 0 ? {} : { body: textOf(env, step.body) },
2645
+ ...step.expect === void 0 ? {} : { expect: step.expect },
2646
+ ...step.retryUntilSeconds === void 0 ? {} : { retryUntilSeconds: step.retryUntilSeconds }
2647
+ });
2648
+ if (step.saveAs !== void 0) Object.assign(env.vars, reachVars(step.saveAs, requested.result));
2649
+ scope.setAttempts(requested.attempts, requested.message);
2650
+ env.info("http request finished", {
2651
+ method: step.method,
2652
+ url: redactUrl(url),
2653
+ status: requested.result.status,
2654
+ met: requested.met,
2655
+ attempts: requested.attempts,
2656
+ durationMs: env.now() - startedAt
2657
+ });
2658
+ if (!requested.met) throw new Error(`http request: ${requested.message}`);
2659
+ }
2660
+ /** Write the run's own bag, for the steps after this one — substitution only, never evaluation. */
2661
+ function runSetBody(step, env) {
2662
+ Object.assign(env.vars, substituteRunVariables(env, step.vars));
2663
+ }
2664
+ /** Pause until the condition is true; at the timeout, `continue` marks the step timed out, `stop` ends the run as a failure. */
2665
+ async function runWaitUntilBody(step, scope, env, path) {
2666
+ const waited = await waitUntil({
2667
+ read: env.read,
2668
+ timeoutMs: step.timeoutS * 1e3,
2669
+ now: env.now,
2670
+ isAborted: env.isAborted,
2671
+ nextWake: env.nextWake
2672
+ });
2673
+ if (waited.result !== "timed-out") return;
2674
+ const message = waitTimedOutMessage(step.timeoutS, waited.lastReason);
2675
+ env.info("wait-until timed out", {
2676
+ step: path,
2677
+ onTimeout: step.onTimeout,
2678
+ reason: waited.lastReason
2679
+ });
2680
+ if (step.onTimeout === "stop") scope.stop(message, "failed");
2681
+ else scope.markTimedOut(message);
2682
+ }
2683
+ /** A notification through one target: the one send path the exporters use. */
2684
+ async function runNotifyBody(step, env) {
2685
+ const sent = await env.send({
2686
+ targetId: step.targetId,
2687
+ body: textOf(env, step.body),
2688
+ ...step.title === void 0 ? {} : { title: textOf(env, step.title) }
2689
+ });
2690
+ if (sent.status === "refused") throw new Error(`notification target ${sent.reason}`);
2691
+ if (sent.status === "failed") throw new Error(`notification failed: ${sent.message}`);
2692
+ }
2693
+ /** An Action run, awaited: the step takes THAT run's outcome. */
2694
+ async function runActionBody(step, env) {
2695
+ const result = await env.run({
2696
+ actionId: step.actionId,
2697
+ variables: substituteRunVariables(env, step.variables ?? {})
2698
+ });
2699
+ if (result.outcome !== "ran") throw new Error(`action ${step.actionId} ${result.outcome}${result.message === void 0 ? "" : `: ${result.message}`}`);
2700
+ }
2701
+ /**
2702
+ * `nested` is whether the loop sits inside a block step: a `forEach` one level
2703
+ * down gives back the device of the loop around it, when there is one; any
2704
+ * other loop leaves its last device in place.
2705
+ */
2706
+ function repeatLoopFields(loop, env, nested) {
2707
+ switch (loop.by) {
2708
+ case "count": return {
2709
+ limit: loop.count,
2710
+ limitIsTimeout: false
2711
+ };
2712
+ case "forEach": {
2713
+ const ids = loop.target.ids;
2714
+ let outer;
2715
+ return {
2716
+ limit: ids.length,
2717
+ limitIsTimeout: false,
2718
+ before: async (iteration) => {
2719
+ if (iteration === 0) outer = env.vars[REPEAT_ITEM_VAR];
2720
+ const id = ids[iteration];
2721
+ if (id !== void 0) env.vars[REPEAT_ITEM_VAR] = id;
2722
+ else if (nested && outer !== void 0) env.vars[REPEAT_ITEM_VAR] = outer;
2723
+ return { go: true };
2724
+ }
2725
+ };
2726
+ }
2727
+ case "while":
2728
+ case "until": {
2729
+ const check = async () => repeatCheck(loop.by, await env.read(loop.when));
2730
+ const waitS = loop.waitS;
2731
+ return {
2732
+ limit: loop.maxIterations,
2733
+ limitIsTimeout: true,
2734
+ ...loop.by === "while" ? { before: check } : { after: check },
2735
+ ...waitS === void 0 ? {} : { between: () => env.sleep(waitS * 1e3) }
2736
+ };
2737
+ }
2738
+ }
2739
+ }
2740
+ //#endregion
2741
+ //#region ../types/dist/esm/automation/action-steps.mjs
2742
+ var NO_EVALUATOR = {
2743
+ result: "unknown",
2744
+ reason: "this consumer has no condition evaluator"
2745
+ };
2746
+ function stepMetaOf(step) {
2747
+ switch (step.kind) {
2748
+ case "command": return commandStepMeta(step.target, step.actionId);
2749
+ case "wait":
2750
+ case "action":
2751
+ case "notify":
2752
+ case "probe":
2753
+ case "http-request":
2754
+ case "wait-until":
2755
+ case "set":
2756
+ case "stop":
2757
+ case "choose":
2758
+ case "parallel":
2759
+ case "repeat": return { kind: step.kind };
2760
+ default: return assertNever(step);
2761
+ }
2762
+ }
2763
+ function assertNever(step) {
2764
+ throw new Error(`step kind not handled by the Action runner: ${JSON.stringify(step)}`);
2765
+ }
2766
+ /** The step needs an effect this consumer did not provide: it fails when it RUNS, with the name of what is missing. */
2767
+ function missing(kind, what) {
2768
+ return /* @__PURE__ */ new Error(`this consumer cannot run a ${kind} step: it has no ${what}`);
2769
+ }
2770
+ function bodyEnv(ctx) {
2771
+ const { deps, bag } = ctx;
2772
+ return {
2773
+ vars: bag,
2774
+ substitute: (value) => resolveStepArgs(value, bag, (name) => deps.onMissingVar(name)),
2775
+ sleep: (ms) => deps.sleep(ms),
2776
+ now: deps.now ?? Date.now,
2777
+ isAborted: deps.isAborted ?? (() => false),
2778
+ info: (message, meta) => deps.info?.(message, meta)
2779
+ };
2780
+ }
2781
+ function readerOf(ctx) {
2782
+ const evaluate = ctx.deps.evaluateCondition;
2783
+ return async (when) => evaluate === void 0 ? NO_EVALUATOR : evaluate(when);
2784
+ }
2785
+ /** The guard and the else list of a step (#472), bound to the run; `{}` for an unguarded step. */
2786
+ function guardOf(step, ctx) {
2787
+ const when = "if" in step ? step.if : void 0;
2788
+ if (when === void 0) return {};
2789
+ const read = readerOf(ctx);
2790
+ const otherwise = "else" in step ? step.else : void 0;
2791
+ return {
2792
+ guard: () => read(when),
2793
+ ...otherwise === void 0 ? {} : { otherwise: buildList(otherwise, ctx) }
2794
+ };
2795
+ }
2796
+ /** A device command: resolve the target, substitute the args, dispatch one call per device. */
2797
+ async function runCommand(step, scope, ctx) {
2798
+ const { deps, bag } = ctx;
2799
+ vocabCall(step.actionId, void 0);
2800
+ const templated = await resolveStepArgsWithTemplates(step.args ?? {}, bag, (name) => deps.onMissingVar(name), deps.renderTemplates);
2801
+ if (templated.notes.length > 0) scope.setTemplateNotes(templated.notes);
2802
+ const args = isPlainRecord$2(templated.value) ? templated.value : {};
2803
+ const target = await deps.resolveTarget(step.target, step.actionId, bag, {
2804
+ actionId: step.actionId,
2805
+ owner: deps.owner
2806
+ });
2807
+ if (target.deviceIds.length === 0) {
2808
+ scope.markEmpty(target.emptyReason ?? "the target matched no device");
2809
+ return;
2810
+ }
2811
+ const call = vocabCall(step.actionId, args);
2812
+ scope.setArgs(args);
2813
+ const [only] = target.deviceIds;
2814
+ if (target.deviceIds.length === 1 && only !== void 0) {
2815
+ scope.setDeviceId(only);
2816
+ await deps.invokeCap({
2817
+ deviceId: only,
2818
+ cap: call.cap,
2819
+ method: call.method,
2820
+ args: call.args
2821
+ });
2822
+ return;
2823
+ }
2824
+ await runForDevices(target.deviceIds, scope, (deviceId) => deps.invokeCap({
2825
+ deviceId,
2826
+ cap: call.cap,
2827
+ method: call.method,
2828
+ args: call.args
2829
+ }));
2830
+ }
2831
+ function buildStep(step, ctx, path) {
2832
+ const { deps } = ctx;
2833
+ const env = bodyEnv(ctx);
2834
+ const read = readerOf(ctx);
2835
+ const common = {
2836
+ meta: stepMetaOf(step),
2837
+ ...guardOf(step, ctx),
2838
+ ...step.enabled === false ? { disabled: true } : {},
2839
+ ..."continueOnError" in step && step.continueOnError === true ? { continueOnError: true } : {}
2840
+ };
2841
+ const inside = {
2842
+ ...ctx,
2843
+ nested: true
2844
+ };
2845
+ switch (step.kind) {
2846
+ case "wait": return {
2847
+ ...common,
2848
+ run: () => deps.sleep(step.seconds * 1e3)
2849
+ };
2850
+ case "command": return {
2851
+ ...common,
2852
+ run: (scope) => runCommand(step, scope, ctx)
2853
+ };
2854
+ case "action": {
2855
+ const run = deps.runAction;
2856
+ return {
2857
+ ...common,
2858
+ run: async () => {
2859
+ if (run === void 0) throw missing("action", "way to run another action");
2860
+ await runActionBody(step, {
2861
+ ...env,
2862
+ run
2863
+ });
2864
+ }
2865
+ };
2866
+ }
2867
+ case "notify": {
2868
+ const send = deps.sendNotification;
2869
+ return {
2870
+ ...common,
2871
+ run: async () => {
2872
+ if (send === void 0) throw missing("notify", "notification sender");
2873
+ await runNotifyBody(step, {
2874
+ ...env,
2875
+ send
2876
+ });
2877
+ }
2878
+ };
2879
+ }
2880
+ case "probe": {
2881
+ const connect = deps.connect;
2882
+ return {
2883
+ ...common,
2884
+ run: async (scope) => {
2885
+ if (connect === void 0) throw missing("probe", "network access");
2886
+ await runProbeBody(step, scope, {
2887
+ ...env,
2888
+ connect
2889
+ });
2890
+ }
2891
+ };
2892
+ }
2893
+ case "http-request": {
2894
+ const fetchFn = deps.fetch;
2895
+ return {
2896
+ ...common,
2897
+ run: async (scope) => {
2898
+ if (fetchFn === void 0) throw missing("http-request", "network access");
2899
+ await runHttpBody(step, scope, {
2900
+ ...env,
2901
+ fetch: fetchFn
2902
+ });
2903
+ }
2904
+ };
2905
+ }
2906
+ case "wait-until": {
2907
+ const poll = deps.waitPollMs ?? 5e3;
2908
+ return {
2909
+ ...common,
2910
+ run: (scope) => runWaitUntilBody(step, scope, {
2911
+ ...env,
2912
+ read: () => read(step.when),
2913
+ nextWake: (ms) => deps.sleep(Math.min(ms, poll))
2914
+ }, path)
2915
+ };
2916
+ }
2917
+ case "set": return {
2918
+ ...common,
2919
+ run: async () => runSetBody(step, env)
2920
+ };
2921
+ case "stop": return {
2922
+ ...common,
2923
+ run: async (scope) => {
2924
+ scope.stop(String(env.substitute(step.reason)), step.outcome);
2925
+ }
2926
+ };
2927
+ case "choose": return {
2928
+ ...common,
2929
+ run: async () => {},
2930
+ choose: {
2931
+ branches: step.branches.map((branch, at) => ({
2932
+ guard: () => read(branch.if),
2933
+ steps: buildList(branch.steps, inside, `${path}.branches.${at}.steps`)
2934
+ })),
2935
+ ...step.else === void 0 ? {} : { otherwise: buildList(step.else, inside, `${path}.else`) }
2936
+ }
2937
+ };
2938
+ case "parallel": return {
2939
+ ...common,
2940
+ run: async () => {},
2941
+ parallel: buildList(step.steps, inside, `${path}.steps`)
2942
+ };
2943
+ case "repeat": {
2944
+ const repeatEnv = {
2945
+ ...env,
2946
+ read
2947
+ };
2948
+ return {
2949
+ ...common,
2950
+ run: async () => {},
2951
+ repeat: {
2952
+ steps: buildList(step.steps, inside, `${path}.steps`),
2953
+ ...repeatLoopFields(step.loop, repeatEnv, ctx.nested)
2954
+ }
2955
+ };
2956
+ }
2957
+ default: return assertNever(step);
2958
+ }
2959
+ }
2960
+ function buildList(steps, ctx, path = "steps") {
2961
+ return steps.map((step, at) => buildStep(step, ctx, `${path}.${at}`));
2962
+ }
2963
+ /**
2964
+ * The runnable form of an Action's steps, bound to one run's variables. The
2965
+ * bag is copied: `set`, `probe` and `http-request` write to THIS run's copy.
2966
+ */
2967
+ function buildActionSteps(steps, vars, deps) {
2968
+ return buildList(steps, {
2969
+ bag: { ...vars },
2970
+ deps,
2971
+ nested: false
2972
+ });
2973
+ }
2974
+ //#endregion
2975
+ //#region ../types/dist/esm/automation/action-graph.mjs
2976
+ function childrenOf(step) {
2977
+ switch (step.kind) {
2978
+ case "wait":
2979
+ case "command": return "else" in step ? step.else ?? [] : [];
2980
+ case "parallel":
2981
+ case "repeat": return step.steps;
2982
+ case "choose": return [...step.branches.flatMap((branch) => branch.steps), ...step.else ?? []];
2983
+ default: return [];
2984
+ }
2985
+ }
2986
+ /** The ids of the Actions a step list runs, at any depth, each once, in the order they are written. */
2987
+ function actionIdsCalledBy(steps) {
2988
+ const ids = [];
2989
+ const visit = (step) => {
2990
+ if (step.kind === "action" && !ids.includes(step.actionId)) ids.push(step.actionId);
2991
+ for (const child of childrenOf(step)) visit(child);
2992
+ };
2993
+ for (const step of steps) visit(step);
2994
+ return ids;
2995
+ }
2996
+ /**
2997
+ * The cycle a save would close, as the ids along it (`[a, b, a]`), or `null`.
2998
+ * `rootId` is the Action being saved and `rootSteps` the steps it is saved with:
2999
+ * the stored copy of `rootId` is never read, only the new one.
3000
+ */
3001
+ async function findActionCycle(rootId, rootSteps, stepsOf) {
3002
+ const cleared = /* @__PURE__ */ new Set();
3003
+ const walk = async (id, steps, path) => {
3004
+ for (const called of actionIdsCalledBy(steps)) {
3005
+ if (called === rootId) return [
3006
+ ...path,
3007
+ id,
3008
+ called
3009
+ ];
3010
+ if (cleared.has(called) || path.includes(called)) continue;
3011
+ const next = await stepsOf(called);
3012
+ if (next === void 0) continue;
3013
+ const found = await walk(called, next, [...path, id]);
3014
+ if (found !== null) return found;
3015
+ cleared.add(called);
3016
+ }
3017
+ return null;
3018
+ };
3019
+ return walk(rootId, rootSteps, []);
3020
+ }
3021
+ var NO_RUN_CHAIN = { ids: [] };
3022
+ /** Why a run may not start under this chain, or `null` when it may. */
3023
+ function refuseRunUnder(chain, actionId) {
3024
+ if (chain.ids.includes(actionId)) return `action cycle: ${[...chain.ids, actionId].join(" -> ")}`;
3025
+ if (chain.ids.length >= 8) return `actions call actions more than 8 deep: ${[...chain.ids, actionId].join(" -> ")}`;
3026
+ return null;
3027
+ }
3028
+ /** The chain of a run of `actionId` started under `chain`. */
3029
+ function chainWith(chain, actionId) {
3030
+ return { ids: [...chain.ids, actionId] };
3031
+ }
3032
+ //#endregion
2426
3033
  //#region ../types/dist/esm/automation/prepare-units.mjs
2427
3034
  /**
2428
3035
  * The save boundary for numbers tied to a quantity (D972), as a pure function
@@ -2504,6 +3111,68 @@ function prepareRecipeUnits(recipe, resolver) {
2504
3111
  }
2505
3112
  }
2506
3113
  //#endregion
3114
+ //#region ../types/dist/esm/automation/export-entities.mjs
3115
+ function errorText$4(err) {
3116
+ return err instanceof Error ? err.message : String(err);
3117
+ }
3118
+ /** Send through one CamStack notification target on behalf of an exporter. */
3119
+ async function sendToExportedTarget(api, log, input) {
3120
+ const { exporter, targetId } = input;
3121
+ const tags = { targetId };
3122
+ try {
3123
+ const { targets, unreadable } = await listNotificationTargets(api);
3124
+ const target = targets.find((t) => t.id === targetId);
3125
+ if (target === void 0 && unreadable.length > 0) throw new Error(`notification targets unreadable from ${unreadable.map((u) => u.addonId).join(", ")}`);
3126
+ if (target === void 0) {
3127
+ log.warn(`${exporter}: exported notifier not used — target-gone`, {
3128
+ tags,
3129
+ meta: { reason: "target-gone" }
3130
+ });
3131
+ return {
3132
+ status: "refused",
3133
+ reason: "target-gone"
3134
+ };
3135
+ }
3136
+ if (!target.enabled) {
3137
+ log.warn(`${exporter}: exported notifier not used — target-disabled`, {
3138
+ tags,
3139
+ meta: { reason: "target-disabled" }
3140
+ });
3141
+ return {
3142
+ status: "refused",
3143
+ reason: "target-disabled"
3144
+ };
3145
+ }
3146
+ const result = await api.notificationOutput.send.mutate({
3147
+ targetId,
3148
+ addonId: target.addonId,
3149
+ notification: NotificationSchema.parse(input.notification)
3150
+ });
3151
+ if (!result.success) {
3152
+ const message = result.error ?? "send failed";
3153
+ log.warn(`${exporter}: exported notifier send failed`, {
3154
+ tags,
3155
+ meta: { message }
3156
+ });
3157
+ return {
3158
+ status: "failed",
3159
+ message
3160
+ };
3161
+ }
3162
+ return { status: "sent" };
3163
+ } catch (err) {
3164
+ const message = errorText$4(err);
3165
+ log.warn(`${exporter}: exported notifier send failed`, {
3166
+ tags,
3167
+ meta: { message }
3168
+ });
3169
+ return {
3170
+ status: "failed",
3171
+ message
3172
+ };
3173
+ }
3174
+ }
3175
+ //#endregion
2507
3176
  //#region ../types/dist/esm/remote/remote-builtin-components.mjs
2508
3177
  var btn = (idSuffix, row, col, init) => ({
2509
3178
  idSuffix,
@@ -10754,9 +11423,22 @@ var RunToken = class {
10754
11423
  this.wakers.add(wake);
10755
11424
  });
10756
11425
  }
11426
+ children = /* @__PURE__ */ new Set();
11427
+ /**
11428
+ * An Action this run started from an `action` step ends with it: stopping the parent, or its
11429
+ * time limit, stops the child. Returns the unlink to call once the child has ended.
11430
+ */
11431
+ link(child) {
11432
+ this.children.add(child);
11433
+ if (this.aborted) child.abort();
11434
+ return () => {
11435
+ this.children.delete(child);
11436
+ };
11437
+ }
10757
11438
  abort() {
10758
11439
  this.aborted = true;
10759
11440
  for (const wake of [...this.wakers]) wake();
11441
+ for (const child of [...this.children]) child.abort();
10760
11442
  }
10761
11443
  };
10762
11444
  function errorMessage$2(err) {
@@ -10778,6 +11460,7 @@ var ActionsService = class {
10778
11460
  targets;
10779
11461
  templates;
10780
11462
  conditions;
11463
+ effects;
10781
11464
  running = /* @__PURE__ */ new Map();
10782
11465
  /** Last run START per action — the throttle's memory. */
10783
11466
  lastStartedAt = /* @__PURE__ */ new Map();
@@ -10800,6 +11483,7 @@ var ActionsService = class {
10800
11483
  this.targets = new ActionTargetResolver(deps.directory, deps.logger);
10801
11484
  this.templates = deps.templates;
10802
11485
  this.conditions = deps.conditions;
11486
+ this.effects = deps.effects;
10803
11487
  }
10804
11488
  /** A device was added, removed, moved or re-bound: forget the cached domains. */
10805
11489
  invalidateTargets() {
@@ -10898,7 +11582,26 @@ var ActionsService = class {
10898
11582
  });
10899
11583
  throw new ActionError("template-scope", reason);
10900
11584
  }
10901
- async run(input) {
11585
+ run(input) {
11586
+ return this.runUnder(input, NO_RUN_CHAIN);
11587
+ }
11588
+ /**
11589
+ * One run, under the chain of Actions that started it (an `action` step runs
11590
+ * an Action from inside a run): an Action already in the chain, or a chain
11591
+ * past the depth bound, is refused — logged with the action id, never hung.
11592
+ */
11593
+ async runUnder(input, chain, parent) {
11594
+ const refusal = refuseRunUnder(chain, input.actionId);
11595
+ if (refusal !== null) {
11596
+ this.logger.warn(`action run refused — ${refusal}`, {
11597
+ ...input.deviceId === void 0 ? {} : { tags: { deviceId: input.deviceId } },
11598
+ meta: {
11599
+ actionId: input.actionId,
11600
+ chain: chain.ids
11601
+ }
11602
+ });
11603
+ throw new ActionError("cycle", refusal);
11604
+ }
10902
11605
  await this.authorize(input.caller, input.actionId, input.deviceId, "run");
10903
11606
  const entry = await this.find(input.actionId);
10904
11607
  if (entry === null) throw new ActionError("not-found", `no action "${input.actionId}"`);
@@ -10967,6 +11670,7 @@ var ActionsService = class {
10967
11670
  }
10968
11671
  this.lastStartedAt.set(entry.id, startedAt);
10969
11672
  const token = new RunToken();
11673
+ const unlink = parent === void 0 ? void 0 : parent.link(token);
10970
11674
  this.running.set(entry.id, {
10971
11675
  runId,
10972
11676
  token,
@@ -10980,7 +11684,8 @@ var ActionsService = class {
10980
11684
  lastRunAt: startedAt,
10981
11685
  lastError: null
10982
11686
  });
10983
- const done = this.execute(entry, resolved.values, runId, startedAt, trigger, token, readable);
11687
+ const done = this.execute(entry, resolved.values, runId, startedAt, trigger, token, readable, chainWith(chain, entry.id), input);
11688
+ if (unlink !== void 0) done.finally(unlink);
10984
11689
  if (input.wait === true) return done;
10985
11690
  return {
10986
11691
  runId,
@@ -11015,13 +11720,13 @@ var ActionsService = class {
11015
11720
  };
11016
11721
  }
11017
11722
  /** Never rejects: a run's failure is its outcome. */
11018
- async execute(entry, values, runId, startedAt, trigger, token, readable) {
11723
+ async execute(entry, values, runId, startedAt, trigger, token, readable, chain, started) {
11019
11724
  let outcome = "failed";
11020
11725
  let steps = [];
11021
11726
  let message;
11022
11727
  const deadline = this.armDeadline(entry.id, runId, token);
11023
11728
  try {
11024
- const running = runSteps(this.runnableFor(entry, values, token, runId, readable), {
11729
+ const running = runSteps(this.runnableFor(entry, values, token, runId, readable, chain, started), {
11025
11730
  pathPrefix: "steps",
11026
11731
  isAborted: () => token.aborted,
11027
11732
  abortReason: "the run was stopped",
@@ -11137,7 +11842,7 @@ var ActionsService = class {
11137
11842
  }
11138
11843
  };
11139
11844
  }
11140
- runnableFor(entry, values, token, runId, readable) {
11845
+ runnableFor(entry, values, token, runId, readable, chain, started) {
11141
11846
  if (entry.source === "internal") {
11142
11847
  const ruleFire = ruleFireOfClaim(readCurrentCommandOrigin());
11143
11848
  return buildActionSteps(entry.steps ?? [], values, {
@@ -11158,7 +11863,30 @@ var ActionsService = class {
11158
11863
  onMissingVar: (name) => this.logger.warn("action template referenced a variable that was never set", { meta: {
11159
11864
  actionId: entry.id,
11160
11865
  variable: name
11161
- } })
11866
+ } }),
11867
+ now: this.now,
11868
+ isAborted: () => token.aborted,
11869
+ info: (message, meta) => this.logger.info(message, { meta: {
11870
+ actionId: entry.id,
11871
+ runId,
11872
+ ...meta
11873
+ } }),
11874
+ runAction: async ({ actionId, variables }) => {
11875
+ const result = await this.runUnder({
11876
+ caller: started.caller,
11877
+ actionId,
11878
+ variables,
11879
+ wait: true,
11880
+ ...started.deviceId === void 0 ? {} : { deviceId: started.deviceId }
11881
+ }, chain, token);
11882
+ return {
11883
+ outcome: result.outcome,
11884
+ message: result.message
11885
+ };
11886
+ },
11887
+ ...this.effects?.fetch === void 0 ? {} : { fetch: this.effects.fetch },
11888
+ ...this.effects?.connect === void 0 ? {} : { connect: this.effects.connect },
11889
+ ...this.effects?.sendNotification === void 0 ? {} : { sendNotification: this.effects.sendNotification }
11162
11890
  });
11163
11891
  }
11164
11892
  return [{
@@ -11222,6 +11950,7 @@ var ActionsService = class {
11222
11950
  if (patch.steps !== void 0) this.requireWithinCeiling(patch.steps, patch.name ?? existing.name);
11223
11951
  if (patch.steps !== void 0) await this.requireOffered(patch.steps, patch.name ?? existing.name);
11224
11952
  const { steps, warnings } = this.normalizeSteps(patch.steps ?? existing.steps ?? [], patch.name ?? existing.name);
11953
+ await this.requireNoCycle(input.actionId, steps, patch.name ?? existing.name);
11225
11954
  const action = await this.store.update(input.actionId, {
11226
11955
  name: patch.name ?? existing.name,
11227
11956
  steps,
@@ -11276,6 +12005,18 @@ var ActionsService = class {
11276
12005
  throw err;
11277
12006
  }
11278
12007
  }
12008
+ /** An Action that would run itself, directly or through others, is refused at save and names the cycle. */
12009
+ async requireNoCycle(actionId, steps, actionName) {
12010
+ const cycle = await findActionCycle(actionId, steps, async (id) => isInternalActionId(id) ? (await this.store.get(id))?.steps : void 0);
12011
+ if (cycle === null) return;
12012
+ const message = `action cycle: ${cycle.join(" -> ")}`;
12013
+ this.logger.warn("action save refused — it would run itself", { meta: {
12014
+ action: actionName,
12015
+ actionId,
12016
+ cycle
12017
+ } });
12018
+ throw new ActionError("cycle", message);
12019
+ }
11279
12020
  /** An action whose waits alone exceed the run ceiling could never finish: refuse the save. */
11280
12021
  requireWithinCeiling(steps, actionName) {
11281
12022
  const total = actionWaitTotalMs(steps);
@@ -11557,6 +12298,23 @@ function withCanonicalStepTargets(data) {
11557
12298
  };
11558
12299
  }
11559
12300
  //#endregion
12301
+ //#region src/builtins/core-blocks/tcp-connect.ts
12302
+ /** Open a TCP connection and close it again: resolves when the port answered, rejects with the reason. */
12303
+ var tcpConnect = (host, port, timeoutMs) => new Promise((resolve, reject) => {
12304
+ const socket = net.connect({
12305
+ host,
12306
+ port
12307
+ });
12308
+ const done = (err) => {
12309
+ socket.destroy();
12310
+ if (err === void 0) resolve();
12311
+ else reject(err);
12312
+ };
12313
+ socket.setTimeout(timeoutMs, () => done(/* @__PURE__ */ new Error(`timed out after ${timeoutMs / 1e3} s`)));
12314
+ socket.once("connect", () => done());
12315
+ socket.once("error", (err) => done(err));
12316
+ });
12317
+ //#endregion
11560
12318
  //#region src/builtins/core-blocks/runs-api.ts
11561
12319
  /**
11562
12320
  * The three `core-blocks` methods that front the runs ledger.
@@ -11728,6 +12486,25 @@ function buildActionsRuntime(deps) {
11728
12486
  invokeCap: invokeCapOver(deps.api),
11729
12487
  templates: templateDoorOver(deps.api),
11730
12488
  conditions: conditionDoorOver(deps.api),
12489
+ effects: {
12490
+ fetch: globalThis.fetch,
12491
+ connect: tcpConnect,
12492
+ sendNotification: async ({ targetId, title, body }) => {
12493
+ const current = deps.api();
12494
+ if (current === void 0) return {
12495
+ status: "failed",
12496
+ message: "no ctx.api on this node — the notification cannot be sent"
12497
+ };
12498
+ return sendToExportedTarget(current, deps.logger.child("actions"), {
12499
+ exporter: "actions",
12500
+ targetId,
12501
+ notification: {
12502
+ body,
12503
+ ...title === void 0 ? {} : { title }
12504
+ }
12505
+ });
12506
+ }
12507
+ },
11731
12508
  emit: (event) => deps.eventBus.emit({
11732
12509
  id: randomUUID(),
11733
12510
  timestamp: /* @__PURE__ */ new Date(),