@camstack/types 1.2.549 → 1.2.550

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.
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,36 @@ 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. Nothing calls it yet: no route declares
543
+ * `perInstance` (the Alexa per-instance route, T3, is the first consumer).
544
+ */
545
+ /** An instance id as it may appear in a path or a query: no separator, no escape, bounded. */
546
+ var ADDON_INSTANCE_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
547
+ function isAddonInstanceId(value) {
548
+ return ADDON_INSTANCE_ID_RE.test(value);
549
+ }
550
+ /** The instance a link was made for, with the default one spelled as the addon id. */
551
+ function oauthLinkInstanceId(link, addonId) {
552
+ return link.instanceId ?? addonId;
553
+ }
554
+ /**
555
+ * True when a verified link may be used on a request addressed to
556
+ * `requestInstanceId` (`AddonHttpRequest.instanceId`, absent on a route that
557
+ * is not per-instance, which is the default instance).
558
+ */
559
+ function oauthLinkServesInstance(link, requestInstanceId, addonId) {
560
+ return oauthLinkInstanceId(link, addonId) === (requestInstanceId ?? addonId);
561
+ }
562
+ //#endregion
532
563
  //#region src/addon/session-health.ts
533
564
  var SESSION_LOST_ALERT_CATEGORY = "integration.session-lost";
534
565
  var SESSION_EPISODE_KEY = "session-lost";
@@ -33415,9 +33446,12 @@ function convertLegacyWhen(half) {
33415
33446
  * every caller — automations, Actions, and the notification centre, which runs
33416
33447
  * only Actions (planning#473).
33417
33448
  */
33449
+ /** The longest one `wait` step lasts. It is cut by a restart of the run and does not survive a hub restart. */
33450
+ var WAIT_MAX_SECONDS = 3600;
33451
+ var WAIT_TOO_LONG = `a wait is at most one hour (${WAIT_MAX_SECONDS} s)`;
33418
33452
  var AutomationWaitStepSchema = zod.z.object({
33419
33453
  kind: zod.z.literal("wait"),
33420
- seconds: zod.z.number().min(0).max(300)
33454
+ seconds: zod.z.number().min(0).max(WAIT_MAX_SECONDS, WAIT_TOO_LONG)
33421
33455
  });
33422
33456
  /** The legacy `deviceId` of a cap step: still READ, never written (D983). */
33423
33457
  var LegacyStepDeviceSchema = zod.z.union([
@@ -33547,20 +33581,224 @@ var ActionStepSchema = zod.z.discriminatedUnion("kind", [GuardedWaitStepSchema,
33547
33581
  path: ["if"]
33548
33582
  });
33549
33583
  });
33584
+ /**
33585
+ * Flow control of an AUTOMATION's list (#500). A standalone list (an action, a
33586
+ * scheduler point, a preset) stays `wait` and `cap`: it has no run of its own
33587
+ * to end and no variable bag to write.
33588
+ */
33589
+ var continueOnErrorShape = {
33590
+ /** A failure of this step is traced `failed-continued` and the next step runs. */
33591
+ continueOnError: zod.z.literal(true).optional() };
33592
+ /** An automation's cap step: the shared guarded cap step, plus `continueOnError`. */
33593
+ var AutomationGuardedCapStepSchema = AutomationCapStepBaseSchema.extend({
33594
+ ...stepGuardShape,
33595
+ ...continueOnErrorShape
33596
+ }).refine((step) => step.target !== void 0 || step.deviceId !== void 0, {
33597
+ message: "a cap step needs a target",
33598
+ path: ["target"]
33599
+ }).refine((step) => step.target?.kind !== "domain" || step.actionId !== void 0, {
33600
+ message: "a domain target needs the vocabulary action it applies to (actionId)",
33601
+ path: ["actionId"]
33602
+ }).refine((step) => step.else === void 0 || step.if !== void 0, elseNeedsIf);
33603
+ var STOP_REASON_MAX = 200;
33604
+ /** End the run here, on purpose. `reason` may carry `{{vars.x}}` slots. */
33605
+ var AutomationStopStepSchema = zod.z.object({
33606
+ kind: zod.z.literal("stop"),
33607
+ reason: zod.z.string().min(1, "a stop needs a reason: it is what the run trace shows").max(200),
33608
+ /** `ok`: the run ends as a success. `failed`: it ends as a failure, with the reason. */
33609
+ outcome: zod.z.enum(["ok", "failed"]),
33610
+ /** Stop only when this reads true; false or unknown does not stop. */
33611
+ if: AutomationWhenSchema.optional()
33612
+ });
33613
+ var SET_VARS_MAX = 20;
33614
+ var SET_VAR_VALUE_MAX = 500;
33615
+ var SET_VAR_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,39}$/;
33616
+ /** Names the run itself writes and reads (`leaf` is what `triggered-by` judges): a step may not overwrite them. */
33617
+ var RESERVED_RUN_VARS = [
33618
+ "kind",
33619
+ "leaf",
33620
+ "at"
33621
+ ];
33622
+ /**
33623
+ * Write variables into the run's bag, for the steps after it. SUBSTITUTION
33624
+ * only, never evaluation: a text value may carry `{{vars.x}}` slots.
33625
+ */
33626
+ var AutomationSetStepSchema = zod.z.object({
33627
+ kind: zod.z.literal("set"),
33628
+ vars: zod.z.record(zod.z.string(), zod.z.union([
33629
+ zod.z.string().max(500),
33630
+ zod.z.number(),
33631
+ zod.z.boolean()
33632
+ ])).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` }),
33633
+ /** Set only when this reads true; false or unknown leaves the bag as it is. */
33634
+ if: AutomationWhenSchema.optional()
33635
+ });
33636
+ var AutomationRunActionStepSchema = zod.z.object({
33637
+ kind: zod.z.literal("action"),
33638
+ /** An entry of the `actions` surface (`internal:<uuid>` or `<addonId>:<localId>`). */
33639
+ actionId: zod.z.string().min(1),
33640
+ /** Values for the action's declared variables; the others take their default. */
33641
+ variables: zod.z.record(zod.z.string(), zod.z.union([
33642
+ zod.z.string(),
33643
+ zod.z.number(),
33644
+ zod.z.boolean()
33645
+ ])).optional(),
33646
+ ...continueOnErrorShape
33647
+ });
33648
+ /** How many branches one `choose` holds. */
33649
+ var CHOOSE_BRANCHES_MAX = 6;
33650
+ /**
33651
+ * A step INSIDE a branch of a `choose`: a flow step with no condition of its
33652
+ * own (the branch is the condition) and no block inside it. Strict, so an `if`
33653
+ * written on such a step is refused rather than dropped.
33654
+ */
33655
+ /** The longest a `wait-until` may wait: six hours. */
33656
+ var WAIT_UNTIL_TIMEOUT_MAX_S = 21600;
33657
+ /**
33658
+ * Pause the run until a condition is true (#500). The timeout is mandatory: a
33659
+ * run never waits without an end. `onTimeout` says what a wait that ran out
33660
+ * does: `continue` goes on to the next step, `stop` ends the run as a failure.
33661
+ * A condition that cannot be read is not "true": the wait goes on (D49).
33662
+ */
33663
+ var AutomationWaitUntilStepSchema = zod.z.object({
33664
+ kind: zod.z.literal("wait-until"),
33665
+ when: AutomationWhenSchema,
33666
+ 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)`),
33667
+ onTimeout: zod.z.enum(["continue", "stop"])
33668
+ }).strict();
33669
+ /** The step kinds that hold steps of their own, or pause on a condition: they nest two levels at most. */
33670
+ var BLOCK_STEP_KINDS = [
33671
+ "choose",
33672
+ "repeat",
33673
+ "parallel",
33674
+ "wait-until"
33675
+ ];
33676
+ var STEP_NEST_MAX = 2;
33677
+ var NEST_TOO_DEEP = `steps nest two levels at most: a step inside a nested choose or repeat can be a plain step only`;
33678
+ function kindOf(input) {
33679
+ return typeof input === "object" && input !== null ? Reflect.get(input, "kind") : void 0;
33680
+ }
33681
+ /** Where the nesting ends, a block step is refused in words rather than as an unknown kind. */
33682
+ function nestTooDeep(issue) {
33683
+ const kind = kindOf(issue.input);
33684
+ return typeof kind === "string" && BLOCK_STEP_KINDS.includes(kind) ? NEST_TOO_DEEP : void 0;
33685
+ }
33686
+ var plainStepSchemas = [
33687
+ AutomationWaitStepSchema.strict(),
33688
+ AutomationCapStepBaseSchema.extend(continueOnErrorShape).strict().refine((step) => step.target !== void 0 || step.deviceId !== void 0, {
33689
+ message: "a cap step needs a target",
33690
+ path: ["target"]
33691
+ }).refine((step) => step.target?.kind !== "domain" || step.actionId !== void 0, {
33692
+ message: "a domain target needs the vocabulary action it applies to (actionId)",
33693
+ path: ["actionId"]
33694
+ }),
33695
+ AutomationStopStepSchema.omit({ if: true }).strict(),
33696
+ AutomationSetStepSchema.omit({ if: true }).strict(),
33697
+ AutomationRunActionStepSchema.strict()
33698
+ ];
33699
+ /**
33700
+ * A plain step: a flow step with no condition of its own and no step inside
33701
+ * it. The second (last) level of nesting holds these only.
33702
+ */
33703
+ var AutomationBranchStepSchema = zod.z.discriminatedUnion("kind", plainStepSchemas, { error: nestTooDeep });
33704
+ var PARALLEL_STEPS_MIN = 2;
33705
+ var PARALLEL_STEPS_MAX = 5;
33706
+ /** A step that can run beside others: it writes no variable and does not end the run. */
33707
+ 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");
33708
+ /**
33709
+ * Several steps at once (#500): all are started together and all are awaited.
33710
+ * A failure fails the run once the others finished, as in a sequence; a member
33711
+ * marked "continue if this fails" does not.
33712
+ */
33713
+ var AutomationParallelStepSchema = zod.z.object({
33714
+ kind: zod.z.literal("parallel"),
33715
+ steps: zod.z.array(AutomationParallelMemberSchema).min(2, "a parallel needs at least two steps").max(5, `a parallel takes at most 5 steps`)
33716
+ }).strict();
33717
+ var REPEAT_COUNT_MAX = 20;
33718
+ var REPEAT_ITERATIONS_MAX = 50;
33719
+ var REPEAT_STEPS_MAX = 10;
33720
+ var REPEAT_DEVICES_MAX = 50;
33721
+ /** The run variable a loop over devices writes before each iteration: the device id. */
33722
+ var REPEAT_ITEM_VAR = "item";
33723
+ var REPEAT_NEEDS_MAX = "a repeat on a condition needs a maximum number of iterations";
33724
+ /** A loop on a condition: the bound is mandatory, so a run never loops without an end. */
33725
+ var repeatConditionShape = {
33726
+ when: AutomationWhenSchema,
33727
+ 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`),
33728
+ /** A pause between two iterations, never after the last. */
33729
+ waitS: zod.z.number().int().min(1).max(WAIT_MAX_SECONDS, WAIT_TOO_LONG).optional()
33730
+ };
33731
+ /** What decides how many times a `repeat` runs. */
33732
+ var AutomationRepeatLoopSchema = zod.z.discriminatedUnion("by", [
33733
+ zod.z.object({
33734
+ by: zod.z.literal("count"),
33735
+ count: zod.z.number().int().min(1).max(20, `a repeat runs at most 20 times`)
33736
+ }).strict(),
33737
+ zod.z.object({
33738
+ by: zod.z.literal("while"),
33739
+ ...repeatConditionShape
33740
+ }).strict(),
33741
+ zod.z.object({
33742
+ by: zod.z.literal("until"),
33743
+ ...repeatConditionShape
33744
+ }).strict(),
33745
+ zod.z.object({
33746
+ by: zod.z.literal("forEach"),
33747
+ target: zod.z.object({
33748
+ kind: zod.z.literal("devices"),
33749
+ 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`)
33750
+ }).strict()
33751
+ }).strict()
33752
+ ]);
33753
+ /**
33754
+ * The same steps several times (#500). Every form is bounded at save, so a
33755
+ * run cannot loop without an end. A failure or a `stop` in the steps ends the
33756
+ * loop and the run, as in a sequence.
33757
+ */
33758
+ function repeatSchemaOf(step) {
33759
+ return zod.z.object({
33760
+ kind: zod.z.literal("repeat"),
33761
+ loop: AutomationRepeatLoopSchema,
33762
+ steps: zod.z.array(step).min(1, "a repeat needs at least one step").max(10, `a repeat takes at most 10 steps`)
33763
+ }).strict();
33764
+ }
33765
+ /**
33766
+ * One step, several ways (#500): the branches are read in order and the FIRST
33767
+ * whose condition is true runs; `else` runs when every branch is false. A
33768
+ * branch that cannot be read ends the choice: nothing runs, not the branches
33769
+ * after it and not the else (D49). The #472 `if` / `else` of a wait or cap
33770
+ * step is the one-branch case and stays as it is stored.
33771
+ */
33772
+ function chooseSchemaOf(step) {
33773
+ const steps = zod.z.array(step).max(10);
33774
+ return zod.z.object({
33775
+ kind: zod.z.literal("choose"),
33776
+ branches: zod.z.array(zod.z.object({
33777
+ if: AutomationWhenSchema,
33778
+ steps: steps.min(1, "a branch needs at least one step")
33779
+ })).min(1, "a choose needs at least one branch").max(6, `a choose takes at most 6 branches`),
33780
+ else: steps.optional()
33781
+ });
33782
+ }
33783
+ var AutomationBodyStepSchema = zod.z.discriminatedUnion("kind", [
33784
+ ...plainStepSchemas,
33785
+ AutomationWaitUntilStepSchema,
33786
+ AutomationParallelStepSchema,
33787
+ chooseSchemaOf(AutomationBranchStepSchema),
33788
+ repeatSchemaOf(AutomationBranchStepSchema)
33789
+ ]);
33790
+ var AutomationRepeatStepSchema = repeatSchemaOf(AutomationBodyStepSchema);
33791
+ var AutomationChooseStepSchema = chooseSchemaOf(AutomationBodyStepSchema);
33550
33792
  var AutomationActionSchema = zod.z.discriminatedUnion("kind", [
33551
33793
  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
- }),
33794
+ AutomationGuardedCapStepSchema,
33795
+ AutomationStopStepSchema,
33796
+ AutomationSetStepSchema,
33797
+ AutomationChooseStepSchema,
33798
+ AutomationWaitUntilStepSchema,
33799
+ AutomationParallelStepSchema,
33800
+ AutomationRepeatStepSchema,
33801
+ AutomationRunActionStepSchema,
33564
33802
  zod.z.object({
33565
33803
  kind: zod.z.literal("code"),
33566
33804
  /** Compiled into the automation's OWN block by esbuild — not a third
@@ -33626,12 +33864,47 @@ function convertLegacyRecipe(legacy) {
33626
33864
  ...rest
33627
33865
  };
33628
33866
  }
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
33867
  var AutomationRecipeSchema = zod.z.union([CurrentAutomationRecipeSchema, LegacyAutomationRecipeSchema.transform(convertLegacyRecipe)]);
33868
+ /** The `if` of a step that can carry one (`action`, `code`, `choose` and `wait-until` steps cannot). */
33869
+ function stepGuardOf(action) {
33870
+ switch (action.kind) {
33871
+ case "action":
33872
+ case "code":
33873
+ case "choose":
33874
+ case "wait-until":
33875
+ case "parallel":
33876
+ case "repeat": return;
33877
+ default: return action.if;
33878
+ }
33879
+ }
33880
+ /** Every condition of a step: its own `if`, or the `if` of each branch of a `choose`. */
33881
+ function stepConditionsOf(action) {
33882
+ const under = (prefix, steps) => steps.flatMap((step, at) => stepConditionsOf(step).map((ref) => ({
33883
+ ...ref,
33884
+ path: `${prefix}.${at}.${ref.path}`
33885
+ })));
33886
+ if (action.kind === "choose") return [...action.branches.flatMap((branch, i) => [{
33887
+ path: `branches.${i}.if`,
33888
+ when: branch.if
33889
+ }, ...under(`branches.${i}.steps`, branch.steps)]), ...under("else", action.else ?? [])];
33890
+ if (action.kind === "wait-until") return [{
33891
+ path: "when",
33892
+ when: action.when
33893
+ }];
33894
+ if (action.kind === "repeat") return [...action.loop.by === "while" || action.loop.by === "until" ? [{
33895
+ path: "loop.when",
33896
+ when: action.loop.when
33897
+ }] : [], ...under("steps", action.steps)];
33898
+ const when = stepGuardOf(action);
33899
+ return when === void 0 ? [] : [{
33900
+ path: "if",
33901
+ when
33902
+ }];
33903
+ }
33904
+ /** Every step a block step holds, at both levels, in the order they are written; none for a plain step. */
33905
+ function nestedStepsOf(action) {
33906
+ 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)]);
33907
+ }
33635
33908
  /** Bounds, shared by `when` and the old names the guards still know. */
33636
33909
  var MAX_CONDITION_DEPTH = 4;
33637
33910
  var MAX_CONDITION_LEAVES = 32;
@@ -33647,9 +33920,8 @@ function validateRecipeBounds(recipe) {
33647
33920
  const ids = new Set(identifiedEventLeaves(recipe.when).map((entry) => entry.id));
33648
33921
  const inRules = triggeredByIssue(recipe.when, ids, "the rules");
33649
33922
  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}`);
33923
+ for (const [index, action] of recipe.actions.entries()) for (const condition of stepConditionsOf(action)) {
33924
+ const issue = triggeredByIssue(condition.when, ids, `step ${index + 1}`);
33653
33925
  if (issue !== null) return issue;
33654
33926
  }
33655
33927
  return null;
@@ -34425,6 +34697,12 @@ function stepMetaOf(action) {
34425
34697
  case "wait": return { kind: "wait" };
34426
34698
  case "code": return { kind: "code" };
34427
34699
  case "action": return { kind: "action" };
34700
+ case "stop": return { kind: "stop" };
34701
+ case "wait-until": return { kind: "wait-until" };
34702
+ case "parallel": return { kind: "parallel" };
34703
+ case "repeat": return { kind: "repeat" };
34704
+ case "set": return { kind: "set" };
34705
+ case "choose": return { kind: "choose" };
34428
34706
  case "cap": {
34429
34707
  const { target, actionId } = normalizeCapStep(action);
34430
34708
  return {
@@ -34645,42 +34923,15 @@ function emitLeaf(trigger, path) {
34645
34923
  }`;
34646
34924
  }
34647
34925
  }
34648
- /** The body of a wait or cap step, shared by a top-level step and an else step. */
34649
- function emitLeafBody(action) {
34926
+ /** What a plain step does when it runs: the body of its `run`, wherever the step sits. */
34927
+ function emitStepBody(action) {
34650
34928
  switch (action.kind) {
34651
34929
  case "wait": return ` await sleep(${j(action.seconds * 1e3)})`;
34652
34930
  case "cap": {
34653
34931
  const { target, actionId } = normalizeCapStep(action);
34654
34932
  return ` await actuateTarget(scope, ${j(target)}, ${j(actionId)}, ${j(action.cap)}, ${j(action.method)}, ${j(action.args ?? {})}, vars)`;
34655
34933
  }
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
34934
+ case "action": return ` // an Action run, awaited: the step takes THAT run's outcome
34684
34935
  const result = await ctx.api.actions.run.mutate({
34685
34936
  actionId: ${j(action.actionId)},
34686
34937
  variables: substituteVariables(${j(action.variables ?? {})}, vars),
@@ -34689,13 +34940,153 @@ ${body}
34689
34940
  })
34690
34941
  if (result.outcome !== 'ran') {
34691
34942
  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
34943
+ }`;
34944
+ case "stop": return ` // end the run here, on purpose: the steps after it are not-run with this reason
34945
+ scope.stop(String(substitute(${j(action.reason)}, vars)), ${j(action.outcome)})`;
34946
+ case "set": return ` // write the run's own bag, for the steps after this one — substitution only
34947
+ Object.assign(vars, substituteVariables(${j(action.vars)}, vars))`;
34948
+ case "code": return ` // inline code action — a fragment of THIS block, bundled by esbuild
34694
34949
  await (async () => {
34695
34950
  ${action.code.split("\n").map((line) => ` ${line}`).join("\n")}
34696
- })()`);
34951
+ })()`;
34697
34952
  }
34698
34953
  }
34954
+ function continues(action) {
34955
+ return (action.kind === "cap" || action.kind === "action") && action.continueOnError === true;
34956
+ }
34957
+ /** Whether the site is inside a block step: the automation's own steps sit at `actions.<n>`. */
34958
+ function isNestedSite(site) {
34959
+ return site.path.split(".").length > 2;
34960
+ }
34961
+ /** A list of steps under `path` (a branch, an else list, the steps of a repeat or a parallel). */
34962
+ function emitList(steps, path) {
34963
+ return steps.map((step, at) => emitStep(step, {
34964
+ meta: j(stepMetaOf(step)),
34965
+ path: `${path}.${at}`
34966
+ })).join("\n");
34967
+ }
34968
+ /** A step's `if` (#472) and its else list, as the fields of a RunnableStep. */
34969
+ function emitGuard(action, site) {
34970
+ const when = stepGuardOf(action);
34971
+ if (when === void 0) return "";
34972
+ const otherwise = emitList(action.kind === "wait" || action.kind === "cap" ? action.else ?? [] : [], `${site.path}.else`);
34973
+ return ` guard: () => evaluateCondition(${j(when)}, ${j(`${site.path}.if`)}, vars),${otherwise === "" ? "" : `\n otherwise: [\n${otherwise}\n],`}
34974
+ `;
34975
+ }
34976
+ /** A `choose` step: its branches, each a condition and a list, and its else list. */
34977
+ function emitChoose(action, site) {
34978
+ const branches = action.branches.map((branch, b) => ` {
34979
+ guard: () => evaluateCondition(${j(branch.if)}, ${j(`${site.path}.branches.${b}.if`)}, vars),
34980
+ steps: [
34981
+ ${emitList(branch.steps, `${site.path}.branches.${b}.steps`)}
34982
+ ],
34983
+ },`).join("\n");
34984
+ const otherwise = emitList(action.else ?? [], `${site.path}.else`);
34985
+ return ` {
34986
+ meta: ${site.meta},
34987
+ // a choose step: the runner reads the branches in order and runs the first that is true
34988
+ run: async () => {},
34989
+ choose: {
34990
+ branches: [
34991
+ ${branches}
34992
+ ],${otherwise === "" ? "" : `\n otherwise: [\n${otherwise}\n],`}
34993
+ },
34994
+ },`;
34995
+ }
34996
+ /** The devices whose report can change a tree's answer; null when one is named by a stable id (any report wakes it). */
34997
+ function wakeDevicesOf(when) {
34998
+ const ids = [];
34999
+ for (const source of collectWhenMirrorSources(when)) {
35000
+ if (source.kind !== "device") return null;
35001
+ if (!ids.includes(source.deviceId)) ids.push(source.deviceId);
35002
+ }
35003
+ return ids;
35004
+ }
35005
+ /** A `wait-until` step: read the condition, wait for a wake, read again, until the timeout. */
35006
+ function emitWaitUntil(action, site) {
35007
+ const onTimeout = action.onTimeout === "stop" ? `scope.stop(message, 'failed')` : "scope.markTimedOut(message)";
35008
+ return ` {
35009
+ meta: ${site.meta},
35010
+ run: async (scope) => {
35011
+ // woken by a report of one of its devices, by the reconcile tick, or by a restart
35012
+ const waited = await waitUntil({
35013
+ read: () => evaluateCondition(${j(action.when)}, ${j(`${site.path}.when`)}, vars),
35014
+ timeoutMs: ${j(action.timeoutS * 1e3)},
35015
+ now: () => Date.now(),
35016
+ isAborted: () => token.aborted,
35017
+ nextWake: (ms) => waitForWake(ms, token, ${j(wakeDevicesOf(action.when))}),
35018
+ })
35019
+ if (waited.result === 'timed-out') {
35020
+ const message = waitTimedOutMessage(${j(action.timeoutS)}, waited.lastReason)
35021
+ ctx.logger.info('wait-until timed out', { step: ${j(site.path)}, onTimeout: ${j(action.onTimeout)}, reason: waited.lastReason })
35022
+ ${onTimeout}
35023
+ }
35024
+ },
35025
+ },`;
35026
+ }
35027
+ /** How a `repeat` decides its iterations, as the fields of a RunnableRepeat. */
35028
+ function emitRepeatLoop(loop, site) {
35029
+ switch (loop.by) {
35030
+ case "count": return `limit: ${j(loop.count)}, limitIsTimeout: false,`;
35031
+ case "forEach": return `// once per device: the device id is in vars.${REPEAT_ITEM_VAR} for the steps of that iteration
35032
+ limit: ${j(loop.target.ids.length)}, limitIsTimeout: false,
35033
+ ...(() => {
35034
+ const ids = ${j(loop.target.ids)}
35035
+ let outer: unknown
35036
+ return {
35037
+ before: async (iteration) => {
35038
+ if (iteration === 0) outer = vars[${j(REPEAT_ITEM_VAR)}]
35039
+ if (iteration < ids.length) vars[${j(REPEAT_ITEM_VAR)}] = ids[iteration]
35040
+ else if (${j(isNestedSite(site))} && outer !== undefined) vars[${j(REPEAT_ITEM_VAR)}] = outer
35041
+ return { go: true }
35042
+ },
35043
+ }
35044
+ })(),`;
35045
+ case "while":
35046
+ case "until": {
35047
+ const read = `repeatCheck(${j(loop.by)}, await evaluateCondition(${j(loop.when)}, ${j(`${site.path}.loop.when`)}, vars))`;
35048
+ const pause = loop.waitS === void 0 ? "" : `\n between: () => sleep(${j(loop.waitS * 1e3)}),`;
35049
+ return `limit: ${j(loop.maxIterations)}, limitIsTimeout: true,
35050
+ ${loop.by === "while" ? "before" : "after"}: async () => ${read},${pause}`;
35051
+ }
35052
+ }
35053
+ }
35054
+ /** One step, wherever it sits: a block step emits its own steps one level down, under its path. */
35055
+ function emitStep(action, site) {
35056
+ if (action.kind === "repeat") return ` {
35057
+ meta: ${site.meta},
35058
+ // a repeat step: the runner runs these once per iteration, under the bound
35059
+ run: async () => {},
35060
+ repeat: {
35061
+ steps: [
35062
+ ${emitList(action.steps, `${site.path}.steps`)}
35063
+ ],
35064
+ ${emitRepeatLoop(action.loop, site)}
35065
+ },
35066
+ },`;
35067
+ if (action.kind === "choose") return emitChoose(action, site);
35068
+ if (action.kind === "wait-until") return emitWaitUntil(action, site);
35069
+ if (action.kind === "parallel") return ` {
35070
+ meta: ${site.meta},
35071
+ // a parallel step: the runner starts these together and awaits them all
35072
+ run: async () => {},
35073
+ parallel: [
35074
+ ${emitList(action.steps, `${site.path}.steps`)}
35075
+ ],
35076
+ },`;
35077
+ return ` {
35078
+ meta: ${site.meta},
35079
+ ${emitGuard(action, site)}${continues(action) ? " continueOnError: true,\n" : ""} run: async (scope) => {
35080
+ ${emitStepBody(action)}
35081
+ },
35082
+ },`;
35083
+ }
35084
+ function emitAction(action, index) {
35085
+ return emitStep(action, {
35086
+ meta: `STEP_META[${index}]!`,
35087
+ path: `actions.${index}`
35088
+ });
35089
+ }
34699
35090
  /**
34700
35091
  * Compile a recipe to the TypeScript of a core block.
34701
35092
  *
@@ -34709,12 +35100,18 @@ function generateAutomationBlock(input) {
34709
35100
  const { name, recipe } = input;
34710
35101
  const runMode = recipe.runMode ?? { mode: "single" };
34711
35102
  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));
35103
+ const elseSteps = (a) => a.kind === "wait" || a.kind === "cap" ? a.else ?? [] : [];
35104
+ const hasDomainTarget = recipe.actions.flatMap((a) => [
35105
+ a,
35106
+ ...elseSteps(a),
35107
+ ...nestedStepsOf(a)
35108
+ ]).some((a) => a.kind === "cap" && normalizeCapStep(a).target.kind === "domain");
35109
+ const guardHoldTrees = recipe.actions.flatMap((a, i) => stepConditionsOf(a).flatMap(({ path, when }) => hasHoldLeaves(when) ? [{
35110
+ path: `actions.${i}.${path}`,
35111
+ when
35112
+ }] : []));
35113
+ const hasTime = hasTimeLeaves(recipe.when) || recipe.actions.some((a) => stepConditionsOf(a).some(({ when }) => hasTimeLeaves(when)));
35114
+ const hasWaitUntil = recipe.actions.some((a) => a.kind === "wait-until" || nestedStepsOf(a).some((n) => n.kind === "wait-until"));
34718
35115
  const eventLeaves = [];
34719
35116
  forEachLeaf(recipe.when, (leaf, path) => {
34720
35117
  if (isEventLeaf(leaf)) eventLeaves.push({
@@ -34763,6 +35160,9 @@ import {
34763
35160
  runForDevices,
34764
35161
  evaluateStepCondition,
34765
35162
  runSteps,
35163
+ repeatCheck,
35164
+ waitUntil,
35165
+ waitTimedOutMessage,
34766
35166
  siteFor,
34767
35167
  validateTimeSpecForSite,
34768
35168
  zoneOnlySite,
@@ -34890,7 +35290,8 @@ ${hasTime ? ` /** The site clock a \`time-is\` leaf reads: memory only at evalu
34890
35290
 
34891
35291
  interface RunToken {
34892
35292
  aborted: boolean
34893
- wake?: () => void
35293
+ /** What cuts short whatever the run is paused on; several at once inside a \`parallel\`. */
35294
+ readonly wakes: Set<() => void>
34894
35295
  }
34895
35296
  interface QueuedRun {
34896
35297
  readonly trigger: Record<string, unknown>
@@ -34901,11 +35302,29 @@ ${hasTime ? ` /** The site clock a \`time-is\` leaf reads: memory only at evalu
34901
35302
  /** Sleep that a restart can cut short. */
34902
35303
  const abortableSleep = (ms: number, token: RunToken): Promise<void> =>
34903
35304
  new Promise((resolve) => {
34904
- const timer = setTimeout(resolve, ms)
34905
- token.wake = () => {
35305
+ const done = (): void => {
34906
35306
  clearTimeout(timer)
35307
+ token.wakes.delete(done)
34907
35308
  resolve()
34908
35309
  }
35310
+ const timer = setTimeout(done, ms)
35311
+ token.wakes.add(done)
35312
+ })
35313
+
35314
+ /** The runs paused on a \`wait-until\`, each with the devices whose report wakes it (null = any). */
35315
+ const stateWaiters = new Map<() => void, readonly number[] | null>()
35316
+ /** Resolve at a report of one of \`deviceIds\`, at the reconcile tick, at a restart, or after \`ms\`. */
35317
+ const waitForWake = (ms: number, token: RunToken, deviceIds: readonly number[] | null): Promise<void> =>
35318
+ new Promise((resolve) => {
35319
+ const done = (): void => {
35320
+ clearTimeout(timer)
35321
+ stateWaiters.delete(done)
35322
+ token.wakes.delete(done)
35323
+ resolve()
35324
+ }
35325
+ const timer = setTimeout(done, Math.min(ms, RECONCILE_MS))
35326
+ stateWaiters.set(done, deviceIds)
35327
+ token.wakes.add(done)
34909
35328
  })
34910
35329
 
34911
35330
  // ── the hub's runs ledger: the stamp is read ONCE here, the ring is written through RPC ──
@@ -35233,6 +35652,13 @@ ${recipe.actions.map((a, i) => emitAction(a, i)).join("\n")}
35233
35652
  error: failure.message,
35234
35653
  })
35235
35654
  },
35655
+ onContinuedFailure: (failure) => {
35656
+ ctx.logger.warn('action failed — continuing, the step is marked to be passed over', {
35657
+ ...(failure.deviceId === undefined ? {} : { tags: { deviceId: failure.deviceId } }),
35658
+ step: failure.index,
35659
+ error: failure.message,
35660
+ })
35661
+ },
35236
35662
  onGuardUnknown: (skipped) => {
35237
35663
  ctx.logger.warn('step skipped — its condition could not be read', {
35238
35664
  ...(skipped.deviceId === undefined ? {} : { tags: { deviceId: skipped.deviceId } }),
@@ -35282,7 +35708,7 @@ ${recipe.actions.map((a, i) => emitAction(a, i)).join("\n")}
35282
35708
  reason: string,
35283
35709
  admission: AutomationRunVerdict,
35284
35710
  ): Promise<void> {
35285
- const token: RunToken = { aborted: false }
35711
+ const token: RunToken = { aborted: false, wakes: new Set() }
35286
35712
  runningTokens.add(token)
35287
35713
  const startedAt = Date.now()
35288
35714
  const runId = newRunId(startedAt)
@@ -35396,7 +35822,7 @@ ${recipe.actions.map((a, i) => emitAction(a, i)).join("\n")}
35396
35822
  ctx.logger.info('automation restarting — ' + admission.reason, deviceTags(trigger))
35397
35823
  for (const running of runningTokens) {
35398
35824
  running.aborted = true
35399
- running.wake?.()
35825
+ for (const wake of [...running.wakes]) wake()
35400
35826
  }
35401
35827
  break
35402
35828
  case 'run':
@@ -35455,6 +35881,16 @@ ${hasTime ? " await refreshSite()\n" : ""} await refreshMirror()
35455
35881
  disposers.push(() => clearInterval(mirrorReconcile))
35456
35882
  }
35457
35883
 
35884
+ ${hasWaitUntil ? ` // a paused run reads its condition again when one of its devices reports
35885
+ disposers.push(
35886
+ ctx.eventBus.subscribe({ category: EventCategory.DeviceStateChanged }, (event) => {
35887
+ const deviceId = event.data['deviceId']
35888
+ for (const [wake, deviceIds] of [...stateWaiters]) {
35889
+ if (deviceIds === null || (typeof deviceId === 'number' && deviceIds.includes(deviceId))) wake()
35890
+ }
35891
+ }),
35892
+ )
35893
+ ` : ""}
35458
35894
  ${eventLeaves.map(({ leaf, path }) => emitLeaf(leaf, path)).join("\n\n")}
35459
35895
 
35460
35896
  return () => {
@@ -35464,7 +35900,7 @@ ${eventLeaves.map(({ leaf, path }) => emitLeaf(leaf, path)).join("\n\n")}
35464
35900
  flushSkip()
35465
35901
  for (const running of runningTokens) {
35466
35902
  running.aborted = true
35467
- running.wake?.()
35903
+ for (const wake of [...running.wakes]) wake()
35468
35904
  }
35469
35905
  for (const dispose of disposers) dispose()
35470
35906
  }
@@ -35809,7 +36245,7 @@ function stepGuardSiteIssues(steps, reading, rootPath) {
35809
36245
  }
35810
36246
  /** The whole recipe: its `when` tree and every step guard. */
35811
36247
  function recipeSiteIssues(recipe, reading) {
35812
- return [...whenSiteIssues(recipe.when, reading), ...stepGuardSiteIssues(recipe.actions, reading, "actions")];
36248
+ return [...whenSiteIssues(recipe.when, reading), ...recipe.actions.flatMap((action, i) => stepConditionsOf(action).flatMap((condition) => whenSiteIssues(condition.when, reading, `actions.${i}.${condition.path}`)))];
35813
36249
  }
35814
36250
  //#endregion
35815
36251
  //#region src/automation/scheduler.ts
@@ -35868,12 +36304,23 @@ var DEFAULT_MAX_HOLD_ATTEMPTS = 3;
35868
36304
  var MAX_HOLD_ATTEMPTS_LIMIT = 20;
35869
36305
  /** A missed edge up to this late still runs. */
35870
36306
  var DEFAULT_MAX_LATE_MS = 10 * 6e4;
36307
+ /**
36308
+ * The longest one `wait` of a scheduler point lasts. A point's steps run in
36309
+ * the scheduler's one serial queue, with no run ceiling: a wait holds every
36310
+ * other scheduler's points for as long as it lasts. An action (one hour) has
36311
+ * its own run and ceiling; a point keeps the five minutes it always had.
36312
+ */
36313
+ var SCHEDULER_WAIT_MAX_SECONDS = 300;
36314
+ var SchedulerStepSchema = ActionStepSchema.refine((step) => step.kind !== "wait" || step.seconds <= 300, {
36315
+ message: `a scheduler point waits at most five minutes (300 s); put a longer wait in an action`,
36316
+ path: ["seconds"]
36317
+ });
35871
36318
  var SchedulerPointSchema = zod.z.object({
35872
36319
  id: zod.z.string().min(1).max(64),
35873
36320
  at: SchedulerTimeSpecSchema,
35874
36321
  mode: SchedulerPointModeSchema,
35875
36322
  /** The actions of an `edge` or `hold`; a `release` has none. */
35876
- steps: zod.z.array(ActionStepSchema).max(20).default([]),
36323
+ steps: zod.z.array(SchedulerStepSchema).max(20).default([]),
35877
36324
  /** Checked when the point runs (an edge) or is applied (a hold). */
35878
36325
  conditions: SchedulerStateTreeSchema.optional(),
35879
36326
  /** Hold only; absent means `respect`. */
@@ -36250,18 +36697,46 @@ var StepTraceBaseSchema = zod.z.object({
36250
36697
  ]).optional(),
36251
36698
  /** Why the condition read what it read, in the evaluator's own words. */
36252
36699
  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. */
36700
+ /** `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
36701
  outcome: zod.z.enum([
36255
36702
  "ok",
36256
36703
  "error",
36257
36704
  "not-run",
36258
36705
  "empty",
36259
- "skipped"
36706
+ "skipped",
36707
+ "failed-continued",
36708
+ "timed-out"
36260
36709
  ]),
36261
36710
  message: zod.z.string().optional()
36262
36711
  });
36712
+ /** What a block step adds to its row: which list ran, what each branch read, how many rounds. */
36713
+ var blockTraceShape = {
36714
+ /** A `choose` step (#500): the list that ran, `branches.<n>` or `else`. Absent when none did. */
36715
+ branch: zod.z.string().optional(),
36716
+ /** A `choose` step: what each branch read, in order, up to the one that decided. */
36717
+ branchChecks: zod.z.array(zod.z.object({
36718
+ condition: zod.z.enum([
36719
+ "true",
36720
+ "false",
36721
+ "unknown"
36722
+ ]),
36723
+ conditionReason: zod.z.string().optional()
36724
+ })).optional(),
36725
+ /** A `repeat` step (#500): how many times its steps ran. */
36726
+ iterations: zod.z.number().int().optional()
36727
+ };
36728
+ /** A step one level down: it may be a block step itself, whose own steps are plain rows (the nesting ends there). */
36729
+ var NestedStepTraceSchema = StepTraceBaseSchema.extend({
36730
+ ...blockTraceShape,
36731
+ steps: zod.z.array(StepTraceBaseSchema).optional()
36732
+ });
36263
36733
  /** 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() });
36734
+ var AutomationStepTraceSchema = StepTraceBaseSchema.extend({
36735
+ else: zod.z.array(StepTraceBaseSchema).optional(),
36736
+ ...blockTraceShape,
36737
+ /** A `choose` step: the steps of the list that ran. A `parallel`: its members. A `repeat`: the LAST iteration. */
36738
+ steps: zod.z.array(NestedStepTraceSchema).optional()
36739
+ });
36265
36740
  var AutomationRunTraceSchema = zod.z.object({
36266
36741
  runId: zod.z.string().min(1),
36267
36742
  startedAt: zod.z.number(),
@@ -36664,6 +37139,46 @@ async function evaluateStepCondition(when, fetchers, now = Date.now, history, si
36664
37139
  }
36665
37140
  //#endregion
36666
37141
  //#region src/automation/step-runner.ts
37142
+ /**
37143
+ * Read the branches in order and stop at the first that decides: `true` runs
37144
+ * it, `unknown` ends the choice with nothing run (D49). All `false` runs the
37145
+ * else list, when there is one.
37146
+ */
37147
+ async function readChoose(choose) {
37148
+ const checks = [];
37149
+ for (const [index, branch] of choose.branches.entries()) {
37150
+ const verdict = await readGuard(branch.guard);
37151
+ checks.push({
37152
+ condition: verdict.result,
37153
+ conditionReason: verdict.reason
37154
+ });
37155
+ if (verdict.result === "true") return {
37156
+ checks,
37157
+ decision: {
37158
+ kind: "run",
37159
+ branch: `branches.${index}`,
37160
+ steps: branch.steps
37161
+ }
37162
+ };
37163
+ if (verdict.result === "unknown") return {
37164
+ checks,
37165
+ decision: {
37166
+ kind: "unknown",
37167
+ index,
37168
+ reason: verdict.reason
37169
+ }
37170
+ };
37171
+ }
37172
+ const otherwise = choose.otherwise ?? [];
37173
+ return {
37174
+ checks,
37175
+ decision: otherwise.length === 0 ? { kind: "none" } : {
37176
+ kind: "run",
37177
+ branch: "else",
37178
+ steps: otherwise
37179
+ }
37180
+ };
37181
+ }
36667
37182
  function errorMessage(err) {
36668
37183
  return err instanceof Error ? err.message : String(err);
36669
37184
  }
@@ -36678,17 +37193,125 @@ async function readGuard(guard) {
36678
37193
  };
36679
37194
  }
36680
37195
  }
37196
+ /**
37197
+ * What a loop's condition says about going on. A `while` goes on while it
37198
+ * reads true, an `until` goes on while it reads false; `unknown` ends either,
37199
+ * with the reason (D49): a loop never runs on a value it could not read.
37200
+ */
37201
+ function repeatCheck(by, verdict) {
37202
+ if (verdict.result === "unknown") return {
37203
+ go: false,
37204
+ reason: `the condition could not be read: ${verdict.reason}`,
37205
+ unknown: true
37206
+ };
37207
+ if (by === "while") return verdict.result === "true" ? { go: true } : {
37208
+ go: false,
37209
+ reason: "the condition is no longer true"
37210
+ };
37211
+ return verdict.result === "true" ? {
37212
+ go: false,
37213
+ reason: "the condition is true"
37214
+ } : { go: true };
37215
+ }
37216
+ /** A loop condition that throws ends the loop as unreadable, never a crash of the run. */
37217
+ async function readRepeatCheck(check, iteration) {
37218
+ if (check === void 0) return { go: true };
37219
+ try {
37220
+ return await check(iteration);
37221
+ } catch (err) {
37222
+ return {
37223
+ go: false,
37224
+ reason: `the condition could not be read: ${errorMessage(err)}`,
37225
+ unknown: true
37226
+ };
37227
+ }
37228
+ }
37229
+ /** Run a loop's steps until its count, its condition, its bound, a failure, a stop or an abort ends it. */
37230
+ async function runRepeat(repeat, options, path) {
37231
+ let iterations = 0;
37232
+ let last;
37233
+ for (;;) {
37234
+ if (options.isAborted()) return {
37235
+ iterations,
37236
+ last,
37237
+ timedOut: false
37238
+ };
37239
+ const before = await readRepeatCheck(repeat.before, iterations);
37240
+ if (!before.go) return {
37241
+ iterations,
37242
+ last,
37243
+ ended: before.reason,
37244
+ timedOut: false,
37245
+ ...before.unknown === true ? { unknown: before.reason } : {}
37246
+ };
37247
+ if (iterations >= repeat.limit) return repeat.limitIsTimeout ? {
37248
+ iterations,
37249
+ last,
37250
+ ended: `stopped at ${repeat.limit} iterations`,
37251
+ timedOut: true
37252
+ } : {
37253
+ iterations,
37254
+ last,
37255
+ ended: "",
37256
+ timedOut: false
37257
+ };
37258
+ last = await runSteps(repeat.steps, {
37259
+ ...options,
37260
+ pathPrefix: `${path}.steps`,
37261
+ indexOffset: 0
37262
+ });
37263
+ iterations += 1;
37264
+ if (last.failed || last.aborted || last.stopped !== void 0) return {
37265
+ iterations,
37266
+ last,
37267
+ timedOut: false
37268
+ };
37269
+ const after = await readRepeatCheck(repeat.after, iterations - 1);
37270
+ if (!after.go) return {
37271
+ iterations,
37272
+ last,
37273
+ ended: after.reason,
37274
+ timedOut: false,
37275
+ ...after.unknown === true ? { unknown: after.reason } : {}
37276
+ };
37277
+ if (repeat.between !== void 0 && iterations < repeat.limit) await repeat.between();
37278
+ }
37279
+ }
36681
37280
  /** The else level of a trace is one level deep: a nested trace carries no `else` of its own. */
36682
37281
  function withoutElse(trace) {
36683
37282
  const { else: _else, ...rest } = trace;
36684
37283
  return rest;
36685
37284
  }
37285
+ /** A plain row: the last level of a trace carries no list of its own. */
37286
+ function plainRow(trace) {
37287
+ const { else: _else, steps: _steps, ...rest } = trace;
37288
+ return rest;
37289
+ }
37290
+ /** A row one level down: it keeps its own steps as plain rows, and no `else`. */
37291
+ function withoutNested(trace) {
37292
+ const { else: _else, steps, ...rest } = trace;
37293
+ return steps === void 0 ? rest : {
37294
+ ...rest,
37295
+ steps: steps.map(plainRow)
37296
+ };
37297
+ }
36686
37298
  async function runSteps(steps, options) {
36687
37299
  const traces = [];
36688
37300
  let failed = false;
36689
37301
  let aborted = false;
36690
- for (const [index, step] of steps.entries()) {
37302
+ let stopped;
37303
+ for (const [position, step] of steps.entries()) {
37304
+ const index = position + (options.indexOffset ?? 0);
36691
37305
  const path = `${options.pathPrefix}.${index}`;
37306
+ if (stopped !== void 0) {
37307
+ traces.push({
37308
+ ...step.meta,
37309
+ path,
37310
+ outcome: "not-run",
37311
+ message: `stopped at ${stopped.path}: ${stopped.reason}`
37312
+ });
37313
+ continue;
37314
+ }
36692
37315
  if (failed || aborted || options.isAborted()) {
36693
37316
  if (!failed) aborted = true;
36694
37317
  traces.push({
@@ -36700,6 +37323,96 @@ async function runSteps(steps, options) {
36700
37323
  continue;
36701
37324
  }
36702
37325
  const startedAt = options.now();
37326
+ if (step.parallel !== void 0) {
37327
+ const members = await Promise.all(step.parallel.map((member, at) => runSteps([member], {
37328
+ ...options,
37329
+ pathPrefix: `${path}.steps`,
37330
+ indexOffset: at
37331
+ })));
37332
+ const anyFailed = members.some((m) => m.failed);
37333
+ if (anyFailed) failed = true;
37334
+ else if (members.some((m) => m.aborted)) aborted = true;
37335
+ traces.push({
37336
+ ...step.meta,
37337
+ path,
37338
+ startedAt,
37339
+ endedAt: options.now(),
37340
+ outcome: anyFailed ? "error" : "ok",
37341
+ ...anyFailed ? { message: "a parallel step failed" } : {},
37342
+ steps: members.flatMap((m) => m.steps.map(withoutNested))
37343
+ });
37344
+ continue;
37345
+ }
37346
+ if (step.repeat !== void 0) {
37347
+ const loop = await runRepeat(step.repeat, options, path);
37348
+ const sub = loop.last;
37349
+ if (loop.unknown !== void 0) options.onGuardUnknown?.({
37350
+ index,
37351
+ path: `${path}.loop.when`,
37352
+ reason: loop.unknown,
37353
+ deviceId: step.meta.deviceId
37354
+ });
37355
+ const bodyFailed = loop.ended === void 0 && sub?.failed === true;
37356
+ if (bodyFailed) failed = true;
37357
+ else if (loop.ended === void 0 && sub?.stopped !== void 0) stopped = sub.stopped;
37358
+ else if (loop.ended === void 0) aborted = true;
37359
+ const times = `ran ${loop.iterations} times`;
37360
+ 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}`;
37361
+ traces.push({
37362
+ ...step.meta,
37363
+ path,
37364
+ startedAt,
37365
+ endedAt: options.now(),
37366
+ outcome: bodyFailed ? "error" : loop.timedOut ? "timed-out" : "ok",
37367
+ message,
37368
+ iterations: loop.iterations,
37369
+ ...sub === void 0 ? {} : { steps: sub.steps.map(withoutNested) }
37370
+ });
37371
+ continue;
37372
+ }
37373
+ if (step.choose !== void 0) {
37374
+ const reading = await readChoose(step.choose);
37375
+ const base = {
37376
+ ...step.meta,
37377
+ path,
37378
+ startedAt,
37379
+ branchChecks: [...reading.checks]
37380
+ };
37381
+ const { decision } = reading;
37382
+ if (decision.kind !== "run") {
37383
+ if (decision.kind === "unknown") options.onGuardUnknown?.({
37384
+ index,
37385
+ path: `${path}.branches.${decision.index}.if`,
37386
+ reason: decision.reason,
37387
+ deviceId: step.meta.deviceId
37388
+ });
37389
+ traces.push({
37390
+ ...base,
37391
+ endedAt: options.now(),
37392
+ outcome: "skipped",
37393
+ message: decision.kind === "unknown" ? `not run: branch ${decision.index + 1} could not be read (${decision.reason})` : "not run: no branch is true"
37394
+ });
37395
+ continue;
37396
+ }
37397
+ const listPath = decision.branch === "else" ? `${path}.else` : `${path}.${decision.branch}.steps`;
37398
+ const sub = await runSteps(decision.steps, {
37399
+ ...options,
37400
+ pathPrefix: listPath,
37401
+ indexOffset: 0
37402
+ });
37403
+ if (sub.failed) failed = true;
37404
+ else if (sub.aborted) aborted = true;
37405
+ if (sub.stopped !== void 0) stopped = sub.stopped;
37406
+ traces.push({
37407
+ ...base,
37408
+ endedAt: options.now(),
37409
+ outcome: sub.failed ? "error" : "ok",
37410
+ ...sub.failed ? { message: "a step of the branch failed" } : {},
37411
+ branch: decision.branch,
37412
+ steps: sub.steps.map(withoutNested)
37413
+ });
37414
+ continue;
37415
+ }
36703
37416
  let guardTrace = {};
36704
37417
  if (step.guard !== void 0) {
36705
37418
  const verdict = await readGuard(step.guard);
@@ -36729,10 +37442,12 @@ async function runSteps(steps, options) {
36729
37442
  }
36730
37443
  const sub = await runSteps(branch, {
36731
37444
  ...options,
36732
- pathPrefix: `${path}.else`
37445
+ pathPrefix: `${path}.else`,
37446
+ indexOffset: 0
36733
37447
  });
36734
37448
  if (sub.failed) failed = true;
36735
37449
  else if (sub.aborted) aborted = true;
37450
+ if (sub.stopped !== void 0) stopped = sub.stopped;
36736
37451
  traces.push({
36737
37452
  ...step.meta,
36738
37453
  ...guardTrace,
@@ -36750,6 +37465,7 @@ async function runSteps(steps, options) {
36750
37465
  let sent;
36751
37466
  const perDevice = [];
36752
37467
  let emptyReason;
37468
+ let timedOutReason;
36753
37469
  let templateNotes = [];
36754
37470
  const scope = {
36755
37471
  setDeviceId: (id) => {
@@ -36766,6 +37482,16 @@ async function runSteps(steps, options) {
36766
37482
  },
36767
37483
  setTemplateNotes: (notes) => {
36768
37484
  templateNotes = notes.slice(0, 20);
37485
+ },
37486
+ stop: (reason, outcome) => {
37487
+ stopped = {
37488
+ reason,
37489
+ outcome,
37490
+ path
37491
+ };
37492
+ },
37493
+ markTimedOut: (reason) => {
37494
+ timedOutReason = reason;
36769
37495
  }
36770
37496
  };
36771
37497
  const templatesTrace = () => templateNotes.length === 0 ? {} : { templates: [...templateNotes] };
@@ -36773,6 +37499,29 @@ async function runSteps(steps, options) {
36773
37499
  const devicesTrace = () => perDevice.length === 0 ? {} : { devices: perDevice.slice(0, 200) };
36774
37500
  try {
36775
37501
  await step.run(scope);
37502
+ const stop = (() => stopped)();
37503
+ if (stop !== void 0) {
37504
+ const message = `stopped: ${stop.reason}`;
37505
+ if (stop.outcome === "failed") {
37506
+ failed = true;
37507
+ options.onFailure({
37508
+ index,
37509
+ path,
37510
+ message,
37511
+ deviceId
37512
+ });
37513
+ }
37514
+ traces.push({
37515
+ ...step.meta,
37516
+ ...guardTrace,
37517
+ path,
37518
+ startedAt,
37519
+ endedAt: options.now(),
37520
+ outcome: stop.outcome === "failed" ? "error" : "ok",
37521
+ message
37522
+ });
37523
+ continue;
37524
+ }
36776
37525
  traces.push({
36777
37526
  ...step.meta,
36778
37527
  ...deviceId === void 0 || perDevice.length > 1 ? {} : { deviceId },
@@ -36783,18 +37532,27 @@ async function runSteps(steps, options) {
36783
37532
  path,
36784
37533
  startedAt,
36785
37534
  endedAt: options.now(),
36786
- outcome: emptyReason === void 0 ? "ok" : "empty",
36787
- ...emptyReason === void 0 ? {} : { message: emptyReason }
37535
+ outcome: timedOutReason !== void 0 ? "timed-out" : emptyReason === void 0 ? "ok" : "empty",
37536
+ ...timedOutReason !== void 0 ? { message: timedOutReason } : emptyReason === void 0 ? {} : { message: emptyReason }
36788
37537
  });
36789
37538
  } catch (err) {
36790
- failed = true;
36791
37539
  const message = errorMessage(err);
36792
- options.onFailure({
37540
+ const continued = step.continueOnError === true;
37541
+ if (continued) options.onContinuedFailure?.({
36793
37542
  index,
36794
37543
  path,
36795
37544
  message,
36796
37545
  deviceId
36797
37546
  });
37547
+ else {
37548
+ failed = true;
37549
+ options.onFailure({
37550
+ index,
37551
+ path,
37552
+ message,
37553
+ deviceId
37554
+ });
37555
+ }
36798
37556
  traces.push({
36799
37557
  ...step.meta,
36800
37558
  ...deviceId === void 0 || perDevice.length > 1 ? {} : { deviceId },
@@ -36805,7 +37563,7 @@ async function runSteps(steps, options) {
36805
37563
  path,
36806
37564
  startedAt,
36807
37565
  endedAt: options.now(),
36808
- outcome: "error",
37566
+ outcome: continued ? "failed-continued" : "error",
36809
37567
  message
36810
37568
  });
36811
37569
  }
@@ -36813,7 +37571,8 @@ async function runSteps(steps, options) {
36813
37571
  return {
36814
37572
  steps: traces,
36815
37573
  failed,
36816
- aborted: aborted && !failed
37574
+ aborted: aborted && !failed,
37575
+ ...stopped === void 0 ? {} : { stopped }
36817
37576
  };
36818
37577
  }
36819
37578
  function isVarRef(value) {
@@ -37095,6 +37854,49 @@ function buildActionSteps(steps, vars, deps) {
37095
37854
  });
37096
37855
  }
37097
37856
  //#endregion
37857
+ //#region src/automation/wait-until.ts
37858
+ async function readSafely(read) {
37859
+ try {
37860
+ return await read();
37861
+ } catch (err) {
37862
+ return {
37863
+ result: "unknown",
37864
+ reason: err instanceof Error ? err.message : String(err)
37865
+ };
37866
+ }
37867
+ }
37868
+ async function waitUntil(input) {
37869
+ const startedAt = input.now();
37870
+ const deadline = startedAt + input.timeoutMs;
37871
+ for (;;) {
37872
+ const verdict = await readSafely(input.read);
37873
+ const waitedMs = input.now() - startedAt;
37874
+ if (input.isAborted()) return {
37875
+ result: "aborted",
37876
+ waitedMs
37877
+ };
37878
+ if (verdict.result === "true") return {
37879
+ result: "met",
37880
+ waitedMs
37881
+ };
37882
+ const remaining = deadline - input.now();
37883
+ if (remaining <= 0) return {
37884
+ result: "timed-out",
37885
+ waitedMs,
37886
+ lastReason: verdict.reason
37887
+ };
37888
+ await input.nextWake(remaining);
37889
+ if (input.isAborted()) return {
37890
+ result: "aborted",
37891
+ waitedMs: input.now() - startedAt
37892
+ };
37893
+ }
37894
+ }
37895
+ /** What the run trace says of a wait that ran out. */
37896
+ function waitTimedOutMessage(timeoutS, lastReason) {
37897
+ return `timed out after ${timeoutS} s: ${lastReason}`;
37898
+ }
37899
+ //#endregion
37098
37900
  //#region src/units/quantity-units.ts
37099
37901
  /**
37100
37902
  * Which units a person may pick for a number of a given quantity. The
@@ -38267,7 +39069,9 @@ var AddonHttpRouteSchema = zod.z.object({
38267
39069
  ]).optional(),
38268
39070
  description: zod.z.string().optional(),
38269
39071
  /** The hub limits this route per client address before the handler runs. */
38270
- rateLimit: zod.z.enum(["auth"]).optional()
39072
+ rateLimit: zod.z.enum(["auth"]).optional(),
39073
+ /** Served once per integration instance; the handler reads `instanceId`. */
39074
+ perInstance: zod.z.boolean().optional()
38271
39075
  });
38272
39076
  /**
38273
39077
  * Cross-process route invocation envelope. The hub captures the
@@ -38284,6 +39088,8 @@ var InvokeRequestSchema = zod.z.object({
38284
39088
  query: zod.z.record(zod.z.string(), zod.z.string()),
38285
39089
  body: zod.z.unknown(),
38286
39090
  headers: zod.z.record(zod.z.string(), zod.z.string()),
39091
+ /** The instance the hub resolved for a `perInstance` route. */
39092
+ instanceId: zod.z.string().optional(),
38287
39093
  user: zod.z.object({
38288
39094
  id: zod.z.string(),
38289
39095
  username: zod.z.string(),
@@ -56347,26 +57153,174 @@ var enumSensorCapability = {
56347
57153
  volatileStateFields: ["lastFetchedAt", "timestamp"]
56348
57154
  };
56349
57155
  //#endregion
57156
+ //#region src/capabilities/event-vocabulary.ts
57157
+ /**
57158
+ * The declared vocabulary of an `event-emitter` device (D1044): what the
57159
+ * device can fire, named for a person and typed for a rule.
57160
+ *
57161
+ * `id` is the native token, verbatim. `kind` is the meaning shared by every
57162
+ * integration, so "any long press" can be asked without knowing a vendor's
57163
+ * token. A device with several buttons declares one entry per button and
57164
+ * token: an entry is identified by its token AND its source.
57165
+ */
57166
+ /** The cross-integration meaning of an event. */
57167
+ var EVENT_VOCABULARY_KINDS = [
57168
+ "press",
57169
+ "long-press",
57170
+ "long-press-start",
57171
+ "release",
57172
+ "repeat",
57173
+ "double-press",
57174
+ "other"
57175
+ ];
57176
+ var EventVocabularyKindSchema = zod.z.enum(EVENT_VOCABULARY_KINDS);
57177
+ /** The part of the device an event comes from: a button, a channel. */
57178
+ var EventVocabularySourceSchema = zod.z.object({
57179
+ id: zod.z.string().min(1),
57180
+ label: zod.z.string().min(1)
57181
+ });
57182
+ /** One scalar field of an event's `data`, by dotted path. */
57183
+ var EventVocabularyFieldSchema = zod.z.object({
57184
+ path: zod.z.string().min(1),
57185
+ kind: zod.z.enum([
57186
+ "string",
57187
+ "number",
57188
+ "boolean",
57189
+ "enum"
57190
+ ]),
57191
+ enumValues: zod.z.array(zod.z.string()).optional(),
57192
+ label: zod.z.string().min(1).optional()
57193
+ });
57194
+ var EventVocabularyEntrySchema = zod.z.object({
57195
+ /** The native token, verbatim. */
57196
+ id: zod.z.string().min(1),
57197
+ source: EventVocabularySourceSchema.optional(),
57198
+ label: zod.z.string().min(1),
57199
+ description: zod.z.string().optional(),
57200
+ kind: EventVocabularyKindSchema.optional(),
57201
+ payload: zod.z.array(EventVocabularyFieldSchema).optional()
57202
+ });
57203
+ /**
57204
+ * The vocabulary of a source that declares tokens and nothing else: one
57205
+ * entry per token, labelled with the token itself.
57206
+ */
57207
+ function plainEventVocabulary(eventTypes) {
57208
+ return [...new Set(eventTypes)].filter((eventType) => eventType !== "").map((eventType) => ({
57209
+ id: eventType,
57210
+ label: eventType
57211
+ }));
57212
+ }
57213
+ /**
57214
+ * Tokens many integrations use for a button, by their normalised spelling
57215
+ * (lower case, words joined by `_`). Exact matches only: a token that
57216
+ * merely contains one of these words gets no kind.
57217
+ */
57218
+ var CONVENTIONAL_KINDS = {
57219
+ press: "press",
57220
+ pressed: "press",
57221
+ single: "press",
57222
+ single_press: "press",
57223
+ single_click: "press",
57224
+ short_press: "press",
57225
+ press_short: "press",
57226
+ click: "press",
57227
+ initial_press: "press",
57228
+ long_press: "long-press",
57229
+ press_long: "long-press",
57230
+ long_click: "long-press",
57231
+ hold: "long-press",
57232
+ long_press_start: "long-press-start",
57233
+ press_long_start: "long-press-start",
57234
+ release: "release",
57235
+ released: "release",
57236
+ long_release: "release",
57237
+ long_press_release: "release",
57238
+ press_long_release: "release",
57239
+ short_release: "release",
57240
+ repeat: "repeat",
57241
+ hold_repeat: "repeat",
57242
+ press_cont: "repeat",
57243
+ double_press: "double-press",
57244
+ double_click: "double-press",
57245
+ double: "double-press",
57246
+ multi_press_2: "double-press"
57247
+ };
57248
+ function normalisedToken(token) {
57249
+ return token.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
57250
+ }
57251
+ function readableToken(token) {
57252
+ const words = normalisedToken(token).replace(/_/g, " ");
57253
+ if (words === "") return token;
57254
+ return `${words.charAt(0).toUpperCase()}${words.slice(1)}`;
57255
+ }
57256
+ /**
57257
+ * The vocabulary of a source that declares tokens only, read by convention:
57258
+ * a readable label, and the shared kind when the token is one many
57259
+ * integrations use for a button. The token itself is kept verbatim.
57260
+ */
57261
+ function conventionalEventVocabulary(eventTypes) {
57262
+ return plainEventVocabulary(eventTypes).map((entry) => {
57263
+ const kind = CONVENTIONAL_KINDS[normalisedToken(entry.id)];
57264
+ const label = readableToken(entry.id);
57265
+ return kind === void 0 ? {
57266
+ id: entry.id,
57267
+ label
57268
+ } : {
57269
+ id: entry.id,
57270
+ label,
57271
+ kind
57272
+ };
57273
+ });
57274
+ }
57275
+ /** The native tokens of a vocabulary, each once, in declaration order. */
57276
+ function eventTypesOfVocabulary(vocabulary) {
57277
+ return [...new Set(vocabulary.map((entry) => entry.id))];
57278
+ }
57279
+ /**
57280
+ * The vocabulary to show and match against. A status with none declared
57281
+ * answers with its plain tokens, so an older provider is still usable.
57282
+ */
57283
+ function readEventVocabulary(status) {
57284
+ const declared = status.vocabulary;
57285
+ if (declared !== void 0 && declared.length > 0) return declared;
57286
+ return plainEventVocabulary(status.eventTypes);
57287
+ }
57288
+ /** The entry a fire belongs to: same token, same source (or both without one). */
57289
+ function findVocabularyEntry(vocabulary, eventType, sourceId) {
57290
+ return vocabulary.find((entry) => entry.id === eventType && entry.source?.id === sourceId);
57291
+ }
57292
+ //#endregion
56350
57293
  //#region src/capabilities/event-emitter.cap.ts
56351
57294
  /**
56352
57295
  * Generic stateless event emitter. Installed on a `DeviceType.EventEmitter`
56353
57296
  * device. Carries the device's EXACT declared event vocabulary verbatim
56354
57297
  * (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`
57298
+ * - structured source (HA `event.*` entity) → `vocabulary` is the fixed
57299
+ * declared set (e.g. press_short, press_long, …).
57300
+ * - generic/legacy source (HA bus events, e.g. zha_event) → `vocabulary`
56358
57301
  * is [] (open) and `lastEvent.data` carries the complex payload.
57302
+ * `vocabulary` (D1044) names each event for a person and types it for a
57303
+ * rule; `eventTypes` is its list of native tokens, kept for older readers.
57304
+ * A fire names the part of the device it came from in `sourceId` when the
57305
+ * vocabulary declares sources (a remote's buttons).
56359
57306
  * `seq` is monotonic so two identical events still produce distinct slice writes.
56360
57307
  */
56361
57308
  var EventFireSchema = zod.z.object({
56362
57309
  deviceId: zod.z.number(),
56363
57310
  eventType: zod.z.string(),
57311
+ sourceId: zod.z.string().optional(),
56364
57312
  data: zod.z.record(zod.z.string(), zod.z.unknown()).nullable(),
56365
57313
  timestamp: zod.z.number().meta(require_sleep.readingMeta("none")),
56366
57314
  seq: zod.z.number().meta(require_sleep.readingMeta("count"))
56367
57315
  });
56368
57316
  var EventEmitterStatusSchema = zod.z.object({
56369
57317
  eventTypes: zod.z.array(zod.z.string()),
57318
+ /**
57319
+ * Required of a provider by the type. A status written before the field
57320
+ * existed still parses, as an empty vocabulary: read it through
57321
+ * `readEventVocabulary`, which then answers with the plain tokens.
57322
+ */
57323
+ vocabulary: zod.z.array(EventVocabularyEntrySchema).default([]),
56370
57324
  lastEvent: EventFireSchema.nullable(),
56371
57325
  eventCountSinceStart: zod.z.number().meta(require_sleep.readingMeta("count"))
56372
57326
  });
@@ -77240,7 +78194,18 @@ var OauthIntegrationDescriptorSchema = zod.z.object({
77240
78194
  * The value is baked into the authorization code at `/authorize` and travels
77241
78195
  * on the tokens, so editing this field changes FUTURE links only.
77242
78196
  */
77243
- refreshTokenTtlSec: zod.z.union([zod.z.number().int().positive(), zod.z.literal("never")]).optional()
78197
+ refreshTokenTtlSec: zod.z.union([zod.z.number().int().positive(), zod.z.literal("never")]).optional(),
78198
+ /**
78199
+ * The integration instances an account can be linked to (planning#415),
78200
+ * beside the default one. `/api/oauth2/authorize?instance=<id>` is accepted
78201
+ * only for an id listed here; with no `instance=` the link is made to the
78202
+ * default instance, which is never listed and always accepted — it is the
78203
+ * address third parties already hold. Omit for a single-instance integration.
78204
+ */
78205
+ instances: zod.z.array(zod.z.object({
78206
+ id: zod.z.string(),
78207
+ displayName: zod.z.string()
78208
+ })).optional()
77244
78209
  });
77245
78210
  var oauthIntegrationCapability = {
77246
78211
  name: "oauth-integration",
@@ -87495,6 +88460,13 @@ var SsoBridgeClaimsSchema = zod.z.object({
87495
88460
  /** OAuth authorization-code binding — set only on `oauth-code` tokens. */
87496
88461
  redirectUri: zod.z.string().optional(),
87497
88462
  integrationId: zod.z.string().optional(),
88463
+ /**
88464
+ * The integration INSTANCE an OAuth link was made for (planning#415). Set on
88465
+ * `oauth-code`, `oauth-access` and `oauth-refresh` tokens of a link made
88466
+ * with `instance=`; absent on a link to the default instance. A cloud relay
88467
+ * reads it off the access token to route; the hub answers from the session.
88468
+ */
88469
+ instanceId: zod.z.string().optional(),
87498
88470
  /** JWT ID — unique per issued code; consumed-set enforces single-use. */
87499
88471
  jti: zod.z.string().optional(),
87500
88472
  /** PKCE S256 challenge — set only on `oauth-code` tokens issued to a public
@@ -90556,6 +91528,8 @@ var OauthSessionSummarySchema = zod.z.object({
90556
91528
  userId: zod.z.string(),
90557
91529
  username: zod.z.string(),
90558
91530
  integrationId: zod.z.string(),
91531
+ /** The instance the link was made for; `null` = the default instance. */
91532
+ instanceId: zod.z.string().nullable().optional(),
90559
91533
  scopes: zod.z.array(TokenScopeSchema),
90560
91534
  createdAt: zod.z.number(),
90561
91535
  lastUsedAt: zod.z.number(),
@@ -90684,6 +91658,9 @@ var userManagementCapability = {
90684
91658
  }),
90685
91659
  oauthIssueCode: require_sleep.method(zod.z.object({
90686
91660
  integrationId: zod.z.string(),
91661
+ /** The integration instance the link is for. Omit for the default
91662
+ * instance — never pass the addon id to mean it. */
91663
+ instanceId: zod.z.string().optional(),
90687
91664
  userId: zod.z.string(),
90688
91665
  username: zod.z.string(),
90689
91666
  scopes: zod.z.array(TokenScopeSchema),
@@ -90725,7 +91702,13 @@ var userManagementCapability = {
90725
91702
  oauthVerifyAccessToken: require_sleep.method(zod.z.object({ token: zod.z.string() }), zod.z.object({
90726
91703
  userId: zod.z.string(),
90727
91704
  username: zod.z.string(),
90728
- scopes: zod.z.array(TokenScopeSchema)
91705
+ scopes: zod.z.array(TokenScopeSchema),
91706
+ /** The instance the link was made for, read from the SESSION.
91707
+ * Absent = the default instance. `oauthLinkServesInstance` is the
91708
+ * helper a per-instance route calls to compare it with the instance
91709
+ * of its path; no route declares `perInstance` yet (the Alexa
91710
+ * per-instance route, T3, is the first consumer). */
91711
+ instanceId: zod.z.string().optional()
90729
91712
  }).nullable(), { access: "view" }),
90730
91713
  listExternalIdentities: require_sleep.method(zod.z.object({ userId: zod.z.string() }), zod.z.array(ExternalIdentitySchema), { auth: "admin" }),
90731
91714
  /** The user an identity is linked to, or `null`. */
@@ -137696,18 +138679,25 @@ exports.AutoTuneWarningSchema = AutoTuneWarningSchema;
137696
138679
  exports.AutoUpdateSettingsSchema = AutoUpdateSettingsSchema;
137697
138680
  exports.AutomationActionSchema = AutomationActionSchema;
137698
138681
  exports.AutomationCapStepSchema = AutomationCapStepSchema;
138682
+ exports.AutomationChooseStepSchema = AutomationChooseStepSchema;
137699
138683
  exports.AutomationConditionOperatorSchema = AutomationConditionOperatorSchema;
137700
138684
  exports.AutomationConditionTraceNodeSchema = AutomationConditionTraceNodeSchema;
137701
138685
  exports.AutomationControlStatusSchema = AutomationControlStatusSchema;
138686
+ exports.AutomationParallelStepSchema = AutomationParallelStepSchema;
137702
138687
  exports.AutomationRecipeSchema = AutomationRecipeSchema;
138688
+ exports.AutomationRepeatLoopSchema = AutomationRepeatLoopSchema;
138689
+ exports.AutomationRepeatStepSchema = AutomationRepeatStepSchema;
137703
138690
  exports.AutomationRunModeSchema = AutomationRunModeSchema;
137704
138691
  exports.AutomationRunOutcomeSchema = AutomationRunOutcomeSchema;
137705
138692
  exports.AutomationRunTraceSchema = AutomationRunTraceSchema;
137706
138693
  exports.AutomationRunVerdictSchema = AutomationRunVerdictSchema;
138694
+ exports.AutomationSetStepSchema = AutomationSetStepSchema;
137707
138695
  exports.AutomationStateDocSchema = AutomationStateDocSchema;
137708
138696
  exports.AutomationStepTraceSchema = AutomationStepTraceSchema;
138697
+ exports.AutomationStopStepSchema = AutomationStopStepSchema;
137709
138698
  exports.AutomationTriggerTraceSchema = AutomationTriggerTraceSchema;
137710
138699
  exports.AutomationWaitStepSchema = AutomationWaitStepSchema;
138700
+ exports.AutomationWaitUntilStepSchema = AutomationWaitUntilStepSchema;
137711
138701
  exports.AutomationWhenSchema = AutomationWhenSchema;
137712
138702
  exports.AvailableIntegrationTypeSchema = AvailableIntegrationTypeSchema;
137713
138703
  exports.BASE_DEVICE_CAPS = BASE_DEVICE_CAPS;
@@ -137785,6 +138775,7 @@ exports.CAP_RUNTIME_FIELD_UNITS = CAP_RUNTIME_FIELD_UNITS;
137785
138775
  exports.CAP_VOCABULARY = require_sleep.CAP_VOCABULARY;
137786
138776
  exports.CAP_VOCABULARY_BY_NAME = require_sleep.CAP_VOCABULARY_BY_NAME;
137787
138777
  exports.CATALOG_LANGS = CATALOG_LANGS;
138778
+ exports.CHOOSE_BRANCHES_MAX = CHOOSE_BRANCHES_MAX;
137788
138779
  exports.CIVIL_TWILIGHT_ALTITUDE_DEG = CIVIL_TWILIGHT_ALTITUDE_DEG;
137789
138780
  exports.CLASS_MAP_MACRO_TARGETS = CLASS_MAP_MACRO_TARGETS;
137790
138781
  exports.CLIMATE_ROLES = CLIMATE_ROLES;
@@ -138287,6 +139278,7 @@ exports.EVENT_LEAF_ID_RE = EVENT_LEAF_ID_RE;
138287
139278
  exports.EVENT_OWNER_TYPES = EVENT_OWNER_TYPES;
138288
139279
  exports.EVENT_PAD_MS = EVENT_PAD_MS;
138289
139280
  exports.EVENT_TAXONOMY = EVENT_TAXONOMY;
139281
+ exports.EVENT_VOCABULARY_KINDS = EVENT_VOCABULARY_KINDS;
138290
139282
  exports.EXPORT_DENSE_MAX_RANGES = EXPORT_DENSE_MAX_RANGES;
138291
139283
  exports.EXPORT_INSTANCE_UNKNOWN = EXPORT_INSTANCE_UNKNOWN;
138292
139284
  exports.EXPRESSION_BUILTINS = require_implemented_methods.EXPRESSION_BUILTINS;
@@ -138341,6 +139333,10 @@ exports.EventMediaKindSchema = EventMediaKindSchema;
138341
139333
  exports.EventMediaProductionSchema = EventMediaProductionSchema;
138342
139334
  exports.EventOwnerTypeSchema = EventOwnerTypeSchema;
138343
139335
  exports.EventSourceType = require_enums.EventSourceType$1;
139336
+ exports.EventVocabularyEntrySchema = EventVocabularyEntrySchema;
139337
+ exports.EventVocabularyFieldSchema = EventVocabularyFieldSchema;
139338
+ exports.EventVocabularyKindSchema = EventVocabularyKindSchema;
139339
+ exports.EventVocabularySourceSchema = EventVocabularySourceSchema;
138344
139340
  exports.ExportBytesSchema = ExportBytesSchema;
138345
139341
  exports.ExportClipSubjectSchema = ExportClipSubjectSchema;
138346
139342
  exports.ExportDenseRangeSchema = ExportDenseRangeSchema;
@@ -139192,6 +140188,8 @@ exports.PALETTE_MIN_CONTRAST = PALETTE_MIN_CONTRAST;
139192
140188
  exports.PALETTE_MIN_DELTA_E = PALETTE_MIN_DELTA_E;
139193
140189
  exports.PALETTE_MIN_DELTA_E_MARK = PALETTE_MIN_DELTA_E_MARK;
139194
140190
  exports.PALETTE_PRESET_IDS = PALETTE_PRESET_IDS;
140191
+ exports.PARALLEL_STEPS_MAX = PARALLEL_STEPS_MAX;
140192
+ exports.PARALLEL_STEPS_MIN = PARALLEL_STEPS_MIN;
139195
140193
  exports.PAUSE_MAX_MS = PAUSE_MAX_MS;
139196
140194
  exports.PEER_BYTES_CHUNK_BYTES = require_sleep.PEER_BYTES_CHUNK_BYTES;
139197
140195
  exports.PEER_BYTES_MAX_OUTSTANDING = require_sleep.PEER_BYTES_MAX_OUTSTANDING;
@@ -139379,8 +140377,14 @@ exports.REMOTE_WIDGET_ROLES = REMOTE_WIDGET_ROLES;
139379
140377
  exports.REMOVAL_RECONCILE_INTERVAL_MS = REMOVAL_RECONCILE_INTERVAL_MS;
139380
140378
  exports.REMOVED_MODEL_IDS = REMOVED_MODEL_IDS;
139381
140379
  exports.REMOVE_LEAF = require_sleep.REMOVE_LEAF;
140380
+ exports.REPEAT_COUNT_MAX = REPEAT_COUNT_MAX;
140381
+ exports.REPEAT_DEVICES_MAX = REPEAT_DEVICES_MAX;
140382
+ exports.REPEAT_ITEM_VAR = REPEAT_ITEM_VAR;
140383
+ exports.REPEAT_ITERATIONS_MAX = REPEAT_ITERATIONS_MAX;
140384
+ exports.REPEAT_STEPS_MAX = REPEAT_STEPS_MAX;
139382
140385
  exports.RESERVED_BINDING_NAMES = require_implemented_methods.RESERVED_BINDING_NAMES;
139383
140386
  exports.RESERVED_COLLECTION_SOURCES = RESERVED_COLLECTION_SOURCES;
140387
+ exports.RESERVED_RUN_VARS = RESERVED_RUN_VARS;
139384
140388
  exports.RESET_PERIODS = require_implemented_methods.RESET_PERIODS;
139385
140389
  exports.RESTORED_CAP_NAMES = RESTORED_CAP_NAMES;
139386
140390
  exports.RESTREAM_INPUT_PROBE = require_implemented_methods.RESTREAM_INPUT_PROBE;
@@ -139614,6 +140618,7 @@ exports.SCENE_DEFAULT_QUIET_SECONDS = SCENE_DEFAULT_QUIET_SECONDS;
139614
140618
  exports.SCENE_DEFAULT_UNCOVERED_POLICY = SCENE_DEFAULT_UNCOVERED_POLICY;
139615
140619
  exports.SCENE_DIVERGED = SCENE_DIVERGED;
139616
140620
  exports.SCENE_RESET_RECAPTURES = SCENE_RESET_RECAPTURES;
140621
+ exports.SCHEDULER_WAIT_MAX_SECONDS = SCHEDULER_WAIT_MAX_SECONDS;
139617
140622
  exports.SCOPED_SETTINGS_SCOPES = require_sleep.SCOPED_SETTINGS_SCOPES;
139618
140623
  exports.SCOPE_PRESETS = SCOPE_PRESETS;
139619
140624
  exports.SECRET_CLEAR = require_sleep.SECRET_CLEAR;
@@ -139627,6 +140632,9 @@ exports.SERVER_NAME_MAX_LENGTH = SERVER_NAME_MAX_LENGTH;
139627
140632
  exports.SERVER_NAME_SETTING_KEY = SERVER_NAME_SETTING_KEY;
139628
140633
  exports.SESSION_LOST_ALERT_CATEGORY = SESSION_LOST_ALERT_CATEGORY;
139629
140634
  exports.SESSION_PLACEMENT_SETTING_KEY = SESSION_PLACEMENT_SETTING_KEY;
140635
+ exports.SET_VARS_MAX = SET_VARS_MAX;
140636
+ exports.SET_VAR_NAME_RE = SET_VAR_NAME_RE;
140637
+ exports.SET_VAR_VALUE_MAX = SET_VAR_VALUE_MAX;
139630
140638
  exports.SHARE_AFFINITY_TOLERANCE_SESSIONS = SHARE_AFFINITY_TOLERANCE_SESSIONS;
139631
140639
  exports.SHARE_SOURCE_SETTING_KEY = SHARE_SOURCE_SETTING_KEY;
139632
140640
  exports.SHARE_VIEW_KINDS = require_sleep.SHARE_VIEW_KINDS;
@@ -139654,6 +140662,8 @@ exports.STATE_LABEL_KEYS = STATE_LABEL_KEYS;
139654
140662
  exports.STATIONARY_OVERLAY_STYLE = STATIONARY_OVERLAY_STYLE;
139655
140663
  exports.STATISTIC_STATS = require_implemented_methods.STATISTIC_STATS;
139656
140664
  exports.STEP_DEVICE_CONCURRENCY = STEP_DEVICE_CONCURRENCY;
140665
+ exports.STEP_NEST_MAX = STEP_NEST_MAX;
140666
+ exports.STOP_REASON_MAX = STOP_REASON_MAX;
139657
140667
  exports.STORAGE_ACCESS_FALLBACK = STORAGE_ACCESS_FALLBACK;
139658
140668
  exports.STORAGE_BYTES_PER_GB = STORAGE_BYTES_PER_GB;
139659
140669
  exports.STORAGE_LOCATION_MODES = STORAGE_LOCATION_MODES;
@@ -140013,6 +141023,8 @@ exports.VideoEncodeSchema = VideoEncodeSchema;
140013
141023
  exports.ViewerDeviceAllowSchema = ViewerDeviceAllowSchema;
140014
141024
  exports.ViewerFeatureIdSchema = ViewerFeatureIdSchema;
140015
141025
  exports.ViewerTokenScopeSchema = ViewerTokenScopeSchema;
141026
+ exports.WAIT_MAX_SECONDS = WAIT_MAX_SECONDS;
141027
+ exports.WAIT_UNTIL_TIMEOUT_MAX_S = WAIT_UNTIL_TIMEOUT_MAX_S;
140016
141028
  exports.WEBRTC_CLIMB_HOLD_CODES = WEBRTC_CLIMB_HOLD_CODES;
140017
141029
  exports.WEBRTC_EGRESS_PROFILE = WEBRTC_EGRESS_PROFILE;
140018
141030
  exports.WEBRTC_TRY_BLOCKERS = WEBRTC_TRY_BLOCKERS;
@@ -140310,6 +141322,7 @@ exports.consumablesCapability = consumablesCapability;
140310
141322
  exports.contactCapability = contactCapability;
140311
141323
  exports.containingParentIndex = containingParentIndex;
140312
141324
  exports.controlCapability = controlCapability;
141325
+ exports.conventionalEventVocabulary = conventionalEventVocabulary;
140313
141326
  exports.convertLegacyCondition = convertLegacyCondition;
140314
141327
  exports.convertLegacyRecipe = convertLegacyRecipe;
140315
141328
  exports.convertLegacyWhen = convertLegacyWhen;
@@ -140498,6 +141511,7 @@ exports.eventEmitterCapability = eventEmitterCapability;
140498
141511
  exports.eventKindLabel = eventKindLabel;
140499
141512
  exports.eventLeafIdAt = eventLeafIdAt;
140500
141513
  exports.eventOverlapsClipWindow = eventOverlapsClipWindow;
141514
+ exports.eventTypesOfVocabulary = eventTypesOfVocabulary;
140501
141515
  exports.evictionPolicyForMode = evictionPolicyForMode;
140502
141516
  exports.evictionPolicyOfLocation = evictionPolicyOfLocation;
140503
141517
  exports.expandAudioChunkToF32le = require_sleep.expandAudioChunkToF32le;
@@ -140542,6 +141556,7 @@ exports.findCompositionCycles = findCompositionCycles;
140542
141556
  exports.findMigrationsBlocked = require_sleep.findMigrationsBlocked;
140543
141557
  exports.findTimezone = findTimezone;
140544
141558
  exports.findVocabAction = require_sleep.findVocabAction;
141559
+ exports.findVocabularyEntry = findVocabularyEntry;
140545
141560
  exports.flattenNestedRecords = flattenNestedRecords;
140546
141561
  exports.flattenPortsOver = flattenPortsOver;
140547
141562
  exports.flipperIrDraft = flipperIrDraft;
@@ -140657,6 +141672,7 @@ exports.invertPresetFeature = invertPresetFeature;
140657
141672
  exports.invocationFromEncodeProfile = require_implemented_methods.invocationFromEncodeProfile;
140658
141673
  exports.irSourceProblem = irSourceProblem;
140659
141674
  exports.irTransmitterCapability = irTransmitterCapability;
141675
+ exports.isAddonInstanceId = isAddonInstanceId;
140660
141676
  exports.isAgentOnlyPlacement = isAgentOnlyPlacement;
140661
141677
  exports.isAirConditioner = isAirConditioner;
140662
141678
  exports.isAlarmControllableCap = isAlarmControllableCap;
@@ -140869,6 +141885,7 @@ exports.nativeObjectDetectionCapability = nativeObjectDetectionCapability;
140869
141885
  exports.navigationCapability = navigationCapability;
140870
141886
  exports.ncAlarmSystemDefaultSettings = ncAlarmSystemDefaultSettings;
140871
141887
  exports.ncMediaPolicyError = ncMediaPolicyError;
141888
+ exports.nestedStepsOf = nestedStepsOf;
140872
141889
  exports.networkAccessCapability = networkAccessCapability;
140873
141890
  exports.networkLinkCapability = networkLinkCapability;
140874
141891
  exports.networkQualityCapability = networkQualityCapability;
@@ -140908,6 +141925,8 @@ exports.notifierCapability = notifierCapability;
140908
141925
  exports.numericSensorCapability = numericSensorCapability;
140909
141926
  exports.oauthIntegrationCapability = oauthIntegrationCapability;
140910
141927
  exports.oauthLandingUrl = oauthLandingUrl;
141928
+ exports.oauthLinkInstanceId = oauthLinkInstanceId;
141929
+ exports.oauthLinkServesInstance = oauthLinkServesInstance;
140911
141930
  exports.objectInputDeclaresAddonId = objectInputDeclaresAddonId;
140912
141931
  exports.objectInputDeclaresRequiredDeviceId = objectInputDeclaresRequiredDeviceId;
140913
141932
  exports.observeHoldLeaves = observeHoldLeaves;
@@ -140989,6 +142008,7 @@ exports.pipelineAnalyticsCapability = pipelineAnalyticsCapability;
140989
142008
  exports.pipelineExecutorCapability = pipelineExecutorCapability;
140990
142009
  exports.pipelineOrchestratorCapability = pipelineOrchestratorCapability;
140991
142010
  exports.pipelineRunnerCapability = pipelineRunnerCapability;
142011
+ exports.plainEventVocabulary = plainEventVocabulary;
140992
142012
  exports.planComposition = planComposition;
140993
142013
  exports.planCompositionEvents = planCompositionEvents;
140994
142014
  exports.planItems = planItems;
@@ -141047,6 +142067,7 @@ exports.readCommandOrigin = require_sleep.readCommandOrigin;
141047
142067
  exports.readDetailCropConvention = readDetailCropConvention;
141048
142068
  exports.readDeviceStateFrom = readDeviceStateFrom;
141049
142069
  exports.readErrorI18n = require_sleep.readErrorI18n;
142070
+ exports.readEventVocabulary = readEventVocabulary;
141050
142071
  exports.readFaceRescoreIntervalMinutes = readFaceRescoreIntervalMinutes;
141051
142072
  exports.readHubMotionDetected = readHubMotionDetected;
141052
142073
  exports.readHubMotionStatus = readHubMotionStatus;
@@ -141100,6 +142121,7 @@ exports.removeGroup = removeGroup;
141100
142121
  exports.removeScalarTarget = removeScalarTarget;
141101
142122
  exports.renameAlarmProfile = renameAlarmProfile;
141102
142123
  exports.renderVocabPhrase = renderVocabPhrase;
142124
+ exports.repeatCheck = repeatCheck;
141103
142125
  exports.replacedFieldKeys = replacedFieldKeys;
141104
142126
  exports.replayDwellIntervals = replayDwellIntervals;
141105
142127
  exports.reportIsScalable = reportIsScalable;
@@ -141303,6 +142325,8 @@ exports.stateVocabularyFor = stateVocabularyFor;
141303
142325
  exports.statisticCadenceMs = require_implemented_methods.statisticCadenceMs;
141304
142326
  exports.statisticDraft = statisticDraft;
141305
142327
  exports.statusInstanceOf = statusInstanceOf;
142328
+ exports.stepConditionsOf = stepConditionsOf;
142329
+ exports.stepGuardOf = stepGuardOf;
141306
142330
  exports.stepGuardSiteIssues = stepGuardSiteIssues;
141307
142331
  exports.stepModelRunsOnFormat = stepModelRunsOnFormat;
141308
142332
  exports.stepPulse = stepPulse;
@@ -141451,6 +142475,8 @@ exports.viewerUiCapability = require_sleep.viewerUiCapability;
141451
142475
  exports.vocabActionIdFor = require_sleep.vocabActionIdFor;
141452
142476
  exports.vocabularyActionsForDevice = actionsForDevice$1;
141453
142477
  exports.vocabularyTriggersForDevice = triggersForDevice;
142478
+ exports.waitTimedOutMessage = waitTimedOutMessage;
142479
+ exports.waitUntil = waitUntil;
141454
142480
  exports.waterHeaterCapability = waterHeaterCapability;
141455
142481
  exports.wattMillisecondsToKwh = require_implemented_methods.wattMillisecondsToKwh;
141456
142482
  exports.weatherCapability = weatherCapability;