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