@camstack/addon-provider-homeassistant 1.1.15 → 1.1.17

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 (3) hide show
  1. package/dist/addon.js +1348 -167
  2. package/dist/addon.mjs +1348 -167
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -4629,7 +4629,7 @@ function _instanceof(cls, params = {}) {
4629
4629
  return inst;
4630
4630
  }
4631
4631
  //#endregion
4632
- //#region ../types/dist/sleep-MHm--th-.mjs
4632
+ //#region ../types/dist/sleep-BiDFW0E7.mjs
4633
4633
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
4634
4634
  EventCategory["SystemBoot"] = "system.boot";
4635
4635
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -5442,6 +5442,100 @@ function createDurableState(deps) {
5442
5442
  };
5443
5443
  }
5444
5444
  /**
5445
+ * Per-node scoping for the shared addon-settings blob.
5446
+ *
5447
+ * An addon's settings store is hub-central (the `addon-settings` cap is
5448
+ * hub-routed — the hub instance answers for every node), so fields whose
5449
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
5450
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
5451
+ * the single shared blob. The SCHEMA field key stays bare: the write path
5452
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
5453
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
5454
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
5455
+ *
5456
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
5457
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
5458
+ * schema and routes reads/writes through these helpers.
5459
+ *
5460
+ * ## No bare-key fallback — deliberate
5461
+ *
5462
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
5463
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
5464
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
5465
+ * the store is invisible to every node, hub included, so one node's
5466
+ * selection can never leak onto another. (This generalizes the
5467
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
5468
+ * arbitrary set of per-node field keys.)
5469
+ *
5470
+ * Pure functions only — no I/O, no imports beyond the language. This is a
5471
+ * LEAF module: import it via its deep path, never from the root barrel.
5472
+ */
5473
+ /**
5474
+ * Normalize a raw kernel node id to the bare node id used for scoping.
5475
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
5476
+ * processes; per-node settings are per-NODE, so strip the addon segment.
5477
+ * `undefined` / `null` / empty falls back to `'hub'`.
5478
+ */
5479
+ function normalizeNodeId(raw) {
5480
+ if (raw === void 0 || raw === null || raw === "") return "hub";
5481
+ const slashIdx = raw.indexOf("/");
5482
+ if (slashIdx < 0) return raw;
5483
+ const bare = raw.slice(0, slashIdx);
5484
+ return bare === "" ? "hub" : bare;
5485
+ }
5486
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
5487
+ function nodeScopedKey(base, nodeId) {
5488
+ return `${base}@${normalizeNodeId(nodeId)}`;
5489
+ }
5490
+ /**
5491
+ * Read a node's value for a per-node field from the raw shared store:
5492
+ * the node-scoped key when present, otherwise `undefined`.
5493
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
5494
+ * schema `default` win on `undefined`.
5495
+ */
5496
+ function readNodeValue(store, base, nodeId) {
5497
+ return store[nodeScopedKey(base, nodeId)];
5498
+ }
5499
+ /**
5500
+ * Re-map a UI/settings patch so every bare perNode field persists under the
5501
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
5502
+ * the write path so a save for one node never clobbers another node's value
5503
+ * (and the bare key is never written). Returns a new object — the input
5504
+ * patch is not mutated.
5505
+ */
5506
+ function scopePatch(patch, perNodeKeys, nodeId) {
5507
+ const out = {};
5508
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
5509
+ return out;
5510
+ }
5511
+ /**
5512
+ * Project the raw shared store onto the bare schema keys for ONE node so a
5513
+ * UI schema (whose field keys are bare) hydrates from that node's own
5514
+ * values:
5515
+ *
5516
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
5517
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
5518
+ * legacy key must never hydrate any node — no bare fallback).
5519
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
5520
+ * each bare perNode key; when the node has no scoped key the bare key is
5521
+ * left ABSENT so the field's schema `default` wins.
5522
+ *
5523
+ * Returns a new object — the input store is not mutated.
5524
+ */
5525
+ function projectStore(store, perNodeKeys, nodeId) {
5526
+ const out = {};
5527
+ for (const [key, value] of Object.entries(store)) {
5528
+ if (key.includes("@")) continue;
5529
+ if (perNodeKeys.has(key)) continue;
5530
+ out[key] = value;
5531
+ }
5532
+ for (const base of perNodeKeys) {
5533
+ const value = readNodeValue(store, base, nodeId);
5534
+ if (value !== void 0) out[base] = value;
5535
+ }
5536
+ return out;
5537
+ }
5538
+ /**
5445
5539
  * Base class for CamStack addons. Eliminates settings boilerplate:
5446
5540
  *
5447
5541
  * - Typed `config` property with automatic resolution from store + defaults
@@ -5609,23 +5703,63 @@ var BaseAddon = class {
5609
5703
  deviceSettingsSchema() {
5610
5704
  return null;
5611
5705
  }
5612
- async getGlobalSettings(overlay, cap, _nodeId) {
5706
+ async getGlobalSettings(overlay, cap, nodeId) {
5613
5707
  const schema = this.globalSettingsSchema(cap);
5614
5708
  if (!schema) return { sections: [] };
5615
- const raw = await this._ctx?.settings?.readAddonStore() ?? {};
5709
+ const projected = await this.resolveGlobalStore(nodeId, cap);
5616
5710
  return hydrateSchema(schema, overlay ? {
5617
- ...raw,
5711
+ ...projected,
5618
5712
  ...overlay
5619
- } : raw);
5713
+ } : projected);
5620
5714
  }
5621
- async updateGlobalSettings(patch, _nodeId) {
5622
- await this._ctx?.settings?.writeAddonStore(patch);
5715
+ /**
5716
+ * The raw addon store PROJECTED onto the target node's bare per-node keys:
5717
+ * every `perNode: true` field carries THAT node's scoped value on its bare
5718
+ * key (absent scoped key ⇒ key absent, so the schema `default` wins — no
5719
+ * bare fallback), all `@`-scoped and stray bare per-node keys are dropped.
5720
+ * A no-op passthrough when the schema declares no `perNode` field.
5721
+ *
5722
+ * This is the sanctioned way for a `getGlobalSettings` OVERRIDE that needs
5723
+ * the store for custom option logic (option narrowing, value snapping) to
5724
+ * read it per-node — never `ctx.settings.readAddonStore()` directly.
5725
+ * `nodeId` omitted ⇒ the local node (node-blind injection from ctx).
5726
+ */
5727
+ async resolveGlobalStore(nodeId, cap) {
5728
+ const raw = await this._ctx?.settings?.readAddonStore() ?? {};
5729
+ const keys = this.perNodeKeys(cap);
5730
+ const node = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
5731
+ return keys.size > 0 ? projectStore(raw, keys, node) : raw;
5732
+ }
5733
+ async updateGlobalSettings(patch, nodeId) {
5734
+ const keys = this.perNodeKeys();
5735
+ const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
5736
+ const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
5737
+ const barePatch = patch;
5738
+ const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
5739
+ await this._ctx?.settings?.writeAddonStore(scoped);
5740
+ if (target !== localNode) return;
5623
5741
  await this.resolveConfig();
5624
5742
  await this.onConfigChanged();
5625
5743
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
5626
5744
  this.maybeAutoRestart(patch, this.globalSettingsSchema());
5627
5745
  }
5628
5746
  /**
5747
+ * The set of field keys the global settings schema declares `perNode: true`
5748
+ * — derived once per `cap` argument and memoized (schemas are static
5749
+ * declarations). Empty set ⇒ every per-node code path is bypassed and the
5750
+ * settings API behaves exactly like the legacy node-agnostic one.
5751
+ */
5752
+ _perNodeKeysCache = /* @__PURE__ */ new Map();
5753
+ perNodeKeys(cap) {
5754
+ const cacheKey = cap ?? "";
5755
+ const cached = this._perNodeKeysCache.get(cacheKey);
5756
+ if (cached) return cached;
5757
+ const schema = this.globalSettingsSchema(cap);
5758
+ const keys = new Set(schema ? schema.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
5759
+ this._perNodeKeysCache.set(cacheKey, keys);
5760
+ return keys;
5761
+ }
5762
+ /**
5629
5763
  * If any field in `patch` is marked `requiresRestart` in `schema`,
5630
5764
  * schedule an addon restart for the next tick. Deferred via
5631
5765
  * `setImmediate` so the tRPC mutation that triggered the write has
@@ -5778,12 +5912,19 @@ var BaseAddon = class {
5778
5912
  * The merge is shallow: each key in `defaults` is checked against the store.
5779
5913
  * Only keys present in defaults are read — the store can contain extra keys
5780
5914
  * (e.g. from older versions) without polluting the typed config.
5915
+ *
5916
+ * Keys the global settings schema declares `perNode: true` resolve from
5917
+ * THIS node's scoped key (`<key>@<localNode>`) via `readNodeValue` — never
5918
+ * from the bare key — so a per-node field resolves to this node's own
5919
+ * selection at boot (absent scoped key ⇒ the constructor default wins).
5781
5920
  */
5782
5921
  async resolveConfig() {
5783
5922
  const stored = await this.readAddonStoreWithRetry();
5923
+ const perNode = this.perNodeKeys();
5924
+ const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
5784
5925
  const resolved = { ...this.defaults };
5785
5926
  for (const key of Object.keys(this.defaults)) {
5786
- const storedValue = stored[key];
5927
+ const storedValue = perNode.has(key) ? readNodeValue(stored, key, localNode) : stored[key];
5787
5928
  if (storedValue !== void 0 && storedValue !== null) {
5788
5929
  const defaultType = typeof this.defaults[key];
5789
5930
  if (typeof storedValue === defaultType) resolved[key] = storedValue;
@@ -5867,6 +6008,27 @@ var BaseAddon = class {
5867
6008
  }
5868
6009
  };
5869
6010
  /**
6011
+ * Collect the keys of every field marked `perNode: true`, recursing into
6012
+ * layout containers (`group` fields and `sub-tabs` tabs) the same way
6013
+ * `hydrateSchema` does. Valueless structural fields (separator/info/…)
6014
+ * don't declare `perNode` and are excluded by the `in` narrowing.
6015
+ */
6016
+ function collectPerNodeFieldKeys(fields) {
6017
+ const collected = [];
6018
+ for (const field of fields) {
6019
+ if (field.type === "group") {
6020
+ collected.push(...collectPerNodeFieldKeys(field.fields));
6021
+ continue;
6022
+ }
6023
+ if (field.type === "sub-tabs") {
6024
+ for (const tab of field.tabs) collected.push(...collectPerNodeFieldKeys(tab.fields));
6025
+ continue;
6026
+ }
6027
+ if ("perNode" in field && field.perNode === true) collected.push(field.key);
6028
+ }
6029
+ return collected;
6030
+ }
6031
+ /**
5870
6032
  * Normalize an `ICamstackAddon.initialize()` return value into the
5871
6033
  * `AddonInitResult` envelope. Arrays are wrapped into `{ providers }`;
5872
6034
  * envelopes pass through; void stays void.
@@ -6274,6 +6436,13 @@ var DeviceType = /* @__PURE__ */ function(DeviceType) {
6274
6436
  /** Single still-image entity (HA `image.*`). Read-only display of an
6275
6437
  * `entity_picture` signed URL the browser loads directly. `image` cap. */
6276
6438
  DeviceType["Image"] = "image";
6439
+ /** Smart pet feeder — cloud-connected food dispenser with a bowl food
6440
+ * level, battery, desiccant life, feeding state and manual-feed /
6441
+ * call-pet / maintenance actions. Installed with the `pet-feeder` cap;
6442
+ * dual-hopper models (D4S/D4SH) expose per-hopper portions. Sources:
6443
+ * native PetKit (`nodepetkit` `FeederDevice`), reusable by other feeder
6444
+ * integrations sharing the same food/desiccant/hopper surface. */
6445
+ DeviceType["PetFeeder"] = "pet-feeder";
6277
6446
  return DeviceType;
6278
6447
  }({});
6279
6448
  var DeviceFeature = /* @__PURE__ */ function(DeviceFeature) {
@@ -7438,6 +7607,601 @@ var _macroLookup = /* @__PURE__ */ new Map();
7438
7607
  for (const [k, v] of Object.entries(YAMNET_TO_MACRO.mapping)) _macroLookup.set(k.toLowerCase(), v);
7439
7608
  for (const [k, v] of Object.entries(APPLE_SA_TO_MACRO.mapping)) _macroLookup.set(k.toLowerCase(), v);
7440
7609
  /**
7610
+ * Error types for the safe expression engine. Two distinct classes so callers
7611
+ * can tell a compile-time (grammar) failure from a runtime (evaluation)
7612
+ * failure — both are non-fatal to the host: read paths degrade to "skip link".
7613
+ */
7614
+ /** Thrown by the tokenizer / parser. Carries a 0-based source `position` when
7615
+ * the failure is anchored to a character (author-facing inline feedback). */
7616
+ var ExpressionParseError = class extends Error {
7617
+ position;
7618
+ constructor(message, position) {
7619
+ super(message);
7620
+ this.name = "ExpressionParseError";
7621
+ this.position = position;
7622
+ }
7623
+ };
7624
+ /** Thrown by the evaluator (unknown identifier, type mismatch, non-finite
7625
+ * result, unknown builtin, step-budget exceeded). */
7626
+ var ExpressionEvalError = class extends Error {
7627
+ constructor(message) {
7628
+ super(message);
7629
+ this.name = "ExpressionEvalError";
7630
+ }
7631
+ };
7632
+ /**
7633
+ * Resource-bound constants for the safe expression engine.
7634
+ *
7635
+ * Every bound is defense-in-depth: the grammar is non-Turing-complete (no
7636
+ * loops, recursion, lambdas or member access — see `ast.ts`), so evaluation is
7637
+ * O(nodeCount) by construction. These caps merely put a hard ceiling on the
7638
+ * work a single author-supplied expression can request, so a hostile or
7639
+ * accidental pathological string can never spend unbounded CPU/memory.
7640
+ */
7641
+ /** Max source length (chars) — checked BEFORE tokenizing so a huge string is
7642
+ * rejected without allocation. */
7643
+ var MAX_EXPRESSION_SOURCE_LENGTH = 2048;
7644
+ /** A legal binding / identifier name. */
7645
+ var EXPRESSION_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
7646
+ /** Binding names an author may NOT use: `now` is auto-injected; the literal
7647
+ * keywords lex as values, not identifiers, so binding to them is meaningless. */
7648
+ var RESERVED_BINDING_NAMES = new Set([
7649
+ "now",
7650
+ "true",
7651
+ "false",
7652
+ "null"
7653
+ ]);
7654
+ /**
7655
+ * Tokenizer for the safe expression mini-language. Hand-rolled, single-pass,
7656
+ * zero-dependency. The grammar is deliberately boring: decimal numbers,
7657
+ * single/double-quoted strings with a tiny escape set, identifiers, the three
7658
+ * value keywords (`true`/`false`/`null`) and a fixed punctuator set. Anything
7659
+ * outside that — a bare `.`, `=`, `[`, `]`, `{`, `}`, `;`, backtick, `&`, `|` —
7660
+ * is a parse error with a source position, so member access / assignment /
7661
+ * template literals are lexically impossible.
7662
+ */
7663
+ var KEYWORDS = new Set([
7664
+ "true",
7665
+ "false",
7666
+ "null"
7667
+ ]);
7668
+ function isDigit(ch) {
7669
+ return ch >= "0" && ch <= "9";
7670
+ }
7671
+ function isIdentStart(ch) {
7672
+ return ch >= "A" && ch <= "Z" || ch >= "a" && ch <= "z" || ch === "_";
7673
+ }
7674
+ function isIdentPart(ch) {
7675
+ return isIdentStart(ch) || isDigit(ch);
7676
+ }
7677
+ function isWhitespace(ch) {
7678
+ return ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
7679
+ }
7680
+ /** Tokenize `source` into a flat token list ending with a single `eof` token.
7681
+ * Throws `ExpressionParseError` on any illegal character or unterminated
7682
+ * string. */
7683
+ function tokenize(source) {
7684
+ if (source.length > 2048) throw new ExpressionParseError(`expression too long (${source.length} > ${MAX_EXPRESSION_SOURCE_LENGTH} chars)`, 0);
7685
+ const tokens = [];
7686
+ let i = 0;
7687
+ const n = source.length;
7688
+ while (i < n) {
7689
+ const ch = source[i];
7690
+ if (isWhitespace(ch)) {
7691
+ i += 1;
7692
+ continue;
7693
+ }
7694
+ if (isDigit(ch)) {
7695
+ const start = i;
7696
+ while (i < n && isDigit(source[i])) i += 1;
7697
+ if (i < n && source[i] === ".") {
7698
+ if (i + 1 >= n || !isDigit(source[i + 1])) throw new ExpressionParseError("malformed number: decimal point needs a digit", i);
7699
+ i += 1;
7700
+ while (i < n && isDigit(source[i])) i += 1;
7701
+ }
7702
+ const text = source.slice(start, i);
7703
+ const value = Number(text);
7704
+ if (!Number.isFinite(value)) throw new ExpressionParseError(`malformed number: '${text}'`, start);
7705
+ tokens.push({
7706
+ type: "number",
7707
+ value,
7708
+ pos: start
7709
+ });
7710
+ continue;
7711
+ }
7712
+ if (ch === "'" || ch === "\"") {
7713
+ const quote = ch;
7714
+ const start = i;
7715
+ i += 1;
7716
+ let out = "";
7717
+ let closed = false;
7718
+ while (i < n) {
7719
+ const c = source[i];
7720
+ if (c === "\\") {
7721
+ const next = i + 1 < n ? source[i + 1] : "";
7722
+ if (next === "\\" || next === "'" || next === "\"") {
7723
+ out += next;
7724
+ i += 2;
7725
+ continue;
7726
+ }
7727
+ throw new ExpressionParseError(`invalid string escape: '\\${next}'`, i);
7728
+ }
7729
+ if (c === quote) {
7730
+ closed = true;
7731
+ i += 1;
7732
+ break;
7733
+ }
7734
+ out += c;
7735
+ i += 1;
7736
+ }
7737
+ if (!closed) throw new ExpressionParseError("unterminated string literal", start);
7738
+ tokens.push({
7739
+ type: "string",
7740
+ value: out,
7741
+ pos: start
7742
+ });
7743
+ continue;
7744
+ }
7745
+ if (isIdentStart(ch)) {
7746
+ const start = i;
7747
+ while (i < n && isIdentPart(source[i])) i += 1;
7748
+ const text = source.slice(start, i);
7749
+ if (KEYWORDS.has(text)) tokens.push({
7750
+ type: "keyword",
7751
+ keyword: keywordOf(text),
7752
+ pos: start
7753
+ });
7754
+ else tokens.push({
7755
+ type: "identifier",
7756
+ name: text,
7757
+ pos: start
7758
+ });
7759
+ continue;
7760
+ }
7761
+ const two = i + 1 < n ? source.slice(i, i + 2) : "";
7762
+ if (two === "<=" || two === ">=" || two === "==" || two === "!=" || two === "&&" || two === "||") {
7763
+ tokens.push({
7764
+ type: "punct",
7765
+ punct: two,
7766
+ pos: i
7767
+ });
7768
+ i += 2;
7769
+ continue;
7770
+ }
7771
+ if (isSinglePunct(ch)) {
7772
+ tokens.push({
7773
+ type: "punct",
7774
+ punct: ch,
7775
+ pos: i
7776
+ });
7777
+ i += 1;
7778
+ continue;
7779
+ }
7780
+ throw new ExpressionParseError(`unexpected character '${ch}'`, i);
7781
+ }
7782
+ tokens.push({
7783
+ type: "eof",
7784
+ pos: n
7785
+ });
7786
+ return tokens;
7787
+ }
7788
+ function keywordOf(text) {
7789
+ if (text === "true") return "true";
7790
+ if (text === "false") return "false";
7791
+ return "null";
7792
+ }
7793
+ function isSinglePunct(ch) {
7794
+ return ch === "(" || ch === ")" || ch === "," || ch === "?" || ch === ":" || ch === "+" || ch === "-" || ch === "*" || ch === "/" || ch === "%" || ch === "!" || ch === "<" || ch === ">";
7795
+ }
7796
+ /**
7797
+ * Frozen, null-prototype builtin function table for the expression engine
7798
+ * (spec §4 rule 4). The table is the SOLE surface of callable functions: the
7799
+ * parser rejects any callee not in it, and the evaluator gates each call on an
7800
+ * own-property check against it.
7801
+ *
7802
+ * Because the object has a NULL prototype AND is `Object.freeze`d:
7803
+ * - it cannot be polluted (no `__proto__` / `constructor` write reaches it);
7804
+ * - a lookup for `toString` / `hasOwnProperty` / `constructor` finds NOTHING
7805
+ * (there is no `Object.prototype` in the chain), so those names are not
7806
+ * callable — they are simply "unknown function" at parse time.
7807
+ *
7808
+ * Every numeric argument is validated as a finite number and every numeric
7809
+ * RESULT is re-checked finite, so `/0`, `sqrt(-1)` (→ NaN) and overflow
7810
+ * (`pow(10,400)` → Infinity) all raise `ExpressionEvalError` and fail the link
7811
+ * closed rather than emitting a garbage value.
7812
+ */
7813
+ function asFiniteNumber(value, name, index) {
7814
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a finite number`);
7815
+ return value;
7816
+ }
7817
+ function asString$1(value, name, index) {
7818
+ if (typeof value !== "string") throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a string`);
7819
+ return value;
7820
+ }
7821
+ function finiteResult(value, name) {
7822
+ if (!Number.isFinite(value)) throw new ExpressionEvalError(`${name}: produced a non-finite result`);
7823
+ return value;
7824
+ }
7825
+ function allFiniteNumbers(args, name) {
7826
+ return args.map((a, idx) => asFiniteNumber(a, name, idx));
7827
+ }
7828
+ var INF = Number.POSITIVE_INFINITY;
7829
+ var table = {
7830
+ min: {
7831
+ minArgs: 1,
7832
+ maxArgs: INF,
7833
+ apply: (args) => finiteResult(Math.min(...allFiniteNumbers(args, "min")), "min")
7834
+ },
7835
+ max: {
7836
+ minArgs: 1,
7837
+ maxArgs: INF,
7838
+ apply: (args) => finiteResult(Math.max(...allFiniteNumbers(args, "max")), "max")
7839
+ },
7840
+ abs: {
7841
+ minArgs: 1,
7842
+ maxArgs: 1,
7843
+ apply: (args) => finiteResult(Math.abs(asFiniteNumber(args[0], "abs", 0)), "abs")
7844
+ },
7845
+ floor: {
7846
+ minArgs: 1,
7847
+ maxArgs: 1,
7848
+ apply: (args) => finiteResult(Math.floor(asFiniteNumber(args[0], "floor", 0)), "floor")
7849
+ },
7850
+ ceil: {
7851
+ minArgs: 1,
7852
+ maxArgs: 1,
7853
+ apply: (args) => finiteResult(Math.ceil(asFiniteNumber(args[0], "ceil", 0)), "ceil")
7854
+ },
7855
+ sqrt: {
7856
+ minArgs: 1,
7857
+ maxArgs: 1,
7858
+ apply: (args) => finiteResult(Math.sqrt(asFiniteNumber(args[0], "sqrt", 0)), "sqrt")
7859
+ },
7860
+ round: {
7861
+ minArgs: 1,
7862
+ maxArgs: 2,
7863
+ apply: (args) => {
7864
+ const x = asFiniteNumber(args[0], "round", 0);
7865
+ const digits = args.length > 1 ? Math.trunc(asFiniteNumber(args[1], "round", 1)) : 0;
7866
+ if (digits < 0 || digits > 100) throw new ExpressionEvalError("round: digits must be between 0 and 100");
7867
+ const factor = 10 ** digits;
7868
+ return finiteResult(Math.round(x * factor) / factor, "round");
7869
+ }
7870
+ },
7871
+ pow: {
7872
+ minArgs: 2,
7873
+ maxArgs: 2,
7874
+ apply: (args) => finiteResult(asFiniteNumber(args[0], "pow", 0) ** asFiniteNumber(args[1], "pow", 1), "pow")
7875
+ },
7876
+ clamp: {
7877
+ minArgs: 3,
7878
+ maxArgs: 3,
7879
+ apply: (args) => {
7880
+ const x = asFiniteNumber(args[0], "clamp", 0);
7881
+ const lo = asFiniteNumber(args[1], "clamp", 1);
7882
+ const hi = asFiniteNumber(args[2], "clamp", 2);
7883
+ if (lo > hi) throw new ExpressionEvalError("clamp: lower bound is greater than upper bound");
7884
+ return finiteResult(Math.min(hi, Math.max(lo, x)), "clamp");
7885
+ }
7886
+ },
7887
+ avg: {
7888
+ minArgs: 1,
7889
+ maxArgs: INF,
7890
+ apply: (args) => {
7891
+ const nums = allFiniteNumbers(args, "avg");
7892
+ return finiteResult(nums.reduce((acc, v) => acc + v, 0) / nums.length, "avg");
7893
+ }
7894
+ },
7895
+ sum: {
7896
+ minArgs: 1,
7897
+ maxArgs: INF,
7898
+ apply: (args) => finiteResult(allFiniteNumbers(args, "sum").reduce((acc, v) => acc + v, 0), "sum")
7899
+ },
7900
+ coalesce: {
7901
+ minArgs: 1,
7902
+ maxArgs: INF,
7903
+ apply: (args) => {
7904
+ for (const a of args) if (a !== null) return a;
7905
+ return null;
7906
+ }
7907
+ },
7908
+ age: {
7909
+ minArgs: 2,
7910
+ maxArgs: 2,
7911
+ apply: (args) => finiteResult(asFiniteNumber(args[0], "age", 0) - asFiniteNumber(args[1], "age", 1), "age")
7912
+ },
7913
+ convert: {
7914
+ minArgs: 3,
7915
+ maxArgs: 3,
7916
+ apply: (args, hooks) => {
7917
+ const x = asFiniteNumber(args[0], "convert", 0);
7918
+ const from = asString$1(args[1], "convert", 1).trim();
7919
+ const to = asString$1(args[2], "convert", 2).trim();
7920
+ if (hooks.convert) {
7921
+ const out = hooks.convert(x, from, to);
7922
+ if (out === null) throw new ExpressionEvalError(`convert: cannot convert '${from}' to '${to}'`);
7923
+ return finiteResult(out, "convert");
7924
+ }
7925
+ if (from === to) return x;
7926
+ throw new ExpressionEvalError("convert: unit conversion table not installed");
7927
+ }
7928
+ }
7929
+ };
7930
+ Object.freeze(Object.assign(Object.create(null), table));
7931
+ /** The set of valid builtin names — used by the parser to reject unknown
7932
+ * callees at parse time (immediate author feedback). */
7933
+ var EXPRESSION_BUILTIN_NAMES = new Set(Object.keys(table));
7934
+ /**
7935
+ * Pratt (precedence-climbing) parser for the safe expression mini-language.
7936
+ *
7937
+ * Precedence (low → high): ternary `?:` (right-assoc) → `||` → `&&` → equality
7938
+ * → relational → additive → multiplicative → unary `! -` → call / primary.
7939
+ * Calls are ONLY `IDENT '(' args? ')'` at primary position — the callee is a
7940
+ * string validated against the builtin table at parse time, so an unknown
7941
+ * function is rejected immediately (author feedback) and a persisted expression
7942
+ * that references a since-removed builtin degrades at read.
7943
+ *
7944
+ * A node counter caps total AST size (`MAX_EXPRESSION_AST_NODES`) and call
7945
+ * arity is capped (`MAX_EXPRESSION_CALL_ARGS`) — both raise `ExpressionParseError`.
7946
+ */
7947
+ /** Binary/logical operator precedence (higher binds tighter). */
7948
+ var BINARY_PRECEDENCE = {
7949
+ "||": 1,
7950
+ "&&": 2,
7951
+ "==": 3,
7952
+ "!=": 3,
7953
+ "<": 4,
7954
+ "<=": 4,
7955
+ ">": 4,
7956
+ ">=": 4,
7957
+ "+": 5,
7958
+ "-": 5,
7959
+ "*": 6,
7960
+ "/": 6,
7961
+ "%": 6
7962
+ };
7963
+ function isLogicalOp(op) {
7964
+ return op === "&&" || op === "||";
7965
+ }
7966
+ function isBinaryOp(op) {
7967
+ return op === "+" || op === "-" || op === "*" || op === "/" || op === "%" || op === "==" || op === "!=" || op === "<" || op === "<=" || op === ">" || op === ">=";
7968
+ }
7969
+ var Parser = class {
7970
+ tokens;
7971
+ pos = 0;
7972
+ nodeCount = 0;
7973
+ identifiers = /* @__PURE__ */ new Set();
7974
+ callees = /* @__PURE__ */ new Set();
7975
+ constructor(tokens) {
7976
+ this.tokens = tokens;
7977
+ }
7978
+ parse() {
7979
+ const ast = this.parseTernary();
7980
+ const tok = this.peek();
7981
+ if (tok.type !== "eof") throw new ExpressionParseError("unexpected trailing input", tok.pos);
7982
+ return {
7983
+ ast,
7984
+ identifiers: this.identifiers,
7985
+ callees: this.callees,
7986
+ nodeCount: this.nodeCount
7987
+ };
7988
+ }
7989
+ peek() {
7990
+ return this.tokens[this.pos];
7991
+ }
7992
+ next() {
7993
+ return this.tokens[this.pos++];
7994
+ }
7995
+ /** Consume a punctuator token, erroring if the next token isn't it. */
7996
+ expectPunct(punct) {
7997
+ const tok = this.peek();
7998
+ if (tok.type !== "punct" || tok.punct !== punct) throw new ExpressionParseError(`expected '${punct}'`, tok.pos);
7999
+ this.pos += 1;
8000
+ }
8001
+ matchPunct(punct) {
8002
+ const tok = this.peek();
8003
+ if (tok.type === "punct" && tok.punct === punct) {
8004
+ this.pos += 1;
8005
+ return true;
8006
+ }
8007
+ return false;
8008
+ }
8009
+ countNode() {
8010
+ this.nodeCount += 1;
8011
+ if (this.nodeCount > 256) throw new ExpressionParseError("expression too complex", this.peek().pos);
8012
+ }
8013
+ parseTernary() {
8014
+ const test = this.parseBinary(1);
8015
+ if (this.matchPunct("?")) {
8016
+ const consequent = this.parseTernary();
8017
+ this.expectPunct(":");
8018
+ const alternate = this.parseTernary();
8019
+ this.countNode();
8020
+ return {
8021
+ kind: "conditional",
8022
+ test,
8023
+ consequent,
8024
+ alternate
8025
+ };
8026
+ }
8027
+ return test;
8028
+ }
8029
+ parseBinary(minPrec) {
8030
+ let left = this.parseUnary();
8031
+ for (;;) {
8032
+ const tok = this.peek();
8033
+ if (tok.type !== "punct") break;
8034
+ const prec = BINARY_PRECEDENCE[tok.punct];
8035
+ if (prec === void 0 || prec < minPrec) break;
8036
+ const op = tok.punct;
8037
+ this.pos += 1;
8038
+ const right = this.parseBinary(prec + 1);
8039
+ this.countNode();
8040
+ if (isLogicalOp(op)) left = {
8041
+ kind: "logical",
8042
+ op,
8043
+ left,
8044
+ right
8045
+ };
8046
+ else if (isBinaryOp(op)) left = {
8047
+ kind: "binary",
8048
+ op,
8049
+ left,
8050
+ right
8051
+ };
8052
+ else throw new ExpressionParseError(`unexpected operator '${op}'`, tok.pos);
8053
+ }
8054
+ return left;
8055
+ }
8056
+ parseUnary() {
8057
+ const tok = this.peek();
8058
+ if (tok.type === "punct" && (tok.punct === "!" || tok.punct === "-")) {
8059
+ const op = tok.punct;
8060
+ this.pos += 1;
8061
+ const operand = this.parseUnary();
8062
+ this.countNode();
8063
+ return {
8064
+ kind: "unary",
8065
+ op,
8066
+ operand
8067
+ };
8068
+ }
8069
+ return this.parsePrimary();
8070
+ }
8071
+ parsePrimary() {
8072
+ const tok = this.next();
8073
+ switch (tok.type) {
8074
+ case "number":
8075
+ this.countNode();
8076
+ return {
8077
+ kind: "literal",
8078
+ value: tok.value
8079
+ };
8080
+ case "string":
8081
+ this.countNode();
8082
+ return {
8083
+ kind: "literal",
8084
+ value: tok.value
8085
+ };
8086
+ case "keyword":
8087
+ this.countNode();
8088
+ return {
8089
+ kind: "literal",
8090
+ value: tok.keyword === "null" ? null : tok.keyword === "true"
8091
+ };
8092
+ case "identifier": {
8093
+ const nextTok = this.peek();
8094
+ if (nextTok.type === "punct" && nextTok.punct === "(") return this.parseCall(tok.name, tok.pos);
8095
+ this.identifiers.add(tok.name);
8096
+ this.countNode();
8097
+ return {
8098
+ kind: "identifier",
8099
+ name: tok.name
8100
+ };
8101
+ }
8102
+ case "punct":
8103
+ if (tok.punct === "(") {
8104
+ const inner = this.parseTernary();
8105
+ this.expectPunct(")");
8106
+ return inner;
8107
+ }
8108
+ throw new ExpressionParseError(`unexpected token '${tok.punct}'`, tok.pos);
8109
+ case "eof": throw new ExpressionParseError("unexpected end of expression", tok.pos);
8110
+ }
8111
+ }
8112
+ parseCall(callee, pos) {
8113
+ if (!EXPRESSION_BUILTIN_NAMES.has(callee)) throw new ExpressionParseError(`unknown function '${callee}'`, pos);
8114
+ this.expectPunct("(");
8115
+ const args = [];
8116
+ if (!this.matchPunct(")")) for (;;) {
8117
+ args.push(this.parseTernary());
8118
+ if (args.length > 16) throw new ExpressionParseError(`too many arguments to '${callee}'`, pos);
8119
+ if (this.matchPunct(",")) continue;
8120
+ this.expectPunct(")");
8121
+ break;
8122
+ }
8123
+ this.callees.add(callee);
8124
+ this.countNode();
8125
+ return {
8126
+ kind: "call",
8127
+ callee,
8128
+ args
8129
+ };
8130
+ }
8131
+ };
8132
+ /** Tokenize + parse `source` into a validated `ParsedExpression`. Throws
8133
+ * `ExpressionParseError` on any lexical or grammatical failure. */
8134
+ function parseExpression(source) {
8135
+ return new Parser(tokenize(source)).parse();
8136
+ }
8137
+ Object.freeze({});
8138
+ /**
8139
+ * LRU compile cache for parsed expressions (spec §2.4 "parse once … LRU keyed
8140
+ * by expr"). The cache stores BOTH successes and failures (negative caching),
8141
+ * so a corrupt persisted string costs exactly one tokenize+parse total — not
8142
+ * one per read on a hot resolve path.
8143
+ *
8144
+ * The cache is a module-level singleton: entries are pure, content-addressed
8145
+ * ASTs keyed by the raw source string, so sharing one instance across all
8146
+ * callers is safe and maximises hit rate.
8147
+ */
8148
+ var cache = /* @__PURE__ */ new Map();
8149
+ function getCached(source) {
8150
+ const hit = cache.get(source);
8151
+ if (hit !== void 0) {
8152
+ cache.delete(source);
8153
+ cache.set(source, hit);
8154
+ return hit;
8155
+ }
8156
+ let result;
8157
+ try {
8158
+ result = {
8159
+ ok: true,
8160
+ parsed: parseExpression(source)
8161
+ };
8162
+ } catch (err) {
8163
+ result = {
8164
+ ok: false,
8165
+ error: err instanceof ExpressionParseError ? err.message : String(err)
8166
+ };
8167
+ }
8168
+ cache.set(source, result);
8169
+ if (cache.size > 256) {
8170
+ const oldest = cache.keys().next().value;
8171
+ if (oldest !== void 0) cache.delete(oldest);
8172
+ }
8173
+ return result;
8174
+ }
8175
+ /** Compile `source`, returning a discriminated result instead of throwing.
8176
+ * Used by read paths that must degrade rather than raise. LRU/negative-cached. */
8177
+ function compileExpressionSafe(source) {
8178
+ return getCached(source);
8179
+ }
8180
+ /**
8181
+ * Author-time validation. Returns `null` when the source is valid, else a
8182
+ * human-readable error message. Checks: the expression compiles; binding count
8183
+ * is within `MAX_EXPRESSION_BINDINGS`; every binding name is a legal identifier,
8184
+ * is not reserved (`now`/keywords) and does not shadow a builtin; and every
8185
+ * FREE identifier of the AST is covered by a binding or the injected `now`.
8186
+ */
8187
+ function validateExpressionSource(src) {
8188
+ const names = Object.keys(src.bindings);
8189
+ if (names.length > 32) return `too many bindings (${names.length} > 32)`;
8190
+ for (const name of names) {
8191
+ if (!EXPRESSION_IDENTIFIER_RE.test(name)) return `invalid binding name '${name}'`;
8192
+ if (RESERVED_BINDING_NAMES.has(name)) return `binding name '${name}' is reserved`;
8193
+ if (EXPRESSION_BUILTIN_NAMES.has(name)) return `binding name '${name}' shadows a builtin function`;
8194
+ }
8195
+ const compiled = compileExpressionSafe(src.expr);
8196
+ if (!compiled.ok) return compiled.error;
8197
+ const bound = new Set(names);
8198
+ for (const id of compiled.parsed.identifiers) {
8199
+ if (id === "now") continue;
8200
+ if (!bound.has(id)) return `expression references unbound identifier '${id}'`;
8201
+ }
8202
+ return null;
8203
+ }
8204
+ /**
7441
8205
  * Accessory device helpers — shared across drivers.
7442
8206
  *
7443
8207
  * Many vendor-specific drivers register accessory child devices on
@@ -8475,7 +9239,13 @@ onStatusChanged: { data: object({
8475
9239
  }) } },
8476
9240
  status: {
8477
9241
  schema: BatteryStatusSchema,
8478
- kind: "push"
9242
+ kind: "push",
9243
+ empty: {
9244
+ percentage: 0,
9245
+ charging: "none",
9246
+ sleeping: false,
9247
+ lastUpdated: 0
9248
+ }
8479
9249
  },
8480
9250
  /**
8481
9251
  * Runtime-state slice — every provider that registers this cap
@@ -9418,21 +10188,38 @@ var connectivityCapability = {
9418
10188
  },
9419
10189
  runtimeState: ConnectivityStatusSchema
9420
10190
  };
10191
+ /**
10192
+ * Generic device-consumables capability — surfaces a device's
10193
+ * maintenance items (vacuum filters/brushes, replaceable cartridges,
10194
+ * descaling cycles, …) with their remaining life and an optional
10195
+ * "Replaced" reset action. Device-agnostic: any provider that knows its
10196
+ * device tracks consumables can register it; the cap declares no
10197
+ * vocabulary of its own — the provider names each item verbatim.
10198
+ *
10199
+ * Like `childLayout`, the cap is INERT until a provider sets items: no
10200
+ * provider populates it by guessing (no HA inference). The UI renders a
10201
+ * "No consumables reported" placeholder when `items` is empty.
10202
+ */
10203
+ /** A single consumable item. Either a continuous `level` (remaining
10204
+ * life %) or a discrete `status` may be known — both may be null when a
10205
+ * provider only knows the item exists. `level` and `status` are not
10206
+ * mutually exclusive; a provider may report both. */
10207
+ var ConsumableItemSchema = object({
10208
+ /** Stable id, e.g. 'main-brush'. */
10209
+ key: string().min(1),
10210
+ /** Display name. */
10211
+ label: string().min(1),
10212
+ /** Remaining life % when known (0..100). */
10213
+ level: number().min(0).max(100).nullable(),
10214
+ /** Discrete state when known (binary mode). */
10215
+ status: _enum(["ok", "replace"]).nullable(),
10216
+ /** Ms epoch of the last replace, when known. */
10217
+ lastResetAt: number().nullable(),
10218
+ /** Whether `reset()` is meaningful for this item. */
10219
+ resettable: boolean()
10220
+ });
9421
10221
  var ConsumablesStatusSchema = object({
9422
- items: array(object({
9423
- /** Stable id, e.g. 'main-brush'. */
9424
- key: string().min(1),
9425
- /** Display name. */
9426
- label: string().min(1),
9427
- /** Remaining life % when known (0..100). */
9428
- level: number().min(0).max(100).nullable(),
9429
- /** Discrete state when known (binary mode). */
9430
- status: _enum(["ok", "replace"]).nullable(),
9431
- /** Ms epoch of the last replace, when known. */
9432
- lastResetAt: number().nullable(),
9433
- /** Whether `reset()` is meaningful for this item. */
9434
- resettable: boolean()
9435
- })),
10222
+ items: array(ConsumableItemSchema),
9436
10223
  lastChangedAt: number()
9437
10224
  });
9438
10225
  var consumablesCapability = {
@@ -9491,7 +10278,25 @@ reset: method(object({
9491
10278
  }) },
9492
10279
  status: {
9493
10280
  schema: ConsumablesStatusSchema,
9494
- kind: "push"
10281
+ kind: "push",
10282
+ empty: {
10283
+ items: [],
10284
+ lastChangedAt: 0
10285
+ },
10286
+ itemArray: {
10287
+ path: "items",
10288
+ keyField: "key",
10289
+ labelField: "label",
10290
+ itemSchema: ConsumableItemSchema,
10291
+ emptyItem: {
10292
+ key: "",
10293
+ label: "",
10294
+ level: null,
10295
+ status: null,
10296
+ lastResetAt: null,
10297
+ resettable: false
10298
+ }
10299
+ }
9495
10300
  },
9496
10301
  runtimeState: ConsumablesStatusSchema.extend({ lastFetchedAt: number() })
9497
10302
  };
@@ -10778,7 +11583,8 @@ var MotionAnalysisResultSchema = object({
10778
11583
  });
10779
11584
  method(object({
10780
11585
  deviceId: number(),
10781
- frame: FrameInputSchema
11586
+ frame: FrameInputSchema.optional(),
11587
+ frameHandle: FrameHandleSchema.optional()
10782
11588
  }), MotionAnalysisResultSchema, { kind: "mutation" }), method(object({ deviceId: number() }), _void(), { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), object({
10783
11589
  deviceId: number(),
10784
11590
  detected: boolean(),
@@ -11025,6 +11831,12 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
11025
11831
  engine: PipelineEngineChoiceSchema.optional(),
11026
11832
  steps: array(PipelineStepInputSchema).min(1),
11027
11833
  frame: FrameInputSchema.optional(),
11834
+ /**
11835
+ * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
11836
+ * the decoded pixels live in. One more member of the one-of
11837
+ * frame/frameHandle/image/imageBase64/referenceImage group.
11838
+ */
11839
+ frameHandle: FrameHandleSchema.optional(),
11028
11840
  imageBase64: string().optional(),
11029
11841
  /**
11030
11842
  * Binary JPEG bytes — preferred over `imageBase64` on internal
@@ -11267,6 +12079,31 @@ var ReportMotionInputSchema = object({
11267
12079
  regions: array(MotionRegionSchema).readonly().optional()
11268
12080
  });
11269
12081
  /**
12082
+ * Where a runner gets a camera's decoded frames (cross-node Phase 2,
12083
+ * restream-owner model — P2c).
12084
+ *
12085
+ * - `local-broker` (DEFAULT): today's path — subscribe to the co-located
12086
+ * stream-broker's shm frame plane. Every pre-P2c attach payload (no
12087
+ * `frameSource` key) parses to this, so the field is additive with zero
12088
+ * behavior change.
12089
+ * - `remote-restream`: the detect node is NOT the camera's source-owner.
12090
+ * The runner acquires the owner's COMPRESSED passthrough restream
12091
+ * (`streamBroker.getStreamWithCodec({video:'copy'})` — refcounted, the
12092
+ * double-pull guard) and decodes LOCALLY via a satellite frame plane +
12093
+ * pull-mode decoder session pinned to its own node. The shm ring stays
12094
+ * node-local; only H.264/H.265 packets cross the wire.
12095
+ * `hubHostnameOverride` mirrors the recorder's `recordingHubHostname`:
12096
+ * when set it overrides the `CAMSTACK_HUB_URL`-derived host the runner
12097
+ * dials for the owner's restream.
12098
+ */
12099
+ var RunnerFrameSourceSchema = discriminatedUnion("kind", [object({ kind: literal("local-broker") }), object({
12100
+ kind: literal("remote-restream"),
12101
+ /** The camera's source-owner node (slice 1: always the hub). */
12102
+ ownerNodeId: string(),
12103
+ /** Operator override for the owner host the runner dials. */
12104
+ hubHostnameOverride: string().optional()
12105
+ })]).describe("Per-camera frame-source mode for the runner (P2c)");
12106
+ /**
11270
12107
  * Camera assignment payload sent by `addon-pipeline-orchestrator` to a
11271
12108
  * specific runner instance via `attachCamera`. Carries everything the
11272
12109
  * runner needs to subscribe to the local broker and execute inference.
@@ -11364,7 +12201,15 @@ var RunnerCameraConfigSchema = object({
11364
12201
  */
11365
12202
  onboardMotionDrivesAnalyzer: boolean().default(true),
11366
12203
  occupancyRecheckSec: number().min(occupancyRecheckSecField.min).max(occupancyRecheckSecField.max).default(occupancyRecheckSecField.default),
11367
- occupancyRecheckFrames: number().min(occupancyRecheckFramesField.min).max(occupancyRecheckFramesField.max).default(occupancyRecheckFramesField.default)
12204
+ occupancyRecheckFrames: number().min(occupancyRecheckFramesField.min).max(occupancyRecheckFramesField.max).default(occupancyRecheckFramesField.default),
12205
+ /**
12206
+ * Where this runner gets the camera's decoded frames (P2c). Defaulted so
12207
+ * every existing payload behaves as `local-broker` — the pre-Phase-2 path.
12208
+ * Populated with `remote-restream` by the orchestrator ONLY when the
12209
+ * camera's detect node differs from its source-owner (P2d, gated by the
12210
+ * `remoteSourcingNodes` rollout setting).
12211
+ */
12212
+ frameSource: RunnerFrameSourceSchema.default({ kind: "local-broker" })
11368
12213
  });
11369
12214
  motionFpsField.min, motionFpsField.max, motionFpsField.step, motionFpsField.default, detectionFpsField.min, detectionFpsField.max, detectionFpsField.step, detectionFpsField.default, motionCooldownMsField.min, motionCooldownMsField.max, motionCooldownMsField.step, motionCooldownMsField.default, occupancyRecheckSecField.min, occupancyRecheckSecField.max, occupancyRecheckSecField.step, occupancyRecheckSecField.default, occupancyRecheckFramesField.min, occupancyRecheckFramesField.max, occupancyRecheckFramesField.step, occupancyRecheckFramesField.default;
11370
12215
  /**
@@ -11928,6 +12773,157 @@ var numericSensorCapability = {
11928
12773
  runtimeState: NumericSensorStatusSchema
11929
12774
  };
11930
12775
  /**
12776
+ * Feeder connectivity / power status — mirrors the HA petkit device-status
12777
+ * enum: `normal` (online, mains), `offline` (not reaching PetKit cloud),
12778
+ * `on_batteries` (running on battery backup). `null` until first reported.
12779
+ */
12780
+ var PetFeederDeviceStatusSchema = _enum([
12781
+ "normal",
12782
+ "offline",
12783
+ "on_batteries"
12784
+ ]);
12785
+ var gramsPortion = number().int().min(4).max(200);
12786
+ var PetFeederStatusSchema = object({
12787
+ /** Food currently in the bowl (grams). Null when the device has not
12788
+ * reported a reading yet. On dual-hopper models this is the combined
12789
+ * bowl reading; per-hopper levels live in `food1`/`food2`. */
12790
+ foodLevel: number().nullable(),
12791
+ /** Hopper-1 food level (grams) on dual-hopper feeders; null on
12792
+ * single-hopper models. */
12793
+ food1: number().nullable(),
12794
+ /** Hopper-2 food level (grams) on dual-hopper feeders; null on
12795
+ * single-hopper models. */
12796
+ food2: number().nullable(),
12797
+ /** Derived low-food flag — mirrors the HA `food_level` binary_sensor
12798
+ * (`device_class: problem`, on = low). True when the bowl is empty /
12799
+ * below the feeder's low threshold. */
12800
+ lowFood: boolean(),
12801
+ /** Battery charge 0..100 (%). Null on mains-powered models or when the
12802
+ * device has no battery reading. */
12803
+ batteryPower: number().min(0).max(100).nullable(),
12804
+ /** Days of desiccant life remaining. Null when the model has no
12805
+ * desiccant sensor. */
12806
+ desiccantLeftDays: number().nullable(),
12807
+ /** True while a feed is in progress. */
12808
+ feeding: boolean(),
12809
+ /** Decoded connectivity / power status (HA petkit device-status enum).
12810
+ * Null until the device has reported a status. */
12811
+ status: PetFeederDeviceStatusSchema.nullable(),
12812
+ /** Decoded human-readable fault message. Null (or the device's `no_error`
12813
+ * sentinel) means healthy; a non-null string is an active fault. Pairs
12814
+ * with `errorCode` for consumers that want the raw integer. */
12815
+ error: string().nullable(),
12816
+ /** Raw device error code (0 / null = no error). */
12817
+ errorCode: number().nullable(),
12818
+ /** True for D4S/D4SH dual-hopper hardware — gates the per-hopper UI. */
12819
+ isDualHopper: boolean(),
12820
+ /** Child-lock (manual-lock) setting — buttons on the unit are disabled. */
12821
+ childLock: boolean(),
12822
+ /** Front indicator-light setting. */
12823
+ indicatorLight: boolean(),
12824
+ /** Play a chime when dispensing. */
12825
+ feedSound: boolean(),
12826
+ /** Speaker / prompt volume level (device-scaled integer). */
12827
+ volume: number(),
12828
+ /** Ms epoch when the slice was last refreshed from the cloud. */
12829
+ lastFetchedAt: number()
12830
+ });
12831
+ var petFeederCapability = {
12832
+ name: "pet-feeder",
12833
+ scope: "device",
12834
+ deviceNative: true,
12835
+ mode: "singleton",
12836
+ deviceTypes: [DeviceType.PetFeeder],
12837
+ methods: {
12838
+ /**
12839
+ * Dispense food now. Single-hopper feeders take `grams`; dual-hopper
12840
+ * feeders (D4S/D4SH) accept `hopper1`/`hopper2` to target one or both
12841
+ * hoppers. All portions honour the 4–200 g hardware range. At least
12842
+ * one of the three must be present — the provider rejects an empty
12843
+ * request.
12844
+ */
12845
+ feed: method(object({
12846
+ deviceId: number().int().nonnegative(),
12847
+ grams: gramsPortion.optional(),
12848
+ hopper1: gramsPortion.optional(),
12849
+ hopper2: gramsPortion.optional()
12850
+ }), _void(), {
12851
+ kind: "mutation",
12852
+ auth: "admin"
12853
+ }),
12854
+ /** Cancel an in-progress manual feed. */
12855
+ cancelFeed: method(object({ deviceId: number().int().nonnegative() }), _void(), {
12856
+ kind: "mutation",
12857
+ auth: "admin"
12858
+ }),
12859
+ /** Reset the desiccant "days remaining" counter after replacing it. */
12860
+ resetDesiccant: method(object({ deviceId: number().int().nonnegative() }), _void(), {
12861
+ kind: "mutation",
12862
+ auth: "admin"
12863
+ }),
12864
+ /** Mark a hopper as refilled (D4H/D4S/D4SH). */
12865
+ markFoodReplenished: method(object({ deviceId: number().int().nonnegative() }), _void(), {
12866
+ kind: "mutation",
12867
+ auth: "admin"
12868
+ }),
12869
+ /** Call the pet with the recorded prompt (D3). */
12870
+ callPet: method(object({ deviceId: number().int().nonnegative() }), _void(), {
12871
+ kind: "mutation",
12872
+ auth: "admin"
12873
+ }),
12874
+ /** Play a stored sound by id (D3 / D4H / D4SH). */
12875
+ playSound: method(object({
12876
+ deviceId: number().int().nonnegative(),
12877
+ soundId: number().int().nonnegative()
12878
+ }), _void(), {
12879
+ kind: "mutation",
12880
+ auth: "admin"
12881
+ }),
12882
+ /** Toggle the child-lock (manual-lock) setting. */
12883
+ setChildLock: method(object({
12884
+ deviceId: number().int().nonnegative(),
12885
+ on: boolean()
12886
+ }), _void(), {
12887
+ kind: "mutation",
12888
+ auth: "admin"
12889
+ }),
12890
+ /** Toggle the front indicator light. */
12891
+ setIndicatorLight: method(object({
12892
+ deviceId: number().int().nonnegative(),
12893
+ on: boolean()
12894
+ }), _void(), {
12895
+ kind: "mutation",
12896
+ auth: "admin"
12897
+ }),
12898
+ /** Toggle the dispense chime. */
12899
+ setFeedSound: method(object({
12900
+ deviceId: number().int().nonnegative(),
12901
+ on: boolean()
12902
+ }), _void(), {
12903
+ kind: "mutation",
12904
+ auth: "admin"
12905
+ }),
12906
+ /** Set the speaker / prompt volume level. */
12907
+ setVolume: method(object({
12908
+ deviceId: number().int().nonnegative(),
12909
+ level: number().int().nonnegative()
12910
+ }), _void(), {
12911
+ kind: "mutation",
12912
+ auth: "admin"
12913
+ })
12914
+ },
12915
+ status: {
12916
+ schema: PetFeederStatusSchema,
12917
+ kind: "poll"
12918
+ },
12919
+ /**
12920
+ * Runtime-state slice — mirrored by the kernel. UI feeder cards read
12921
+ * the full slice via `device.state.petFeeder.value` and refresh on
12922
+ * every poll without re-querying the provider.
12923
+ */
12924
+ runtimeState: PetFeederStatusSchema
12925
+ };
12926
+ /**
11931
12927
  * Multi-metric electrical meter. One slice can carry any combination
11932
12928
  * of instantaneous power (W), cumulative energy (kWh), voltage (V),
11933
12929
  * and current (A) — all fields optional so a single-metric source
@@ -13230,6 +14226,7 @@ var DEVICE_LOCAL_STATE_CAPS = {
13230
14226
  nativeObjectDetection: nativeObjectDetectionCapability,
13231
14227
  notifier: notifierCapability,
13232
14228
  numericSensor: numericSensorCapability,
14229
+ petFeeder: petFeederCapability,
13233
14230
  powerMeter: powerMeterCapability,
13234
14231
  presence: presenceCapability,
13235
14232
  pressureSensor: pressureSensorCapability,
@@ -15195,10 +16192,12 @@ method(object({ codec: string() }), boolean()), method(_void(), object({
15195
16192
  url: string()
15196
16193
  }), _void()), method(object({
15197
16194
  sessionId: string(),
15198
- maxCount: number().default(1)
16195
+ maxCount: number().default(1),
16196
+ waitMs: number().optional()
15199
16197
  }), array(DecodedFrameSchema)), method(object({
15200
16198
  sessionId: string(),
15201
- maxCount: number().default(1)
16199
+ maxCount: number().default(1),
16200
+ waitMs: number().optional()
15202
16201
  }), array(FrameHandleSchema)), method(object({ handle: FrameHandleSchema }), DecodedFrameSchema.nullable()), method(object({ sessionId: string() }), ShmRingStatsSchema.nullable()), method(object({
15203
16202
  sessionId: string(),
15204
16203
  config: DecoderSessionConfigSchema.partial()
@@ -15502,14 +16501,63 @@ var ChildLayoutEntrySchema = object({
15502
16501
  collapsed: boolean().optional()
15503
16502
  });
15504
16503
  /** Cap-wire shape of a DeviceLink — structurally mirrors `DeviceLink` in
15505
- * `device-management.ts`. */
16504
+ * `device-management.ts`. Source is a union: a FIELD source copies a sibling
16505
+ * accessory's status field (`kind` optional/absent for wire compat); a
16506
+ * LITERAL source carries a per-device constant (no sibling is read); a
16507
+ * GLOBAL source (P2e) copies ANY device's status field, addressed by the
16508
+ * source device's full re-sync-stable `stableId`. */
16509
+ var DeviceLinkFieldSourceSchema = object({
16510
+ kind: literal("field").optional(),
16511
+ sourceKey: string(),
16512
+ cap: string(),
16513
+ fieldPath: string()
16514
+ });
16515
+ var DeviceLinkLiteralSourceSchema = object({
16516
+ kind: literal("literal"),
16517
+ value: union([
16518
+ string(),
16519
+ number(),
16520
+ boolean(),
16521
+ _null()
16522
+ ])
16523
+ });
16524
+ var DeviceLinkGlobalSourceSchema = object({
16525
+ kind: literal("global"),
16526
+ sourceStableId: string(),
16527
+ cap: string(),
16528
+ fieldPath: string()
16529
+ });
16530
+ /** Expression source (Stage X): compute the target field from N named bindings
16531
+ * via the safe expression engine. Bindings are field | literal | global — never
16532
+ * another expression (no nesting). The `superRefine` runs the SAME author-time
16533
+ * validation as `validateExpressionSource` (compiles the expr, checks binding
16534
+ * names + identifier coverage) so every wire boundary that parses a DeviceLink
16535
+ * (tRPC mount, kernel create pre-seed, projection output) validates-at-write.
16536
+ * Compiles are LRU-cached, so repeated validation of the same expr is a hit. */
16537
+ var DeviceLinkExpressionSourceSchema = object({
16538
+ kind: literal("expression"),
16539
+ expr: string().min(1).max(MAX_EXPRESSION_SOURCE_LENGTH),
16540
+ bindings: record(string().regex(EXPRESSION_IDENTIFIER_RE), union([
16541
+ DeviceLinkFieldSourceSchema,
16542
+ DeviceLinkLiteralSourceSchema,
16543
+ DeviceLinkGlobalSourceSchema
16544
+ ]))
16545
+ }).superRefine((src, ctx) => {
16546
+ const err = validateExpressionSource(src);
16547
+ if (err !== null) ctx.addIssue({
16548
+ code: "custom",
16549
+ message: err,
16550
+ path: ["expr"]
16551
+ });
16552
+ });
15506
16553
  var DeviceLinkSchema = object({
15507
16554
  id: string(),
15508
- source: object({
15509
- sourceKey: string(),
15510
- cap: string(),
15511
- fieldPath: string()
15512
- }),
16555
+ source: union([
16556
+ DeviceLinkFieldSourceSchema,
16557
+ DeviceLinkLiteralSourceSchema,
16558
+ DeviceLinkGlobalSourceSchema,
16559
+ DeviceLinkExpressionSourceSchema
16560
+ ]),
15513
16561
  target: object({
15514
16562
  cap: string(),
15515
16563
  fieldPath: string(),
@@ -15538,6 +16586,31 @@ var DeviceLinkSchema = object({
15538
16586
  })
15539
16587
  ]).optional()
15540
16588
  });
16589
+ /** Cap-wire shape of a per-cap display refinement — mirrors
16590
+ * `DeviceCapDisplayOverride` in `device-management.ts`. */
16591
+ var DeviceCapDisplayOverrideSchema = object({
16592
+ unit: string().min(1).optional(),
16593
+ precision: number().int().min(0).max(10).optional()
16594
+ });
16595
+ /** Cap-wire shape of an operator-authored per-device display override —
16596
+ * mirrors `DeviceDisplayOverride` in `device-management.ts`. `precision`
16597
+ * bounds mirror `numeric-sensor.cap.ts` (`int 0-10`). */
16598
+ var DeviceDisplayOverrideSchema = object({
16599
+ icon: string().min(1).optional(),
16600
+ label: string().min(1).optional(),
16601
+ unit: string().min(1).optional(),
16602
+ precision: number().int().min(0).max(10).optional(),
16603
+ hidden: boolean().optional(),
16604
+ perCap: record(string(), DeviceCapDisplayOverrideSchema).optional()
16605
+ });
16606
+ /** Cap-wire shape of a per-role display default — mirrors `RoleDisplayDefault`
16607
+ * in `device-management.ts`. Keyed by `DeviceRole` string (role strings cross
16608
+ * the wire as plain strings everywhere else — cf. `DeviceInfoSchema.role`). */
16609
+ var RoleDisplayDefaultSchema = object({
16610
+ unit: string().min(1).optional(),
16611
+ precision: number().int().min(0).max(10).optional(),
16612
+ icon: string().min(1).optional()
16613
+ });
15541
16614
  /**
15542
16615
  * Serializable projection of a live IDevice.
15543
16616
  * Returned by listAll, getDevice, getChildren.
@@ -15593,7 +16666,9 @@ var DeviceInfoSchema = object({
15593
16666
  * `DeviceMeta.childLayout`. Absent ⇒ no layout declared. */
15594
16667
  childLayout: array(ChildLayoutEntrySchema).readonly().optional(),
15595
16668
  /** Operator-authored cross-device field wirings. See `DeviceMeta.deviceLinks`. */
15596
- deviceLinks: array(DeviceLinkSchema).readonly().optional()
16669
+ deviceLinks: array(DeviceLinkSchema).readonly().optional(),
16670
+ /** Operator-authored per-device display override. See `DeviceMeta.display`. */
16671
+ display: DeviceDisplayOverrideSchema.optional()
15597
16672
  });
15598
16673
  var ConfigEntrySchema = object({
15599
16674
  key: string(),
@@ -15658,7 +16733,9 @@ var DeviceMetaSchema = object({
15658
16733
  deviceLinks: array(DeviceLinkSchema).readonly().optional(),
15659
16734
  /** Semantic role string (`DeviceRole`) — propagated from the spawn pre-seed.
15660
16735
  * Optional: only present for accessory children that carry a known role. */
15661
- role: string().nullable().optional()
16736
+ role: string().nullable().optional(),
16737
+ /** Operator-authored per-device display override. See `DeviceMeta.display`. */
16738
+ display: DeviceDisplayOverrideSchema.optional()
15662
16739
  });
15663
16740
  /** ConfigUISchema passed through as unknown — mirrors device-provider's CreationSchemaOutputSchema */
15664
16741
  var ConfigUISchemaOutput = unknown().nullable();
@@ -15752,7 +16829,19 @@ method(object({
15752
16829
  }), _void(), {
15753
16830
  kind: "mutation",
15754
16831
  auth: "admin"
15755
- }), method(object({ deviceId: number() }), object({ caps: array(object({
16832
+ }), method(object({
16833
+ deviceId: number(),
16834
+ display: DeviceDisplayOverrideSchema.nullable()
16835
+ }), _void(), {
16836
+ kind: "mutation",
16837
+ auth: "admin"
16838
+ }), method(object({}), object({ defaults: record(string(), RoleDisplayDefaultSchema) }), { kind: "query" }), method(object({ defaults: record(string(), RoleDisplayDefaultSchema) }), _void(), {
16839
+ kind: "mutation",
16840
+ auth: "admin"
16841
+ }), method(object({
16842
+ deviceId: number(),
16843
+ includeSynthesizable: boolean().optional()
16844
+ }), object({ caps: array(object({
15756
16845
  cap: string(),
15757
16846
  fields: array(object({
15758
16847
  path: string(),
@@ -15762,8 +16851,13 @@ method(object({
15762
16851
  "boolean",
15763
16852
  "enum"
15764
16853
  ]),
15765
- enumValues: array(string()).optional()
15766
- })).readonly()
16854
+ enumValues: array(string()).optional(),
16855
+ item: boolean().optional()
16856
+ })).readonly(),
16857
+ itemArray: object({
16858
+ path: string(),
16859
+ keyField: string()
16860
+ }).optional()
15767
16861
  })).readonly() }), { kind: "query" }), method(object({
15768
16862
  deviceId: number(),
15769
16863
  role: string().nullable()
@@ -15833,7 +16927,11 @@ method(object({
15833
16927
  deviceId: number(),
15834
16928
  entries: array(object({
15835
16929
  capName: string(),
15836
- kind: _enum(["native", "wrapped"]),
16930
+ kind: _enum([
16931
+ "native",
16932
+ "wrapped",
16933
+ "linked"
16934
+ ]),
15837
16935
  providerAddonId: string(),
15838
16936
  providerNodeId: string(),
15839
16937
  nativeAddonId: string()
@@ -15842,7 +16940,11 @@ method(object({
15842
16940
  deviceId: number(),
15843
16941
  entries: array(object({
15844
16942
  capName: string(),
15845
- kind: _enum(["native", "wrapped"]),
16943
+ kind: _enum([
16944
+ "native",
16945
+ "wrapped",
16946
+ "linked"
16947
+ ]),
15846
16948
  providerAddonId: string(),
15847
16949
  providerNodeId: string(),
15848
16950
  nativeAddonId: string()
@@ -19705,7 +20807,10 @@ var HwAccelBackendInputSchema = _enum([
19705
20807
  "webgpu",
19706
20808
  "none"
19707
20809
  ]).nullable().optional();
19708
- var HwAccelResolutionSchema = object({ preferred: array(string()).readonly() });
20810
+ var HwAccelResolutionSchema = object({
20811
+ preferred: array(string()).readonly(),
20812
+ rationale: string()
20813
+ });
19709
20814
  var HardwareEncoderIdSchema = _enum([
19710
20815
  "h264_videotoolbox",
19711
20816
  "hevc_videotoolbox",
@@ -19810,10 +20915,7 @@ var ResolvedInferenceConfigSchema = object({
19810
20915
  format: ModelFormatSchema,
19811
20916
  reason: string()
19812
20917
  });
19813
- method(_void(), PlatformCapabilitiesSchema), method(_void(), HardwareInfoSchema), method(object({ requirements: array(ModelRequirementSchema).readonly() }), ResolvedInferenceConfigSchema), method(object({
19814
- prefer: HwAccelBackendInputSchema,
19815
- nodeId: string().optional()
19816
- }), HwAccelResolutionSchema), method(_void(), HardwareEncodersSchema), method(_void(), HardwareEncodersSchema, {
20918
+ method(_void(), PlatformCapabilitiesSchema), method(_void(), HardwareInfoSchema), method(object({ requirements: array(ModelRequirementSchema).readonly() }), ResolvedInferenceConfigSchema), method(object({ prefer: HwAccelBackendInputSchema }), HwAccelResolutionSchema), method(_void(), HardwareEncodersSchema), method(_void(), HardwareEncodersSchema, {
19817
20919
  kind: "mutation",
19818
20920
  auth: "admin"
19819
20921
  }), method(_void(), HardwareDecodeAccelsSchema), method(_void(), HardwareDecodeAccelsSchema, {
@@ -19872,6 +20974,16 @@ DeviceType.Camera, DeviceType.Sensor, DeviceType.Switch, method(object({ deviceI
19872
20974
  kind: "mutation",
19873
20975
  auth: "admin"
19874
20976
  });
20977
+ /**
20978
+ * `recording` cap — footage availability + HLS playback manifests + per-device
20979
+ * recording config. NOTE on events (source of truth, R5/C3): this cap carries
20980
+ * NO event surface — `getPlaybackManifest` returns playlist URLs only. Timeline
20981
+ * events (motion/object/audio) come from `pipelineAnalytics` (durable SQLite
20982
+ * rows); the recorder's internal EventMap markers are ephemeral in-RAM
20983
+ * annotations that are not exposed here and must not be treated as an event
20984
+ * feed. Event<->footage joins are by time, padded with the shared `EVENT_PAD_MS`
20985
+ * (`interfaces/recording-config.ts`).
20986
+ */
19875
20987
  var RecordingStatusSchema = object({
19876
20988
  deviceId: number(),
19877
20989
  enabled: boolean(),
@@ -21508,6 +22620,12 @@ Object.freeze({
21508
22620
  addonId: null,
21509
22621
  access: "view"
21510
22622
  },
22623
+ "deviceManager.getRoleDisplayDefaults": {
22624
+ capName: "device-manager",
22625
+ capScope: "system",
22626
+ addonId: null,
22627
+ access: "view"
22628
+ },
21511
22629
  "deviceManager.getSettingsSchema": {
21512
22630
  capName: "device-manager",
21513
22631
  capScope: "system",
@@ -21658,6 +22776,12 @@ Object.freeze({
21658
22776
  addonId: null,
21659
22777
  access: "create"
21660
22778
  },
22779
+ "deviceManager.setDisplay": {
22780
+ capName: "device-manager",
22781
+ capScope: "system",
22782
+ addonId: null,
22783
+ access: "create"
22784
+ },
21661
22785
  "deviceManager.setIntegrationId": {
21662
22786
  capName: "device-manager",
21663
22787
  capScope: "system",
@@ -21700,6 +22824,12 @@ Object.freeze({
21700
22824
  addonId: null,
21701
22825
  access: "create"
21702
22826
  },
22827
+ "deviceManager.setRoleDisplayDefaults": {
22828
+ capName: "device-manager",
22829
+ capScope: "system",
22830
+ addonId: null,
22831
+ access: "create"
22832
+ },
21703
22833
  "deviceManager.setStreamProfileMap": {
21704
22834
  capName: "device-manager",
21705
22835
  capScope: "system",
@@ -22750,6 +23880,66 @@ Object.freeze({
22750
23880
  addonId: null,
22751
23881
  access: "create"
22752
23882
  },
23883
+ "petFeeder.callPet": {
23884
+ capName: "pet-feeder",
23885
+ capScope: "device",
23886
+ addonId: null,
23887
+ access: "create"
23888
+ },
23889
+ "petFeeder.cancelFeed": {
23890
+ capName: "pet-feeder",
23891
+ capScope: "device",
23892
+ addonId: null,
23893
+ access: "create"
23894
+ },
23895
+ "petFeeder.feed": {
23896
+ capName: "pet-feeder",
23897
+ capScope: "device",
23898
+ addonId: null,
23899
+ access: "create"
23900
+ },
23901
+ "petFeeder.markFoodReplenished": {
23902
+ capName: "pet-feeder",
23903
+ capScope: "device",
23904
+ addonId: null,
23905
+ access: "create"
23906
+ },
23907
+ "petFeeder.playSound": {
23908
+ capName: "pet-feeder",
23909
+ capScope: "device",
23910
+ addonId: null,
23911
+ access: "create"
23912
+ },
23913
+ "petFeeder.resetDesiccant": {
23914
+ capName: "pet-feeder",
23915
+ capScope: "device",
23916
+ addonId: null,
23917
+ access: "delete"
23918
+ },
23919
+ "petFeeder.setChildLock": {
23920
+ capName: "pet-feeder",
23921
+ capScope: "device",
23922
+ addonId: null,
23923
+ access: "create"
23924
+ },
23925
+ "petFeeder.setFeedSound": {
23926
+ capName: "pet-feeder",
23927
+ capScope: "device",
23928
+ addonId: null,
23929
+ access: "create"
23930
+ },
23931
+ "petFeeder.setIndicatorLight": {
23932
+ capName: "pet-feeder",
23933
+ capScope: "device",
23934
+ addonId: null,
23935
+ access: "create"
23936
+ },
23937
+ "petFeeder.setVolume": {
23938
+ capName: "pet-feeder",
23939
+ capScope: "device",
23940
+ addonId: null,
23941
+ access: "create"
23942
+ },
22753
23943
  "pipelineAnalytics.clearTracks": {
22754
23944
  capName: "pipeline-analytics",
22755
23945
  capScope: "device",
@@ -28217,20 +29407,86 @@ function selectBatteryEntity(entities) {
28217
29407
  * fires — but not 0 % (the cell isn't dead, it just needs replacing). */
28218
29408
  var BINARY_BATTERY_NORMAL_PCT = 100;
28219
29409
  var BINARY_BATTERY_LOW_PCT = 15;
28220
- /** Parse an HA battery state string (`"42"`) into a clamped 0–100 percentage.
28221
- * Returns `null` for non-numeric states (`unavailable` / `unknown`). */
28222
- function parseBatteryPercentage(raw) {
28223
- const value = Number(raw);
28224
- if (!Number.isFinite(value)) return null;
28225
- return Math.max(0, Math.min(100, value));
28226
- }
28227
- /** Map a BINARY battery state (`LOW_BAT`) to a percentage. HA convention:
28228
- * `on` / `true` = LOW, `off` / `false` = normal. Unknown states → `null`. */
28229
- function parseBinaryBatteryPercentage(raw) {
28230
- const s = raw.trim().toLowerCase();
28231
- if (s === "on" || s === "true" || s === "low") return BINARY_BATTERY_LOW_PCT;
28232
- if (s === "off" || s === "false" || s === "normal" || s === "ok") return BINARY_BATTERY_NORMAL_PCT;
28233
- return null;
29410
+ /**
29411
+ * Derive the container's device-level `battery` wiring from its entities as
29412
+ * auto-authored `DeviceLink`s. The battery cap on the container is SYNTHESIZED
29413
+ * by the generic device-link machinery (cap `status.empty` + these links)
29414
+ * no native battery provider is registered on the container.
29415
+ *
29416
+ * - NUMERIC battery sensor (real 0–100 %): field link `numeric-sensor.value →
29417
+ * battery.percentage` with a `linear 1x+0 clamp [0,100]` transform (preserves
29418
+ * the historical `parseBatteryPercentage` clamping so an out-of-range
29419
+ * firmware value can never fail the whole synthesized status), plus
29420
+ * `lastFetchedAt lastUpdated`.
29421
+ * - BINARY `LOW_BAT` indicator: `binary.on battery.percentage` through an
29422
+ * `enum-map` (`on`/low 15 %, `off`/normal 100 % the historical
29423
+ * `parseBinaryBatteryPercentage` mapping), `lastChangedAt → lastUpdated`,
29424
+ * plus a LITERAL `binary: true` flag so the UI renders "Normal"/"Low"
29425
+ * instead of a misleading exact percentage.
29426
+ * - Numeric is preferred over binary when a device exposes both
29427
+ * (`selectBatteryEntity`); no battery entity → no links (cap absent).
29428
+ *
29429
+ * `sourceKey` is the battery child's accessory `stableIdSuffix` (its
29430
+ * `entityId` — see `getAccessoryChildren`), so links survive a re-sync.
29431
+ */
29432
+ function buildBatteryLinks(entities) {
29433
+ const battery = selectBatteryEntity(entities);
29434
+ if (!battery) return [];
29435
+ const binary = isBinaryBattery(battery);
29436
+ const cap = binary ? "binary" : "numeric-sensor";
29437
+ const percentage = {
29438
+ id: "battery-percentage",
29439
+ source: {
29440
+ sourceKey: battery.entityId,
29441
+ cap,
29442
+ fieldPath: binary ? "on" : "value"
29443
+ },
29444
+ target: {
29445
+ cap: "battery",
29446
+ fieldPath: "percentage"
29447
+ },
29448
+ transform: binary ? {
29449
+ kind: "enum-map",
29450
+ mapping: {
29451
+ true: BINARY_BATTERY_LOW_PCT,
29452
+ false: BINARY_BATTERY_NORMAL_PCT
29453
+ }
29454
+ } : {
29455
+ kind: "linear",
29456
+ scale: 1,
29457
+ offset: 0,
29458
+ clamp: [0, 100]
29459
+ }
29460
+ };
29461
+ const lastUpdated = {
29462
+ id: "battery-lastUpdated",
29463
+ source: {
29464
+ sourceKey: battery.entityId,
29465
+ cap,
29466
+ fieldPath: binary ? "lastChangedAt" : "lastFetchedAt"
29467
+ },
29468
+ target: {
29469
+ cap: "battery",
29470
+ fieldPath: "lastUpdated"
29471
+ },
29472
+ transform: { kind: "identity" }
29473
+ };
29474
+ if (!binary) return [percentage, lastUpdated];
29475
+ return [
29476
+ percentage,
29477
+ lastUpdated,
29478
+ {
29479
+ id: "battery-binary",
29480
+ source: {
29481
+ kind: "literal",
29482
+ value: true
29483
+ },
29484
+ target: {
29485
+ cap: "battery",
29486
+ fieldPath: "binary"
29487
+ }
29488
+ }
29489
+ ];
28234
29490
  }
28235
29491
  /**
28236
29492
  * Parent container device for a single HA physical device. Owns no
@@ -28253,17 +29509,6 @@ var HaContainerDevice = class HaContainerDevice extends BaseDevice {
28253
29509
  features;
28254
29510
  brokerId;
28255
29511
  integrationId;
28256
- /** entityId of the battery entity (if any) on this physical device. The
28257
- * device-level `battery` cap mirrors this entity's live percentage. */
28258
- batteryEntityId;
28259
- /** True when the battery entity is a binary `LOW_BAT` indicator (no real
28260
- * percentage) rather than a numeric sensor — drives the state decode. */
28261
- batteryIsBinary;
28262
- /** Disposer for the cap event-bus listener that decodes battery pushes. */
28263
- batteryEventUnsub = null;
28264
- /** Upstream broker subscription id for the battery entity — released in
28265
- * `removeDevice`. Null until `onActivate` subscribes. */
28266
- batterySubscriptionId = null;
28267
29512
  /** Set of this device's entity ids (the physical HA device's entities). The
28268
29513
  * container's `online` is derived as "any of these entities reachable" (A3). */
28269
29514
  entityIds;
@@ -28284,76 +29529,11 @@ var HaContainerDevice = class HaContainerDevice extends BaseDevice {
28284
29529
  super(ctx, haContainerSchema, { type: DeviceType.Container });
28285
29530
  this.brokerId = cfg.brokerId;
28286
29531
  this.integrationId = cfg.integrationId;
28287
- this.batteryEntityId = batteryEntity?.entityId ?? null;
28288
- this.batteryIsBinary = batteryEntity !== null && isBinaryBattery(batteryEntity);
28289
29532
  this.features = batteryEntity !== null ? [DeviceFeature.Resyncable, DeviceFeature.BatteryOperated] : [DeviceFeature.Resyncable];
28290
29533
  this.entityIds = new Set(cfg.entities.map((e) => e.entityId));
28291
29534
  this.online = false;
28292
29535
  }
28293
29536
  /**
28294
- * Register the device-level `battery` cap on the container, backed by
28295
- * the runtime-state slice. The UI battery badge gates on the presence
28296
- * of this slice (the `useDeviceBattery` hook reads `device.state.battery`),
28297
- * so registering the cap + seeding the slice is what surfaces the badge
28298
- * on the physical device — the per-entity numeric-sensor child stays.
28299
- *
28300
- * The slice is fed from the battery entity's live HA state via the same
28301
- * `broker.message` event-bus mechanism the per-domain children use; the
28302
- * listener is attached here so the integration manager's immediate
28303
- * cache-replay (triggered by the broker subscription in `onActivate`)
28304
- * lands after the cap schema is installed.
28305
- */
28306
- registerBatteryCap() {
28307
- const COLD_START = {
28308
- percentage: this.batteryIsBinary ? BINARY_BATTERY_NORMAL_PCT : 0,
28309
- charging: "none",
28310
- sleeping: false,
28311
- lastUpdated: 0,
28312
- binary: this.batteryIsBinary
28313
- };
28314
- this.ctx.registerNativeCap(batteryCapability, {
28315
- getStatus: async ({ deviceId }) => {
28316
- if (deviceId !== this.id) throw new Error(`HaContainerDevice: battery deviceId mismatch, expected ${this.id}, got ${deviceId}`);
28317
- return this.runtimeState.getCapState("battery") ?? COLD_START;
28318
- },
28319
- wakeForStream: async () => ({
28320
- awoke: true,
28321
- durationMs: 0
28322
- })
28323
- });
28324
- this.runtimeState.setCapState("battery", COLD_START);
28325
- this.attachBatteryEventListener();
28326
- }
28327
- /** Subscribe to `broker.message` events and decode the battery entity's
28328
- * percentage into the `battery` slice on every matching push. */
28329
- attachBatteryEventListener() {
28330
- const handler = (event) => {
28331
- const data = event.data;
28332
- if (!data) return;
28333
- if (data.brokerId !== this.brokerId) return;
28334
- if (data.key !== this.batteryEntityId) return;
28335
- const state = data.payload;
28336
- if (!state) return;
28337
- this.applyBatteryState(state);
28338
- };
28339
- const unsub = this.ctx.eventBus.subscribe({ category: HaContainerDevice.BROKER_MSG_CATEGORY }, handler);
28340
- this.batteryEventUnsub = typeof unsub === "function" ? unsub : null;
28341
- }
28342
- /** Decode an HA entity state into the battery slice. Non-numeric states
28343
- * (`unavailable` / `unknown`) leave the last known value untouched. */
28344
- applyBatteryState(state) {
28345
- const percentage = this.batteryIsBinary ? parseBinaryBatteryPercentage(state.state) : parseBatteryPercentage(state.state);
28346
- if (percentage === null) return;
28347
- const next = {
28348
- percentage,
28349
- charging: "none",
28350
- sleeping: false,
28351
- lastUpdated: Date.parse(state.last_updated) || Date.now(),
28352
- binary: this.batteryIsBinary
28353
- };
28354
- this.runtimeState.setCapState("battery", next);
28355
- }
28356
- /**
28357
29537
  * Subscribe to `broker.message` events for every one of this device's
28358
29538
  * entities and derive the container's `online` from their aggregate
28359
29539
  * availability (A3): `online = any entity reachable`. A child entity is
@@ -28412,21 +29592,7 @@ var HaContainerDevice = class HaContainerDevice extends BaseDevice {
28412
29592
  }
28413
29593
  }
28414
29594
  await this.persistChildLayout();
28415
- if (this.batteryEntityId === null) return;
28416
- this.registerBatteryCap();
28417
- try {
28418
- const result = await this.ctx.api.broker.subscribe.mutate({
28419
- brokerId: this.brokerId,
28420
- filter: { entityIds: [this.batteryEntityId] }
28421
- });
28422
- this.batterySubscriptionId = result.subscriptionId;
28423
- } catch (err) {
28424
- this.ctx.logger.warn("ha-container failed to subscribe battery entity", { meta: {
28425
- entityId: this.batteryEntityId,
28426
- brokerId: this.brokerId,
28427
- error: errMsg(err)
28428
- } });
28429
- }
29595
+ await this.persistBatteryLinks();
28430
29596
  }
28431
29597
  async removeDevice() {
28432
29598
  if (this.availabilityEventUnsub) {
@@ -28444,21 +29610,6 @@ var HaContainerDevice = class HaContainerDevice extends BaseDevice {
28444
29610
  } catch {}
28445
29611
  this.availabilitySubscriptionId = null;
28446
29612
  }
28447
- if (this.batteryEventUnsub) {
28448
- try {
28449
- this.batteryEventUnsub();
28450
- } catch {}
28451
- this.batteryEventUnsub = null;
28452
- }
28453
- if (this.batterySubscriptionId !== null) {
28454
- try {
28455
- await this.ctx.api.broker.unsubscribe.mutate({
28456
- brokerId: this.brokerId,
28457
- subscriptionId: this.batterySubscriptionId
28458
- });
28459
- } catch {}
28460
- this.batterySubscriptionId = null;
28461
- }
28462
29613
  }
28463
29614
  /**
28464
29615
  * Derive this container's `childLayout` from its LIVE entities and persist it
@@ -28483,6 +29634,33 @@ var HaContainerDevice = class HaContainerDevice extends BaseDevice {
28483
29634
  }
28484
29635
  }
28485
29636
  /**
29637
+ * Derive this container's device-level battery wiring from its LIVE entities
29638
+ * (`buildBatteryLinks`) and persist it via `deviceManager.setDeviceLinks`,
29639
+ * PRESERVING any operator-authored links that target other caps (the
29640
+ * mutation replaces the device's whole `deviceLinks` array, so we merge:
29641
+ * foreign-target links kept, battery-target links replaced by the derived
29642
+ * set). Churn-free: skips the mutation when the persisted links already
29643
+ * match. Idempotent + best-effort (mirrors `persistChildLayout`): a failure
29644
+ * is logged and swallowed so it never breaks activation or reconcile.
29645
+ */
29646
+ async persistBatteryLinks() {
29647
+ try {
29648
+ const built = buildBatteryLinks(this.config.values.entities);
29649
+ const current = (await this.ctx.api.deviceManager.getDevice.query({ deviceId: this.id }))?.deviceLinks ?? [];
29650
+ const next = [...current.filter((l) => l.target.cap !== "battery"), ...built];
29651
+ if (JSON.stringify(next) === JSON.stringify(current)) return;
29652
+ await this.ctx.api.deviceManager.setDeviceLinks.mutate({
29653
+ deviceId: this.id,
29654
+ deviceLinks: next
29655
+ });
29656
+ } catch (err) {
29657
+ this.ctx.logger.warn("ha-container failed to persist battery device-links", { meta: {
29658
+ haDeviceId: this.config.values.haDeviceId,
29659
+ error: errMsg(err)
29660
+ } });
29661
+ }
29662
+ }
29663
+ /**
28486
29664
  * Device-level RAW upstream state for the physical HA device. HA has no
28487
29665
  * single device-level state blob — a device's truth lives in its entities —
28488
29666
  * so we aggregate every linked entity's raw `{ state, attributes }` (the
@@ -32912,7 +34090,10 @@ var HaProviderAddon = class HaProviderAddon extends BaseDeviceProvider {
32912
34090
  }
32913
34091
  }
32914
34092
  if (plan.membershipChanged && container instanceof HaContainerDevice) await container.reprobe();
32915
- if (container instanceof HaContainerDevice) await container.persistChildLayout();
34093
+ if (container instanceof HaContainerDevice) {
34094
+ await container.persistChildLayout();
34095
+ await container.persistBatteryLinks();
34096
+ }
32916
34097
  const integrationId = container.config.get("integrationId");
32917
34098
  this.ctx.logger.info("ha re-sync: container reconciled", {
32918
34099
  tags: {