@camstack/types 1.2.549 → 1.2.551

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 (33) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/addon/addon-instance.d.ts +23 -0
  3. package/dist/addon/build-addon-route-provider.d.ts +2 -0
  4. package/dist/addon.js +1 -1
  5. package/dist/addon.mjs +1 -1
  6. package/dist/automation/fired-trigger.d.ts +44 -0
  7. package/dist/automation/index.d.ts +8 -5
  8. package/dist/automation/recipe.d.ts +12105 -604
  9. package/dist/automation/scheduler.d.ts +7 -0
  10. package/dist/automation/step-runner.d.ts +70 -0
  11. package/dist/automation/trace.d.ts +254 -145
  12. package/dist/automation/wait-until.d.ts +32 -0
  13. package/dist/automation/when-site.d.ts +1 -1
  14. package/dist/automation/when.d.ts +39 -1
  15. package/dist/capabilities/actions.cap.d.ts +1 -178
  16. package/dist/capabilities/addon-routes.cap.d.ts +3 -0
  17. package/dist/capabilities/core-blocks.cap.d.ts +117 -8723
  18. package/dist/capabilities/event-emitter.cap.d.ts +99 -3
  19. package/dist/capabilities/event-vocabulary.d.ts +99 -0
  20. package/dist/capabilities/index.d.ts +1 -0
  21. package/dist/capabilities/oauth-integration.cap.d.ts +8 -0
  22. package/dist/capabilities/schedulers.cap.d.ts +1 -178
  23. package/dist/capabilities/sso-bridge.cap.d.ts +3 -0
  24. package/dist/capabilities/user-management.cap.d.ts +4 -0
  25. package/dist/generated/addon-cap-facts.d.ts +1 -1
  26. package/dist/index.d.ts +4 -2
  27. package/dist/index.js +1488 -156
  28. package/dist/index.mjs +1442 -157
  29. package/dist/interfaces/addon-routes.d.ts +13 -0
  30. package/dist/interfaces/config-ui.d.ts +15 -24
  31. package/dist/{sleep-Bn346wCJ.mjs → sleep-D0roI_CZ.mjs} +4 -0
  32. package/dist/{sleep-LFKpQ2_f.js → sleep-dcR4vBFG.js} +4 -0
  33. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_sleep = require("./sleep-LFKpQ2_f.js");
2
+ const require_sleep = require("./sleep-dcR4vBFG.js");
3
3
  const require_event_category = require("./event-category-BC4RRerT.js");
4
4
  const require_composed_stable_id = require("./composed-stable-id-CDNLq7Y8.js");
5
5
  const require_implemented_methods = require("./implemented-methods-Cj65uy2F.js");
@@ -461,6 +461,7 @@ function buildAddonRouteProvider(id, routes) {
461
461
  query: input.query,
462
462
  body: input.body,
463
463
  headers: input.headers,
464
+ ...match.route.perInstance === true && input.instanceId !== void 0 ? { instanceId: input.instanceId } : {},
464
465
  ...input.user ? { user: input.user } : {},
465
466
  ...input.scopedToken !== void 0 ? { scopedToken: input.scopedToken } : {}
466
467
  };
@@ -529,6 +530,35 @@ function buildCapturingReply(envelope) {
529
530
  return wrapper;
530
531
  }
531
532
  //#endregion
533
+ //#region src/addon/addon-instance.ts
534
+ /**
535
+ * The integration instance of an addon, as it appears in an address or on an
536
+ * OAuth link (planning#415, D1046).
537
+ *
538
+ * The DEFAULT instance has two spellings on the wire and one in the code: a
539
+ * path with no instance segment and a link with no instance both mean it, and
540
+ * its id is the addon id. {@link oauthLinkServesInstance} is the one
541
+ * comparison a per-instance route is meant to call, so nobody compares
542
+ * `undefined` with an id. The Alexa export's routes are its first caller.
543
+ */
544
+ /** An instance id as it may appear in a path or a query: no separator, no escape, bounded. */
545
+ var ADDON_INSTANCE_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
546
+ function isAddonInstanceId(value) {
547
+ return ADDON_INSTANCE_ID_RE.test(value);
548
+ }
549
+ /** The instance a link was made for, with the default one spelled as the addon id. */
550
+ function oauthLinkInstanceId(link, addonId) {
551
+ return link.instanceId ?? addonId;
552
+ }
553
+ /**
554
+ * True when a verified link may be used on a request addressed to
555
+ * `requestInstanceId` (`AddonHttpRequest.instanceId`, absent on a route that
556
+ * is not per-instance, which is the default instance).
557
+ */
558
+ function oauthLinkServesInstance(link, requestInstanceId, addonId) {
559
+ return oauthLinkInstanceId(link, addonId) === (requestInstanceId ?? addonId);
560
+ }
561
+ //#endregion
532
562
  //#region src/addon/session-health.ts
533
563
  var SESSION_LOST_ALERT_CATEGORY = "integration.session-lost";
534
564
  var SESSION_EPISODE_KEY = "session-lost";
@@ -5710,12 +5740,12 @@ function toStreamSourceEntry(stream) {
5710
5740
  function isString(v) {
5711
5741
  return typeof v === "string";
5712
5742
  }
5713
- function isRecord$5(v) {
5743
+ function isRecord$6(v) {
5714
5744
  return typeof v === "object" && v !== null && !Array.isArray(v);
5715
5745
  }
5716
5746
  function parseStreamEntry(v) {
5717
5747
  if (isString(v) && v.trim()) return { url: v };
5718
- if (isRecord$5(v) && isString(v["url"]) && v["url"].trim()) return {
5748
+ if (isRecord$6(v) && isString(v["url"]) && v["url"].trim()) return {
5719
5749
  url: v["url"],
5720
5750
  label: isString(v["label"]) ? v["label"] : void 0
5721
5751
  };
@@ -6356,20 +6386,20 @@ var SURVIVING_TRIGGER_KEYS = [
6356
6386
  "objectClasses",
6357
6387
  "sensorDeviceIds"
6358
6388
  ];
6359
- function isRecord$4(value) {
6389
+ function isRecord$5(value) {
6360
6390
  return typeof value === "object" && value !== null && !Array.isArray(value);
6361
6391
  }
6362
6392
  function listensToLegacySignal(band) {
6363
- return isRecord$4(band) && isRecord$4(band.triggers) && band.triggers.deviceSignal === true;
6393
+ return isRecord$5(band) && isRecord$5(band.triggers) && band.triggers.deviceSignal === true;
6364
6394
  }
6365
6395
  function hasSurvivingTrigger(band) {
6366
6396
  const triggers = band.triggers;
6367
- if (!isRecord$4(triggers)) return false;
6397
+ if (!isRecord$5(triggers)) return false;
6368
6398
  return SURVIVING_TRIGGER_KEYS.some((key) => triggers[key] !== void 0);
6369
6399
  }
6370
6400
  function withoutLegacySignal(band) {
6371
6401
  const triggers = band.triggers;
6372
- if (!isRecord$4(triggers)) return band;
6402
+ if (!isRecord$5(triggers)) return band;
6373
6403
  const { deviceSignal: _retired, ...rest } = triggers;
6374
6404
  return {
6375
6405
  ...band,
@@ -6399,11 +6429,11 @@ function migrateLegacyDeviceSignalConfig(raw) {
6399
6429
  migrated: false,
6400
6430
  strippedOnly: false
6401
6431
  };
6402
- if (!isRecord$4(raw) || !Array.isArray(raw.bands)) return unchanged;
6432
+ if (!isRecord$5(raw) || !Array.isArray(raw.bands)) return unchanged;
6403
6433
  if (!raw.bands.some(listensToLegacySignal)) return unchanged;
6404
6434
  const kept = [];
6405
6435
  for (const band of raw.bands) {
6406
- if (!listensToLegacySignal(band) || !isRecord$4(band)) {
6436
+ if (!listensToLegacySignal(band) || !isRecord$5(band)) {
6407
6437
  kept.push(band);
6408
6438
  continue;
6409
6439
  }
@@ -32141,6 +32171,143 @@ function anySubjectMatches(subjects, observed) {
32141
32171
  };
32142
32172
  }
32143
32173
  //#endregion
32174
+ //#region src/capabilities/event-vocabulary.ts
32175
+ /**
32176
+ * The declared vocabulary of an `event-emitter` device (D1044): what the
32177
+ * device can fire, named for a person and typed for a rule.
32178
+ *
32179
+ * `id` is the native token, verbatim. `kind` is the meaning shared by every
32180
+ * integration, so "any long press" can be asked without knowing a vendor's
32181
+ * token. A device with several buttons declares one entry per button and
32182
+ * token: an entry is identified by its token AND its source.
32183
+ */
32184
+ /** The cross-integration meaning of an event. */
32185
+ var EVENT_VOCABULARY_KINDS = [
32186
+ "press",
32187
+ "long-press",
32188
+ "long-press-start",
32189
+ "release",
32190
+ "repeat",
32191
+ "double-press",
32192
+ "other"
32193
+ ];
32194
+ var EventVocabularyKindSchema = zod.z.enum(EVENT_VOCABULARY_KINDS);
32195
+ /** The part of the device an event comes from: a button, a channel. */
32196
+ var EventVocabularySourceSchema = zod.z.object({
32197
+ id: zod.z.string().min(1),
32198
+ label: zod.z.string().min(1)
32199
+ });
32200
+ /** One scalar field of an event's `data`, by dotted path. */
32201
+ var EventVocabularyFieldSchema = zod.z.object({
32202
+ path: zod.z.string().min(1),
32203
+ kind: zod.z.enum([
32204
+ "string",
32205
+ "number",
32206
+ "boolean",
32207
+ "enum"
32208
+ ]),
32209
+ enumValues: zod.z.array(zod.z.string()).optional(),
32210
+ label: zod.z.string().min(1).optional()
32211
+ });
32212
+ var EventVocabularyEntrySchema = zod.z.object({
32213
+ /** The native token, verbatim. */
32214
+ id: zod.z.string().min(1),
32215
+ source: EventVocabularySourceSchema.optional(),
32216
+ label: zod.z.string().min(1),
32217
+ description: zod.z.string().optional(),
32218
+ kind: EventVocabularyKindSchema.optional(),
32219
+ payload: zod.z.array(EventVocabularyFieldSchema).optional()
32220
+ });
32221
+ /**
32222
+ * The vocabulary of a source that declares tokens and nothing else: one
32223
+ * entry per token, labelled with the token itself.
32224
+ */
32225
+ function plainEventVocabulary(eventTypes) {
32226
+ return [...new Set(eventTypes)].filter((eventType) => eventType !== "").map((eventType) => ({
32227
+ id: eventType,
32228
+ label: eventType
32229
+ }));
32230
+ }
32231
+ /**
32232
+ * Tokens many integrations use for a button, by their normalised spelling
32233
+ * (lower case, words joined by `_`). Exact matches only: a token that
32234
+ * merely contains one of these words gets no kind.
32235
+ */
32236
+ var CONVENTIONAL_KINDS = {
32237
+ press: "press",
32238
+ pressed: "press",
32239
+ single: "press",
32240
+ single_press: "press",
32241
+ single_click: "press",
32242
+ short_press: "press",
32243
+ press_short: "press",
32244
+ click: "press",
32245
+ initial_press: "press",
32246
+ long_press: "long-press",
32247
+ press_long: "long-press",
32248
+ long_click: "long-press",
32249
+ hold: "long-press",
32250
+ long_press_start: "long-press-start",
32251
+ press_long_start: "long-press-start",
32252
+ release: "release",
32253
+ released: "release",
32254
+ long_release: "release",
32255
+ long_press_release: "release",
32256
+ press_long_release: "release",
32257
+ short_release: "release",
32258
+ repeat: "repeat",
32259
+ hold_repeat: "repeat",
32260
+ press_cont: "repeat",
32261
+ double_press: "double-press",
32262
+ double_click: "double-press",
32263
+ double: "double-press",
32264
+ multi_press_2: "double-press"
32265
+ };
32266
+ function normalisedToken(token) {
32267
+ return token.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
32268
+ }
32269
+ function readableToken(token) {
32270
+ const words = normalisedToken(token).replace(/_/g, " ");
32271
+ if (words === "") return token;
32272
+ return `${words.charAt(0).toUpperCase()}${words.slice(1)}`;
32273
+ }
32274
+ /**
32275
+ * The vocabulary of a source that declares tokens only, read by convention:
32276
+ * a readable label, and the shared kind when the token is one many
32277
+ * integrations use for a button. The token itself is kept verbatim.
32278
+ */
32279
+ function conventionalEventVocabulary(eventTypes) {
32280
+ return plainEventVocabulary(eventTypes).map((entry) => {
32281
+ const kind = CONVENTIONAL_KINDS[normalisedToken(entry.id)];
32282
+ const label = readableToken(entry.id);
32283
+ return kind === void 0 ? {
32284
+ id: entry.id,
32285
+ label
32286
+ } : {
32287
+ id: entry.id,
32288
+ label,
32289
+ kind
32290
+ };
32291
+ });
32292
+ }
32293
+ /** The native tokens of a vocabulary, each once, in declaration order. */
32294
+ function eventTypesOfVocabulary(vocabulary) {
32295
+ return [...new Set(vocabulary.map((entry) => entry.id))];
32296
+ }
32297
+ /**
32298
+ * The vocabulary to show and match against. A status with none declared
32299
+ * answers with its plain tokens, so an older provider is still usable.
32300
+ */
32301
+ function readEventVocabulary(status) {
32302
+ const declared = status.vocabulary;
32303
+ if (declared !== void 0 && declared.length > 0) return declared;
32304
+ return plainEventVocabulary(status.eventTypes);
32305
+ }
32306
+ /** The entry a fire belongs to: same token, same source (or both without one). */
32307
+ function findVocabularyEntry(vocabulary, eventType, sourceId) {
32308
+ return vocabulary.find((entry) => entry.id === eventType && entry.source?.id === sourceId);
32309
+ }
32310
+ //#endregion
32144
32311
  //#region src/time/solar.ts
32145
32312
  /**
32146
32313
  * Where the sun is, from a latitude and a longitude — the one solar
@@ -32891,6 +33058,33 @@ var ScheduleLeafSchema = zod.z.object({
32891
33058
  /** @deprecated legacy cron — new schedules use `at`. */
32892
33059
  cron: zod.z.string().min(1).max(120).optional()
32893
33060
  }).refine((leaf) => leaf.at === void 0 !== (leaf.cron === void 0), { message: "a schedule names exactly one of `at` (a time spec) and `cron` (legacy)" }).refine((leaf) => leaf.days === void 0 || leaf.at !== void 0, { message: "`days` goes with `at`; a cron expression carries its own days" });
33061
+ /**
33062
+ * One payload predicate of a `device-fired` row: the value at `path` inside
33063
+ * the fire's `data` (dotted) equals `equals`. Compared strictly, no coercion.
33064
+ */
33065
+ var DeviceFiredMatchSchema = zod.z.object({
33066
+ path: zod.z.string().min(1).max(120),
33067
+ equals: zod.z.union([
33068
+ zod.z.string(),
33069
+ zod.z.number(),
33070
+ zod.z.boolean()
33071
+ ])
33072
+ });
33073
+ /**
33074
+ * "fires": one device of the `event-emitter` capability reported an event
33075
+ * (D1045). Every list is an OR, the lists together an AND; an absent list does
33076
+ * not narrow. `eventIds` are the device's own tokens, `sourceIds` the parts of
33077
+ * the device (a button), `kinds` the shared press kinds of its vocabulary.
33078
+ */
33079
+ var DeviceFiredLeafSchema = zod.z.object({
33080
+ kind: zod.z.literal("device-fired"),
33081
+ ...eventLeafId,
33082
+ deviceId: zod.z.number().int().nonnegative(),
33083
+ eventIds: zod.z.array(zod.z.string().min(1)).min(1).max(64).optional(),
33084
+ sourceIds: zod.z.array(zod.z.string().min(1)).min(1).max(64).optional(),
33085
+ kinds: zod.z.array(EventVocabularyKindSchema).min(1).optional(),
33086
+ match: zod.z.array(DeviceFiredMatchSchema).min(1).max(8).optional()
33087
+ });
32894
33088
  var ManualLeafSchema = zod.z.object({
32895
33089
  kind: zod.z.literal("manual"),
32896
33090
  ...eventLeafId
@@ -33034,6 +33228,7 @@ var AutomationWhenSchema = zod.z.lazy(() => zod.z.discriminatedUnion("kind", [
33034
33228
  }),
33035
33229
  DeviceBecomesLeafSchema,
33036
33230
  DeviceEventLeafSchema,
33231
+ DeviceFiredLeafSchema,
33037
33232
  ScheduleLeafSchema,
33038
33233
  ManualLeafSchema,
33039
33234
  IntervalLeafSchema,
@@ -33048,6 +33243,7 @@ var AutomationWhenSchema = zod.z.lazy(() => zod.z.discriminatedUnion("kind", [
33048
33243
  var EVENT_KINDS = new Set([
33049
33244
  "device-becomes",
33050
33245
  "device-event",
33246
+ "device-fired",
33051
33247
  "schedule",
33052
33248
  "manual",
33053
33249
  "interval",
@@ -33146,6 +33342,7 @@ function hasEmptyContainer(node) {
33146
33342
  var LEAF_WORDS = {
33147
33343
  "device-becomes": "a device value that becomes",
33148
33344
  "device-event": "a device event",
33345
+ "device-fired": "a device firing an event",
33149
33346
  schedule: "a schedule",
33150
33347
  manual: "a manual run",
33151
33348
  interval: "an interval",
@@ -33415,9 +33612,12 @@ function convertLegacyWhen(half) {
33415
33612
  * every caller — automations, Actions, and the notification centre, which runs
33416
33613
  * only Actions (planning#473).
33417
33614
  */
33615
+ /** The longest one `wait` step lasts. It is cut by a restart of the run and does not survive a hub restart. */
33616
+ var WAIT_MAX_SECONDS = 3600;
33617
+ var WAIT_TOO_LONG = `a wait is at most one hour (${WAIT_MAX_SECONDS} s)`;
33418
33618
  var AutomationWaitStepSchema = zod.z.object({
33419
33619
  kind: zod.z.literal("wait"),
33420
- seconds: zod.z.number().min(0).max(300)
33620
+ seconds: zod.z.number().min(0).max(WAIT_MAX_SECONDS, WAIT_TOO_LONG)
33421
33621
  });
33422
33622
  /** The legacy `deviceId` of a cap step: still READ, never written (D983). */
33423
33623
  var LegacyStepDeviceSchema = zod.z.union([
@@ -33547,20 +33747,224 @@ var ActionStepSchema = zod.z.discriminatedUnion("kind", [GuardedWaitStepSchema,
33547
33747
  path: ["if"]
33548
33748
  });
33549
33749
  });
33750
+ /**
33751
+ * Flow control of an AUTOMATION's list (#500). A standalone list (an action, a
33752
+ * scheduler point, a preset) stays `wait` and `cap`: it has no run of its own
33753
+ * to end and no variable bag to write.
33754
+ */
33755
+ var continueOnErrorShape = {
33756
+ /** A failure of this step is traced `failed-continued` and the next step runs. */
33757
+ continueOnError: zod.z.literal(true).optional() };
33758
+ /** An automation's cap step: the shared guarded cap step, plus `continueOnError`. */
33759
+ var AutomationGuardedCapStepSchema = AutomationCapStepBaseSchema.extend({
33760
+ ...stepGuardShape,
33761
+ ...continueOnErrorShape
33762
+ }).refine((step) => step.target !== void 0 || step.deviceId !== void 0, {
33763
+ message: "a cap step needs a target",
33764
+ path: ["target"]
33765
+ }).refine((step) => step.target?.kind !== "domain" || step.actionId !== void 0, {
33766
+ message: "a domain target needs the vocabulary action it applies to (actionId)",
33767
+ path: ["actionId"]
33768
+ }).refine((step) => step.else === void 0 || step.if !== void 0, elseNeedsIf);
33769
+ var STOP_REASON_MAX = 200;
33770
+ /** End the run here, on purpose. `reason` may carry `{{vars.x}}` slots. */
33771
+ var AutomationStopStepSchema = zod.z.object({
33772
+ kind: zod.z.literal("stop"),
33773
+ reason: zod.z.string().min(1, "a stop needs a reason: it is what the run trace shows").max(200),
33774
+ /** `ok`: the run ends as a success. `failed`: it ends as a failure, with the reason. */
33775
+ outcome: zod.z.enum(["ok", "failed"]),
33776
+ /** Stop only when this reads true; false or unknown does not stop. */
33777
+ if: AutomationWhenSchema.optional()
33778
+ });
33779
+ var SET_VARS_MAX = 20;
33780
+ var SET_VAR_VALUE_MAX = 500;
33781
+ var SET_VAR_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,39}$/;
33782
+ /** Names the run itself writes and reads (`leaf` is what `triggered-by` judges): a step may not overwrite them. */
33783
+ var RESERVED_RUN_VARS = [
33784
+ "kind",
33785
+ "leaf",
33786
+ "at"
33787
+ ];
33788
+ /**
33789
+ * Write variables into the run's bag, for the steps after it. SUBSTITUTION
33790
+ * only, never evaluation: a text value may carry `{{vars.x}}` slots.
33791
+ */
33792
+ var AutomationSetStepSchema = zod.z.object({
33793
+ kind: zod.z.literal("set"),
33794
+ vars: zod.z.record(zod.z.string(), zod.z.union([
33795
+ zod.z.string().max(500),
33796
+ zod.z.number(),
33797
+ zod.z.boolean()
33798
+ ])).refine((vars) => Object.keys(vars).every((name) => SET_VAR_NAME_RE.test(name)), { message: "a variable name is letters, digits and _, not starting with a digit (max 40)" }).refine((vars) => Object.keys(vars).length >= 1, { message: "set needs at least one variable" }).refine((vars) => Object.keys(vars).length <= 20, { message: `set holds at most 20 variables` }).refine((vars) => Object.keys(vars).every((name) => !RESERVED_RUN_VARS.includes(name)), { message: `the names ${RESERVED_RUN_VARS.join(", ")} belong to the run and cannot be set` }),
33799
+ /** Set only when this reads true; false or unknown leaves the bag as it is. */
33800
+ if: AutomationWhenSchema.optional()
33801
+ });
33802
+ var AutomationRunActionStepSchema = zod.z.object({
33803
+ kind: zod.z.literal("action"),
33804
+ /** An entry of the `actions` surface (`internal:<uuid>` or `<addonId>:<localId>`). */
33805
+ actionId: zod.z.string().min(1),
33806
+ /** Values for the action's declared variables; the others take their default. */
33807
+ variables: zod.z.record(zod.z.string(), zod.z.union([
33808
+ zod.z.string(),
33809
+ zod.z.number(),
33810
+ zod.z.boolean()
33811
+ ])).optional(),
33812
+ ...continueOnErrorShape
33813
+ });
33814
+ /** How many branches one `choose` holds. */
33815
+ var CHOOSE_BRANCHES_MAX = 6;
33816
+ /**
33817
+ * A step INSIDE a branch of a `choose`: a flow step with no condition of its
33818
+ * own (the branch is the condition) and no block inside it. Strict, so an `if`
33819
+ * written on such a step is refused rather than dropped.
33820
+ */
33821
+ /** The longest a `wait-until` may wait: six hours. */
33822
+ var WAIT_UNTIL_TIMEOUT_MAX_S = 21600;
33823
+ /**
33824
+ * Pause the run until a condition is true (#500). The timeout is mandatory: a
33825
+ * run never waits without an end. `onTimeout` says what a wait that ran out
33826
+ * does: `continue` goes on to the next step, `stop` ends the run as a failure.
33827
+ * A condition that cannot be read is not "true": the wait goes on (D49).
33828
+ */
33829
+ var AutomationWaitUntilStepSchema = zod.z.object({
33830
+ kind: zod.z.literal("wait-until"),
33831
+ when: AutomationWhenSchema,
33832
+ timeoutS: zod.z.number().int().min(1, "a wait needs a timeout of at least one second").max(WAIT_UNTIL_TIMEOUT_MAX_S, `a wait for a condition is at most six hours (${WAIT_UNTIL_TIMEOUT_MAX_S} s)`),
33833
+ onTimeout: zod.z.enum(["continue", "stop"])
33834
+ }).strict();
33835
+ /** The step kinds that hold steps of their own, or pause on a condition: they nest two levels at most. */
33836
+ var BLOCK_STEP_KINDS = [
33837
+ "choose",
33838
+ "repeat",
33839
+ "parallel",
33840
+ "wait-until"
33841
+ ];
33842
+ var STEP_NEST_MAX = 2;
33843
+ var NEST_TOO_DEEP = `steps nest two levels at most: a step inside a nested choose or repeat can be a plain step only`;
33844
+ function kindOf(input) {
33845
+ return typeof input === "object" && input !== null ? Reflect.get(input, "kind") : void 0;
33846
+ }
33847
+ /** Where the nesting ends, a block step is refused in words rather than as an unknown kind. */
33848
+ function nestTooDeep(issue) {
33849
+ const kind = kindOf(issue.input);
33850
+ return typeof kind === "string" && BLOCK_STEP_KINDS.includes(kind) ? NEST_TOO_DEEP : void 0;
33851
+ }
33852
+ var plainStepSchemas = [
33853
+ AutomationWaitStepSchema.strict(),
33854
+ AutomationCapStepBaseSchema.extend(continueOnErrorShape).strict().refine((step) => step.target !== void 0 || step.deviceId !== void 0, {
33855
+ message: "a cap step needs a target",
33856
+ path: ["target"]
33857
+ }).refine((step) => step.target?.kind !== "domain" || step.actionId !== void 0, {
33858
+ message: "a domain target needs the vocabulary action it applies to (actionId)",
33859
+ path: ["actionId"]
33860
+ }),
33861
+ AutomationStopStepSchema.omit({ if: true }).strict(),
33862
+ AutomationSetStepSchema.omit({ if: true }).strict(),
33863
+ AutomationRunActionStepSchema.strict()
33864
+ ];
33865
+ /**
33866
+ * A plain step: a flow step with no condition of its own and no step inside
33867
+ * it. The second (last) level of nesting holds these only.
33868
+ */
33869
+ var AutomationBranchStepSchema = zod.z.discriminatedUnion("kind", plainStepSchemas, { error: nestTooDeep });
33870
+ var PARALLEL_STEPS_MIN = 2;
33871
+ var PARALLEL_STEPS_MAX = 5;
33872
+ /** A step that can run beside others: it writes no variable and does not end the run. */
33873
+ var AutomationParallelMemberSchema = AutomationBranchStepSchema.refine((step) => step.kind === "cap" || step.kind === "action" || step.kind === "wait", "a parallel holds device commands, actions and waits only: a set or a stop beside other steps has no order");
33874
+ /**
33875
+ * Several steps at once (#500): all are started together and all are awaited.
33876
+ * A failure fails the run once the others finished, as in a sequence; a member
33877
+ * marked "continue if this fails" does not.
33878
+ */
33879
+ var AutomationParallelStepSchema = zod.z.object({
33880
+ kind: zod.z.literal("parallel"),
33881
+ steps: zod.z.array(AutomationParallelMemberSchema).min(2, "a parallel needs at least two steps").max(5, `a parallel takes at most 5 steps`)
33882
+ }).strict();
33883
+ var REPEAT_COUNT_MAX = 20;
33884
+ var REPEAT_ITERATIONS_MAX = 50;
33885
+ var REPEAT_STEPS_MAX = 10;
33886
+ var REPEAT_DEVICES_MAX = 50;
33887
+ /** The run variable a loop over devices writes before each iteration: the device id. */
33888
+ var REPEAT_ITEM_VAR = "item";
33889
+ var REPEAT_NEEDS_MAX = "a repeat on a condition needs a maximum number of iterations";
33890
+ /** A loop on a condition: the bound is mandatory, so a run never loops without an end. */
33891
+ var repeatConditionShape = {
33892
+ when: AutomationWhenSchema,
33893
+ maxIterations: zod.z.number({ error: REPEAT_NEEDS_MAX }).int().min(1, REPEAT_NEEDS_MAX).max(50, `a repeat on a condition runs at most 50 times`),
33894
+ /** A pause between two iterations, never after the last. */
33895
+ waitS: zod.z.number().int().min(1).max(WAIT_MAX_SECONDS, WAIT_TOO_LONG).optional()
33896
+ };
33897
+ /** What decides how many times a `repeat` runs. */
33898
+ var AutomationRepeatLoopSchema = zod.z.discriminatedUnion("by", [
33899
+ zod.z.object({
33900
+ by: zod.z.literal("count"),
33901
+ count: zod.z.number().int().min(1).max(20, `a repeat runs at most 20 times`)
33902
+ }).strict(),
33903
+ zod.z.object({
33904
+ by: zod.z.literal("while"),
33905
+ ...repeatConditionShape
33906
+ }).strict(),
33907
+ zod.z.object({
33908
+ by: zod.z.literal("until"),
33909
+ ...repeatConditionShape
33910
+ }).strict(),
33911
+ zod.z.object({
33912
+ by: zod.z.literal("forEach"),
33913
+ target: zod.z.object({
33914
+ kind: zod.z.literal("devices"),
33915
+ ids: zod.z.array(zod.z.number().int()).min(1, "a repeat over devices needs at least one device").max(50, `a repeat over devices takes at most 50 devices`)
33916
+ }).strict()
33917
+ }).strict()
33918
+ ]);
33919
+ /**
33920
+ * The same steps several times (#500). Every form is bounded at save, so a
33921
+ * run cannot loop without an end. A failure or a `stop` in the steps ends the
33922
+ * loop and the run, as in a sequence.
33923
+ */
33924
+ function repeatSchemaOf(step) {
33925
+ return zod.z.object({
33926
+ kind: zod.z.literal("repeat"),
33927
+ loop: AutomationRepeatLoopSchema,
33928
+ steps: zod.z.array(step).min(1, "a repeat needs at least one step").max(10, `a repeat takes at most 10 steps`)
33929
+ }).strict();
33930
+ }
33931
+ /**
33932
+ * One step, several ways (#500): the branches are read in order and the FIRST
33933
+ * whose condition is true runs; `else` runs when every branch is false. A
33934
+ * branch that cannot be read ends the choice: nothing runs, not the branches
33935
+ * after it and not the else (D49). The #472 `if` / `else` of a wait or cap
33936
+ * step is the one-branch case and stays as it is stored.
33937
+ */
33938
+ function chooseSchemaOf(step) {
33939
+ const steps = zod.z.array(step).max(10);
33940
+ return zod.z.object({
33941
+ kind: zod.z.literal("choose"),
33942
+ branches: zod.z.array(zod.z.object({
33943
+ if: AutomationWhenSchema,
33944
+ steps: steps.min(1, "a branch needs at least one step")
33945
+ })).min(1, "a choose needs at least one branch").max(6, `a choose takes at most 6 branches`),
33946
+ else: steps.optional()
33947
+ });
33948
+ }
33949
+ var AutomationBodyStepSchema = zod.z.discriminatedUnion("kind", [
33950
+ ...plainStepSchemas,
33951
+ AutomationWaitUntilStepSchema,
33952
+ AutomationParallelStepSchema,
33953
+ chooseSchemaOf(AutomationBranchStepSchema),
33954
+ repeatSchemaOf(AutomationBranchStepSchema)
33955
+ ]);
33956
+ var AutomationRepeatStepSchema = repeatSchemaOf(AutomationBodyStepSchema);
33957
+ var AutomationChooseStepSchema = chooseSchemaOf(AutomationBodyStepSchema);
33550
33958
  var AutomationActionSchema = zod.z.discriminatedUnion("kind", [
33551
33959
  GuardedWaitStepSchema,
33552
- GuardedCapStepSchema,
33553
- zod.z.object({
33554
- kind: zod.z.literal("action"),
33555
- /** An entry of the `actions` surface (`internal:<uuid>` or `<addonId>:<localId>`). */
33556
- actionId: zod.z.string().min(1),
33557
- /** Values for the action's declared variables; the others take their default. */
33558
- variables: zod.z.record(zod.z.string(), zod.z.union([
33559
- zod.z.string(),
33560
- zod.z.number(),
33561
- zod.z.boolean()
33562
- ])).optional()
33563
- }),
33960
+ AutomationGuardedCapStepSchema,
33961
+ AutomationStopStepSchema,
33962
+ AutomationSetStepSchema,
33963
+ AutomationChooseStepSchema,
33964
+ AutomationWaitUntilStepSchema,
33965
+ AutomationParallelStepSchema,
33966
+ AutomationRepeatStepSchema,
33967
+ AutomationRunActionStepSchema,
33564
33968
  zod.z.object({
33565
33969
  kind: zod.z.literal("code"),
33566
33970
  /** Compiled into the automation's OWN block by esbuild — not a third
@@ -33626,12 +34030,47 @@ function convertLegacyRecipe(legacy) {
33626
34030
  ...rest
33627
34031
  };
33628
34032
  }
33629
- /**
33630
- * Where recipes are PARSED (the core-blocks cap, the MCP tool, the literal a
33631
- * saved block carries): the new shape as it is, or the old shape converted to
33632
- * it. The output type is always the new one.
33633
- */
33634
34033
  var AutomationRecipeSchema = zod.z.union([CurrentAutomationRecipeSchema, LegacyAutomationRecipeSchema.transform(convertLegacyRecipe)]);
34034
+ /** The `if` of a step that can carry one (`action`, `code`, `choose` and `wait-until` steps cannot). */
34035
+ function stepGuardOf(action) {
34036
+ switch (action.kind) {
34037
+ case "action":
34038
+ case "code":
34039
+ case "choose":
34040
+ case "wait-until":
34041
+ case "parallel":
34042
+ case "repeat": return;
34043
+ default: return action.if;
34044
+ }
34045
+ }
34046
+ /** Every condition of a step: its own `if`, or the `if` of each branch of a `choose`. */
34047
+ function stepConditionsOf(action) {
34048
+ const under = (prefix, steps) => steps.flatMap((step, at) => stepConditionsOf(step).map((ref) => ({
34049
+ ...ref,
34050
+ path: `${prefix}.${at}.${ref.path}`
34051
+ })));
34052
+ if (action.kind === "choose") return [...action.branches.flatMap((branch, i) => [{
34053
+ path: `branches.${i}.if`,
34054
+ when: branch.if
34055
+ }, ...under(`branches.${i}.steps`, branch.steps)]), ...under("else", action.else ?? [])];
34056
+ if (action.kind === "wait-until") return [{
34057
+ path: "when",
34058
+ when: action.when
34059
+ }];
34060
+ if (action.kind === "repeat") return [...action.loop.by === "while" || action.loop.by === "until" ? [{
34061
+ path: "loop.when",
34062
+ when: action.loop.when
34063
+ }] : [], ...under("steps", action.steps)];
34064
+ const when = stepGuardOf(action);
34065
+ return when === void 0 ? [] : [{
34066
+ path: "if",
34067
+ when
34068
+ }];
34069
+ }
34070
+ /** Every step a block step holds, at both levels, in the order they are written; none for a plain step. */
34071
+ function nestedStepsOf(action) {
34072
+ return (action.kind === "parallel" || action.kind === "repeat" ? action.steps : action.kind === "choose" ? [...action.branches.flatMap((branch) => branch.steps), ...action.else ?? []] : []).flatMap((step) => [step, ...nestedStepsOf(step)]);
34073
+ }
33635
34074
  /** Bounds, shared by `when` and the old names the guards still know. */
33636
34075
  var MAX_CONDITION_DEPTH = 4;
33637
34076
  var MAX_CONDITION_LEAVES = 32;
@@ -33647,9 +34086,8 @@ function validateRecipeBounds(recipe) {
33647
34086
  const ids = new Set(identifiedEventLeaves(recipe.when).map((entry) => entry.id));
33648
34087
  const inRules = triggeredByIssue(recipe.when, ids, "the rules");
33649
34088
  if (inRules !== null) return inRules;
33650
- for (const [index, action] of recipe.actions.entries()) {
33651
- if (action.kind !== "wait" && action.kind !== "cap" || action.if === void 0) continue;
33652
- const issue = triggeredByIssue(action.if, ids, `step ${index + 1}`);
34089
+ for (const [index, action] of recipe.actions.entries()) for (const condition of stepConditionsOf(action)) {
34090
+ const issue = triggeredByIssue(condition.when, ids, `step ${index + 1}`);
33653
34091
  if (issue !== null) return issue;
33654
34092
  }
33655
34093
  return null;
@@ -34373,6 +34811,16 @@ var BECOMES_DESCRIPTIONS = {
34373
34811
  from: "the value before the change, empty when it is not known",
34374
34812
  to: "the value it changed to"
34375
34813
  };
34814
+ /**
34815
+ * A fire's payload is offered too, as `data.<path>` (`{{vars.data.channel}}`):
34816
+ * those names depend on the device, so they are not in this list.
34817
+ */
34818
+ var FIRED_DESCRIPTIONS = {
34819
+ deviceId: "the device that fired",
34820
+ eventType: "the event, as the device names it",
34821
+ sourceId: "the part of the device that fired (a button), empty when it names none",
34822
+ eventKind: "the kind of press (press, long-press …), empty when the device declares none"
34823
+ };
34376
34824
  function describe$1(descriptions) {
34377
34825
  return Object.entries(descriptions).map(([name, description]) => ({
34378
34826
  name,
@@ -34381,6 +34829,10 @@ function describe$1(descriptions) {
34381
34829
  }
34382
34830
  var DETECTION_VARIABLES = describe$1(DETECTION_DESCRIPTIONS);
34383
34831
  var STATIONARY_VARIABLES = describe$1(STATIONARY_DESCRIPTIONS);
34832
+ var FIRED_VARIABLES = describe$1(FIRED_DESCRIPTIONS).map((v) => v.name === "deviceId" ? {
34833
+ ...v,
34834
+ hintKey: "firedDeviceId"
34835
+ } : v);
34384
34836
  var BECOMES_VARIABLES = describe$1(BECOMES_DESCRIPTIONS).map((v) => v.name === "deviceId" ? {
34385
34837
  ...v,
34386
34838
  hintKey: "becomesDeviceId"
@@ -34396,6 +34848,7 @@ function triggerLeafVariables(kind) {
34396
34848
  if (kind === "detection") return DETECTION_VARIABLES;
34397
34849
  if (kind === "stationary") return STATIONARY_VARIABLES;
34398
34850
  if (kind === "device-becomes") return BECOMES_VARIABLES;
34851
+ if (kind === "device-fired") return FIRED_VARIABLES;
34399
34852
  return [];
34400
34853
  }
34401
34854
  /**
@@ -34425,6 +34878,12 @@ function stepMetaOf(action) {
34425
34878
  case "wait": return { kind: "wait" };
34426
34879
  case "code": return { kind: "code" };
34427
34880
  case "action": return { kind: "action" };
34881
+ case "stop": return { kind: "stop" };
34882
+ case "wait-until": return { kind: "wait-until" };
34883
+ case "parallel": return { kind: "parallel" };
34884
+ case "repeat": return { kind: "repeat" };
34885
+ case "set": return { kind: "set" };
34886
+ case "choose": return { kind: "choose" };
34428
34887
  case "cap": {
34429
34888
  const { target, actionId } = normalizeCapStep(action);
34430
34889
  return {
@@ -34509,6 +34968,52 @@ function emitLeaf(trigger, path) {
34509
34968
  },
34510
34969
  ),
34511
34970
  )`;
34971
+ case "device-fired": return ` // event leaf ${path}: device fired — the bus event is the normal door; the
34972
+ // reconcile reads the device's event-emitter slice, so a fire whose event was
34973
+ // dropped is still seen while it is the LATEST one (D8, D1045). The first good
34974
+ // read only seeds: what fired before the start is not a trigger.
34975
+ {
34976
+ const watch = new DeviceFiredWatch(${j(trigger)})
34977
+ // The reconcile answers the same "nothing new" every tick: said once per reason.
34978
+ let lastQuiet = ''
34979
+ const land = (decision: ReturnType<DeviceFiredWatch['onEvent']>, door: 'event' | 'reconcile'): void => {
34980
+ if (decision.kind === 'ignore') {
34981
+ if (door === 'reconcile' && decision.why === lastQuiet) return
34982
+ if (door === 'reconcile') lastQuiet = decision.why
34983
+ ctx.logger.debug('device-fired trigger did not run — ' + decision.why, {
34984
+ tags: { deviceId: ${j(trigger.deviceId)} },
34985
+ leaf: ${at},
34986
+ door,
34987
+ })
34988
+ return
34989
+ }
34990
+ if (decision.kind === 'reject') {
34991
+ ctx.logger.debug('device-fired trigger rejected a fire', {
34992
+ tags: { deviceId: decision.vars.deviceId },
34993
+ reason: decision.reason,
34994
+ })
34995
+ }
34996
+ void run(
34997
+ { kind: 'device-fired', leaf: ${at}, at: Date.now(), ${varsPick("device-fired")}, ...decision.data },
34998
+ decision.reason,
34999
+ decision.kind === 'fire',
35000
+ )
35001
+ }
35002
+ disposers.push(
35003
+ ctx.eventBus.subscribe(
35004
+ { category: EventCategory.EventEmitted, deviceId: ${j(trigger.deviceId)} },
35005
+ (event) => land(watch.onEvent(event.data), 'event'),
35006
+ ),
35007
+ )
35008
+ const check = async (): Promise<void> => {
35009
+ const read = await readCapSlice(${j(trigger.deviceId)}, 'event-emitter')
35010
+ if (!read.ok) return // a failed read changes nothing: the next good one still seeds (D49)
35011
+ land(watch.onStatus(read.slice), 'reconcile')
35012
+ }
35013
+ void check()
35014
+ const reconcile = setInterval(() => { void check() }, RECONCILE_MS)
35015
+ disposers.push(() => clearInterval(reconcile))
35016
+ }`;
34512
35017
  case "device-becomes": {
34513
35018
  const hold = holdOf(trigger);
34514
35019
  return ` // event leaf ${path}: device state — the mirror is the authority, the
@@ -34645,42 +35150,15 @@ function emitLeaf(trigger, path) {
34645
35150
  }`;
34646
35151
  }
34647
35152
  }
34648
- /** The body of a wait or cap step, shared by a top-level step and an else step. */
34649
- function emitLeafBody(action) {
35153
+ /** What a plain step does when it runs: the body of its `run`, wherever the step sits. */
35154
+ function emitStepBody(action) {
34650
35155
  switch (action.kind) {
34651
35156
  case "wait": return ` await sleep(${j(action.seconds * 1e3)})`;
34652
35157
  case "cap": {
34653
35158
  const { target, actionId } = normalizeCapStep(action);
34654
35159
  return ` await actuateTarget(scope, ${j(target)}, ${j(actionId)}, ${j(action.cap)}, ${j(action.method)}, ${j(action.args ?? {})}, vars)`;
34655
35160
  }
34656
- default: return null;
34657
- }
34658
- }
34659
- /** A step's `if` (#472) and its else list, as the fields of a RunnableStep. */
34660
- function emitGuard(action, index) {
34661
- if (action.kind !== "wait" && action.kind !== "cap") return "";
34662
- if (action.if === void 0) return "";
34663
- const otherwise = (action.else ?? []).map((el) => {
34664
- const body = emitLeafBody(el);
34665
- return `{ meta: ${j(stepMetaOf(el))}, run: async (scope) => {\n${body ?? ""}\n } }`;
34666
- }).join(", ");
34667
- return ` guard: () => evaluateCondition(${j(action.if)}, ${j(`actions.${index}.if`)}, vars),${otherwise === "" ? "" : `\n otherwise: [${otherwise}],`}
34668
- `;
34669
- }
34670
- function emitAction(action, index) {
34671
- const step = (body) => ` {
34672
- meta: STEP_META[${index}]!,
34673
- ${emitGuard(action, index)} run: async (scope) => {
34674
- ${body}
34675
- },
34676
- },`;
34677
- switch (action.kind) {
34678
- case "wait": return step(` await sleep(${j(action.seconds * 1e3)})`);
34679
- case "cap": {
34680
- const { target, actionId } = normalizeCapStep(action);
34681
- return step(` await actuateTarget(scope, ${j(target)}, ${j(actionId)}, ${j(action.cap)}, ${j(action.method)}, ${j(action.args ?? {})}, vars)`);
34682
- }
34683
- case "action": return step(` // an Action run, awaited: the step takes THAT run's outcome
35161
+ case "action": return ` // an Action run, awaited: the step takes THAT run's outcome
34684
35162
  const result = await ctx.api.actions.run.mutate({
34685
35163
  actionId: ${j(action.actionId)},
34686
35164
  variables: substituteVariables(${j(action.variables ?? {})}, vars),
@@ -34689,13 +35167,153 @@ ${body}
34689
35167
  })
34690
35168
  if (result.outcome !== 'ran') {
34691
35169
  throw new Error('action ' + ${j(action.actionId)} + ' ' + result.outcome + (result.message === undefined ? '' : ': ' + result.message))
34692
- }`);
34693
- case "code": return step(` // inline code action — a fragment of THIS block, bundled by esbuild
35170
+ }`;
35171
+ case "stop": return ` // end the run here, on purpose: the steps after it are not-run with this reason
35172
+ scope.stop(String(substitute(${j(action.reason)}, vars)), ${j(action.outcome)})`;
35173
+ case "set": return ` // write the run's own bag, for the steps after this one — substitution only
35174
+ Object.assign(vars, substituteVariables(${j(action.vars)}, vars))`;
35175
+ case "code": return ` // inline code action — a fragment of THIS block, bundled by esbuild
34694
35176
  await (async () => {
34695
35177
  ${action.code.split("\n").map((line) => ` ${line}`).join("\n")}
34696
- })()`);
35178
+ })()`;
34697
35179
  }
34698
35180
  }
35181
+ function continues(action) {
35182
+ return (action.kind === "cap" || action.kind === "action") && action.continueOnError === true;
35183
+ }
35184
+ /** Whether the site is inside a block step: the automation's own steps sit at `actions.<n>`. */
35185
+ function isNestedSite(site) {
35186
+ return site.path.split(".").length > 2;
35187
+ }
35188
+ /** A list of steps under `path` (a branch, an else list, the steps of a repeat or a parallel). */
35189
+ function emitList(steps, path) {
35190
+ return steps.map((step, at) => emitStep(step, {
35191
+ meta: j(stepMetaOf(step)),
35192
+ path: `${path}.${at}`
35193
+ })).join("\n");
35194
+ }
35195
+ /** A step's `if` (#472) and its else list, as the fields of a RunnableStep. */
35196
+ function emitGuard(action, site) {
35197
+ const when = stepGuardOf(action);
35198
+ if (when === void 0) return "";
35199
+ const otherwise = emitList(action.kind === "wait" || action.kind === "cap" ? action.else ?? [] : [], `${site.path}.else`);
35200
+ return ` guard: () => evaluateCondition(${j(when)}, ${j(`${site.path}.if`)}, vars),${otherwise === "" ? "" : `\n otherwise: [\n${otherwise}\n],`}
35201
+ `;
35202
+ }
35203
+ /** A `choose` step: its branches, each a condition and a list, and its else list. */
35204
+ function emitChoose(action, site) {
35205
+ const branches = action.branches.map((branch, b) => ` {
35206
+ guard: () => evaluateCondition(${j(branch.if)}, ${j(`${site.path}.branches.${b}.if`)}, vars),
35207
+ steps: [
35208
+ ${emitList(branch.steps, `${site.path}.branches.${b}.steps`)}
35209
+ ],
35210
+ },`).join("\n");
35211
+ const otherwise = emitList(action.else ?? [], `${site.path}.else`);
35212
+ return ` {
35213
+ meta: ${site.meta},
35214
+ // a choose step: the runner reads the branches in order and runs the first that is true
35215
+ run: async () => {},
35216
+ choose: {
35217
+ branches: [
35218
+ ${branches}
35219
+ ],${otherwise === "" ? "" : `\n otherwise: [\n${otherwise}\n],`}
35220
+ },
35221
+ },`;
35222
+ }
35223
+ /** The devices whose report can change a tree's answer; null when one is named by a stable id (any report wakes it). */
35224
+ function wakeDevicesOf(when) {
35225
+ const ids = [];
35226
+ for (const source of collectWhenMirrorSources(when)) {
35227
+ if (source.kind !== "device") return null;
35228
+ if (!ids.includes(source.deviceId)) ids.push(source.deviceId);
35229
+ }
35230
+ return ids;
35231
+ }
35232
+ /** A `wait-until` step: read the condition, wait for a wake, read again, until the timeout. */
35233
+ function emitWaitUntil(action, site) {
35234
+ const onTimeout = action.onTimeout === "stop" ? `scope.stop(message, 'failed')` : "scope.markTimedOut(message)";
35235
+ return ` {
35236
+ meta: ${site.meta},
35237
+ run: async (scope) => {
35238
+ // woken by a report of one of its devices, by the reconcile tick, or by a restart
35239
+ const waited = await waitUntil({
35240
+ read: () => evaluateCondition(${j(action.when)}, ${j(`${site.path}.when`)}, vars),
35241
+ timeoutMs: ${j(action.timeoutS * 1e3)},
35242
+ now: () => Date.now(),
35243
+ isAborted: () => token.aborted,
35244
+ nextWake: (ms) => waitForWake(ms, token, ${j(wakeDevicesOf(action.when))}),
35245
+ })
35246
+ if (waited.result === 'timed-out') {
35247
+ const message = waitTimedOutMessage(${j(action.timeoutS)}, waited.lastReason)
35248
+ ctx.logger.info('wait-until timed out', { step: ${j(site.path)}, onTimeout: ${j(action.onTimeout)}, reason: waited.lastReason })
35249
+ ${onTimeout}
35250
+ }
35251
+ },
35252
+ },`;
35253
+ }
35254
+ /** How a `repeat` decides its iterations, as the fields of a RunnableRepeat. */
35255
+ function emitRepeatLoop(loop, site) {
35256
+ switch (loop.by) {
35257
+ case "count": return `limit: ${j(loop.count)}, limitIsTimeout: false,`;
35258
+ case "forEach": return `// once per device: the device id is in vars.${REPEAT_ITEM_VAR} for the steps of that iteration
35259
+ limit: ${j(loop.target.ids.length)}, limitIsTimeout: false,
35260
+ ...(() => {
35261
+ const ids = ${j(loop.target.ids)}
35262
+ let outer: unknown
35263
+ return {
35264
+ before: async (iteration) => {
35265
+ if (iteration === 0) outer = vars[${j(REPEAT_ITEM_VAR)}]
35266
+ if (iteration < ids.length) vars[${j(REPEAT_ITEM_VAR)}] = ids[iteration]
35267
+ else if (${j(isNestedSite(site))} && outer !== undefined) vars[${j(REPEAT_ITEM_VAR)}] = outer
35268
+ return { go: true }
35269
+ },
35270
+ }
35271
+ })(),`;
35272
+ case "while":
35273
+ case "until": {
35274
+ const read = `repeatCheck(${j(loop.by)}, await evaluateCondition(${j(loop.when)}, ${j(`${site.path}.loop.when`)}, vars))`;
35275
+ const pause = loop.waitS === void 0 ? "" : `\n between: () => sleep(${j(loop.waitS * 1e3)}),`;
35276
+ return `limit: ${j(loop.maxIterations)}, limitIsTimeout: true,
35277
+ ${loop.by === "while" ? "before" : "after"}: async () => ${read},${pause}`;
35278
+ }
35279
+ }
35280
+ }
35281
+ /** One step, wherever it sits: a block step emits its own steps one level down, under its path. */
35282
+ function emitStep(action, site) {
35283
+ if (action.kind === "repeat") return ` {
35284
+ meta: ${site.meta},
35285
+ // a repeat step: the runner runs these once per iteration, under the bound
35286
+ run: async () => {},
35287
+ repeat: {
35288
+ steps: [
35289
+ ${emitList(action.steps, `${site.path}.steps`)}
35290
+ ],
35291
+ ${emitRepeatLoop(action.loop, site)}
35292
+ },
35293
+ },`;
35294
+ if (action.kind === "choose") return emitChoose(action, site);
35295
+ if (action.kind === "wait-until") return emitWaitUntil(action, site);
35296
+ if (action.kind === "parallel") return ` {
35297
+ meta: ${site.meta},
35298
+ // a parallel step: the runner starts these together and awaits them all
35299
+ run: async () => {},
35300
+ parallel: [
35301
+ ${emitList(action.steps, `${site.path}.steps`)}
35302
+ ],
35303
+ },`;
35304
+ return ` {
35305
+ meta: ${site.meta},
35306
+ ${emitGuard(action, site)}${continues(action) ? " continueOnError: true,\n" : ""} run: async (scope) => {
35307
+ ${emitStepBody(action)}
35308
+ },
35309
+ },`;
35310
+ }
35311
+ function emitAction(action, index) {
35312
+ return emitStep(action, {
35313
+ meta: `STEP_META[${index}]!`,
35314
+ path: `actions.${index}`
35315
+ });
35316
+ }
34699
35317
  /**
34700
35318
  * Compile a recipe to the TypeScript of a core block.
34701
35319
  *
@@ -34709,12 +35327,18 @@ function generateAutomationBlock(input) {
34709
35327
  const { name, recipe } = input;
34710
35328
  const runMode = recipe.runMode ?? { mode: "single" };
34711
35329
  const stepMeta = recipe.actions.map(stepMetaOf);
34712
- const hasDomainTarget = recipe.actions.some((a) => a.kind === "cap" && normalizeCapStep(a).target.kind === "domain");
34713
- const guardHoldTrees = recipe.actions.flatMap((a, i) => (a.kind === "wait" || a.kind === "cap") && a.if !== void 0 && hasHoldLeaves(a.if) ? [{
34714
- path: `actions.${i}.if`,
34715
- when: a.if
34716
- }] : []);
34717
- const hasTime = hasTimeLeaves(recipe.when) || recipe.actions.some((a) => (a.kind === "wait" || a.kind === "cap") && a.if !== void 0 && hasTimeLeaves(a.if));
35330
+ const elseSteps = (a) => a.kind === "wait" || a.kind === "cap" ? a.else ?? [] : [];
35331
+ const hasDomainTarget = recipe.actions.flatMap((a) => [
35332
+ a,
35333
+ ...elseSteps(a),
35334
+ ...nestedStepsOf(a)
35335
+ ]).some((a) => a.kind === "cap" && normalizeCapStep(a).target.kind === "domain");
35336
+ const guardHoldTrees = recipe.actions.flatMap((a, i) => stepConditionsOf(a).flatMap(({ path, when }) => hasHoldLeaves(when) ? [{
35337
+ path: `actions.${i}.${path}`,
35338
+ when
35339
+ }] : []));
35340
+ const hasTime = hasTimeLeaves(recipe.when) || recipe.actions.some((a) => stepConditionsOf(a).some(({ when }) => hasTimeLeaves(when)));
35341
+ const hasWaitUntil = recipe.actions.some((a) => a.kind === "wait-until" || nestedStepsOf(a).some((n) => n.kind === "wait-until"));
34718
35342
  const eventLeaves = [];
34719
35343
  forEachLeaf(recipe.when, (leaf, path) => {
34720
35344
  if (isEventLeaf(leaf)) eventLeaves.push({
@@ -34743,6 +35367,7 @@ import {
34743
35367
  ConditionMirror,
34744
35368
  HoldTracker,
34745
35369
  DetectionTriggerFilter,
35370
+ DeviceFiredWatch,
34746
35371
  EventCategory,
34747
35372
  RunGate,
34748
35373
  buildTriggerTrace,
@@ -34763,6 +35388,9 @@ import {
34763
35388
  runForDevices,
34764
35389
  evaluateStepCondition,
34765
35390
  runSteps,
35391
+ repeatCheck,
35392
+ waitUntil,
35393
+ waitTimedOutMessage,
34766
35394
  siteFor,
34767
35395
  validateTimeSpecForSite,
34768
35396
  zoneOnlySite,
@@ -34890,7 +35518,8 @@ ${hasTime ? ` /** The site clock a \`time-is\` leaf reads: memory only at evalu
34890
35518
 
34891
35519
  interface RunToken {
34892
35520
  aborted: boolean
34893
- wake?: () => void
35521
+ /** What cuts short whatever the run is paused on; several at once inside a \`parallel\`. */
35522
+ readonly wakes: Set<() => void>
34894
35523
  }
34895
35524
  interface QueuedRun {
34896
35525
  readonly trigger: Record<string, unknown>
@@ -34901,11 +35530,29 @@ ${hasTime ? ` /** The site clock a \`time-is\` leaf reads: memory only at evalu
34901
35530
  /** Sleep that a restart can cut short. */
34902
35531
  const abortableSleep = (ms: number, token: RunToken): Promise<void> =>
34903
35532
  new Promise((resolve) => {
34904
- const timer = setTimeout(resolve, ms)
34905
- token.wake = () => {
35533
+ const done = (): void => {
35534
+ clearTimeout(timer)
35535
+ token.wakes.delete(done)
35536
+ resolve()
35537
+ }
35538
+ const timer = setTimeout(done, ms)
35539
+ token.wakes.add(done)
35540
+ })
35541
+
35542
+ /** The runs paused on a \`wait-until\`, each with the devices whose report wakes it (null = any). */
35543
+ const stateWaiters = new Map<() => void, readonly number[] | null>()
35544
+ /** Resolve at a report of one of \`deviceIds\`, at the reconcile tick, at a restart, or after \`ms\`. */
35545
+ const waitForWake = (ms: number, token: RunToken, deviceIds: readonly number[] | null): Promise<void> =>
35546
+ new Promise((resolve) => {
35547
+ const done = (): void => {
34906
35548
  clearTimeout(timer)
35549
+ stateWaiters.delete(done)
35550
+ token.wakes.delete(done)
34907
35551
  resolve()
34908
35552
  }
35553
+ const timer = setTimeout(done, Math.min(ms, RECONCILE_MS))
35554
+ stateWaiters.set(done, deviceIds)
35555
+ token.wakes.add(done)
34909
35556
  })
34910
35557
 
34911
35558
  // ── the hub's runs ledger: the stamp is read ONCE here, the ring is written through RPC ──
@@ -35063,24 +35710,15 @@ ${hasTime ? ` // a time-is leaf changes sides at a boundary with no device ev
35063
35710
  }
35064
35711
  }
35065
35712
 
35066
- /** Read one cap field off the state mirror. \`ok: false\` when the device,
35067
- * the cap or the field cannot be resolved — the caller decides what that
35068
- * means (the device-state trigger changes nothing), and it is logged at
35069
- * debug with the device. (Conditions read the ConditionMirror instead.) */
35070
- async function readField(
35713
+ /** One cap slice off the state mirror. \`ok: false\` when the read threw —
35714
+ * logged at debug with the device; the caller decides what that means. */
35715
+ async function readCapSlice(
35071
35716
  deviceId: number,
35072
35717
  cap: string,
35073
- fieldPath: string,
35074
- ): Promise<{ readonly ok: true; readonly value: unknown } | { readonly ok: false }> {
35718
+ ): Promise<{ readonly ok: true; readonly slice: unknown } | { readonly ok: false }> {
35075
35719
  try {
35076
35720
  const slice = await ctx.api.deviceState.getCapSlice.query({ deviceId, capName: cap })
35077
- let cursor: unknown = slice
35078
- for (const part of fieldPath.split('.')) {
35079
- if (cursor === null || typeof cursor !== 'object') return { ok: false }
35080
- cursor = Reflect.get(cursor, part)
35081
- }
35082
- if (cursor === undefined) return { ok: false }
35083
- return { ok: true, value: cursor }
35721
+ return { ok: true, slice }
35084
35722
  } catch (err: unknown) {
35085
35723
  ctx.logger.debug('device state read failed — the leaf keeps what it knew', {
35086
35724
  tags: { deviceId },
@@ -35091,6 +35729,26 @@ ${hasTime ? ` // a time-is leaf changes sides at a boundary with no device ev
35091
35729
  }
35092
35730
  }
35093
35731
 
35732
+ /** Read one cap field off the state mirror. \`ok: false\` when the device,
35733
+ * the cap or the field cannot be resolved — the caller decides what that
35734
+ * means (the device-state trigger changes nothing). (Conditions read the
35735
+ * ConditionMirror instead.) */
35736
+ async function readField(
35737
+ deviceId: number,
35738
+ cap: string,
35739
+ fieldPath: string,
35740
+ ): Promise<{ readonly ok: true; readonly value: unknown } | { readonly ok: false }> {
35741
+ const read = await readCapSlice(deviceId, cap)
35742
+ if (!read.ok) return { ok: false }
35743
+ let cursor: unknown = read.slice
35744
+ for (const part of fieldPath.split('.')) {
35745
+ if (cursor === null || typeof cursor !== 'object') return { ok: false }
35746
+ cursor = Reflect.get(cursor, part)
35747
+ }
35748
+ if (cursor === undefined) return { ok: false }
35749
+ return { ok: true, value: cursor }
35750
+ }
35751
+
35094
35752
  /** A trigger var keeps primitives only. */
35095
35753
  function toTraceScalar(value: unknown): string | number | boolean | null {
35096
35754
  return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? value : null
@@ -35233,6 +35891,13 @@ ${recipe.actions.map((a, i) => emitAction(a, i)).join("\n")}
35233
35891
  error: failure.message,
35234
35892
  })
35235
35893
  },
35894
+ onContinuedFailure: (failure) => {
35895
+ ctx.logger.warn('action failed — continuing, the step is marked to be passed over', {
35896
+ ...(failure.deviceId === undefined ? {} : { tags: { deviceId: failure.deviceId } }),
35897
+ step: failure.index,
35898
+ error: failure.message,
35899
+ })
35900
+ },
35236
35901
  onGuardUnknown: (skipped) => {
35237
35902
  ctx.logger.warn('step skipped — its condition could not be read', {
35238
35903
  ...(skipped.deviceId === undefined ? {} : { tags: { deviceId: skipped.deviceId } }),
@@ -35282,7 +35947,7 @@ ${recipe.actions.map((a, i) => emitAction(a, i)).join("\n")}
35282
35947
  reason: string,
35283
35948
  admission: AutomationRunVerdict,
35284
35949
  ): Promise<void> {
35285
- const token: RunToken = { aborted: false }
35950
+ const token: RunToken = { aborted: false, wakes: new Set() }
35286
35951
  runningTokens.add(token)
35287
35952
  const startedAt = Date.now()
35288
35953
  const runId = newRunId(startedAt)
@@ -35396,7 +36061,7 @@ ${recipe.actions.map((a, i) => emitAction(a, i)).join("\n")}
35396
36061
  ctx.logger.info('automation restarting — ' + admission.reason, deviceTags(trigger))
35397
36062
  for (const running of runningTokens) {
35398
36063
  running.aborted = true
35399
- running.wake?.()
36064
+ for (const wake of [...running.wakes]) wake()
35400
36065
  }
35401
36066
  break
35402
36067
  case 'run':
@@ -35455,6 +36120,16 @@ ${hasTime ? " await refreshSite()\n" : ""} await refreshMirror()
35455
36120
  disposers.push(() => clearInterval(mirrorReconcile))
35456
36121
  }
35457
36122
 
36123
+ ${hasWaitUntil ? ` // a paused run reads its condition again when one of its devices reports
36124
+ disposers.push(
36125
+ ctx.eventBus.subscribe({ category: EventCategory.DeviceStateChanged }, (event) => {
36126
+ const deviceId = event.data['deviceId']
36127
+ for (const [wake, deviceIds] of [...stateWaiters]) {
36128
+ if (deviceIds === null || (typeof deviceId === 'number' && deviceIds.includes(deviceId))) wake()
36129
+ }
36130
+ }),
36131
+ )
36132
+ ` : ""}
35458
36133
  ${eventLeaves.map(({ leaf, path }) => emitLeaf(leaf, path)).join("\n\n")}
35459
36134
 
35460
36135
  return () => {
@@ -35464,7 +36139,7 @@ ${eventLeaves.map(({ leaf, path }) => emitLeaf(leaf, path)).join("\n\n")}
35464
36139
  flushSkip()
35465
36140
  for (const running of runningTokens) {
35466
36141
  running.aborted = true
35467
- running.wake?.()
36142
+ for (const wake of [...running.wakes]) wake()
35468
36143
  }
35469
36144
  for (const dispose of disposers) dispose()
35470
36145
  }
@@ -35657,6 +36332,236 @@ function evaluateStationaryTrigger(trigger, event) {
35657
36332
  };
35658
36333
  }
35659
36334
  //#endregion
36335
+ //#region src/capabilities/event-emitter.cap.ts
36336
+ /**
36337
+ * Generic stateless event emitter. Installed on a `DeviceType.EventEmitter`
36338
+ * device. Carries the device's EXACT declared event vocabulary verbatim
36339
+ * (NO normalization). Two shapes:
36340
+ * - structured source (HA `event.*` entity) → `vocabulary` is the fixed
36341
+ * declared set (e.g. press_short, press_long, …).
36342
+ * - generic/legacy source (HA bus events, e.g. zha_event) → `vocabulary`
36343
+ * is [] (open) and `lastEvent.data` carries the complex payload.
36344
+ * `vocabulary` (D1044) names each event for a person and types it for a
36345
+ * rule; `eventTypes` is its list of native tokens, kept for older readers.
36346
+ * A fire names the part of the device it came from in `sourceId` when the
36347
+ * vocabulary declares sources (a remote's buttons).
36348
+ * `seq` is monotonic so two identical events still produce distinct slice writes.
36349
+ */
36350
+ var EventFireSchema = zod.z.object({
36351
+ deviceId: zod.z.number(),
36352
+ eventType: zod.z.string(),
36353
+ sourceId: zod.z.string().optional(),
36354
+ data: zod.z.record(zod.z.string(), zod.z.unknown()).nullable(),
36355
+ timestamp: zod.z.number().meta(require_sleep.readingMeta("none")),
36356
+ seq: zod.z.number().meta(require_sleep.readingMeta("count"))
36357
+ });
36358
+ var EventEmitterStatusSchema = zod.z.object({
36359
+ eventTypes: zod.z.array(zod.z.string()),
36360
+ /**
36361
+ * Required of a provider by the type. A status written before the field
36362
+ * existed still parses, as an empty vocabulary: read it through
36363
+ * `readEventVocabulary`, which then answers with the plain tokens.
36364
+ */
36365
+ vocabulary: zod.z.array(EventVocabularyEntrySchema).default([]),
36366
+ lastEvent: EventFireSchema.nullable(),
36367
+ eventCountSinceStart: zod.z.number().meta(require_sleep.readingMeta("count"))
36368
+ });
36369
+ var eventEmitterCapability = {
36370
+ name: "event-emitter",
36371
+ scope: "device",
36372
+ deviceNative: true,
36373
+ mode: "singleton",
36374
+ deviceTypes: [require_composed_stable_id.DeviceType.EventEmitter],
36375
+ methods: {},
36376
+ events: { onEvent: { data: EventFireSchema } },
36377
+ status: {
36378
+ schema: EventEmitterStatusSchema,
36379
+ kind: "push"
36380
+ },
36381
+ runtimeState: EventEmitterStatusSchema,
36382
+ /**
36383
+ * Runtime-state durability: **session** — `eventCountSinceStart` names its own scope.
36384
+ *
36385
+ * See `RuntimeStateDurability`. Enforced by
36386
+ * `scripts/check-runtime-state-durability.ts`.
36387
+ */
36388
+ durability: "session",
36389
+ /**
36390
+ * History (D850): none — `eventCountSinceStart` resets with the addon; events live in ledgers.
36391
+ */
36392
+ history: "none"
36393
+ };
36394
+ //#endregion
36395
+ //#region src/automation/fired-trigger.ts
36396
+ /**
36397
+ * The `device-fired` trigger: does this fire of an `event-emitter` device start
36398
+ * a run (D1045).
36399
+ *
36400
+ * Two doors lead here, and a fire passes exactly one of them:
36401
+ * - the bus event (`EventCategory.EventEmitted`, payload `EventFire`) — the
36402
+ * normal path;
36403
+ * - the reconcile read of the device's `event-emitter` slice — events are
36404
+ * telemetry (D8), so a fire whose event was dropped is still seen as
36405
+ * `lastEvent`, when it is the latest one. Only the LATEST is recoverable.
36406
+ *
36407
+ * The watch remembers the newest fire it has handled. "Newer" is the fire's
36408
+ * timestamp, then its `seq`: `seq` restarts at 1 with the provider, so it
36409
+ * orders two fires of one provider run and nothing else.
36410
+ *
36411
+ * The first reading of the slice only SEEDS (a restart is not a press), and a
36412
+ * read that failed changes nothing (D49): the next good one still seeds.
36413
+ */
36414
+ /** How deep a payload is walked, and how many variables one fire may add. */
36415
+ var MAX_DATA_DEPTH = 3;
36416
+ var MAX_DATA_VARS = 32;
36417
+ function isScalar(value) {
36418
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
36419
+ }
36420
+ function isRecord$4(value) {
36421
+ return value !== null && typeof value === "object" && !Array.isArray(value);
36422
+ }
36423
+ /** The scalars of a fire's payload as `data.<path>` variables; lists and nulls are left out. */
36424
+ function firedDataVars(data) {
36425
+ const out = {};
36426
+ const walk = (value, path, depth) => {
36427
+ if (Object.keys(out).length >= MAX_DATA_VARS) return;
36428
+ if (isScalar(value)) {
36429
+ out[path] = value;
36430
+ return;
36431
+ }
36432
+ if (!isRecord$4(value) || depth >= MAX_DATA_DEPTH) return;
36433
+ for (const [key, child] of Object.entries(value)) walk(child, `${path}.${key}`, depth + 1);
36434
+ };
36435
+ if (isRecord$4(data)) for (const [key, child] of Object.entries(data)) walk(child, `data.${key}`, 1);
36436
+ return out;
36437
+ }
36438
+ function readPath(data, path) {
36439
+ let cursor = data;
36440
+ for (const part of path.split(".")) {
36441
+ if (!isRecord$4(cursor)) return void 0;
36442
+ cursor = cursor[part];
36443
+ }
36444
+ return cursor;
36445
+ }
36446
+ function isNewer(fire, than) {
36447
+ if (than === null) return true;
36448
+ if (fire.timestamp !== than.timestamp) return fire.timestamp > than.timestamp;
36449
+ return fire.seq > than.seq;
36450
+ }
36451
+ /** Said in the trace when the reconcile, not the bus event, brought the fire. */
36452
+ var FIRED_RECOVERED_NOTE = "recovered by reconcile";
36453
+ var DeviceFiredWatch = class {
36454
+ leaf;
36455
+ /** The newest fire handled, by either door. */
36456
+ #last = null;
36457
+ /** A baseline exists: a slice was read, or a bus event arrived. */
36458
+ #seeded = false;
36459
+ /** The device's vocabulary as last read; `null` until a slice answered. */
36460
+ #vocabulary = null;
36461
+ constructor(leaf) {
36462
+ this.leaf = leaf;
36463
+ }
36464
+ /** A bus event (`event.data` of `EventCategory.EventEmitted`). */
36465
+ onEvent(data) {
36466
+ const parsed = EventFireSchema.safeParse(data);
36467
+ if (!parsed.success) return {
36468
+ kind: "ignore",
36469
+ why: "malformed event"
36470
+ };
36471
+ const fire = parsed.data;
36472
+ if (fire.deviceId !== this.leaf.deviceId) return {
36473
+ kind: "ignore",
36474
+ why: `device ${fire.deviceId} is not the trigger's device`
36475
+ };
36476
+ if (!isNewer(fire, this.#last)) return {
36477
+ kind: "ignore",
36478
+ why: "this fire was already handled"
36479
+ };
36480
+ this.#last = {
36481
+ timestamp: fire.timestamp,
36482
+ seq: fire.seq
36483
+ };
36484
+ this.#seeded = true;
36485
+ return this.#judge(fire, false);
36486
+ }
36487
+ /** A reading of the device's `event-emitter` slice (seed, then reconcile). */
36488
+ onStatus(status) {
36489
+ const parsed = EventEmitterStatusSchema.safeParse(status);
36490
+ if (!parsed.success) return {
36491
+ kind: "ignore",
36492
+ why: "the event-emitter status is unreadable"
36493
+ };
36494
+ this.#vocabulary = readEventVocabulary(parsed.data);
36495
+ const fire = parsed.data.lastEvent;
36496
+ const first = !this.#seeded;
36497
+ this.#seeded = true;
36498
+ if (fire === null) return {
36499
+ kind: "ignore",
36500
+ why: "the device has not fired"
36501
+ };
36502
+ if (!isNewer(fire, this.#last)) return {
36503
+ kind: "ignore",
36504
+ why: "this fire was already handled"
36505
+ };
36506
+ this.#last = {
36507
+ timestamp: fire.timestamp,
36508
+ seq: fire.seq
36509
+ };
36510
+ if (first) return {
36511
+ kind: "ignore",
36512
+ why: "seeded: what fired before the start is not a trigger"
36513
+ };
36514
+ if (fire.deviceId !== this.leaf.deviceId) return {
36515
+ kind: "ignore",
36516
+ why: `device ${fire.deviceId} is not the trigger's device`
36517
+ };
36518
+ return this.#judge(fire, true);
36519
+ }
36520
+ #kindOf(fire) {
36521
+ const vocabulary = this.#vocabulary ?? conventionalEventVocabulary([fire.eventType]);
36522
+ return (findVocabularyEntry(vocabulary, fire.eventType, fire.sourceId) ?? findVocabularyEntry(vocabulary, fire.eventType))?.kind;
36523
+ }
36524
+ #judge(fire, recovered) {
36525
+ const { eventIds, sourceIds, kinds, match } = this.leaf;
36526
+ if (eventIds !== void 0 && !eventIds.includes(fire.eventType)) return {
36527
+ kind: "ignore",
36528
+ why: `event ${fire.eventType} is not one of [${eventIds.join(", ")}]`
36529
+ };
36530
+ if (sourceIds !== void 0 && (fire.sourceId === void 0 || !sourceIds.includes(fire.sourceId))) return {
36531
+ kind: "ignore",
36532
+ why: `source ${fire.sourceId ?? "(none)"} is not one of [${sourceIds.join(", ")}]`
36533
+ };
36534
+ const kind = this.#kindOf(fire);
36535
+ if (kinds !== void 0 && (kind === void 0 || !kinds.includes(kind))) return {
36536
+ kind: "ignore",
36537
+ why: `kind ${kind ?? "(none)"} is not one of [${kinds.join(", ")}]`
36538
+ };
36539
+ const vars = {
36540
+ deviceId: fire.deviceId,
36541
+ eventType: fire.eventType,
36542
+ sourceId: fire.sourceId ?? "",
36543
+ eventKind: kind ?? ""
36544
+ };
36545
+ const data = firedDataVars(fire.data);
36546
+ for (const predicate of match ?? []) {
36547
+ const found = readPath(fire.data, predicate.path);
36548
+ if (found !== predicate.equals) return {
36549
+ kind: "reject",
36550
+ reason: `data.${predicate.path} is ${JSON.stringify(found) ?? "not set"}, the trigger wants ${JSON.stringify(predicate.equals)}`,
36551
+ vars,
36552
+ data
36553
+ };
36554
+ }
36555
+ const what = `${fire.eventType}${fire.sourceId === void 0 ? "" : ` from ${fire.sourceId}`}`;
36556
+ return {
36557
+ kind: "fire",
36558
+ reason: recovered ? `${what} — ${FIRED_RECOVERED_NOTE}` : what,
36559
+ vars,
36560
+ data
36561
+ };
36562
+ }
36563
+ };
36564
+ //#endregion
35660
36565
  //#region src/automation/run-gate.ts
35661
36566
  var MINUTE_MS$2 = 6e4;
35662
36567
  function minutes(ms) {
@@ -35809,7 +36714,7 @@ function stepGuardSiteIssues(steps, reading, rootPath) {
35809
36714
  }
35810
36715
  /** The whole recipe: its `when` tree and every step guard. */
35811
36716
  function recipeSiteIssues(recipe, reading) {
35812
- return [...whenSiteIssues(recipe.when, reading), ...stepGuardSiteIssues(recipe.actions, reading, "actions")];
36717
+ return [...whenSiteIssues(recipe.when, reading), ...recipe.actions.flatMap((action, i) => stepConditionsOf(action).flatMap((condition) => whenSiteIssues(condition.when, reading, `actions.${i}.${condition.path}`)))];
35813
36718
  }
35814
36719
  //#endregion
35815
36720
  //#region src/automation/scheduler.ts
@@ -35868,12 +36773,23 @@ var DEFAULT_MAX_HOLD_ATTEMPTS = 3;
35868
36773
  var MAX_HOLD_ATTEMPTS_LIMIT = 20;
35869
36774
  /** A missed edge up to this late still runs. */
35870
36775
  var DEFAULT_MAX_LATE_MS = 10 * 6e4;
36776
+ /**
36777
+ * The longest one `wait` of a scheduler point lasts. A point's steps run in
36778
+ * the scheduler's one serial queue, with no run ceiling: a wait holds every
36779
+ * other scheduler's points for as long as it lasts. An action (one hour) has
36780
+ * its own run and ceiling; a point keeps the five minutes it always had.
36781
+ */
36782
+ var SCHEDULER_WAIT_MAX_SECONDS = 300;
36783
+ var SchedulerStepSchema = ActionStepSchema.refine((step) => step.kind !== "wait" || step.seconds <= 300, {
36784
+ message: `a scheduler point waits at most five minutes (300 s); put a longer wait in an action`,
36785
+ path: ["seconds"]
36786
+ });
35871
36787
  var SchedulerPointSchema = zod.z.object({
35872
36788
  id: zod.z.string().min(1).max(64),
35873
36789
  at: SchedulerTimeSpecSchema,
35874
36790
  mode: SchedulerPointModeSchema,
35875
36791
  /** The actions of an `edge` or `hold`; a `release` has none. */
35876
- steps: zod.z.array(ActionStepSchema).max(20).default([]),
36792
+ steps: zod.z.array(SchedulerStepSchema).max(20).default([]),
35877
36793
  /** Checked when the point runs (an edge) or is applied (a hold). */
35878
36794
  conditions: SchedulerStateTreeSchema.optional(),
35879
36795
  /** Hold only; absent means `respect`. */
@@ -36177,6 +37093,7 @@ var AutomationConditionTraceNodeSchema = zod.z.object({
36177
37093
  "triggered-by",
36178
37094
  "device-becomes",
36179
37095
  "device-event",
37096
+ "device-fired",
36180
37097
  "schedule",
36181
37098
  "interval",
36182
37099
  "manual",
@@ -36250,18 +37167,46 @@ var StepTraceBaseSchema = zod.z.object({
36250
37167
  ]).optional(),
36251
37168
  /** Why the condition read what it read, in the evaluator's own words. */
36252
37169
  conditionReason: zod.z.string().optional(),
36253
- /** `empty`: the target resolved to no device, so nothing was done — never silently `ok`. `skipped`: its `if` was false (or unknown) and nothing ran in its place. */
37170
+ /** `empty`: the target resolved to no device, so nothing was done — never silently `ok`. `skipped`: its `if` was false (or unknown) and nothing ran in its place. `failed-continued`: it failed and was marked to be passed over (#500). */
36254
37171
  outcome: zod.z.enum([
36255
37172
  "ok",
36256
37173
  "error",
36257
37174
  "not-run",
36258
37175
  "empty",
36259
- "skipped"
37176
+ "skipped",
37177
+ "failed-continued",
37178
+ "timed-out"
36260
37179
  ]),
36261
37180
  message: zod.z.string().optional()
36262
37181
  });
37182
+ /** What a block step adds to its row: which list ran, what each branch read, how many rounds. */
37183
+ var blockTraceShape = {
37184
+ /** A `choose` step (#500): the list that ran, `branches.<n>` or `else`. Absent when none did. */
37185
+ branch: zod.z.string().optional(),
37186
+ /** A `choose` step: what each branch read, in order, up to the one that decided. */
37187
+ branchChecks: zod.z.array(zod.z.object({
37188
+ condition: zod.z.enum([
37189
+ "true",
37190
+ "false",
37191
+ "unknown"
37192
+ ]),
37193
+ conditionReason: zod.z.string().optional()
37194
+ })).optional(),
37195
+ /** A `repeat` step (#500): how many times its steps ran. */
37196
+ iterations: zod.z.number().int().optional()
37197
+ };
37198
+ /** A step one level down: it may be a block step itself, whose own steps are plain rows (the nesting ends there). */
37199
+ var NestedStepTraceSchema = StepTraceBaseSchema.extend({
37200
+ ...blockTraceShape,
37201
+ steps: zod.z.array(StepTraceBaseSchema).optional()
37202
+ });
36263
37203
  /** A step trace; the `else` steps that ran are one level of the same shape (the nesting is bounded at one). */
36264
- var AutomationStepTraceSchema = StepTraceBaseSchema.extend({ else: zod.z.array(StepTraceBaseSchema).optional() });
37204
+ var AutomationStepTraceSchema = StepTraceBaseSchema.extend({
37205
+ else: zod.z.array(StepTraceBaseSchema).optional(),
37206
+ ...blockTraceShape,
37207
+ /** A `choose` step: the steps of the list that ran. A `parallel`: its members. A `repeat`: the LAST iteration. */
37208
+ steps: zod.z.array(NestedStepTraceSchema).optional()
37209
+ });
36265
37210
  var AutomationRunTraceSchema = zod.z.object({
36266
37211
  runId: zod.z.string().min(1),
36267
37212
  startedAt: zod.z.number(),
@@ -36664,6 +37609,46 @@ async function evaluateStepCondition(when, fetchers, now = Date.now, history, si
36664
37609
  }
36665
37610
  //#endregion
36666
37611
  //#region src/automation/step-runner.ts
37612
+ /**
37613
+ * Read the branches in order and stop at the first that decides: `true` runs
37614
+ * it, `unknown` ends the choice with nothing run (D49). All `false` runs the
37615
+ * else list, when there is one.
37616
+ */
37617
+ async function readChoose(choose) {
37618
+ const checks = [];
37619
+ for (const [index, branch] of choose.branches.entries()) {
37620
+ const verdict = await readGuard(branch.guard);
37621
+ checks.push({
37622
+ condition: verdict.result,
37623
+ conditionReason: verdict.reason
37624
+ });
37625
+ if (verdict.result === "true") return {
37626
+ checks,
37627
+ decision: {
37628
+ kind: "run",
37629
+ branch: `branches.${index}`,
37630
+ steps: branch.steps
37631
+ }
37632
+ };
37633
+ if (verdict.result === "unknown") return {
37634
+ checks,
37635
+ decision: {
37636
+ kind: "unknown",
37637
+ index,
37638
+ reason: verdict.reason
37639
+ }
37640
+ };
37641
+ }
37642
+ const otherwise = choose.otherwise ?? [];
37643
+ return {
37644
+ checks,
37645
+ decision: otherwise.length === 0 ? { kind: "none" } : {
37646
+ kind: "run",
37647
+ branch: "else",
37648
+ steps: otherwise
37649
+ }
37650
+ };
37651
+ }
36667
37652
  function errorMessage(err) {
36668
37653
  return err instanceof Error ? err.message : String(err);
36669
37654
  }
@@ -36678,17 +37663,125 @@ async function readGuard(guard) {
36678
37663
  };
36679
37664
  }
36680
37665
  }
37666
+ /**
37667
+ * What a loop's condition says about going on. A `while` goes on while it
37668
+ * reads true, an `until` goes on while it reads false; `unknown` ends either,
37669
+ * with the reason (D49): a loop never runs on a value it could not read.
37670
+ */
37671
+ function repeatCheck(by, verdict) {
37672
+ if (verdict.result === "unknown") return {
37673
+ go: false,
37674
+ reason: `the condition could not be read: ${verdict.reason}`,
37675
+ unknown: true
37676
+ };
37677
+ if (by === "while") return verdict.result === "true" ? { go: true } : {
37678
+ go: false,
37679
+ reason: "the condition is no longer true"
37680
+ };
37681
+ return verdict.result === "true" ? {
37682
+ go: false,
37683
+ reason: "the condition is true"
37684
+ } : { go: true };
37685
+ }
37686
+ /** A loop condition that throws ends the loop as unreadable, never a crash of the run. */
37687
+ async function readRepeatCheck(check, iteration) {
37688
+ if (check === void 0) return { go: true };
37689
+ try {
37690
+ return await check(iteration);
37691
+ } catch (err) {
37692
+ return {
37693
+ go: false,
37694
+ reason: `the condition could not be read: ${errorMessage(err)}`,
37695
+ unknown: true
37696
+ };
37697
+ }
37698
+ }
37699
+ /** Run a loop's steps until its count, its condition, its bound, a failure, a stop or an abort ends it. */
37700
+ async function runRepeat(repeat, options, path) {
37701
+ let iterations = 0;
37702
+ let last;
37703
+ for (;;) {
37704
+ if (options.isAborted()) return {
37705
+ iterations,
37706
+ last,
37707
+ timedOut: false
37708
+ };
37709
+ const before = await readRepeatCheck(repeat.before, iterations);
37710
+ if (!before.go) return {
37711
+ iterations,
37712
+ last,
37713
+ ended: before.reason,
37714
+ timedOut: false,
37715
+ ...before.unknown === true ? { unknown: before.reason } : {}
37716
+ };
37717
+ if (iterations >= repeat.limit) return repeat.limitIsTimeout ? {
37718
+ iterations,
37719
+ last,
37720
+ ended: `stopped at ${repeat.limit} iterations`,
37721
+ timedOut: true
37722
+ } : {
37723
+ iterations,
37724
+ last,
37725
+ ended: "",
37726
+ timedOut: false
37727
+ };
37728
+ last = await runSteps(repeat.steps, {
37729
+ ...options,
37730
+ pathPrefix: `${path}.steps`,
37731
+ indexOffset: 0
37732
+ });
37733
+ iterations += 1;
37734
+ if (last.failed || last.aborted || last.stopped !== void 0) return {
37735
+ iterations,
37736
+ last,
37737
+ timedOut: false
37738
+ };
37739
+ const after = await readRepeatCheck(repeat.after, iterations - 1);
37740
+ if (!after.go) return {
37741
+ iterations,
37742
+ last,
37743
+ ended: after.reason,
37744
+ timedOut: false,
37745
+ ...after.unknown === true ? { unknown: after.reason } : {}
37746
+ };
37747
+ if (repeat.between !== void 0 && iterations < repeat.limit) await repeat.between();
37748
+ }
37749
+ }
36681
37750
  /** The else level of a trace is one level deep: a nested trace carries no `else` of its own. */
36682
37751
  function withoutElse(trace) {
36683
37752
  const { else: _else, ...rest } = trace;
36684
37753
  return rest;
36685
37754
  }
37755
+ /** A plain row: the last level of a trace carries no list of its own. */
37756
+ function plainRow(trace) {
37757
+ const { else: _else, steps: _steps, ...rest } = trace;
37758
+ return rest;
37759
+ }
37760
+ /** A row one level down: it keeps its own steps as plain rows, and no `else`. */
37761
+ function withoutNested(trace) {
37762
+ const { else: _else, steps, ...rest } = trace;
37763
+ return steps === void 0 ? rest : {
37764
+ ...rest,
37765
+ steps: steps.map(plainRow)
37766
+ };
37767
+ }
36686
37768
  async function runSteps(steps, options) {
36687
37769
  const traces = [];
36688
37770
  let failed = false;
36689
37771
  let aborted = false;
36690
- for (const [index, step] of steps.entries()) {
37772
+ let stopped;
37773
+ for (const [position, step] of steps.entries()) {
37774
+ const index = position + (options.indexOffset ?? 0);
36691
37775
  const path = `${options.pathPrefix}.${index}`;
37776
+ if (stopped !== void 0) {
37777
+ traces.push({
37778
+ ...step.meta,
37779
+ path,
37780
+ outcome: "not-run",
37781
+ message: `stopped at ${stopped.path}: ${stopped.reason}`
37782
+ });
37783
+ continue;
37784
+ }
36692
37785
  if (failed || aborted || options.isAborted()) {
36693
37786
  if (!failed) aborted = true;
36694
37787
  traces.push({
@@ -36700,6 +37793,96 @@ async function runSteps(steps, options) {
36700
37793
  continue;
36701
37794
  }
36702
37795
  const startedAt = options.now();
37796
+ if (step.parallel !== void 0) {
37797
+ const members = await Promise.all(step.parallel.map((member, at) => runSteps([member], {
37798
+ ...options,
37799
+ pathPrefix: `${path}.steps`,
37800
+ indexOffset: at
37801
+ })));
37802
+ const anyFailed = members.some((m) => m.failed);
37803
+ if (anyFailed) failed = true;
37804
+ else if (members.some((m) => m.aborted)) aborted = true;
37805
+ traces.push({
37806
+ ...step.meta,
37807
+ path,
37808
+ startedAt,
37809
+ endedAt: options.now(),
37810
+ outcome: anyFailed ? "error" : "ok",
37811
+ ...anyFailed ? { message: "a parallel step failed" } : {},
37812
+ steps: members.flatMap((m) => m.steps.map(withoutNested))
37813
+ });
37814
+ continue;
37815
+ }
37816
+ if (step.repeat !== void 0) {
37817
+ const loop = await runRepeat(step.repeat, options, path);
37818
+ const sub = loop.last;
37819
+ if (loop.unknown !== void 0) options.onGuardUnknown?.({
37820
+ index,
37821
+ path: `${path}.loop.when`,
37822
+ reason: loop.unknown,
37823
+ deviceId: step.meta.deviceId
37824
+ });
37825
+ const bodyFailed = loop.ended === void 0 && sub?.failed === true;
37826
+ if (bodyFailed) failed = true;
37827
+ else if (loop.ended === void 0 && sub?.stopped !== void 0) stopped = sub.stopped;
37828
+ else if (loop.ended === void 0) aborted = true;
37829
+ const times = `ran ${loop.iterations} times`;
37830
+ const message = bodyFailed ? `a step failed in iteration ${loop.iterations}` : loop.ended === void 0 ? times : loop.timedOut ? loop.ended : loop.ended === "" ? times : `${times}: ${loop.ended}`;
37831
+ traces.push({
37832
+ ...step.meta,
37833
+ path,
37834
+ startedAt,
37835
+ endedAt: options.now(),
37836
+ outcome: bodyFailed ? "error" : loop.timedOut ? "timed-out" : "ok",
37837
+ message,
37838
+ iterations: loop.iterations,
37839
+ ...sub === void 0 ? {} : { steps: sub.steps.map(withoutNested) }
37840
+ });
37841
+ continue;
37842
+ }
37843
+ if (step.choose !== void 0) {
37844
+ const reading = await readChoose(step.choose);
37845
+ const base = {
37846
+ ...step.meta,
37847
+ path,
37848
+ startedAt,
37849
+ branchChecks: [...reading.checks]
37850
+ };
37851
+ const { decision } = reading;
37852
+ if (decision.kind !== "run") {
37853
+ if (decision.kind === "unknown") options.onGuardUnknown?.({
37854
+ index,
37855
+ path: `${path}.branches.${decision.index}.if`,
37856
+ reason: decision.reason,
37857
+ deviceId: step.meta.deviceId
37858
+ });
37859
+ traces.push({
37860
+ ...base,
37861
+ endedAt: options.now(),
37862
+ outcome: "skipped",
37863
+ message: decision.kind === "unknown" ? `not run: branch ${decision.index + 1} could not be read (${decision.reason})` : "not run: no branch is true"
37864
+ });
37865
+ continue;
37866
+ }
37867
+ const listPath = decision.branch === "else" ? `${path}.else` : `${path}.${decision.branch}.steps`;
37868
+ const sub = await runSteps(decision.steps, {
37869
+ ...options,
37870
+ pathPrefix: listPath,
37871
+ indexOffset: 0
37872
+ });
37873
+ if (sub.failed) failed = true;
37874
+ else if (sub.aborted) aborted = true;
37875
+ if (sub.stopped !== void 0) stopped = sub.stopped;
37876
+ traces.push({
37877
+ ...base,
37878
+ endedAt: options.now(),
37879
+ outcome: sub.failed ? "error" : "ok",
37880
+ ...sub.failed ? { message: "a step of the branch failed" } : {},
37881
+ branch: decision.branch,
37882
+ steps: sub.steps.map(withoutNested)
37883
+ });
37884
+ continue;
37885
+ }
36703
37886
  let guardTrace = {};
36704
37887
  if (step.guard !== void 0) {
36705
37888
  const verdict = await readGuard(step.guard);
@@ -36729,10 +37912,12 @@ async function runSteps(steps, options) {
36729
37912
  }
36730
37913
  const sub = await runSteps(branch, {
36731
37914
  ...options,
36732
- pathPrefix: `${path}.else`
37915
+ pathPrefix: `${path}.else`,
37916
+ indexOffset: 0
36733
37917
  });
36734
37918
  if (sub.failed) failed = true;
36735
37919
  else if (sub.aborted) aborted = true;
37920
+ if (sub.stopped !== void 0) stopped = sub.stopped;
36736
37921
  traces.push({
36737
37922
  ...step.meta,
36738
37923
  ...guardTrace,
@@ -36750,6 +37935,7 @@ async function runSteps(steps, options) {
36750
37935
  let sent;
36751
37936
  const perDevice = [];
36752
37937
  let emptyReason;
37938
+ let timedOutReason;
36753
37939
  let templateNotes = [];
36754
37940
  const scope = {
36755
37941
  setDeviceId: (id) => {
@@ -36766,6 +37952,16 @@ async function runSteps(steps, options) {
36766
37952
  },
36767
37953
  setTemplateNotes: (notes) => {
36768
37954
  templateNotes = notes.slice(0, 20);
37955
+ },
37956
+ stop: (reason, outcome) => {
37957
+ stopped = {
37958
+ reason,
37959
+ outcome,
37960
+ path
37961
+ };
37962
+ },
37963
+ markTimedOut: (reason) => {
37964
+ timedOutReason = reason;
36769
37965
  }
36770
37966
  };
36771
37967
  const templatesTrace = () => templateNotes.length === 0 ? {} : { templates: [...templateNotes] };
@@ -36773,6 +37969,29 @@ async function runSteps(steps, options) {
36773
37969
  const devicesTrace = () => perDevice.length === 0 ? {} : { devices: perDevice.slice(0, 200) };
36774
37970
  try {
36775
37971
  await step.run(scope);
37972
+ const stop = (() => stopped)();
37973
+ if (stop !== void 0) {
37974
+ const message = `stopped: ${stop.reason}`;
37975
+ if (stop.outcome === "failed") {
37976
+ failed = true;
37977
+ options.onFailure({
37978
+ index,
37979
+ path,
37980
+ message,
37981
+ deviceId
37982
+ });
37983
+ }
37984
+ traces.push({
37985
+ ...step.meta,
37986
+ ...guardTrace,
37987
+ path,
37988
+ startedAt,
37989
+ endedAt: options.now(),
37990
+ outcome: stop.outcome === "failed" ? "error" : "ok",
37991
+ message
37992
+ });
37993
+ continue;
37994
+ }
36776
37995
  traces.push({
36777
37996
  ...step.meta,
36778
37997
  ...deviceId === void 0 || perDevice.length > 1 ? {} : { deviceId },
@@ -36783,18 +38002,27 @@ async function runSteps(steps, options) {
36783
38002
  path,
36784
38003
  startedAt,
36785
38004
  endedAt: options.now(),
36786
- outcome: emptyReason === void 0 ? "ok" : "empty",
36787
- ...emptyReason === void 0 ? {} : { message: emptyReason }
38005
+ outcome: timedOutReason !== void 0 ? "timed-out" : emptyReason === void 0 ? "ok" : "empty",
38006
+ ...timedOutReason !== void 0 ? { message: timedOutReason } : emptyReason === void 0 ? {} : { message: emptyReason }
36788
38007
  });
36789
38008
  } catch (err) {
36790
- failed = true;
36791
38009
  const message = errorMessage(err);
36792
- options.onFailure({
38010
+ const continued = step.continueOnError === true;
38011
+ if (continued) options.onContinuedFailure?.({
36793
38012
  index,
36794
38013
  path,
36795
38014
  message,
36796
38015
  deviceId
36797
38016
  });
38017
+ else {
38018
+ failed = true;
38019
+ options.onFailure({
38020
+ index,
38021
+ path,
38022
+ message,
38023
+ deviceId
38024
+ });
38025
+ }
36798
38026
  traces.push({
36799
38027
  ...step.meta,
36800
38028
  ...deviceId === void 0 || perDevice.length > 1 ? {} : { deviceId },
@@ -36805,7 +38033,7 @@ async function runSteps(steps, options) {
36805
38033
  path,
36806
38034
  startedAt,
36807
38035
  endedAt: options.now(),
36808
- outcome: "error",
38036
+ outcome: continued ? "failed-continued" : "error",
36809
38037
  message
36810
38038
  });
36811
38039
  }
@@ -36813,7 +38041,8 @@ async function runSteps(steps, options) {
36813
38041
  return {
36814
38042
  steps: traces,
36815
38043
  failed,
36816
- aborted: aborted && !failed
38044
+ aborted: aborted && !failed,
38045
+ ...stopped === void 0 ? {} : { stopped }
36817
38046
  };
36818
38047
  }
36819
38048
  function isVarRef(value) {
@@ -36821,7 +38050,8 @@ function isVarRef(value) {
36821
38050
  const keys = Object.keys(value);
36822
38051
  return keys.length === 1 && keys[0] === "$var" && typeof Reflect.get(value, "$var") === "string";
36823
38052
  }
36824
- var TEMPLATE_RE = /\{\{\s*vars\.([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;
38053
+ /** `{{vars.name}}`, or a dotted name (`{{vars.data.channel}}`): the bag is flat, the dots are part of the key. */
38054
+ var TEMPLATE_RE = /\{\{\s*vars\.([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)\s*\}\}/g;
36825
38055
  /**
36826
38056
  * Substitute a step's args from the run's variables. SUBSTITUTION only, never
36827
38057
  * evaluation:
@@ -36871,7 +38101,7 @@ function newSlotNonce() {
36871
38101
  return Math.random().toString(36).slice(2, 12);
36872
38102
  }
36873
38103
  function slotPattern(nonce) {
36874
- return new RegExp(`${VAR_SLOT_OPEN}${nonce}:([A-Za-z_][A-Za-z0-9_]*)${VAR_SLOT_CLOSE}`, "g");
38104
+ return new RegExp(`${VAR_SLOT_OPEN}${nonce}:([A-Za-z_][A-Za-z0-9_.]*)${VAR_SLOT_CLOSE}`, "g");
36875
38105
  }
36876
38106
  /** `text` with every `{{vars.x}}` slot (the only slot the run-time holds) replaced by `replacement`. */
36877
38107
  function holdVarSlots(text, replacement) {
@@ -37095,6 +38325,49 @@ function buildActionSteps(steps, vars, deps) {
37095
38325
  });
37096
38326
  }
37097
38327
  //#endregion
38328
+ //#region src/automation/wait-until.ts
38329
+ async function readSafely(read) {
38330
+ try {
38331
+ return await read();
38332
+ } catch (err) {
38333
+ return {
38334
+ result: "unknown",
38335
+ reason: err instanceof Error ? err.message : String(err)
38336
+ };
38337
+ }
38338
+ }
38339
+ async function waitUntil(input) {
38340
+ const startedAt = input.now();
38341
+ const deadline = startedAt + input.timeoutMs;
38342
+ for (;;) {
38343
+ const verdict = await readSafely(input.read);
38344
+ const waitedMs = input.now() - startedAt;
38345
+ if (input.isAborted()) return {
38346
+ result: "aborted",
38347
+ waitedMs
38348
+ };
38349
+ if (verdict.result === "true") return {
38350
+ result: "met",
38351
+ waitedMs
38352
+ };
38353
+ const remaining = deadline - input.now();
38354
+ if (remaining <= 0) return {
38355
+ result: "timed-out",
38356
+ waitedMs,
38357
+ lastReason: verdict.reason
38358
+ };
38359
+ await input.nextWake(remaining);
38360
+ if (input.isAborted()) return {
38361
+ result: "aborted",
38362
+ waitedMs: input.now() - startedAt
38363
+ };
38364
+ }
38365
+ }
38366
+ /** What the run trace says of a wait that ran out. */
38367
+ function waitTimedOutMessage(timeoutS, lastReason) {
38368
+ return `timed out after ${timeoutS} s: ${lastReason}`;
38369
+ }
38370
+ //#endregion
37098
38371
  //#region src/units/quantity-units.ts
37099
38372
  /**
37100
38373
  * Which units a person may pick for a number of a given quantity. The
@@ -37517,6 +38790,29 @@ var AUTOMATION_LEAF_CATALOG = {
37517
38790
  category: ""
37518
38791
  })
37519
38792
  },
38793
+ "device-fired": {
38794
+ kind: "device-fired",
38795
+ category: "devices",
38796
+ role: "event",
38797
+ allowedIn: EVENT_CONTEXTS,
38798
+ i18nKey: "automation.leafCatalog.device-fired",
38799
+ keywords: [
38800
+ "button",
38801
+ "press",
38802
+ "long",
38803
+ "remote",
38804
+ "switch",
38805
+ "key",
38806
+ "fires",
38807
+ "event",
38808
+ "click"
38809
+ ],
38810
+ needsDeviceValue: false,
38811
+ seed: () => ({
38812
+ kind: "device-fired",
38813
+ deviceId: 0
38814
+ })
38815
+ },
37520
38816
  schedule: {
37521
38817
  kind: "schedule",
37522
38818
  category: "time",
@@ -37704,6 +39000,7 @@ var AUTOMATION_LEAF_KINDS = [
37704
39000
  "detection",
37705
39001
  "stationary",
37706
39002
  "device-becomes",
39003
+ "device-fired",
37707
39004
  "device-event",
37708
39005
  "schedule",
37709
39006
  "interval",
@@ -38267,7 +39564,9 @@ var AddonHttpRouteSchema = zod.z.object({
38267
39564
  ]).optional(),
38268
39565
  description: zod.z.string().optional(),
38269
39566
  /** The hub limits this route per client address before the handler runs. */
38270
- rateLimit: zod.z.enum(["auth"]).optional()
39567
+ rateLimit: zod.z.enum(["auth"]).optional(),
39568
+ /** Served once per integration instance; the handler reads `instanceId`. */
39569
+ perInstance: zod.z.boolean().optional()
38271
39570
  });
38272
39571
  /**
38273
39572
  * Cross-process route invocation envelope. The hub captures the
@@ -38284,6 +39583,8 @@ var InvokeRequestSchema = zod.z.object({
38284
39583
  query: zod.z.record(zod.z.string(), zod.z.string()),
38285
39584
  body: zod.z.unknown(),
38286
39585
  headers: zod.z.record(zod.z.string(), zod.z.string()),
39586
+ /** The instance the hub resolved for a `perInstance` route. */
39587
+ instanceId: zod.z.string().optional(),
38287
39588
  user: zod.z.object({
38288
39589
  id: zod.z.string(),
38289
39590
  username: zod.z.string(),
@@ -56347,55 +57648,6 @@ var enumSensorCapability = {
56347
57648
  volatileStateFields: ["lastFetchedAt", "timestamp"]
56348
57649
  };
56349
57650
  //#endregion
56350
- //#region src/capabilities/event-emitter.cap.ts
56351
- /**
56352
- * Generic stateless event emitter. Installed on a `DeviceType.EventEmitter`
56353
- * device. Carries the device's EXACT declared event vocabulary verbatim
56354
- * (NO normalization). Two shapes:
56355
- * - structured source (HA `event.*` entity) → `eventTypes` is the fixed
56356
- * declared vocabulary (e.g. ['press_short','press_long',...]).
56357
- * - generic/legacy source (HA bus events, e.g. zha_event) → `eventTypes`
56358
- * is [] (open) and `lastEvent.data` carries the complex payload.
56359
- * `seq` is monotonic so two identical events still produce distinct slice writes.
56360
- */
56361
- var EventFireSchema = zod.z.object({
56362
- deviceId: zod.z.number(),
56363
- eventType: zod.z.string(),
56364
- data: zod.z.record(zod.z.string(), zod.z.unknown()).nullable(),
56365
- timestamp: zod.z.number().meta(require_sleep.readingMeta("none")),
56366
- seq: zod.z.number().meta(require_sleep.readingMeta("count"))
56367
- });
56368
- var EventEmitterStatusSchema = zod.z.object({
56369
- eventTypes: zod.z.array(zod.z.string()),
56370
- lastEvent: EventFireSchema.nullable(),
56371
- eventCountSinceStart: zod.z.number().meta(require_sleep.readingMeta("count"))
56372
- });
56373
- var eventEmitterCapability = {
56374
- name: "event-emitter",
56375
- scope: "device",
56376
- deviceNative: true,
56377
- mode: "singleton",
56378
- deviceTypes: [require_composed_stable_id.DeviceType.EventEmitter],
56379
- methods: {},
56380
- events: { onEvent: { data: EventFireSchema } },
56381
- status: {
56382
- schema: EventEmitterStatusSchema,
56383
- kind: "push"
56384
- },
56385
- runtimeState: EventEmitterStatusSchema,
56386
- /**
56387
- * Runtime-state durability: **session** — `eventCountSinceStart` names its own scope.
56388
- *
56389
- * See `RuntimeStateDurability`. Enforced by
56390
- * `scripts/check-runtime-state-durability.ts`.
56391
- */
56392
- durability: "session",
56393
- /**
56394
- * History (D850): none — `eventCountSinceStart` resets with the addon; events live in ledgers.
56395
- */
56396
- history: "none"
56397
- };
56398
- //#endregion
56399
57651
  //#region src/capabilities/face-gallery.cap.ts
56400
57652
  var IdentitySchema = zod.z.object({
56401
57653
  id: zod.z.string(),
@@ -77240,7 +78492,18 @@ var OauthIntegrationDescriptorSchema = zod.z.object({
77240
78492
  * The value is baked into the authorization code at `/authorize` and travels
77241
78493
  * on the tokens, so editing this field changes FUTURE links only.
77242
78494
  */
77243
- refreshTokenTtlSec: zod.z.union([zod.z.number().int().positive(), zod.z.literal("never")]).optional()
78495
+ refreshTokenTtlSec: zod.z.union([zod.z.number().int().positive(), zod.z.literal("never")]).optional(),
78496
+ /**
78497
+ * The integration instances an account can be linked to (planning#415),
78498
+ * beside the default one. `/api/oauth2/authorize?instance=<id>` is accepted
78499
+ * only for an id listed here; with no `instance=` the link is made to the
78500
+ * default instance, which is never listed and always accepted — it is the
78501
+ * address third parties already hold. Omit for a single-instance integration.
78502
+ */
78503
+ instances: zod.z.array(zod.z.object({
78504
+ id: zod.z.string(),
78505
+ displayName: zod.z.string()
78506
+ })).optional()
77244
78507
  });
77245
78508
  var oauthIntegrationCapability = {
77246
78509
  name: "oauth-integration",
@@ -87495,6 +88758,13 @@ var SsoBridgeClaimsSchema = zod.z.object({
87495
88758
  /** OAuth authorization-code binding — set only on `oauth-code` tokens. */
87496
88759
  redirectUri: zod.z.string().optional(),
87497
88760
  integrationId: zod.z.string().optional(),
88761
+ /**
88762
+ * The integration INSTANCE an OAuth link was made for (planning#415). Set on
88763
+ * `oauth-code`, `oauth-access` and `oauth-refresh` tokens of a link made
88764
+ * with `instance=`; absent on a link to the default instance. A cloud relay
88765
+ * reads it off the access token to route; the hub answers from the session.
88766
+ */
88767
+ instanceId: zod.z.string().optional(),
87498
88768
  /** JWT ID — unique per issued code; consumed-set enforces single-use. */
87499
88769
  jti: zod.z.string().optional(),
87500
88770
  /** PKCE S256 challenge — set only on `oauth-code` tokens issued to a public
@@ -90556,6 +91826,8 @@ var OauthSessionSummarySchema = zod.z.object({
90556
91826
  userId: zod.z.string(),
90557
91827
  username: zod.z.string(),
90558
91828
  integrationId: zod.z.string(),
91829
+ /** The instance the link was made for; `null` = the default instance. */
91830
+ instanceId: zod.z.string().nullable().optional(),
90559
91831
  scopes: zod.z.array(TokenScopeSchema),
90560
91832
  createdAt: zod.z.number(),
90561
91833
  lastUsedAt: zod.z.number(),
@@ -90684,6 +91956,9 @@ var userManagementCapability = {
90684
91956
  }),
90685
91957
  oauthIssueCode: require_sleep.method(zod.z.object({
90686
91958
  integrationId: zod.z.string(),
91959
+ /** The integration instance the link is for. Omit for the default
91960
+ * instance — never pass the addon id to mean it. */
91961
+ instanceId: zod.z.string().optional(),
90687
91962
  userId: zod.z.string(),
90688
91963
  username: zod.z.string(),
90689
91964
  scopes: zod.z.array(TokenScopeSchema),
@@ -90725,7 +92000,13 @@ var userManagementCapability = {
90725
92000
  oauthVerifyAccessToken: require_sleep.method(zod.z.object({ token: zod.z.string() }), zod.z.object({
90726
92001
  userId: zod.z.string(),
90727
92002
  username: zod.z.string(),
90728
- scopes: zod.z.array(TokenScopeSchema)
92003
+ scopes: zod.z.array(TokenScopeSchema),
92004
+ /** The instance the link was made for, read from the SESSION.
92005
+ * Absent = the default instance. `oauthLinkServesInstance` is the
92006
+ * helper a per-instance route calls to compare it with the instance
92007
+ * of its path; no route declares `perInstance` yet (the Alexa
92008
+ * per-instance route, T3, is the first consumer). */
92009
+ instanceId: zod.z.string().optional()
90729
92010
  }).nullable(), { access: "view" }),
90730
92011
  listExternalIdentities: require_sleep.method(zod.z.object({ userId: zod.z.string() }), zod.z.array(ExternalIdentitySchema), { auth: "admin" }),
90731
92012
  /** The user an identity is linked to, or `null`. */
@@ -95016,6 +96297,10 @@ function leafIssues(site, when, root) {
95016
96297
  }
95017
96298
  return;
95018
96299
  }
96300
+ if (leaf.kind === "device-fired") {
96301
+ if (deviceOf(site, leaf.deviceId) === void 0) issues.push(`${at}: no device has id ${leaf.deviceId}`);
96302
+ return;
96303
+ }
95019
96304
  if (leaf.kind === "device-event" && leaf.deviceId !== void 0) {
95020
96305
  if (deviceOf(site, leaf.deviceId) === void 0) issues.push(`${at}: no device has id ${leaf.deviceId}`);
95021
96306
  }
@@ -137696,18 +138981,25 @@ exports.AutoTuneWarningSchema = AutoTuneWarningSchema;
137696
138981
  exports.AutoUpdateSettingsSchema = AutoUpdateSettingsSchema;
137697
138982
  exports.AutomationActionSchema = AutomationActionSchema;
137698
138983
  exports.AutomationCapStepSchema = AutomationCapStepSchema;
138984
+ exports.AutomationChooseStepSchema = AutomationChooseStepSchema;
137699
138985
  exports.AutomationConditionOperatorSchema = AutomationConditionOperatorSchema;
137700
138986
  exports.AutomationConditionTraceNodeSchema = AutomationConditionTraceNodeSchema;
137701
138987
  exports.AutomationControlStatusSchema = AutomationControlStatusSchema;
138988
+ exports.AutomationParallelStepSchema = AutomationParallelStepSchema;
137702
138989
  exports.AutomationRecipeSchema = AutomationRecipeSchema;
138990
+ exports.AutomationRepeatLoopSchema = AutomationRepeatLoopSchema;
138991
+ exports.AutomationRepeatStepSchema = AutomationRepeatStepSchema;
137703
138992
  exports.AutomationRunModeSchema = AutomationRunModeSchema;
137704
138993
  exports.AutomationRunOutcomeSchema = AutomationRunOutcomeSchema;
137705
138994
  exports.AutomationRunTraceSchema = AutomationRunTraceSchema;
137706
138995
  exports.AutomationRunVerdictSchema = AutomationRunVerdictSchema;
138996
+ exports.AutomationSetStepSchema = AutomationSetStepSchema;
137707
138997
  exports.AutomationStateDocSchema = AutomationStateDocSchema;
137708
138998
  exports.AutomationStepTraceSchema = AutomationStepTraceSchema;
138999
+ exports.AutomationStopStepSchema = AutomationStopStepSchema;
137709
139000
  exports.AutomationTriggerTraceSchema = AutomationTriggerTraceSchema;
137710
139001
  exports.AutomationWaitStepSchema = AutomationWaitStepSchema;
139002
+ exports.AutomationWaitUntilStepSchema = AutomationWaitUntilStepSchema;
137711
139003
  exports.AutomationWhenSchema = AutomationWhenSchema;
137712
139004
  exports.AvailableIntegrationTypeSchema = AvailableIntegrationTypeSchema;
137713
139005
  exports.BASE_DEVICE_CAPS = BASE_DEVICE_CAPS;
@@ -137785,6 +139077,7 @@ exports.CAP_RUNTIME_FIELD_UNITS = CAP_RUNTIME_FIELD_UNITS;
137785
139077
  exports.CAP_VOCABULARY = require_sleep.CAP_VOCABULARY;
137786
139078
  exports.CAP_VOCABULARY_BY_NAME = require_sleep.CAP_VOCABULARY_BY_NAME;
137787
139079
  exports.CATALOG_LANGS = CATALOG_LANGS;
139080
+ exports.CHOOSE_BRANCHES_MAX = CHOOSE_BRANCHES_MAX;
137788
139081
  exports.CIVIL_TWILIGHT_ALTITUDE_DEG = CIVIL_TWILIGHT_ALTITUDE_DEG;
137789
139082
  exports.CLASS_MAP_MACRO_TARGETS = CLASS_MAP_MACRO_TARGETS;
137790
139083
  exports.CLIMATE_ROLES = CLIMATE_ROLES;
@@ -138191,6 +139484,8 @@ exports.DeviceExportInstancePinSchema = InstancePinSchema;
138191
139484
  exports.DeviceExportStatusSchema = DeviceExportStatusSchema;
138192
139485
  exports.DeviceExportUnexposeInputSchema = UnexposeInputSchema;
138193
139486
  exports.DeviceFeature = require_composed_stable_id.DeviceFeature;
139487
+ exports.DeviceFiredMatchSchema = DeviceFiredMatchSchema;
139488
+ exports.DeviceFiredWatch = DeviceFiredWatch;
138194
139489
  exports.DeviceHistoryKindSchema = DeviceHistoryKindSchema;
138195
139490
  exports.DeviceHistoryOrphanDeleteRefusalSchema = DeviceHistoryOrphanDeleteRefusalSchema;
138196
139491
  exports.DeviceHistoryOrphanReasonSchema = DeviceHistoryOrphanReasonSchema;
@@ -138287,6 +139582,7 @@ exports.EVENT_LEAF_ID_RE = EVENT_LEAF_ID_RE;
138287
139582
  exports.EVENT_OWNER_TYPES = EVENT_OWNER_TYPES;
138288
139583
  exports.EVENT_PAD_MS = EVENT_PAD_MS;
138289
139584
  exports.EVENT_TAXONOMY = EVENT_TAXONOMY;
139585
+ exports.EVENT_VOCABULARY_KINDS = EVENT_VOCABULARY_KINDS;
138290
139586
  exports.EXPORT_DENSE_MAX_RANGES = EXPORT_DENSE_MAX_RANGES;
138291
139587
  exports.EXPORT_INSTANCE_UNKNOWN = EXPORT_INSTANCE_UNKNOWN;
138292
139588
  exports.EXPRESSION_BUILTINS = require_implemented_methods.EXPRESSION_BUILTINS;
@@ -138341,6 +139637,10 @@ exports.EventMediaKindSchema = EventMediaKindSchema;
138341
139637
  exports.EventMediaProductionSchema = EventMediaProductionSchema;
138342
139638
  exports.EventOwnerTypeSchema = EventOwnerTypeSchema;
138343
139639
  exports.EventSourceType = require_enums.EventSourceType$1;
139640
+ exports.EventVocabularyEntrySchema = EventVocabularyEntrySchema;
139641
+ exports.EventVocabularyFieldSchema = EventVocabularyFieldSchema;
139642
+ exports.EventVocabularyKindSchema = EventVocabularyKindSchema;
139643
+ exports.EventVocabularySourceSchema = EventVocabularySourceSchema;
138344
139644
  exports.ExportBytesSchema = ExportBytesSchema;
138345
139645
  exports.ExportClipSubjectSchema = ExportClipSubjectSchema;
138346
139646
  exports.ExportDenseRangeSchema = ExportDenseRangeSchema;
@@ -138404,6 +139704,7 @@ exports.FEEDER_EXAMPLE_ADDON_ID = FEEDER_EXAMPLE_ADDON_ID;
138404
139704
  exports.FEEDER_EXAMPLE_HA_DEVICE_ID = FEEDER_EXAMPLE_HA_DEVICE_ID;
138405
139705
  exports.FEW_SHOT_COUNT = FEW_SHOT_COUNT;
138406
139706
  exports.FFMPEG_PATH_ENV = require_implemented_methods.FFMPEG_PATH_ENV;
139707
+ exports.FIRED_RECOVERED_NOTE = FIRED_RECOVERED_NOTE;
138407
139708
  exports.FIRST_LEVEL_MACRO_CLASSES = FIRST_LEVEL_MACRO_CLASSES;
138408
139709
  exports.FORBIDDEN_MESSAGE_PREFIX = require_sleep.FORBIDDEN_MESSAGE_PREFIX;
138409
139710
  exports.FORWARD_INPUT_KEY = require_implemented_methods.FORWARD_INPUT_KEY;
@@ -139192,6 +140493,8 @@ exports.PALETTE_MIN_CONTRAST = PALETTE_MIN_CONTRAST;
139192
140493
  exports.PALETTE_MIN_DELTA_E = PALETTE_MIN_DELTA_E;
139193
140494
  exports.PALETTE_MIN_DELTA_E_MARK = PALETTE_MIN_DELTA_E_MARK;
139194
140495
  exports.PALETTE_PRESET_IDS = PALETTE_PRESET_IDS;
140496
+ exports.PARALLEL_STEPS_MAX = PARALLEL_STEPS_MAX;
140497
+ exports.PARALLEL_STEPS_MIN = PARALLEL_STEPS_MIN;
139195
140498
  exports.PAUSE_MAX_MS = PAUSE_MAX_MS;
139196
140499
  exports.PEER_BYTES_CHUNK_BYTES = require_sleep.PEER_BYTES_CHUNK_BYTES;
139197
140500
  exports.PEER_BYTES_MAX_OUTSTANDING = require_sleep.PEER_BYTES_MAX_OUTSTANDING;
@@ -139379,8 +140682,14 @@ exports.REMOTE_WIDGET_ROLES = REMOTE_WIDGET_ROLES;
139379
140682
  exports.REMOVAL_RECONCILE_INTERVAL_MS = REMOVAL_RECONCILE_INTERVAL_MS;
139380
140683
  exports.REMOVED_MODEL_IDS = REMOVED_MODEL_IDS;
139381
140684
  exports.REMOVE_LEAF = require_sleep.REMOVE_LEAF;
140685
+ exports.REPEAT_COUNT_MAX = REPEAT_COUNT_MAX;
140686
+ exports.REPEAT_DEVICES_MAX = REPEAT_DEVICES_MAX;
140687
+ exports.REPEAT_ITEM_VAR = REPEAT_ITEM_VAR;
140688
+ exports.REPEAT_ITERATIONS_MAX = REPEAT_ITERATIONS_MAX;
140689
+ exports.REPEAT_STEPS_MAX = REPEAT_STEPS_MAX;
139382
140690
  exports.RESERVED_BINDING_NAMES = require_implemented_methods.RESERVED_BINDING_NAMES;
139383
140691
  exports.RESERVED_COLLECTION_SOURCES = RESERVED_COLLECTION_SOURCES;
140692
+ exports.RESERVED_RUN_VARS = RESERVED_RUN_VARS;
139384
140693
  exports.RESET_PERIODS = require_implemented_methods.RESET_PERIODS;
139385
140694
  exports.RESTORED_CAP_NAMES = RESTORED_CAP_NAMES;
139386
140695
  exports.RESTREAM_INPUT_PROBE = require_implemented_methods.RESTREAM_INPUT_PROBE;
@@ -139614,6 +140923,7 @@ exports.SCENE_DEFAULT_QUIET_SECONDS = SCENE_DEFAULT_QUIET_SECONDS;
139614
140923
  exports.SCENE_DEFAULT_UNCOVERED_POLICY = SCENE_DEFAULT_UNCOVERED_POLICY;
139615
140924
  exports.SCENE_DIVERGED = SCENE_DIVERGED;
139616
140925
  exports.SCENE_RESET_RECAPTURES = SCENE_RESET_RECAPTURES;
140926
+ exports.SCHEDULER_WAIT_MAX_SECONDS = SCHEDULER_WAIT_MAX_SECONDS;
139617
140927
  exports.SCOPED_SETTINGS_SCOPES = require_sleep.SCOPED_SETTINGS_SCOPES;
139618
140928
  exports.SCOPE_PRESETS = SCOPE_PRESETS;
139619
140929
  exports.SECRET_CLEAR = require_sleep.SECRET_CLEAR;
@@ -139627,6 +140937,9 @@ exports.SERVER_NAME_MAX_LENGTH = SERVER_NAME_MAX_LENGTH;
139627
140937
  exports.SERVER_NAME_SETTING_KEY = SERVER_NAME_SETTING_KEY;
139628
140938
  exports.SESSION_LOST_ALERT_CATEGORY = SESSION_LOST_ALERT_CATEGORY;
139629
140939
  exports.SESSION_PLACEMENT_SETTING_KEY = SESSION_PLACEMENT_SETTING_KEY;
140940
+ exports.SET_VARS_MAX = SET_VARS_MAX;
140941
+ exports.SET_VAR_NAME_RE = SET_VAR_NAME_RE;
140942
+ exports.SET_VAR_VALUE_MAX = SET_VAR_VALUE_MAX;
139630
140943
  exports.SHARE_AFFINITY_TOLERANCE_SESSIONS = SHARE_AFFINITY_TOLERANCE_SESSIONS;
139631
140944
  exports.SHARE_SOURCE_SETTING_KEY = SHARE_SOURCE_SETTING_KEY;
139632
140945
  exports.SHARE_VIEW_KINDS = require_sleep.SHARE_VIEW_KINDS;
@@ -139654,6 +140967,8 @@ exports.STATE_LABEL_KEYS = STATE_LABEL_KEYS;
139654
140967
  exports.STATIONARY_OVERLAY_STYLE = STATIONARY_OVERLAY_STYLE;
139655
140968
  exports.STATISTIC_STATS = require_implemented_methods.STATISTIC_STATS;
139656
140969
  exports.STEP_DEVICE_CONCURRENCY = STEP_DEVICE_CONCURRENCY;
140970
+ exports.STEP_NEST_MAX = STEP_NEST_MAX;
140971
+ exports.STOP_REASON_MAX = STOP_REASON_MAX;
139657
140972
  exports.STORAGE_ACCESS_FALLBACK = STORAGE_ACCESS_FALLBACK;
139658
140973
  exports.STORAGE_BYTES_PER_GB = STORAGE_BYTES_PER_GB;
139659
140974
  exports.STORAGE_LOCATION_MODES = STORAGE_LOCATION_MODES;
@@ -140013,6 +141328,8 @@ exports.VideoEncodeSchema = VideoEncodeSchema;
140013
141328
  exports.ViewerDeviceAllowSchema = ViewerDeviceAllowSchema;
140014
141329
  exports.ViewerFeatureIdSchema = ViewerFeatureIdSchema;
140015
141330
  exports.ViewerTokenScopeSchema = ViewerTokenScopeSchema;
141331
+ exports.WAIT_MAX_SECONDS = WAIT_MAX_SECONDS;
141332
+ exports.WAIT_UNTIL_TIMEOUT_MAX_S = WAIT_UNTIL_TIMEOUT_MAX_S;
140016
141333
  exports.WEBRTC_CLIMB_HOLD_CODES = WEBRTC_CLIMB_HOLD_CODES;
140017
141334
  exports.WEBRTC_EGRESS_PROFILE = WEBRTC_EGRESS_PROFILE;
140018
141335
  exports.WEBRTC_TRY_BLOCKERS = WEBRTC_TRY_BLOCKERS;
@@ -140310,6 +141627,7 @@ exports.consumablesCapability = consumablesCapability;
140310
141627
  exports.contactCapability = contactCapability;
140311
141628
  exports.containingParentIndex = containingParentIndex;
140312
141629
  exports.controlCapability = controlCapability;
141630
+ exports.conventionalEventVocabulary = conventionalEventVocabulary;
140313
141631
  exports.convertLegacyCondition = convertLegacyCondition;
140314
141632
  exports.convertLegacyRecipe = convertLegacyRecipe;
140315
141633
  exports.convertLegacyWhen = convertLegacyWhen;
@@ -140498,6 +141816,7 @@ exports.eventEmitterCapability = eventEmitterCapability;
140498
141816
  exports.eventKindLabel = eventKindLabel;
140499
141817
  exports.eventLeafIdAt = eventLeafIdAt;
140500
141818
  exports.eventOverlapsClipWindow = eventOverlapsClipWindow;
141819
+ exports.eventTypesOfVocabulary = eventTypesOfVocabulary;
140501
141820
  exports.evictionPolicyForMode = evictionPolicyForMode;
140502
141821
  exports.evictionPolicyOfLocation = evictionPolicyOfLocation;
140503
141822
  exports.expandAudioChunkToF32le = require_sleep.expandAudioChunkToF32le;
@@ -140542,6 +141861,8 @@ exports.findCompositionCycles = findCompositionCycles;
140542
141861
  exports.findMigrationsBlocked = require_sleep.findMigrationsBlocked;
140543
141862
  exports.findTimezone = findTimezone;
140544
141863
  exports.findVocabAction = require_sleep.findVocabAction;
141864
+ exports.findVocabularyEntry = findVocabularyEntry;
141865
+ exports.firedDataVars = firedDataVars;
140545
141866
  exports.flattenNestedRecords = flattenNestedRecords;
140546
141867
  exports.flattenPortsOver = flattenPortsOver;
140547
141868
  exports.flipperIrDraft = flipperIrDraft;
@@ -140657,6 +141978,7 @@ exports.invertPresetFeature = invertPresetFeature;
140657
141978
  exports.invocationFromEncodeProfile = require_implemented_methods.invocationFromEncodeProfile;
140658
141979
  exports.irSourceProblem = irSourceProblem;
140659
141980
  exports.irTransmitterCapability = irTransmitterCapability;
141981
+ exports.isAddonInstanceId = isAddonInstanceId;
140660
141982
  exports.isAgentOnlyPlacement = isAgentOnlyPlacement;
140661
141983
  exports.isAirConditioner = isAirConditioner;
140662
141984
  exports.isAlarmControllableCap = isAlarmControllableCap;
@@ -140869,6 +142191,7 @@ exports.nativeObjectDetectionCapability = nativeObjectDetectionCapability;
140869
142191
  exports.navigationCapability = navigationCapability;
140870
142192
  exports.ncAlarmSystemDefaultSettings = ncAlarmSystemDefaultSettings;
140871
142193
  exports.ncMediaPolicyError = ncMediaPolicyError;
142194
+ exports.nestedStepsOf = nestedStepsOf;
140872
142195
  exports.networkAccessCapability = networkAccessCapability;
140873
142196
  exports.networkLinkCapability = networkLinkCapability;
140874
142197
  exports.networkQualityCapability = networkQualityCapability;
@@ -140908,6 +142231,8 @@ exports.notifierCapability = notifierCapability;
140908
142231
  exports.numericSensorCapability = numericSensorCapability;
140909
142232
  exports.oauthIntegrationCapability = oauthIntegrationCapability;
140910
142233
  exports.oauthLandingUrl = oauthLandingUrl;
142234
+ exports.oauthLinkInstanceId = oauthLinkInstanceId;
142235
+ exports.oauthLinkServesInstance = oauthLinkServesInstance;
140911
142236
  exports.objectInputDeclaresAddonId = objectInputDeclaresAddonId;
140912
142237
  exports.objectInputDeclaresRequiredDeviceId = objectInputDeclaresRequiredDeviceId;
140913
142238
  exports.observeHoldLeaves = observeHoldLeaves;
@@ -140989,6 +142314,7 @@ exports.pipelineAnalyticsCapability = pipelineAnalyticsCapability;
140989
142314
  exports.pipelineExecutorCapability = pipelineExecutorCapability;
140990
142315
  exports.pipelineOrchestratorCapability = pipelineOrchestratorCapability;
140991
142316
  exports.pipelineRunnerCapability = pipelineRunnerCapability;
142317
+ exports.plainEventVocabulary = plainEventVocabulary;
140992
142318
  exports.planComposition = planComposition;
140993
142319
  exports.planCompositionEvents = planCompositionEvents;
140994
142320
  exports.planItems = planItems;
@@ -141047,6 +142373,7 @@ exports.readCommandOrigin = require_sleep.readCommandOrigin;
141047
142373
  exports.readDetailCropConvention = readDetailCropConvention;
141048
142374
  exports.readDeviceStateFrom = readDeviceStateFrom;
141049
142375
  exports.readErrorI18n = require_sleep.readErrorI18n;
142376
+ exports.readEventVocabulary = readEventVocabulary;
141050
142377
  exports.readFaceRescoreIntervalMinutes = readFaceRescoreIntervalMinutes;
141051
142378
  exports.readHubMotionDetected = readHubMotionDetected;
141052
142379
  exports.readHubMotionStatus = readHubMotionStatus;
@@ -141100,6 +142427,7 @@ exports.removeGroup = removeGroup;
141100
142427
  exports.removeScalarTarget = removeScalarTarget;
141101
142428
  exports.renameAlarmProfile = renameAlarmProfile;
141102
142429
  exports.renderVocabPhrase = renderVocabPhrase;
142430
+ exports.repeatCheck = repeatCheck;
141103
142431
  exports.replacedFieldKeys = replacedFieldKeys;
141104
142432
  exports.replayDwellIntervals = replayDwellIntervals;
141105
142433
  exports.reportIsScalable = reportIsScalable;
@@ -141303,6 +142631,8 @@ exports.stateVocabularyFor = stateVocabularyFor;
141303
142631
  exports.statisticCadenceMs = require_implemented_methods.statisticCadenceMs;
141304
142632
  exports.statisticDraft = statisticDraft;
141305
142633
  exports.statusInstanceOf = statusInstanceOf;
142634
+ exports.stepConditionsOf = stepConditionsOf;
142635
+ exports.stepGuardOf = stepGuardOf;
141306
142636
  exports.stepGuardSiteIssues = stepGuardSiteIssues;
141307
142637
  exports.stepModelRunsOnFormat = stepModelRunsOnFormat;
141308
142638
  exports.stepPulse = stepPulse;
@@ -141451,6 +142781,8 @@ exports.viewerUiCapability = require_sleep.viewerUiCapability;
141451
142781
  exports.vocabActionIdFor = require_sleep.vocabActionIdFor;
141452
142782
  exports.vocabularyActionsForDevice = actionsForDevice$1;
141453
142783
  exports.vocabularyTriggersForDevice = triggersForDevice;
142784
+ exports.waitTimedOutMessage = waitTimedOutMessage;
142785
+ exports.waitUntil = waitUntil;
141454
142786
  exports.waterHeaterCapability = waterHeaterCapability;
141455
142787
  exports.wattMillisecondsToKwh = require_implemented_methods.wattMillisecondsToKwh;
141456
142788
  exports.weatherCapability = weatherCapability;