@camstack/addon-static-turn 1.1.14 → 1.1.16

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.
@@ -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) {
@@ -7421,6 +7590,601 @@ var _macroLookup = /* @__PURE__ */ new Map();
7421
7590
  for (const [k, v] of Object.entries(YAMNET_TO_MACRO.mapping)) _macroLookup.set(k.toLowerCase(), v);
7422
7591
  for (const [k, v] of Object.entries(APPLE_SA_TO_MACRO.mapping)) _macroLookup.set(k.toLowerCase(), v);
7423
7592
  /**
7593
+ * Error types for the safe expression engine. Two distinct classes so callers
7594
+ * can tell a compile-time (grammar) failure from a runtime (evaluation)
7595
+ * failure — both are non-fatal to the host: read paths degrade to "skip link".
7596
+ */
7597
+ /** Thrown by the tokenizer / parser. Carries a 0-based source `position` when
7598
+ * the failure is anchored to a character (author-facing inline feedback). */
7599
+ var ExpressionParseError = class extends Error {
7600
+ position;
7601
+ constructor(message, position) {
7602
+ super(message);
7603
+ this.name = "ExpressionParseError";
7604
+ this.position = position;
7605
+ }
7606
+ };
7607
+ /** Thrown by the evaluator (unknown identifier, type mismatch, non-finite
7608
+ * result, unknown builtin, step-budget exceeded). */
7609
+ var ExpressionEvalError = class extends Error {
7610
+ constructor(message) {
7611
+ super(message);
7612
+ this.name = "ExpressionEvalError";
7613
+ }
7614
+ };
7615
+ /**
7616
+ * Resource-bound constants for the safe expression engine.
7617
+ *
7618
+ * Every bound is defense-in-depth: the grammar is non-Turing-complete (no
7619
+ * loops, recursion, lambdas or member access — see `ast.ts`), so evaluation is
7620
+ * O(nodeCount) by construction. These caps merely put a hard ceiling on the
7621
+ * work a single author-supplied expression can request, so a hostile or
7622
+ * accidental pathological string can never spend unbounded CPU/memory.
7623
+ */
7624
+ /** Max source length (chars) — checked BEFORE tokenizing so a huge string is
7625
+ * rejected without allocation. */
7626
+ var MAX_EXPRESSION_SOURCE_LENGTH = 2048;
7627
+ /** A legal binding / identifier name. */
7628
+ var EXPRESSION_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
7629
+ /** Binding names an author may NOT use: `now` is auto-injected; the literal
7630
+ * keywords lex as values, not identifiers, so binding to them is meaningless. */
7631
+ var RESERVED_BINDING_NAMES = new Set([
7632
+ "now",
7633
+ "true",
7634
+ "false",
7635
+ "null"
7636
+ ]);
7637
+ /**
7638
+ * Tokenizer for the safe expression mini-language. Hand-rolled, single-pass,
7639
+ * zero-dependency. The grammar is deliberately boring: decimal numbers,
7640
+ * single/double-quoted strings with a tiny escape set, identifiers, the three
7641
+ * value keywords (`true`/`false`/`null`) and a fixed punctuator set. Anything
7642
+ * outside that — a bare `.`, `=`, `[`, `]`, `{`, `}`, `;`, backtick, `&`, `|` —
7643
+ * is a parse error with a source position, so member access / assignment /
7644
+ * template literals are lexically impossible.
7645
+ */
7646
+ var KEYWORDS = new Set([
7647
+ "true",
7648
+ "false",
7649
+ "null"
7650
+ ]);
7651
+ function isDigit(ch) {
7652
+ return ch >= "0" && ch <= "9";
7653
+ }
7654
+ function isIdentStart(ch) {
7655
+ return ch >= "A" && ch <= "Z" || ch >= "a" && ch <= "z" || ch === "_";
7656
+ }
7657
+ function isIdentPart(ch) {
7658
+ return isIdentStart(ch) || isDigit(ch);
7659
+ }
7660
+ function isWhitespace(ch) {
7661
+ return ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
7662
+ }
7663
+ /** Tokenize `source` into a flat token list ending with a single `eof` token.
7664
+ * Throws `ExpressionParseError` on any illegal character or unterminated
7665
+ * string. */
7666
+ function tokenize(source) {
7667
+ if (source.length > 2048) throw new ExpressionParseError(`expression too long (${source.length} > ${MAX_EXPRESSION_SOURCE_LENGTH} chars)`, 0);
7668
+ const tokens = [];
7669
+ let i = 0;
7670
+ const n = source.length;
7671
+ while (i < n) {
7672
+ const ch = source[i];
7673
+ if (isWhitespace(ch)) {
7674
+ i += 1;
7675
+ continue;
7676
+ }
7677
+ if (isDigit(ch)) {
7678
+ const start = i;
7679
+ while (i < n && isDigit(source[i])) i += 1;
7680
+ if (i < n && source[i] === ".") {
7681
+ if (i + 1 >= n || !isDigit(source[i + 1])) throw new ExpressionParseError("malformed number: decimal point needs a digit", i);
7682
+ i += 1;
7683
+ while (i < n && isDigit(source[i])) i += 1;
7684
+ }
7685
+ const text = source.slice(start, i);
7686
+ const value = Number(text);
7687
+ if (!Number.isFinite(value)) throw new ExpressionParseError(`malformed number: '${text}'`, start);
7688
+ tokens.push({
7689
+ type: "number",
7690
+ value,
7691
+ pos: start
7692
+ });
7693
+ continue;
7694
+ }
7695
+ if (ch === "'" || ch === "\"") {
7696
+ const quote = ch;
7697
+ const start = i;
7698
+ i += 1;
7699
+ let out = "";
7700
+ let closed = false;
7701
+ while (i < n) {
7702
+ const c = source[i];
7703
+ if (c === "\\") {
7704
+ const next = i + 1 < n ? source[i + 1] : "";
7705
+ if (next === "\\" || next === "'" || next === "\"") {
7706
+ out += next;
7707
+ i += 2;
7708
+ continue;
7709
+ }
7710
+ throw new ExpressionParseError(`invalid string escape: '\\${next}'`, i);
7711
+ }
7712
+ if (c === quote) {
7713
+ closed = true;
7714
+ i += 1;
7715
+ break;
7716
+ }
7717
+ out += c;
7718
+ i += 1;
7719
+ }
7720
+ if (!closed) throw new ExpressionParseError("unterminated string literal", start);
7721
+ tokens.push({
7722
+ type: "string",
7723
+ value: out,
7724
+ pos: start
7725
+ });
7726
+ continue;
7727
+ }
7728
+ if (isIdentStart(ch)) {
7729
+ const start = i;
7730
+ while (i < n && isIdentPart(source[i])) i += 1;
7731
+ const text = source.slice(start, i);
7732
+ if (KEYWORDS.has(text)) tokens.push({
7733
+ type: "keyword",
7734
+ keyword: keywordOf(text),
7735
+ pos: start
7736
+ });
7737
+ else tokens.push({
7738
+ type: "identifier",
7739
+ name: text,
7740
+ pos: start
7741
+ });
7742
+ continue;
7743
+ }
7744
+ const two = i + 1 < n ? source.slice(i, i + 2) : "";
7745
+ if (two === "<=" || two === ">=" || two === "==" || two === "!=" || two === "&&" || two === "||") {
7746
+ tokens.push({
7747
+ type: "punct",
7748
+ punct: two,
7749
+ pos: i
7750
+ });
7751
+ i += 2;
7752
+ continue;
7753
+ }
7754
+ if (isSinglePunct(ch)) {
7755
+ tokens.push({
7756
+ type: "punct",
7757
+ punct: ch,
7758
+ pos: i
7759
+ });
7760
+ i += 1;
7761
+ continue;
7762
+ }
7763
+ throw new ExpressionParseError(`unexpected character '${ch}'`, i);
7764
+ }
7765
+ tokens.push({
7766
+ type: "eof",
7767
+ pos: n
7768
+ });
7769
+ return tokens;
7770
+ }
7771
+ function keywordOf(text) {
7772
+ if (text === "true") return "true";
7773
+ if (text === "false") return "false";
7774
+ return "null";
7775
+ }
7776
+ function isSinglePunct(ch) {
7777
+ return ch === "(" || ch === ")" || ch === "," || ch === "?" || ch === ":" || ch === "+" || ch === "-" || ch === "*" || ch === "/" || ch === "%" || ch === "!" || ch === "<" || ch === ">";
7778
+ }
7779
+ /**
7780
+ * Frozen, null-prototype builtin function table for the expression engine
7781
+ * (spec §4 rule 4). The table is the SOLE surface of callable functions: the
7782
+ * parser rejects any callee not in it, and the evaluator gates each call on an
7783
+ * own-property check against it.
7784
+ *
7785
+ * Because the object has a NULL prototype AND is `Object.freeze`d:
7786
+ * - it cannot be polluted (no `__proto__` / `constructor` write reaches it);
7787
+ * - a lookup for `toString` / `hasOwnProperty` / `constructor` finds NOTHING
7788
+ * (there is no `Object.prototype` in the chain), so those names are not
7789
+ * callable — they are simply "unknown function" at parse time.
7790
+ *
7791
+ * Every numeric argument is validated as a finite number and every numeric
7792
+ * RESULT is re-checked finite, so `/0`, `sqrt(-1)` (→ NaN) and overflow
7793
+ * (`pow(10,400)` → Infinity) all raise `ExpressionEvalError` and fail the link
7794
+ * closed rather than emitting a garbage value.
7795
+ */
7796
+ function asFiniteNumber(value, name, index) {
7797
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a finite number`);
7798
+ return value;
7799
+ }
7800
+ function asString$1(value, name, index) {
7801
+ if (typeof value !== "string") throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a string`);
7802
+ return value;
7803
+ }
7804
+ function finiteResult(value, name) {
7805
+ if (!Number.isFinite(value)) throw new ExpressionEvalError(`${name}: produced a non-finite result`);
7806
+ return value;
7807
+ }
7808
+ function allFiniteNumbers(args, name) {
7809
+ return args.map((a, idx) => asFiniteNumber(a, name, idx));
7810
+ }
7811
+ var INF = Number.POSITIVE_INFINITY;
7812
+ var table = {
7813
+ min: {
7814
+ minArgs: 1,
7815
+ maxArgs: INF,
7816
+ apply: (args) => finiteResult(Math.min(...allFiniteNumbers(args, "min")), "min")
7817
+ },
7818
+ max: {
7819
+ minArgs: 1,
7820
+ maxArgs: INF,
7821
+ apply: (args) => finiteResult(Math.max(...allFiniteNumbers(args, "max")), "max")
7822
+ },
7823
+ abs: {
7824
+ minArgs: 1,
7825
+ maxArgs: 1,
7826
+ apply: (args) => finiteResult(Math.abs(asFiniteNumber(args[0], "abs", 0)), "abs")
7827
+ },
7828
+ floor: {
7829
+ minArgs: 1,
7830
+ maxArgs: 1,
7831
+ apply: (args) => finiteResult(Math.floor(asFiniteNumber(args[0], "floor", 0)), "floor")
7832
+ },
7833
+ ceil: {
7834
+ minArgs: 1,
7835
+ maxArgs: 1,
7836
+ apply: (args) => finiteResult(Math.ceil(asFiniteNumber(args[0], "ceil", 0)), "ceil")
7837
+ },
7838
+ sqrt: {
7839
+ minArgs: 1,
7840
+ maxArgs: 1,
7841
+ apply: (args) => finiteResult(Math.sqrt(asFiniteNumber(args[0], "sqrt", 0)), "sqrt")
7842
+ },
7843
+ round: {
7844
+ minArgs: 1,
7845
+ maxArgs: 2,
7846
+ apply: (args) => {
7847
+ const x = asFiniteNumber(args[0], "round", 0);
7848
+ const digits = args.length > 1 ? Math.trunc(asFiniteNumber(args[1], "round", 1)) : 0;
7849
+ if (digits < 0 || digits > 100) throw new ExpressionEvalError("round: digits must be between 0 and 100");
7850
+ const factor = 10 ** digits;
7851
+ return finiteResult(Math.round(x * factor) / factor, "round");
7852
+ }
7853
+ },
7854
+ pow: {
7855
+ minArgs: 2,
7856
+ maxArgs: 2,
7857
+ apply: (args) => finiteResult(asFiniteNumber(args[0], "pow", 0) ** asFiniteNumber(args[1], "pow", 1), "pow")
7858
+ },
7859
+ clamp: {
7860
+ minArgs: 3,
7861
+ maxArgs: 3,
7862
+ apply: (args) => {
7863
+ const x = asFiniteNumber(args[0], "clamp", 0);
7864
+ const lo = asFiniteNumber(args[1], "clamp", 1);
7865
+ const hi = asFiniteNumber(args[2], "clamp", 2);
7866
+ if (lo > hi) throw new ExpressionEvalError("clamp: lower bound is greater than upper bound");
7867
+ return finiteResult(Math.min(hi, Math.max(lo, x)), "clamp");
7868
+ }
7869
+ },
7870
+ avg: {
7871
+ minArgs: 1,
7872
+ maxArgs: INF,
7873
+ apply: (args) => {
7874
+ const nums = allFiniteNumbers(args, "avg");
7875
+ return finiteResult(nums.reduce((acc, v) => acc + v, 0) / nums.length, "avg");
7876
+ }
7877
+ },
7878
+ sum: {
7879
+ minArgs: 1,
7880
+ maxArgs: INF,
7881
+ apply: (args) => finiteResult(allFiniteNumbers(args, "sum").reduce((acc, v) => acc + v, 0), "sum")
7882
+ },
7883
+ coalesce: {
7884
+ minArgs: 1,
7885
+ maxArgs: INF,
7886
+ apply: (args) => {
7887
+ for (const a of args) if (a !== null) return a;
7888
+ return null;
7889
+ }
7890
+ },
7891
+ age: {
7892
+ minArgs: 2,
7893
+ maxArgs: 2,
7894
+ apply: (args) => finiteResult(asFiniteNumber(args[0], "age", 0) - asFiniteNumber(args[1], "age", 1), "age")
7895
+ },
7896
+ convert: {
7897
+ minArgs: 3,
7898
+ maxArgs: 3,
7899
+ apply: (args, hooks) => {
7900
+ const x = asFiniteNumber(args[0], "convert", 0);
7901
+ const from = asString$1(args[1], "convert", 1).trim();
7902
+ const to = asString$1(args[2], "convert", 2).trim();
7903
+ if (hooks.convert) {
7904
+ const out = hooks.convert(x, from, to);
7905
+ if (out === null) throw new ExpressionEvalError(`convert: cannot convert '${from}' to '${to}'`);
7906
+ return finiteResult(out, "convert");
7907
+ }
7908
+ if (from === to) return x;
7909
+ throw new ExpressionEvalError("convert: unit conversion table not installed");
7910
+ }
7911
+ }
7912
+ };
7913
+ Object.freeze(Object.assign(Object.create(null), table));
7914
+ /** The set of valid builtin names — used by the parser to reject unknown
7915
+ * callees at parse time (immediate author feedback). */
7916
+ var EXPRESSION_BUILTIN_NAMES = new Set(Object.keys(table));
7917
+ /**
7918
+ * Pratt (precedence-climbing) parser for the safe expression mini-language.
7919
+ *
7920
+ * Precedence (low → high): ternary `?:` (right-assoc) → `||` → `&&` → equality
7921
+ * → relational → additive → multiplicative → unary `! -` → call / primary.
7922
+ * Calls are ONLY `IDENT '(' args? ')'` at primary position — the callee is a
7923
+ * string validated against the builtin table at parse time, so an unknown
7924
+ * function is rejected immediately (author feedback) and a persisted expression
7925
+ * that references a since-removed builtin degrades at read.
7926
+ *
7927
+ * A node counter caps total AST size (`MAX_EXPRESSION_AST_NODES`) and call
7928
+ * arity is capped (`MAX_EXPRESSION_CALL_ARGS`) — both raise `ExpressionParseError`.
7929
+ */
7930
+ /** Binary/logical operator precedence (higher binds tighter). */
7931
+ var BINARY_PRECEDENCE = {
7932
+ "||": 1,
7933
+ "&&": 2,
7934
+ "==": 3,
7935
+ "!=": 3,
7936
+ "<": 4,
7937
+ "<=": 4,
7938
+ ">": 4,
7939
+ ">=": 4,
7940
+ "+": 5,
7941
+ "-": 5,
7942
+ "*": 6,
7943
+ "/": 6,
7944
+ "%": 6
7945
+ };
7946
+ function isLogicalOp(op) {
7947
+ return op === "&&" || op === "||";
7948
+ }
7949
+ function isBinaryOp(op) {
7950
+ return op === "+" || op === "-" || op === "*" || op === "/" || op === "%" || op === "==" || op === "!=" || op === "<" || op === "<=" || op === ">" || op === ">=";
7951
+ }
7952
+ var Parser = class {
7953
+ tokens;
7954
+ pos = 0;
7955
+ nodeCount = 0;
7956
+ identifiers = /* @__PURE__ */ new Set();
7957
+ callees = /* @__PURE__ */ new Set();
7958
+ constructor(tokens) {
7959
+ this.tokens = tokens;
7960
+ }
7961
+ parse() {
7962
+ const ast = this.parseTernary();
7963
+ const tok = this.peek();
7964
+ if (tok.type !== "eof") throw new ExpressionParseError("unexpected trailing input", tok.pos);
7965
+ return {
7966
+ ast,
7967
+ identifiers: this.identifiers,
7968
+ callees: this.callees,
7969
+ nodeCount: this.nodeCount
7970
+ };
7971
+ }
7972
+ peek() {
7973
+ return this.tokens[this.pos];
7974
+ }
7975
+ next() {
7976
+ return this.tokens[this.pos++];
7977
+ }
7978
+ /** Consume a punctuator token, erroring if the next token isn't it. */
7979
+ expectPunct(punct) {
7980
+ const tok = this.peek();
7981
+ if (tok.type !== "punct" || tok.punct !== punct) throw new ExpressionParseError(`expected '${punct}'`, tok.pos);
7982
+ this.pos += 1;
7983
+ }
7984
+ matchPunct(punct) {
7985
+ const tok = this.peek();
7986
+ if (tok.type === "punct" && tok.punct === punct) {
7987
+ this.pos += 1;
7988
+ return true;
7989
+ }
7990
+ return false;
7991
+ }
7992
+ countNode() {
7993
+ this.nodeCount += 1;
7994
+ if (this.nodeCount > 256) throw new ExpressionParseError("expression too complex", this.peek().pos);
7995
+ }
7996
+ parseTernary() {
7997
+ const test = this.parseBinary(1);
7998
+ if (this.matchPunct("?")) {
7999
+ const consequent = this.parseTernary();
8000
+ this.expectPunct(":");
8001
+ const alternate = this.parseTernary();
8002
+ this.countNode();
8003
+ return {
8004
+ kind: "conditional",
8005
+ test,
8006
+ consequent,
8007
+ alternate
8008
+ };
8009
+ }
8010
+ return test;
8011
+ }
8012
+ parseBinary(minPrec) {
8013
+ let left = this.parseUnary();
8014
+ for (;;) {
8015
+ const tok = this.peek();
8016
+ if (tok.type !== "punct") break;
8017
+ const prec = BINARY_PRECEDENCE[tok.punct];
8018
+ if (prec === void 0 || prec < minPrec) break;
8019
+ const op = tok.punct;
8020
+ this.pos += 1;
8021
+ const right = this.parseBinary(prec + 1);
8022
+ this.countNode();
8023
+ if (isLogicalOp(op)) left = {
8024
+ kind: "logical",
8025
+ op,
8026
+ left,
8027
+ right
8028
+ };
8029
+ else if (isBinaryOp(op)) left = {
8030
+ kind: "binary",
8031
+ op,
8032
+ left,
8033
+ right
8034
+ };
8035
+ else throw new ExpressionParseError(`unexpected operator '${op}'`, tok.pos);
8036
+ }
8037
+ return left;
8038
+ }
8039
+ parseUnary() {
8040
+ const tok = this.peek();
8041
+ if (tok.type === "punct" && (tok.punct === "!" || tok.punct === "-")) {
8042
+ const op = tok.punct;
8043
+ this.pos += 1;
8044
+ const operand = this.parseUnary();
8045
+ this.countNode();
8046
+ return {
8047
+ kind: "unary",
8048
+ op,
8049
+ operand
8050
+ };
8051
+ }
8052
+ return this.parsePrimary();
8053
+ }
8054
+ parsePrimary() {
8055
+ const tok = this.next();
8056
+ switch (tok.type) {
8057
+ case "number":
8058
+ this.countNode();
8059
+ return {
8060
+ kind: "literal",
8061
+ value: tok.value
8062
+ };
8063
+ case "string":
8064
+ this.countNode();
8065
+ return {
8066
+ kind: "literal",
8067
+ value: tok.value
8068
+ };
8069
+ case "keyword":
8070
+ this.countNode();
8071
+ return {
8072
+ kind: "literal",
8073
+ value: tok.keyword === "null" ? null : tok.keyword === "true"
8074
+ };
8075
+ case "identifier": {
8076
+ const nextTok = this.peek();
8077
+ if (nextTok.type === "punct" && nextTok.punct === "(") return this.parseCall(tok.name, tok.pos);
8078
+ this.identifiers.add(tok.name);
8079
+ this.countNode();
8080
+ return {
8081
+ kind: "identifier",
8082
+ name: tok.name
8083
+ };
8084
+ }
8085
+ case "punct":
8086
+ if (tok.punct === "(") {
8087
+ const inner = this.parseTernary();
8088
+ this.expectPunct(")");
8089
+ return inner;
8090
+ }
8091
+ throw new ExpressionParseError(`unexpected token '${tok.punct}'`, tok.pos);
8092
+ case "eof": throw new ExpressionParseError("unexpected end of expression", tok.pos);
8093
+ }
8094
+ }
8095
+ parseCall(callee, pos) {
8096
+ if (!EXPRESSION_BUILTIN_NAMES.has(callee)) throw new ExpressionParseError(`unknown function '${callee}'`, pos);
8097
+ this.expectPunct("(");
8098
+ const args = [];
8099
+ if (!this.matchPunct(")")) for (;;) {
8100
+ args.push(this.parseTernary());
8101
+ if (args.length > 16) throw new ExpressionParseError(`too many arguments to '${callee}'`, pos);
8102
+ if (this.matchPunct(",")) continue;
8103
+ this.expectPunct(")");
8104
+ break;
8105
+ }
8106
+ this.callees.add(callee);
8107
+ this.countNode();
8108
+ return {
8109
+ kind: "call",
8110
+ callee,
8111
+ args
8112
+ };
8113
+ }
8114
+ };
8115
+ /** Tokenize + parse `source` into a validated `ParsedExpression`. Throws
8116
+ * `ExpressionParseError` on any lexical or grammatical failure. */
8117
+ function parseExpression(source) {
8118
+ return new Parser(tokenize(source)).parse();
8119
+ }
8120
+ Object.freeze({});
8121
+ /**
8122
+ * LRU compile cache for parsed expressions (spec §2.4 "parse once … LRU keyed
8123
+ * by expr"). The cache stores BOTH successes and failures (negative caching),
8124
+ * so a corrupt persisted string costs exactly one tokenize+parse total — not
8125
+ * one per read on a hot resolve path.
8126
+ *
8127
+ * The cache is a module-level singleton: entries are pure, content-addressed
8128
+ * ASTs keyed by the raw source string, so sharing one instance across all
8129
+ * callers is safe and maximises hit rate.
8130
+ */
8131
+ var cache = /* @__PURE__ */ new Map();
8132
+ function getCached(source) {
8133
+ const hit = cache.get(source);
8134
+ if (hit !== void 0) {
8135
+ cache.delete(source);
8136
+ cache.set(source, hit);
8137
+ return hit;
8138
+ }
8139
+ let result;
8140
+ try {
8141
+ result = {
8142
+ ok: true,
8143
+ parsed: parseExpression(source)
8144
+ };
8145
+ } catch (err) {
8146
+ result = {
8147
+ ok: false,
8148
+ error: err instanceof ExpressionParseError ? err.message : String(err)
8149
+ };
8150
+ }
8151
+ cache.set(source, result);
8152
+ if (cache.size > 256) {
8153
+ const oldest = cache.keys().next().value;
8154
+ if (oldest !== void 0) cache.delete(oldest);
8155
+ }
8156
+ return result;
8157
+ }
8158
+ /** Compile `source`, returning a discriminated result instead of throwing.
8159
+ * Used by read paths that must degrade rather than raise. LRU/negative-cached. */
8160
+ function compileExpressionSafe(source) {
8161
+ return getCached(source);
8162
+ }
8163
+ /**
8164
+ * Author-time validation. Returns `null` when the source is valid, else a
8165
+ * human-readable error message. Checks: the expression compiles; binding count
8166
+ * is within `MAX_EXPRESSION_BINDINGS`; every binding name is a legal identifier,
8167
+ * is not reserved (`now`/keywords) and does not shadow a builtin; and every
8168
+ * FREE identifier of the AST is covered by a binding or the injected `now`.
8169
+ */
8170
+ function validateExpressionSource(src) {
8171
+ const names = Object.keys(src.bindings);
8172
+ if (names.length > 32) return `too many bindings (${names.length} > 32)`;
8173
+ for (const name of names) {
8174
+ if (!EXPRESSION_IDENTIFIER_RE.test(name)) return `invalid binding name '${name}'`;
8175
+ if (RESERVED_BINDING_NAMES.has(name)) return `binding name '${name}' is reserved`;
8176
+ if (EXPRESSION_BUILTIN_NAMES.has(name)) return `binding name '${name}' shadows a builtin function`;
8177
+ }
8178
+ const compiled = compileExpressionSafe(src.expr);
8179
+ if (!compiled.ok) return compiled.error;
8180
+ const bound = new Set(names);
8181
+ for (const id of compiled.parsed.identifiers) {
8182
+ if (id === "now") continue;
8183
+ if (!bound.has(id)) return `expression references unbound identifier '${id}'`;
8184
+ }
8185
+ return null;
8186
+ }
8187
+ /**
7424
8188
  * Accessory device helpers — shared across drivers.
7425
8189
  *
7426
8190
  * Many vendor-specific drivers register accessory child devices on
@@ -9323,7 +10087,8 @@ var MotionAnalysisResultSchema = object({
9323
10087
  });
9324
10088
  method(object({
9325
10089
  deviceId: number(),
9326
- frame: FrameInputSchema
10090
+ frame: FrameInputSchema.optional(),
10091
+ frameHandle: FrameHandleSchema.optional()
9327
10092
  }), MotionAnalysisResultSchema, { kind: "mutation" }), method(object({ deviceId: number() }), _void(), { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), object({
9328
10093
  deviceId: number(),
9329
10094
  detected: boolean(),
@@ -9570,6 +10335,12 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
9570
10335
  engine: PipelineEngineChoiceSchema.optional(),
9571
10336
  steps: array(PipelineStepInputSchema).min(1),
9572
10337
  frame: FrameInputSchema.optional(),
10338
+ /**
10339
+ * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
10340
+ * the decoded pixels live in. One more member of the one-of
10341
+ * frame/frameHandle/image/imageBase64/referenceImage group.
10342
+ */
10343
+ frameHandle: FrameHandleSchema.optional(),
9573
10344
  imageBase64: string().optional(),
9574
10345
  /**
9575
10346
  * Binary JPEG bytes — preferred over `imageBase64` on internal
@@ -9779,6 +10550,31 @@ var ReportMotionInputSchema = object({
9779
10550
  regions: array(MotionRegionSchema).readonly().optional()
9780
10551
  });
9781
10552
  /**
10553
+ * Where a runner gets a camera's decoded frames (cross-node Phase 2,
10554
+ * restream-owner model — P2c).
10555
+ *
10556
+ * - `local-broker` (DEFAULT): today's path — subscribe to the co-located
10557
+ * stream-broker's shm frame plane. Every pre-P2c attach payload (no
10558
+ * `frameSource` key) parses to this, so the field is additive with zero
10559
+ * behavior change.
10560
+ * - `remote-restream`: the detect node is NOT the camera's source-owner.
10561
+ * The runner acquires the owner's COMPRESSED passthrough restream
10562
+ * (`streamBroker.getStreamWithCodec({video:'copy'})` — refcounted, the
10563
+ * double-pull guard) and decodes LOCALLY via a satellite frame plane +
10564
+ * pull-mode decoder session pinned to its own node. The shm ring stays
10565
+ * node-local; only H.264/H.265 packets cross the wire.
10566
+ * `hubHostnameOverride` mirrors the recorder's `recordingHubHostname`:
10567
+ * when set it overrides the `CAMSTACK_HUB_URL`-derived host the runner
10568
+ * dials for the owner's restream.
10569
+ */
10570
+ var RunnerFrameSourceSchema = discriminatedUnion("kind", [object({ kind: literal("local-broker") }), object({
10571
+ kind: literal("remote-restream"),
10572
+ /** The camera's source-owner node (slice 1: always the hub). */
10573
+ ownerNodeId: string(),
10574
+ /** Operator override for the owner host the runner dials. */
10575
+ hubHostnameOverride: string().optional()
10576
+ })]).describe("Per-camera frame-source mode for the runner (P2c)");
10577
+ /**
9782
10578
  * Camera assignment payload sent by `addon-pipeline-orchestrator` to a
9783
10579
  * specific runner instance via `attachCamera`. Carries everything the
9784
10580
  * runner needs to subscribe to the local broker and execute inference.
@@ -9876,7 +10672,15 @@ var RunnerCameraConfigSchema = object({
9876
10672
  */
9877
10673
  onboardMotionDrivesAnalyzer: boolean().default(true),
9878
10674
  occupancyRecheckSec: number().min(occupancyRecheckSecField.min).max(occupancyRecheckSecField.max).default(occupancyRecheckSecField.default),
9879
- occupancyRecheckFrames: number().min(occupancyRecheckFramesField.min).max(occupancyRecheckFramesField.max).default(occupancyRecheckFramesField.default)
10675
+ occupancyRecheckFrames: number().min(occupancyRecheckFramesField.min).max(occupancyRecheckFramesField.max).default(occupancyRecheckFramesField.default),
10676
+ /**
10677
+ * Where this runner gets the camera's decoded frames (P2c). Defaulted so
10678
+ * every existing payload behaves as `local-broker` — the pre-Phase-2 path.
10679
+ * Populated with `remote-restream` by the orchestrator ONLY when the
10680
+ * camera's detect node differs from its source-owner (P2d, gated by the
10681
+ * `remoteSourcingNodes` rollout setting).
10682
+ */
10683
+ frameSource: RunnerFrameSourceSchema.default({ kind: "local-broker" })
9880
10684
  });
9881
10685
  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;
9882
10686
  /**
@@ -10241,6 +11045,113 @@ object({
10241
11045
  lastFetchedAt: number()
10242
11046
  });
10243
11047
  DeviceType.Sensor;
11048
+ /**
11049
+ * Feeder connectivity / power status — mirrors the HA petkit device-status
11050
+ * enum: `normal` (online, mains), `offline` (not reaching PetKit cloud),
11051
+ * `on_batteries` (running on battery backup). `null` until first reported.
11052
+ */
11053
+ var PetFeederDeviceStatusSchema = _enum([
11054
+ "normal",
11055
+ "offline",
11056
+ "on_batteries"
11057
+ ]);
11058
+ var gramsPortion = number().int().min(4).max(200);
11059
+ object({
11060
+ /** Food currently in the bowl (grams). Null when the device has not
11061
+ * reported a reading yet. On dual-hopper models this is the combined
11062
+ * bowl reading; per-hopper levels live in `food1`/`food2`. */
11063
+ foodLevel: number().nullable(),
11064
+ /** Hopper-1 food level (grams) on dual-hopper feeders; null on
11065
+ * single-hopper models. */
11066
+ food1: number().nullable(),
11067
+ /** Hopper-2 food level (grams) on dual-hopper feeders; null on
11068
+ * single-hopper models. */
11069
+ food2: number().nullable(),
11070
+ /** Derived low-food flag — mirrors the HA `food_level` binary_sensor
11071
+ * (`device_class: problem`, on = low). True when the bowl is empty /
11072
+ * below the feeder's low threshold. */
11073
+ lowFood: boolean(),
11074
+ /** Battery charge 0..100 (%). Null on mains-powered models or when the
11075
+ * device has no battery reading. */
11076
+ batteryPower: number().min(0).max(100).nullable(),
11077
+ /** Days of desiccant life remaining. Null when the model has no
11078
+ * desiccant sensor. */
11079
+ desiccantLeftDays: number().nullable(),
11080
+ /** True while a feed is in progress. */
11081
+ feeding: boolean(),
11082
+ /** Decoded connectivity / power status (HA petkit device-status enum).
11083
+ * Null until the device has reported a status. */
11084
+ status: PetFeederDeviceStatusSchema.nullable(),
11085
+ /** Decoded human-readable fault message. Null (or the device's `no_error`
11086
+ * sentinel) means healthy; a non-null string is an active fault. Pairs
11087
+ * with `errorCode` for consumers that want the raw integer. */
11088
+ error: string().nullable(),
11089
+ /** Raw device error code (0 / null = no error). */
11090
+ errorCode: number().nullable(),
11091
+ /** True for D4S/D4SH dual-hopper hardware — gates the per-hopper UI. */
11092
+ isDualHopper: boolean(),
11093
+ /** Child-lock (manual-lock) setting — buttons on the unit are disabled. */
11094
+ childLock: boolean(),
11095
+ /** Front indicator-light setting. */
11096
+ indicatorLight: boolean(),
11097
+ /** Play a chime when dispensing. */
11098
+ feedSound: boolean(),
11099
+ /** Speaker / prompt volume level (device-scaled integer). */
11100
+ volume: number(),
11101
+ /** Ms epoch when the slice was last refreshed from the cloud. */
11102
+ lastFetchedAt: number()
11103
+ });
11104
+ DeviceType.PetFeeder, method(object({
11105
+ deviceId: number().int().nonnegative(),
11106
+ grams: gramsPortion.optional(),
11107
+ hopper1: gramsPortion.optional(),
11108
+ hopper2: gramsPortion.optional()
11109
+ }), _void(), {
11110
+ kind: "mutation",
11111
+ auth: "admin"
11112
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
11113
+ kind: "mutation",
11114
+ auth: "admin"
11115
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
11116
+ kind: "mutation",
11117
+ auth: "admin"
11118
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
11119
+ kind: "mutation",
11120
+ auth: "admin"
11121
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
11122
+ kind: "mutation",
11123
+ auth: "admin"
11124
+ }), method(object({
11125
+ deviceId: number().int().nonnegative(),
11126
+ soundId: number().int().nonnegative()
11127
+ }), _void(), {
11128
+ kind: "mutation",
11129
+ auth: "admin"
11130
+ }), method(object({
11131
+ deviceId: number().int().nonnegative(),
11132
+ on: boolean()
11133
+ }), _void(), {
11134
+ kind: "mutation",
11135
+ auth: "admin"
11136
+ }), method(object({
11137
+ deviceId: number().int().nonnegative(),
11138
+ on: boolean()
11139
+ }), _void(), {
11140
+ kind: "mutation",
11141
+ auth: "admin"
11142
+ }), method(object({
11143
+ deviceId: number().int().nonnegative(),
11144
+ on: boolean()
11145
+ }), _void(), {
11146
+ kind: "mutation",
11147
+ auth: "admin"
11148
+ }), method(object({
11149
+ deviceId: number().int().nonnegative(),
11150
+ level: number().int().nonnegative()
11151
+ }), _void(), {
11152
+ kind: "mutation",
11153
+ auth: "admin"
11154
+ });
10244
11155
  object({
10245
11156
  /** Instantaneous power draw in watts. */
10246
11157
  watts: number().optional(),
@@ -12068,10 +12979,12 @@ method(object({ codec: string() }), boolean()), method(_void(), object({
12068
12979
  url: string()
12069
12980
  }), _void()), method(object({
12070
12981
  sessionId: string(),
12071
- maxCount: number().default(1)
12982
+ maxCount: number().default(1),
12983
+ waitMs: number().optional()
12072
12984
  }), array(DecodedFrameSchema)), method(object({
12073
12985
  sessionId: string(),
12074
- maxCount: number().default(1)
12986
+ maxCount: number().default(1),
12987
+ waitMs: number().optional()
12075
12988
  }), array(FrameHandleSchema)), method(object({ handle: FrameHandleSchema }), DecodedFrameSchema.nullable()), method(object({ sessionId: string() }), ShmRingStatsSchema.nullable()), method(object({
12076
12989
  sessionId: string(),
12077
12990
  config: DecoderSessionConfigSchema.partial()
@@ -12358,14 +13271,63 @@ var ChildLayoutEntrySchema = object({
12358
13271
  collapsed: boolean().optional()
12359
13272
  });
12360
13273
  /** Cap-wire shape of a DeviceLink — structurally mirrors `DeviceLink` in
12361
- * `device-management.ts`. */
13274
+ * `device-management.ts`. Source is a union: a FIELD source copies a sibling
13275
+ * accessory's status field (`kind` optional/absent for wire compat); a
13276
+ * LITERAL source carries a per-device constant (no sibling is read); a
13277
+ * GLOBAL source (P2e) copies ANY device's status field, addressed by the
13278
+ * source device's full re-sync-stable `stableId`. */
13279
+ var DeviceLinkFieldSourceSchema = object({
13280
+ kind: literal("field").optional(),
13281
+ sourceKey: string(),
13282
+ cap: string(),
13283
+ fieldPath: string()
13284
+ });
13285
+ var DeviceLinkLiteralSourceSchema = object({
13286
+ kind: literal("literal"),
13287
+ value: union([
13288
+ string(),
13289
+ number(),
13290
+ boolean(),
13291
+ _null()
13292
+ ])
13293
+ });
13294
+ var DeviceLinkGlobalSourceSchema = object({
13295
+ kind: literal("global"),
13296
+ sourceStableId: string(),
13297
+ cap: string(),
13298
+ fieldPath: string()
13299
+ });
13300
+ /** Expression source (Stage X): compute the target field from N named bindings
13301
+ * via the safe expression engine. Bindings are field | literal | global — never
13302
+ * another expression (no nesting). The `superRefine` runs the SAME author-time
13303
+ * validation as `validateExpressionSource` (compiles the expr, checks binding
13304
+ * names + identifier coverage) so every wire boundary that parses a DeviceLink
13305
+ * (tRPC mount, kernel create pre-seed, projection output) validates-at-write.
13306
+ * Compiles are LRU-cached, so repeated validation of the same expr is a hit. */
13307
+ var DeviceLinkExpressionSourceSchema = object({
13308
+ kind: literal("expression"),
13309
+ expr: string().min(1).max(MAX_EXPRESSION_SOURCE_LENGTH),
13310
+ bindings: record(string().regex(EXPRESSION_IDENTIFIER_RE), union([
13311
+ DeviceLinkFieldSourceSchema,
13312
+ DeviceLinkLiteralSourceSchema,
13313
+ DeviceLinkGlobalSourceSchema
13314
+ ]))
13315
+ }).superRefine((src, ctx) => {
13316
+ const err = validateExpressionSource(src);
13317
+ if (err !== null) ctx.addIssue({
13318
+ code: "custom",
13319
+ message: err,
13320
+ path: ["expr"]
13321
+ });
13322
+ });
12362
13323
  var DeviceLinkSchema = object({
12363
13324
  id: string(),
12364
- source: object({
12365
- sourceKey: string(),
12366
- cap: string(),
12367
- fieldPath: string()
12368
- }),
13325
+ source: union([
13326
+ DeviceLinkFieldSourceSchema,
13327
+ DeviceLinkLiteralSourceSchema,
13328
+ DeviceLinkGlobalSourceSchema,
13329
+ DeviceLinkExpressionSourceSchema
13330
+ ]),
12369
13331
  target: object({
12370
13332
  cap: string(),
12371
13333
  fieldPath: string(),
@@ -12394,6 +13356,31 @@ var DeviceLinkSchema = object({
12394
13356
  })
12395
13357
  ]).optional()
12396
13358
  });
13359
+ /** Cap-wire shape of a per-cap display refinement — mirrors
13360
+ * `DeviceCapDisplayOverride` in `device-management.ts`. */
13361
+ var DeviceCapDisplayOverrideSchema = object({
13362
+ unit: string().min(1).optional(),
13363
+ precision: number().int().min(0).max(10).optional()
13364
+ });
13365
+ /** Cap-wire shape of an operator-authored per-device display override —
13366
+ * mirrors `DeviceDisplayOverride` in `device-management.ts`. `precision`
13367
+ * bounds mirror `numeric-sensor.cap.ts` (`int 0-10`). */
13368
+ var DeviceDisplayOverrideSchema = object({
13369
+ icon: string().min(1).optional(),
13370
+ label: string().min(1).optional(),
13371
+ unit: string().min(1).optional(),
13372
+ precision: number().int().min(0).max(10).optional(),
13373
+ hidden: boolean().optional(),
13374
+ perCap: record(string(), DeviceCapDisplayOverrideSchema).optional()
13375
+ });
13376
+ /** Cap-wire shape of a per-role display default — mirrors `RoleDisplayDefault`
13377
+ * in `device-management.ts`. Keyed by `DeviceRole` string (role strings cross
13378
+ * the wire as plain strings everywhere else — cf. `DeviceInfoSchema.role`). */
13379
+ var RoleDisplayDefaultSchema = object({
13380
+ unit: string().min(1).optional(),
13381
+ precision: number().int().min(0).max(10).optional(),
13382
+ icon: string().min(1).optional()
13383
+ });
12397
13384
  /**
12398
13385
  * Serializable projection of a live IDevice.
12399
13386
  * Returned by listAll, getDevice, getChildren.
@@ -12449,7 +13436,9 @@ var DeviceInfoSchema = object({
12449
13436
  * `DeviceMeta.childLayout`. Absent ⇒ no layout declared. */
12450
13437
  childLayout: array(ChildLayoutEntrySchema).readonly().optional(),
12451
13438
  /** Operator-authored cross-device field wirings. See `DeviceMeta.deviceLinks`. */
12452
- deviceLinks: array(DeviceLinkSchema).readonly().optional()
13439
+ deviceLinks: array(DeviceLinkSchema).readonly().optional(),
13440
+ /** Operator-authored per-device display override. See `DeviceMeta.display`. */
13441
+ display: DeviceDisplayOverrideSchema.optional()
12453
13442
  });
12454
13443
  var ConfigEntrySchema = object({
12455
13444
  key: string(),
@@ -12514,7 +13503,9 @@ var DeviceMetaSchema = object({
12514
13503
  deviceLinks: array(DeviceLinkSchema).readonly().optional(),
12515
13504
  /** Semantic role string (`DeviceRole`) — propagated from the spawn pre-seed.
12516
13505
  * Optional: only present for accessory children that carry a known role. */
12517
- role: string().nullable().optional()
13506
+ role: string().nullable().optional(),
13507
+ /** Operator-authored per-device display override. See `DeviceMeta.display`. */
13508
+ display: DeviceDisplayOverrideSchema.optional()
12518
13509
  });
12519
13510
  /** ConfigUISchema passed through as unknown — mirrors device-provider's CreationSchemaOutputSchema */
12520
13511
  var ConfigUISchemaOutput = unknown().nullable();
@@ -12608,7 +13599,19 @@ method(object({
12608
13599
  }), _void(), {
12609
13600
  kind: "mutation",
12610
13601
  auth: "admin"
12611
- }), method(object({ deviceId: number() }), object({ caps: array(object({
13602
+ }), method(object({
13603
+ deviceId: number(),
13604
+ display: DeviceDisplayOverrideSchema.nullable()
13605
+ }), _void(), {
13606
+ kind: "mutation",
13607
+ auth: "admin"
13608
+ }), method(object({}), object({ defaults: record(string(), RoleDisplayDefaultSchema) }), { kind: "query" }), method(object({ defaults: record(string(), RoleDisplayDefaultSchema) }), _void(), {
13609
+ kind: "mutation",
13610
+ auth: "admin"
13611
+ }), method(object({
13612
+ deviceId: number(),
13613
+ includeSynthesizable: boolean().optional()
13614
+ }), object({ caps: array(object({
12612
13615
  cap: string(),
12613
13616
  fields: array(object({
12614
13617
  path: string(),
@@ -12618,8 +13621,13 @@ method(object({
12618
13621
  "boolean",
12619
13622
  "enum"
12620
13623
  ]),
12621
- enumValues: array(string()).optional()
12622
- })).readonly()
13624
+ enumValues: array(string()).optional(),
13625
+ item: boolean().optional()
13626
+ })).readonly(),
13627
+ itemArray: object({
13628
+ path: string(),
13629
+ keyField: string()
13630
+ }).optional()
12623
13631
  })).readonly() }), { kind: "query" }), method(object({
12624
13632
  deviceId: number(),
12625
13633
  role: string().nullable()
@@ -12689,7 +13697,11 @@ method(object({
12689
13697
  deviceId: number(),
12690
13698
  entries: array(object({
12691
13699
  capName: string(),
12692
- kind: _enum(["native", "wrapped"]),
13700
+ kind: _enum([
13701
+ "native",
13702
+ "wrapped",
13703
+ "linked"
13704
+ ]),
12693
13705
  providerAddonId: string(),
12694
13706
  providerNodeId: string(),
12695
13707
  nativeAddonId: string()
@@ -12698,7 +13710,11 @@ method(object({
12698
13710
  deviceId: number(),
12699
13711
  entries: array(object({
12700
13712
  capName: string(),
12701
- kind: _enum(["native", "wrapped"]),
13713
+ kind: _enum([
13714
+ "native",
13715
+ "wrapped",
13716
+ "linked"
13717
+ ]),
12702
13718
  providerAddonId: string(),
12703
13719
  providerNodeId: string(),
12704
13720
  nativeAddonId: string()
@@ -13940,7 +14956,10 @@ var AgentLoadSummarySchema = object({
13940
14956
  online: boolean(),
13941
14957
  load: RunnerLocalLoadSchema,
13942
14958
  /** Computed score used by the L2 capacity balancer (lower = less loaded). */
13943
- score: number()
14959
+ score: number(),
14960
+ /** This node's decode hwaccel backend (per-node `probedBestHwaccel`), or null
14961
+ * when not yet probed — for the cluster Pipeline table UI (P0.2). */
14962
+ decodeHwaccel: string().nullable()
13944
14963
  });
13945
14964
  /**
13946
14965
  * Aggregate metrics across the whole detection cluster. Replaces the legacy
@@ -16481,7 +17500,10 @@ var HwAccelBackendInputSchema = _enum([
16481
17500
  "webgpu",
16482
17501
  "none"
16483
17502
  ]).nullable().optional();
16484
- var HwAccelResolutionSchema = object({ preferred: array(string()).readonly() });
17503
+ var HwAccelResolutionSchema = object({
17504
+ preferred: array(string()).readonly(),
17505
+ rationale: string()
17506
+ });
16485
17507
  var HardwareEncoderIdSchema = _enum([
16486
17508
  "h264_videotoolbox",
16487
17509
  "hevc_videotoolbox",
@@ -16496,7 +17518,7 @@ var HardwareEncoderIdSchema = _enum([
16496
17518
  "libx264",
16497
17519
  "libx265"
16498
17520
  ]);
16499
- var HardwareEncodersSchema = object({
17521
+ object({
16500
17522
  encoders: array(object({
16501
17523
  encoder: HardwareEncoderIdSchema,
16502
17524
  codec: _enum(["H264", "H265"]),
@@ -16515,15 +17537,7 @@ var HardwareEncodersSchema = object({
16515
17537
  defaultH265: HardwareEncoderIdSchema,
16516
17538
  probedAt: number()
16517
17539
  });
16518
- /**
16519
- * Decode-side companion to {@link HardwareEncodersSchema}: the `-hwaccel`
16520
- * methods the configured ffmpeg binary actually supports (parsed from
16521
- * `ffmpeg -hwaccels`). Used to gate decode-hwaccel attempts so the transcode
16522
- * egress never spends a spawn on a backend this build cannot offer. Per-stream
16523
- * decode fragility (e.g. VideoToolbox HEVC) is still handled by the egress's
16524
- * software fallback — this only filters out wholly-unsupported backends.
16525
- */
16526
- var HardwareDecodeAccelsSchema = object({
17540
+ object({
16527
17541
  methods: array(string()).readonly(),
16528
17542
  probedAt: number()
16529
17543
  });
@@ -16586,16 +17600,7 @@ var ResolvedInferenceConfigSchema = object({
16586
17600
  format: ModelFormatSchema,
16587
17601
  reason: string()
16588
17602
  });
16589
- method(_void(), PlatformCapabilitiesSchema), method(_void(), HardwareInfoSchema), method(object({ requirements: array(ModelRequirementSchema).readonly() }), ResolvedInferenceConfigSchema), method(object({
16590
- prefer: HwAccelBackendInputSchema,
16591
- nodeId: string().optional()
16592
- }), HwAccelResolutionSchema), method(_void(), HardwareEncodersSchema), method(_void(), HardwareEncodersSchema, {
16593
- kind: "mutation",
16594
- auth: "admin"
16595
- }), method(_void(), HardwareDecodeAccelsSchema), method(_void(), HardwareDecodeAccelsSchema, {
16596
- kind: "mutation",
16597
- auth: "admin"
16598
- });
17603
+ method(_void(), PlatformCapabilitiesSchema), method(_void(), HardwareInfoSchema), method(object({ requirements: array(ModelRequirementSchema).readonly() }), ResolvedInferenceConfigSchema), method(object({ prefer: HwAccelBackendInputSchema }), HwAccelResolutionSchema);
16599
17604
  var PtzPresetSchema = object({
16600
17605
  id: string(),
16601
17606
  name: string()
@@ -16648,6 +17653,16 @@ DeviceType.Camera, DeviceType.Sensor, DeviceType.Switch, method(object({ deviceI
16648
17653
  kind: "mutation",
16649
17654
  auth: "admin"
16650
17655
  });
17656
+ /**
17657
+ * `recording` cap — footage availability + HLS playback manifests + per-device
17658
+ * recording config. NOTE on events (source of truth, R5/C3): this cap carries
17659
+ * NO event surface — `getPlaybackManifest` returns playlist URLs only. Timeline
17660
+ * events (motion/object/audio) come from `pipelineAnalytics` (durable SQLite
17661
+ * rows); the recorder's internal EventMap markers are ephemeral in-RAM
17662
+ * annotations that are not exposed here and must not be treated as an event
17663
+ * feed. Event<->footage joins are by time, padded with the shared `EVENT_PAD_MS`
17664
+ * (`interfaces/recording-config.ts`).
17665
+ */
16651
17666
  var RecordingStatusSchema = object({
16652
17667
  deviceId: number(),
16653
17668
  enabled: boolean(),
@@ -18284,6 +19299,12 @@ Object.freeze({
18284
19299
  addonId: null,
18285
19300
  access: "view"
18286
19301
  },
19302
+ "deviceManager.getRoleDisplayDefaults": {
19303
+ capName: "device-manager",
19304
+ capScope: "system",
19305
+ addonId: null,
19306
+ access: "view"
19307
+ },
18287
19308
  "deviceManager.getSettingsSchema": {
18288
19309
  capName: "device-manager",
18289
19310
  capScope: "system",
@@ -18434,6 +19455,12 @@ Object.freeze({
18434
19455
  addonId: null,
18435
19456
  access: "create"
18436
19457
  },
19458
+ "deviceManager.setDisplay": {
19459
+ capName: "device-manager",
19460
+ capScope: "system",
19461
+ addonId: null,
19462
+ access: "create"
19463
+ },
18437
19464
  "deviceManager.setIntegrationId": {
18438
19465
  capName: "device-manager",
18439
19466
  capScope: "system",
@@ -18476,6 +19503,12 @@ Object.freeze({
18476
19503
  addonId: null,
18477
19504
  access: "create"
18478
19505
  },
19506
+ "deviceManager.setRoleDisplayDefaults": {
19507
+ capName: "device-manager",
19508
+ capScope: "system",
19509
+ addonId: null,
19510
+ access: "create"
19511
+ },
18479
19512
  "deviceManager.setStreamProfileMap": {
18480
19513
  capName: "device-manager",
18481
19514
  capScope: "system",
@@ -19526,6 +20559,66 @@ Object.freeze({
19526
20559
  addonId: null,
19527
20560
  access: "create"
19528
20561
  },
20562
+ "petFeeder.callPet": {
20563
+ capName: "pet-feeder",
20564
+ capScope: "device",
20565
+ addonId: null,
20566
+ access: "create"
20567
+ },
20568
+ "petFeeder.cancelFeed": {
20569
+ capName: "pet-feeder",
20570
+ capScope: "device",
20571
+ addonId: null,
20572
+ access: "create"
20573
+ },
20574
+ "petFeeder.feed": {
20575
+ capName: "pet-feeder",
20576
+ capScope: "device",
20577
+ addonId: null,
20578
+ access: "create"
20579
+ },
20580
+ "petFeeder.markFoodReplenished": {
20581
+ capName: "pet-feeder",
20582
+ capScope: "device",
20583
+ addonId: null,
20584
+ access: "create"
20585
+ },
20586
+ "petFeeder.playSound": {
20587
+ capName: "pet-feeder",
20588
+ capScope: "device",
20589
+ addonId: null,
20590
+ access: "create"
20591
+ },
20592
+ "petFeeder.resetDesiccant": {
20593
+ capName: "pet-feeder",
20594
+ capScope: "device",
20595
+ addonId: null,
20596
+ access: "delete"
20597
+ },
20598
+ "petFeeder.setChildLock": {
20599
+ capName: "pet-feeder",
20600
+ capScope: "device",
20601
+ addonId: null,
20602
+ access: "create"
20603
+ },
20604
+ "petFeeder.setFeedSound": {
20605
+ capName: "pet-feeder",
20606
+ capScope: "device",
20607
+ addonId: null,
20608
+ access: "create"
20609
+ },
20610
+ "petFeeder.setIndicatorLight": {
20611
+ capName: "pet-feeder",
20612
+ capScope: "device",
20613
+ addonId: null,
20614
+ access: "create"
20615
+ },
20616
+ "petFeeder.setVolume": {
20617
+ capName: "pet-feeder",
20618
+ capScope: "device",
20619
+ addonId: null,
20620
+ access: "create"
20621
+ },
19529
20622
  "pipelineAnalytics.clearTracks": {
19530
20623
  capName: "pipeline-analytics",
19531
20624
  capScope: "device",
@@ -20132,30 +21225,6 @@ Object.freeze({
20132
21225
  addonId: null,
20133
21226
  access: "view"
20134
21227
  },
20135
- "platformProbe.getHardwareDecodeAccels": {
20136
- capName: "platform-probe",
20137
- capScope: "system",
20138
- addonId: null,
20139
- access: "view"
20140
- },
20141
- "platformProbe.getHardwareEncoders": {
20142
- capName: "platform-probe",
20143
- capScope: "system",
20144
- addonId: null,
20145
- access: "view"
20146
- },
20147
- "platformProbe.refreshHardwareDecodeAccels": {
20148
- capName: "platform-probe",
20149
- capScope: "system",
20150
- addonId: null,
20151
- access: "create"
20152
- },
20153
- "platformProbe.refreshHardwareEncoders": {
20154
- capName: "platform-probe",
20155
- capScope: "system",
20156
- addonId: null,
20157
- access: "create"
20158
- },
20159
21228
  "platformProbe.resolveHwAccel": {
20160
21229
  capName: "platform-probe",
20161
21230
  capScope: "system",