@camstack/addon-cloudflare 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.
@@ -4627,7 +4627,7 @@ function _instanceof(cls, params = {}) {
4627
4627
  return inst;
4628
4628
  }
4629
4629
  //#endregion
4630
- //#region ../types/dist/sleep-MHm--th-.mjs
4630
+ //#region ../types/dist/sleep-BiDFW0E7.mjs
4631
4631
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
4632
4632
  EventCategory["SystemBoot"] = "system.boot";
4633
4633
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -5440,6 +5440,100 @@ function createDurableState(deps) {
5440
5440
  };
5441
5441
  }
5442
5442
  /**
5443
+ * Per-node scoping for the shared addon-settings blob.
5444
+ *
5445
+ * An addon's settings store is hub-central (the `addon-settings` cap is
5446
+ * hub-routed — the hub instance answers for every node), so fields whose
5447
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
5448
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
5449
+ * the single shared blob. The SCHEMA field key stays bare: the write path
5450
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
5451
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
5452
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
5453
+ *
5454
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
5455
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
5456
+ * schema and routes reads/writes through these helpers.
5457
+ *
5458
+ * ## No bare-key fallback — deliberate
5459
+ *
5460
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
5461
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
5462
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
5463
+ * the store is invisible to every node, hub included, so one node's
5464
+ * selection can never leak onto another. (This generalizes the
5465
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
5466
+ * arbitrary set of per-node field keys.)
5467
+ *
5468
+ * Pure functions only — no I/O, no imports beyond the language. This is a
5469
+ * LEAF module: import it via its deep path, never from the root barrel.
5470
+ */
5471
+ /**
5472
+ * Normalize a raw kernel node id to the bare node id used for scoping.
5473
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
5474
+ * processes; per-node settings are per-NODE, so strip the addon segment.
5475
+ * `undefined` / `null` / empty falls back to `'hub'`.
5476
+ */
5477
+ function normalizeNodeId(raw) {
5478
+ if (raw === void 0 || raw === null || raw === "") return "hub";
5479
+ const slashIdx = raw.indexOf("/");
5480
+ if (slashIdx < 0) return raw;
5481
+ const bare = raw.slice(0, slashIdx);
5482
+ return bare === "" ? "hub" : bare;
5483
+ }
5484
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
5485
+ function nodeScopedKey(base, nodeId) {
5486
+ return `${base}@${normalizeNodeId(nodeId)}`;
5487
+ }
5488
+ /**
5489
+ * Read a node's value for a per-node field from the raw shared store:
5490
+ * the node-scoped key when present, otherwise `undefined`.
5491
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
5492
+ * schema `default` win on `undefined`.
5493
+ */
5494
+ function readNodeValue(store, base, nodeId) {
5495
+ return store[nodeScopedKey(base, nodeId)];
5496
+ }
5497
+ /**
5498
+ * Re-map a UI/settings patch so every bare perNode field persists under the
5499
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
5500
+ * the write path so a save for one node never clobbers another node's value
5501
+ * (and the bare key is never written). Returns a new object — the input
5502
+ * patch is not mutated.
5503
+ */
5504
+ function scopePatch(patch, perNodeKeys, nodeId) {
5505
+ const out = {};
5506
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
5507
+ return out;
5508
+ }
5509
+ /**
5510
+ * Project the raw shared store onto the bare schema keys for ONE node so a
5511
+ * UI schema (whose field keys are bare) hydrates from that node's own
5512
+ * values:
5513
+ *
5514
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
5515
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
5516
+ * legacy key must never hydrate any node — no bare fallback).
5517
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
5518
+ * each bare perNode key; when the node has no scoped key the bare key is
5519
+ * left ABSENT so the field's schema `default` wins.
5520
+ *
5521
+ * Returns a new object — the input store is not mutated.
5522
+ */
5523
+ function projectStore(store, perNodeKeys, nodeId) {
5524
+ const out = {};
5525
+ for (const [key, value] of Object.entries(store)) {
5526
+ if (key.includes("@")) continue;
5527
+ if (perNodeKeys.has(key)) continue;
5528
+ out[key] = value;
5529
+ }
5530
+ for (const base of perNodeKeys) {
5531
+ const value = readNodeValue(store, base, nodeId);
5532
+ if (value !== void 0) out[base] = value;
5533
+ }
5534
+ return out;
5535
+ }
5536
+ /**
5443
5537
  * Base class for CamStack addons. Eliminates settings boilerplate:
5444
5538
  *
5445
5539
  * - Typed `config` property with automatic resolution from store + defaults
@@ -5607,23 +5701,63 @@ var BaseAddon = class {
5607
5701
  deviceSettingsSchema() {
5608
5702
  return null;
5609
5703
  }
5610
- async getGlobalSettings(overlay, cap, _nodeId) {
5704
+ async getGlobalSettings(overlay, cap, nodeId) {
5611
5705
  const schema = this.globalSettingsSchema(cap);
5612
5706
  if (!schema) return { sections: [] };
5613
- const raw = await this._ctx?.settings?.readAddonStore() ?? {};
5707
+ const projected = await this.resolveGlobalStore(nodeId, cap);
5614
5708
  return hydrateSchema(schema, overlay ? {
5615
- ...raw,
5709
+ ...projected,
5616
5710
  ...overlay
5617
- } : raw);
5711
+ } : projected);
5618
5712
  }
5619
- async updateGlobalSettings(patch, _nodeId) {
5620
- await this._ctx?.settings?.writeAddonStore(patch);
5713
+ /**
5714
+ * The raw addon store PROJECTED onto the target node's bare per-node keys:
5715
+ * every `perNode: true` field carries THAT node's scoped value on its bare
5716
+ * key (absent scoped key ⇒ key absent, so the schema `default` wins — no
5717
+ * bare fallback), all `@`-scoped and stray bare per-node keys are dropped.
5718
+ * A no-op passthrough when the schema declares no `perNode` field.
5719
+ *
5720
+ * This is the sanctioned way for a `getGlobalSettings` OVERRIDE that needs
5721
+ * the store for custom option logic (option narrowing, value snapping) to
5722
+ * read it per-node — never `ctx.settings.readAddonStore()` directly.
5723
+ * `nodeId` omitted ⇒ the local node (node-blind injection from ctx).
5724
+ */
5725
+ async resolveGlobalStore(nodeId, cap) {
5726
+ const raw = await this._ctx?.settings?.readAddonStore() ?? {};
5727
+ const keys = this.perNodeKeys(cap);
5728
+ const node = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
5729
+ return keys.size > 0 ? projectStore(raw, keys, node) : raw;
5730
+ }
5731
+ async updateGlobalSettings(patch, nodeId) {
5732
+ const keys = this.perNodeKeys();
5733
+ const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
5734
+ const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
5735
+ const barePatch = patch;
5736
+ const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
5737
+ await this._ctx?.settings?.writeAddonStore(scoped);
5738
+ if (target !== localNode) return;
5621
5739
  await this.resolveConfig();
5622
5740
  await this.onConfigChanged();
5623
5741
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
5624
5742
  this.maybeAutoRestart(patch, this.globalSettingsSchema());
5625
5743
  }
5626
5744
  /**
5745
+ * The set of field keys the global settings schema declares `perNode: true`
5746
+ * — derived once per `cap` argument and memoized (schemas are static
5747
+ * declarations). Empty set ⇒ every per-node code path is bypassed and the
5748
+ * settings API behaves exactly like the legacy node-agnostic one.
5749
+ */
5750
+ _perNodeKeysCache = /* @__PURE__ */ new Map();
5751
+ perNodeKeys(cap) {
5752
+ const cacheKey = cap ?? "";
5753
+ const cached = this._perNodeKeysCache.get(cacheKey);
5754
+ if (cached) return cached;
5755
+ const schema = this.globalSettingsSchema(cap);
5756
+ const keys = new Set(schema ? schema.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
5757
+ this._perNodeKeysCache.set(cacheKey, keys);
5758
+ return keys;
5759
+ }
5760
+ /**
5627
5761
  * If any field in `patch` is marked `requiresRestart` in `schema`,
5628
5762
  * schedule an addon restart for the next tick. Deferred via
5629
5763
  * `setImmediate` so the tRPC mutation that triggered the write has
@@ -5776,12 +5910,19 @@ var BaseAddon = class {
5776
5910
  * The merge is shallow: each key in `defaults` is checked against the store.
5777
5911
  * Only keys present in defaults are read — the store can contain extra keys
5778
5912
  * (e.g. from older versions) without polluting the typed config.
5913
+ *
5914
+ * Keys the global settings schema declares `perNode: true` resolve from
5915
+ * THIS node's scoped key (`<key>@<localNode>`) via `readNodeValue` — never
5916
+ * from the bare key — so a per-node field resolves to this node's own
5917
+ * selection at boot (absent scoped key ⇒ the constructor default wins).
5779
5918
  */
5780
5919
  async resolveConfig() {
5781
5920
  const stored = await this.readAddonStoreWithRetry();
5921
+ const perNode = this.perNodeKeys();
5922
+ const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
5782
5923
  const resolved = { ...this.defaults };
5783
5924
  for (const key of Object.keys(this.defaults)) {
5784
- const storedValue = stored[key];
5925
+ const storedValue = perNode.has(key) ? readNodeValue(stored, key, localNode) : stored[key];
5785
5926
  if (storedValue !== void 0 && storedValue !== null) {
5786
5927
  const defaultType = typeof this.defaults[key];
5787
5928
  if (typeof storedValue === defaultType) resolved[key] = storedValue;
@@ -5865,6 +6006,27 @@ var BaseAddon = class {
5865
6006
  }
5866
6007
  };
5867
6008
  /**
6009
+ * Collect the keys of every field marked `perNode: true`, recursing into
6010
+ * layout containers (`group` fields and `sub-tabs` tabs) the same way
6011
+ * `hydrateSchema` does. Valueless structural fields (separator/info/…)
6012
+ * don't declare `perNode` and are excluded by the `in` narrowing.
6013
+ */
6014
+ function collectPerNodeFieldKeys(fields) {
6015
+ const collected = [];
6016
+ for (const field of fields) {
6017
+ if (field.type === "group") {
6018
+ collected.push(...collectPerNodeFieldKeys(field.fields));
6019
+ continue;
6020
+ }
6021
+ if (field.type === "sub-tabs") {
6022
+ for (const tab of field.tabs) collected.push(...collectPerNodeFieldKeys(tab.fields));
6023
+ continue;
6024
+ }
6025
+ if ("perNode" in field && field.perNode === true) collected.push(field.key);
6026
+ }
6027
+ return collected;
6028
+ }
6029
+ /**
5868
6030
  * Normalize an `ICamstackAddon.initialize()` return value into the
5869
6031
  * `AddonInitResult` envelope. Arrays are wrapped into `{ providers }`;
5870
6032
  * envelopes pass through; void stays void.
@@ -6272,6 +6434,13 @@ var DeviceType = /* @__PURE__ */ function(DeviceType) {
6272
6434
  /** Single still-image entity (HA `image.*`). Read-only display of an
6273
6435
  * `entity_picture` signed URL the browser loads directly. `image` cap. */
6274
6436
  DeviceType["Image"] = "image";
6437
+ /** Smart pet feeder — cloud-connected food dispenser with a bowl food
6438
+ * level, battery, desiccant life, feeding state and manual-feed /
6439
+ * call-pet / maintenance actions. Installed with the `pet-feeder` cap;
6440
+ * dual-hopper models (D4S/D4SH) expose per-hopper portions. Sources:
6441
+ * native PetKit (`nodepetkit` `FeederDevice`), reusable by other feeder
6442
+ * integrations sharing the same food/desiccant/hopper surface. */
6443
+ DeviceType["PetFeeder"] = "pet-feeder";
6275
6444
  return DeviceType;
6276
6445
  }({});
6277
6446
  var DeviceFeature = /* @__PURE__ */ function(DeviceFeature) {
@@ -7420,6 +7589,601 @@ var _macroLookup = /* @__PURE__ */ new Map();
7420
7589
  for (const [k, v] of Object.entries(YAMNET_TO_MACRO.mapping)) _macroLookup.set(k.toLowerCase(), v);
7421
7590
  for (const [k, v] of Object.entries(APPLE_SA_TO_MACRO.mapping)) _macroLookup.set(k.toLowerCase(), v);
7422
7591
  /**
7592
+ * Error types for the safe expression engine. Two distinct classes so callers
7593
+ * can tell a compile-time (grammar) failure from a runtime (evaluation)
7594
+ * failure — both are non-fatal to the host: read paths degrade to "skip link".
7595
+ */
7596
+ /** Thrown by the tokenizer / parser. Carries a 0-based source `position` when
7597
+ * the failure is anchored to a character (author-facing inline feedback). */
7598
+ var ExpressionParseError = class extends Error {
7599
+ position;
7600
+ constructor(message, position) {
7601
+ super(message);
7602
+ this.name = "ExpressionParseError";
7603
+ this.position = position;
7604
+ }
7605
+ };
7606
+ /** Thrown by the evaluator (unknown identifier, type mismatch, non-finite
7607
+ * result, unknown builtin, step-budget exceeded). */
7608
+ var ExpressionEvalError = class extends Error {
7609
+ constructor(message) {
7610
+ super(message);
7611
+ this.name = "ExpressionEvalError";
7612
+ }
7613
+ };
7614
+ /**
7615
+ * Resource-bound constants for the safe expression engine.
7616
+ *
7617
+ * Every bound is defense-in-depth: the grammar is non-Turing-complete (no
7618
+ * loops, recursion, lambdas or member access — see `ast.ts`), so evaluation is
7619
+ * O(nodeCount) by construction. These caps merely put a hard ceiling on the
7620
+ * work a single author-supplied expression can request, so a hostile or
7621
+ * accidental pathological string can never spend unbounded CPU/memory.
7622
+ */
7623
+ /** Max source length (chars) — checked BEFORE tokenizing so a huge string is
7624
+ * rejected without allocation. */
7625
+ var MAX_EXPRESSION_SOURCE_LENGTH = 2048;
7626
+ /** A legal binding / identifier name. */
7627
+ var EXPRESSION_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
7628
+ /** Binding names an author may NOT use: `now` is auto-injected; the literal
7629
+ * keywords lex as values, not identifiers, so binding to them is meaningless. */
7630
+ var RESERVED_BINDING_NAMES = new Set([
7631
+ "now",
7632
+ "true",
7633
+ "false",
7634
+ "null"
7635
+ ]);
7636
+ /**
7637
+ * Tokenizer for the safe expression mini-language. Hand-rolled, single-pass,
7638
+ * zero-dependency. The grammar is deliberately boring: decimal numbers,
7639
+ * single/double-quoted strings with a tiny escape set, identifiers, the three
7640
+ * value keywords (`true`/`false`/`null`) and a fixed punctuator set. Anything
7641
+ * outside that — a bare `.`, `=`, `[`, `]`, `{`, `}`, `;`, backtick, `&`, `|` —
7642
+ * is a parse error with a source position, so member access / assignment /
7643
+ * template literals are lexically impossible.
7644
+ */
7645
+ var KEYWORDS = new Set([
7646
+ "true",
7647
+ "false",
7648
+ "null"
7649
+ ]);
7650
+ function isDigit(ch) {
7651
+ return ch >= "0" && ch <= "9";
7652
+ }
7653
+ function isIdentStart(ch) {
7654
+ return ch >= "A" && ch <= "Z" || ch >= "a" && ch <= "z" || ch === "_";
7655
+ }
7656
+ function isIdentPart(ch) {
7657
+ return isIdentStart(ch) || isDigit(ch);
7658
+ }
7659
+ function isWhitespace(ch) {
7660
+ return ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
7661
+ }
7662
+ /** Tokenize `source` into a flat token list ending with a single `eof` token.
7663
+ * Throws `ExpressionParseError` on any illegal character or unterminated
7664
+ * string. */
7665
+ function tokenize(source) {
7666
+ if (source.length > 2048) throw new ExpressionParseError(`expression too long (${source.length} > ${MAX_EXPRESSION_SOURCE_LENGTH} chars)`, 0);
7667
+ const tokens = [];
7668
+ let i = 0;
7669
+ const n = source.length;
7670
+ while (i < n) {
7671
+ const ch = source[i];
7672
+ if (isWhitespace(ch)) {
7673
+ i += 1;
7674
+ continue;
7675
+ }
7676
+ if (isDigit(ch)) {
7677
+ const start = i;
7678
+ while (i < n && isDigit(source[i])) i += 1;
7679
+ if (i < n && source[i] === ".") {
7680
+ if (i + 1 >= n || !isDigit(source[i + 1])) throw new ExpressionParseError("malformed number: decimal point needs a digit", i);
7681
+ i += 1;
7682
+ while (i < n && isDigit(source[i])) i += 1;
7683
+ }
7684
+ const text = source.slice(start, i);
7685
+ const value = Number(text);
7686
+ if (!Number.isFinite(value)) throw new ExpressionParseError(`malformed number: '${text}'`, start);
7687
+ tokens.push({
7688
+ type: "number",
7689
+ value,
7690
+ pos: start
7691
+ });
7692
+ continue;
7693
+ }
7694
+ if (ch === "'" || ch === "\"") {
7695
+ const quote = ch;
7696
+ const start = i;
7697
+ i += 1;
7698
+ let out = "";
7699
+ let closed = false;
7700
+ while (i < n) {
7701
+ const c = source[i];
7702
+ if (c === "\\") {
7703
+ const next = i + 1 < n ? source[i + 1] : "";
7704
+ if (next === "\\" || next === "'" || next === "\"") {
7705
+ out += next;
7706
+ i += 2;
7707
+ continue;
7708
+ }
7709
+ throw new ExpressionParseError(`invalid string escape: '\\${next}'`, i);
7710
+ }
7711
+ if (c === quote) {
7712
+ closed = true;
7713
+ i += 1;
7714
+ break;
7715
+ }
7716
+ out += c;
7717
+ i += 1;
7718
+ }
7719
+ if (!closed) throw new ExpressionParseError("unterminated string literal", start);
7720
+ tokens.push({
7721
+ type: "string",
7722
+ value: out,
7723
+ pos: start
7724
+ });
7725
+ continue;
7726
+ }
7727
+ if (isIdentStart(ch)) {
7728
+ const start = i;
7729
+ while (i < n && isIdentPart(source[i])) i += 1;
7730
+ const text = source.slice(start, i);
7731
+ if (KEYWORDS.has(text)) tokens.push({
7732
+ type: "keyword",
7733
+ keyword: keywordOf(text),
7734
+ pos: start
7735
+ });
7736
+ else tokens.push({
7737
+ type: "identifier",
7738
+ name: text,
7739
+ pos: start
7740
+ });
7741
+ continue;
7742
+ }
7743
+ const two = i + 1 < n ? source.slice(i, i + 2) : "";
7744
+ if (two === "<=" || two === ">=" || two === "==" || two === "!=" || two === "&&" || two === "||") {
7745
+ tokens.push({
7746
+ type: "punct",
7747
+ punct: two,
7748
+ pos: i
7749
+ });
7750
+ i += 2;
7751
+ continue;
7752
+ }
7753
+ if (isSinglePunct(ch)) {
7754
+ tokens.push({
7755
+ type: "punct",
7756
+ punct: ch,
7757
+ pos: i
7758
+ });
7759
+ i += 1;
7760
+ continue;
7761
+ }
7762
+ throw new ExpressionParseError(`unexpected character '${ch}'`, i);
7763
+ }
7764
+ tokens.push({
7765
+ type: "eof",
7766
+ pos: n
7767
+ });
7768
+ return tokens;
7769
+ }
7770
+ function keywordOf(text) {
7771
+ if (text === "true") return "true";
7772
+ if (text === "false") return "false";
7773
+ return "null";
7774
+ }
7775
+ function isSinglePunct(ch) {
7776
+ return ch === "(" || ch === ")" || ch === "," || ch === "?" || ch === ":" || ch === "+" || ch === "-" || ch === "*" || ch === "/" || ch === "%" || ch === "!" || ch === "<" || ch === ">";
7777
+ }
7778
+ /**
7779
+ * Frozen, null-prototype builtin function table for the expression engine
7780
+ * (spec §4 rule 4). The table is the SOLE surface of callable functions: the
7781
+ * parser rejects any callee not in it, and the evaluator gates each call on an
7782
+ * own-property check against it.
7783
+ *
7784
+ * Because the object has a NULL prototype AND is `Object.freeze`d:
7785
+ * - it cannot be polluted (no `__proto__` / `constructor` write reaches it);
7786
+ * - a lookup for `toString` / `hasOwnProperty` / `constructor` finds NOTHING
7787
+ * (there is no `Object.prototype` in the chain), so those names are not
7788
+ * callable — they are simply "unknown function" at parse time.
7789
+ *
7790
+ * Every numeric argument is validated as a finite number and every numeric
7791
+ * RESULT is re-checked finite, so `/0`, `sqrt(-1)` (→ NaN) and overflow
7792
+ * (`pow(10,400)` → Infinity) all raise `ExpressionEvalError` and fail the link
7793
+ * closed rather than emitting a garbage value.
7794
+ */
7795
+ function asFiniteNumber(value, name, index) {
7796
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a finite number`);
7797
+ return value;
7798
+ }
7799
+ function asString$1(value, name, index) {
7800
+ if (typeof value !== "string") throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a string`);
7801
+ return value;
7802
+ }
7803
+ function finiteResult(value, name) {
7804
+ if (!Number.isFinite(value)) throw new ExpressionEvalError(`${name}: produced a non-finite result`);
7805
+ return value;
7806
+ }
7807
+ function allFiniteNumbers(args, name) {
7808
+ return args.map((a, idx) => asFiniteNumber(a, name, idx));
7809
+ }
7810
+ var INF = Number.POSITIVE_INFINITY;
7811
+ var table = {
7812
+ min: {
7813
+ minArgs: 1,
7814
+ maxArgs: INF,
7815
+ apply: (args) => finiteResult(Math.min(...allFiniteNumbers(args, "min")), "min")
7816
+ },
7817
+ max: {
7818
+ minArgs: 1,
7819
+ maxArgs: INF,
7820
+ apply: (args) => finiteResult(Math.max(...allFiniteNumbers(args, "max")), "max")
7821
+ },
7822
+ abs: {
7823
+ minArgs: 1,
7824
+ maxArgs: 1,
7825
+ apply: (args) => finiteResult(Math.abs(asFiniteNumber(args[0], "abs", 0)), "abs")
7826
+ },
7827
+ floor: {
7828
+ minArgs: 1,
7829
+ maxArgs: 1,
7830
+ apply: (args) => finiteResult(Math.floor(asFiniteNumber(args[0], "floor", 0)), "floor")
7831
+ },
7832
+ ceil: {
7833
+ minArgs: 1,
7834
+ maxArgs: 1,
7835
+ apply: (args) => finiteResult(Math.ceil(asFiniteNumber(args[0], "ceil", 0)), "ceil")
7836
+ },
7837
+ sqrt: {
7838
+ minArgs: 1,
7839
+ maxArgs: 1,
7840
+ apply: (args) => finiteResult(Math.sqrt(asFiniteNumber(args[0], "sqrt", 0)), "sqrt")
7841
+ },
7842
+ round: {
7843
+ minArgs: 1,
7844
+ maxArgs: 2,
7845
+ apply: (args) => {
7846
+ const x = asFiniteNumber(args[0], "round", 0);
7847
+ const digits = args.length > 1 ? Math.trunc(asFiniteNumber(args[1], "round", 1)) : 0;
7848
+ if (digits < 0 || digits > 100) throw new ExpressionEvalError("round: digits must be between 0 and 100");
7849
+ const factor = 10 ** digits;
7850
+ return finiteResult(Math.round(x * factor) / factor, "round");
7851
+ }
7852
+ },
7853
+ pow: {
7854
+ minArgs: 2,
7855
+ maxArgs: 2,
7856
+ apply: (args) => finiteResult(asFiniteNumber(args[0], "pow", 0) ** asFiniteNumber(args[1], "pow", 1), "pow")
7857
+ },
7858
+ clamp: {
7859
+ minArgs: 3,
7860
+ maxArgs: 3,
7861
+ apply: (args) => {
7862
+ const x = asFiniteNumber(args[0], "clamp", 0);
7863
+ const lo = asFiniteNumber(args[1], "clamp", 1);
7864
+ const hi = asFiniteNumber(args[2], "clamp", 2);
7865
+ if (lo > hi) throw new ExpressionEvalError("clamp: lower bound is greater than upper bound");
7866
+ return finiteResult(Math.min(hi, Math.max(lo, x)), "clamp");
7867
+ }
7868
+ },
7869
+ avg: {
7870
+ minArgs: 1,
7871
+ maxArgs: INF,
7872
+ apply: (args) => {
7873
+ const nums = allFiniteNumbers(args, "avg");
7874
+ return finiteResult(nums.reduce((acc, v) => acc + v, 0) / nums.length, "avg");
7875
+ }
7876
+ },
7877
+ sum: {
7878
+ minArgs: 1,
7879
+ maxArgs: INF,
7880
+ apply: (args) => finiteResult(allFiniteNumbers(args, "sum").reduce((acc, v) => acc + v, 0), "sum")
7881
+ },
7882
+ coalesce: {
7883
+ minArgs: 1,
7884
+ maxArgs: INF,
7885
+ apply: (args) => {
7886
+ for (const a of args) if (a !== null) return a;
7887
+ return null;
7888
+ }
7889
+ },
7890
+ age: {
7891
+ minArgs: 2,
7892
+ maxArgs: 2,
7893
+ apply: (args) => finiteResult(asFiniteNumber(args[0], "age", 0) - asFiniteNumber(args[1], "age", 1), "age")
7894
+ },
7895
+ convert: {
7896
+ minArgs: 3,
7897
+ maxArgs: 3,
7898
+ apply: (args, hooks) => {
7899
+ const x = asFiniteNumber(args[0], "convert", 0);
7900
+ const from = asString$1(args[1], "convert", 1).trim();
7901
+ const to = asString$1(args[2], "convert", 2).trim();
7902
+ if (hooks.convert) {
7903
+ const out = hooks.convert(x, from, to);
7904
+ if (out === null) throw new ExpressionEvalError(`convert: cannot convert '${from}' to '${to}'`);
7905
+ return finiteResult(out, "convert");
7906
+ }
7907
+ if (from === to) return x;
7908
+ throw new ExpressionEvalError("convert: unit conversion table not installed");
7909
+ }
7910
+ }
7911
+ };
7912
+ Object.freeze(Object.assign(Object.create(null), table));
7913
+ /** The set of valid builtin names — used by the parser to reject unknown
7914
+ * callees at parse time (immediate author feedback). */
7915
+ var EXPRESSION_BUILTIN_NAMES = new Set(Object.keys(table));
7916
+ /**
7917
+ * Pratt (precedence-climbing) parser for the safe expression mini-language.
7918
+ *
7919
+ * Precedence (low → high): ternary `?:` (right-assoc) → `||` → `&&` → equality
7920
+ * → relational → additive → multiplicative → unary `! -` → call / primary.
7921
+ * Calls are ONLY `IDENT '(' args? ')'` at primary position — the callee is a
7922
+ * string validated against the builtin table at parse time, so an unknown
7923
+ * function is rejected immediately (author feedback) and a persisted expression
7924
+ * that references a since-removed builtin degrades at read.
7925
+ *
7926
+ * A node counter caps total AST size (`MAX_EXPRESSION_AST_NODES`) and call
7927
+ * arity is capped (`MAX_EXPRESSION_CALL_ARGS`) — both raise `ExpressionParseError`.
7928
+ */
7929
+ /** Binary/logical operator precedence (higher binds tighter). */
7930
+ var BINARY_PRECEDENCE = {
7931
+ "||": 1,
7932
+ "&&": 2,
7933
+ "==": 3,
7934
+ "!=": 3,
7935
+ "<": 4,
7936
+ "<=": 4,
7937
+ ">": 4,
7938
+ ">=": 4,
7939
+ "+": 5,
7940
+ "-": 5,
7941
+ "*": 6,
7942
+ "/": 6,
7943
+ "%": 6
7944
+ };
7945
+ function isLogicalOp(op) {
7946
+ return op === "&&" || op === "||";
7947
+ }
7948
+ function isBinaryOp(op) {
7949
+ return op === "+" || op === "-" || op === "*" || op === "/" || op === "%" || op === "==" || op === "!=" || op === "<" || op === "<=" || op === ">" || op === ">=";
7950
+ }
7951
+ var Parser = class {
7952
+ tokens;
7953
+ pos = 0;
7954
+ nodeCount = 0;
7955
+ identifiers = /* @__PURE__ */ new Set();
7956
+ callees = /* @__PURE__ */ new Set();
7957
+ constructor(tokens) {
7958
+ this.tokens = tokens;
7959
+ }
7960
+ parse() {
7961
+ const ast = this.parseTernary();
7962
+ const tok = this.peek();
7963
+ if (tok.type !== "eof") throw new ExpressionParseError("unexpected trailing input", tok.pos);
7964
+ return {
7965
+ ast,
7966
+ identifiers: this.identifiers,
7967
+ callees: this.callees,
7968
+ nodeCount: this.nodeCount
7969
+ };
7970
+ }
7971
+ peek() {
7972
+ return this.tokens[this.pos];
7973
+ }
7974
+ next() {
7975
+ return this.tokens[this.pos++];
7976
+ }
7977
+ /** Consume a punctuator token, erroring if the next token isn't it. */
7978
+ expectPunct(punct) {
7979
+ const tok = this.peek();
7980
+ if (tok.type !== "punct" || tok.punct !== punct) throw new ExpressionParseError(`expected '${punct}'`, tok.pos);
7981
+ this.pos += 1;
7982
+ }
7983
+ matchPunct(punct) {
7984
+ const tok = this.peek();
7985
+ if (tok.type === "punct" && tok.punct === punct) {
7986
+ this.pos += 1;
7987
+ return true;
7988
+ }
7989
+ return false;
7990
+ }
7991
+ countNode() {
7992
+ this.nodeCount += 1;
7993
+ if (this.nodeCount > 256) throw new ExpressionParseError("expression too complex", this.peek().pos);
7994
+ }
7995
+ parseTernary() {
7996
+ const test = this.parseBinary(1);
7997
+ if (this.matchPunct("?")) {
7998
+ const consequent = this.parseTernary();
7999
+ this.expectPunct(":");
8000
+ const alternate = this.parseTernary();
8001
+ this.countNode();
8002
+ return {
8003
+ kind: "conditional",
8004
+ test,
8005
+ consequent,
8006
+ alternate
8007
+ };
8008
+ }
8009
+ return test;
8010
+ }
8011
+ parseBinary(minPrec) {
8012
+ let left = this.parseUnary();
8013
+ for (;;) {
8014
+ const tok = this.peek();
8015
+ if (tok.type !== "punct") break;
8016
+ const prec = BINARY_PRECEDENCE[tok.punct];
8017
+ if (prec === void 0 || prec < minPrec) break;
8018
+ const op = tok.punct;
8019
+ this.pos += 1;
8020
+ const right = this.parseBinary(prec + 1);
8021
+ this.countNode();
8022
+ if (isLogicalOp(op)) left = {
8023
+ kind: "logical",
8024
+ op,
8025
+ left,
8026
+ right
8027
+ };
8028
+ else if (isBinaryOp(op)) left = {
8029
+ kind: "binary",
8030
+ op,
8031
+ left,
8032
+ right
8033
+ };
8034
+ else throw new ExpressionParseError(`unexpected operator '${op}'`, tok.pos);
8035
+ }
8036
+ return left;
8037
+ }
8038
+ parseUnary() {
8039
+ const tok = this.peek();
8040
+ if (tok.type === "punct" && (tok.punct === "!" || tok.punct === "-")) {
8041
+ const op = tok.punct;
8042
+ this.pos += 1;
8043
+ const operand = this.parseUnary();
8044
+ this.countNode();
8045
+ return {
8046
+ kind: "unary",
8047
+ op,
8048
+ operand
8049
+ };
8050
+ }
8051
+ return this.parsePrimary();
8052
+ }
8053
+ parsePrimary() {
8054
+ const tok = this.next();
8055
+ switch (tok.type) {
8056
+ case "number":
8057
+ this.countNode();
8058
+ return {
8059
+ kind: "literal",
8060
+ value: tok.value
8061
+ };
8062
+ case "string":
8063
+ this.countNode();
8064
+ return {
8065
+ kind: "literal",
8066
+ value: tok.value
8067
+ };
8068
+ case "keyword":
8069
+ this.countNode();
8070
+ return {
8071
+ kind: "literal",
8072
+ value: tok.keyword === "null" ? null : tok.keyword === "true"
8073
+ };
8074
+ case "identifier": {
8075
+ const nextTok = this.peek();
8076
+ if (nextTok.type === "punct" && nextTok.punct === "(") return this.parseCall(tok.name, tok.pos);
8077
+ this.identifiers.add(tok.name);
8078
+ this.countNode();
8079
+ return {
8080
+ kind: "identifier",
8081
+ name: tok.name
8082
+ };
8083
+ }
8084
+ case "punct":
8085
+ if (tok.punct === "(") {
8086
+ const inner = this.parseTernary();
8087
+ this.expectPunct(")");
8088
+ return inner;
8089
+ }
8090
+ throw new ExpressionParseError(`unexpected token '${tok.punct}'`, tok.pos);
8091
+ case "eof": throw new ExpressionParseError("unexpected end of expression", tok.pos);
8092
+ }
8093
+ }
8094
+ parseCall(callee, pos) {
8095
+ if (!EXPRESSION_BUILTIN_NAMES.has(callee)) throw new ExpressionParseError(`unknown function '${callee}'`, pos);
8096
+ this.expectPunct("(");
8097
+ const args = [];
8098
+ if (!this.matchPunct(")")) for (;;) {
8099
+ args.push(this.parseTernary());
8100
+ if (args.length > 16) throw new ExpressionParseError(`too many arguments to '${callee}'`, pos);
8101
+ if (this.matchPunct(",")) continue;
8102
+ this.expectPunct(")");
8103
+ break;
8104
+ }
8105
+ this.callees.add(callee);
8106
+ this.countNode();
8107
+ return {
8108
+ kind: "call",
8109
+ callee,
8110
+ args
8111
+ };
8112
+ }
8113
+ };
8114
+ /** Tokenize + parse `source` into a validated `ParsedExpression`. Throws
8115
+ * `ExpressionParseError` on any lexical or grammatical failure. */
8116
+ function parseExpression(source) {
8117
+ return new Parser(tokenize(source)).parse();
8118
+ }
8119
+ Object.freeze({});
8120
+ /**
8121
+ * LRU compile cache for parsed expressions (spec §2.4 "parse once … LRU keyed
8122
+ * by expr"). The cache stores BOTH successes and failures (negative caching),
8123
+ * so a corrupt persisted string costs exactly one tokenize+parse total — not
8124
+ * one per read on a hot resolve path.
8125
+ *
8126
+ * The cache is a module-level singleton: entries are pure, content-addressed
8127
+ * ASTs keyed by the raw source string, so sharing one instance across all
8128
+ * callers is safe and maximises hit rate.
8129
+ */
8130
+ var cache = /* @__PURE__ */ new Map();
8131
+ function getCached(source) {
8132
+ const hit = cache.get(source);
8133
+ if (hit !== void 0) {
8134
+ cache.delete(source);
8135
+ cache.set(source, hit);
8136
+ return hit;
8137
+ }
8138
+ let result;
8139
+ try {
8140
+ result = {
8141
+ ok: true,
8142
+ parsed: parseExpression(source)
8143
+ };
8144
+ } catch (err) {
8145
+ result = {
8146
+ ok: false,
8147
+ error: err instanceof ExpressionParseError ? err.message : String(err)
8148
+ };
8149
+ }
8150
+ cache.set(source, result);
8151
+ if (cache.size > 256) {
8152
+ const oldest = cache.keys().next().value;
8153
+ if (oldest !== void 0) cache.delete(oldest);
8154
+ }
8155
+ return result;
8156
+ }
8157
+ /** Compile `source`, returning a discriminated result instead of throwing.
8158
+ * Used by read paths that must degrade rather than raise. LRU/negative-cached. */
8159
+ function compileExpressionSafe(source) {
8160
+ return getCached(source);
8161
+ }
8162
+ /**
8163
+ * Author-time validation. Returns `null` when the source is valid, else a
8164
+ * human-readable error message. Checks: the expression compiles; binding count
8165
+ * is within `MAX_EXPRESSION_BINDINGS`; every binding name is a legal identifier,
8166
+ * is not reserved (`now`/keywords) and does not shadow a builtin; and every
8167
+ * FREE identifier of the AST is covered by a binding or the injected `now`.
8168
+ */
8169
+ function validateExpressionSource(src) {
8170
+ const names = Object.keys(src.bindings);
8171
+ if (names.length > 32) return `too many bindings (${names.length} > 32)`;
8172
+ for (const name of names) {
8173
+ if (!EXPRESSION_IDENTIFIER_RE.test(name)) return `invalid binding name '${name}'`;
8174
+ if (RESERVED_BINDING_NAMES.has(name)) return `binding name '${name}' is reserved`;
8175
+ if (EXPRESSION_BUILTIN_NAMES.has(name)) return `binding name '${name}' shadows a builtin function`;
8176
+ }
8177
+ const compiled = compileExpressionSafe(src.expr);
8178
+ if (!compiled.ok) return compiled.error;
8179
+ const bound = new Set(names);
8180
+ for (const id of compiled.parsed.identifiers) {
8181
+ if (id === "now") continue;
8182
+ if (!bound.has(id)) return `expression references unbound identifier '${id}'`;
8183
+ }
8184
+ return null;
8185
+ }
8186
+ /**
7423
8187
  * Accessory device helpers — shared across drivers.
7424
8188
  *
7425
8189
  * Many vendor-specific drivers register accessory child devices on
@@ -9322,7 +10086,8 @@ var MotionAnalysisResultSchema = object({
9322
10086
  });
9323
10087
  method(object({
9324
10088
  deviceId: number(),
9325
- frame: FrameInputSchema
10089
+ frame: FrameInputSchema.optional(),
10090
+ frameHandle: FrameHandleSchema.optional()
9326
10091
  }), MotionAnalysisResultSchema, { kind: "mutation" }), method(object({ deviceId: number() }), _void(), { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), object({
9327
10092
  deviceId: number(),
9328
10093
  detected: boolean(),
@@ -9569,6 +10334,12 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
9569
10334
  engine: PipelineEngineChoiceSchema.optional(),
9570
10335
  steps: array(PipelineStepInputSchema).min(1),
9571
10336
  frame: FrameInputSchema.optional(),
10337
+ /**
10338
+ * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
10339
+ * the decoded pixels live in. One more member of the one-of
10340
+ * frame/frameHandle/image/imageBase64/referenceImage group.
10341
+ */
10342
+ frameHandle: FrameHandleSchema.optional(),
9572
10343
  imageBase64: string().optional(),
9573
10344
  /**
9574
10345
  * Binary JPEG bytes — preferred over `imageBase64` on internal
@@ -9778,6 +10549,31 @@ var ReportMotionInputSchema = object({
9778
10549
  regions: array(MotionRegionSchema).readonly().optional()
9779
10550
  });
9780
10551
  /**
10552
+ * Where a runner gets a camera's decoded frames (cross-node Phase 2,
10553
+ * restream-owner model — P2c).
10554
+ *
10555
+ * - `local-broker` (DEFAULT): today's path — subscribe to the co-located
10556
+ * stream-broker's shm frame plane. Every pre-P2c attach payload (no
10557
+ * `frameSource` key) parses to this, so the field is additive with zero
10558
+ * behavior change.
10559
+ * - `remote-restream`: the detect node is NOT the camera's source-owner.
10560
+ * The runner acquires the owner's COMPRESSED passthrough restream
10561
+ * (`streamBroker.getStreamWithCodec({video:'copy'})` — refcounted, the
10562
+ * double-pull guard) and decodes LOCALLY via a satellite frame plane +
10563
+ * pull-mode decoder session pinned to its own node. The shm ring stays
10564
+ * node-local; only H.264/H.265 packets cross the wire.
10565
+ * `hubHostnameOverride` mirrors the recorder's `recordingHubHostname`:
10566
+ * when set it overrides the `CAMSTACK_HUB_URL`-derived host the runner
10567
+ * dials for the owner's restream.
10568
+ */
10569
+ var RunnerFrameSourceSchema = discriminatedUnion("kind", [object({ kind: literal("local-broker") }), object({
10570
+ kind: literal("remote-restream"),
10571
+ /** The camera's source-owner node (slice 1: always the hub). */
10572
+ ownerNodeId: string(),
10573
+ /** Operator override for the owner host the runner dials. */
10574
+ hubHostnameOverride: string().optional()
10575
+ })]).describe("Per-camera frame-source mode for the runner (P2c)");
10576
+ /**
9781
10577
  * Camera assignment payload sent by `addon-pipeline-orchestrator` to a
9782
10578
  * specific runner instance via `attachCamera`. Carries everything the
9783
10579
  * runner needs to subscribe to the local broker and execute inference.
@@ -9875,7 +10671,15 @@ var RunnerCameraConfigSchema = object({
9875
10671
  */
9876
10672
  onboardMotionDrivesAnalyzer: boolean().default(true),
9877
10673
  occupancyRecheckSec: number().min(occupancyRecheckSecField.min).max(occupancyRecheckSecField.max).default(occupancyRecheckSecField.default),
9878
- occupancyRecheckFrames: number().min(occupancyRecheckFramesField.min).max(occupancyRecheckFramesField.max).default(occupancyRecheckFramesField.default)
10674
+ occupancyRecheckFrames: number().min(occupancyRecheckFramesField.min).max(occupancyRecheckFramesField.max).default(occupancyRecheckFramesField.default),
10675
+ /**
10676
+ * Where this runner gets the camera's decoded frames (P2c). Defaulted so
10677
+ * every existing payload behaves as `local-broker` — the pre-Phase-2 path.
10678
+ * Populated with `remote-restream` by the orchestrator ONLY when the
10679
+ * camera's detect node differs from its source-owner (P2d, gated by the
10680
+ * `remoteSourcingNodes` rollout setting).
10681
+ */
10682
+ frameSource: RunnerFrameSourceSchema.default({ kind: "local-broker" })
9879
10683
  });
9880
10684
  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;
9881
10685
  /**
@@ -10240,6 +11044,113 @@ object({
10240
11044
  lastFetchedAt: number()
10241
11045
  });
10242
11046
  DeviceType.Sensor;
11047
+ /**
11048
+ * Feeder connectivity / power status — mirrors the HA petkit device-status
11049
+ * enum: `normal` (online, mains), `offline` (not reaching PetKit cloud),
11050
+ * `on_batteries` (running on battery backup). `null` until first reported.
11051
+ */
11052
+ var PetFeederDeviceStatusSchema = _enum([
11053
+ "normal",
11054
+ "offline",
11055
+ "on_batteries"
11056
+ ]);
11057
+ var gramsPortion = number().int().min(4).max(200);
11058
+ object({
11059
+ /** Food currently in the bowl (grams). Null when the device has not
11060
+ * reported a reading yet. On dual-hopper models this is the combined
11061
+ * bowl reading; per-hopper levels live in `food1`/`food2`. */
11062
+ foodLevel: number().nullable(),
11063
+ /** Hopper-1 food level (grams) on dual-hopper feeders; null on
11064
+ * single-hopper models. */
11065
+ food1: number().nullable(),
11066
+ /** Hopper-2 food level (grams) on dual-hopper feeders; null on
11067
+ * single-hopper models. */
11068
+ food2: number().nullable(),
11069
+ /** Derived low-food flag — mirrors the HA `food_level` binary_sensor
11070
+ * (`device_class: problem`, on = low). True when the bowl is empty /
11071
+ * below the feeder's low threshold. */
11072
+ lowFood: boolean(),
11073
+ /** Battery charge 0..100 (%). Null on mains-powered models or when the
11074
+ * device has no battery reading. */
11075
+ batteryPower: number().min(0).max(100).nullable(),
11076
+ /** Days of desiccant life remaining. Null when the model has no
11077
+ * desiccant sensor. */
11078
+ desiccantLeftDays: number().nullable(),
11079
+ /** True while a feed is in progress. */
11080
+ feeding: boolean(),
11081
+ /** Decoded connectivity / power status (HA petkit device-status enum).
11082
+ * Null until the device has reported a status. */
11083
+ status: PetFeederDeviceStatusSchema.nullable(),
11084
+ /** Decoded human-readable fault message. Null (or the device's `no_error`
11085
+ * sentinel) means healthy; a non-null string is an active fault. Pairs
11086
+ * with `errorCode` for consumers that want the raw integer. */
11087
+ error: string().nullable(),
11088
+ /** Raw device error code (0 / null = no error). */
11089
+ errorCode: number().nullable(),
11090
+ /** True for D4S/D4SH dual-hopper hardware — gates the per-hopper UI. */
11091
+ isDualHopper: boolean(),
11092
+ /** Child-lock (manual-lock) setting — buttons on the unit are disabled. */
11093
+ childLock: boolean(),
11094
+ /** Front indicator-light setting. */
11095
+ indicatorLight: boolean(),
11096
+ /** Play a chime when dispensing. */
11097
+ feedSound: boolean(),
11098
+ /** Speaker / prompt volume level (device-scaled integer). */
11099
+ volume: number(),
11100
+ /** Ms epoch when the slice was last refreshed from the cloud. */
11101
+ lastFetchedAt: number()
11102
+ });
11103
+ DeviceType.PetFeeder, method(object({
11104
+ deviceId: number().int().nonnegative(),
11105
+ grams: gramsPortion.optional(),
11106
+ hopper1: gramsPortion.optional(),
11107
+ hopper2: gramsPortion.optional()
11108
+ }), _void(), {
11109
+ kind: "mutation",
11110
+ auth: "admin"
11111
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
11112
+ kind: "mutation",
11113
+ auth: "admin"
11114
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
11115
+ kind: "mutation",
11116
+ auth: "admin"
11117
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
11118
+ kind: "mutation",
11119
+ auth: "admin"
11120
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
11121
+ kind: "mutation",
11122
+ auth: "admin"
11123
+ }), method(object({
11124
+ deviceId: number().int().nonnegative(),
11125
+ soundId: number().int().nonnegative()
11126
+ }), _void(), {
11127
+ kind: "mutation",
11128
+ auth: "admin"
11129
+ }), method(object({
11130
+ deviceId: number().int().nonnegative(),
11131
+ on: boolean()
11132
+ }), _void(), {
11133
+ kind: "mutation",
11134
+ auth: "admin"
11135
+ }), method(object({
11136
+ deviceId: number().int().nonnegative(),
11137
+ on: boolean()
11138
+ }), _void(), {
11139
+ kind: "mutation",
11140
+ auth: "admin"
11141
+ }), method(object({
11142
+ deviceId: number().int().nonnegative(),
11143
+ on: boolean()
11144
+ }), _void(), {
11145
+ kind: "mutation",
11146
+ auth: "admin"
11147
+ }), method(object({
11148
+ deviceId: number().int().nonnegative(),
11149
+ level: number().int().nonnegative()
11150
+ }), _void(), {
11151
+ kind: "mutation",
11152
+ auth: "admin"
11153
+ });
10243
11154
  object({
10244
11155
  /** Instantaneous power draw in watts. */
10245
11156
  watts: number().optional(),
@@ -12088,10 +12999,12 @@ method(object({ codec: string() }), boolean()), method(_void(), object({
12088
12999
  url: string()
12089
13000
  }), _void()), method(object({
12090
13001
  sessionId: string(),
12091
- maxCount: number().default(1)
13002
+ maxCount: number().default(1),
13003
+ waitMs: number().optional()
12092
13004
  }), array(DecodedFrameSchema)), method(object({
12093
13005
  sessionId: string(),
12094
- maxCount: number().default(1)
13006
+ maxCount: number().default(1),
13007
+ waitMs: number().optional()
12095
13008
  }), array(FrameHandleSchema)), method(object({ handle: FrameHandleSchema }), DecodedFrameSchema.nullable()), method(object({ sessionId: string() }), ShmRingStatsSchema.nullable()), method(object({
12096
13009
  sessionId: string(),
12097
13010
  config: DecoderSessionConfigSchema.partial()
@@ -12378,14 +13291,63 @@ var ChildLayoutEntrySchema = object({
12378
13291
  collapsed: boolean().optional()
12379
13292
  });
12380
13293
  /** Cap-wire shape of a DeviceLink — structurally mirrors `DeviceLink` in
12381
- * `device-management.ts`. */
13294
+ * `device-management.ts`. Source is a union: a FIELD source copies a sibling
13295
+ * accessory's status field (`kind` optional/absent for wire compat); a
13296
+ * LITERAL source carries a per-device constant (no sibling is read); a
13297
+ * GLOBAL source (P2e) copies ANY device's status field, addressed by the
13298
+ * source device's full re-sync-stable `stableId`. */
13299
+ var DeviceLinkFieldSourceSchema = object({
13300
+ kind: literal("field").optional(),
13301
+ sourceKey: string(),
13302
+ cap: string(),
13303
+ fieldPath: string()
13304
+ });
13305
+ var DeviceLinkLiteralSourceSchema = object({
13306
+ kind: literal("literal"),
13307
+ value: union([
13308
+ string(),
13309
+ number(),
13310
+ boolean(),
13311
+ _null()
13312
+ ])
13313
+ });
13314
+ var DeviceLinkGlobalSourceSchema = object({
13315
+ kind: literal("global"),
13316
+ sourceStableId: string(),
13317
+ cap: string(),
13318
+ fieldPath: string()
13319
+ });
13320
+ /** Expression source (Stage X): compute the target field from N named bindings
13321
+ * via the safe expression engine. Bindings are field | literal | global — never
13322
+ * another expression (no nesting). The `superRefine` runs the SAME author-time
13323
+ * validation as `validateExpressionSource` (compiles the expr, checks binding
13324
+ * names + identifier coverage) so every wire boundary that parses a DeviceLink
13325
+ * (tRPC mount, kernel create pre-seed, projection output) validates-at-write.
13326
+ * Compiles are LRU-cached, so repeated validation of the same expr is a hit. */
13327
+ var DeviceLinkExpressionSourceSchema = object({
13328
+ kind: literal("expression"),
13329
+ expr: string().min(1).max(MAX_EXPRESSION_SOURCE_LENGTH),
13330
+ bindings: record(string().regex(EXPRESSION_IDENTIFIER_RE), union([
13331
+ DeviceLinkFieldSourceSchema,
13332
+ DeviceLinkLiteralSourceSchema,
13333
+ DeviceLinkGlobalSourceSchema
13334
+ ]))
13335
+ }).superRefine((src, ctx) => {
13336
+ const err = validateExpressionSource(src);
13337
+ if (err !== null) ctx.addIssue({
13338
+ code: "custom",
13339
+ message: err,
13340
+ path: ["expr"]
13341
+ });
13342
+ });
12382
13343
  var DeviceLinkSchema = object({
12383
13344
  id: string(),
12384
- source: object({
12385
- sourceKey: string(),
12386
- cap: string(),
12387
- fieldPath: string()
12388
- }),
13345
+ source: union([
13346
+ DeviceLinkFieldSourceSchema,
13347
+ DeviceLinkLiteralSourceSchema,
13348
+ DeviceLinkGlobalSourceSchema,
13349
+ DeviceLinkExpressionSourceSchema
13350
+ ]),
12389
13351
  target: object({
12390
13352
  cap: string(),
12391
13353
  fieldPath: string(),
@@ -12414,6 +13376,31 @@ var DeviceLinkSchema = object({
12414
13376
  })
12415
13377
  ]).optional()
12416
13378
  });
13379
+ /** Cap-wire shape of a per-cap display refinement — mirrors
13380
+ * `DeviceCapDisplayOverride` in `device-management.ts`. */
13381
+ var DeviceCapDisplayOverrideSchema = object({
13382
+ unit: string().min(1).optional(),
13383
+ precision: number().int().min(0).max(10).optional()
13384
+ });
13385
+ /** Cap-wire shape of an operator-authored per-device display override —
13386
+ * mirrors `DeviceDisplayOverride` in `device-management.ts`. `precision`
13387
+ * bounds mirror `numeric-sensor.cap.ts` (`int 0-10`). */
13388
+ var DeviceDisplayOverrideSchema = object({
13389
+ icon: string().min(1).optional(),
13390
+ label: string().min(1).optional(),
13391
+ unit: string().min(1).optional(),
13392
+ precision: number().int().min(0).max(10).optional(),
13393
+ hidden: boolean().optional(),
13394
+ perCap: record(string(), DeviceCapDisplayOverrideSchema).optional()
13395
+ });
13396
+ /** Cap-wire shape of a per-role display default — mirrors `RoleDisplayDefault`
13397
+ * in `device-management.ts`. Keyed by `DeviceRole` string (role strings cross
13398
+ * the wire as plain strings everywhere else — cf. `DeviceInfoSchema.role`). */
13399
+ var RoleDisplayDefaultSchema = object({
13400
+ unit: string().min(1).optional(),
13401
+ precision: number().int().min(0).max(10).optional(),
13402
+ icon: string().min(1).optional()
13403
+ });
12417
13404
  /**
12418
13405
  * Serializable projection of a live IDevice.
12419
13406
  * Returned by listAll, getDevice, getChildren.
@@ -12469,7 +13456,9 @@ var DeviceInfoSchema = object({
12469
13456
  * `DeviceMeta.childLayout`. Absent ⇒ no layout declared. */
12470
13457
  childLayout: array(ChildLayoutEntrySchema).readonly().optional(),
12471
13458
  /** Operator-authored cross-device field wirings. See `DeviceMeta.deviceLinks`. */
12472
- deviceLinks: array(DeviceLinkSchema).readonly().optional()
13459
+ deviceLinks: array(DeviceLinkSchema).readonly().optional(),
13460
+ /** Operator-authored per-device display override. See `DeviceMeta.display`. */
13461
+ display: DeviceDisplayOverrideSchema.optional()
12473
13462
  });
12474
13463
  var ConfigEntrySchema = object({
12475
13464
  key: string(),
@@ -12534,7 +13523,9 @@ var DeviceMetaSchema = object({
12534
13523
  deviceLinks: array(DeviceLinkSchema).readonly().optional(),
12535
13524
  /** Semantic role string (`DeviceRole`) — propagated from the spawn pre-seed.
12536
13525
  * Optional: only present for accessory children that carry a known role. */
12537
- role: string().nullable().optional()
13526
+ role: string().nullable().optional(),
13527
+ /** Operator-authored per-device display override. See `DeviceMeta.display`. */
13528
+ display: DeviceDisplayOverrideSchema.optional()
12538
13529
  });
12539
13530
  /** ConfigUISchema passed through as unknown — mirrors device-provider's CreationSchemaOutputSchema */
12540
13531
  var ConfigUISchemaOutput = unknown().nullable();
@@ -12628,7 +13619,19 @@ method(object({
12628
13619
  }), _void(), {
12629
13620
  kind: "mutation",
12630
13621
  auth: "admin"
12631
- }), method(object({ deviceId: number() }), object({ caps: array(object({
13622
+ }), method(object({
13623
+ deviceId: number(),
13624
+ display: DeviceDisplayOverrideSchema.nullable()
13625
+ }), _void(), {
13626
+ kind: "mutation",
13627
+ auth: "admin"
13628
+ }), method(object({}), object({ defaults: record(string(), RoleDisplayDefaultSchema) }), { kind: "query" }), method(object({ defaults: record(string(), RoleDisplayDefaultSchema) }), _void(), {
13629
+ kind: "mutation",
13630
+ auth: "admin"
13631
+ }), method(object({
13632
+ deviceId: number(),
13633
+ includeSynthesizable: boolean().optional()
13634
+ }), object({ caps: array(object({
12632
13635
  cap: string(),
12633
13636
  fields: array(object({
12634
13637
  path: string(),
@@ -12638,8 +13641,13 @@ method(object({
12638
13641
  "boolean",
12639
13642
  "enum"
12640
13643
  ]),
12641
- enumValues: array(string()).optional()
12642
- })).readonly()
13644
+ enumValues: array(string()).optional(),
13645
+ item: boolean().optional()
13646
+ })).readonly(),
13647
+ itemArray: object({
13648
+ path: string(),
13649
+ keyField: string()
13650
+ }).optional()
12643
13651
  })).readonly() }), { kind: "query" }), method(object({
12644
13652
  deviceId: number(),
12645
13653
  role: string().nullable()
@@ -12709,7 +13717,11 @@ method(object({
12709
13717
  deviceId: number(),
12710
13718
  entries: array(object({
12711
13719
  capName: string(),
12712
- kind: _enum(["native", "wrapped"]),
13720
+ kind: _enum([
13721
+ "native",
13722
+ "wrapped",
13723
+ "linked"
13724
+ ]),
12713
13725
  providerAddonId: string(),
12714
13726
  providerNodeId: string(),
12715
13727
  nativeAddonId: string()
@@ -12718,7 +13730,11 @@ method(object({
12718
13730
  deviceId: number(),
12719
13731
  entries: array(object({
12720
13732
  capName: string(),
12721
- kind: _enum(["native", "wrapped"]),
13733
+ kind: _enum([
13734
+ "native",
13735
+ "wrapped",
13736
+ "linked"
13737
+ ]),
12722
13738
  providerAddonId: string(),
12723
13739
  providerNodeId: string(),
12724
13740
  nativeAddonId: string()
@@ -13977,7 +14993,10 @@ var AgentLoadSummarySchema = object({
13977
14993
  online: boolean(),
13978
14994
  load: RunnerLocalLoadSchema,
13979
14995
  /** Computed score used by the L2 capacity balancer (lower = less loaded). */
13980
- score: number()
14996
+ score: number(),
14997
+ /** This node's decode hwaccel backend (per-node `probedBestHwaccel`), or null
14998
+ * when not yet probed — for the cluster Pipeline table UI (P0.2). */
14999
+ decodeHwaccel: string().nullable()
13981
15000
  });
13982
15001
  /**
13983
15002
  * Aggregate metrics across the whole detection cluster. Replaces the legacy
@@ -16518,7 +17537,10 @@ var HwAccelBackendInputSchema = _enum([
16518
17537
  "webgpu",
16519
17538
  "none"
16520
17539
  ]).nullable().optional();
16521
- var HwAccelResolutionSchema = object({ preferred: array(string()).readonly() });
17540
+ var HwAccelResolutionSchema = object({
17541
+ preferred: array(string()).readonly(),
17542
+ rationale: string()
17543
+ });
16522
17544
  var HardwareEncoderIdSchema = _enum([
16523
17545
  "h264_videotoolbox",
16524
17546
  "hevc_videotoolbox",
@@ -16533,7 +17555,7 @@ var HardwareEncoderIdSchema = _enum([
16533
17555
  "libx264",
16534
17556
  "libx265"
16535
17557
  ]);
16536
- var HardwareEncodersSchema = object({
17558
+ object({
16537
17559
  encoders: array(object({
16538
17560
  encoder: HardwareEncoderIdSchema,
16539
17561
  codec: _enum(["H264", "H265"]),
@@ -16552,15 +17574,7 @@ var HardwareEncodersSchema = object({
16552
17574
  defaultH265: HardwareEncoderIdSchema,
16553
17575
  probedAt: number()
16554
17576
  });
16555
- /**
16556
- * Decode-side companion to {@link HardwareEncodersSchema}: the `-hwaccel`
16557
- * methods the configured ffmpeg binary actually supports (parsed from
16558
- * `ffmpeg -hwaccels`). Used to gate decode-hwaccel attempts so the transcode
16559
- * egress never spends a spawn on a backend this build cannot offer. Per-stream
16560
- * decode fragility (e.g. VideoToolbox HEVC) is still handled by the egress's
16561
- * software fallback — this only filters out wholly-unsupported backends.
16562
- */
16563
- var HardwareDecodeAccelsSchema = object({
17577
+ object({
16564
17578
  methods: array(string()).readonly(),
16565
17579
  probedAt: number()
16566
17580
  });
@@ -16623,16 +17637,7 @@ var ResolvedInferenceConfigSchema = object({
16623
17637
  format: ModelFormatSchema,
16624
17638
  reason: string()
16625
17639
  });
16626
- method(_void(), PlatformCapabilitiesSchema), method(_void(), HardwareInfoSchema), method(object({ requirements: array(ModelRequirementSchema).readonly() }), ResolvedInferenceConfigSchema), method(object({
16627
- prefer: HwAccelBackendInputSchema,
16628
- nodeId: string().optional()
16629
- }), HwAccelResolutionSchema), method(_void(), HardwareEncodersSchema), method(_void(), HardwareEncodersSchema, {
16630
- kind: "mutation",
16631
- auth: "admin"
16632
- }), method(_void(), HardwareDecodeAccelsSchema), method(_void(), HardwareDecodeAccelsSchema, {
16633
- kind: "mutation",
16634
- auth: "admin"
16635
- });
17640
+ method(_void(), PlatformCapabilitiesSchema), method(_void(), HardwareInfoSchema), method(object({ requirements: array(ModelRequirementSchema).readonly() }), ResolvedInferenceConfigSchema), method(object({ prefer: HwAccelBackendInputSchema }), HwAccelResolutionSchema);
16636
17641
  var PtzPresetSchema = object({
16637
17642
  id: string(),
16638
17643
  name: string()
@@ -16685,6 +17690,16 @@ DeviceType.Camera, DeviceType.Sensor, DeviceType.Switch, method(object({ deviceI
16685
17690
  kind: "mutation",
16686
17691
  auth: "admin"
16687
17692
  });
17693
+ /**
17694
+ * `recording` cap — footage availability + HLS playback manifests + per-device
17695
+ * recording config. NOTE on events (source of truth, R5/C3): this cap carries
17696
+ * NO event surface — `getPlaybackManifest` returns playlist URLs only. Timeline
17697
+ * events (motion/object/audio) come from `pipelineAnalytics` (durable SQLite
17698
+ * rows); the recorder's internal EventMap markers are ephemeral in-RAM
17699
+ * annotations that are not exposed here and must not be treated as an event
17700
+ * feed. Event<->footage joins are by time, padded with the shared `EVENT_PAD_MS`
17701
+ * (`interfaces/recording-config.ts`).
17702
+ */
16688
17703
  var RecordingStatusSchema = object({
16689
17704
  deviceId: number(),
16690
17705
  enabled: boolean(),
@@ -18321,6 +19336,12 @@ Object.freeze({
18321
19336
  addonId: null,
18322
19337
  access: "view"
18323
19338
  },
19339
+ "deviceManager.getRoleDisplayDefaults": {
19340
+ capName: "device-manager",
19341
+ capScope: "system",
19342
+ addonId: null,
19343
+ access: "view"
19344
+ },
18324
19345
  "deviceManager.getSettingsSchema": {
18325
19346
  capName: "device-manager",
18326
19347
  capScope: "system",
@@ -18471,6 +19492,12 @@ Object.freeze({
18471
19492
  addonId: null,
18472
19493
  access: "create"
18473
19494
  },
19495
+ "deviceManager.setDisplay": {
19496
+ capName: "device-manager",
19497
+ capScope: "system",
19498
+ addonId: null,
19499
+ access: "create"
19500
+ },
18474
19501
  "deviceManager.setIntegrationId": {
18475
19502
  capName: "device-manager",
18476
19503
  capScope: "system",
@@ -18513,6 +19540,12 @@ Object.freeze({
18513
19540
  addonId: null,
18514
19541
  access: "create"
18515
19542
  },
19543
+ "deviceManager.setRoleDisplayDefaults": {
19544
+ capName: "device-manager",
19545
+ capScope: "system",
19546
+ addonId: null,
19547
+ access: "create"
19548
+ },
18516
19549
  "deviceManager.setStreamProfileMap": {
18517
19550
  capName: "device-manager",
18518
19551
  capScope: "system",
@@ -19563,6 +20596,66 @@ Object.freeze({
19563
20596
  addonId: null,
19564
20597
  access: "create"
19565
20598
  },
20599
+ "petFeeder.callPet": {
20600
+ capName: "pet-feeder",
20601
+ capScope: "device",
20602
+ addonId: null,
20603
+ access: "create"
20604
+ },
20605
+ "petFeeder.cancelFeed": {
20606
+ capName: "pet-feeder",
20607
+ capScope: "device",
20608
+ addonId: null,
20609
+ access: "create"
20610
+ },
20611
+ "petFeeder.feed": {
20612
+ capName: "pet-feeder",
20613
+ capScope: "device",
20614
+ addonId: null,
20615
+ access: "create"
20616
+ },
20617
+ "petFeeder.markFoodReplenished": {
20618
+ capName: "pet-feeder",
20619
+ capScope: "device",
20620
+ addonId: null,
20621
+ access: "create"
20622
+ },
20623
+ "petFeeder.playSound": {
20624
+ capName: "pet-feeder",
20625
+ capScope: "device",
20626
+ addonId: null,
20627
+ access: "create"
20628
+ },
20629
+ "petFeeder.resetDesiccant": {
20630
+ capName: "pet-feeder",
20631
+ capScope: "device",
20632
+ addonId: null,
20633
+ access: "delete"
20634
+ },
20635
+ "petFeeder.setChildLock": {
20636
+ capName: "pet-feeder",
20637
+ capScope: "device",
20638
+ addonId: null,
20639
+ access: "create"
20640
+ },
20641
+ "petFeeder.setFeedSound": {
20642
+ capName: "pet-feeder",
20643
+ capScope: "device",
20644
+ addonId: null,
20645
+ access: "create"
20646
+ },
20647
+ "petFeeder.setIndicatorLight": {
20648
+ capName: "pet-feeder",
20649
+ capScope: "device",
20650
+ addonId: null,
20651
+ access: "create"
20652
+ },
20653
+ "petFeeder.setVolume": {
20654
+ capName: "pet-feeder",
20655
+ capScope: "device",
20656
+ addonId: null,
20657
+ access: "create"
20658
+ },
19566
20659
  "pipelineAnalytics.clearTracks": {
19567
20660
  capName: "pipeline-analytics",
19568
20661
  capScope: "device",
@@ -20169,30 +21262,6 @@ Object.freeze({
20169
21262
  addonId: null,
20170
21263
  access: "view"
20171
21264
  },
20172
- "platformProbe.getHardwareDecodeAccels": {
20173
- capName: "platform-probe",
20174
- capScope: "system",
20175
- addonId: null,
20176
- access: "view"
20177
- },
20178
- "platformProbe.getHardwareEncoders": {
20179
- capName: "platform-probe",
20180
- capScope: "system",
20181
- addonId: null,
20182
- access: "view"
20183
- },
20184
- "platformProbe.refreshHardwareDecodeAccels": {
20185
- capName: "platform-probe",
20186
- capScope: "system",
20187
- addonId: null,
20188
- access: "create"
20189
- },
20190
- "platformProbe.refreshHardwareEncoders": {
20191
- capName: "platform-probe",
20192
- capScope: "system",
20193
- addonId: null,
20194
- access: "create"
20195
- },
20196
21265
  "platformProbe.resolveHwAccel": {
20197
21266
  capName: "platform-probe",
20198
21267
  capScope: "system",