@camstack/server 1.2.857 → 1.2.858

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 (94) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/api/trpc/generated-cap-mounts.js +2 -1
  3. package/dist/api/trpc/generated-cap-routers.js +15 -1
  4. package/dist/core/addon/instance-links.service.js +6 -2
  5. package/package.json +15 -11
  6. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  7. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  8. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  9. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  10. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  11. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  12. package/system/dist/builtins/autotrack/index.js +1 -1
  13. package/system/dist/builtins/autotrack/index.mjs +1 -1
  14. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  15. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  16. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  17. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  18. package/system/dist/builtins/camera-grid/index.js +1 -1
  19. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  20. package/system/dist/builtins/composer/composer.addon.js +4 -4
  21. package/system/dist/builtins/composer/composer.addon.mjs +4 -4
  22. package/system/dist/builtins/console-logging/index.js +1 -1
  23. package/system/dist/builtins/console-logging/index.mjs +1 -1
  24. package/system/dist/builtins/core-blocks/automation-template-instances.d.ts +38 -0
  25. package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +6 -0
  26. package/system/dist/builtins/core-blocks/core-blocks.addon.js +227 -21
  27. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +227 -21
  28. package/system/dist/builtins/core-blocks/remote-wiring.d.ts +3 -0
  29. package/system/dist/builtins/core-blocks/templates-service.d.ts +11 -0
  30. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  31. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  32. package/system/dist/builtins/device-manager/device-manager.addon.js +2 -2
  33. package/system/dist/builtins/device-manager/device-manager.addon.mjs +2 -2
  34. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  35. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  36. package/system/dist/builtins/keychain/index.js +4 -4
  37. package/system/dist/builtins/keychain/index.mjs +4 -4
  38. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  39. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  40. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  41. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  42. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  43. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  44. package/system/dist/builtins/loki-logging/index.js +1 -1
  45. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  46. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  47. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  48. package/system/dist/builtins/platform-probe/index.js +1 -1
  49. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  50. package/system/dist/builtins/record-entries/index.js +1 -1
  51. package/system/dist/builtins/record-entries/index.mjs +1 -1
  52. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  53. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  54. package/system/dist/builtins/snapshot/index.js +1 -1
  55. package/system/dist/builtins/snapshot/index.mjs +1 -1
  56. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  57. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  58. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  59. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  60. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  61. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  62. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  63. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  64. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  65. package/system/dist/builtins/system-config/system-config.addon.mjs +3 -3
  66. package/system/dist/builtins/winston-logging/index.js +1 -1
  67. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  68. package/system/dist/{capture-engine-BpTIydES.mjs → capture-engine-B4_fq2JB.mjs} +1 -1
  69. package/system/dist/{capture-engine-OjKUSU7_.js → capture-engine-yhFFC7F8.js} +1 -1
  70. package/system/dist/{composition-sources-eLYlvnnR.mjs → composition-sources-BQOEYCJG.mjs} +1 -1
  71. package/system/dist/{composition-sources-WroUQ4J-.js → composition-sources-CKSSe5ny.js} +1 -1
  72. package/system/dist/{constants-B8nWtzwq.js → constants-dfnEfsX7.js} +1 -1
  73. package/system/dist/{constants-DO33IJ7k.mjs → constants-h8wJE_8O.mjs} +1 -1
  74. package/system/dist/{device-ca-EtzHeETW.js → device-ca-_o0-3jJ6.js} +1 -1
  75. package/system/dist/{device-ca-BOquIg22.mjs → device-ca-h54CenJx.mjs} +1 -1
  76. package/system/dist/{dist-n0kCY8sq.js → dist-WEGVb8qV.js} +2961 -64
  77. package/system/dist/{dist-7eN_r5dA.mjs → dist-atHH8IeD.mjs} +2902 -65
  78. package/system/dist/file-host-worker.js +1 -1
  79. package/system/dist/file-host-worker.mjs +1 -1
  80. package/system/dist/{hub-identity-C_6dgozE.mjs → hub-identity-DLF698tj.mjs} +1 -1
  81. package/system/dist/{hub-identity-Cz0pt7Ho.js → hub-identity-nIMYA24i.js} +1 -1
  82. package/system/dist/{hub-mdns-ciao-CmGrhCgY.js → hub-mdns-ciao-B6ZHStt1.js} +2 -2
  83. package/system/dist/{hub-mdns-ciao-CdHseQBh.mjs → hub-mdns-ciao-DchpUVAk.mjs} +2 -2
  84. package/system/dist/index.js +12 -8
  85. package/system/dist/index.mjs +12 -8
  86. package/system/dist/{legacy-integration-rows-door-Bm1OQy6O.js → legacy-integration-rows-door-BbaIE1qF.js} +1 -1
  87. package/system/dist/{legacy-integration-rows-door-Cnqq1aq-.mjs → legacy-integration-rows-door-DBO3ZLmn.mjs} +1 -1
  88. package/system/dist/{rename-composition-block-CuKj9mH0.mjs → rename-composition-block-6ISzMLgj.mjs} +1 -1
  89. package/system/dist/{rename-composition-block-D82Y4jGp.js → rename-composition-block-IIfaFnEl.js} +1 -1
  90. package/system/dist/{restore-archive-C2kHLNPq.js → restore-archive-ChRNoqGg.js} +1 -1
  91. package/system/dist/{restore-archive-BOnkR2ZT.mjs → restore-archive-DeDRh7Lf.mjs} +1 -1
  92. package/system/dist/{wal-maintenance-Bdrc5v7T.mjs → wal-maintenance-BXj9xnDD.mjs} +0 -0
  93. package/system/dist/{wal-maintenance-CBrmyT6U.js → wal-maintenance-l3CsKEaJ.js} +0 -0
  94. package/system/package.json +1 -1
@@ -812,7 +812,7 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
812
812
  return EventCategory;
813
813
  }({});
814
814
  //#endregion
815
- //#region ../types/dist/composed-stable-id-iddnCQ51.mjs
815
+ //#region ../types/dist/composed-stable-id-B3wcvtvW.mjs
816
816
  /**
817
817
  import { errMsg } from '@camstack/types'
818
818
  * Extract a human-readable message from an unknown error value.
@@ -939,6 +939,10 @@ var DeviceType = /* @__PURE__ */ function(DeviceType) {
939
939
  * water, cooling, solar), its system modes and its power. One main read-only
940
940
  * `heat-pump-status` cap carries all of it; `heat-pump-control` sets it (D1026). */
941
941
  DeviceType["HeatPump"] = "heat-pump";
942
+ /** A home energy installation (any vendor): solar, grid, house, a metered heat pump
943
+ * and the storage as branches of one bus. One read-only `energy-system` cap carries
944
+ * every value; the storage is a field of it, never the `battery` cap (#513, #522). */
945
+ DeviceType["EnergySystem"] = "energy-system";
942
946
  return DeviceType;
943
947
  }({});
944
948
  var DeviceFeature = /* @__PURE__ */ function(DeviceFeature) {
@@ -1257,7 +1261,7 @@ var DeviceRole = /* @__PURE__ */ function(DeviceRole) {
1257
1261
  */
1258
1262
  var COMPOSED_DEVICE_STABLE_ID_PREFIX = "composed-";
1259
1263
  //#endregion
1260
- //#region ../types/dist/sleep-C9PbO6Nb.mjs
1264
+ //#region ../types/dist/sleep-Cykc2bzi.mjs
1261
1265
  /**
1262
1266
  * The audio chunk plane's byte format, and the ONE expansion from a coded
1263
1267
  * window to float samples (D455).
@@ -3132,7 +3136,7 @@ var KeychainWriteRefusedError = class extends Error {
3132
3136
  }
3133
3137
  };
3134
3138
  var KEEP = { kind: "keep" };
3135
- function isRecord$4(value) {
3139
+ function isRecord$4$1(value) {
3136
3140
  return typeof value === "object" && value !== null && !Array.isArray(value);
3137
3141
  }
3138
3142
  function defaultMintId() {
@@ -3145,7 +3149,7 @@ function collectSecretMarkerRefs(value, out = []) {
3145
3149
  return out;
3146
3150
  }
3147
3151
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
3148
- else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
3152
+ else if (isRecord$4$1(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
3149
3153
  return out;
3150
3154
  }
3151
3155
  async function storedValueEquals(secrets, marker, candidate) {
@@ -3200,7 +3204,7 @@ function rowId(row, idKey) {
3200
3204
  return null;
3201
3205
  }
3202
3206
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
3203
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
3207
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4$1) : [];
3204
3208
  if (!Array.isArray(incoming)) {
3205
3209
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
3206
3210
  return {
@@ -3216,7 +3220,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
3216
3220
  const kept = /* @__PURE__ */ new Set();
3217
3221
  const rows = [];
3218
3222
  for (const row of incoming) {
3219
- if (!isRecord$4(row)) {
3223
+ if (!isRecord$4$1(row)) {
3220
3224
  rows.push(row);
3221
3225
  continue;
3222
3226
  }
@@ -3241,7 +3245,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
3241
3245
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
3242
3246
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
3243
3247
  case "object": {
3244
- if (!isRecord$4(incoming)) {
3248
+ if (!isRecord$4$1(incoming)) {
3245
3249
  if (incoming === void 0) return KEEP;
3246
3250
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
3247
3251
  return {
@@ -3249,7 +3253,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
3249
3253
  value: incoming
3250
3254
  };
3251
3255
  }
3252
- const storedObj = isRecord$4(stored) ? stored : {};
3256
+ const storedObj = isRecord$4$1(stored) ? stored : {};
3253
3257
  return {
3254
3258
  kind: "value",
3255
3259
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -3372,7 +3376,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
3372
3376
  value: items
3373
3377
  };
3374
3378
  }
3375
- if (isRecord$4(v)) {
3379
+ if (isRecord$4$1(v)) {
3376
3380
  const out = {};
3377
3381
  for (const [k, child] of Object.entries(v)) {
3378
3382
  const s = substitute(child);
@@ -13648,6 +13652,13 @@ var CAP_VOCABULARY_BY_NAME = {
13648
13652
  }
13649
13653
  ]
13650
13654
  },
13655
+ "energy-system": {
13656
+ scope: "device",
13657
+ noun: {
13658
+ en: "Energy system",
13659
+ it: "Sistema energetico"
13660
+ }
13661
+ },
13651
13662
  "air-quality-sensor": {
13652
13663
  scope: "device",
13653
13664
  noun: {
@@ -15770,6 +15781,7 @@ var CAP_NAMES = Object.freeze([
15770
15781
  "do-not-disturb",
15771
15782
  "doorbell",
15772
15783
  "embedding-encoder",
15784
+ "energy-system",
15773
15785
  "enum-sensor",
15774
15786
  "event-emitter",
15775
15787
  "face-gallery",
@@ -16547,6 +16559,96 @@ Object.freeze({
16547
16559
  "path": "pressCountSinceStart",
16548
16560
  "valueType": "number"
16549
16561
  }],
16562
+ "energy-system": [
16563
+ {
16564
+ "path": "solar.powerW",
16565
+ "valueType": "number"
16566
+ },
16567
+ {
16568
+ "path": "solar.energyKwh",
16569
+ "valueType": "number"
16570
+ },
16571
+ {
16572
+ "path": "solar.todayKwh",
16573
+ "valueType": "number"
16574
+ },
16575
+ {
16576
+ "path": "grid.powerW",
16577
+ "valueType": "number"
16578
+ },
16579
+ {
16580
+ "path": "grid.importKwh",
16581
+ "valueType": "number"
16582
+ },
16583
+ {
16584
+ "path": "grid.exportKwh",
16585
+ "valueType": "number"
16586
+ },
16587
+ {
16588
+ "path": "grid.importTodayKwh",
16589
+ "valueType": "number"
16590
+ },
16591
+ {
16592
+ "path": "grid.exportTodayKwh",
16593
+ "valueType": "number"
16594
+ },
16595
+ {
16596
+ "path": "house.powerW",
16597
+ "valueType": "number"
16598
+ },
16599
+ {
16600
+ "path": "house.energyKwh",
16601
+ "valueType": "number"
16602
+ },
16603
+ {
16604
+ "path": "house.todayKwh",
16605
+ "valueType": "number"
16606
+ },
16607
+ {
16608
+ "path": "heatPump.powerW",
16609
+ "valueType": "number"
16610
+ },
16611
+ {
16612
+ "path": "heatPump.energyKwh",
16613
+ "valueType": "number"
16614
+ },
16615
+ {
16616
+ "path": "heatPump.todayKwh",
16617
+ "valueType": "number"
16618
+ },
16619
+ {
16620
+ "path": "storage.stateOfChargePct",
16621
+ "valueType": "number"
16622
+ },
16623
+ {
16624
+ "path": "storage.storedKwh",
16625
+ "valueType": "number"
16626
+ },
16627
+ {
16628
+ "path": "storage.capacityKwh",
16629
+ "valueType": "number"
16630
+ },
16631
+ {
16632
+ "path": "storage.powerW",
16633
+ "valueType": "number"
16634
+ },
16635
+ {
16636
+ "path": "storage.chargedKwh",
16637
+ "valueType": "number"
16638
+ },
16639
+ {
16640
+ "path": "storage.dischargedKwh",
16641
+ "valueType": "number"
16642
+ },
16643
+ {
16644
+ "path": "storage.chargedTodayKwh",
16645
+ "valueType": "number"
16646
+ },
16647
+ {
16648
+ "path": "storage.dischargedTodayKwh",
16649
+ "valueType": "number"
16650
+ }
16651
+ ],
16550
16652
  "enum-sensor": [{
16551
16653
  "path": "value",
16552
16654
  "valueType": "string"
@@ -18000,7 +18102,7 @@ function sleep(ms) {
18000
18102
  return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
18001
18103
  }
18002
18104
  //#endregion
18003
- //#region ../types/dist/implemented-methods-CSTk6zYK.mjs
18105
+ //#region ../types/dist/implemented-methods-CgUBu6uM.mjs
18004
18106
  var AUDIO_ENCODER_BY_CODEC = {
18005
18107
  opus: "libopus",
18006
18108
  aac: "aac",
@@ -46786,6 +46888,106 @@ var ActionTargetResolver = class {
46786
46888
  };
46787
46889
  }
46788
46890
  };
46891
+ var EventVocabularyKindSchema = zod.z.enum([
46892
+ "press",
46893
+ "long-press",
46894
+ "long-press-start",
46895
+ "release",
46896
+ "repeat",
46897
+ "double-press",
46898
+ "other"
46899
+ ]);
46900
+ /** The part of the device an event comes from: a button, a channel. */
46901
+ var EventVocabularySourceSchema = zod.z.object({
46902
+ id: zod.z.string().min(1),
46903
+ label: zod.z.string().min(1)
46904
+ });
46905
+ /** One scalar field of an event's `data`, by dotted path. */
46906
+ var EventVocabularyFieldSchema = zod.z.object({
46907
+ path: zod.z.string().min(1),
46908
+ kind: zod.z.enum([
46909
+ "string",
46910
+ "number",
46911
+ "boolean",
46912
+ "enum"
46913
+ ]),
46914
+ enumValues: zod.z.array(zod.z.string()).optional(),
46915
+ label: zod.z.string().min(1).optional()
46916
+ });
46917
+ var EventVocabularyEntrySchema = zod.z.object({
46918
+ /** The native token, verbatim. */
46919
+ id: zod.z.string().min(1),
46920
+ source: EventVocabularySourceSchema.optional(),
46921
+ label: zod.z.string().min(1),
46922
+ description: zod.z.string().optional(),
46923
+ kind: EventVocabularyKindSchema.optional(),
46924
+ payload: zod.z.array(EventVocabularyFieldSchema).optional()
46925
+ });
46926
+ /**
46927
+ * The link an automation made FROM a template carries (#527): which template,
46928
+ * the values the operator filled in, and — when the template has since changed
46929
+ * so that those values no longer fit — the problems that say why.
46930
+ *
46931
+ * It lives inside the recipe (`AutomationRecipe.template`), so the one row in
46932
+ * `core_blocks` stays the one artefact: there is no second store of instances
46933
+ * to drift from the blocks, and deleting the automation deletes the link.
46934
+ * "Convert to a free automation" is dropping this field.
46935
+ *
46936
+ * This file depends on nothing in `recipe.ts`, so the recipe can embed it and
46937
+ * the template engine (`template/automation-template.ts`) can import both.
46938
+ */
46939
+ /** An `event` input's value: the same three narrowing lists a `device-fired` row takes. */
46940
+ var TemplateEventValueSchema = zod.z.object({
46941
+ eventIds: zod.z.array(zod.z.string().min(1)).min(1).max(64).optional(),
46942
+ sourceIds: zod.z.array(zod.z.string().min(1)).min(1).max(64).optional(),
46943
+ kinds: zod.z.array(EventVocabularyKindSchema).min(1).optional()
46944
+ }).refine((value) => value.eventIds !== void 0 || value.sourceIds !== void 0 || value.kinds !== void 0, { message: "an event names at least one event, part or kind" });
46945
+ /** An `action` input's value: a vocabulary action and its open args. */
46946
+ var TemplateActionValueSchema = zod.z.object({
46947
+ actionId: zod.z.string().min(1),
46948
+ args: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
46949
+ });
46950
+ /** The value of one non-group input. Which member is right is the input kind's to judge. */
46951
+ var TemplateScalarValueSchema = zod.z.union([
46952
+ zod.z.number(),
46953
+ zod.z.string(),
46954
+ zod.z.boolean(),
46955
+ zod.z.array(zod.z.number().int().nonnegative()),
46956
+ TemplateEventValueSchema,
46957
+ TemplateActionValueSchema
46958
+ ]);
46959
+ /** One row of a repeatable group: row-input key → value. */
46960
+ var TemplateGroupRowSchema = zod.z.record(zod.z.string(), TemplateScalarValueSchema);
46961
+ var TemplateInputValueSchema = zod.z.union([TemplateScalarValueSchema, zod.z.array(TemplateGroupRowSchema)]);
46962
+ /** Input key → value. */
46963
+ var TemplateInputValuesSchema = zod.z.record(zod.z.string(), TemplateInputValueSchema);
46964
+ var TemplateInstanceProblemSchema = zod.z.object({
46965
+ code: zod.z.enum([
46966
+ "missing-input",
46967
+ "invalid-input",
46968
+ "invalid-recipe",
46969
+ "missing-template",
46970
+ "edited-by-hand"
46971
+ ]),
46972
+ /** Dotted input address (`buttons.2.targets`); absent for a whole-recipe problem. */
46973
+ input: zod.z.string().optional(),
46974
+ detail: zod.z.string()
46975
+ });
46976
+ var AutomationTemplateLinkSchema = zod.z.object({
46977
+ templateId: zod.z.string().min(1),
46978
+ values: TemplateInputValuesSchema,
46979
+ /**
46980
+ * Fingerprint of the generated code with this literal blanked
46981
+ * (`instanceCodeHash`), stamped by `generateAutomationBlock`. Code that no
46982
+ * longer matches it was edited by hand, and is never regenerated over.
46983
+ */
46984
+ codeHash: zod.z.string().optional(),
46985
+ /**
46986
+ * Present when the last re-expansion refused these values. The automation
46987
+ * keeps running the body of its last good expansion; nothing is dropped.
46988
+ */
46989
+ problems: zod.z.array(TemplateInstanceProblemSchema).min(1).optional()
46990
+ });
46789
46991
  /**
46790
46992
  * What an expression's named bindings READ from.
46791
46993
  *
@@ -47444,41 +47646,6 @@ function anySubjectMatches(subjects, observed) {
47444
47646
  reason: subjects.length === 1 ? lastReason : `none of [${subjects.map(describeSubject).join(", ")}] matches (${observed.className || "unknown"})`
47445
47647
  };
47446
47648
  }
47447
- var EventVocabularyKindSchema = zod.z.enum([
47448
- "press",
47449
- "long-press",
47450
- "long-press-start",
47451
- "release",
47452
- "repeat",
47453
- "double-press",
47454
- "other"
47455
- ]);
47456
- /** The part of the device an event comes from: a button, a channel. */
47457
- var EventVocabularySourceSchema = zod.z.object({
47458
- id: zod.z.string().min(1),
47459
- label: zod.z.string().min(1)
47460
- });
47461
- /** One scalar field of an event's `data`, by dotted path. */
47462
- var EventVocabularyFieldSchema = zod.z.object({
47463
- path: zod.z.string().min(1),
47464
- kind: zod.z.enum([
47465
- "string",
47466
- "number",
47467
- "boolean",
47468
- "enum"
47469
- ]),
47470
- enumValues: zod.z.array(zod.z.string()).optional(),
47471
- label: zod.z.string().min(1).optional()
47472
- });
47473
- var EventVocabularyEntrySchema = zod.z.object({
47474
- /** The native token, verbatim. */
47475
- id: zod.z.string().min(1),
47476
- source: EventVocabularySourceSchema.optional(),
47477
- label: zod.z.string().min(1),
47478
- description: zod.z.string().optional(),
47479
- kind: EventVocabularyKindSchema.optional(),
47480
- payload: zod.z.array(EventVocabularyFieldSchema).optional()
47481
- });
47482
47649
  /**
47483
47650
  * Where the sun is, from a latitude and a longitude — the one solar
47484
47651
  * calculation in the repo. Compact NOAA sunrise equation (accurate to about a
@@ -47807,6 +47974,17 @@ var HoldTraceSchema = zod.z.object({
47807
47974
  /** When it completes (ms epoch), for a pending hold. */
47808
47975
  deadline: zod.z.number().optional()
47809
47976
  });
47977
+ /**
47978
+ * The ONE reader of a leaf's hold. A leaf stored before #498 carries `forMs`
47979
+ * (a `held` window); it reads as `for: { ms, mode: 'held' }`. `0` is no hold.
47980
+ */
47981
+ function holdOf(leaf) {
47982
+ if (leaf.for !== void 0) return leaf.for;
47983
+ if (leaf.forMs !== void 0 && leaf.forMs > 0) return {
47984
+ ms: leaf.forMs,
47985
+ mode: "held"
47986
+ };
47987
+ }
47810
47988
  /** `30 s`, `5 min`, `1 h 5 min` — a hold window for a human. */
47811
47989
  function describeHoldMs(ms) {
47812
47990
  const s = Math.round(ms / 1e3);
@@ -48206,6 +48384,20 @@ function hasTriggeredByLeaves(when) {
48206
48384
  }
48207
48385
  /** Why a `triggered-by` leaf is refused outside an automation: there is no trigger row to name. */
48208
48386
  var TRIGGERED_BY_NEEDS_AUTOMATION = "\"triggered by\" reads which trigger started an automation — an action or a scheduler has no trigger rows, so it could never be true here";
48387
+ /**
48388
+ * What is wrong with the `triggered-by` leaves of `tree`, given the ids the
48389
+ * automation's event leaves carry: an id nothing carries can never be true.
48390
+ * `where` names the tree in the message (`the rules`, `step 2`).
48391
+ */
48392
+ function triggeredByIssue(tree, knownIds, where) {
48393
+ let issue = null;
48394
+ forEachLeaf(tree, (leaf) => {
48395
+ if (issue !== null || leaf.kind !== "triggered-by") return;
48396
+ const missing = leaf.leafIds.find((id) => !knownIds.has(id));
48397
+ if (missing !== void 0) issue = `${where}: "triggered by" names the trigger "${missing}", and no trigger row of this automation has that id — pick one of its trigger rows`;
48398
+ });
48399
+ return issue;
48400
+ }
48209
48401
  function hasEmptyContainer(node) {
48210
48402
  if (isLeaf(node)) return false;
48211
48403
  if (node.kind === "not") return hasEmptyContainer(node.child);
@@ -48670,6 +48862,8 @@ var AutomationParallelStepSchema = zod.z.object({
48670
48862
  kind: zod.z.literal("parallel"),
48671
48863
  steps: zod.z.array(AutomationParallelMemberSchema).min(2, "a parallel needs at least two steps").max(5, `a parallel takes at most 5 steps`)
48672
48864
  }).strict();
48865
+ /** The run variable a loop over devices writes before each iteration: the device id. */
48866
+ var REPEAT_ITEM_VAR = "item";
48673
48867
  var REPEAT_NEEDS_MAX = "a repeat on a condition needs a maximum number of iterations";
48674
48868
  /** A loop on a condition: the bound is mandatory, so a run never loops without an end. */
48675
48869
  var repeatConditionShape = {
@@ -48790,7 +48984,13 @@ var CurrentAutomationRecipeSchema = zod.z.object({
48790
48984
  actions: zod.z.array(AutomationActionSchema),
48791
48985
  runMode: AutomationRunModeSchema.optional(),
48792
48986
  /** How many run traces the automation keeps (default {@link DEFAULT_TRACE_KEEP}). */
48793
- keepTraces: zod.z.number().int().min(1).max(100).optional()
48987
+ keepTraces: zod.z.number().int().min(1).max(100).optional(),
48988
+ /**
48989
+ * Set when the automation was made from a template (#527): the template and
48990
+ * the values filled in. The rest of the recipe is then the expansion, which
48991
+ * the template engine rewrites when the template changes.
48992
+ */
48993
+ template: AutomationTemplateLinkSchema.optional()
48794
48994
  });
48795
48995
  /** A recipe as it was stored before the single tree. Read-only: nothing writes this. */
48796
48996
  var LegacyAutomationRecipeSchema = zod.z.object({
@@ -48812,6 +49012,64 @@ function convertLegacyRecipe(legacy) {
48812
49012
  };
48813
49013
  }
48814
49014
  var AutomationRecipeSchema = zod.z.union([CurrentAutomationRecipeSchema, LegacyAutomationRecipeSchema.transform(convertLegacyRecipe)]);
49015
+ /** The `if` of a step that can carry one (`action`, `code`, `choose` and `wait-until` steps cannot). */
49016
+ function stepGuardOf(action) {
49017
+ switch (action.kind) {
49018
+ case "action":
49019
+ case "code":
49020
+ case "choose":
49021
+ case "wait-until":
49022
+ case "parallel":
49023
+ case "repeat": return;
49024
+ default: return action.if;
49025
+ }
49026
+ }
49027
+ /** Every condition of a step: its own `if`, or the `if` of each branch of a `choose`. */
49028
+ function stepConditionsOf(action) {
49029
+ const under = (prefix, steps) => steps.flatMap((step, at) => stepConditionsOf(step).map((ref) => ({
49030
+ ...ref,
49031
+ path: `${prefix}.${at}.${ref.path}`
49032
+ })));
49033
+ if (action.kind === "choose") return [...action.branches.flatMap((branch, i) => [{
49034
+ path: `branches.${i}.if`,
49035
+ when: branch.if
49036
+ }, ...under(`branches.${i}.steps`, branch.steps)]), ...under("else", action.else ?? [])];
49037
+ if (action.kind === "wait-until") return [{
49038
+ path: "when",
49039
+ when: action.when
49040
+ }];
49041
+ if (action.kind === "repeat") return [...action.loop.by === "while" || action.loop.by === "until" ? [{
49042
+ path: "loop.when",
49043
+ when: action.loop.when
49044
+ }] : [], ...under("steps", action.steps)];
49045
+ const when = stepGuardOf(action);
49046
+ return when === void 0 ? [] : [{
49047
+ path: "if",
49048
+ when
49049
+ }];
49050
+ }
49051
+ /** Every step a block step holds, at both levels, in the order they are written; none for a plain step. */
49052
+ function nestedStepsOf(action) {
49053
+ 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)]);
49054
+ }
49055
+ /**
49056
+ * Author-time check. Returns `null` when the recipe is legal, else a message
49057
+ * naming what is wrong — the editor shows it verbatim, so it has to read like
49058
+ * something an operator can act on.
49059
+ */
49060
+ function validateRecipeBounds(recipe) {
49061
+ if (recipe.actions.length === 0) return "an automation needs at least one action — a rule that does nothing is not a rule";
49062
+ const tree = validateWhenTree(recipe.when);
49063
+ if (tree !== null) return tree;
49064
+ const ids = new Set(identifiedEventLeaves(recipe.when).map((entry) => entry.id));
49065
+ const inRules = triggeredByIssue(recipe.when, ids, "the rules");
49066
+ if (inRules !== null) return inRules;
49067
+ for (const [index, action] of recipe.actions.entries()) for (const condition of stepConditionsOf(action)) {
49068
+ const issue = triggeredByIssue(condition.when, ids, `step ${index + 1}`);
49069
+ if (issue !== null) return issue;
49070
+ }
49071
+ return null;
49072
+ }
48815
49073
  /**
48816
49074
  * Save-time check of a `when` tree against the SITE: a `time-is` window
48817
49075
  * bounded by a sun event needs the site location, and any window needs a known
@@ -50774,6 +51032,111 @@ function evaluateWhenTree(when, reader, now, options = {}) {
50774
51032
  ...state.timeDueInMs === void 0 ? {} : { timeDueInMs: state.timeDueInMs }
50775
51033
  };
50776
51034
  }
51035
+ /** Does any state leaf of the tree carry a `for`? */
51036
+ function hasHoldLeaves(when) {
51037
+ let found = false;
51038
+ forEachLeaf(when, (leaf) => {
51039
+ if ((leaf.kind === "device-is" || leaf.kind === "expression") && leaf.for !== void 0) found = true;
51040
+ });
51041
+ return found;
51042
+ }
51043
+ /**
51044
+ * Reads the `AUTOMATION_RECIPE` literal `generateAutomationBlock` embeds in a
51045
+ * block's code — parsed as JSON, never evaluated — for code that runs where the
51046
+ * admin UI's reader does not (the hub re-expanding template instances, #527).
51047
+ *
51048
+ * A brace scan, not a regex: the recipe nests. Strings are tracked so a `}`
51049
+ * inside a device name cannot close the object early; the value is
51050
+ * `JSON.stringify` output, so `"` is the only quote that can open one.
51051
+ */
51052
+ /** The declaration the generator emits, matched whole. */
51053
+ var AUTOMATION_RECIPE_DECLARATION = "const AUTOMATION_RECIPE =";
51054
+ /** The JSON text of the literal, or null when the code declares none. */
51055
+ function findRecipeLiteralJson(code) {
51056
+ const declStart = code.indexOf(AUTOMATION_RECIPE_DECLARATION);
51057
+ if (declStart < 0) return null;
51058
+ const start = code.indexOf("{", declStart + 25);
51059
+ if (start < 0) return null;
51060
+ let depth = 0;
51061
+ let inString = false;
51062
+ let escaped = false;
51063
+ for (let i = start; i < code.length; i += 1) {
51064
+ const ch = code.charAt(i);
51065
+ if (inString) {
51066
+ if (escaped) escaped = false;
51067
+ else if (ch === "\\") escaped = true;
51068
+ else if (ch === "\"") inString = false;
51069
+ continue;
51070
+ }
51071
+ if (ch === "\"") {
51072
+ inString = true;
51073
+ continue;
51074
+ }
51075
+ if (ch === "{") depth += 1;
51076
+ else if (ch === "}") {
51077
+ depth -= 1;
51078
+ if (depth === 0) return code.slice(start, i + 1);
51079
+ }
51080
+ }
51081
+ return null;
51082
+ }
51083
+ function readRecipeLiteral(code) {
51084
+ const json = findRecipeLiteralJson(code);
51085
+ if (json === null) return { status: "none" };
51086
+ let raw;
51087
+ try {
51088
+ raw = JSON.parse(json);
51089
+ } catch (error) {
51090
+ return {
51091
+ status: "invalid",
51092
+ detail: error instanceof Error ? error.message : String(error)
51093
+ };
51094
+ }
51095
+ const parsed = AutomationRecipeSchema.safeParse(raw);
51096
+ if (parsed.success) return {
51097
+ status: "recipe",
51098
+ recipe: parsed.data
51099
+ };
51100
+ const first = parsed.error.issues[0];
51101
+ return {
51102
+ status: "invalid",
51103
+ detail: first === void 0 ? "not a recipe" : `${first.path.join(".")}: ${first.message}`
51104
+ };
51105
+ }
51106
+ /** Where the literal's JSON sits in the code, or null when there is none. */
51107
+ function literalSpan(code) {
51108
+ const json = findRecipeLiteralJson(code);
51109
+ if (json === null) return null;
51110
+ const start = code.indexOf(json, code.indexOf(AUTOMATION_RECIPE_DECLARATION));
51111
+ return {
51112
+ start,
51113
+ end: start + json.length
51114
+ };
51115
+ }
51116
+ /** FNV-1a, 32 bit, hex: a fingerprint, not a security boundary. */
51117
+ function fnv1a(text) {
51118
+ let hash = 2166136261;
51119
+ for (let i = 0; i < text.length; i += 1) {
51120
+ hash ^= text.charCodeAt(i);
51121
+ hash = Math.imul(hash, 16777619) >>> 0;
51122
+ }
51123
+ return hash.toString(16).padStart(8, "0");
51124
+ }
51125
+ /**
51126
+ * The fingerprint of a block's code with its recipe literal blanked, so the
51127
+ * hash a literal carries does not change the hash. Null when there is no literal.
51128
+ */
51129
+ function instanceCodeHash(code) {
51130
+ const span = literalSpan(code);
51131
+ if (span === null) return null;
51132
+ return fnv1a(`${code.slice(0, span.start)}{}${code.slice(span.end)}`);
51133
+ }
51134
+ /** The same code with only its recipe literal replaced; everything else is kept byte for byte. */
51135
+ function replaceRecipeLiteral(code, recipe) {
51136
+ const span = literalSpan(code);
51137
+ if (span === null) return null;
51138
+ return `${code.slice(0, span.start)}${JSON.stringify(recipe, null, 2)}${code.slice(span.end)}`;
51139
+ }
50777
51140
  var DETECTION_DESCRIPTIONS = {
50778
51141
  deviceId: "the camera that saw it",
50779
51142
  className: "what it saw",
@@ -50809,16 +51172,1324 @@ function describe$1(descriptions) {
50809
51172
  description
50810
51173
  }));
50811
51174
  }
50812
- describe$1(DETECTION_DESCRIPTIONS);
50813
- describe$1(STATIONARY_DESCRIPTIONS);
50814
- describe$1(FIRED_DESCRIPTIONS).map((v) => v.name === "deviceId" ? {
51175
+ var DETECTION_VARIABLES = describe$1(DETECTION_DESCRIPTIONS);
51176
+ var STATIONARY_VARIABLES = describe$1(STATIONARY_DESCRIPTIONS);
51177
+ var FIRED_VARIABLES = describe$1(FIRED_DESCRIPTIONS).map((v) => v.name === "deviceId" ? {
50815
51178
  ...v,
50816
51179
  hintKey: "firedDeviceId"
50817
51180
  } : v);
50818
- describe$1(BECOMES_DESCRIPTIONS).map((v) => v.name === "deviceId" ? {
51181
+ var BECOMES_VARIABLES = describe$1(BECOMES_DESCRIPTIONS).map((v) => v.name === "deviceId" ? {
50819
51182
  ...v,
50820
51183
  hintKey: "becomesDeviceId"
50821
51184
  } : v);
51185
+ /** What one event row kind provides; kinds that provide none are absent. */
51186
+ function triggerLeafVariables(kind) {
51187
+ if (kind === "detection") return DETECTION_VARIABLES;
51188
+ if (kind === "stationary") return STATIONARY_VARIABLES;
51189
+ if (kind === "device-becomes") return BECOMES_VARIABLES;
51190
+ if (kind === "device-fired") return FIRED_VARIABLES;
51191
+ return [];
51192
+ }
51193
+ /** How often the state mirror is re-read as the backstop for a dropped event
51194
+ * (D8: an event WAKES the evaluation, the reconcile guarantees it). */
51195
+ var RECONCILE_MS = 15e3;
51196
+ /** What a step trace shows before the step runs. */
51197
+ function stepMetaOf(action) {
51198
+ switch (action.kind) {
51199
+ case "wait": return { kind: "wait" };
51200
+ case "code": return { kind: "code" };
51201
+ case "action": return { kind: "action" };
51202
+ case "stop": return { kind: "stop" };
51203
+ case "wait-until": return { kind: "wait-until" };
51204
+ case "parallel": return { kind: "parallel" };
51205
+ case "repeat": return { kind: "repeat" };
51206
+ case "set": return { kind: "set" };
51207
+ case "choose": return { kind: "choose" };
51208
+ case "command": return commandStepMeta(action.target, action.actionId);
51209
+ }
51210
+ }
51211
+ function j(value) {
51212
+ return JSON.stringify(value);
51213
+ }
51214
+ /** Legacy cron: armed to the next minute boundary, re-armed from the wall clock. */
51215
+ /**
51216
+ * `deviceId: decision.vars.deviceId, …` for one event kind — the names come from
51217
+ * the one trigger-variable list the editor also reads, so the run's bag holds
51218
+ * exactly what the editor offers and nothing a trigger happens to carry beyond it.
51219
+ */
51220
+ function varsPick(kind) {
51221
+ return triggerLeafVariables(kind).map((v) => `${v.name}: decision.vars.${v.name}`).join(", ");
51222
+ }
51223
+ function emitCronSchedule(cron, path) {
51224
+ return ` // event leaf ${path}: schedule — armed to the next minute boundary and
51225
+ // RE-ARMED from the wall clock every tick, so it cannot drift the way a
51226
+ // setInterval(24h) does. No cron library: a block cannot resolve one.
51227
+ {
51228
+ let timer: ReturnType<typeof setTimeout> | undefined
51229
+ const arm = (): void => {
51230
+ timer = setTimeout(() => {
51231
+ if (cronMatches(${j(cron)}, new Date())) {
51232
+ void run({ kind: 'schedule', leaf: ${j(path)}, at: Date.now() })
51233
+ }
51234
+ arm()
51235
+ }, nextMinuteBoundary())
51236
+ }
51237
+ arm()
51238
+ disposers.push(() => { if (timer !== undefined) clearTimeout(timer) })
51239
+ }`;
51240
+ }
51241
+ /** A time spec: armed to the NEXT occurrence, re-read from the site each cycle. */
51242
+ function emitTimeSpecSchedule(spec, days, path) {
51243
+ return ` // event leaf ${path}: schedule — armed to the next occurrence of the time
51244
+ // spec, re-computed from the site (location, zone) every cycle, so a DST change
51245
+ // or a moved site is picked up and the sun's drift never accumulates.
51246
+ {
51247
+ const spec: TimeSpec = ${j(spec)}
51248
+ let timer: ReturnType<typeof setTimeout> | undefined
51249
+ let disposed = false
51250
+ const arm = async (): Promise<void> => {
51251
+ const next = await nextScheduleMoment(spec, ${days === void 0 ? "undefined" : j(days)}, ${j(path)})
51252
+ if (disposed) return
51253
+ if (next === null) return
51254
+ timer = setTimeout(() => {
51255
+ if (next > Date.now()) { void arm(); return }
51256
+ void run({ kind: 'schedule', leaf: ${j(path)}, at: Date.now() })
51257
+ void arm()
51258
+ }, Math.min(Math.max(next - Date.now(), 0), MAX_TIMER_MS))
51259
+ }
51260
+ void arm()
51261
+ disposers.push(() => { disposed = true; if (timer !== undefined) clearTimeout(timer) })
51262
+ }`;
51263
+ }
51264
+ function emitLeaf(trigger, path) {
51265
+ const at = j(path);
51266
+ switch (trigger.kind) {
51267
+ case "schedule": return trigger.at === void 0 ? emitCronSchedule(trigger.cron ?? "", path) : emitTimeSpecSchedule(trigger.at, trigger.days, path);
51268
+ case "device-event": return ` // event leaf ${path}: device event
51269
+ disposers.push(
51270
+ ctx.eventBus.subscribe(
51271
+ { category: ${j(trigger.category)}${trigger.deviceId === void 0 ? "" : `, deviceId: ${j(trigger.deviceId)}`} },
51272
+ (event) => {
51273
+ void run({
51274
+ kind: 'device-event',
51275
+ leaf: ${at},
51276
+ at: Date.now(),
51277
+ deviceId: event.deviceId,
51278
+ category: ${j(trigger.category)},
51279
+ })
51280
+ },
51281
+ ),
51282
+ )`;
51283
+ case "device-fired": return ` // event leaf ${path}: device fired — the bus event is the normal door; the
51284
+ // reconcile reads the device's event-emitter slice, so a fire whose event was
51285
+ // dropped is still seen while it is the LATEST one (D8, D1045). The first good
51286
+ // read only seeds: what fired before the start is not a trigger.
51287
+ {
51288
+ const watch = new DeviceFiredWatch(${j(trigger)})
51289
+ // The reconcile answers the same "nothing new" every tick: said once per reason.
51290
+ let lastQuiet = ''
51291
+ const land = (decision: ReturnType<DeviceFiredWatch['onEvent']>, door: 'event' | 'reconcile'): void => {
51292
+ if (decision.kind === 'ignore') {
51293
+ if (door === 'reconcile' && decision.why === lastQuiet) return
51294
+ if (door === 'reconcile') lastQuiet = decision.why
51295
+ ctx.logger.debug('device-fired trigger did not run — ' + decision.why, {
51296
+ tags: { deviceId: ${j(trigger.deviceId)} },
51297
+ leaf: ${at},
51298
+ door,
51299
+ })
51300
+ return
51301
+ }
51302
+ if (decision.kind === 'reject') {
51303
+ ctx.logger.debug('device-fired trigger rejected a fire', {
51304
+ tags: { deviceId: decision.vars.deviceId },
51305
+ reason: decision.reason,
51306
+ })
51307
+ }
51308
+ void run(
51309
+ { kind: 'device-fired', leaf: ${at}, at: Date.now(), ${varsPick("device-fired")}, ...decision.data },
51310
+ decision.reason,
51311
+ decision.kind === 'fire',
51312
+ )
51313
+ }
51314
+ disposers.push(
51315
+ ctx.eventBus.subscribe(
51316
+ { category: EventCategory.EventEmitted, deviceId: ${j(trigger.deviceId)} },
51317
+ (event) => land(watch.onEvent(event.data), 'event'),
51318
+ ),
51319
+ )
51320
+ const check = async (): Promise<void> => {
51321
+ const read = await readCapSlice(${j(trigger.deviceId)}, 'event-emitter')
51322
+ if (!read.ok) return // a failed read changes nothing: the next good one still seeds (D49)
51323
+ land(watch.onStatus(read.slice), 'reconcile')
51324
+ }
51325
+ void check()
51326
+ const reconcile = setInterval(() => { void check() }, RECONCILE_MS)
51327
+ disposers.push(() => clearInterval(reconcile))
51328
+ }`;
51329
+ case "device-becomes": {
51330
+ const hold = holdOf(trigger);
51331
+ return ` // event leaf ${path}: device state — the mirror is the authority, the
51332
+ // event only WAKES the evaluation, so a dropped event delays and never loses.
51333
+ // It fires on a TRANSITION (never on a re-report or the reconcile); a hold is
51334
+ // a timer armed when the transition happens and fired ONCE per episode.
51335
+ {
51336
+ let debounce: ReturnType<typeof setTimeout> | undefined
51337
+ const watch = new BecomesWatch(${j({
51338
+ ...trigger.becomes === void 0 ? {} : { becomes: trigger.becomes },
51339
+ ...trigger.operator === void 0 ? {} : {
51340
+ operator: trigger.operator,
51341
+ value: trigger.value
51342
+ },
51343
+ ...hold === void 0 ? {} : { hold }
51344
+ })}, {
51345
+ timers: {
51346
+ set: (fn, ms) => setTimeout(fn, ms),
51347
+ clear: (handle) => clearTimeout(handle),
51348
+ now: () => Date.now(),
51349
+ },
51350
+ read: () => readField(${j(trigger.deviceId)}, ${j(trigger.cap)}, ${j(trigger.fieldPath)}),
51351
+ emit: (effect) => {
51352
+ const occurrence = {
51353
+ kind: 'device-becomes',
51354
+ leaf: ${at},
51355
+ at: Date.now(),
51356
+ deviceId: ${j(trigger.deviceId)},
51357
+ cap: ${j(trigger.cap)},
51358
+ field: ${j(trigger.fieldPath)},
51359
+ to: toTraceScalar(effect.value),
51360
+ ...(effect.kind === 'fire' ? { from: toTraceScalar(effect.from) } : {}),
51361
+ ...(effect.hold === undefined ? {} : { hold: effect.hold }),
51362
+ }
51363
+ if (effect.kind === 'fire') {
51364
+ if (effect.hold !== undefined) {
51365
+ ctx.logger.info(describeHold(effect.hold), { tags: { deviceId: ${j(trigger.deviceId)} }, leaf: ${at} })
51366
+ }
51367
+ void run(occurrence, effect.hold === undefined ? 'fired' : describeHold(effect.hold))
51368
+ return
51369
+ }
51370
+ ctx.logger.debug(describeHold(effect.hold), { tags: { deviceId: ${j(trigger.deviceId)} }, leaf: ${at} })
51371
+ record(
51372
+ skipTrace(occurrence, describeHold(effect.hold), 'skipped-trigger', undefined, effect.hold.phase === 'pending'),
51373
+ )
51374
+ },
51375
+ })
51376
+ disposers.push(() => watch.dispose())
51377
+ const check = async (): Promise<void> => {
51378
+ const read = await readField(${j(trigger.deviceId)}, ${j(trigger.cap)}, ${j(trigger.fieldPath)})
51379
+ if (!read.ok) return // a failed read changes nothing, and never cancels a hold (D49)
51380
+ watch.observe(read.value)
51381
+ }
51382
+ const wake = (): void => {
51383
+ if (debounce !== undefined) clearTimeout(debounce)
51384
+ debounce = setTimeout(() => { void check() }, ${j(trigger.debounceMs ?? 0)})
51385
+ }
51386
+ disposers.push(() => { if (debounce !== undefined) clearTimeout(debounce) })
51387
+ disposers.push(
51388
+ ctx.eventBus.subscribe({ category: 'device.state-changed', deviceId: ${j(trigger.deviceId)} }, wake),
51389
+ )
51390
+ // Seed what the field holds NOW without firing: a restart is not a transition.
51391
+ void check()
51392
+ const reconcile = setInterval(() => { void check() }, RECONCILE_MS)
51393
+ disposers.push(() => clearInterval(reconcile))
51394
+ }`;
51395
+ }
51396
+ case "manual": return ` // event leaf ${path}: manual — fired by automation-control.trigger
51397
+ // ("Run actions"), which runs the THEN half with an EMPTY vars bag. A manual
51398
+ // run bypasses only the cooldown wait, never the single/queued limits.`;
51399
+ case "interval": return ` // event leaf ${path}: interval — every ${trigger.minutes} min, first run jittered so
51400
+ // blocks restarted together do not all fire on the same second.
51401
+ {
51402
+ let interval: ReturnType<typeof setInterval> | undefined
51403
+ const first = setTimeout(() => {
51404
+ void run({ kind: 'interval', leaf: ${at}, at: Date.now() })
51405
+ interval = setInterval(() => { void run({ kind: 'interval', leaf: ${at}, at: Date.now() }) }, ${j(trigger.minutes * 6e4)})
51406
+ }, Math.floor(Math.random() * Math.min(${j(trigger.minutes * 6e4)}, 30_000)) + 1)
51407
+ disposers.push(() => {
51408
+ clearTimeout(first)
51409
+ if (interval !== undefined) clearInterval(interval)
51410
+ })
51411
+ }`;
51412
+ case "detection": return ` // event leaf ${path}: detection — ONE fire per (device, track); a rejected event is
51413
+ // traced with its reason and never fires.
51414
+ {
51415
+ const filter = new DetectionTriggerFilter(${j(trigger)})
51416
+ disposers.push(
51417
+ ctx.eventBus.subscribe(
51418
+ { category: EventCategory.PipelineAnalyticsTrackLifecycle },
51419
+ (event) => {
51420
+ const decision = filter.evaluate(event.data, Date.now())
51421
+ if (decision.kind === 'ignore') return
51422
+ if (decision.kind === 'reject') {
51423
+ ctx.logger.debug('detection trigger rejected an event', {
51424
+ tags: { deviceId: decision.vars.deviceId },
51425
+ reason: decision.reason,
51426
+ })
51427
+ }
51428
+ void run(
51429
+ { kind: 'detection', leaf: ${at}, at: Date.now(), ${varsPick("detection")} },
51430
+ decision.reason,
51431
+ decision.kind === 'fire',
51432
+ )
51433
+ },
51434
+ ),
51435
+ )
51436
+ }`;
51437
+ case "stationary": return ` // event leaf ${path}: stationary — a parked object appeared / departed. Stateless:
51438
+ // the registry emits one event per transition. A dropped event only misses a fire;
51439
+ // the stationary-present STATE leaf reads the registry, not this event.
51440
+ {
51441
+ const trigger = ${j(trigger)} as const
51442
+ disposers.push(
51443
+ ctx.eventBus.subscribe(
51444
+ { category: EventCategory.PipelineAnalyticsStationaryChanged },
51445
+ (event) => {
51446
+ const decision = evaluateStationaryTrigger(trigger, event.data)
51447
+ if (decision.kind === 'ignore') return
51448
+ if (decision.kind === 'reject') {
51449
+ ctx.logger.debug('stationary trigger rejected an event', {
51450
+ tags: { deviceId: decision.vars.deviceId },
51451
+ reason: decision.reason,
51452
+ })
51453
+ }
51454
+ void run(
51455
+ { kind: 'stationary', leaf: ${at}, at: Date.now(), ${varsPick("stationary")} },
51456
+ decision.reason,
51457
+ decision.kind === 'fire',
51458
+ )
51459
+ },
51460
+ ),
51461
+ )
51462
+ }`;
51463
+ }
51464
+ }
51465
+ /** What a plain step does when it runs: the body of its `run`, wherever the step sits. */
51466
+ function emitStepBody(action) {
51467
+ switch (action.kind) {
51468
+ case "wait": return ` await sleep(${j(action.seconds * 1e3)})`;
51469
+ case "command": return ` await actuateTarget(scope, ${j(action.target)}, ${j(action.actionId)}, ${j(action.args ?? {})}, vars)`;
51470
+ case "action": return ` // an Action run, awaited: the step takes THAT run's outcome
51471
+ const result = await ctx.api.actions.run.mutate({
51472
+ actionId: ${j(action.actionId)},
51473
+ variables: substituteVariables(${j(action.variables ?? {})}, vars),
51474
+ wait: true,
51475
+ origin: { blockId: BLOCK_ID ?? undefined },
51476
+ })
51477
+ if (result.outcome !== 'ran') {
51478
+ throw new Error('action ' + ${j(action.actionId)} + ' ' + result.outcome + (result.message === undefined ? '' : ': ' + result.message))
51479
+ }`;
51480
+ case "stop": return ` // end the run here, on purpose: the steps after it are not-run with this reason
51481
+ scope.stop(String(substitute(${j(action.reason)}, vars)), ${j(action.outcome)})`;
51482
+ case "set": return ` // write the run's own bag, for the steps after this one — substitution only
51483
+ Object.assign(vars, substituteVariables(${j(action.vars)}, vars))`;
51484
+ case "code": return ` // inline code action — a fragment of THIS block, bundled by esbuild
51485
+ await (async () => {
51486
+ ${action.code.split("\n").map((line) => ` ${line}`).join("\n")}
51487
+ })()`;
51488
+ }
51489
+ }
51490
+ function continues(action) {
51491
+ return (action.kind === "command" || action.kind === "action") && action.continueOnError === true;
51492
+ }
51493
+ /** Whether the site is inside a block step: the automation's own steps sit at `actions.<n>`. */
51494
+ function isNestedSite(site) {
51495
+ return site.path.split(".").length > 2;
51496
+ }
51497
+ /** A list of steps under `path` (a branch, an else list, the steps of a repeat or a parallel). */
51498
+ function emitList(steps, path) {
51499
+ return steps.map((step, at) => emitStep(step, {
51500
+ meta: j(stepMetaOf(step)),
51501
+ path: `${path}.${at}`
51502
+ })).join("\n");
51503
+ }
51504
+ /** A step's `if` (#472) and its else list, as the fields of a RunnableStep. */
51505
+ function emitGuard(action, site) {
51506
+ const when = stepGuardOf(action);
51507
+ if (when === void 0) return "";
51508
+ const otherwise = emitList(action.kind === "wait" || action.kind === "command" ? action.else ?? [] : [], `${site.path}.else`);
51509
+ return ` guard: () => evaluateCondition(${j(when)}, ${j(`${site.path}.if`)}, vars),${otherwise === "" ? "" : `\n otherwise: [\n${otherwise}\n],`}
51510
+ `;
51511
+ }
51512
+ /** A `choose` step: its branches, each a condition and a list, and its else list. */
51513
+ function emitChoose(action, site) {
51514
+ const branches = action.branches.map((branch, b) => ` {
51515
+ guard: () => evaluateCondition(${j(branch.if)}, ${j(`${site.path}.branches.${b}.if`)}, vars),
51516
+ steps: [
51517
+ ${emitList(branch.steps, `${site.path}.branches.${b}.steps`)}
51518
+ ],
51519
+ },`).join("\n");
51520
+ const otherwise = emitList(action.else ?? [], `${site.path}.else`);
51521
+ return ` {
51522
+ meta: ${site.meta},
51523
+ // a choose step: the runner reads the branches in order and runs the first that is true
51524
+ run: async () => {},
51525
+ choose: {
51526
+ branches: [
51527
+ ${branches}
51528
+ ],${otherwise === "" ? "" : `\n otherwise: [\n${otherwise}\n],`}
51529
+ },
51530
+ },`;
51531
+ }
51532
+ /** The devices whose report can change a tree's answer; null when one is named by a stable id (any report wakes it). */
51533
+ function wakeDevicesOf(when) {
51534
+ const ids = [];
51535
+ for (const source of collectWhenMirrorSources(when)) {
51536
+ if (source.kind !== "device") return null;
51537
+ if (!ids.includes(source.deviceId)) ids.push(source.deviceId);
51538
+ }
51539
+ return ids;
51540
+ }
51541
+ /** A `wait-until` step: read the condition, wait for a wake, read again, until the timeout. */
51542
+ function emitWaitUntil(action, site) {
51543
+ const onTimeout = action.onTimeout === "stop" ? `scope.stop(message, 'failed')` : "scope.markTimedOut(message)";
51544
+ return ` {
51545
+ meta: ${site.meta},
51546
+ run: async (scope) => {
51547
+ // woken by a report of one of its devices, by the reconcile tick, or by a restart
51548
+ const waited = await waitUntil({
51549
+ read: () => evaluateCondition(${j(action.when)}, ${j(`${site.path}.when`)}, vars),
51550
+ timeoutMs: ${j(action.timeoutS * 1e3)},
51551
+ now: () => Date.now(),
51552
+ isAborted: () => token.aborted,
51553
+ nextWake: (ms) => waitForWake(ms, token, ${j(wakeDevicesOf(action.when))}),
51554
+ })
51555
+ if (waited.result === 'timed-out') {
51556
+ const message = waitTimedOutMessage(${j(action.timeoutS)}, waited.lastReason)
51557
+ ctx.logger.info('wait-until timed out', { step: ${j(site.path)}, onTimeout: ${j(action.onTimeout)}, reason: waited.lastReason })
51558
+ ${onTimeout}
51559
+ }
51560
+ },
51561
+ },`;
51562
+ }
51563
+ /** How a `repeat` decides its iterations, as the fields of a RunnableRepeat. */
51564
+ function emitRepeatLoop(loop, site) {
51565
+ switch (loop.by) {
51566
+ case "count": return `limit: ${j(loop.count)}, limitIsTimeout: false,`;
51567
+ case "forEach": return `// once per device: the device id is in vars.${REPEAT_ITEM_VAR} for the steps of that iteration
51568
+ limit: ${j(loop.target.ids.length)}, limitIsTimeout: false,
51569
+ ...(() => {
51570
+ const ids = ${j(loop.target.ids)}
51571
+ let outer: unknown
51572
+ return {
51573
+ before: async (iteration) => {
51574
+ if (iteration === 0) outer = vars[${j(REPEAT_ITEM_VAR)}]
51575
+ if (iteration < ids.length) vars[${j(REPEAT_ITEM_VAR)}] = ids[iteration]
51576
+ else if (${j(isNestedSite(site))} && outer !== undefined) vars[${j(REPEAT_ITEM_VAR)}] = outer
51577
+ return { go: true }
51578
+ },
51579
+ }
51580
+ })(),`;
51581
+ case "while":
51582
+ case "until": {
51583
+ const read = `repeatCheck(${j(loop.by)}, await evaluateCondition(${j(loop.when)}, ${j(`${site.path}.loop.when`)}, vars))`;
51584
+ const pause = loop.waitS === void 0 ? "" : `\n between: () => sleep(${j(loop.waitS * 1e3)}),`;
51585
+ return `limit: ${j(loop.maxIterations)}, limitIsTimeout: true,
51586
+ ${loop.by === "while" ? "before" : "after"}: async () => ${read},${pause}`;
51587
+ }
51588
+ }
51589
+ }
51590
+ /** One step, wherever it sits: a block step emits its own steps one level down, under its path. */
51591
+ function emitStep(action, site) {
51592
+ if (action.kind === "repeat") return ` {
51593
+ meta: ${site.meta},
51594
+ // a repeat step: the runner runs these once per iteration, under the bound
51595
+ run: async () => {},
51596
+ repeat: {
51597
+ steps: [
51598
+ ${emitList(action.steps, `${site.path}.steps`)}
51599
+ ],
51600
+ ${emitRepeatLoop(action.loop, site)}
51601
+ },
51602
+ },`;
51603
+ if (action.kind === "choose") return emitChoose(action, site);
51604
+ if (action.kind === "wait-until") return emitWaitUntil(action, site);
51605
+ if (action.kind === "parallel") return ` {
51606
+ meta: ${site.meta},
51607
+ // a parallel step: the runner starts these together and awaits them all
51608
+ run: async () => {},
51609
+ parallel: [
51610
+ ${emitList(action.steps, `${site.path}.steps`)}
51611
+ ],
51612
+ },`;
51613
+ return ` {
51614
+ meta: ${site.meta},
51615
+ ${emitGuard(action, site)}${continues(action) ? " continueOnError: true,\n" : ""} run: async (scope) => {
51616
+ ${emitStepBody(action)}
51617
+ },
51618
+ },`;
51619
+ }
51620
+ function emitAction(action, index) {
51621
+ return emitStep(action, {
51622
+ meta: `STEP_META[${index}]!`,
51623
+ path: `actions.${index}`
51624
+ });
51625
+ }
51626
+ /**
51627
+ * Compile a recipe to the TypeScript of a core block.
51628
+ *
51629
+ * Throws when the recipe is out of bounds — generation is not the place to
51630
+ * discover that, but it is the last place it can still be caught before code
51631
+ * that the operator did not author starts running.
51632
+ */
51633
+ /**
51634
+ * An instance of an automation template (#527) also carries the fingerprint of
51635
+ * the code it was generated as (`template.codeHash`), so the hub can tell a
51636
+ * block edited by hand from one it may regenerate. The fingerprint blanks the
51637
+ * literal, so stamping it does not change it.
51638
+ */
51639
+ function generateAutomationBlock(input) {
51640
+ const link = input.recipe.template;
51641
+ if (link === void 0) return renderAutomationBlock(input);
51642
+ const unstamped = {
51643
+ templateId: link.templateId,
51644
+ values: link.values,
51645
+ ...link.problems === void 0 ? {} : { problems: link.problems }
51646
+ };
51647
+ const first = renderAutomationBlock({
51648
+ ...input,
51649
+ recipe: {
51650
+ ...input.recipe,
51651
+ template: unstamped
51652
+ }
51653
+ });
51654
+ const codeHash = instanceCodeHash(first);
51655
+ if (codeHash === null) return first;
51656
+ return renderAutomationBlock({
51657
+ ...input,
51658
+ recipe: {
51659
+ ...input.recipe,
51660
+ template: {
51661
+ ...unstamped,
51662
+ codeHash
51663
+ }
51664
+ }
51665
+ });
51666
+ }
51667
+ function renderAutomationBlock(input) {
51668
+ const boundsError = validateRecipeBounds(input.recipe);
51669
+ if (boundsError !== null) throw new Error(`cannot generate an automation from an invalid recipe: ${boundsError}`);
51670
+ const { name, recipe } = input;
51671
+ const runMode = recipe.runMode ?? { mode: "single" };
51672
+ const stepMeta = recipe.actions.map(stepMetaOf);
51673
+ const elseSteps = (a) => a.kind === "wait" || a.kind === "command" ? a.else ?? [] : [];
51674
+ const hasDomainTarget = recipe.actions.flatMap((a) => [
51675
+ a,
51676
+ ...elseSteps(a),
51677
+ ...nestedStepsOf(a)
51678
+ ]).some((a) => a.kind === "command" && a.target.kind === "domain");
51679
+ const guardHoldTrees = recipe.actions.flatMap((a, i) => stepConditionsOf(a).flatMap(({ path, when }) => hasHoldLeaves(when) ? [{
51680
+ path: `actions.${i}.${path}`,
51681
+ when
51682
+ }] : []));
51683
+ const hasTime = hasTimeLeaves(recipe.when) || recipe.actions.some((a) => stepConditionsOf(a).some(({ when }) => hasTimeLeaves(when)));
51684
+ const hasWaitUntil = recipe.actions.some((a) => a.kind === "wait-until" || nestedStepsOf(a).some((n) => n.kind === "wait-until"));
51685
+ const eventLeaves = [];
51686
+ forEachLeaf(recipe.when, (leaf, path) => {
51687
+ if (isEventLeaf(leaf)) eventLeaves.push({
51688
+ leaf,
51689
+ path
51690
+ });
51691
+ });
51692
+ return `import type {
51693
+ ActionTarget,
51694
+ AddonContext,
51695
+ AutomationConditionTraceNode,
51696
+ AutomationRunTrace,
51697
+ AutomationRunVerdict,
51698
+ AutomationWhen,
51699
+ AutomationStepTrace,
51700
+ RunnableStep,
51701
+ StepScope,
51702
+ TimeSite,
51703
+ TimeSpec,
51704
+ WeekdayKey,
51705
+ } from '@camstack/types'
51706
+ import {
51707
+ ACTION_TARGET_INVALIDATION_EVENTS,
51708
+ ActionTargetResolver,
51709
+ BecomesWatch,
51710
+ ConditionMirror,
51711
+ HoldTracker,
51712
+ DetectionTriggerFilter,
51713
+ DeviceFiredWatch,
51714
+ EventCategory,
51715
+ RunGate,
51716
+ buildTriggerTrace,
51717
+ collectWhenMirrorSources,
51718
+ coreBlockIdFromAddonId,
51719
+ describeHold,
51720
+ evaluateWhenTree,
51721
+ evaluateStationaryTrigger,
51722
+ eventLeafIdAt,
51723
+ isSkippedTrace,
51724
+ mergeSkipTraces,
51725
+ nextOccurrence,
51726
+ nextTimeBoundaryInMs,
51727
+ observeHoldLeaves,
51728
+ stableIdMapOf,
51729
+ resolveStepArgs,
51730
+ resolveStepArgsWithTemplates,
51731
+ runForDevices,
51732
+ vocabCall,
51733
+ evaluateStepCondition,
51734
+ runSteps,
51735
+ repeatCheck,
51736
+ waitUntil,
51737
+ waitTimedOutMessage,
51738
+ siteFor,
51739
+ validateTimeSpecForSite,
51740
+ zoneOnlySite,
51741
+ } from '@camstack/types'
51742
+
51743
+ /**
51744
+ * ${name}
51745
+ *
51746
+ * GENERATED FROM A RECIPE — do not edit by hand. Editing this file makes it a
51747
+ * script: the visual editor reads AUTOMATION_RECIPE below, and hand edits are
51748
+ * lost the next time the recipe is saved. Use "Eject to code" to take ownership
51749
+ * of it permanently (one way).
51750
+ */
51751
+
51752
+ const AUTOMATION_RECIPE = ${JSON.stringify(recipe, null, 2)} as const
51753
+
51754
+ const RECONCILE_MS = ${RECONCILE_MS}
51755
+
51756
+ /** How triggers that arrive while busy (or cooling down) are handled. */
51757
+ const RUN_MODE = ${j(runMode)} as const
51758
+
51759
+ /** Run traces kept (a ring, held in the hub's runs ledger). */
51760
+ const KEEP_TRACES = ${recipe.keepTraces ?? 20}
51761
+
51762
+ /** The ONE tree: event leaves (instants) and state leaves (durations). */
51763
+ const WHEN = AUTOMATION_RECIPE.when
51764
+
51765
+ /** No event leaf: the automation fires when the tree goes false → true, never because it was already true. */
51766
+ const STATE_ONLY = ${!hasEventLeaves(recipe.when)}
51767
+
51768
+ /** Skips that repeat are folded into one trace; it goes to the hub after this. */
51769
+ const SKIP_FLUSH_MS = 5_000
51770
+
51771
+ /** Static facts about each action step, for its trace. */
51772
+ const STEP_META: ReadonlyArray<{ kind: string; cap?: string; method?: string; actionId?: string; deviceId?: number }> = ${j(stepMeta)}
51773
+
51774
+ /** True when a step acts on a whole domain: only then does the block listen for registry changes. */
51775
+ const HAS_DOMAIN_TARGET = ${hasDomainTarget}
51776
+
51777
+ /** A state leaf of the tree carries a \`for\`: its clock is fed on every mirror update, so it counts while nothing fires. */
51778
+ const HAS_HOLD = ${hasHoldLeaves(recipe.when)}
51779
+
51780
+ /** A \`time-is\` leaf (in the tree or a guard) reads the site clock: the site is kept in memory and a timer wakes the tree at each boundary. */
51781
+ const HAS_TIME = ${hasTime}
51782
+
51783
+ /** Guards (a step's \`if\`) with a \`for\`: they keep their own mirror and clocks, fed the same way. */
51784
+ const GUARD_HOLD_TREES: ReadonlyArray<{ path: string; when: AutomationWhen }> = ${j(guardHoldTrees)}
51785
+
51786
+ /** setTimeout cannot arm past 2^31-1 ms; a longer wait re-arms on wake. */
51787
+ const MAX_TIMER_MS = 2_000_000_000
51788
+
51789
+ /** A cap is named \`alarm-panel\`; \`ctx.api\` is keyed by the ROUTER name,
51790
+ * \`alarmPanel\`. Indexing ctx.api with the cap name yields undefined and every
51791
+ * action throws, so the conversion is not cosmetic. */
51792
+ function capToRouterKey(cap: string): string {
51793
+ return cap.replace(/-([a-z0-9])/g, (_m, c: string) => c.toUpperCase())
51794
+ }
51795
+
51796
+ /** Ms until the top of the next minute. Recomputed every tick so a long-lived
51797
+ * schedule cannot accumulate drift. */
51798
+ function nextMinuteBoundary(): number {
51799
+ const now = Date.now()
51800
+ return 60_000 - (now % 60_000)
51801
+ }
51802
+
51803
+ /** Does \`when\` satisfy a 5-field cron expression (min hour dom mon dow)?
51804
+ * Supports wildcards, step syntax, ranges, comma lists and plain numbers —
51805
+ * the subset an operator can author, and nothing that needs a library. */
51806
+ function cronMatches(expr: string, when: Date): boolean {
51807
+ const fields = expr.trim().split(/\\s+/)
51808
+ if (fields.length !== 5) return false
51809
+ const actual = [
51810
+ when.getMinutes(),
51811
+ when.getHours(),
51812
+ when.getDate(),
51813
+ when.getMonth() + 1,
51814
+ when.getDay(),
51815
+ ]
51816
+ return fields.every((field, i) => matchField(field, actual[i]!))
51817
+ }
51818
+
51819
+ function matchField(field: string, value: number): boolean {
51820
+ for (const part of field.split(',')) {
51821
+ const [range, stepRaw] = part.split('/')
51822
+ const step = stepRaw === undefined ? 1 : Number.parseInt(stepRaw, 10)
51823
+ if (!Number.isFinite(step) || step < 1) continue
51824
+ if (range === '*') {
51825
+ if (value % step === 0) return true
51826
+ continue
51827
+ }
51828
+ const bounds = range!.split('-')
51829
+ const lo = Number.parseInt(bounds[0]!, 10)
51830
+ const hi = bounds[1] === undefined ? lo : Number.parseInt(bounds[1], 10)
51831
+ if (!Number.isFinite(lo) || !Number.isFinite(hi)) continue
51832
+ if (value >= lo && value <= hi && (value - lo) % step === 0) return true
51833
+ }
51834
+ return false
51835
+ }
51836
+
51837
+ export default function block(ctx: AddonContext) {
51838
+ const disposers: Array<() => void> = []
51839
+ const gate = new RunGate(RUN_MODE)
51840
+ const MIRROR_SOURCES = collectWhenMirrorSources(WHEN)
51841
+ const mirror = new ConditionMirror(MIRROR_SOURCES)
51842
+ const holds = new HoldTracker()
51843
+ const guardMirror = new ConditionMirror(
51844
+ collectWhenMirrorSources({ kind: 'all', children: GUARD_HOLD_TREES.map((t) => t.when) }),
51845
+ )
51846
+ const guardHolds = new HoldTracker()
51847
+ let holdTimer: ReturnType<typeof setTimeout> | undefined
51848
+ ${hasTime ? ` /** The site clock a \`time-is\` leaf reads: memory only at evaluation time (D49), refreshed at start and on the reconcile. */
51849
+ let site: TimeSite | undefined
51850
+ ` : ""} const BLOCK_ID = coreBlockIdFromAddonId(ctx.id)
51851
+ /** The cooldown stamp: memory is the authority at fire time (D49); the hub ledger is read once at start. */
51852
+ let lastRunStartedAt: number | null = null
51853
+ /** True when the stamp could not be read at start — the first run is let through and says so. */
51854
+ let stampUnknown = false
51855
+ let sendChain: Promise<void> = Promise.resolve()
51856
+ let pendingSkip: AutomationRunTrace | undefined
51857
+ let skipTimer: ReturnType<typeof setTimeout> | undefined
51858
+ let stopped = false
51859
+ let runCounter = 0
51860
+ const runningTokens = new Set<RunToken>()
51861
+ const queue: QueuedRun[] = []
51862
+
51863
+ interface RunToken {
51864
+ aborted: boolean
51865
+ /** What cuts short whatever the run is paused on; several at once inside a \`parallel\`. */
51866
+ readonly wakes: Set<() => void>
51867
+ }
51868
+ interface QueuedRun {
51869
+ readonly trigger: Record<string, unknown>
51870
+ readonly reason: string
51871
+ readonly queuedAt: number
51872
+ }
51873
+
51874
+ /** Sleep that a restart can cut short. */
51875
+ const abortableSleep = (ms: number, token: RunToken): Promise<void> =>
51876
+ new Promise((resolve) => {
51877
+ const done = (): void => {
51878
+ clearTimeout(timer)
51879
+ token.wakes.delete(done)
51880
+ resolve()
51881
+ }
51882
+ const timer = setTimeout(done, ms)
51883
+ token.wakes.add(done)
51884
+ })
51885
+
51886
+ /** The runs paused on a \`wait-until\`, each with the devices whose report wakes it (null = any). */
51887
+ const stateWaiters = new Map<() => void, readonly number[] | null>()
51888
+ /** Resolve at a report of one of \`deviceIds\`, at the reconcile tick, at a restart, or after \`ms\`. */
51889
+ const waitForWake = (ms: number, token: RunToken, deviceIds: readonly number[] | null): Promise<void> =>
51890
+ new Promise((resolve) => {
51891
+ const done = (): void => {
51892
+ clearTimeout(timer)
51893
+ stateWaiters.delete(done)
51894
+ token.wakes.delete(done)
51895
+ resolve()
51896
+ }
51897
+ const timer = setTimeout(done, Math.min(ms, RECONCILE_MS))
51898
+ stateWaiters.set(done, deviceIds)
51899
+ token.wakes.add(done)
51900
+ })
51901
+
51902
+ // ── the hub's runs ledger: the stamp is read ONCE here, the ring is written through RPC ──
51903
+ async function loadState(): Promise<void> {
51904
+ if (BLOCK_ID === null) {
51905
+ ctx.logger.warn('this is not a core-block addon id — no run ledger, cooldown and traces will not survive a restart', { addonId: ctx.id })
51906
+ return
51907
+ }
51908
+ try {
51909
+ const doc = await ctx.api.coreBlocks.getAutomationRunState.query({ blockId: BLOCK_ID })
51910
+ lastRunStartedAt = doc.lastRunStartedAt
51911
+ } catch (err: unknown) {
51912
+ stampUnknown = true
51913
+ ctx.logger.warn('could not read the stored cooldown stamp — the first run is let through', {
51914
+ blockId: BLOCK_ID,
51915
+ error: err instanceof Error ? err.message : String(err),
51916
+ })
51917
+ }
51918
+ }
51919
+
51920
+ function send(payload: { trace?: AutomationRunTrace; runStartedAt?: number }): Promise<void> {
51921
+ if (BLOCK_ID === null) return Promise.resolve()
51922
+ const blockId = BLOCK_ID
51923
+ sendChain = sendChain.then(async () => {
51924
+ try {
51925
+ await ctx.api.coreBlocks.reportAutomationRun.mutate({ blockId, keepTraces: KEEP_TRACES, ...payload })
51926
+ } catch (err: unknown) {
51927
+ ctx.logger.warn('could not report the run to the hub ledger', {
51928
+ blockId,
51929
+ error: err instanceof Error ? err.message : String(err),
51930
+ })
51931
+ }
51932
+ })
51933
+ return sendChain
51934
+ }
51935
+
51936
+ function flushSkip(): void {
51937
+ if (skipTimer !== undefined) {
51938
+ clearTimeout(skipTimer)
51939
+ skipTimer = undefined
51940
+ }
51941
+ if (pendingSkip === undefined) return
51942
+ const trace = pendingSkip
51943
+ pendingSkip = undefined
51944
+ void send({ trace })
51945
+ }
51946
+
51947
+ /** A skip identical to the one waiting is COUNTED on it; anything else flushes it first. */
51948
+ function record(trace: AutomationRunTrace): void {
51949
+ if (isSkippedTrace(trace)) {
51950
+ if (pendingSkip !== undefined) {
51951
+ const merged = mergeSkipTraces(pendingSkip, trace)
51952
+ if (merged !== null) {
51953
+ pendingSkip = merged
51954
+ return
51955
+ }
51956
+ flushSkip()
51957
+ }
51958
+ pendingSkip = trace
51959
+ skipTimer = setTimeout(flushSkip, SKIP_FLUSH_MS)
51960
+ return
51961
+ }
51962
+ flushSkip()
51963
+ void send({ trace })
51964
+ }
51965
+
51966
+ ${hasTime ? ` /** Read the site into memory. A failed read keeps the previous value (D49). */
51967
+ async function refreshSite(): Promise<void> {
51968
+ try {
51969
+ const reading = await ctx.api.system.getSiteLocation.query()
51970
+ site = siteFor(reading) ?? zoneOnlySite(reading.timeZone)
51971
+ } catch (error) {
51972
+ ctx.logger.warn('site clock not refreshed — keeping the previous one', {
51973
+ error: error instanceof Error ? error.message : String(error),
51974
+ })
51975
+ }
51976
+ }
51977
+
51978
+ ` : ""} // ── the condition mirror (D49): memory only at fire time ──
51979
+ async function refreshMirror(): Promise<void> {
51980
+ const report = await mirror.refresh({
51981
+ fetchSlice: (deviceId, cap) => ctx.api.deviceState.getCapSlice.query({ deviceId, capName: cap }),
51982
+ fetchStableIds: async () => {
51983
+ const all = await ctx.api.deviceManager.listAll.query({})
51984
+ return stableIdMapOf(all)
51985
+ },
51986
+ })
51987
+ if (report.kept > 0) {
51988
+ ctx.logger.debug('condition mirror kept stale values for sources it could not read', report)
51989
+ }
51990
+ if (GUARD_HOLD_TREES.length > 0) await guardMirror.refresh(mirrorFetchers())
51991
+ }
51992
+
51993
+ function mirrorFetchers() {
51994
+ return {
51995
+ fetchSlice: (deviceId: number, cap: string) => ctx.api.deviceState.getCapSlice.query({ deviceId, capName: cap }),
51996
+ fetchStableIds: async () => {
51997
+ const all = await ctx.api.deviceManager.listAll.query({})
51998
+ return stableIdMapOf(all)
51999
+ },
52000
+ }
52001
+ }
52002
+
52003
+ /** Feed the clock of every \`for\` (the tree's and the guards'), and arm a timer for the
52004
+ * soonest pending one so a hold completes ON TIME, not at the next reconcile. */
52005
+ function feedHolds(): void {
52006
+ if (stopped) return
52007
+ const now = Date.now()
52008
+ const dues: number[] = []
52009
+ if (HAS_HOLD) {
52010
+ const due = observeHoldLeaves(WHEN, mirror, now, holds)
52011
+ if (due !== undefined) dues.push(due)
52012
+ }
52013
+ for (const tree of GUARD_HOLD_TREES) {
52014
+ const due = observeHoldLeaves(tree.when, guardMirror, now, guardHolds, tree.path)
52015
+ if (due !== undefined) dues.push(due)
52016
+ }
52017
+ ${hasTime ? ` // a time-is leaf changes sides at a boundary with no device event: wake the tree there
52018
+ const timeDue = nextTimeBoundaryInMs(WHEN, now, site)
52019
+ if (timeDue !== undefined) dues.push(timeDue)
52020
+ ` : ""} if (holdTimer !== undefined) clearTimeout(holdTimer)
52021
+ holdTimer = undefined
52022
+ if (dues.length === 0) return
52023
+ holdTimer = setTimeout(() => {
52024
+ feedHolds()
52025
+ evaluateStateTree()
52026
+ }, Math.min(Math.max(Math.min(...dues), 0), MAX_TIMER_MS))
52027
+ }
52028
+
52029
+ /** The next moment a schedule leaf fires, from the CURRENT site. A sun spec on
52030
+ * a site with no location is refused ON THE RECORD and never guessed — it
52031
+ * does not fire, and says why. null = nothing to arm. */
52032
+ async function nextScheduleMoment(
52033
+ spec: TimeSpec,
52034
+ days: readonly WeekdayKey[] | undefined,
52035
+ leaf: string,
52036
+ ): Promise<number | null> {
52037
+ try {
52038
+ const reading = await ctx.api.system.getSiteLocation.query()
52039
+ const checked = validateTimeSpecForSite(spec, reading)
52040
+ if (!checked.ok) {
52041
+ ctx.logger.warn('schedule not armed: ' + checked.message, { leaf, reason: checked.reason })
52042
+ return null
52043
+ }
52044
+ const site = checked.site ?? zoneOnlySite(reading.timeZone)
52045
+ const next = nextOccurrence(spec, Date.now(), site, days === undefined ? {} : { days })
52046
+ if (next === null) ctx.logger.info('schedule has no further occurrence', { leaf })
52047
+ return next
52048
+ } catch (error) {
52049
+ ctx.logger.warn('schedule not armed: could not read the site, retrying in a minute', {
52050
+ leaf,
52051
+ error: error instanceof Error ? error.message : String(error),
52052
+ })
52053
+ return Date.now() + 60_000
52054
+ }
52055
+ }
52056
+
52057
+ /** One cap slice off the state mirror. \`ok: false\` when the read threw —
52058
+ * logged at debug with the device; the caller decides what that means. */
52059
+ async function readCapSlice(
52060
+ deviceId: number,
52061
+ cap: string,
52062
+ ): Promise<{ readonly ok: true; readonly slice: unknown } | { readonly ok: false }> {
52063
+ try {
52064
+ const slice = await ctx.api.deviceState.getCapSlice.query({ deviceId, capName: cap })
52065
+ return { ok: true, slice }
52066
+ } catch (err: unknown) {
52067
+ ctx.logger.debug('device state read failed — the leaf keeps what it knew', {
52068
+ tags: { deviceId },
52069
+ cap,
52070
+ error: err instanceof Error ? err.message : String(err),
52071
+ })
52072
+ return { ok: false }
52073
+ }
52074
+ }
52075
+
52076
+ /** Read one cap field off the state mirror. \`ok: false\` when the device,
52077
+ * the cap or the field cannot be resolved — the caller decides what that
52078
+ * means (the device-state trigger changes nothing). (Conditions read the
52079
+ * ConditionMirror instead.) */
52080
+ async function readField(
52081
+ deviceId: number,
52082
+ cap: string,
52083
+ fieldPath: string,
52084
+ ): Promise<{ readonly ok: true; readonly value: unknown } | { readonly ok: false }> {
52085
+ const read = await readCapSlice(deviceId, cap)
52086
+ if (!read.ok) return { ok: false }
52087
+ let cursor: unknown = read.slice
52088
+ for (const part of fieldPath.split('.')) {
52089
+ if (cursor === null || typeof cursor !== 'object') return { ok: false }
52090
+ cursor = Reflect.get(cursor, part)
52091
+ }
52092
+ if (cursor === undefined) return { ok: false }
52093
+ return { ok: true, value: cursor }
52094
+ }
52095
+
52096
+ /** A trigger var keeps primitives only. */
52097
+ function toTraceScalar(value: unknown): string | number | boolean | null {
52098
+ return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? value : null
52099
+ }
52100
+
52101
+ /** WHO a step acts on (D983): picked devices, a \`$var\`, or a whole domain
52102
+ * resolved NOW. The cache is dropped on every registry event that can change
52103
+ * it; an empty answer is logged by the resolver and traced as \`empty\`. */
52104
+ const targets = new ActionTargetResolver(
52105
+ {
52106
+ listDeviceIdsByCaps: (capNames) => ctx.api.deviceManager.listDeviceIdsByCaps.query({ capNames: [...capNames] }),
52107
+ listDevices: async (deviceIds) => {
52108
+ const rows = await ctx.api.deviceManager.listAll.query({ deviceIds: [...deviceIds], projection: 'slim' })
52109
+ return rows.map((d) => ({ id: d.id, type: d.type, location: d.location, disabled: d.disabled }))
52110
+ },
52111
+ },
52112
+ ctx.logger,
52113
+ )
52114
+ if (HAS_DOMAIN_TARGET) {
52115
+ for (const category of ACTION_TARGET_INVALIDATION_EVENTS) {
52116
+ disposers.push(ctx.eventBus.subscribe({ category }, () => targets.invalidate()))
52117
+ }
52118
+ }
52119
+
52120
+ async function actuateTarget(
52121
+ scope: StepScope,
52122
+ target: ActionTarget,
52123
+ actionId: string,
52124
+ args: Record<string, unknown>,
52125
+ vars: Record<string, unknown>,
52126
+ ): Promise<void> {
52127
+ // the action id becomes its cap method here, at dispatch, through the vocabulary index
52128
+ const { cap, method, args: callArgs } = vocabCall(actionId, args)
52129
+ const resolved = await targets.resolve(target, actionId, vars, {
52130
+ actionId,
52131
+ owner: BLOCK_ID ?? undefined,
52132
+ })
52133
+ if (resolved.deviceIds.length === 0) {
52134
+ scope.markEmpty(resolved.emptyReason ?? 'the target matched no device')
52135
+ return
52136
+ }
52137
+ const [only] = resolved.deviceIds
52138
+ if (resolved.deviceIds.length === 1 && only !== undefined) {
52139
+ scope.setDeviceId(only)
52140
+ await actuate(scope, only, cap, method, callArgs, vars)
52141
+ return
52142
+ }
52143
+ await runForDevices(resolved.deviceIds, scope, (deviceId) => actuate(scope, deviceId, cap, method, callArgs, vars))
52144
+ }
52145
+
52146
+ function warnMissingVar(name: string): void {
52147
+ ctx.logger.warn('template referenced a var that was never set', { var: name })
52148
+ }
52149
+
52150
+ /** Device value templates (D1021) render on the hub through the ONE renderer; this block keeps no copy. */
52151
+ async function renderTemplates(templates: readonly string[]) {
52152
+ const out = await ctx.api.deviceManager.renderDeviceTemplates.query({ templates: [...templates] })
52153
+ return out.results
52154
+ }
52155
+
52156
+ /** Substitute {{vars.x}} slots and { $var } values. Substitution only — never evaluation. */
52157
+ function substitute(value: unknown, vars: Record<string, unknown>): unknown {
52158
+ return resolveStepArgs(value, vars, warnMissingVar)
52159
+ }
52160
+
52161
+ /** The variables handed to an Action step, substituted and kept to primitives. */
52162
+ function substituteVariables(
52163
+ raw: Record<string, string | number | boolean>,
52164
+ vars: Record<string, unknown>,
52165
+ ): Record<string, string | number | boolean> {
52166
+ const out: Record<string, string | number | boolean> = {}
52167
+ for (const [key, value] of Object.entries(raw)) {
52168
+ const resolved = substitute(value, vars)
52169
+ if (typeof resolved === 'string' || typeof resolved === 'number' || typeof resolved === 'boolean') {
52170
+ out[key] = resolved
52171
+ }
52172
+ }
52173
+ return out
52174
+ }
52175
+
52176
+ async function actuate(
52177
+ scope: StepScope,
52178
+ deviceId: number,
52179
+ cap: string,
52180
+ method: string,
52181
+ args: Record<string, unknown>,
52182
+ vars: Record<string, unknown>,
52183
+ ): Promise<void> {
52184
+ const templated = await resolveStepArgsWithTemplates(args, vars, warnMissingVar, renderTemplates)
52185
+ if (templated.notes.length > 0) scope.setTemplateNotes(templated.notes)
52186
+ const substituted = templated.value
52187
+ const resolved: Record<string, unknown> =
52188
+ substituted !== null && typeof substituted === 'object' ? { ...substituted } : {}
52189
+ scope.setArgs(resolved)
52190
+ // Forked-addon ctx.api namespaces are tRPC Proxies over a noop function
52191
+ // (typeof === 'function'), not plain objects — reject only null/undefined.
52192
+ const client: unknown = Reflect.get(ctx.api, capToRouterKey(cap))
52193
+ const proc: unknown =
52194
+ client !== null && client !== undefined ? Reflect.get(client as object, method) : undefined
52195
+ const mutate: unknown =
52196
+ proc !== null && proc !== undefined ? Reflect.get(proc as object, 'mutate') : undefined
52197
+ if (typeof mutate !== 'function') {
52198
+ throw new Error('no such device method: ' + cap + '.' + method)
52199
+ }
52200
+ await mutate({ ...resolved, deviceId })
52201
+ }
52202
+
52203
+ /** A step's \`if\` (#472), read on a mirror filled for exactly its leaves, NOW (D49: unread = unknown). */
52204
+ function evaluateCondition(when: AutomationWhen, path: string, vars: Record<string, unknown>) {
52205
+ // \`triggered-by\` reads the run: the id of the leaf that started it, by the path the trigger carries.
52206
+ const firedLeaf = vars['leaf']
52207
+ const trigger = { leafId: typeof firedLeaf === 'string' ? eventLeafIdAt(WHEN, firedLeaf) : null }
52208
+ const history = GUARD_HOLD_TREES.some((t) => t.path === path)
52209
+ ? { mirror: guardMirror, holds: guardHolds, rootPath: path }
52210
+ : undefined
52211
+ return evaluateStepCondition(when, mirrorFetchers(), Date.now, history, ${hasTime ? "site" : "undefined"}, trigger)
52212
+ }
52213
+
52214
+ /** The THEN half, through the ONE shared step runner: stops at the first
52215
+ * failure (continuing past a failed step executes an intent the operator
52216
+ * never expressed); every step is traced, the ones after a failure (or an
52217
+ * abort) are marked not-run. */
52218
+ async function runActions(
52219
+ vars: Record<string, unknown>,
52220
+ token: RunToken,
52221
+ ): Promise<{ steps: readonly AutomationStepTrace[]; failed: boolean }> {
52222
+ const sleep = (ms: number): Promise<void> => abortableSleep(ms, token)
52223
+ const steps: RunnableStep[] = [
52224
+ ${recipe.actions.map((a, i) => emitAction(a, i)).join("\n")}
52225
+ ]
52226
+ return runSteps(steps, {
52227
+ pathPrefix: 'actions',
52228
+ isAborted: () => token.aborted,
52229
+ abortReason: 'aborted by a restart',
52230
+ now: () => Date.now(),
52231
+ onFailure: (failure) => {
52232
+ ctx.logger.warn('action failed — stopping the sequence', {
52233
+ ...(failure.deviceId === undefined ? {} : { tags: { deviceId: failure.deviceId } }),
52234
+ step: failure.index,
52235
+ error: failure.message,
52236
+ })
52237
+ },
52238
+ onContinuedFailure: (failure) => {
52239
+ ctx.logger.warn('action failed — continuing, the step is marked to be passed over', {
52240
+ ...(failure.deviceId === undefined ? {} : { tags: { deviceId: failure.deviceId } }),
52241
+ step: failure.index,
52242
+ error: failure.message,
52243
+ })
52244
+ },
52245
+ onGuardUnknown: (skipped) => {
52246
+ ctx.logger.warn('step skipped — its condition could not be read', {
52247
+ ...(skipped.deviceId === undefined ? {} : { tags: { deviceId: skipped.deviceId } }),
52248
+ step: skipped.index,
52249
+ reason: skipped.reason,
52250
+ })
52251
+ },
52252
+ })
52253
+ }
52254
+
52255
+ function deviceTags(trigger: Record<string, unknown>): { tags?: { deviceId: number } } {
52256
+ const deviceId = trigger['deviceId']
52257
+ return typeof deviceId === 'number' ? { tags: { deviceId } } : {}
52258
+ }
52259
+
52260
+ function newRunId(at: number): string {
52261
+ runCounter += 1
52262
+ return at.toString(36) + '-' + runCounter.toString(36)
52263
+ }
52264
+
52265
+ /** A trigger that never became a run (rejected, or dropped by the run mode). */
52266
+ function skipTrace(
52267
+ trigger: Record<string, unknown>,
52268
+ reason: string,
52269
+ outcome: AutomationRunTrace['outcome'],
52270
+ verdict: AutomationRunVerdict | undefined,
52271
+ accepted: boolean,
52272
+ ): AutomationRunTrace {
52273
+ const now = Date.now()
52274
+ return {
52275
+ runId: newRunId(now),
52276
+ startedAt: now,
52277
+ endedAt: now,
52278
+ trigger: buildTriggerTrace(trigger, accepted ? 'pass' : 'fail', reason),
52279
+ conditions: [],
52280
+ ...(verdict === undefined ? {} : { verdict }),
52281
+ steps: [],
52282
+ outcome,
52283
+ repeat: 1,
52284
+ lastAt: now,
52285
+ }
52286
+ }
52287
+
52288
+ /** One admitted run: conditions (memory only), the cooldown, the actions. */
52289
+ async function execute(
52290
+ trigger: Record<string, unknown>,
52291
+ reason: string,
52292
+ admission: AutomationRunVerdict,
52293
+ ): Promise<void> {
52294
+ const token: RunToken = { aborted: false, wakes: new Set() }
52295
+ runningTokens.add(token)
52296
+ const startedAt = Date.now()
52297
+ const runId = newRunId(startedAt)
52298
+ let verdict = admission
52299
+ let outcome: AutomationRunTrace['outcome'] = 'ran'
52300
+ let nodes: AutomationConditionTraceNode[] = []
52301
+ let steps: AutomationStepTrace[] = []
52302
+ try {
52303
+ const firedLeaf = trigger['leaf']
52304
+ const evaluation = evaluateWhenTree(WHEN, mirror, Date.now(), {
52305
+ holds,${hasTime ? "\n ...(site === undefined ? {} : { site })," : ""}
52306
+ ...(typeof firedLeaf === 'string' ? { firedPath: firedLeaf } : {}),
52307
+ })
52308
+ nodes = [...evaluation.nodes]
52309
+ for (const node of nodes) {
52310
+ if (node.kind === 'device-is' && node.observed === null && node.deviceId !== undefined) {
52311
+ ctx.logger.warn('condition leaf value unknown — treated as false', {
52312
+ tags: { deviceId: node.deviceId },
52313
+ path: node.path,
52314
+ cap: node.cap,
52315
+ fieldPath: node.fieldPath,
52316
+ })
52317
+ }
52318
+ }
52319
+ if (!evaluation.pass) {
52320
+ outcome = 'skipped-conditions'
52321
+ ctx.logger.debug('automation did not run — the rule tree was false at that instant', { trigger, ...deviceTags(trigger) })
52322
+ return
52323
+ }
52324
+ const letThrough = stampUnknown && RUN_MODE.mode === 'cooldown'
52325
+ const cooldown = letThrough
52326
+ ? { ok: true, bypassed: true, reason: 'cooldown stamp unreadable at start — run let through' }
52327
+ : gate.cooldown({
52328
+ manual: trigger['kind'] === 'manual',
52329
+ now: Date.now(),
52330
+ lastRunStartedAt,
52331
+ })
52332
+ if (!cooldown.ok) {
52333
+ outcome = 'skipped-cooldown'
52334
+ verdict = { mode: RUN_MODE, decision: 'cooldown', reason: cooldown.reason }
52335
+ ctx.logger.info('automation did not run — ' + cooldown.reason, deviceTags(trigger))
52336
+ return
52337
+ }
52338
+ if (cooldown.bypassed) verdict = { mode: RUN_MODE, decision: 'bypass', reason: cooldown.reason }
52339
+ // Stamped when the actions START, and reported to the hub before they run,
52340
+ // so a restart mid-run cannot fire again inside the window.
52341
+ lastRunStartedAt = startedAt
52342
+ stampUnknown = false
52343
+ await send({ runStartedAt: startedAt })
52344
+ ctx.logger.info('automation running', { trigger, ...deviceTags(trigger) })
52345
+ const vars: Record<string, unknown> = { ...trigger }
52346
+ const result = await runActions(vars, token)
52347
+ steps = result.steps
52348
+ outcome = token.aborted ? 'aborted' : result.failed ? 'failed' : 'ran'
52349
+ } catch (err: unknown) {
52350
+ outcome = 'failed'
52351
+ ctx.logger.warn('automation run failed', { error: err instanceof Error ? err.message : String(err), ...deviceTags(trigger) })
52352
+ } finally {
52353
+ runningTokens.delete(token)
52354
+ const endedAt = Date.now()
52355
+ record({
52356
+ runId,
52357
+ startedAt,
52358
+ endedAt,
52359
+ trigger: buildTriggerTrace(trigger, 'pass', reason),
52360
+ conditions: nodes,
52361
+ verdict,
52362
+ steps,
52363
+ outcome,
52364
+ repeat: 1,
52365
+ lastAt: endedAt,
52366
+ })
52367
+ if (gate.release()) {
52368
+ const next = queue.shift()
52369
+ if (next !== undefined && !stopped) {
52370
+ void execute(next.trigger, next.reason, {
52371
+ mode: RUN_MODE,
52372
+ decision: 'queued',
52373
+ reason: 'queued, then ran after waiting ' + (Date.now() - next.queuedAt) + ' ms',
52374
+ })
52375
+ }
52376
+ }
52377
+ }
52378
+ }
52379
+
52380
+ /** Every trigger lands here. \`accepted\` = the trigger itself was satisfied
52381
+ * (a rejected detection event is only traced). */
52382
+ async function run(
52383
+ trigger: Record<string, unknown>,
52384
+ reason = 'fired',
52385
+ accepted = true,
52386
+ ): Promise<void> {
52387
+ await ready
52388
+ if (stopped) return
52389
+ if (!accepted) {
52390
+ record(skipTrace(trigger, reason, 'skipped-trigger', undefined, false))
52391
+ return
52392
+ }
52393
+ const admission = gate.admit()
52394
+ const verdict: AutomationRunVerdict = { mode: RUN_MODE, decision: admission.decision, reason: admission.reason }
52395
+ switch (admission.decision) {
52396
+ case 'drop':
52397
+ ctx.logger.info('automation trigger dropped — ' + admission.reason, deviceTags(trigger))
52398
+ record(skipTrace(trigger, reason, 'skipped-overlap', verdict, true))
52399
+ return
52400
+ case 'queued':
52401
+ ctx.logger.info('automation trigger queued — ' + admission.reason, deviceTags(trigger))
52402
+ queue.push({ trigger, reason, queuedAt: Date.now() })
52403
+ return
52404
+ case 'restart':
52405
+ ctx.logger.info('automation restarting — ' + admission.reason, deviceTags(trigger))
52406
+ for (const running of runningTokens) {
52407
+ running.aborted = true
52408
+ for (const wake of [...running.wakes]) wake()
52409
+ }
52410
+ break
52411
+ case 'run':
52412
+ break
52413
+ }
52414
+ await execute(trigger, reason, verdict)
52415
+ }
52416
+
52417
+ const ready: Promise<void> = (async () => {
52418
+ await loadState()
52419
+ ${hasTime ? " await refreshSite()\n" : ""} await refreshMirror()
52420
+ feedHolds()
52421
+ stateWatching = true
52422
+ evaluateStateTree()
52423
+ })()
52424
+
52425
+ /**
52426
+ * Rule 2 — a tree of states only. It fires when the tree goes false → true.
52427
+ * The FIRST evaluation only seeds \`treeWasTrue\` (a tree that is already true
52428
+ * when the hub or runner starts must not fire), and an evaluation that read an
52429
+ * unknown value neither seeds nor moves it: unknown is not false.
52430
+ */
52431
+ let treeWasTrue: boolean | undefined
52432
+ let stateWatching = false
52433
+ function evaluateStateTree(): void {
52434
+ if (!STATE_ONLY || !stateWatching || stopped) return
52435
+ const evaluation = evaluateWhenTree(WHEN, mirror, Date.now(), { holds${hasTime ? ", ...(site === undefined ? {} : { site })" : ""} })
52436
+ if (evaluation.unknown) return
52437
+ const was = treeWasTrue
52438
+ treeWasTrue = evaluation.pass
52439
+ if (was === false && evaluation.pass) {
52440
+ void run({ kind: 'state', leaf: 'when', at: Date.now() }, 'the rules became true', true)
52441
+ }
52442
+ }
52443
+
52444
+ if (MIRROR_SOURCES.length > 0 || GUARD_HOLD_TREES.length > 0 || HAS_TIME) {
52445
+ disposers.push(
52446
+ ctx.eventBus.subscribe({ category: EventCategory.DeviceStateChanged }, (event) => {
52447
+ const data = event.data
52448
+ const deviceId = data['deviceId']
52449
+ const capName = data['capName']
52450
+ if (typeof deviceId === 'number' && typeof capName === 'string') {
52451
+ mirror.apply(deviceId, capName, data['slice'])
52452
+ guardMirror.apply(deviceId, capName, data['slice'])
52453
+ feedHolds()
52454
+ evaluateStateTree()
52455
+ }
52456
+ }),
52457
+ )
52458
+ const mirrorReconcile = setInterval(() => {
52459
+ void ${hasTime ? "Promise.all([refreshSite(), refreshMirror()])" : "refreshMirror()"}.then(() => {
52460
+ feedHolds()
52461
+ evaluateStateTree()
52462
+ })
52463
+ }, RECONCILE_MS)
52464
+ disposers.push(() => clearInterval(mirrorReconcile))
52465
+ }
52466
+
52467
+ ${hasWaitUntil ? ` // a paused run reads its condition again when one of its devices reports
52468
+ disposers.push(
52469
+ ctx.eventBus.subscribe({ category: EventCategory.DeviceStateChanged }, (event) => {
52470
+ const deviceId = event.data['deviceId']
52471
+ for (const [wake, deviceIds] of [...stateWaiters]) {
52472
+ if (deviceIds === null || (typeof deviceId === 'number' && deviceIds.includes(deviceId))) wake()
52473
+ }
52474
+ }),
52475
+ )
52476
+ ` : ""}
52477
+ ${eventLeaves.map(({ leaf, path }) => emitLeaf(leaf, path)).join("\n\n")}
52478
+
52479
+ return () => {
52480
+ stopped = true
52481
+ if (holdTimer !== undefined) clearTimeout(holdTimer)
52482
+ queue.length = 0
52483
+ flushSkip()
52484
+ for (const running of runningTokens) {
52485
+ running.aborted = true
52486
+ for (const wake of [...running.wakes]) wake()
52487
+ }
52488
+ for (const dispose of disposers) dispose()
52489
+ }
52490
+ }
52491
+ `;
52492
+ }
50822
52493
  new Set(Object.values(COCO_TO_MACRO.mapping));
50823
52494
  /**
50824
52495
  * Generic stateless event emitter. Installed on a `DeviceType.EventEmitter`
@@ -51253,6 +52924,95 @@ function checkPickedUnit(unit, target) {
51253
52924
  target
51254
52925
  });
51255
52926
  }
52927
+ function normalizeLeaf(leaf, resolver, path) {
52928
+ const quantity = resolver.fieldQuantity(leaf.cap, leaf.fieldPath);
52929
+ const base = quantity === void 0 ? void 0 : baseUnitForQuantity(quantity);
52930
+ const wantsUnit = isQuantityValue(leaf.value) || leaf.unit !== void 0;
52931
+ if (base === void 0 || quantity === void 0) {
52932
+ if (wantsUnit) throw new QuantityUnitError("no-quantity", `${leaf.cap}.${leaf.fieldPath} is not a quantity — it takes no unit`);
52933
+ return {
52934
+ leaf,
52935
+ warnings: []
52936
+ };
52937
+ }
52938
+ if (isQuantityValue(leaf.value)) {
52939
+ const converted = convertQuantityInput({
52940
+ value: leaf.value.value,
52941
+ unit: leaf.value.unit,
52942
+ target: base
52943
+ });
52944
+ return {
52945
+ leaf: {
52946
+ ...leaf,
52947
+ value: converted,
52948
+ unit: pickedUnit(leaf.value.unit)
52949
+ },
52950
+ warnings: []
52951
+ };
52952
+ }
52953
+ if (typeof leaf.value !== "number") return {
52954
+ leaf,
52955
+ warnings: []
52956
+ };
52957
+ if (leaf.unit !== void 0) {
52958
+ checkPickedUnit(leaf.unit, base);
52959
+ return {
52960
+ leaf,
52961
+ warnings: []
52962
+ };
52963
+ }
52964
+ if (!hasUnitChoice(quantity)) return {
52965
+ leaf,
52966
+ warnings: []
52967
+ };
52968
+ return {
52969
+ leaf,
52970
+ warnings: [bareWarning({
52971
+ path,
52972
+ deviceId: leaf.deviceId,
52973
+ field: leaf.fieldPath,
52974
+ value: leaf.value,
52975
+ assumedUnit: base
52976
+ })]
52977
+ };
52978
+ }
52979
+ /** Normalise every leaf of a condition tree. Throws {@link QuantityUnitError}. */
52980
+ function normalizeConditionUnits(condition, resolver, path = "when") {
52981
+ switch (condition.kind) {
52982
+ case "device-is": {
52983
+ const { leaf, warnings } = normalizeLeaf(condition, resolver, path);
52984
+ return {
52985
+ value: leaf,
52986
+ warnings
52987
+ };
52988
+ }
52989
+ case "not": {
52990
+ const inner = normalizeConditionUnits(condition.child, resolver, `${path}.child`);
52991
+ return {
52992
+ value: {
52993
+ ...condition,
52994
+ child: inner.value
52995
+ },
52996
+ warnings: inner.warnings
52997
+ };
52998
+ }
52999
+ case "all":
53000
+ case "any": {
53001
+ const children = condition.children.map((child, i) => normalizeConditionUnits(child, resolver, `${path}.children.${i}`));
53002
+ return {
53003
+ value: {
53004
+ ...condition,
53005
+ children: children.map((c) => c.value)
53006
+ },
53007
+ warnings: children.flatMap((c) => c.warnings)
53008
+ };
53009
+ }
53010
+ default: return {
53011
+ value: condition,
53012
+ warnings: []
53013
+ };
53014
+ }
53015
+ }
51256
53016
  function normalizeCommandStepUnits(step, resolver, path) {
51257
53017
  const deviceId = step.target.kind === "devices" && step.target.ids.length === 1 ? step.target.ids[0] : void 0;
51258
53018
  const { cap, method } = vocabCall(step.actionId, void 0);
@@ -51313,6 +53073,97 @@ function normalizeActionUnits(actions, resolver, path = "steps") {
51313
53073
  warnings
51314
53074
  };
51315
53075
  }
53076
+ /** Normalise a whole recipe: its `when` tree and its actions. */
53077
+ function normalizeRecipeUnits(recipe, resolver) {
53078
+ const when = normalizeConditionUnits(recipe.when, resolver, "when");
53079
+ const actions = normalizeActionUnits(recipe.actions, resolver, "actions");
53080
+ return {
53081
+ value: {
53082
+ ...recipe,
53083
+ when: when.value,
53084
+ actions: actions.value
53085
+ },
53086
+ warnings: [...when.warnings, ...actions.warnings]
53087
+ };
53088
+ }
53089
+ /**
53090
+ * The save boundary for numbers tied to a quantity (D972), as a pure function
53091
+ * over a {@link UnitResolver} — shared by every surface that saves a recipe
53092
+ * (the admin editor, the public MCP), so none of them carries its own copy.
53093
+ *
53094
+ * A recipe carries its numbers in their STORED unit plus the unit the person
53095
+ * picked (`leaf.unit`, `step.argUnits`). Two things must be true of what is
53096
+ * saved:
53097
+ *
53098
+ * - a bare number on a quantity field is never saved silently — a leaf or arg
53099
+ * that came without a picked unit is stamped with the unit it was always
53100
+ * read in, so the saved recipe says it;
53101
+ * - the recipe goes through {@link normalizeRecipeUnits}, the same function the
53102
+ * server runs, so a unit that cannot belong to its field is refused here with
53103
+ * the same message instead of at the hub.
53104
+ */
53105
+ function stampCondition(condition, resolver) {
53106
+ switch (condition.kind) {
53107
+ case "device-is": {
53108
+ if (typeof condition.value !== "number" || condition.unit !== void 0) return condition;
53109
+ const quantity = resolver.fieldQuantity(condition.cap, condition.fieldPath);
53110
+ if (quantity === void 0 || unitsForQuantity(quantity).length < 2) return condition;
53111
+ const base = baseUnitForQuantity(quantity);
53112
+ return base === void 0 ? condition : {
53113
+ ...condition,
53114
+ unit: base
53115
+ };
53116
+ }
53117
+ case "not": return {
53118
+ ...condition,
53119
+ child: stampCondition(condition.child, resolver)
53120
+ };
53121
+ case "all":
53122
+ case "any": return {
53123
+ ...condition,
53124
+ children: condition.children.map((child) => stampCondition(child, resolver))
53125
+ };
53126
+ default: return condition;
53127
+ }
53128
+ }
53129
+ function stampAction(action, resolver) {
53130
+ if (action.kind !== "command" || action.args === void 0) return action;
53131
+ const { cap, method } = vocabCall(action.actionId, void 0);
53132
+ const argUnits = { ...action.argUnits };
53133
+ for (const [arg, value] of Object.entries(action.args)) {
53134
+ if (typeof value !== "number" || argUnits[arg] !== void 0) continue;
53135
+ const meta = resolver.paramMeta(cap, method, arg);
53136
+ if (meta !== void 0 && unitsForQuantity(meta.quantity).length > 1) argUnits[arg] = meta.unit;
53137
+ }
53138
+ return Object.keys(argUnits).length === 0 ? action : {
53139
+ ...action,
53140
+ argUnits
53141
+ };
53142
+ }
53143
+ /**
53144
+ * The recipe as it is saved: every quantity number carries its unit, and the
53145
+ * whole recipe passes the server's unit check. `ok: false` names why it cannot
53146
+ * be saved.
53147
+ */
53148
+ function prepareRecipeUnits(recipe, resolver) {
53149
+ const stamped = {
53150
+ ...recipe,
53151
+ when: stampCondition(recipe.when, resolver),
53152
+ actions: recipe.actions.map((action) => stampAction(action, resolver))
53153
+ };
53154
+ try {
53155
+ return {
53156
+ ok: true,
53157
+ recipe: normalizeRecipeUnits(stamped, resolver).value
53158
+ };
53159
+ } catch (error) {
53160
+ if (error instanceof QuantityUnitError) return {
53161
+ ok: false,
53162
+ error: error.message
53163
+ };
53164
+ throw error;
53165
+ }
53166
+ }
51316
53167
  /**
51317
53168
  * `device-export` — collection cap for addons that export camstack
51318
53169
  * devices to external ecosystems (HomeAssistant via MQTT discovery,
@@ -60223,7 +62074,8 @@ var CAP_CUSTOMIZE_CATALOG = {
60223
62074
  DeviceType.Washer,
60224
62075
  DeviceType.Dryer,
60225
62076
  DeviceType.Gateway,
60226
- DeviceType.HeatPump
62077
+ DeviceType.HeatPump,
62078
+ DeviceType.EnergySystem
60227
62079
  ],
60228
62080
  apply: "add",
60229
62081
  vocabularyCap: "consumables",
@@ -62021,7 +63873,7 @@ function groupTemplate(id) {
62021
63873
  }
62022
63874
  /**
62023
63875
  * Cap history catalog, projected from every `*.cap.ts` `history` block.
62024
- * 44 caps with series (89 series), 37 caps answered `'none'`.
63876
+ * 45 caps with series (103 series), 37 caps answered `'none'`.
62025
63877
  * Field keys are `runtimeState` paths (`a.b` into fixed objects only).
62026
63878
  */
62027
63879
  var HISTORY_CATALOG = {
@@ -62165,6 +64017,85 @@ var HISTORY_CATALOG = {
62165
64017
  "powerOn": { kind: "boolean" }
62166
64018
  },
62167
64019
  "do-not-disturb": { "enabled": { kind: "boolean" } },
64020
+ "energy-system": {
64021
+ "solar.powerW": {
64022
+ kind: "gauge",
64023
+ unit: "W",
64024
+ deadband: 50,
64025
+ displayName: "Solar power"
64026
+ },
64027
+ "solar.energyKwh": {
64028
+ kind: "counter",
64029
+ unit: "kWh",
64030
+ displayName: "Solar energy"
64031
+ },
64032
+ "grid.powerW": {
64033
+ kind: "gauge",
64034
+ unit: "W",
64035
+ deadband: 50,
64036
+ displayName: "Grid power"
64037
+ },
64038
+ "grid.importKwh": {
64039
+ kind: "counter",
64040
+ unit: "kWh",
64041
+ displayName: "Grid import"
64042
+ },
64043
+ "grid.exportKwh": {
64044
+ kind: "counter",
64045
+ unit: "kWh",
64046
+ displayName: "Grid export"
64047
+ },
64048
+ "house.powerW": {
64049
+ kind: "gauge",
64050
+ unit: "W",
64051
+ deadband: 50,
64052
+ displayName: "House power"
64053
+ },
64054
+ "house.energyKwh": {
64055
+ kind: "counter",
64056
+ unit: "kWh",
64057
+ displayName: "House energy"
64058
+ },
64059
+ "heatPump.powerW": {
64060
+ kind: "gauge",
64061
+ unit: "W",
64062
+ deadband: 50,
64063
+ displayName: "Heat pump power"
64064
+ },
64065
+ "heatPump.energyKwh": {
64066
+ kind: "counter",
64067
+ unit: "kWh",
64068
+ displayName: "Heat pump energy"
64069
+ },
64070
+ "storage.stateOfChargePct": {
64071
+ kind: "gauge",
64072
+ unit: "%",
64073
+ deadband: 1,
64074
+ displayName: "Storage charge"
64075
+ },
64076
+ "storage.storedKwh": {
64077
+ kind: "gauge",
64078
+ unit: "kWh",
64079
+ deadband: .05,
64080
+ displayName: "Stored energy"
64081
+ },
64082
+ "storage.powerW": {
64083
+ kind: "gauge",
64084
+ unit: "W",
64085
+ deadband: 50,
64086
+ displayName: "Storage power"
64087
+ },
64088
+ "storage.chargedKwh": {
64089
+ kind: "counter",
64090
+ unit: "kWh",
64091
+ displayName: "Storage charged"
64092
+ },
64093
+ "storage.dischargedKwh": {
64094
+ kind: "counter",
64095
+ unit: "kWh",
64096
+ displayName: "Storage discharged"
64097
+ }
64098
+ },
62168
64099
  "enum-sensor": { "value": {
62169
64100
  kind: "enum",
62170
64101
  skipWhenSet: "timestamp"
@@ -66231,13 +68162,13 @@ var DeviceTemplateRenderSchema = zod.z.discriminatedUnion("ok", [zod.z.object({
66231
68162
  function templateCapKey(cap) {
66232
68163
  return cap.replace(/-/g, "_");
66233
68164
  }
66234
- function isRecord$3(value) {
68165
+ function isRecord$4(value) {
66235
68166
  return typeof value === "object" && value !== null && !Array.isArray(value);
66236
68167
  }
66237
68168
  function pickPath(root, path) {
66238
68169
  let cursor = root;
66239
68170
  for (const part of path) if (Array.isArray(cursor) && typeof part === "number") cursor = cursor[part];
66240
- else if (isRecord$3(cursor) && Object.hasOwn(cursor, String(part))) cursor = cursor[String(part)];
68171
+ else if (isRecord$4(cursor) && Object.hasOwn(cursor, String(part))) cursor = cursor[String(part)];
66241
68172
  else return;
66242
68173
  return cursor;
66243
68174
  }
@@ -66274,7 +68205,7 @@ function resolveTemplateRef(view, path) {
66274
68205
  }
66275
68206
  const owners = caps.filter((cap) => {
66276
68207
  const slice = view.slices[cap];
66277
- return isRecord$3(slice) && Object.hasOwn(slice, String(head));
68208
+ return isRecord$4(slice) && Object.hasOwn(slice, String(head));
66278
68209
  });
66279
68210
  if (owners.length === 0) return {
66280
68211
  kind: "missing",
@@ -70702,6 +72633,187 @@ var embeddingEncoderCapability = {
70702
72633
  },
70703
72634
  vocabulary: { notOperatorFacing: NOT_A_DEVICE.ML }
70704
72635
  };
72636
+ /**
72637
+ * Energy system (#513): the one READ-ONLY cap of a home energy installation —
72638
+ * solar production, the grid connection, the house, a heat pump where the
72639
+ * system meters one, and the storage. Each part is a branch of one bus.
72640
+ *
72641
+ * A part the system does not have is `null` (the whole object); a value the
72642
+ * system did not report is `null`, never `0` (D393).
72643
+ *
72644
+ * Signs, all in watts:
72645
+ * - `solar.powerW`, `house.powerW`, `heatPump.powerW` are magnitudes (≥ 0);
72646
+ * - `grid.powerW` is + importing, − exporting;
72647
+ * - `storage.powerW` is + charging, − discharging.
72648
+ *
72649
+ * The storage is a FIELD of this model, never the `battery` cap: that cap says
72650
+ * a device runs on a battery and feeds the low-battery alerts, and a home
72651
+ * storage at 19 % is not a device about to go flat (#522).
72652
+ *
72653
+ * Lifetime kWh are counters (D944); a `…TodayKwh` is the system's own day total.
72654
+ * The self-consumption share is not a field: it derives at read time
72655
+ * ({@link energySystemSelfConsumptionPct}).
72656
+ */
72657
+ /** Production: the panels. */
72658
+ var EnergySolarSchema = zod.z.object({
72659
+ powerW: zod.z.number().nullable().meta(readingMeta("power")),
72660
+ /** Lifetime production, kWh. */
72661
+ energyKwh: zod.z.number().nullable().meta(readingMeta("energy")),
72662
+ /** Produced today, kWh. */
72663
+ todayKwh: zod.z.number().nullable().meta(readingMeta("energy"))
72664
+ });
72665
+ /** The grid connection: + import, − export. */
72666
+ var EnergyGridSchema = zod.z.object({
72667
+ powerW: zod.z.number().nullable().meta(readingMeta("power")),
72668
+ /** Lifetime imported, kWh. */
72669
+ importKwh: zod.z.number().nullable().meta(readingMeta("energy")),
72670
+ /** Lifetime exported, kWh. */
72671
+ exportKwh: zod.z.number().nullable().meta(readingMeta("energy")),
72672
+ importTodayKwh: zod.z.number().nullable().meta(readingMeta("energy")),
72673
+ exportTodayKwh: zod.z.number().nullable().meta(readingMeta("energy"))
72674
+ });
72675
+ /** A consumer on the bus (the house, the heat pump): power and energy drawn. */
72676
+ var EnergyConsumerSchema = zod.z.object({
72677
+ powerW: zod.z.number().nullable().meta(readingMeta("power")),
72678
+ /** Lifetime consumption, kWh. */
72679
+ energyKwh: zod.z.number().nullable().meta(readingMeta("energy")),
72680
+ /** Consumed today, kWh. */
72681
+ todayKwh: zod.z.number().nullable().meta(readingMeta("energy"))
72682
+ });
72683
+ /** The home storage (accumulo): + charging, − discharging. */
72684
+ var EnergyStorageSchema = zod.z.object({
72685
+ /** State of charge, 0..100. */
72686
+ stateOfChargePct: zod.z.number().nullable().meta(readingMeta("percentage")),
72687
+ /** Energy held now, kWh. */
72688
+ storedKwh: zod.z.number().nullable().meta(readingMeta("energy")),
72689
+ /** Usable capacity, kWh. */
72690
+ capacityKwh: zod.z.number().nullable().meta(readingMeta("energy")),
72691
+ powerW: zod.z.number().nullable().meta(readingMeta("power")),
72692
+ /** Lifetime charged, kWh. */
72693
+ chargedKwh: zod.z.number().nullable().meta(readingMeta("energy")),
72694
+ /** Lifetime discharged, kWh. */
72695
+ dischargedKwh: zod.z.number().nullable().meta(readingMeta("energy")),
72696
+ chargedTodayKwh: zod.z.number().nullable().meta(readingMeta("energy")),
72697
+ dischargedTodayKwh: zod.z.number().nullable().meta(readingMeta("energy"))
72698
+ });
72699
+ var EnergySystemStatusSchema = zod.z.object({
72700
+ solar: EnergySolarSchema.nullable(),
72701
+ grid: EnergyGridSchema.nullable(),
72702
+ house: EnergyConsumerSchema.nullable(),
72703
+ heatPump: EnergyConsumerSchema.nullable(),
72704
+ storage: EnergyStorageSchema.nullable(),
72705
+ /** Ms epoch when the slice was last read from the system. */
72706
+ lastFetchedAt: zod.z.number()
72707
+ });
72708
+ var energySystemCapability = {
72709
+ name: "energy-system",
72710
+ scope: "device",
72711
+ deviceNative: true,
72712
+ mode: "singleton",
72713
+ deviceTypes: [DeviceType.EnergySystem],
72714
+ methods: {},
72715
+ status: {
72716
+ schema: EnergySystemStatusSchema,
72717
+ kind: "push"
72718
+ },
72719
+ runtimeState: EnergySystemStatusSchema,
72720
+ /**
72721
+ * Runtime-state durability: **session** — the system answers on the next
72722
+ * poll, so a restart that clears the slice loses nothing a reader needs (the
72723
+ * series are recorded). See `RuntimeStateDurability`.
72724
+ */
72725
+ durability: "session",
72726
+ /**
72727
+ * History (D850): every power is a gauge, every lifetime kWh a counter (the
72728
+ * kWh of a period is computed at read time, D944). A part the system does not
72729
+ * have is null and records nothing. Day totals are not recorded: they are the
72730
+ * counters' difference over the day.
72731
+ */
72732
+ history: { fields: {
72733
+ "solar.powerW": {
72734
+ kind: "gauge",
72735
+ unit: "W",
72736
+ deadband: 50,
72737
+ displayName: "Solar power"
72738
+ },
72739
+ "solar.energyKwh": {
72740
+ kind: "counter",
72741
+ unit: "kWh",
72742
+ displayName: "Solar energy"
72743
+ },
72744
+ "grid.powerW": {
72745
+ kind: "gauge",
72746
+ unit: "W",
72747
+ deadband: 50,
72748
+ displayName: "Grid power"
72749
+ },
72750
+ "grid.importKwh": {
72751
+ kind: "counter",
72752
+ unit: "kWh",
72753
+ displayName: "Grid import"
72754
+ },
72755
+ "grid.exportKwh": {
72756
+ kind: "counter",
72757
+ unit: "kWh",
72758
+ displayName: "Grid export"
72759
+ },
72760
+ "house.powerW": {
72761
+ kind: "gauge",
72762
+ unit: "W",
72763
+ deadband: 50,
72764
+ displayName: "House power"
72765
+ },
72766
+ "house.energyKwh": {
72767
+ kind: "counter",
72768
+ unit: "kWh",
72769
+ displayName: "House energy"
72770
+ },
72771
+ "heatPump.powerW": {
72772
+ kind: "gauge",
72773
+ unit: "W",
72774
+ deadband: 50,
72775
+ displayName: "Heat pump power"
72776
+ },
72777
+ "heatPump.energyKwh": {
72778
+ kind: "counter",
72779
+ unit: "kWh",
72780
+ displayName: "Heat pump energy"
72781
+ },
72782
+ "storage.stateOfChargePct": {
72783
+ kind: "gauge",
72784
+ unit: "%",
72785
+ deadband: 1,
72786
+ displayName: "Storage charge"
72787
+ },
72788
+ "storage.storedKwh": {
72789
+ kind: "gauge",
72790
+ unit: "kWh",
72791
+ deadband: .05,
72792
+ displayName: "Stored energy"
72793
+ },
72794
+ "storage.powerW": {
72795
+ kind: "gauge",
72796
+ unit: "W",
72797
+ deadband: 50,
72798
+ displayName: "Storage power"
72799
+ },
72800
+ "storage.chargedKwh": {
72801
+ kind: "counter",
72802
+ unit: "kWh",
72803
+ displayName: "Storage charged"
72804
+ },
72805
+ "storage.dischargedKwh": {
72806
+ kind: "counter",
72807
+ unit: "kWh",
72808
+ displayName: "Storage discharged"
72809
+ }
72810
+ } },
72811
+ volatileStateFields: ["lastFetchedAt"],
72812
+ vocabulary: {
72813
+ noun: t("Energy system", "Sistema energetico"),
72814
+ order: 4020
72815
+ }
72816
+ };
70705
72817
  zod.z.enum([
70706
72818
  "date",
70707
72819
  "time",
@@ -73506,6 +75618,7 @@ var HERO_SCENE_BY_TYPE = {
73506
75618
  [DeviceType.Humidifier]: "control-dial",
73507
75619
  [DeviceType.WaterHeater]: "heater",
73508
75620
  [DeviceType.HeatPump]: "heat-pump",
75621
+ [DeviceType.EnergySystem]: "generic",
73509
75622
  [DeviceType.Fan]: "fan",
73510
75623
  [DeviceType.MediaPlayer]: "tv",
73511
75624
  [DeviceType.AlarmPanel]: "alarm",
@@ -74933,6 +77046,19 @@ var IntegrationInstanceKindSchema = zod.z.object({
74933
77046
  * finds the instances whose kind names it; absent takes the kind `id`.
74934
77047
  */
74935
77048
  brokerKind: zod.z.string().min(1).optional(),
77049
+ /**
77050
+ * Other function caps an instance of this kind also serves (a Google account sends mail, so it
77051
+ * serves `smtp-provider` beside being a `broker`). A link to one of these caps lists and accepts
77052
+ * the instance; a page section stays the kinds whose `functionCap` it names. Absent means none.
77053
+ */
77054
+ alsoServes: zod.z.array(zod.z.string().min(1)).optional(),
77055
+ /**
77056
+ * The kind's own icon (a brand mark), hub-relative or a `data:` URI. Absent: the client shows
77057
+ * the provider addon's icon.
77058
+ */
77059
+ iconUrl: zod.z.string().min(1).optional(),
77060
+ /** The media type `iconUrl` serves (`image/svg+xml`, `image/png`); the URL carries no extension. */
77061
+ iconMediaType: zod.z.string().min(1).optional(),
74936
77062
  /** What instances of this kind are for the Integrations page; absent takes the provider's `role`. */
74937
77063
  role: IntegrationInstanceRoleSchema.optional(),
74938
77064
  /** `testInstance` really probes the remote for this kind; absent takes the provider's `canTest`. */
@@ -102902,8 +105028,464 @@ var temperatureSensorCapability = {
102902
105028
  }]
102903
105029
  }
102904
105030
  };
102905
- var TemplateKindSchema = zod.z.enum(["remote"]);
102906
- var TEMPLATE_PAYLOAD_SCHEMAS = { remote: RemoteLayoutPayloadSchema };
105031
+ var inputKey = zod.z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,39}$/);
105032
+ var inputBase = {
105033
+ key: inputKey,
105034
+ label: zod.z.string().min(1).max(80),
105035
+ description: zod.z.string().max(300).optional(),
105036
+ /** Absent means required. */
105037
+ optional: zod.z.literal(true).optional()
105038
+ };
105039
+ var TemplateDeviceFilterSchema = zod.z.object({
105040
+ /** Only devices that offer this capability. */
105041
+ capability: zod.z.string().min(1).optional(),
105042
+ /** Only devices of this role / device type (`light`, `switch`, `button`). */
105043
+ role: zod.z.string().min(1).optional()
105044
+ });
105045
+ var DeviceInputSchema = zod.z.object({
105046
+ kind: zod.z.literal("device"),
105047
+ ...inputBase,
105048
+ multiple: zod.z.literal(true).optional(),
105049
+ filter: TemplateDeviceFilterSchema.optional()
105050
+ });
105051
+ var EventInputSchema = zod.z.object({
105052
+ kind: zod.z.literal("event"),
105053
+ ...inputBase,
105054
+ /** The device input (same level) whose event vocabulary is offered (D1044). */
105055
+ deviceInput: inputKey
105056
+ });
105057
+ var ActionInputSchema$1 = zod.z.object({
105058
+ kind: zod.z.literal("action"),
105059
+ ...inputBase,
105060
+ /** The device input (same level) whose actions are offered; absent offers all (D1050). */
105061
+ deviceInput: inputKey.optional()
105062
+ });
105063
+ var NumberInputSchema = zod.z.object({
105064
+ kind: zod.z.literal("number"),
105065
+ ...inputBase,
105066
+ min: zod.z.number().optional(),
105067
+ max: zod.z.number().optional(),
105068
+ default: zod.z.number().optional()
105069
+ });
105070
+ var DurationInputSchema = zod.z.object({
105071
+ kind: zod.z.literal("duration"),
105072
+ ...inputBase,
105073
+ /** Seconds. */
105074
+ min: zod.z.number().nonnegative().optional(),
105075
+ max: zod.z.number().nonnegative().optional(),
105076
+ default: zod.z.number().nonnegative().optional()
105077
+ });
105078
+ var TextInputSchema = zod.z.object({
105079
+ kind: zod.z.literal("text"),
105080
+ ...inputBase,
105081
+ maxLength: zod.z.number().int().min(1).max(2e3).optional(),
105082
+ default: zod.z.string().optional()
105083
+ });
105084
+ var TemplateSelectOptionSchema = zod.z.object({
105085
+ value: zod.z.string().min(1),
105086
+ label: zod.z.string().min(1).max(80)
105087
+ });
105088
+ var SelectInputSchema = zod.z.object({
105089
+ kind: zod.z.literal("select"),
105090
+ ...inputBase,
105091
+ options: zod.z.array(TemplateSelectOptionSchema).min(1).max(50),
105092
+ default: zod.z.string().optional()
105093
+ });
105094
+ var BooleanInputSchema = zod.z.object({
105095
+ kind: zod.z.literal("boolean"),
105096
+ ...inputBase,
105097
+ default: zod.z.boolean().optional()
105098
+ });
105099
+ var TemplateScalarInputSchema = zod.z.discriminatedUnion("kind", [
105100
+ DeviceInputSchema,
105101
+ EventInputSchema,
105102
+ ActionInputSchema$1,
105103
+ NumberInputSchema,
105104
+ DurationInputSchema,
105105
+ TextInputSchema,
105106
+ SelectInputSchema,
105107
+ BooleanInputSchema
105108
+ ]);
105109
+ var GroupInputSchema = zod.z.object({
105110
+ kind: zod.z.literal("group"),
105111
+ ...inputBase,
105112
+ inputs: zod.z.array(TemplateScalarInputSchema).min(1).max(10),
105113
+ minRows: zod.z.number().int().min(0).max(20).optional(),
105114
+ maxRows: zod.z.number().int().min(1).max(20).optional()
105115
+ });
105116
+ var TemplateInputSchema = zod.z.discriminatedUnion("kind", [...TemplateScalarInputSchema.options, GroupInputSchema]);
105117
+ var TemplatePathSchema = zod.z.array(zod.z.union([zod.z.string().min(1), zod.z.number().int().nonnegative()])).max(24);
105118
+ var TemplateValueBindingSchema = zod.z.object({
105119
+ kind: zod.z.literal("value"),
105120
+ input: inputKey,
105121
+ path: TemplatePathSchema,
105122
+ /** A device value written as a step target (`{ kind: 'devices', ids }`). */
105123
+ as: zod.z.literal("target").optional()
105124
+ });
105125
+ var TemplateRowIdBindingSchema = zod.z.object({
105126
+ kind: zod.z.literal("row-id"),
105127
+ path: TemplatePathSchema
105128
+ });
105129
+ var TemplateRowItemBindingSchema = zod.z.discriminatedUnion("kind", [TemplateValueBindingSchema, TemplateRowIdBindingSchema]);
105130
+ var TemplateRowsBindingSchema = zod.z.object({
105131
+ kind: zod.z.literal("rows"),
105132
+ input: inputKey,
105133
+ /** The list in the body the rows are appended to. */
105134
+ path: TemplatePathSchema,
105135
+ /** The JSON copied once per row. */
105136
+ item: zod.z.unknown(),
105137
+ bindings: zod.z.array(TemplateRowItemBindingSchema).max(40)
105138
+ });
105139
+ var TemplateBindingSchema = zod.z.discriminatedUnion("kind", [TemplateValueBindingSchema, TemplateRowsBindingSchema]);
105140
+ function bindingProblems(payload, ctx) {
105141
+ const byKey = /* @__PURE__ */ new Map();
105142
+ payload.inputs.forEach((input, index) => {
105143
+ if (byKey.has(input.key)) ctx.addIssue({
105144
+ code: "custom",
105145
+ message: `input "${input.key}" is declared twice`,
105146
+ path: ["inputs", index]
105147
+ });
105148
+ byKey.set(input.key, input);
105149
+ const siblings = input.kind === "group" ? input.inputs : payload.inputs;
105150
+ for (const scalar of input.kind === "group" ? input.inputs : [input]) {
105151
+ if (scalar.kind !== "event" && scalar.kind !== "action") continue;
105152
+ if (scalar.deviceInput === void 0) continue;
105153
+ const device = siblings.find((s) => s.key === scalar.deviceInput);
105154
+ if (device === void 0 || device.kind !== "device") ctx.addIssue({
105155
+ code: "custom",
105156
+ message: `"${scalar.key}" reads the device input "${scalar.deviceInput}", which is not a device input beside it`,
105157
+ path: ["inputs", index]
105158
+ });
105159
+ }
105160
+ });
105161
+ payload.bindings.forEach((binding, index) => {
105162
+ const input = byKey.get(binding.input);
105163
+ if (input === void 0) {
105164
+ ctx.addIssue({
105165
+ code: "custom",
105166
+ message: `binding names the undeclared input "${binding.input}"`,
105167
+ path: ["bindings", index]
105168
+ });
105169
+ return;
105170
+ }
105171
+ if (binding.kind === "value" && input.kind === "group") ctx.addIssue({
105172
+ code: "custom",
105173
+ message: `group "${input.key}" is bound with rows, not a value`,
105174
+ path: ["bindings", index]
105175
+ });
105176
+ if (binding.kind === "rows") {
105177
+ if (input.kind !== "group") {
105178
+ ctx.addIssue({
105179
+ code: "custom",
105180
+ message: `rows need a group input, "${input.key}" is ${input.kind}`,
105181
+ path: ["bindings", index]
105182
+ });
105183
+ return;
105184
+ }
105185
+ for (const row of binding.bindings) if (row.kind === "value" && !input.inputs.some((i) => i.key === row.input)) ctx.addIssue({
105186
+ code: "custom",
105187
+ message: `row binding names "${row.input}", which group "${input.key}" does not declare`,
105188
+ path: ["bindings", index]
105189
+ });
105190
+ }
105191
+ });
105192
+ }
105193
+ var AutomationTemplatePayloadSchema = zod.z.object({
105194
+ version: zod.z.literal(1),
105195
+ description: zod.z.string().max(500).optional(),
105196
+ /** The automation body; a recipe once the inputs are written into it. */
105197
+ body: zod.z.record(zod.z.string(), zod.z.unknown()),
105198
+ inputs: zod.z.array(TemplateInputSchema).max(30),
105199
+ bindings: zod.z.array(TemplateBindingSchema).max(100)
105200
+ }).superRefine(bindingProblems);
105201
+ function valueProblem(input, value) {
105202
+ switch (input.kind) {
105203
+ case "device":
105204
+ if (input.multiple === true) return Array.isArray(value) && value.length > 0 && value.every((v) => typeof v === "number" && Number.isInteger(v) && v >= 0) ? null : "pick at least one device";
105205
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? null : "pick one device";
105206
+ case "event": return TemplateEventValueSchema.safeParse(value).success ? null : "pick an event";
105207
+ case "action": {
105208
+ const parsed = TemplateActionValueSchema.safeParse(value);
105209
+ if (!parsed.success) return "pick an action";
105210
+ return findVocabAction(parsed.data.actionId) === void 0 ? `"${parsed.data.actionId}" is not a vocabulary action` : null;
105211
+ }
105212
+ case "number":
105213
+ case "duration":
105214
+ if (typeof value !== "number" || !Number.isFinite(value)) return "a number is required";
105215
+ if (input.min !== void 0 && value < input.min) return `at least ${input.min}`;
105216
+ if (input.max !== void 0 && value > input.max) return `at most ${input.max}`;
105217
+ return null;
105218
+ case "text":
105219
+ if (typeof value !== "string") return "text is required";
105220
+ return input.maxLength !== void 0 && value.length > input.maxLength ? `at most ${input.maxLength} characters` : null;
105221
+ case "select": return typeof value === "string" && input.options.some((o) => o.value === value) ? null : "pick one of the options";
105222
+ case "boolean": return typeof value === "boolean" ? null : "on or off";
105223
+ }
105224
+ }
105225
+ function defaultOf(input) {
105226
+ switch (input.kind) {
105227
+ case "number":
105228
+ case "duration":
105229
+ case "text":
105230
+ case "select":
105231
+ case "boolean": return input.default;
105232
+ default: return;
105233
+ }
105234
+ }
105235
+ function isScalar(value) {
105236
+ return !(Array.isArray(value) && value.some((v) => typeof v === "object" && v !== null));
105237
+ }
105238
+ function isRowList(value) {
105239
+ return Array.isArray(value) && value.every((v) => typeof v === "object" && v !== null && !Array.isArray(v));
105240
+ }
105241
+ function resolveScalars(inputs, values, prefix, problems) {
105242
+ const out = /* @__PURE__ */ new Map();
105243
+ for (const input of inputs) {
105244
+ const address = `${prefix}${input.key}`;
105245
+ const raw = values[input.key] ?? defaultOf(input);
105246
+ if (raw === void 0) {
105247
+ if (input.optional !== true) problems.push({
105248
+ code: "missing-input",
105249
+ input: address,
105250
+ detail: `"${input.label}" is required`
105251
+ });
105252
+ continue;
105253
+ }
105254
+ const problem = isScalar(raw) ? valueProblem(input, raw) : "a single value is required";
105255
+ if (problem !== null || !isScalar(raw)) {
105256
+ problems.push({
105257
+ code: "invalid-input",
105258
+ input: address,
105259
+ detail: problem ?? "invalid value"
105260
+ });
105261
+ continue;
105262
+ }
105263
+ out.set(input.key, raw);
105264
+ }
105265
+ return out;
105266
+ }
105267
+ function resolveValues(payload, values, problems) {
105268
+ const scalars = resolveScalars(payload.inputs.filter((i) => i.kind !== "group"), values, "", problems);
105269
+ const groups = /* @__PURE__ */ new Map();
105270
+ for (const input of payload.inputs) {
105271
+ if (input.kind !== "group") continue;
105272
+ const raw = values[input.key] ?? [];
105273
+ if (!isRowList(raw)) {
105274
+ problems.push({
105275
+ code: "invalid-input",
105276
+ input: input.key,
105277
+ detail: "a list of rows is required"
105278
+ });
105279
+ continue;
105280
+ }
105281
+ const min = input.minRows ?? (input.optional === true ? 0 : 1);
105282
+ const max = input.maxRows ?? 20;
105283
+ if (raw.length < min) {
105284
+ problems.push({
105285
+ code: raw.length === 0 ? "missing-input" : "invalid-input",
105286
+ input: input.key,
105287
+ detail: `"${input.label}" needs at least ${min} row(s)`
105288
+ });
105289
+ continue;
105290
+ }
105291
+ if (raw.length > max) {
105292
+ problems.push({
105293
+ code: "invalid-input",
105294
+ input: input.key,
105295
+ detail: `"${input.label}" takes at most ${max} row(s)`
105296
+ });
105297
+ continue;
105298
+ }
105299
+ groups.set(input.key, raw.map((row, index) => resolveScalars(input.inputs, row, `${input.key}.${index}.`, problems)));
105300
+ }
105301
+ return {
105302
+ scalars,
105303
+ groups
105304
+ };
105305
+ }
105306
+ function isRecord$3(value) {
105307
+ return typeof value === "object" && value !== null && !Array.isArray(value);
105308
+ }
105309
+ var PathError = class extends Error {};
105310
+ function getAt(root, path) {
105311
+ let node = root;
105312
+ for (const segment of path) if (typeof segment === "number") node = Array.isArray(node) ? node[segment] : void 0;
105313
+ else node = isRecord$3(node) ? node[segment] : void 0;
105314
+ return node;
105315
+ }
105316
+ /** `root` with `value` at `path`; missing containers are created, a wrong one throws. */
105317
+ function setAt(root, path, value) {
105318
+ const [head, ...rest] = path;
105319
+ if (head === void 0) return value;
105320
+ if (typeof head === "number") {
105321
+ const list = root === void 0 ? [] : root;
105322
+ if (!Array.isArray(list)) throw new PathError(`expected a list at index ${head}`);
105323
+ const next = [...list];
105324
+ next[head] = setAt(list[head], rest, value);
105325
+ return next;
105326
+ }
105327
+ const object = root === void 0 ? {} : root;
105328
+ if (!isRecord$3(object)) throw new PathError(`expected an object at "${head}"`);
105329
+ return {
105330
+ ...object,
105331
+ [head]: setAt(object[head], rest, value)
105332
+ };
105333
+ }
105334
+ var EVENT_FIELDS = [
105335
+ "eventIds",
105336
+ "sourceIds",
105337
+ "kinds"
105338
+ ];
105339
+ var ACTION_FIELDS = [
105340
+ "actionId",
105341
+ "args",
105342
+ "argUnits"
105343
+ ];
105344
+ function mergeInto(current, drop, patch) {
105345
+ const base = isRecord$3(current) ? current : {};
105346
+ return {
105347
+ ...Object.fromEntries(Object.entries(base).filter(([k]) => !drop.includes(k))),
105348
+ ...patch
105349
+ };
105350
+ }
105351
+ function writeValue(root, binding, input, value) {
105352
+ switch (input.kind) {
105353
+ case "event": return setAt(root, binding.path, mergeInto(getAt(root, binding.path), EVENT_FIELDS, TemplateEventValueSchema.parse(value)));
105354
+ case "action": return setAt(root, binding.path, mergeInto(getAt(root, binding.path), ACTION_FIELDS, TemplateActionValueSchema.parse(value)));
105355
+ case "device":
105356
+ if (binding.as === "target") {
105357
+ const ids = Array.isArray(value) ? value : [value];
105358
+ return setAt(root, binding.path, {
105359
+ kind: "devices",
105360
+ ids
105361
+ });
105362
+ }
105363
+ return setAt(root, binding.path, value);
105364
+ default: return setAt(root, binding.path, value);
105365
+ }
105366
+ }
105367
+ function applyRows(root, binding, group, rows) {
105368
+ const existing = getAt(root, binding.path);
105369
+ const list = existing === void 0 ? [] : existing;
105370
+ if (!Array.isArray(list)) throw new PathError(`rows of "${group.key}" need a list`);
105371
+ const items = rows.map((row, index) => {
105372
+ let item = binding.item;
105373
+ for (const rowBinding of binding.bindings) {
105374
+ if (rowBinding.kind === "row-id") {
105375
+ item = setAt(item, rowBinding.path, `${group.key}-${index}`);
105376
+ continue;
105377
+ }
105378
+ const input = group.inputs.find((i) => i.key === rowBinding.input);
105379
+ const value = row.get(rowBinding.input);
105380
+ if (input === void 0 || value === void 0) continue;
105381
+ item = writeValue(item, rowBinding, input, value);
105382
+ }
105383
+ return item;
105384
+ });
105385
+ return setAt(root, binding.path, [...list, ...items]);
105386
+ }
105387
+ /** The body with the values written in, as a recipe — or every reason it is not one. */
105388
+ function expandAutomationTemplate(payload, values) {
105389
+ const problems = [];
105390
+ const resolved = resolveValues(payload, values, problems);
105391
+ if (problems.length > 0) return {
105392
+ ok: false,
105393
+ problems
105394
+ };
105395
+ let body = payload.body;
105396
+ try {
105397
+ for (const binding of payload.bindings) {
105398
+ const input = payload.inputs.find((i) => i.key === binding.input);
105399
+ if (input === void 0) continue;
105400
+ if (binding.kind === "rows") {
105401
+ if (input.kind !== "group") continue;
105402
+ body = applyRows(body, binding, input, resolved.groups.get(input.key) ?? []);
105403
+ continue;
105404
+ }
105405
+ if (input.kind === "group") continue;
105406
+ const value = resolved.scalars.get(input.key);
105407
+ if (value === void 0) continue;
105408
+ body = writeValue(body, binding, input, value);
105409
+ }
105410
+ } catch (error) {
105411
+ if (!(error instanceof PathError)) throw error;
105412
+ return {
105413
+ ok: false,
105414
+ problems: [{
105415
+ code: "invalid-recipe",
105416
+ detail: error.message
105417
+ }]
105418
+ };
105419
+ }
105420
+ const parsed = AutomationRecipeSchema.safeParse(body);
105421
+ if (!parsed.success) return {
105422
+ ok: false,
105423
+ problems: parsed.error.issues.slice(0, 5).map((issue) => ({
105424
+ code: "invalid-recipe",
105425
+ detail: `${issue.path.join(".")}: ${issue.message}`
105426
+ }))
105427
+ };
105428
+ const { template: _ignored, ...recipe } = parsed.data;
105429
+ return {
105430
+ ok: true,
105431
+ recipe
105432
+ };
105433
+ }
105434
+ /**
105435
+ * An instance after its template changed (or vanished, `payload === null`):
105436
+ * re-expanded when its values still fit, otherwise its previous body kept and
105437
+ * the link flagged with the problems. Never dropped.
105438
+ */
105439
+ function reexpandAutomationInstance(payload, current) {
105440
+ const link = current.template;
105441
+ if (link === void 0) return {
105442
+ recipe: current,
105443
+ flagged: false
105444
+ };
105445
+ const expanded = payload === null ? {
105446
+ ok: false,
105447
+ problems: [{
105448
+ code: "missing-template",
105449
+ detail: `template "${link.templateId}" is gone`
105450
+ }]
105451
+ } : expandAutomationTemplate(payload, link.values);
105452
+ if (expanded.ok) return {
105453
+ recipe: {
105454
+ ...expanded.recipe,
105455
+ template: {
105456
+ templateId: link.templateId,
105457
+ values: link.values
105458
+ }
105459
+ },
105460
+ flagged: false
105461
+ };
105462
+ const [first, ...rest] = expanded.problems;
105463
+ if (first === void 0) return {
105464
+ recipe: current,
105465
+ flagged: false
105466
+ };
105467
+ return {
105468
+ recipe: {
105469
+ ...current,
105470
+ template: {
105471
+ ...link,
105472
+ problems: [first, ...rest]
105473
+ }
105474
+ },
105475
+ flagged: true
105476
+ };
105477
+ }
105478
+ zod.z.object({
105479
+ format: zod.z.literal("camstack.automation-template"),
105480
+ version: zod.z.literal(1),
105481
+ name: zod.z.string().min(1).max(120),
105482
+ payload: AutomationTemplatePayloadSchema
105483
+ });
105484
+ var TemplateKindSchema = zod.z.enum(["remote", "automation"]);
105485
+ var TEMPLATE_PAYLOAD_SCHEMAS = {
105486
+ remote: RemoteLayoutPayloadSchema,
105487
+ automation: AutomationTemplatePayloadSchema
105488
+ };
102907
105489
  /** The payload as the kind's schema reads it, or why it is not one. */
102908
105490
  function checkTemplatePayload(kind, payload) {
102909
105491
  const parsed = TEMPLATE_PAYLOAD_SCHEMAS[kind].safeParse(payload);
@@ -102922,7 +105504,9 @@ function checkTemplatePayload(kind, payload) {
102922
105504
  * button grid of a remote) and the schema each payload must satisfy are
102923
105505
  * declared by the system in `template-kinds.ts`. Nothing here is specific to a
102924
105506
  * kind: the engine validates a payload against its kind's schema and, on a
102925
- * delete, asks the kind's owner whether anything still points at the record.
105507
+ * delete, asks the kind's owner whether anything still points at the record
105508
+ * (a device's remote, an automation made from the template). Saving an
105509
+ * `automation` template re-expands every automation made from it (#527).
102926
105510
  *
102927
105511
  * Every refusal is a typed result — a UI says "unknown kind" or names the
102928
105512
  * devices that still use a template, without parsing text.
@@ -102934,14 +105518,20 @@ var TemplateRecordSchema = zod.z.object({
102934
105518
  /** Shaped by the kind; `checkTemplatePayload(kind, payload)` reads it. */
102935
105519
  payload: zod.z.unknown(),
102936
105520
  createdAt: zod.z.number(),
102937
- updatedAt: zod.z.number()
105521
+ updatedAt: zod.z.number(),
105522
+ /** Shipped with CamStack (`builtin:` ids): listed beside the operator's, never updated or deleted. */
105523
+ builtIn: zod.z.literal(true).optional()
102938
105524
  });
102939
105525
  var TemplateWriteResultSchema = zod.z.discriminatedUnion("status", [zod.z.object({
102940
105526
  status: zod.z.literal("saved"),
102941
105527
  template: TemplateRecordSchema
102942
105528
  }), zod.z.object({
102943
105529
  status: zod.z.literal("refused"),
102944
- reason: zod.z.enum(["invalid-payload", "not-found"]),
105530
+ reason: zod.z.enum([
105531
+ "invalid-payload",
105532
+ "not-found",
105533
+ "read-only"
105534
+ ]),
102945
105535
  detail: zod.z.string()
102946
105536
  })]);
102947
105537
  /** A device still pointing at a template. */
@@ -102949,12 +105539,19 @@ var TemplateUserSchema = zod.z.object({
102949
105539
  deviceId: zod.z.number().int().nonnegative(),
102950
105540
  name: zod.z.string()
102951
105541
  });
105542
+ /** An automation made from a template (#527): a core block whose recipe links to it. */
105543
+ var TemplateAutomationUserSchema = zod.z.object({
105544
+ blockId: zod.z.string().min(1),
105545
+ name: zod.z.string()
105546
+ });
102952
105547
  var TemplateDeleteResultSchema = zod.z.discriminatedUnion("status", [
102953
105548
  zod.z.object({ status: zod.z.literal("deleted") }),
102954
105549
  zod.z.object({ status: zod.z.literal("not-found") }),
105550
+ zod.z.object({ status: zod.z.literal("read-only") }),
102955
105551
  zod.z.object({
102956
105552
  status: zod.z.literal("in-use"),
102957
- devices: zod.z.array(TemplateUserSchema).min(1)
105553
+ devices: zod.z.array(TemplateUserSchema),
105554
+ automations: zod.z.array(TemplateAutomationUserSchema)
102958
105555
  })
102959
105556
  ]);
102960
105557
  var templateCapability = {
@@ -106488,6 +109085,7 @@ var ALL_CAPABILITY_DEFINITIONS = [
106488
109085
  doNotDisturbCapability,
106489
109086
  doorbellCapability,
106490
109087
  embeddingEncoderCapability,
109088
+ energySystemCapability,
106491
109089
  enumSensorCapability,
106492
109090
  eventEmitterCapability,
106493
109091
  faceGalleryCapability,
@@ -107509,6 +110107,225 @@ var BUILTIN_REMOTE_COMPONENTS = [
107509
110107
  }
107510
110108
  ];
107511
110109
  /**
110110
+ * Automation templates shipped with CamStack (#527). They are read-only records
110111
+ * of the template store: `template.list` returns them beside the operator's
110112
+ * own, under `builtin:` ids, and an update or delete of one is refused. They
110113
+ * are code, not seeded rows, so a new release changes them without a
110114
+ * migration and nothing an operator saved is ever overwritten.
110115
+ */
110116
+ var BUILTIN_TEMPLATE_ID_PREFIX = "builtin:";
110117
+ var BUILTIN_AUTOMATION_TEMPLATES = [{
110118
+ id: `${BUILTIN_TEMPLATE_ID_PREFIX}buttons-to-devices`,
110119
+ name: "Buttons → devices",
110120
+ payload: {
110121
+ version: 1,
110122
+ description: "Each row: when a button sends an event, run an action on a set of devices.",
110123
+ body: {
110124
+ when: {
110125
+ kind: "any",
110126
+ children: []
110127
+ },
110128
+ actions: [{
110129
+ kind: "choose",
110130
+ branches: []
110131
+ }],
110132
+ runMode: {
110133
+ mode: "queued",
110134
+ max: 5
110135
+ }
110136
+ },
110137
+ inputs: [{
110138
+ kind: "group",
110139
+ key: "buttons",
110140
+ label: "Buttons",
110141
+ maxRows: 6,
110142
+ inputs: [
110143
+ {
110144
+ kind: "device",
110145
+ key: "button",
110146
+ label: "Button",
110147
+ filter: { capability: "event-emitter" }
110148
+ },
110149
+ {
110150
+ kind: "event",
110151
+ key: "event",
110152
+ label: "Event",
110153
+ deviceInput: "button"
110154
+ },
110155
+ {
110156
+ kind: "device",
110157
+ key: "targets",
110158
+ label: "Devices",
110159
+ multiple: true
110160
+ },
110161
+ {
110162
+ kind: "action",
110163
+ key: "action",
110164
+ label: "Action",
110165
+ deviceInput: "targets"
110166
+ }
110167
+ ]
110168
+ }],
110169
+ bindings: [{
110170
+ kind: "rows",
110171
+ input: "buttons",
110172
+ path: ["when", "children"],
110173
+ item: { kind: "device-fired" },
110174
+ bindings: [
110175
+ {
110176
+ kind: "row-id",
110177
+ path: ["id"]
110178
+ },
110179
+ {
110180
+ kind: "value",
110181
+ input: "button",
110182
+ path: ["deviceId"]
110183
+ },
110184
+ {
110185
+ kind: "value",
110186
+ input: "event",
110187
+ path: []
110188
+ }
110189
+ ]
110190
+ }, {
110191
+ kind: "rows",
110192
+ input: "buttons",
110193
+ path: [
110194
+ "actions",
110195
+ 0,
110196
+ "branches"
110197
+ ],
110198
+ item: {
110199
+ if: {
110200
+ kind: "triggered-by",
110201
+ leafIds: []
110202
+ },
110203
+ steps: [{ kind: "command" }]
110204
+ },
110205
+ bindings: [
110206
+ {
110207
+ kind: "row-id",
110208
+ path: [
110209
+ "if",
110210
+ "leafIds",
110211
+ 0
110212
+ ]
110213
+ },
110214
+ {
110215
+ kind: "value",
110216
+ input: "targets",
110217
+ path: [
110218
+ "steps",
110219
+ 0,
110220
+ "target"
110221
+ ],
110222
+ as: "target"
110223
+ },
110224
+ {
110225
+ kind: "value",
110226
+ input: "action",
110227
+ path: ["steps", 0]
110228
+ }
110229
+ ]
110230
+ }]
110231
+ }
110232
+ }, {
110233
+ id: `${BUILTIN_TEMPLATE_ID_PREFIX}motion-light`,
110234
+ name: "Motion → light, off after a delay",
110235
+ payload: {
110236
+ version: 1,
110237
+ description: "Turns lights on when a motion sensor detects motion and off once it has been quiet for the delay. New motion restarts the delay.",
110238
+ body: {
110239
+ when: {
110240
+ kind: "device-becomes",
110241
+ cap: "motion",
110242
+ fieldPath: "detected",
110243
+ becomes: true
110244
+ },
110245
+ actions: [
110246
+ {
110247
+ kind: "command",
110248
+ actionId: "switch.on"
110249
+ },
110250
+ {
110251
+ kind: "wait",
110252
+ seconds: 300
110253
+ },
110254
+ {
110255
+ kind: "command",
110256
+ actionId: "switch.off"
110257
+ }
110258
+ ],
110259
+ runMode: { mode: "restart" }
110260
+ },
110261
+ inputs: [
110262
+ {
110263
+ kind: "device",
110264
+ key: "sensor",
110265
+ label: "Motion sensor",
110266
+ filter: { capability: "motion" }
110267
+ },
110268
+ {
110269
+ kind: "device",
110270
+ key: "lights",
110271
+ label: "Lights",
110272
+ multiple: true,
110273
+ filter: { capability: "switch" }
110274
+ },
110275
+ {
110276
+ kind: "duration",
110277
+ key: "delay",
110278
+ label: "Off after (seconds)",
110279
+ min: 10,
110280
+ max: 3600,
110281
+ default: 300
110282
+ }
110283
+ ],
110284
+ bindings: [
110285
+ {
110286
+ kind: "value",
110287
+ input: "sensor",
110288
+ path: ["when", "deviceId"]
110289
+ },
110290
+ {
110291
+ kind: "value",
110292
+ input: "lights",
110293
+ path: [
110294
+ "actions",
110295
+ 0,
110296
+ "target"
110297
+ ],
110298
+ as: "target"
110299
+ },
110300
+ {
110301
+ kind: "value",
110302
+ input: "delay",
110303
+ path: [
110304
+ "actions",
110305
+ 1,
110306
+ "seconds"
110307
+ ]
110308
+ },
110309
+ {
110310
+ kind: "value",
110311
+ input: "lights",
110312
+ path: [
110313
+ "actions",
110314
+ 2,
110315
+ "target"
110316
+ ],
110317
+ as: "target"
110318
+ }
110319
+ ]
110320
+ }
110321
+ }];
110322
+ function isBuiltinTemplateId(id) {
110323
+ return id.startsWith(BUILTIN_TEMPLATE_ID_PREFIX);
110324
+ }
110325
+ function builtinAutomationTemplate(id) {
110326
+ return BUILTIN_AUTOMATION_TEMPLATES.find((t) => t.id === id);
110327
+ }
110328
+ /**
107512
110329
  * Propose a running threshold from a device's own power history (planning#405).
107513
110330
  *
107514
110331
  * Pure and deterministic: the same series gives the same answer. The series is
@@ -109020,6 +111837,7 @@ var DEVICE_LOCAL_STATE_CAPS = {
109020
111837
  dishwasher: dishwasherCapability,
109021
111838
  doNotDisturb: doNotDisturbCapability,
109022
111839
  doorbell: doorbellCapability,
111840
+ energySystem: energySystemCapability,
109023
111841
  enumSensor: enumSensorCapability,
109024
111842
  eventEmitter: eventEmitterCapability,
109025
111843
  fanControl: fanControlCapability,
@@ -110185,7 +113003,7 @@ var DeclaredDevices = class {
110185
113003
  return removed;
110186
113004
  }
110187
113005
  };
110188
- DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.HeatPump, DeviceType.Camera, DeviceType.Hub, DeviceType.Switch, DeviceType.Siren, DeviceType.Light, DeviceType.Fan, DeviceType.Sensor, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Gateway;
113006
+ DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.HeatPump, DeviceType.EnergySystem, DeviceType.Camera, DeviceType.Hub, DeviceType.Switch, DeviceType.Siren, DeviceType.Light, DeviceType.Fan, DeviceType.Sensor, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Gateway;
110189
113007
  new Set(Object.values(DeviceType));
110190
113008
  /** True when a value is a navigable node: a plain object OR a tRPC v11 client
110191
113009
  * proxy node (a callable `Proxy(noop)` → `typeof === 'function'`, NOT an
@@ -113065,6 +115883,7 @@ var HERO_LAYOUT_BY_TYPE = {
113065
115883
  [DeviceType.Humidifier]: HUMIDIFIER_LAYOUT,
113066
115884
  [DeviceType.WaterHeater]: CLIMATE_LAYOUT,
113067
115885
  [DeviceType.HeatPump]: HEAT_PUMP_LAYOUT,
115886
+ [DeviceType.EnergySystem]: HERO_LAYOUT_DEFAULT,
113068
115887
  [DeviceType.Fan]: FAN_LAYOUT,
113069
115888
  [DeviceType.MediaPlayer]: MEDIA_PLAYER_LAYOUT,
113070
115889
  [DeviceType.AlarmPanel]: ALARM_LAYOUT,
@@ -113788,6 +116607,7 @@ var HERO_LOOK_BY_TYPE = {
113788
116607
  [DeviceType.Humidifier]: HUMIDIFIER_LOOK,
113789
116608
  [DeviceType.WaterHeater]: WATER_HEATER_LOOK,
113790
116609
  [DeviceType.HeatPump]: HEAT_PUMP_LOOK,
116610
+ [DeviceType.EnergySystem]: HERO_LOOK_DEFAULT,
113791
116611
  [DeviceType.Fan]: FAN_LOOK,
113792
116612
  [DeviceType.MediaPlayer]: MEDIA_PLAYER_LOOK,
113793
116613
  [DeviceType.AlarmPanel]: ALARM_LOOK,
@@ -117416,6 +120236,13 @@ var METHOD_ACCESS_MAP = Object.freeze({
117416
120236
  access: "delete",
117417
120237
  role: "admin"
117418
120238
  },
120239
+ "energySystem.getStatus": {
120240
+ capName: "energy-system",
120241
+ capScope: "device",
120242
+ addonId: null,
120243
+ access: "view",
120244
+ role: "viewer"
120245
+ },
117419
120246
  "enumSensor.getStatus": {
117420
120247
  capName: "enum-sensor",
117421
120248
  capScope: "device",
@@ -124778,7 +127605,7 @@ function offered(received) {
124778
127605
  };
124779
127606
  }
124780
127607
  offered(HA_AS), withheld(HOMEKIT_REASON), withheld(ALEXA_REASON), withheld(GOOGLE_REASON), withheld(MATTER_REASON);
124781
- DeviceType.Camera, DeviceType.Hub, DeviceType.Light, DeviceType.Siren, DeviceType.Switch, DeviceType.Sensor, DeviceType.Climate, DeviceType.HeatPump, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.Fan, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Gateway;
127608
+ DeviceType.Camera, DeviceType.Hub, DeviceType.Light, DeviceType.Siren, DeviceType.Switch, DeviceType.Sensor, DeviceType.Climate, DeviceType.HeatPump, DeviceType.EnergySystem, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.Fan, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Dryer, DeviceType.Gateway;
124782
127609
  DeviceRole.Siren, DeviceRole.Floodlight, DeviceRole.Spotlight, DeviceRole.PirSensor, DeviceRole.Chime, DeviceRole.Autotrack, DeviceRole.Nightvision, DeviceRole.PrivacyMask, DeviceRole.Doorbell, DeviceRole.CoverBlind, DeviceRole.CoverShutter, DeviceRole.CoverAwning, DeviceRole.CoverCurtain, DeviceRole.CoverGarage, DeviceRole.CoverGate, DeviceRole.CoverDoor, DeviceRole.CoverWindow, DeviceRole.BinaryHelper, DeviceRole.Outlet, DeviceRole.SwitchHeater, DeviceRole.SwitchFan, DeviceRole.SwitchLight, DeviceRole.ClimateAc, DeviceRole.ClimateThermostat, DeviceRole.ClimateFloor, DeviceRole.ClimateRadiator, DeviceRole.ClimateHeater, DeviceRole.ClimateHeatPumpCircuit, DeviceRole.MotionSensor, DeviceRole.ContactSensor, DeviceRole.LeakSensor, DeviceRole.SmokeSensor, DeviceRole.COSensor, DeviceRole.GasSensor, DeviceRole.TamperSensor, DeviceRole.VibrationSensor, DeviceRole.ConnectivitySensor, DeviceRole.SoundSensor, DeviceRole.BinarySensor, DeviceRole.TemperatureSensor, DeviceRole.HumiditySensor, DeviceRole.AmbientLightSensor, DeviceRole.PressureSensor, DeviceRole.WindSensor, DeviceRole.RainSensor, DeviceRole.UvSensor, DeviceRole.SolarRadiationSensor, DeviceRole.SoilMoistureSensor, DeviceRole.PowerSensor, DeviceRole.EnergySensor, DeviceRole.VoltageSensor, DeviceRole.CurrentSensor, DeviceRole.AirQualitySensor, DeviceRole.BatterySensor, DeviceRole.NumericSensor, DeviceRole.EnumSensor, DeviceRole.DateTimeSensor, DeviceRole.GenericSensor, DeviceRole.NumericControl, DeviceRole.SelectControl, DeviceRole.TextControl, DeviceRole.DateTimeControl, DeviceRole.MobilePushNotifier, DeviceRole.MessagingNotifier, DeviceRole.EmailNotifier, DeviceRole.GenericNotifier, DeviceRole.IrTransmitter;
124783
127610
  new Set(Object.values(DeviceType));
124784
127611
  new Set(Object.values(DeviceRole));
@@ -124813,6 +127640,7 @@ var CAP_NAMES_WITH_STATUS = [
124813
127640
  "dishwasher",
124814
127641
  "do-not-disturb",
124815
127642
  "doorbell",
127643
+ "energy-system",
124816
127644
  "enum-sensor",
124817
127645
  "event-emitter",
124818
127646
  "fan-control",
@@ -125826,6 +128654,11 @@ Object.freeze({
125826
128654
  form: "single",
125827
128655
  optional: false
125828
128656
  }],
128657
+ "energySystem.getStatus": [{
128658
+ name: "deviceId",
128659
+ form: "single",
128660
+ optional: false
128661
+ }],
125829
128662
  "enumSensor.getStatus": [{
125830
128663
  name: "deviceId",
125831
128664
  form: "single",
@@ -127984,7 +130817,7 @@ Object.freeze({
127984
130817
  });
127985
130818
  /**
127986
130819
  * Per-cap runtime-state policy, projected from every `*.cap.ts` that declares
127987
- * `runtimeState`. 82 caps: 42 `restored`, 40 `session`.
130820
+ * `runtimeState`. 83 caps: 42 `restored`, 41 `session`.
127988
130821
  *
127989
130822
  * A cap absent from this map has no runtime-state slice at all. A cap PRESENT
127990
130823
  * with `durability: 'session'` has one and has decided not to keep it.
@@ -128079,6 +130912,10 @@ var RUNTIME_STATE_POLICY = {
128079
130912
  durability: "restored",
128080
130913
  volatileFields: []
128081
130914
  },
130915
+ "energy-system": {
130916
+ durability: "session",
130917
+ volatileFields: ["lastFetchedAt"]
130918
+ },
128082
130919
  "enum-sensor": {
128083
130920
  durability: "restored",
128084
130921
  volatileFields: ["lastFetchedAt", "timestamp"]
@@ -130256,6 +133093,18 @@ Object.defineProperty(exports, "AutomationStateDocSchema", {
130256
133093
  return AutomationStateDocSchema;
130257
133094
  }
130258
133095
  });
133096
+ Object.defineProperty(exports, "AutomationTemplatePayloadSchema", {
133097
+ enumerable: true,
133098
+ get: function() {
133099
+ return AutomationTemplatePayloadSchema;
133100
+ }
133101
+ });
133102
+ Object.defineProperty(exports, "BUILTIN_AUTOMATION_TEMPLATES", {
133103
+ enumerable: true,
133104
+ get: function() {
133105
+ return BUILTIN_AUTOMATION_TEMPLATES;
133106
+ }
133107
+ });
130259
133108
  Object.defineProperty(exports, "BUILTIN_REMOTE_COMPONENTS", {
130260
133109
  enumerable: true,
130261
133110
  get: function() {
@@ -131420,6 +134269,12 @@ Object.defineProperty(exports, "buildStreamParamsConfigSchema", {
131420
134269
  return buildStreamParamsConfigSchema;
131421
134270
  }
131422
134271
  });
134272
+ Object.defineProperty(exports, "builtinAutomationTemplate", {
134273
+ enumerable: true,
134274
+ get: function() {
134275
+ return builtinAutomationTemplate;
134276
+ }
134277
+ });
131423
134278
  Object.defineProperty(exports, "calendarsCapability", {
131424
134279
  enumerable: true,
131425
134280
  get: function() {
@@ -132020,6 +134875,12 @@ Object.defineProperty(exports, "gbToBytes", {
132020
134875
  return gbToBytes;
132021
134876
  }
132022
134877
  });
134878
+ Object.defineProperty(exports, "generateAutomationBlock", {
134879
+ enumerable: true,
134880
+ get: function() {
134881
+ return generateAutomationBlock;
134882
+ }
134883
+ });
132023
134884
  Object.defineProperty(exports, "generateDeviceAlias", {
132024
134885
  enumerable: true,
132025
134886
  get: function() {
@@ -132092,6 +134953,12 @@ Object.defineProperty(exports, "implementedMethodsOf", {
132092
134953
  return implementedMethodsOf;
132093
134954
  }
132094
134955
  });
134956
+ Object.defineProperty(exports, "instanceCodeHash", {
134957
+ enumerable: true,
134958
+ get: function() {
134959
+ return instanceCodeHash;
134960
+ }
134961
+ });
132095
134962
  Object.defineProperty(exports, "integrateReading", {
132096
134963
  enumerable: true,
132097
134964
  get: function() {
@@ -132146,6 +135013,12 @@ Object.defineProperty(exports, "isArrayOutputSchema", {
132146
135013
  return isArrayOutputSchema;
132147
135014
  }
132148
135015
  });
135016
+ Object.defineProperty(exports, "isBuiltinTemplateId", {
135017
+ enumerable: true,
135018
+ get: function() {
135019
+ return isBuiltinTemplateId;
135020
+ }
135021
+ });
132149
135022
  Object.defineProperty(exports, "isCollectionArrayMethod", {
132150
135023
  enumerable: true,
132151
135024
  get: function() {
@@ -132644,6 +135517,12 @@ Object.defineProperty(exports, "preconditionOf", {
132644
135517
  return preconditionOf;
132645
135518
  }
132646
135519
  });
135520
+ Object.defineProperty(exports, "prepareRecipeUnits", {
135521
+ enumerable: true,
135522
+ get: function() {
135523
+ return prepareRecipeUnits;
135524
+ }
135525
+ });
132647
135526
  Object.defineProperty(exports, "problemsBlockSave", {
132648
135527
  enumerable: true,
132649
135528
  get: function() {
@@ -132680,6 +135559,12 @@ Object.defineProperty(exports, "ptzAutotrackCapability", {
132680
135559
  return ptzAutotrackCapability;
132681
135560
  }
132682
135561
  });
135562
+ Object.defineProperty(exports, "readRecipeLiteral", {
135563
+ enumerable: true,
135564
+ get: function() {
135565
+ return readRecipeLiteral;
135566
+ }
135567
+ });
132683
135568
  Object.defineProperty(exports, "readStoredRemoteConfig", {
132684
135569
  enumerable: true,
132685
135570
  get: function() {
@@ -132722,6 +135607,12 @@ Object.defineProperty(exports, "reducePoints", {
132722
135607
  return reducePoints;
132723
135608
  }
132724
135609
  });
135610
+ Object.defineProperty(exports, "reexpandAutomationInstance", {
135611
+ enumerable: true,
135612
+ get: function() {
135613
+ return reexpandAutomationInstance;
135614
+ }
135615
+ });
132725
135616
  Object.defineProperty(exports, "remoteCapability", {
132726
135617
  enumerable: true,
132727
135618
  get: function() {
@@ -132740,6 +135631,12 @@ Object.defineProperty(exports, "remoteSourceSteps", {
132740
135631
  return remoteSourceSteps;
132741
135632
  }
132742
135633
  });
135634
+ Object.defineProperty(exports, "replaceRecipeLiteral", {
135635
+ enumerable: true,
135636
+ get: function() {
135637
+ return replaceRecipeLiteral;
135638
+ }
135639
+ });
132743
135640
  Object.defineProperty(exports, "replacedFieldKeys", {
132744
135641
  enumerable: true,
132745
135642
  get: function() {