@camstack/types 1.2.161 → 1.2.163

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/addon.js +14 -43
  2. package/dist/addon.mjs +14 -43
  3. package/dist/capabilities/alerts.cap.d.ts +5 -5
  4. package/dist/capabilities/index.d.ts +7 -5
  5. package/dist/capabilities/notifier.cap.d.ts +3 -3
  6. package/dist/capabilities/pet-feeder.cap.d.ts +4 -4
  7. package/dist/capabilities/snapshot.cap.d.ts +2 -2
  8. package/dist/capabilities/storage-occupancy.cap.d.ts +72 -0
  9. package/dist/capabilities/storage-provider.cap.d.ts +110 -11
  10. package/dist/capabilities/storage.cap.d.ts +43 -22
  11. package/dist/capabilities/stream-broker.cap.d.ts +1 -1
  12. package/dist/enums/event-category.d.ts +13 -0
  13. package/dist/enums.js +1 -1
  14. package/dist/enums.mjs +1 -1
  15. package/dist/{event-category-b8kBSOTT.js → event-category-BVo6ta6_.js} +13 -0
  16. package/dist/{event-category-zAv7pMUz.mjs → event-category-CnLqLOKs.mjs} +13 -0
  17. package/dist/generated/addon-api.d.ts +22 -7
  18. package/dist/generated/capability-router-map.d.ts +5 -2
  19. package/dist/generated/collection-array-methods.d.ts +1 -1
  20. package/dist/generated/method-access-map.d.ts +1 -1
  21. package/dist/generated/system-proxy.d.ts +1 -1
  22. package/dist/index.d.ts +17 -15
  23. package/dist/index.js +2049 -1702
  24. package/dist/index.mjs +2028 -1703
  25. package/dist/interfaces/event-bus.d.ts +19 -0
  26. package/dist/interfaces/storage-location-mode.d.ts +135 -0
  27. package/dist/interfaces/storage-location.d.ts +79 -4
  28. package/dist/node.d.ts +13 -11
  29. package/dist/node.js +935 -876
  30. package/dist/node.mjs +936 -879
  31. package/dist/{sleep-DDIFZGbc.js → sleep-BZtO-eFY.js} +1 -1
  32. package/dist/{sleep-Cfij6Jj9.mjs → sleep-Bd-Y4RUt.mjs} +1 -1
  33. package/dist/storage/physical-root.d.ts +25 -0
  34. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_event_category = require("./event-category-b8kBSOTT.js");
3
- const require_sleep = require("./sleep-DDIFZGbc.js");
2
+ const require_event_category = require("./event-category-BVo6ta6_.js");
3
+ const require_sleep = require("./sleep-BZtO-eFY.js");
4
4
  const require_canonical_hash = require("./canonical-hash-DNV8S5ET.js");
5
5
  const require_enums = require("./enums.js");
6
6
  const require_err_msg = require("./err-msg-COpsHMw2.js");
@@ -1432,378 +1432,6 @@ function logLevelAtMost(level, threshold) {
1432
1432
  return LOG_LEVEL_RANK[level] <= LOG_LEVEL_RANK[threshold];
1433
1433
  }
1434
1434
  //#endregion
1435
- //#region src/logging/log-channel.ts
1436
- /**
1437
- * Per-component log CHANNELS — the gate a hot path consults, and the registry
1438
- * an addon declares its channels in.
1439
- *
1440
- * ## Two axes, deliberately separated
1441
- *
1442
- * - **DECLARATION** — which channels exist. Only the addon knows:
1443
- * `stream-broker` knows webrtc/ICE/RTP, `provider-reolink` knows
1444
- * baichuan/handshake. A hand-wired central list rots at the first addition,
1445
- * and rots silently. So a channel is declared where it is consulted, and the
1446
- * `log-channels` capability enumerates the declarations.
1447
- * - **VALUE** — at which level, for which scope, until when. That stays ONE
1448
- * thing: the logging settings document on the `system` cap. Two authorities
1449
- * over the values is the exact defect
1450
- * `docs/design/plans/2026-08-26-logging-per-componente.md` was written to
1451
- * remove; re-introducing it from the cure side would be grotesque.
1452
- *
1453
- * Nothing in this file reads a clock, an env var or a store. The registry is
1454
- * a MIRROR: it is moved only by {@link LogChannelRegistry.apply}, called off
1455
- * the hot path with a value somebody actually read, and by
1456
- * {@link LogChannelRegistry.tick}, called on a timer. A store read that fails
1457
- * never reaches here, so it can neither disarm an armed channel nor arm a
1458
- * disarmed one (D49).
1459
- *
1460
- * ## The canonical call shape
1461
- *
1462
- * ```ts
1463
- * if (CH_RTP.on && CH_RTP.wants(deviceId)) {
1464
- * CH_RTP.log(logger, 'rtp subscriber added', { tags: { deviceId }, meta: { ssrc } })
1465
- * }
1466
- * ```
1467
- *
1468
- * `on` is a plain boolean FIELD — never a getter — and it is the FIRST thing
1469
- * read. Disarmed, a call site costs one load and one branch, and the `extras`
1470
- * object literal is never constructed because it lives inside the branch. It
1471
- * is the same shape already proven in production at `stream-broker.ts:1650`,
1472
- * and the same discipline `LoggingGate.allowsDestination` uses for the
1473
- * destination floor (measured at 1.93 ns/call when off).
1474
- *
1475
- * ## Why a channel emits at `info`
1476
- *
1477
- * `loki-logging.addon.ts` pins the destination default at `info` and
1478
- * `loki-destination.ts` drops everything below it, so a line emitted at
1479
- * `debug` never reaches Loki and the hub's in-memory ring only holds ~35
1480
- * minutes. A diagnostic that cannot be read an hour later is worse than no
1481
- * diagnostic, because it looks done. {@link LogChannelGate.log} therefore
1482
- * emits at the channel's declared level, whose schema floor is `info`.
1483
- */
1484
- /**
1485
- * The level a channel writes at once armed.
1486
- *
1487
- * `debug` is absent ON PURPOSE and not by omission: below `info` the line does
1488
- * not leave the process for Loki, and the whole point of arming a channel is
1489
- * to read it later.
1490
- */
1491
- var LogChannelLevelSchema = zod.z.enum([
1492
- "info",
1493
- "warn",
1494
- "error"
1495
- ]);
1496
- /**
1497
- * What an addon declares about one channel. No value, no state — a
1498
- * declaration is inert.
1499
- */
1500
- var LogChannelDescriptorSchema = zod.z.object({
1501
- /**
1502
- * Dotted `area.thing`, unique across the workspace. `area` is conventionally
1503
- * the addon's short name so an operator reading a channel list can tell who
1504
- * owns it without a second lookup.
1505
- */
1506
- name: zod.z.string().min(3).regex(/^[a-z0-9-]+(\.[a-z0-9-]+)+$/, "a channel name is dotted lower-kebab, e.g. area.thing"),
1507
- /** One sentence: what the operator will SEE after arming it. */
1508
- description: zod.z.string().min(1),
1509
- /** The level its lines are emitted at. Never below `info`. */
1510
- defaultLevel: LogChannelLevelSchema,
1511
- /**
1512
- * Whether this channel can be narrowed to a camera.
1513
- *
1514
- * `true` is a PROMISE with two halves, and both must hold: the gate is
1515
- * consulted with the numeric device id, AND every line the channel admits
1516
- * carries `tags: { deviceId }` with that same numeric id. The second half is
1517
- * what makes `| json | deviceId="617"` work in Loki — `loki-payload.ts`
1518
- * keeps `deviceId` out of the stream labels for cardinality, so the tag in
1519
- * the body is the only way to filter.
1520
- *
1521
- * A channel whose lines carry the device only in `meta` (or not at all) is
1522
- * declared `false`. Declaring it `true` anyway would be a lie the UI repeats:
1523
- * the operator narrows to one camera, sees nothing, and concludes the code
1524
- * path was never taken.
1525
- */
1526
- perDevice: zod.z.boolean()
1527
- });
1528
- /**
1529
- * An armed window over one channel, as the document hands it to a mirror.
1530
- *
1531
- * A window is a DEADLINE, never a flag (ADR-0244): a channel somebody forgot
1532
- * expires by itself, which is the one failure a boolean cannot avoid.
1533
- */
1534
- var LogChannelWindowSchema = zod.z.object({
1535
- channel: zod.z.string().min(1),
1536
- /** Epoch ms the window closes at. */
1537
- armedUntilMs: zod.z.number(),
1538
- /** `null` = every camera. A non-empty list narrows to those numeric ids. */
1539
- deviceIds: zod.z.array(zod.z.number().int()).readonly().nullable()
1540
- });
1541
- /**
1542
- * The gate a hot path holds.
1543
- *
1544
- * Obtain it ONCE — at module scope or in a constructor — and keep the
1545
- * reference. Looking a channel up by name per line would put a Map lookup on
1546
- * the path this class exists to keep free.
1547
- */
1548
- var LogChannelGate = class {
1549
- descriptor;
1550
- /**
1551
- * HOT PATH GUARD. A plain data FIELD, and it must stay one.
1552
- *
1553
- * `log-channel.spec.ts` asserts the property descriptor has no getter and
1554
- * booby-traps the device set, so turning this into an accessor — or reading
1555
- * anything before it — fails the spec instead of taxing every line the
1556
- * process emits.
1557
- */
1558
- on = false;
1559
- /** `null` while armed for every camera. Never read while `on` is false. */
1560
- devices = null;
1561
- level;
1562
- closesAtMs = 0;
1563
- constructor(descriptor) {
1564
- this.descriptor = descriptor;
1565
- this.level = descriptor.defaultLevel;
1566
- }
1567
- /** Epoch ms this channel disarms itself at. 0 when disarmed. */
1568
- get armedUntilMs() {
1569
- return this.on ? this.closesAtMs : 0;
1570
- }
1571
- /**
1572
- * Does this channel want a line about `deviceId`?
1573
- *
1574
- * Call it only behind `gate.on &&`. On its own it is still correct — the
1575
- * guard is repeated inside — but the point of the prefix is that a disarmed
1576
- * channel must not pay the call at all.
1577
- */
1578
- wants(deviceId) {
1579
- if (!this.on) return false;
1580
- return this.devices === null || this.devices.has(deviceId);
1581
- }
1582
- /**
1583
- * Emit one line on this channel, at the channel's declared level.
1584
- *
1585
- * The channel name is added as `tags.logChannel` so LogQL can select the
1586
- * channel without matching on the message text, and whatever `tags` the
1587
- * caller passed — `deviceId` above all — is preserved.
1588
- */
1589
- log(logger, message, extras) {
1590
- if (!this.on) return;
1591
- const tags = {
1592
- ...extras.tags,
1593
- logChannel: this.descriptor.name
1594
- };
1595
- const line = {
1596
- ...extras,
1597
- tags
1598
- };
1599
- if (this.level === "error") logger.error(message, line);
1600
- else if (this.level === "warn") logger.warn(message, line);
1601
- else logger.info(message, line);
1602
- }
1603
- /**
1604
- * Arm (or RE-arm, restarting) this channel. Off the hot path only.
1605
- *
1606
- * An empty `deviceIds` list is treated as "every camera" rather than "no
1607
- * camera": a window that matches nothing is indistinguishable from a
1608
- * disarmed one, and the operator who asked for it would wait for lines that
1609
- * can never come.
1610
- */
1611
- arm(window) {
1612
- const ids = window.deviceIds;
1613
- this.devices = ids === null || ids.length === 0 ? null : new Set(ids);
1614
- this.closesAtMs = window.armedUntilMs;
1615
- this.on = true;
1616
- }
1617
- /** Disarm. Off the hot path only. */
1618
- disarm() {
1619
- this.on = false;
1620
- this.devices = null;
1621
- this.closesAtMs = 0;
1622
- }
1623
- };
1624
- /**
1625
- * Every channel this PROCESS declares, and the mirror of what is armed on it.
1626
- *
1627
- * One per process. A forked runner has its own, and it is refreshed through
1628
- * the `log-channels` capability by the hub that owns the document — the
1629
- * registry never reaches for a value itself.
1630
- */
1631
- var LogChannelRegistry = class {
1632
- gates = /* @__PURE__ */ new Map();
1633
- /**
1634
- * Declare a channel and get its gate.
1635
- *
1636
- * A duplicate name throws. Two declarations of one name is a programming
1637
- * error, not a merge: the operator would arm one and the other would stay
1638
- * dark, which is the dead-knob shape (D62) with an extra step.
1639
- */
1640
- declare(descriptor) {
1641
- const parsed = LogChannelDescriptorSchema.parse(descriptor);
1642
- if (this.gates.get(parsed.name) !== void 0) throw new Error(`log channel "${parsed.name}" is already declared in this process — two declarations of one name is a programming error, not a merge`);
1643
- const gate = new LogChannelGate(parsed);
1644
- this.gates.set(parsed.name, gate);
1645
- return gate;
1646
- }
1647
- /** The declarations, sorted by name so a list is stable to read and diff. */
1648
- list() {
1649
- return [...this.gates.values()].map((gate) => gate.descriptor).sort((a, b) => a.name.localeCompare(b.name));
1650
- }
1651
- /** The gate for a declared channel, or `undefined`. */
1652
- gate(name) {
1653
- return this.gates.get(name);
1654
- }
1655
- /**
1656
- * Apply the FULL set of armed windows. Off the hot path.
1657
- *
1658
- * Full, not incremental, and that is the whole design: the document is the
1659
- * authority, so a channel the document does not name is disarmed here. An
1660
- * incremental apply would let a disarm get lost in transit and leave a
1661
- * channel running that nobody can see is running.
1662
- *
1663
- * A window already past its deadline is ignored rather than armed — a
1664
- * restore that re-armed an expired window would make a forgotten diagnostic
1665
- * immortal across restarts.
1666
- *
1667
- * Returns the names it could not place, so the caller can log them: a
1668
- * channel named in the document that this process does not declare is
1669
- * either a typo or an addon that has not booted yet, and both deserve a
1670
- * line rather than silence.
1671
- */
1672
- apply(windows, nowMs) {
1673
- const wanted = /* @__PURE__ */ new Map();
1674
- const unknown = [];
1675
- for (const window of windows) {
1676
- if (window.armedUntilMs <= nowMs) continue;
1677
- if (!this.gates.has(window.channel)) {
1678
- unknown.push(window.channel);
1679
- continue;
1680
- }
1681
- wanted.set(window.channel, window);
1682
- }
1683
- for (const [name, gate] of this.gates) {
1684
- const window = wanted.get(name);
1685
- if (window === void 0) gate.disarm();
1686
- else gate.arm(window);
1687
- }
1688
- return unknown;
1689
- }
1690
- /**
1691
- * Disarm whatever has run out. Called on a timer, NEVER from a log path — a
1692
- * diagnostic that adds a `Date.now()` to the path it is measuring measures
1693
- * itself.
1694
- *
1695
- * Returns the names it closed, so the caller can write the one line that
1696
- * says a window ended and stops "it went quiet" from reading as "the branch
1697
- * was not taken".
1698
- */
1699
- tick(nowMs) {
1700
- const closed = [];
1701
- for (const [name, gate] of this.gates) if (gate.on && gate.armedUntilMs <= nowMs) {
1702
- gate.disarm();
1703
- closed.push(name);
1704
- }
1705
- return closed;
1706
- }
1707
- /** The channels armed right now, as the document would describe them. */
1708
- armed() {
1709
- const out = [];
1710
- for (const [name, gate] of this.gates) if (gate.on) out.push({
1711
- channel: name,
1712
- armedUntilMs: gate.armedUntilMs,
1713
- deviceIds: null
1714
- });
1715
- return out;
1716
- }
1717
- };
1718
- //#endregion
1719
- //#region src/logging/log-channel.singleton.ts
1720
- /**
1721
- * Process-wide holder for the {@link LogChannelRegistry}.
1722
- *
1723
- * Three call sites that never meet need the SAME instance: the hot paths that
1724
- * declare a gate at module scope, the `log-channels` provider that enumerates
1725
- * the declarations for the hub, and the same provider applying the windows the
1726
- * document hands down. A registry built inside any one of them would be
1727
- * refreshed and collected — the shape of a knob that never does anything.
1728
- *
1729
- * Same idiom as `logging-gate.singleton.ts` and
1730
- * `http-request-census.singleton.ts`.
1731
- */
1732
- var instance = null;
1733
- /** The process-wide log channel registry. Created empty on first use. */
1734
- function getLogChannelRegistry() {
1735
- instance ??= new LogChannelRegistry();
1736
- return instance;
1737
- }
1738
- /**
1739
- * Declare a channel on the process-wide registry and get its gate.
1740
- *
1741
- * The one call an addon makes. Keep the returned gate in a module-scope
1742
- * `const`: looking a channel up by name per line would put a Map lookup on
1743
- * exactly the path this mechanism exists to keep free.
1744
- *
1745
- * `scripts/check-log-channel-gated.ts` reads these call sites. It pairs the
1746
- * declared name with the binding it is assigned to and refuses to let a
1747
- * channel ship that no `<binding>.on` anywhere consults — a declared channel
1748
- * nobody reads is a knob the operator turns with nothing happening, forever,
1749
- * and without a line. That is D62, and this repo has now shipped it three
1750
- * times (`audioThresholdDbfs`, the HA entities with no source, the second
1751
- * per-camera switch that wrote a store nobody read).
1752
- */
1753
- function declareLogChannel(descriptor) {
1754
- return getLogChannelRegistry().declare(descriptor);
1755
- }
1756
- /** Test-only: drop the instance so a spec starts from an empty registry. */
1757
- function __resetLogChannelRegistryForTests() {
1758
- instance = null;
1759
- }
1760
- //#endregion
1761
- //#region src/logging/log-channel-provider.ts
1762
- /**
1763
- * How often expiry is noticed. Coarse on purpose: the cost of a channel
1764
- * running a few seconds past its deadline is a few extra lines, and the cost
1765
- * of a tight timer in every addon process is paid forever.
1766
- */
1767
- var LOG_CHANNEL_TICK_MS = 5e3;
1768
- /**
1769
- * Build the `log-channels` provider for this process.
1770
- *
1771
- * `logger` is used ONLY off the hot path — for the arm/expiry lines — so a
1772
- * channel that is never armed costs this module nothing but a timer.
1773
- */
1774
- function createLogChannelsProvider(logger, options = {}) {
1775
- const registry = getLogChannelRegistry();
1776
- const now = options.now ?? Date.now;
1777
- const tickMs = options.tickMs ?? 5e3;
1778
- const timer = setInterval(() => {
1779
- const closed = registry.tick(now());
1780
- for (const name of closed) logger.info("log channel window closed", {
1781
- tags: { logChannel: name },
1782
- meta: { channel: name }
1783
- });
1784
- }, tickMs);
1785
- timer.unref?.();
1786
- return {
1787
- list: () => registry.list(),
1788
- apply: (input) => {
1789
- const unknown = registry.apply(input.windows, now());
1790
- const armed = registry.armed();
1791
- logger.info("log channels applied", { meta: {
1792
- armed: armed.map((window) => window.channel),
1793
- unknown,
1794
- declared: registry.list().length
1795
- } });
1796
- return {
1797
- armed: armed.length,
1798
- unknown
1799
- };
1800
- },
1801
- stop: () => {
1802
- clearInterval(timer);
1803
- }
1804
- };
1805
- }
1806
- //#endregion
1807
1435
  //#region src/interfaces/ops-log.ts
1808
1436
  /**
1809
1437
  * Ops-log — the durable, append-only operations audit shared by the
@@ -3015,6 +2643,158 @@ var RECOGNITION_TYPES = [
3015
2643
  "custom"
3016
2644
  ];
3017
2645
  //#endregion
2646
+ //#region src/interfaces/storage-location-mode.ts
2647
+ /**
2648
+ * The storage-location STATE MODEL (D385) — one typed state, one policy module.
2649
+ *
2650
+ * A location's state used to be split across two authorities: the typed
2651
+ * `enabled` field (THE write switch since D383) and an untyped `config.readOnly`
2652
+ * key. They did not mean the same thing — `enabled: false` was still evicted
2653
+ * under disk pressure while `config.readOnly` was deliberately excluded — and
2654
+ * neither name said which. Every consumer re-derived the difference, and the
2655
+ * three questions that actually matter were answered in six places.
2656
+ *
2657
+ * This module is the ONLY place in the repo allowed to interpret the state. It
2658
+ * answers three questions and nothing else:
2659
+ *
2660
+ * - may this location be WRITTEN to? {@link modeMayWrite}
2661
+ * - may this location be READ? {@link modeMayRead}
2662
+ * - what is its eviction policy? {@link evictionPolicyForMode}
2663
+ *
2664
+ * | mode | write | read | eviction |
2665
+ * | ---------- | ----- | ---- | ------------------------------ |
2666
+ * | `active` | yes | yes | `normal` (pressure + usage cap) |
2667
+ * | `readonly` | no | yes | `never` |
2668
+ * | `drain` | no | yes | `drain` (paced, until empty) |
2669
+ * | `disabled` | no | no | `never` |
2670
+ *
2671
+ * `scripts/check-storage-location-mode-single-owner.ts` fails the build when
2672
+ * anything outside this module reads `config['readOnly']` or compares `enabled`
2673
+ * directly. A rule nothing checks has already been broken somewhere.
2674
+ */
2675
+ var STORAGE_LOCATION_MODES = [
2676
+ "active",
2677
+ "readonly",
2678
+ "drain",
2679
+ "disabled"
2680
+ ];
2681
+ /**
2682
+ * The one typed state of a storage location. Authoritative Zod schema — the TS
2683
+ * alias below is `z.infer<>` of it, never a second spelling.
2684
+ */
2685
+ var StorageLocationModeSchema = zod.z.enum(STORAGE_LOCATION_MODES);
2686
+ /**
2687
+ * What disk-pressure and usage-cap relief may do to a location.
2688
+ *
2689
+ * - `normal` — the existing behaviour: free-percent guard plus `maxUsedGb`.
2690
+ * - `never` — excluded entirely. A retiring disk the operator is copying off
2691
+ * must not race the relocate mover, and a disabled one is not the
2692
+ * system's to erase.
2693
+ * - `drain` — a monotonically descending effective usage cap, paced to what
2694
+ * the ACTIVE locations of the same class gained (D386). This is
2695
+ * the only policy that shrinks a location the system is not
2696
+ * writing to.
2697
+ */
2698
+ var StorageEvictionPolicySchema = zod.z.enum([
2699
+ "normal",
2700
+ "never",
2701
+ "drain"
2702
+ ]);
2703
+ /**
2704
+ * The legacy untyped drain key. Named ONCE, here, so the guard has exactly one
2705
+ * sanctioned reader and the string never appears anywhere else.
2706
+ */
2707
+ var LEGACY_READ_ONLY_CONFIG_KEY = "readOnly";
2708
+ /** Is this mode a write target? Only `active` is. */
2709
+ function modeMayWrite(mode) {
2710
+ return mode === "active";
2711
+ }
2712
+ /** May this mode be read (playback, timeline, scrub, relocate source)? */
2713
+ function modeMayRead(mode) {
2714
+ return mode !== "disabled";
2715
+ }
2716
+ /** What eviction may do here. See {@link StorageEvictionPolicy}. */
2717
+ function evictionPolicyForMode(mode) {
2718
+ switch (mode) {
2719
+ case "active": return "normal";
2720
+ case "drain": return "drain";
2721
+ case "readonly":
2722
+ case "disabled": return "never";
2723
+ }
2724
+ }
2725
+ /**
2726
+ * The mode a LEGACY row implies, or `null` when it implies nothing — the row is
2727
+ * already stamped, or it carried neither flag.
2728
+ *
2729
+ * Both legacy flags fold to `readonly`, which is the CONSERVATIVE direction: a
2730
+ * state change must never start deleting footage on its own, and it must never
2731
+ * make footage that was still being served disappear. `enabled: false` used to
2732
+ * leave the location evictable under pressure; folding it to `readonly` stops
2733
+ * that, which is a strictly safer answer than the one it replaces.
2734
+ */
2735
+ function legacyModeOf(location) {
2736
+ if (location.mode !== void 0) return null;
2737
+ if (location.config["readOnly"] === true) return "readonly";
2738
+ if (location.enabled === false) return "readonly";
2739
+ return null;
2740
+ }
2741
+ /**
2742
+ * The state of a location, stamped or folded. THE one interpretation: a row
2743
+ * that predates D385 is never ambiguous, and a stamped `mode` always wins over
2744
+ * whatever the legacy pair still says.
2745
+ */
2746
+ function resolveLocationMode(location) {
2747
+ return (isStorageLocationMode(location.mode) ? location.mode : void 0) ?? legacyModeOf(location) ?? "active";
2748
+ }
2749
+ /** Is this one of the four states? The stamped value crosses a wire, and a
2750
+ * value nobody defined must not be rendered as if it were a state. */
2751
+ function isStorageLocationMode(value) {
2752
+ return STORAGE_LOCATION_MODES.some((mode) => mode === value);
2753
+ }
2754
+ /** May this location be written to? */
2755
+ function mayWriteToLocation(location) {
2756
+ return modeMayWrite(resolveLocationMode(location));
2757
+ }
2758
+ /** May this location be read? A `disabled` one may not — and that is an
2759
+ * operator CHOICE, which callers must report as unavailable rather than as an
2760
+ * unknown-location fault. */
2761
+ function mayReadLocation(location) {
2762
+ return modeMayRead(resolveLocationMode(location));
2763
+ }
2764
+ /** What eviction may do to this location. */
2765
+ function evictionPolicyOfLocation(location) {
2766
+ return evictionPolicyForMode(resolveLocationMode(location));
2767
+ }
2768
+ /**
2769
+ * The config blob with the retired drain key removed. Returns the SAME object
2770
+ * when there was nothing to strip, so a caller can tell "changed" from
2771
+ * "unchanged" by identity and skip a pointless persist.
2772
+ */
2773
+ function strippedOfLegacyReadOnly(config) {
2774
+ if (!("readOnly" in config)) return config;
2775
+ const next = { ...config };
2776
+ delete next[LEGACY_READ_ONLY_CONFIG_KEY];
2777
+ return next;
2778
+ }
2779
+ /**
2780
+ * Set a location's mode, and with it everything that must agree with it.
2781
+ *
2782
+ * `enabled` stays readable for one release as a DERIVED value (`mode ===
2783
+ * 'active'`) so consumers that have not moved yet keep working, and the legacy
2784
+ * `config.readOnly` key is DELETED. This function is the only way to write
2785
+ * either, which is what makes it impossible for the two to disagree.
2786
+ *
2787
+ * Returns a new object — the input is never mutated.
2788
+ */
2789
+ function withLocationMode(location, mode) {
2790
+ return {
2791
+ ...location,
2792
+ mode,
2793
+ enabled: modeMayWrite(mode),
2794
+ config: strippedOfLegacyReadOnly(location.config)
2795
+ };
2796
+ }
2797
+ //#endregion
3018
2798
  //#region src/interfaces/storage-location.ts
3019
2799
  /**
3020
2800
  * `StorageLocationType` — an addon-declared id that identifies the *kind* of
@@ -3041,8 +2821,11 @@ var StorageLocationTypeSchema = zod.z.string().regex(/^[a-z][a-zA-Z0-9-]*$/);
3041
2821
  * `STORAGE_LOCATION_CARDINALITY` map has been removed.
3042
2822
  *
3043
2823
  * `id` is a stable namespaced string of the form `<type>:<slug>`.
3044
- * The default location for a type uses `id === <type>:default` by
3045
- * convention (the bare type ref like `'backups'` resolves to it).
2824
+ * The seed names its first instance `<type>:default` — a NAME, not a flag.
2825
+ * There is no default location any more (D383): `enabled` is the whole write
2826
+ * model, and a bare type ref resolves to the sole location of the type, or —
2827
+ * transitionally, only while legacy NULL-stamped rows exist — to the row whose
2828
+ * slug is `default`.
3046
2829
  *
3047
2830
  * `isSystem` is a legacy persisted flag. Seed still creates the initial
3048
2831
  * `<type>:default` locations; the flag is no longer a lock, a badge, or a
@@ -3063,23 +2846,37 @@ var StorageLocationSchema = zod.z.object({
3063
2846
  * flag at upsert time, not here (the schema is provider-agnostic).
3064
2847
  */
3065
2848
  nodeId: zod.z.string().optional(),
3066
- isDefault: zod.z.boolean().default(false),
3067
2849
  isSystem: zod.z.boolean().default(false),
3068
2850
  /**
3069
- * Operator opt-in: whether consumers that BALANCE across several locations
3070
- * of a type may write here. Recordings reads it today; event media and
3071
- * backups are the next consumers, which is why the flag lives on the
3072
- * location rather than in any one addon's store — nothing has to be
3073
- * extended to add the next consumer.
2851
+ * THE write switch, and the only one (D383). `enabled: true` means every
2852
+ * consumer that chooses a write target for this type may write here, and all
2853
+ * enabled locations of a type are used TOGETHER; `false` means read-only —
2854
+ * still read, still played back, still age-swept, still drained, never
2855
+ * written.
3074
2856
  *
3075
- * OPTIONAL, and ABSENT MEANS ACTIVE. Every location persisted before the
3076
- * flag existed reads back with no flag and keeps working exactly as before;
3077
- * that is the whole compat story, and it is why no migration ships with it.
3078
- * A newly CREATED sibling is stamped `false` by the orchestrator (creating a
3079
- * disk must not silently start writing to it); the default of a type is
3080
- * always stamped `true`.
2857
+ * OPTIONAL only for the wire: an upsert that omits it means "leave what is
2858
+ * stored" on an update and "born inert unless it is the first location of its
2859
+ * type" on a create. On a PERSISTED row absence is legacy and it means
2860
+ * enabled — {@link isLocationEnabled} is the one place that says so, and the
2861
+ * orchestrator stamps every flagless row `true` once at hydrate so absence
2862
+ * stops existing rather than being re-derived on every read.
3081
2863
  */
3082
2864
  enabled: zod.z.boolean().optional(),
2865
+ /**
2866
+ * THE state of this location (D385), and the only authority on what may be
2867
+ * written, read or evicted here. Interpreted in exactly one place —
2868
+ * `storage-location-mode.ts` — which also folds the legacy
2869
+ * `enabled` / `config.readOnly` pair into a mode so an old row is never
2870
+ * ambiguous.
2871
+ *
2872
+ * OPTIONAL only for the wire and for rows written before D385: absence is
2873
+ * resolved by `resolveLocationMode`, and the orchestrator stamps every
2874
+ * unstamped row ONCE at hydrate so absence stops existing rather than being
2875
+ * re-derived on every read. `enabled` survives one release as a DERIVED
2876
+ * mirror (`mode === 'active'`); `withLocationMode` is the only writer of
2877
+ * either, so the two cannot disagree.
2878
+ */
2879
+ mode: StorageLocationModeSchema.optional(),
3083
2880
  /** COMPUTED at read time by the orchestrator (statfs of the backing volume
3084
2881
  * for node-local locations it can reach) — never persisted, absent when the
3085
2882
  * volume is remote/unreachable. The single capacity truth every UI reads. */
@@ -3087,13 +2884,83 @@ var StorageLocationSchema = zod.z.object({
3087
2884
  totalBytes: zod.z.number(),
3088
2885
  availableBytes: zod.z.number()
3089
2886
  }).nullable().optional(),
2887
+ /**
2888
+ * How much of that volume CamStack ITSELF holds on this location (D388) —
2889
+ * COMPUTED at read time from the `storage-occupancy` providers' own figures,
2890
+ * never persisted, never a filesystem walk.
2891
+ *
2892
+ * **ABSENT MEANS UNKNOWN, never zero.** No provider has reported for this
2893
+ * location yet — nobody stores here, the owning addon is down, or the first
2894
+ * refresh has not completed. A UI must omit the segment rather than draw it
2895
+ * at zero, which would claim we occupy nothing (D315). It is an OBJECT and
2896
+ * not a bare number precisely so that a `?? 0` on the consuming side has to
2897
+ * be spelled out loud instead of appearing by accident.
2898
+ *
2899
+ * `measuredAtMs` is the OLDEST contributing measurement, so it is honest
2900
+ * about the whole figure rather than about its freshest part.
2901
+ */
2902
+ owned: zod.z.object({
2903
+ bytes: zod.z.number().int().nonnegative(),
2904
+ measuredAtMs: zod.z.number().int().nonnegative()
2905
+ }).optional(),
3090
2906
  createdAt: zod.z.number(),
3091
2907
  updatedAt: zod.z.number()
3092
2908
  });
3093
2909
  /**
2910
+ * The retired `isDefault` key, DECLARED rather than dropped.
2911
+ *
2912
+ * A key removed from a non-strict `z.object` is stripped in silence (D380,
2913
+ * D381): a reader that still needs the old value gets `undefined` and cannot
2914
+ * tell "absent" from "never sent". The one reader that legitimately needs it —
2915
+ * the location store's boot migration, which turns the old default flag into
2916
+ * the `enabled` write set — parses THIS schema against the raw row instead, so
2917
+ * the migration is explicit and the live schema stays clean. Nothing else in
2918
+ * the repo may read it; `scripts/check-no-storage-default.ts` enforces that.
2919
+ */
2920
+ var LegacyStorageLocationDefaultSchema = zod.z.object({ isDefault: zod.z.boolean().optional() });
2921
+ function isLocationEnabled(location) {
2922
+ return mayWriteToLocation({
2923
+ ...location,
2924
+ config: location.config ?? {}
2925
+ });
2926
+ }
2927
+ /**
2928
+ * Bytes in one GB, for every storage figure an operator types.
2929
+ *
2930
+ * BINARY (1024³), everywhere. The repo had both: the orchestrator's
2931
+ * `maxUsedGb` → bytes conversion used 1024³ while the recorder's placement
2932
+ * headroom used 10⁹ for the SAME stored key, so a location with a cap set was
2933
+ * silently 7.4% off depending on which side of the pipe asked. The persisted
2934
+ * values were entered against the binary unit and the admin UI reads it, so
2935
+ * that is the one that stays. Every GB knob — `maxUsedGb`, `minFreeGb` —
2936
+ * converts through {@link gbToBytes} and nowhere else.
2937
+ */
2938
+ var STORAGE_BYTES_PER_GB = 1024 ** 3;
2939
+ /** GB → bytes, binary. Fractional GB is admitted and floored. */
2940
+ function gbToBytes(gb) {
2941
+ return Math.floor(gb * STORAGE_BYTES_PER_GB);
2942
+ }
2943
+ /**
2944
+ * How far a `drain` has got (D386) — the read a UI renders, and nothing more.
2945
+ *
2946
+ * `estimatedEmptyAtMs` is derived from the growth the ratchet has actually
2947
+ * OBSERVED and is `null` when it has observed none. Never a fabricated date: a
2948
+ * drain with no observed growth has no honest ETA, and inventing one is how an
2949
+ * operator learns not to believe the screen.
2950
+ */
2951
+ var StorageDrainProgressSchema = zod.z.object({
2952
+ locationId: zod.z.string(),
2953
+ startedAtMs: zod.z.number(),
2954
+ startBytes: zod.z.number(),
2955
+ bytesRemaining: zod.z.number(),
2956
+ drained: zod.z.boolean(),
2957
+ estimatedEmptyAtMs: zod.z.number().nullable()
2958
+ });
2959
+ /**
3094
2960
  * Reference accepted by consumer-facing `api.storage.*` calls.
3095
2961
  * Either:
3096
- * - a `StorageLocationType` (e.g. `'backups'`) → orchestrator resolves to the default of that type
2962
+ * - a `StorageLocationType` (e.g. `'backups'`) → the sole location of that type
2963
+ * (transitionally, the `<type>:default`-slugged row when several exist)
3097
2964
  * - a fully-qualified id (e.g. `'backups:nas-01'`) → addresses a specific instance
3098
2965
  *
3099
2966
  * The orchestrator's `resolveRef(ref)` handles both cases.
@@ -3457,358 +3324,535 @@ function findTimezone(id) {
3457
3324
  return TIMEZONES.find((tz) => tz.id === id);
3458
3325
  }
3459
3326
  //#endregion
3460
- //#region src/stream-selection.ts
3461
- function pickPreferredRtspEntry(entries, pref, deviceId, options = {}) {
3462
- if (entries.length === 0) return null;
3463
- const prefix = `${deviceId}/`;
3464
- const toPicked = (e) => ({
3465
- brokerId: e.brokerId,
3466
- profileId: e.brokerId.startsWith(prefix) ? e.brokerId.slice(prefix.length) : e.brokerId,
3467
- url: e.url,
3468
- mutedUrl: e.mutedUrl,
3469
- enabled: e.enabled,
3470
- ...e.codec !== void 0 ? { codec: e.codec } : {},
3471
- ...e.resolution !== void 0 ? { resolution: e.resolution } : {}
3472
- });
3473
- if (pref !== "auto") {
3474
- const match = entries.find((e) => e.enabled && e.url.length > 0 && (e.profile === pref || e.brokerId === `${prefix}${pref}`));
3475
- if (match) return toPicked(match);
3476
- }
3477
- const eligible = entries.filter((e) => e.enabled && e.url.length > 0);
3478
- if (eligible.length === 0) return null;
3479
- const target = options.targetResolution;
3480
- if (target) {
3481
- const withRes = eligible.filter((e) => e.resolution !== void 0);
3482
- if (withRes.length > 0) {
3483
- const picked = pickClosestResolution(withRes, target);
3484
- if (picked) return toPicked(picked);
3485
- }
3486
- }
3487
- return toPicked(eligible[0]);
3488
- }
3489
- /**
3490
- * Pick the entry whose `resolution` is closest to `target`. Prefer
3491
- * entries ≥ target (downscale is cheap at the consumer; upscale is
3492
- * lossy). Among the rest pick the LARGEST still ≤ target so the
3493
- * consumer gets the best feasible quality. "Closeness" is the
3494
- * `width × height` pixel delta.
3495
- */
3496
- function pickClosestResolution(entries, target) {
3497
- const targetPixels = target.width * target.height;
3498
- let bestAbove;
3499
- let bestBelow;
3500
- for (const e of entries) {
3501
- if (e.resolution === void 0) continue;
3502
- const pixels = e.resolution.width * e.resolution.height;
3503
- if (pixels >= targetPixels) {
3504
- if (!bestAbove || pixels < bestAbove.pixels) bestAbove = {
3505
- entry: e,
3506
- pixels
3507
- };
3508
- } else if (!bestBelow || pixels > bestBelow.pixels) bestBelow = {
3509
- entry: e,
3510
- pixels
3511
- };
3512
- }
3513
- return bestAbove?.entry ?? bestBelow?.entry;
3514
- }
3515
- //#endregion
3516
- //#region src/metrics/load-series-fold.ts
3517
- /** Bucket key for rows no addon owns. Stable, so its series is continuous. */
3518
- var UNATTRIBUTED_BUCKET_KEY = "__unattributed__";
3519
- var ROOT_BUCKET_KEY = "__root__";
3520
- function bucketFor(row) {
3521
- if (row.addonId !== null) return {
3522
- key: row.addonId,
3523
- kind: "addon"
3524
- };
3525
- if (row.classification === "root") return {
3526
- key: ROOT_BUCKET_KEY,
3527
- kind: "root"
3528
- };
3529
- return {
3530
- key: UNATTRIBUTED_BUCKET_KEY,
3531
- kind: "unattributed"
3532
- };
3533
- }
3534
- /** Round to one decimal — the precision both producers already emit at. */
3535
- function deci(value) {
3536
- return Math.round(value * 10) / 10;
3537
- }
3538
- /**
3539
- * Fold one snapshot into one point per function.
3540
- *
3541
- * Produces a ONE-SAMPLE point: `min === max` on every field, `samples === 1`.
3542
- * That is what lets a live event and a reduced server bucket sit in the same
3543
- * series without the consumer knowing which is which.
3544
- */
3545
- function foldSnapshotByFunction(rows, atMs) {
3546
- const acc = /* @__PURE__ */ new Map();
3547
- for (const row of rows) {
3548
- const { key, kind } = bucketFor(row);
3549
- const cur = acc.get(key) ?? {
3550
- kind,
3551
- main: 0,
3552
- gc: 0,
3553
- lifetime: 0,
3554
- memory: 0,
3555
- count: 0,
3556
- splitKnown: true
3557
- };
3558
- const known = row.cpuMainPercent !== null && row.cpuGcPercent !== null;
3559
- acc.set(key, {
3560
- kind: cur.kind,
3561
- main: cur.main + (row.cpuMainPercent ?? 0),
3562
- gc: cur.gc + (row.cpuGcPercent ?? 0),
3563
- lifetime: cur.lifetime + row.cpuPercent,
3564
- memory: cur.memory + row.memoryRssBytes,
3565
- count: cur.count + 1,
3566
- splitKnown: cur.splitKnown && known
3567
- });
3568
- }
3569
- return [...acc.entries()].map(([key, a]) => {
3570
- const main = a.splitKnown ? deci(a.main) : null;
3571
- const gc = a.splitKnown ? deci(a.gc) : null;
3572
- const lifetime = deci(a.lifetime);
3573
- return {
3574
- key,
3575
- kind: a.kind,
3576
- point: {
3577
- atMs,
3578
- samples: 1,
3579
- cpuMainPercent: main,
3580
- cpuMainPercentMin: main,
3581
- cpuGcPercent: gc,
3582
- cpuGcPercentMin: gc,
3583
- cpuLifetimePercent: lifetime,
3584
- cpuLifetimePercentMin: lifetime,
3585
- memoryRssBytes: a.memory,
3586
- memoryRssBytesMin: a.memory,
3587
- processCount: a.count,
3588
- processCountMin: a.count
3589
- }
3590
- };
3591
- });
3592
- }
3593
- /** The narrower of two bounds, treating `null` (UNKNOWN) as absorbing. */
3594
- function minNullable(a, b) {
3595
- if (a === null || b === null) return null;
3596
- return a < b ? a : b;
3597
- }
3598
- function maxNullable(a, b) {
3599
- if (a === null || b === null) return null;
3600
- return a > b ? a : b;
3601
- }
3602
- /** Merge `next` into `held`, keeping the widest [min, max] of each field. */
3603
- function mergePoints(held, next, atMs) {
3604
- return {
3605
- atMs,
3606
- samples: held.samples + next.samples,
3607
- cpuMainPercent: maxNullable(held.cpuMainPercent, next.cpuMainPercent),
3608
- cpuMainPercentMin: minNullable(held.cpuMainPercentMin, next.cpuMainPercentMin),
3609
- cpuGcPercent: maxNullable(held.cpuGcPercent, next.cpuGcPercent),
3610
- cpuGcPercentMin: minNullable(held.cpuGcPercentMin, next.cpuGcPercentMin),
3611
- cpuLifetimePercent: Math.max(held.cpuLifetimePercent, next.cpuLifetimePercent),
3612
- cpuLifetimePercentMin: Math.min(held.cpuLifetimePercentMin, next.cpuLifetimePercentMin),
3613
- memoryRssBytes: Math.max(held.memoryRssBytes, next.memoryRssBytes),
3614
- memoryRssBytesMin: Math.min(held.memoryRssBytesMin, next.memoryRssBytesMin),
3615
- processCount: Math.max(held.processCount, next.processCount),
3616
- processCountMin: Math.min(held.processCountMin, next.processCountMin)
3617
- };
3618
- }
3619
- /**
3620
- * The bucket width that brings `spanMs` down to at most `maxPoints` points,
3621
- * snapped up to a whole multiple of the sampling cadence.
3622
- *
3623
- * Returns `cadenceMs` (no reduction) when the span already fits. A caller that
3624
- * asks for a `maxPoints` of 0 or less gets no reduction rather than an
3625
- * infinite bucket — a nonsensical request must not produce a plausible chart.
3626
- */
3627
- function resolveBucketMs(spanMs, cadenceMs, maxPoints) {
3628
- if (maxPoints <= 0 || cadenceMs <= 0 || spanMs <= 0) return Math.max(cadenceMs, 1);
3629
- const wanted = spanMs / maxPoints;
3630
- if (wanted <= cadenceMs) return cadenceMs;
3631
- return Math.ceil(wanted / cadenceMs) * cadenceMs;
3632
- }
3633
- /**
3634
- * Reduce one function's points into buckets of `bucketMs`, preserving the
3635
- * extremes.
3636
- *
3637
- * Points are expected oldest-first and are returned oldest-first. A bucket
3638
- * with no samples is ABSENT — not zero, not interpolated, not the previous
3639
- * value held over.
3640
- */
3641
- function reducePoints(points, bucketMs, origin) {
3642
- if (bucketMs <= 0 || points.length === 0) return points;
3643
- const buckets = /* @__PURE__ */ new Map();
3644
- for (const point of points) {
3645
- const start = origin + Math.floor((point.atMs - origin) / bucketMs) * bucketMs;
3646
- const held = buckets.get(start);
3647
- buckets.set(start, held === void 0 ? {
3648
- ...point,
3649
- atMs: start
3650
- } : mergePoints(held, point, start));
3651
- }
3652
- return [...buckets.values()].toSorted((a, b) => a.atMs - b.atMs);
3653
- }
3654
- //#endregion
3655
- //#region src/metrics/failure-counters.ts
3327
+ //#region src/logging/log-channel.ts
3656
3328
  /**
3657
- * `FailureCounters` — the per-camera counter every "how often does this camera
3658
- * lose work, and why" question is answered from.
3659
- *
3660
- * ## Why a primitive and not four counters
3661
- *
3662
- * Four open failure modes were being triaged on 2026-08-28 and every one of
3663
- * them was measured the same way: grep a log line, count it, and then guess at
3664
- * the denominator. The guess is the defect. `enrichment crop native miss` read
3665
- * as "35x worse than yesterday" and turned out to be **flat all day** the
3666
- * moment it was divided by the successes on the same path — 0.25 misses per
3667
- * landed capture, 0.08–0.33 across twelve hours, no trend. The count moved
3668
- * because the traffic moved.
3669
- *
3670
- * So the unit here is not a counter. It is a **ratio with its denominator
3671
- * attached**: {@link FailureCounterSample.attempts} is incremented on every
3672
- * try, {@link FailureCounterSample.succeeded} on the ones that landed, and the
3673
- * reasons partition the rest. A consumer can always divide; it can never
3674
- * un-divide a bare count.
3675
- *
3676
- * ## Per camera, always
3329
+ * Per-component log CHANNELS — the gate a hot path consults, and the registry
3330
+ * an addon declares its channels in.
3677
3331
  *
3678
- * The key is the numeric `deviceId` — the same value every log line in this
3679
- * repo carries as `tags.deviceId`. There is no fleet-total mode and no
3680
- * device-less bucket, because the question is always "why is 617 worse than
3681
- * 615?" and a fleet total cannot answer it. A caller that cannot name the
3682
- * camera must not note anything: an unnamed per-camera count is
3683
- * indistinguishable from a shared one, which is how one camera's failures
3684
- * quietly become everybody's.
3332
+ * ## Two axes, deliberately separated
3685
3333
  *
3686
- * ## Cumulative, never drained
3334
+ * - **DECLARATION** — which channels exist. Only the addon knows:
3335
+ * `stream-broker` knows webrtc/ICE/RTP, `provider-reolink` knows
3336
+ * baichuan/handshake. A hand-wired central list rots at the first addition,
3337
+ * and rots silently. So a channel is declared where it is consulted, and the
3338
+ * `log-channels` capability enumerates the declarations.
3339
+ * - **VALUE** — at which level, for which scope, until when. That stays ONE
3340
+ * thing: the logging settings document on the `system` cap. Two authorities
3341
+ * over the values is the exact defect
3342
+ * `docs/design/plans/2026-08-26-logging-per-componente.md` was written to
3343
+ * remove; re-introducing it from the cure side would be grotesque.
3687
3344
  *
3688
- * A read NEVER resets anything. `load-contribution.cap.ts` already argued this
3689
- * for CPU seconds and the argument carries over verbatim: *"a rate needs a
3690
- * window, a window needs a sampler, and a new per-node sampler is the defect
3691
- * half of `docs/architecture/load-ledger.md` documents. A counter can be
3692
- * differenced by whoever already keeps a history; a rate cannot be
3693
- * un-averaged."* A draining read has a second failure this surface cannot
3694
- * afford — two consumers polling it would each destroy half of the other's
3695
- * numbers, silently.
3345
+ * Nothing in this file reads a clock, an env var or a store. The registry is
3346
+ * a MIRROR: it is moved only by {@link LogChannelRegistry.apply}, called off
3347
+ * the hot path with a value somebody actually read, and by
3348
+ * {@link LogChannelRegistry.tick}, called on a timer. A store read that fails
3349
+ * never reaches here, so it can neither disarm an armed channel nor arm a
3350
+ * disarmed one (D49).
3696
3351
  *
3697
- * {@link FailureCounterSample.sinceMs} is the incarnation marker: it is when
3698
- * this counter started, and a consumer differencing two reads must drop the
3699
- * interval when it changes, because the counter restarted from zero in a new
3700
- * process.
3352
+ * ## The canonical call shape
3701
3353
  *
3702
- * ## Bounded, and the bound is the point
3354
+ * ```ts
3355
+ * if (CH_RTP.on && CH_RTP.wants(deviceId)) {
3356
+ * CH_RTP.log(logger, 'rtp subscriber added', { tags: { deviceId }, meta: { ssrc } })
3357
+ * }
3358
+ * ```
3703
3359
  *
3704
- * This lives in the memory of a process that is already the subject of an RSS
3705
- * budget, so both dimensions are capped: {@link MAX_KEYS} counters and
3706
- * {@link MAX_REASONS_PER_KEY} distinct reasons within one. Past the reason cap
3707
- * the counts are folded into {@link OVERFLOW_REASON} rather than dropped —
3708
- * losing them would make `attempts - succeeded` stop equalling the reason
3709
- * total, and the ratio the whole surface exists to publish would quietly stop
3710
- * adding up. Past the key cap a new key is refused and
3711
- * {@link FailureCounters.keysRefused} says so, so the omission is visible
3712
- * instead of silent.
3360
+ * `on` is a plain boolean FIELD — never a getter — and it is the FIRST thing
3361
+ * read. Disarmed, a call site costs one load and one branch, and the `extras`
3362
+ * object literal is never constructed because it lives inside the branch. It
3363
+ * is the same shape already proven in production at `stream-broker.ts:1650`,
3364
+ * and the same discipline `LoggingGate.allowsDestination` uses for the
3365
+ * destination floor (measured at 1.93 ns/call when off).
3713
3366
  *
3714
- * ## No timers, no IO, no logging
3367
+ * ## Why a channel emits at `info`
3715
3368
  *
3716
- * Pure. It is read on whatever beat the caller already has. A telemetry
3717
- * primitive that schedules its own work is a second sampler, and this repo has
3718
- * paid for one of those already (`docs/architecture/load-ledger.md`).
3369
+ * `loki-logging.addon.ts` pins the destination default at `info` and
3370
+ * `loki-destination.ts` drops everything below it, so a line emitted at
3371
+ * `debug` never reaches Loki and the hub's in-memory ring only holds ~35
3372
+ * minutes. A diagnostic that cannot be read an hour later is worse than no
3373
+ * diagnostic, because it looks done. {@link LogChannelGate.log} therefore
3374
+ * emits at the channel's declared level, whose schema floor is `info`.
3719
3375
  */
3720
- /** Distinct reason strings kept per counter before folding. */
3721
- var MAX_REASONS_PER_KEY = 16;
3722
3376
  /**
3723
- * Distinct (device, family, variant) counters one instance will hold.
3377
+ * The level a channel writes at once armed.
3724
3378
  *
3725
- * A large fleet x the handful of families any single addon reports, with
3726
- * slack. At ~200 B per counter this is a ~100 KB ceiling on a process that
3727
- * already declares an RSS budget in the gigabytes.
3379
+ * `debug` is absent ON PURPOSE and not by omission: below `info` the line does
3380
+ * not leave the process for Loki, and the whole point of arming a channel is
3381
+ * to read it later.
3728
3382
  */
3729
- var MAX_KEYS = 1024;
3383
+ var LogChannelLevelSchema = zod.z.enum([
3384
+ "info",
3385
+ "warn",
3386
+ "error"
3387
+ ]);
3730
3388
  /**
3731
- * Where reasons past {@link MAX_REASONS_PER_KEY} go.
3389
+ * What an addon declares about one channel. No value, no state — a
3390
+ * declaration is inert.
3391
+ */
3392
+ var LogChannelDescriptorSchema = zod.z.object({
3393
+ /**
3394
+ * Dotted `area.thing`, unique across the workspace. `area` is conventionally
3395
+ * the addon's short name so an operator reading a channel list can tell who
3396
+ * owns it without a second lookup.
3397
+ */
3398
+ name: zod.z.string().min(3).regex(/^[a-z0-9-]+(\.[a-z0-9-]+)+$/, "a channel name is dotted lower-kebab, e.g. area.thing"),
3399
+ /** One sentence: what the operator will SEE after arming it. */
3400
+ description: zod.z.string().min(1),
3401
+ /** The level its lines are emitted at. Never below `info`. */
3402
+ defaultLevel: LogChannelLevelSchema,
3403
+ /**
3404
+ * Whether this channel can be narrowed to a camera.
3405
+ *
3406
+ * `true` is a PROMISE with two halves, and both must hold: the gate is
3407
+ * consulted with the numeric device id, AND every line the channel admits
3408
+ * carries `tags: { deviceId }` with that same numeric id. The second half is
3409
+ * what makes `| json | deviceId="617"` work in Loki — `loki-payload.ts`
3410
+ * keeps `deviceId` out of the stream labels for cardinality, so the tag in
3411
+ * the body is the only way to filter.
3412
+ *
3413
+ * A channel whose lines carry the device only in `meta` (or not at all) is
3414
+ * declared `false`. Declaring it `true` anyway would be a lie the UI repeats:
3415
+ * the operator narrows to one camera, sees nothing, and concludes the code
3416
+ * path was never taken.
3417
+ */
3418
+ perDevice: zod.z.boolean()
3419
+ });
3420
+ /**
3421
+ * An armed window over one channel, as the document hands it to a mirror.
3732
3422
  *
3733
- * They are FOLDED, never dropped: `attempts - succeeded` must always equal the
3734
- * sum of the reason counts, or the ratio stops adding up.
3423
+ * A window is a DEADLINE, never a flag (ADR-0244): a channel somebody forgot
3424
+ * expires by itself, which is the one failure a boolean cannot avoid.
3735
3425
  */
3736
- var OVERFLOW_REASON = "other";
3737
- /** `deviceId` + `family` + optional `variant`, flattened into the map key. */
3738
- function counterKey(deviceId, family, variant) {
3739
- return variant === void 0 ? `${deviceId}${family}` : `${deviceId}${family}${variant}`;
3740
- }
3426
+ var LogChannelWindowSchema = zod.z.object({
3427
+ channel: zod.z.string().min(1),
3428
+ /** Epoch ms the window closes at. */
3429
+ armedUntilMs: zod.z.number(),
3430
+ /** `null` = every camera. A non-empty list narrows to those numeric ids. */
3431
+ deviceIds: zod.z.array(zod.z.number().int()).readonly().nullable()
3432
+ });
3741
3433
  /**
3742
- * A bounded set of per-camera, cumulative failure counters.
3434
+ * The gate a hot path holds.
3743
3435
  *
3744
- * One instance per contributing subsystem. `note` is O(1) and allocation-free
3745
- * on the steady path; `snapshot` reads without mutating anything.
3436
+ * Obtain it ONCE — at module scope or in a constructor — and keep the
3437
+ * reference. Looking a channel up by name per line would put a Map lookup on
3438
+ * the path this class exists to keep free.
3746
3439
  */
3747
- var FailureCounters = class {
3748
- maxKeys;
3749
- maxReasons;
3750
- counters = /* @__PURE__ */ new Map();
3751
- refused = 0;
3752
- constructor(maxKeys = MAX_KEYS, maxReasons = 16) {
3753
- this.maxKeys = maxKeys;
3754
- this.maxReasons = maxReasons;
3755
- }
3440
+ var LogChannelGate = class {
3441
+ descriptor;
3756
3442
  /**
3757
- * Counters refused because {@link MAX_KEYS} was already held.
3443
+ * HOT PATH GUARD. A plain data FIELD, and it must stay one.
3758
3444
  *
3759
- * Cumulative for the life of the instance: a bound that bit is a fact about
3760
- * the deployment, and a surface that hid it would under-report a fleet
3761
- * precisely when the fleet got large enough to matter.
3445
+ * `log-channel.spec.ts` asserts the property descriptor has no getter and
3446
+ * booby-traps the device set, so turning this into an accessor — or reading
3447
+ * anything before it — fails the spec instead of taxing every line the
3448
+ * process emits.
3762
3449
  */
3763
- get keysRefused() {
3764
- return this.refused;
3450
+ on = false;
3451
+ /** `null` while armed for every camera. Never read while `on` is false. */
3452
+ devices = null;
3453
+ level;
3454
+ closesAtMs = 0;
3455
+ constructor(descriptor) {
3456
+ this.descriptor = descriptor;
3457
+ this.level = descriptor.defaultLevel;
3765
3458
  }
3766
- /** Counters currently held. */
3767
- get size() {
3768
- return this.counters.size;
3459
+ /** Epoch ms this channel disarms itself at. 0 when disarmed. */
3460
+ get armedUntilMs() {
3461
+ return this.on ? this.closesAtMs : 0;
3769
3462
  }
3770
3463
  /**
3771
- * Fold one observation in.
3464
+ * Does this channel want a line about `deviceId`?
3772
3465
  *
3773
- * A non-positive or non-integer `deviceId` is REFUSED rather than bucketed:
3774
- * see the module docblock — an entry that cannot name its camera is worse
3775
- * than no entry.
3466
+ * Call it only behind `gate.on &&`. On its own it is still correct — the
3467
+ * guard is repeated inside — but the point of the prefix is that a disarmed
3468
+ * channel must not pay the call at all.
3776
3469
  */
3777
- note(observation, nowMs) {
3778
- if (!Number.isInteger(observation.deviceId) || observation.deviceId <= 0) return;
3779
- const key = counterKey(observation.deviceId, observation.family, observation.variant);
3780
- let counter = this.counters.get(key);
3781
- if (counter === void 0) {
3782
- if (this.counters.size >= this.maxKeys) {
3783
- this.refused += 1;
3784
- return;
3785
- }
3786
- counter = {
3787
- deviceId: observation.deviceId,
3788
- family: observation.family,
3789
- variant: observation.variant,
3790
- sinceMs: nowMs,
3791
- attempts: 0,
3792
- succeeded: 0,
3793
- reasons: /* @__PURE__ */ new Map()
3794
- };
3795
- this.counters.set(key, counter);
3796
- }
3797
- counter.attempts += 1;
3798
- if (observation.reason === void 0) {
3799
- counter.succeeded += 1;
3800
- return;
3801
- }
3802
- const reason = counter.reasons.has(observation.reason) || counter.reasons.size < this.maxReasons ? observation.reason : OVERFLOW_REASON;
3803
- counter.reasons.set(reason, (counter.reasons.get(reason) ?? 0) + 1);
3470
+ wants(deviceId) {
3471
+ if (!this.on) return false;
3472
+ return this.devices === null || this.devices.has(deviceId);
3804
3473
  }
3805
- /** Read every counter. Never mutates — see the module docblock. */
3806
- snapshot(nowMs) {
3807
- const out = [];
3808
- for (const counter of this.counters.values()) out.push({
3809
- deviceId: counter.deviceId,
3810
- family: counter.family,
3811
- ...counter.variant !== void 0 ? { variant: counter.variant } : {},
3474
+ /**
3475
+ * Emit one line on this channel, at the channel's declared level.
3476
+ *
3477
+ * The channel name is added as `tags.logChannel` so LogQL can select the
3478
+ * channel without matching on the message text, and whatever `tags` the
3479
+ * caller passed — `deviceId` above all — is preserved.
3480
+ */
3481
+ log(logger, message, extras) {
3482
+ if (!this.on) return;
3483
+ const tags = {
3484
+ ...extras.tags,
3485
+ logChannel: this.descriptor.name
3486
+ };
3487
+ const line = {
3488
+ ...extras,
3489
+ tags
3490
+ };
3491
+ if (this.level === "error") logger.error(message, line);
3492
+ else if (this.level === "warn") logger.warn(message, line);
3493
+ else logger.info(message, line);
3494
+ }
3495
+ /**
3496
+ * Arm (or RE-arm, restarting) this channel. Off the hot path only.
3497
+ *
3498
+ * An empty `deviceIds` list is treated as "every camera" rather than "no
3499
+ * camera": a window that matches nothing is indistinguishable from a
3500
+ * disarmed one, and the operator who asked for it would wait for lines that
3501
+ * can never come.
3502
+ */
3503
+ arm(window) {
3504
+ const ids = window.deviceIds;
3505
+ this.devices = ids === null || ids.length === 0 ? null : new Set(ids);
3506
+ this.closesAtMs = window.armedUntilMs;
3507
+ this.on = true;
3508
+ }
3509
+ /** Disarm. Off the hot path only. */
3510
+ disarm() {
3511
+ this.on = false;
3512
+ this.devices = null;
3513
+ this.closesAtMs = 0;
3514
+ }
3515
+ };
3516
+ /**
3517
+ * Every channel this PROCESS declares, and the mirror of what is armed on it.
3518
+ *
3519
+ * One per process. A forked runner has its own, and it is refreshed through
3520
+ * the `log-channels` capability by the hub that owns the document — the
3521
+ * registry never reaches for a value itself.
3522
+ */
3523
+ var LogChannelRegistry = class {
3524
+ gates = /* @__PURE__ */ new Map();
3525
+ /**
3526
+ * Declare a channel and get its gate.
3527
+ *
3528
+ * A duplicate name throws. Two declarations of one name is a programming
3529
+ * error, not a merge: the operator would arm one and the other would stay
3530
+ * dark, which is the dead-knob shape (D62) with an extra step.
3531
+ */
3532
+ declare(descriptor) {
3533
+ const parsed = LogChannelDescriptorSchema.parse(descriptor);
3534
+ if (this.gates.get(parsed.name) !== void 0) throw new Error(`log channel "${parsed.name}" is already declared in this process — two declarations of one name is a programming error, not a merge`);
3535
+ const gate = new LogChannelGate(parsed);
3536
+ this.gates.set(parsed.name, gate);
3537
+ return gate;
3538
+ }
3539
+ /** The declarations, sorted by name so a list is stable to read and diff. */
3540
+ list() {
3541
+ return [...this.gates.values()].map((gate) => gate.descriptor).sort((a, b) => a.name.localeCompare(b.name));
3542
+ }
3543
+ /** The gate for a declared channel, or `undefined`. */
3544
+ gate(name) {
3545
+ return this.gates.get(name);
3546
+ }
3547
+ /**
3548
+ * Apply the FULL set of armed windows. Off the hot path.
3549
+ *
3550
+ * Full, not incremental, and that is the whole design: the document is the
3551
+ * authority, so a channel the document does not name is disarmed here. An
3552
+ * incremental apply would let a disarm get lost in transit and leave a
3553
+ * channel running that nobody can see is running.
3554
+ *
3555
+ * A window already past its deadline is ignored rather than armed — a
3556
+ * restore that re-armed an expired window would make a forgotten diagnostic
3557
+ * immortal across restarts.
3558
+ *
3559
+ * Returns the names it could not place, so the caller can log them: a
3560
+ * channel named in the document that this process does not declare is
3561
+ * either a typo or an addon that has not booted yet, and both deserve a
3562
+ * line rather than silence.
3563
+ */
3564
+ apply(windows, nowMs) {
3565
+ const wanted = /* @__PURE__ */ new Map();
3566
+ const unknown = [];
3567
+ for (const window of windows) {
3568
+ if (window.armedUntilMs <= nowMs) continue;
3569
+ if (!this.gates.has(window.channel)) {
3570
+ unknown.push(window.channel);
3571
+ continue;
3572
+ }
3573
+ wanted.set(window.channel, window);
3574
+ }
3575
+ for (const [name, gate] of this.gates) {
3576
+ const window = wanted.get(name);
3577
+ if (window === void 0) gate.disarm();
3578
+ else gate.arm(window);
3579
+ }
3580
+ return unknown;
3581
+ }
3582
+ /**
3583
+ * Disarm whatever has run out. Called on a timer, NEVER from a log path — a
3584
+ * diagnostic that adds a `Date.now()` to the path it is measuring measures
3585
+ * itself.
3586
+ *
3587
+ * Returns the names it closed, so the caller can write the one line that
3588
+ * says a window ended and stops "it went quiet" from reading as "the branch
3589
+ * was not taken".
3590
+ */
3591
+ tick(nowMs) {
3592
+ const closed = [];
3593
+ for (const [name, gate] of this.gates) if (gate.on && gate.armedUntilMs <= nowMs) {
3594
+ gate.disarm();
3595
+ closed.push(name);
3596
+ }
3597
+ return closed;
3598
+ }
3599
+ /** The channels armed right now, as the document would describe them. */
3600
+ armed() {
3601
+ const out = [];
3602
+ for (const [name, gate] of this.gates) if (gate.on) out.push({
3603
+ channel: name,
3604
+ armedUntilMs: gate.armedUntilMs,
3605
+ deviceIds: null
3606
+ });
3607
+ return out;
3608
+ }
3609
+ };
3610
+ //#endregion
3611
+ //#region src/logging/log-channel.singleton.ts
3612
+ /**
3613
+ * Process-wide holder for the {@link LogChannelRegistry}.
3614
+ *
3615
+ * Three call sites that never meet need the SAME instance: the hot paths that
3616
+ * declare a gate at module scope, the `log-channels` provider that enumerates
3617
+ * the declarations for the hub, and the same provider applying the windows the
3618
+ * document hands down. A registry built inside any one of them would be
3619
+ * refreshed and collected — the shape of a knob that never does anything.
3620
+ *
3621
+ * Same idiom as `logging-gate.singleton.ts` and
3622
+ * `http-request-census.singleton.ts`.
3623
+ */
3624
+ var instance = null;
3625
+ /** The process-wide log channel registry. Created empty on first use. */
3626
+ function getLogChannelRegistry() {
3627
+ instance ??= new LogChannelRegistry();
3628
+ return instance;
3629
+ }
3630
+ /**
3631
+ * Declare a channel on the process-wide registry and get its gate.
3632
+ *
3633
+ * The one call an addon makes. Keep the returned gate in a module-scope
3634
+ * `const`: looking a channel up by name per line would put a Map lookup on
3635
+ * exactly the path this mechanism exists to keep free.
3636
+ *
3637
+ * `scripts/check-log-channel-gated.ts` reads these call sites. It pairs the
3638
+ * declared name with the binding it is assigned to and refuses to let a
3639
+ * channel ship that no `<binding>.on` anywhere consults — a declared channel
3640
+ * nobody reads is a knob the operator turns with nothing happening, forever,
3641
+ * and without a line. That is D62, and this repo has now shipped it three
3642
+ * times (`audioThresholdDbfs`, the HA entities with no source, the second
3643
+ * per-camera switch that wrote a store nobody read).
3644
+ */
3645
+ function declareLogChannel(descriptor) {
3646
+ return getLogChannelRegistry().declare(descriptor);
3647
+ }
3648
+ /** Test-only: drop the instance so a spec starts from an empty registry. */
3649
+ function __resetLogChannelRegistryForTests() {
3650
+ instance = null;
3651
+ }
3652
+ //#endregion
3653
+ //#region src/logging/log-channel-provider.ts
3654
+ /**
3655
+ * How often expiry is noticed. Coarse on purpose: the cost of a channel
3656
+ * running a few seconds past its deadline is a few extra lines, and the cost
3657
+ * of a tight timer in every addon process is paid forever.
3658
+ */
3659
+ var LOG_CHANNEL_TICK_MS = 5e3;
3660
+ /**
3661
+ * Build the `log-channels` provider for this process.
3662
+ *
3663
+ * `logger` is used ONLY off the hot path — for the arm/expiry lines — so a
3664
+ * channel that is never armed costs this module nothing but a timer.
3665
+ */
3666
+ function createLogChannelsProvider(logger, options = {}) {
3667
+ const registry = getLogChannelRegistry();
3668
+ const now = options.now ?? Date.now;
3669
+ const tickMs = options.tickMs ?? 5e3;
3670
+ const timer = setInterval(() => {
3671
+ const closed = registry.tick(now());
3672
+ for (const name of closed) logger.info("log channel window closed", {
3673
+ tags: { logChannel: name },
3674
+ meta: { channel: name }
3675
+ });
3676
+ }, tickMs);
3677
+ timer.unref?.();
3678
+ return {
3679
+ list: () => registry.list(),
3680
+ apply: (input) => {
3681
+ const unknown = registry.apply(input.windows, now());
3682
+ const armed = registry.armed();
3683
+ logger.info("log channels applied", { meta: {
3684
+ armed: armed.map((window) => window.channel),
3685
+ unknown,
3686
+ declared: registry.list().length
3687
+ } });
3688
+ return {
3689
+ armed: armed.length,
3690
+ unknown
3691
+ };
3692
+ },
3693
+ stop: () => {
3694
+ clearInterval(timer);
3695
+ }
3696
+ };
3697
+ }
3698
+ //#endregion
3699
+ //#region src/metrics/failure-counters.ts
3700
+ /**
3701
+ * `FailureCounters` — the per-camera counter every "how often does this camera
3702
+ * lose work, and why" question is answered from.
3703
+ *
3704
+ * ## Why a primitive and not four counters
3705
+ *
3706
+ * Four open failure modes were being triaged on 2026-08-28 and every one of
3707
+ * them was measured the same way: grep a log line, count it, and then guess at
3708
+ * the denominator. The guess is the defect. `enrichment crop native miss` read
3709
+ * as "35x worse than yesterday" and turned out to be **flat all day** the
3710
+ * moment it was divided by the successes on the same path — 0.25 misses per
3711
+ * landed capture, 0.08–0.33 across twelve hours, no trend. The count moved
3712
+ * because the traffic moved.
3713
+ *
3714
+ * So the unit here is not a counter. It is a **ratio with its denominator
3715
+ * attached**: {@link FailureCounterSample.attempts} is incremented on every
3716
+ * try, {@link FailureCounterSample.succeeded} on the ones that landed, and the
3717
+ * reasons partition the rest. A consumer can always divide; it can never
3718
+ * un-divide a bare count.
3719
+ *
3720
+ * ## Per camera, always
3721
+ *
3722
+ * The key is the numeric `deviceId` — the same value every log line in this
3723
+ * repo carries as `tags.deviceId`. There is no fleet-total mode and no
3724
+ * device-less bucket, because the question is always "why is 617 worse than
3725
+ * 615?" and a fleet total cannot answer it. A caller that cannot name the
3726
+ * camera must not note anything: an unnamed per-camera count is
3727
+ * indistinguishable from a shared one, which is how one camera's failures
3728
+ * quietly become everybody's.
3729
+ *
3730
+ * ## Cumulative, never drained
3731
+ *
3732
+ * A read NEVER resets anything. `load-contribution.cap.ts` already argued this
3733
+ * for CPU seconds and the argument carries over verbatim: *"a rate needs a
3734
+ * window, a window needs a sampler, and a new per-node sampler is the defect
3735
+ * half of `docs/architecture/load-ledger.md` documents. A counter can be
3736
+ * differenced by whoever already keeps a history; a rate cannot be
3737
+ * un-averaged."* A draining read has a second failure this surface cannot
3738
+ * afford — two consumers polling it would each destroy half of the other's
3739
+ * numbers, silently.
3740
+ *
3741
+ * {@link FailureCounterSample.sinceMs} is the incarnation marker: it is when
3742
+ * this counter started, and a consumer differencing two reads must drop the
3743
+ * interval when it changes, because the counter restarted from zero in a new
3744
+ * process.
3745
+ *
3746
+ * ## Bounded, and the bound is the point
3747
+ *
3748
+ * This lives in the memory of a process that is already the subject of an RSS
3749
+ * budget, so both dimensions are capped: {@link MAX_KEYS} counters and
3750
+ * {@link MAX_REASONS_PER_KEY} distinct reasons within one. Past the reason cap
3751
+ * the counts are folded into {@link OVERFLOW_REASON} rather than dropped —
3752
+ * losing them would make `attempts - succeeded` stop equalling the reason
3753
+ * total, and the ratio the whole surface exists to publish would quietly stop
3754
+ * adding up. Past the key cap a new key is refused and
3755
+ * {@link FailureCounters.keysRefused} says so, so the omission is visible
3756
+ * instead of silent.
3757
+ *
3758
+ * ## No timers, no IO, no logging
3759
+ *
3760
+ * Pure. It is read on whatever beat the caller already has. A telemetry
3761
+ * primitive that schedules its own work is a second sampler, and this repo has
3762
+ * paid for one of those already (`docs/architecture/load-ledger.md`).
3763
+ */
3764
+ /** Distinct reason strings kept per counter before folding. */
3765
+ var MAX_REASONS_PER_KEY = 16;
3766
+ /**
3767
+ * Distinct (device, family, variant) counters one instance will hold.
3768
+ *
3769
+ * A large fleet x the handful of families any single addon reports, with
3770
+ * slack. At ~200 B per counter this is a ~100 KB ceiling on a process that
3771
+ * already declares an RSS budget in the gigabytes.
3772
+ */
3773
+ var MAX_KEYS = 1024;
3774
+ /**
3775
+ * Where reasons past {@link MAX_REASONS_PER_KEY} go.
3776
+ *
3777
+ * They are FOLDED, never dropped: `attempts - succeeded` must always equal the
3778
+ * sum of the reason counts, or the ratio stops adding up.
3779
+ */
3780
+ var OVERFLOW_REASON = "other";
3781
+ /** `deviceId` + `family` + optional `variant`, flattened into the map key. */
3782
+ function counterKey(deviceId, family, variant) {
3783
+ return variant === void 0 ? `${deviceId}${family}` : `${deviceId}${family}${variant}`;
3784
+ }
3785
+ /**
3786
+ * A bounded set of per-camera, cumulative failure counters.
3787
+ *
3788
+ * One instance per contributing subsystem. `note` is O(1) and allocation-free
3789
+ * on the steady path; `snapshot` reads without mutating anything.
3790
+ */
3791
+ var FailureCounters = class {
3792
+ maxKeys;
3793
+ maxReasons;
3794
+ counters = /* @__PURE__ */ new Map();
3795
+ refused = 0;
3796
+ constructor(maxKeys = MAX_KEYS, maxReasons = 16) {
3797
+ this.maxKeys = maxKeys;
3798
+ this.maxReasons = maxReasons;
3799
+ }
3800
+ /**
3801
+ * Counters refused because {@link MAX_KEYS} was already held.
3802
+ *
3803
+ * Cumulative for the life of the instance: a bound that bit is a fact about
3804
+ * the deployment, and a surface that hid it would under-report a fleet
3805
+ * precisely when the fleet got large enough to matter.
3806
+ */
3807
+ get keysRefused() {
3808
+ return this.refused;
3809
+ }
3810
+ /** Counters currently held. */
3811
+ get size() {
3812
+ return this.counters.size;
3813
+ }
3814
+ /**
3815
+ * Fold one observation in.
3816
+ *
3817
+ * A non-positive or non-integer `deviceId` is REFUSED rather than bucketed:
3818
+ * see the module docblock — an entry that cannot name its camera is worse
3819
+ * than no entry.
3820
+ */
3821
+ note(observation, nowMs) {
3822
+ if (!Number.isInteger(observation.deviceId) || observation.deviceId <= 0) return;
3823
+ const key = counterKey(observation.deviceId, observation.family, observation.variant);
3824
+ let counter = this.counters.get(key);
3825
+ if (counter === void 0) {
3826
+ if (this.counters.size >= this.maxKeys) {
3827
+ this.refused += 1;
3828
+ return;
3829
+ }
3830
+ counter = {
3831
+ deviceId: observation.deviceId,
3832
+ family: observation.family,
3833
+ variant: observation.variant,
3834
+ sinceMs: nowMs,
3835
+ attempts: 0,
3836
+ succeeded: 0,
3837
+ reasons: /* @__PURE__ */ new Map()
3838
+ };
3839
+ this.counters.set(key, counter);
3840
+ }
3841
+ counter.attempts += 1;
3842
+ if (observation.reason === void 0) {
3843
+ counter.succeeded += 1;
3844
+ return;
3845
+ }
3846
+ const reason = counter.reasons.has(observation.reason) || counter.reasons.size < this.maxReasons ? observation.reason : OVERFLOW_REASON;
3847
+ counter.reasons.set(reason, (counter.reasons.get(reason) ?? 0) + 1);
3848
+ }
3849
+ /** Read every counter. Never mutates — see the module docblock. */
3850
+ snapshot(nowMs) {
3851
+ const out = [];
3852
+ for (const counter of this.counters.values()) out.push({
3853
+ deviceId: counter.deviceId,
3854
+ family: counter.family,
3855
+ ...counter.variant !== void 0 ? { variant: counter.variant } : {},
3812
3856
  sinceMs: counter.sinceMs,
3813
3857
  atMs: nowMs,
3814
3858
  attempts: counter.attempts,
@@ -3836,64 +3880,259 @@ function failureRate(sample) {
3836
3880
  return (sample.attempts - sample.succeeded) / sample.attempts;
3837
3881
  }
3838
3882
  //#endregion
3839
- //#region src/types/model-variant-groups.ts
3840
- var FORMAT_KEYS = [
3841
- "onnx",
3842
- "coreml",
3843
- "openvino",
3844
- "tflite",
3845
- "pt"
3846
- ];
3847
- /**
3848
- * Display spelling of a family. Uppercasing the id is wrong for any family
3849
- * whose name is not all-caps — it rendered `yolov9` as "YOLOV9", a word the
3850
- * product uses nowhere else (the catalog, the docs and the model files all say
3851
- * "YOLOv9").
3852
- */
3853
- var FAMILY_LABEL = {
3854
- yolo26: "YOLO26",
3855
- yolov9: "YOLOv9"
3856
- };
3857
- function familyLabel(family) {
3858
- return FAMILY_LABEL[family] ?? family.toUpperCase();
3883
+ //#region src/metrics/load-series-fold.ts
3884
+ /** Bucket key for rows no addon owns. Stable, so its series is continuous. */
3885
+ var UNATTRIBUTED_BUCKET_KEY = "__unattributed__";
3886
+ var ROOT_BUCKET_KEY = "__root__";
3887
+ function bucketFor(row) {
3888
+ if (row.addonId !== null) return {
3889
+ key: row.addonId,
3890
+ kind: "addon"
3891
+ };
3892
+ if (row.classification === "root") return {
3893
+ key: ROOT_BUCKET_KEY,
3894
+ kind: "root"
3895
+ };
3896
+ return {
3897
+ key: UNATTRIBUTED_BUCKET_KEY,
3898
+ kind: "unattributed"
3899
+ };
3900
+ }
3901
+ /** Round to one decimal — the precision both producers already emit at. */
3902
+ function deci(value) {
3903
+ return Math.round(value * 10) / 10;
3859
3904
  }
3860
- /** `@640`, `@320×320`, `@ 256` — a resolution stated inside a model name. */
3861
- var RESOLUTION_IN_NAME = /\s*@\s*\d+\s*(?:[x×]\s*\d+)?/gi;
3862
3905
  /**
3863
- * Strip a leading family label AND any stated resolution from a base model name
3864
- * → clean tier label.
3906
+ * Fold one snapshot into one point per function.
3865
3907
  *
3866
- * The resolution strip is not cosmetic. The tier is chosen BEFORE the
3867
- * resolution chip, and a family whose builds all state their input (our yolov9
3868
- * ships only 320 and 640, no resolution-less build) made the tier inherit its
3869
- * base entry's name verbatim: the ladder read "Tiny @640 / Small @640 / …" and
3870
- * kept saying 640 while the operator had 320 selected below it.
3908
+ * Produces a ONE-SAMPLE point: `min === max` on every field, `samples === 1`.
3909
+ * That is what lets a live event and a reduced server bucket sit in the same
3910
+ * series without the consumer knowing which is which.
3871
3911
  */
3872
- function tierLabel(family, baseName) {
3873
- const fl = familyLabel(family);
3874
- const stripped = baseName.replace(new RegExp(`^${fl}\\s+`, "i"), "").replace(RESOLUTION_IN_NAME, "").trim();
3875
- return stripped.length > 0 ? stripped : baseName;
3876
- }
3877
- function variantLabel(precision, optimization) {
3878
- const parts = [];
3879
- if (optimization === "fast") parts.push("Fast");
3880
- parts.push(precision === "int8" ? "Int8" : "Standard");
3881
- return parts.join(" · ");
3912
+ function foldSnapshotByFunction(rows, atMs) {
3913
+ const acc = /* @__PURE__ */ new Map();
3914
+ for (const row of rows) {
3915
+ const { key, kind } = bucketFor(row);
3916
+ const cur = acc.get(key) ?? {
3917
+ kind,
3918
+ main: 0,
3919
+ gc: 0,
3920
+ lifetime: 0,
3921
+ memory: 0,
3922
+ count: 0,
3923
+ splitKnown: true
3924
+ };
3925
+ const known = row.cpuMainPercent !== null && row.cpuGcPercent !== null;
3926
+ acc.set(key, {
3927
+ kind: cur.kind,
3928
+ main: cur.main + (row.cpuMainPercent ?? 0),
3929
+ gc: cur.gc + (row.cpuGcPercent ?? 0),
3930
+ lifetime: cur.lifetime + row.cpuPercent,
3931
+ memory: cur.memory + row.memoryRssBytes,
3932
+ count: cur.count + 1,
3933
+ splitKnown: cur.splitKnown && known
3934
+ });
3935
+ }
3936
+ return [...acc.entries()].map(([key, a]) => {
3937
+ const main = a.splitKnown ? deci(a.main) : null;
3938
+ const gc = a.splitKnown ? deci(a.gc) : null;
3939
+ const lifetime = deci(a.lifetime);
3940
+ return {
3941
+ key,
3942
+ kind: a.kind,
3943
+ point: {
3944
+ atMs,
3945
+ samples: 1,
3946
+ cpuMainPercent: main,
3947
+ cpuMainPercentMin: main,
3948
+ cpuGcPercent: gc,
3949
+ cpuGcPercentMin: gc,
3950
+ cpuLifetimePercent: lifetime,
3951
+ cpuLifetimePercentMin: lifetime,
3952
+ memoryRssBytes: a.memory,
3953
+ memoryRssBytesMin: a.memory,
3954
+ processCount: a.count,
3955
+ processCountMin: a.count
3956
+ }
3957
+ };
3958
+ });
3882
3959
  }
3883
- function entryFormats(entry) {
3884
- return FORMAT_KEYS.filter((f) => entry.formats[f] !== void 0);
3960
+ /** The narrower of two bounds, treating `null` (UNKNOWN) as absorbing. */
3961
+ function minNullable(a, b) {
3962
+ if (a === null || b === null) return null;
3963
+ return a < b ? a : b;
3885
3964
  }
3886
- function smallestSizeMB(entry) {
3887
- const sizes = FORMAT_KEYS.map((f) => entry.formats[f]?.sizeMB).filter((n) => typeof n === "number");
3888
- return sizes.length > 0 ? Math.min(...sizes) : 0;
3965
+ function maxNullable(a, b) {
3966
+ if (a === null || b === null) return null;
3967
+ return a > b ? a : b;
3889
3968
  }
3890
- var TIER_ORDER = [
3891
- "t",
3892
- "n",
3893
- "s",
3894
- "m",
3895
- "c",
3896
- "l",
3969
+ /** Merge `next` into `held`, keeping the widest [min, max] of each field. */
3970
+ function mergePoints(held, next, atMs) {
3971
+ return {
3972
+ atMs,
3973
+ samples: held.samples + next.samples,
3974
+ cpuMainPercent: maxNullable(held.cpuMainPercent, next.cpuMainPercent),
3975
+ cpuMainPercentMin: minNullable(held.cpuMainPercentMin, next.cpuMainPercentMin),
3976
+ cpuGcPercent: maxNullable(held.cpuGcPercent, next.cpuGcPercent),
3977
+ cpuGcPercentMin: minNullable(held.cpuGcPercentMin, next.cpuGcPercentMin),
3978
+ cpuLifetimePercent: Math.max(held.cpuLifetimePercent, next.cpuLifetimePercent),
3979
+ cpuLifetimePercentMin: Math.min(held.cpuLifetimePercentMin, next.cpuLifetimePercentMin),
3980
+ memoryRssBytes: Math.max(held.memoryRssBytes, next.memoryRssBytes),
3981
+ memoryRssBytesMin: Math.min(held.memoryRssBytesMin, next.memoryRssBytesMin),
3982
+ processCount: Math.max(held.processCount, next.processCount),
3983
+ processCountMin: Math.min(held.processCountMin, next.processCountMin)
3984
+ };
3985
+ }
3986
+ /**
3987
+ * The bucket width that brings `spanMs` down to at most `maxPoints` points,
3988
+ * snapped up to a whole multiple of the sampling cadence.
3989
+ *
3990
+ * Returns `cadenceMs` (no reduction) when the span already fits. A caller that
3991
+ * asks for a `maxPoints` of 0 or less gets no reduction rather than an
3992
+ * infinite bucket — a nonsensical request must not produce a plausible chart.
3993
+ */
3994
+ function resolveBucketMs(spanMs, cadenceMs, maxPoints) {
3995
+ if (maxPoints <= 0 || cadenceMs <= 0 || spanMs <= 0) return Math.max(cadenceMs, 1);
3996
+ const wanted = spanMs / maxPoints;
3997
+ if (wanted <= cadenceMs) return cadenceMs;
3998
+ return Math.ceil(wanted / cadenceMs) * cadenceMs;
3999
+ }
4000
+ /**
4001
+ * Reduce one function's points into buckets of `bucketMs`, preserving the
4002
+ * extremes.
4003
+ *
4004
+ * Points are expected oldest-first and are returned oldest-first. A bucket
4005
+ * with no samples is ABSENT — not zero, not interpolated, not the previous
4006
+ * value held over.
4007
+ */
4008
+ function reducePoints(points, bucketMs, origin) {
4009
+ if (bucketMs <= 0 || points.length === 0) return points;
4010
+ const buckets = /* @__PURE__ */ new Map();
4011
+ for (const point of points) {
4012
+ const start = origin + Math.floor((point.atMs - origin) / bucketMs) * bucketMs;
4013
+ const held = buckets.get(start);
4014
+ buckets.set(start, held === void 0 ? {
4015
+ ...point,
4016
+ atMs: start
4017
+ } : mergePoints(held, point, start));
4018
+ }
4019
+ return [...buckets.values()].toSorted((a, b) => a.atMs - b.atMs);
4020
+ }
4021
+ //#endregion
4022
+ //#region src/stream-selection.ts
4023
+ function pickPreferredRtspEntry(entries, pref, deviceId, options = {}) {
4024
+ if (entries.length === 0) return null;
4025
+ const prefix = `${deviceId}/`;
4026
+ const toPicked = (e) => ({
4027
+ brokerId: e.brokerId,
4028
+ profileId: e.brokerId.startsWith(prefix) ? e.brokerId.slice(prefix.length) : e.brokerId,
4029
+ url: e.url,
4030
+ mutedUrl: e.mutedUrl,
4031
+ enabled: e.enabled,
4032
+ ...e.codec !== void 0 ? { codec: e.codec } : {},
4033
+ ...e.resolution !== void 0 ? { resolution: e.resolution } : {}
4034
+ });
4035
+ if (pref !== "auto") {
4036
+ const match = entries.find((e) => e.enabled && e.url.length > 0 && (e.profile === pref || e.brokerId === `${prefix}${pref}`));
4037
+ if (match) return toPicked(match);
4038
+ }
4039
+ const eligible = entries.filter((e) => e.enabled && e.url.length > 0);
4040
+ if (eligible.length === 0) return null;
4041
+ const target = options.targetResolution;
4042
+ if (target) {
4043
+ const withRes = eligible.filter((e) => e.resolution !== void 0);
4044
+ if (withRes.length > 0) {
4045
+ const picked = pickClosestResolution(withRes, target);
4046
+ if (picked) return toPicked(picked);
4047
+ }
4048
+ }
4049
+ return toPicked(eligible[0]);
4050
+ }
4051
+ /**
4052
+ * Pick the entry whose `resolution` is closest to `target`. Prefer
4053
+ * entries ≥ target (downscale is cheap at the consumer; upscale is
4054
+ * lossy). Among the rest pick the LARGEST still ≤ target so the
4055
+ * consumer gets the best feasible quality. "Closeness" is the
4056
+ * `width × height` pixel delta.
4057
+ */
4058
+ function pickClosestResolution(entries, target) {
4059
+ const targetPixels = target.width * target.height;
4060
+ let bestAbove;
4061
+ let bestBelow;
4062
+ for (const e of entries) {
4063
+ if (e.resolution === void 0) continue;
4064
+ const pixels = e.resolution.width * e.resolution.height;
4065
+ if (pixels >= targetPixels) {
4066
+ if (!bestAbove || pixels < bestAbove.pixels) bestAbove = {
4067
+ entry: e,
4068
+ pixels
4069
+ };
4070
+ } else if (!bestBelow || pixels > bestBelow.pixels) bestBelow = {
4071
+ entry: e,
4072
+ pixels
4073
+ };
4074
+ }
4075
+ return bestAbove?.entry ?? bestBelow?.entry;
4076
+ }
4077
+ //#endregion
4078
+ //#region src/types/model-variant-groups.ts
4079
+ var FORMAT_KEYS = [
4080
+ "onnx",
4081
+ "coreml",
4082
+ "openvino",
4083
+ "tflite",
4084
+ "pt"
4085
+ ];
4086
+ /**
4087
+ * Display spelling of a family. Uppercasing the id is wrong for any family
4088
+ * whose name is not all-caps — it rendered `yolov9` as "YOLOV9", a word the
4089
+ * product uses nowhere else (the catalog, the docs and the model files all say
4090
+ * "YOLOv9").
4091
+ */
4092
+ var FAMILY_LABEL = {
4093
+ yolo26: "YOLO26",
4094
+ yolov9: "YOLOv9"
4095
+ };
4096
+ function familyLabel(family) {
4097
+ return FAMILY_LABEL[family] ?? family.toUpperCase();
4098
+ }
4099
+ /** `@640`, `@320×320`, `@ 256` — a resolution stated inside a model name. */
4100
+ var RESOLUTION_IN_NAME = /\s*@\s*\d+\s*(?:[x×]\s*\d+)?/gi;
4101
+ /**
4102
+ * Strip a leading family label AND any stated resolution from a base model name
4103
+ * → clean tier label.
4104
+ *
4105
+ * The resolution strip is not cosmetic. The tier is chosen BEFORE the
4106
+ * resolution chip, and a family whose builds all state their input (our yolov9
4107
+ * ships only 320 and 640, no resolution-less build) made the tier inherit its
4108
+ * base entry's name verbatim: the ladder read "Tiny @640 / Small @640 / …" and
4109
+ * kept saying 640 while the operator had 320 selected below it.
4110
+ */
4111
+ function tierLabel(family, baseName) {
4112
+ const fl = familyLabel(family);
4113
+ const stripped = baseName.replace(new RegExp(`^${fl}\\s+`, "i"), "").replace(RESOLUTION_IN_NAME, "").trim();
4114
+ return stripped.length > 0 ? stripped : baseName;
4115
+ }
4116
+ function variantLabel(precision, optimization) {
4117
+ const parts = [];
4118
+ if (optimization === "fast") parts.push("Fast");
4119
+ parts.push(precision === "int8" ? "Int8" : "Standard");
4120
+ return parts.join(" · ");
4121
+ }
4122
+ function entryFormats(entry) {
4123
+ return FORMAT_KEYS.filter((f) => entry.formats[f] !== void 0);
4124
+ }
4125
+ function smallestSizeMB(entry) {
4126
+ const sizes = FORMAT_KEYS.map((f) => entry.formats[f]?.sizeMB).filter((n) => typeof n === "number");
4127
+ return sizes.length > 0 ? Math.min(...sizes) : 0;
4128
+ }
4129
+ var TIER_ORDER = [
4130
+ "t",
4131
+ "n",
4132
+ "s",
4133
+ "m",
4134
+ "c",
4135
+ "l",
3897
4136
  "x"
3898
4137
  ];
3899
4138
  var PRECISION_ORDER = ["fp32", "int8"];
@@ -23148,7 +23387,6 @@ var storageCapability = {
23148
23387
  }), zod.z.instanceof(Uint8Array)),
23149
23388
  endDownload: require_sleep.method(zod.z.object({ downloadId: zod.z.string() }), zod.z.void(), { kind: "mutation" }),
23150
23389
  listLocations: require_sleep.method(zod.z.object({ type: StorageLocationTypeSchema.optional() }), zod.z.array(StorageLocationSchema).readonly()),
23151
- getDefaultLocation: require_sleep.method(zod.z.object({ type: StorageLocationTypeSchema }), StorageLocationSchema.nullable()),
23152
23390
  listLocationDeclarations: require_sleep.method(zod.z.void(), zod.z.array(StorageLocationDeclarationSchema).readonly()),
23153
23391
  upsertLocation: require_sleep.method(StorageLocationSchema.omit({
23154
23392
  createdAt: true,
@@ -23178,6 +23416,12 @@ var storageCapability = {
23178
23416
  kind: "mutation",
23179
23417
  auth: "admin"
23180
23418
  }),
23419
+ /**
23420
+ * How far each draining location has got (D386). A pure READ of what the
23421
+ * last pressure sweep computed — it starts no work, and a location that is
23422
+ * not draining simply does not appear.
23423
+ */
23424
+ listDrainProgress: require_sleep.method(zod.z.void(), zod.z.array(StorageDrainProgressSchema).readonly()),
23181
23425
  testLocation: require_sleep.method(zod.z.object({ id: zod.z.string() }), zod.z.object({
23182
23426
  ok: zod.z.boolean(),
23183
23427
  error: zod.z.string().optional()
@@ -23330,6 +23574,73 @@ var storageMigrationCapability = {
23330
23574
  }
23331
23575
  };
23332
23576
  //#endregion
23577
+ //#region src/capabilities/storage-occupancy.cap.ts
23578
+ /**
23579
+ * `storage-occupancy` — how many bytes an addon actually HOLDS on a storage
23580
+ * location (D388).
23581
+ *
23582
+ * ## Why this is not `storage-evictable`
23583
+ *
23584
+ * `storage-evictable.getEvictableUsage` looks like the same question and is
23585
+ * not, in two ways that both matter and both bite hardest on the locations an
23586
+ * operator most wants a figure for:
23587
+ *
23588
+ * - it reports the whole eviction DOMAIN, not the location. `recordings:default`
23589
+ * and `recordingsLow:default` deliberately share one root and evict as one
23590
+ * oldest-first pool, so both answer with the SAME combined total. As an
23591
+ * occupancy figure that double-counts the disk.
23592
+ * - it reports ZERO for a location whose eviction policy is `never` (D385) —
23593
+ * a `readonly` or `disabled` disk. Those are exactly the disks an operator
23594
+ * is retiring and staring at.
23595
+ *
23596
+ * So this is its own contract with its own quantity, and the quantity is
23597
+ * OCCUPIED: every byte the addon holds on that location, whether or not it
23598
+ * would ever be willing to delete it. A provider that can only answer
23599
+ * "evictable" must not register here — a number that silently means different
23600
+ * things per class is worse than no number.
23601
+ *
23602
+ * ## Absence is an answer
23603
+ *
23604
+ * A location nobody reports for is UNKNOWN, never zero (D315). The orchestrator
23605
+ * stamps `StorageLocation.owned` only for locations it has a report for, and
23606
+ * the field is an OBJECT rather than a bare number so that a `?? 0` on the
23607
+ * consuming side has to be written out loud instead of appearing by accident.
23608
+ *
23609
+ * `internal: true` — consumed by the orchestrator's `listLocations` stamp, never
23610
+ * a public client surface. Clients read the stamped `StorageLocation.owned`.
23611
+ */
23612
+ /** One provider's occupancy answer for one location. */
23613
+ var StorageOccupancyReportSchema = zod.z.object({
23614
+ locationId: zod.z.string(),
23615
+ /** Bytes this provider holds on THAT location — not its eviction domain, and
23616
+ * not net of what it is willing to delete. */
23617
+ ownedBytes: zod.z.number().int().nonnegative(),
23618
+ /** When the provider last actually measured this. The orchestrator carries it
23619
+ * through so a UI can say how old the figure is instead of implying "now". */
23620
+ measuredAtMs: zod.z.number().int().nonnegative()
23621
+ });
23622
+ var storageOccupancyCapability = {
23623
+ name: "storage-occupancy",
23624
+ scope: "system",
23625
+ mode: "collection",
23626
+ internal: true,
23627
+ methods: {
23628
+ /**
23629
+ * Occupancy for the given locations, in ONE round trip.
23630
+ *
23631
+ * A provider answers only for the locations it actually holds bytes on and
23632
+ * OMITS the rest — an omitted location is "I hold nothing measurable here",
23633
+ * which the orchestrator merges as a contribution of nothing rather than as
23634
+ * a claim that the location is empty. Only a location no provider reports
23635
+ * at all stays unknown.
23636
+ *
23637
+ * This must be CHEAP and must never walk a filesystem: it is on the admin
23638
+ * UI's `listLocations` path. The owner keeps its own figure fresh (D224) and
23639
+ * answers from what it already has.
23640
+ */
23641
+ getOccupancy: require_sleep.method(zod.z.object({ locationIds: zod.z.array(zod.z.string()).readonly() }), zod.z.array(StorageOccupancyReportSchema).readonly(), { auth: "admin" }) }
23642
+ };
23643
+ //#endregion
23333
23644
  //#region src/capabilities/storage-provider.cap.ts
23334
23645
  var ProviderInfoSchema = zod.z.discriminatedUnion("shouldSaveDiskSpace", [zod.z.object({
23335
23646
  providerId: zod.z.string().min(1),
@@ -25746,125 +26057,6 @@ onStatusChanged: { data: zod.z.object({
25746
26057
  volatileStateFields: ["lastUpdated"]
25747
26058
  };
25748
26059
  //#endregion
25749
- //#region src/capabilities/network-link.cap.ts
25750
- /**
25751
- * How a device reaches the network, and how well.
25752
- *
25753
- * NOT `connectivity`: that cap is an UPSTREAM system's binary view of whether
25754
- * an entity is reachable (a Home Assistant `binary_sensor` with
25755
- * `device_class: connectivity`). This one is the device's OWN link — the
25756
- * medium it is on and the signal it sees — the way `battery` is the device's
25757
- * own charge.
25758
- *
25759
- * `'wifi'`, `'ethernet'` and `'cellular'` are links the firmware actually
25760
- * reported. `'unknown'` is the ABSENCE of an answer — the provider has
25761
- * registered the capability but has not read the link yet (D315: unknown is
25762
- * not empty). Consumers skip it rather than draw a wire or a bar.
25763
- */
25764
- var NETWORK_LINK_TYPES = [
25765
- "wifi",
25766
- "ethernet",
25767
- "cellular",
25768
- "unknown"
25769
- ];
25770
- /**
25771
- * Network-link snapshot. Same shape for every provider (a Reolink wifi
25772
- * camera, a Home Assistant device with a signal-strength sensor, a Tapo
25773
- * plug): one slice under `device.runtimeState['network-link']`, one badge,
25774
- * one Home Assistant projection.
25775
- */
25776
- var NetworkLinkStatusSchema = zod.z.object({
25777
- /** The link the device is on. `'unknown'` = not read yet, not "no link". */
25778
- type: zod.z.enum(NETWORK_LINK_TYPES),
25779
- /**
25780
- * Link quality, 0..100 inclusive, normalised by the provider from whatever
25781
- * the firmware reports (bars, RSSI, a vendor scale). **`null` means NOT
25782
- * KNOWN or NOT APPLICABLE** — a wired link has no signal, and a wireless
25783
- * one whose reading has not landed must not be drawn at 0 %. Consumers
25784
- * SKIP a null rather than coerce it.
25785
- */
25786
- signalPercent: zod.z.number().min(0).max(100).nullable(),
25787
- /** Raw received signal strength in dBm, when the firmware reports one. */
25788
- rssiDbm: zod.z.number().optional(),
25789
- /** Network name of a wireless link, when the firmware reports it. */
25790
- ssid: zod.z.string().optional(),
25791
- /** Ms epoch of the last observation. Lets consumers reason about freshness. */
25792
- lastUpdated: zod.z.number()
25793
- });
25794
- /** The slice a provider seeds before its first read: nothing is known yet. */
25795
- var NETWORK_LINK_UNKNOWN = {
25796
- type: "unknown",
25797
- signalPercent: null,
25798
- lastUpdated: 0
25799
- };
25800
- /**
25801
- * Normalise a signal the firmware reports as BARS (0..`maxBars`) to 0..100.
25802
- * Out-of-range or non-finite input is not a reading: `null`.
25803
- */
25804
- function signalPercentFromBars(bars, maxBars) {
25805
- if (bars === void 0 || !Number.isFinite(bars) || maxBars <= 0) return null;
25806
- if (bars < 0 || bars > maxBars) return null;
25807
- return Math.round(bars / maxBars * 100);
25808
- }
25809
- /**
25810
- * Normalise an RSSI in dBm to 0..100 on the usual wifi scale: -100 dBm and
25811
- * below is 0 %, -50 dBm and above is 100 %, linear between. Non-finite or
25812
- * positive input is not an RSSI: `null`.
25813
- */
25814
- function signalPercentFromRssi(rssiDbm) {
25815
- if (rssiDbm === void 0 || !Number.isFinite(rssiDbm) || rssiDbm > 0) return null;
25816
- return Math.round((Math.min(-50, Math.max(-100, rssiDbm)) + 100) * 2);
25817
- }
25818
- var networkLinkCapability = {
25819
- name: "network-link",
25820
- scope: "device",
25821
- deviceNative: true,
25822
- mode: "singleton",
25823
- deviceTypes: [
25824
- require_sleep.DeviceType.Camera,
25825
- require_sleep.DeviceType.Sensor,
25826
- require_sleep.DeviceType.Button,
25827
- require_sleep.DeviceType.Switch,
25828
- require_sleep.DeviceType.Light,
25829
- require_sleep.DeviceType.Lock,
25830
- require_sleep.DeviceType.Siren
25831
- ],
25832
- methods: {},
25833
- events: {
25834
- /**
25835
- * Emitted whenever the cached status changes (a link switch, a signal
25836
- * reading that moved). Mirrored on the parent chain by the
25837
- * DeviceEventPropagator like `battery.onStatusChanged`.
25838
- */
25839
- onStatusChanged: { data: zod.z.object({
25840
- deviceId: zod.z.number(),
25841
- status: NetworkLinkStatusSchema
25842
- }) } },
25843
- status: {
25844
- schema: NetworkLinkStatusSchema,
25845
- kind: "push",
25846
- empty: NETWORK_LINK_UNKNOWN
25847
- },
25848
- /**
25849
- * Runtime-state slice — every provider stores the same shape under
25850
- * `device.runtimeState['network-link']`, read once by the badge and the
25851
- * Home Assistant projector regardless of the driver.
25852
- */
25853
- runtimeState: NetworkLinkStatusSchema,
25854
- /**
25855
- * Runtime-state durability: **restored** — a link reading is slow to
25856
- * change and a sleeping battery camera may not report for hours; the
25857
- * restored slice is what the badge shows until the next read.
25858
- *
25859
- * See `RuntimeStateDurability`. Enforced by
25860
- * `scripts/check-runtime-state-durability.ts`.
25861
- */
25862
- durability: "restored",
25863
- /** Clock fields: written, but excluded from the compare that decides
25864
- * whether persisting is worth a SQLite commit. */
25865
- volatileStateFields: ["lastUpdated"]
25866
- };
25867
- //#endregion
25868
26060
  //#region src/capabilities/binary.cap.ts
25869
26061
  /**
25870
26062
  * Generic boolean sensor — last-resort fallback when no domain-
@@ -29562,308 +29754,852 @@ var MotionStatusSchema = zod.z.object({
29562
29754
  autoClearAfterMs: zod.z.number().nullable()
29563
29755
  });
29564
29756
  /**
29565
- * Payload of `motion.onMotionChanged` event + the corresponding bus
29566
- * event `EventCategory.MotionOnMotionChanged`. Single source of truth
29567
- * — both the cap event surface and the bus payload type alias to this
29568
- * schema.
29757
+ * Payload of `motion.onMotionChanged` event + the corresponding bus
29758
+ * event `EventCategory.MotionOnMotionChanged`. Single source of truth
29759
+ * — both the cap event surface and the bus payload type alias to this
29760
+ * schema.
29761
+ */
29762
+ var MotionOnMotionChangedDataSchema = zod.z.object({
29763
+ deviceId: zod.z.number(),
29764
+ detected: zod.z.boolean(),
29765
+ timestamp: zod.z.number(),
29766
+ source: MotionSourceEnum,
29767
+ regions: zod.z.array(MotionRegionSchema).readonly().optional()
29768
+ });
29769
+ var motionCapability = {
29770
+ name: "motion",
29771
+ scope: "device",
29772
+ mode: "singleton",
29773
+ /**
29774
+ * Providers register per-device natives via `ctx.registerNativeCap`
29775
+ * (Hikvision/Reolink/Amcrest/Wyze/HA/Homematic/Alexa/Matter) — there is
29776
+ * NO system singleton provider. Without this flag `resolveCapMount`
29777
+ * derived `{ kind: 'singleton' }`, so `motion.getStatus`/`isDetected`
29778
+ * resolved via `registry.getSingleton('motion')` (always null) and every
29779
+ * call 412'd "provider not available" while bindings listed a live
29780
+ * `motion` native (2026-08-02). The flag routes the router through
29781
+ * `requireDeviceScoped` → `getProviderForDevice`, like `motion-trigger`,
29782
+ * `snapshot` and every other per-device native cap.
29783
+ */
29784
+ deviceNative: true,
29785
+ deviceTypes: [require_sleep.DeviceType.Camera, require_sleep.DeviceType.Sensor],
29786
+ methods: {
29787
+ /**
29788
+ * Pull the current motion state synchronously. Convenience shortcut
29789
+ * for consumers that don't need the full status object; equivalent
29790
+ * to `getStatus()?.detected ?? false`. Will likely be folded into
29791
+ * `getStatus` once the auto-injected status surface lands in every
29792
+ * consumer.
29793
+ */
29794
+ isDetected: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.boolean()) },
29795
+ events: {
29796
+ /**
29797
+ * Fires every time the runner transitions a camera between
29798
+ * `watching` and `active` phases. `source` carries which motion
29799
+ * path drove the transition; `regions` is populated only for
29800
+ * `source: 'analyzer'` (frame-diff regions from the ML motion
29801
+ * detector) — onboard sources don't carry per-frame regions
29802
+ * here (camera-provided zones / AI metadata live in dedicated
29803
+ * channels: `detection.camera-native`, future zone capability).
29804
+ *
29805
+ * Consumers that want all motion pushes (even with `detected`
29806
+ * unchanged) should subscribe to the status subscription via
29807
+ * `device-manager.subscribeDeviceStatusAggregate` instead.
29808
+ */
29809
+ onMotionChanged: { data: MotionOnMotionChangedDataSchema } },
29810
+ status: {
29811
+ schema: MotionStatusSchema,
29812
+ kind: "push"
29813
+ },
29814
+ /**
29815
+ * Runtime-state slice — the last observed motion snapshot, mirrored
29816
+ * by the kernel and readable cross-process via
29817
+ * `device.state.motion.value`. Reads never invoke the provider, so
29818
+ * UIs and other addons can poll the cached state safely.
29819
+ */
29820
+ runtimeState: MotionStatusSchema,
29821
+ /**
29822
+ * Runtime-state durability: **session** — self-clearing by construction (`autoClearAfterMs`); a restored `detected: true` is a frozen event, and the next frame re-publishes the real one.
29823
+ *
29824
+ * See `RuntimeStateDurability`. Enforced by
29825
+ * `scripts/check-runtime-state-durability.ts`.
29826
+ */
29827
+ durability: "session"
29828
+ };
29829
+ //#endregion
29830
+ //#region src/capabilities/motion-trigger.cap.ts
29831
+ /**
29832
+ * Motion-trigger toggle for accessory devices.
29833
+ *
29834
+ * "Motion trigger" means: when the parent camera detects motion, the
29835
+ * accessory activates automatically. The cap exposes a single boolean
29836
+ * — `enabled` — that drivers map to the vendor-specific firmware
29837
+ * action (Reolink: `setSirenOnMotion`, `setFloodlightOnMotion`; ONVIF
29838
+ * relay: schedule binding; …).
29839
+ *
29840
+ * The accessory still has its own `switch` cap for direct on/off; this
29841
+ * cap is independent. Toggling motion-trigger on does NOT necessarily
29842
+ * toggle the switch on — it just instructs the firmware to flip the
29843
+ * switch when motion fires.
29844
+ *
29845
+ * Driver-specific knobs (motion duration window, brightness while
29846
+ * triggered, schedule windows) live in the device's
29847
+ * `getSettingsUISchema()` instead of bloating this cap — same
29848
+ * principle as `switch` and `brightness` keeping their surface
29849
+ * minimal.
29850
+ */
29851
+ var MotionTriggerStatusSchema = zod.z.object({
29852
+ enabled: zod.z.boolean(),
29853
+ /** Ms epoch of the last operator-driven change. */
29854
+ lastChangedAt: zod.z.number()
29855
+ });
29856
+ /**
29857
+ * Persistent slice mirrored across restarts. The provider writes here
29858
+ * on every successful firmware fetch / setMotionTrigger push; the cap
29859
+ * router and admin-ui hero read straight from this snapshot via
29860
+ * `device.state.motionTrigger.value` instead of re-issuing a firmware
29861
+ * round-trip on every UI mount. `lastFetchedAt` lets the framework
29862
+ * helper (`createRuntimeStateBridge`) stale-check before deciding
29863
+ * whether to refresh from the camera.
29864
+ */
29865
+ var MotionTriggerRuntimeStateSchema = MotionTriggerStatusSchema.extend({
29866
+ /** Ms epoch of the last successful camera fetch (0 = never). */
29867
+ lastFetchedAt: zod.z.number() });
29868
+ var motionTriggerCapability = {
29869
+ name: "motion-trigger",
29870
+ scope: "device",
29871
+ deviceNative: true,
29872
+ mode: "singleton",
29873
+ deviceTypes: [
29874
+ require_sleep.DeviceType.Light,
29875
+ require_sleep.DeviceType.Siren,
29876
+ require_sleep.DeviceType.Switch
29877
+ ],
29878
+ methods: { setMotionTrigger: require_sleep.method(zod.z.object({
29879
+ deviceId: zod.z.number().int().nonnegative(),
29880
+ enabled: zod.z.boolean()
29881
+ }), zod.z.void(), {
29882
+ kind: "mutation",
29883
+ auth: "admin"
29884
+ }) },
29885
+ events: { onMotionTriggerChanged: { data: zod.z.object({
29886
+ deviceId: zod.z.number(),
29887
+ enabled: zod.z.boolean(),
29888
+ lastChangedAt: zod.z.number()
29889
+ }) } },
29890
+ status: {
29891
+ schema: MotionTriggerStatusSchema,
29892
+ kind: "command-driven"
29893
+ },
29894
+ runtimeState: MotionTriggerRuntimeStateSchema,
29895
+ /**
29896
+ * Runtime-state durability: **session** — the authority for motion-trigger enablement is the provider's own config; the slice is a mirror of it, re-published on connect.
29897
+ *
29898
+ * See `RuntimeStateDurability`. Enforced by
29899
+ * `scripts/check-runtime-state-durability.ts`.
29900
+ */
29901
+ durability: "session"
29902
+ };
29903
+ //#endregion
29904
+ //#region src/capabilities/motion-zones.cap.ts
29905
+ /**
29906
+ * Motion-zones share the same MaskShape vocabulary as privacy-mask — the
29907
+ * on-camera motion-detection mask is a single `grid` region (a row-major
29908
+ * boolean cell lattice the camera's onboard VMD evaluates). Composing it as
29909
+ * a region keeps one drawing-plane model across all geometry caps.
29910
+ */
29911
+ /** A motion-zone region — exactly one boolean cell grid today. */
29912
+ var MotionZoneRegionSchema = zod.z.object({
29913
+ id: zod.z.number(),
29914
+ enabled: zod.z.boolean(),
29915
+ shape: MaskGridShapeSchema
29916
+ });
29917
+ /** Current on-camera motion-detection state — master enable + sensitivity +
29918
+ * the grid region(s). */
29919
+ var MotionZoneStatusSchema = zod.z.object({
29920
+ enabled: zod.z.boolean(),
29921
+ sensitivity: zod.z.number(),
29922
+ /** Grid region(s). Today exactly one `grid` shape. */
29923
+ regions: zod.z.array(MotionZoneRegionSchema),
29924
+ lastFetchedAt: zod.z.number()
29925
+ });
29926
+ /** Per-camera availability — grid dims are fixed per camera model; the UI
29927
+ * sizes its editor from `grid`. */
29928
+ var MotionZoneOptionsSchema = zod.z.object({
29929
+ maxRegions: zod.z.number(),
29930
+ supportedShapes: zod.z.array(MaskShapeKindSchema),
29931
+ grid: MaskGridDimsSchema,
29932
+ sensitivity: zod.z.object({
29933
+ min: zod.z.number(),
29934
+ max: zod.z.number(),
29935
+ step: zod.z.number()
29936
+ })
29937
+ });
29938
+ /** Partial change — every field optional. */
29939
+ var MotionZonePatchSchema = zod.z.object({
29940
+ enabled: zod.z.boolean().optional(),
29941
+ sensitivity: zod.z.number().optional(),
29942
+ regions: zod.z.array(MotionZoneRegionSchema).optional()
29943
+ });
29944
+ var motionZonesCapability = {
29945
+ name: "motion-zones",
29946
+ scope: "device",
29947
+ deviceNative: true,
29948
+ mode: "singleton",
29949
+ deviceTypes: [require_sleep.DeviceType.Camera],
29950
+ deviceConfig: { ui: {
29951
+ kind: "widget",
29952
+ widgetId: "host/motion-zones-grid",
29953
+ tab: "motion",
29954
+ label: "Motion Zones"
29955
+ } },
29956
+ methods: {
29957
+ getOptions: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), MotionZoneOptionsSchema),
29958
+ setZone: require_sleep.method(zod.z.object({
29959
+ deviceId: zod.z.number(),
29960
+ patch: MotionZonePatchSchema
29961
+ }), zod.z.void(), {
29962
+ kind: "mutation",
29963
+ auth: "admin"
29964
+ })
29965
+ },
29966
+ status: {
29967
+ schema: MotionZoneStatusSchema,
29968
+ kind: "poll"
29969
+ },
29970
+ runtimeState: MotionZoneStatusSchema,
29971
+ /**
29972
+ * Runtime-state durability: **restored** — the 14 KB polygon list is the single largest slice on the fleet and has not changed since the operator drew it. Highest value per byte in the table.
29973
+ *
29974
+ * See `RuntimeStateDurability`. Enforced by
29975
+ * `scripts/check-runtime-state-durability.ts`.
29976
+ */
29977
+ durability: "restored",
29978
+ /** Clock fields: written, but excluded from the compare that decides
29979
+ * whether persisting is worth a SQLite commit. */
29980
+ volatileStateFields: ["lastFetchedAt"]
29981
+ };
29982
+ //#endregion
29983
+ //#region src/capabilities/native-object-detection.cap.ts
29984
+ /**
29985
+ * On-camera AI object detection cap. Surfaces per-device the classes
29986
+ * the firmware can detect and the last-seen instance of each. The
29987
+ * provider also fan-outs these to the global `detection.camera-native`
29988
+ * event bus with `source: 'onboard'` so cross-cutting system services
29989
+ * (alert-center, advanced-notifier, recording-engine) can subscribe
29990
+ * once and receive events from every camera.
29991
+ *
29992
+ * Distinct from `motion-detection` (ML pipeline) and `motion` (hardware
29993
+ * PIR or firmware motion pulse): this cap is specifically the AI
29994
+ * classifier output coming FROM the camera, not the local pipeline.
29995
+ */
29996
+ var NativeObjectClassEnum = zod.z.enum([
29997
+ "person",
29998
+ "vehicle",
29999
+ "animal",
30000
+ "face",
30001
+ "package",
30002
+ "other"
30003
+ ]);
30004
+ var NativeDetectionSchema = zod.z.object({
30005
+ class: NativeObjectClassEnum,
30006
+ timestamp: zod.z.number(),
30007
+ /** Firmware-provided confidence [0..1]. Reolink pushes don't carry it → undefined. */
30008
+ confidence: zod.z.number().min(0).max(1).optional()
30009
+ });
30010
+ var NativeObjectDetectionStatusSchema = zod.z.object({
30011
+ /**
30012
+ * Last observed instance per class. Missing entries mean the class
30013
+ * is supported but nothing has been seen since the provider started.
30014
+ *
30015
+ * MUST be a partial record: providers seed an empty `{}` on cold-start
30016
+ * and write one class at a time as detections arrive. In Zod 4
30017
+ * `z.record(enum, …)` is EXHAUSTIVE (requires every enum key), so a
30018
+ * partial write throws "expected object, received undefined" for every
30019
+ * unseen class. `z.partialRecord` keeps the enum-key narrowing while
30020
+ * allowing the sparse shape the providers actually write.
30021
+ */
30022
+ lastByClass: zod.z.partialRecord(NativeObjectClassEnum, NativeDetectionSchema.nullable()),
30023
+ /** Classes the firmware is capable of detecting — enumerated at device register. */
30024
+ supportedClasses: zod.z.array(NativeObjectClassEnum).readonly(),
30025
+ /**
30026
+ * Whether forwarding of onboard AI detections is enabled for this device.
30027
+ * Default FALSE (opt-in, cold-start) — onboard AI pushes are noisy/sparse and
30028
+ * churn the tracker, so forwarding stays off until the operator enables it.
30029
+ */
30030
+ enabled: zod.z.boolean()
30031
+ });
30032
+ var NativeObjectDetectionRuntimeStateSchema = NativeObjectDetectionStatusSchema.extend({
30033
+ /** Required by createRuntimeStateBridge — epoch ms of last refresh. */
30034
+ lastFetchedAt: zod.z.number() });
30035
+ var nativeObjectDetectionCapability = {
30036
+ name: "native-object-detection",
30037
+ scope: "device",
30038
+ deviceNative: true,
30039
+ mode: "singleton",
30040
+ deviceTypes: [require_sleep.DeviceType.Camera],
30041
+ methods: { setEnabled: require_sleep.method(zod.z.object({
30042
+ deviceId: zod.z.number(),
30043
+ enabled: zod.z.boolean()
30044
+ }), zod.z.void(), {
30045
+ kind: "mutation",
30046
+ auth: "admin"
30047
+ }) },
30048
+ events: { onDetected: { data: zod.z.object({
30049
+ deviceId: zod.z.number(),
30050
+ detection: NativeDetectionSchema
30051
+ }) } },
30052
+ status: {
30053
+ schema: NativeObjectDetectionStatusSchema,
30054
+ kind: "push"
30055
+ },
30056
+ runtimeState: NativeObjectDetectionRuntimeStateSchema,
30057
+ /**
30058
+ * Runtime-state durability: **restored** — `enabled` is an operator toggle on a camera whose refresh is a no-op and whose staleMs is Infinity. There is no hardware value to re-read — losing it loses the setting.
30059
+ *
30060
+ * See `RuntimeStateDurability`. Enforced by
30061
+ * `scripts/check-runtime-state-durability.ts`.
30062
+ */
30063
+ durability: "restored",
30064
+ /** Clock fields: written, but excluded from the compare that decides
30065
+ * whether persisting is worth a SQLite commit. */
30066
+ volatileStateFields: ["lastFetchedAt"]
30067
+ };
30068
+ //#endregion
30069
+ //#region src/capabilities/navigation.cap.ts
30070
+ /**
30071
+ * `navigation` — a device-scoped capability that natively expresses the FULL
30072
+ * navigation / action surface of a robot that DRIVES ITSELF and carries an
30073
+ * on-board camera (the Dreame robot-vacuum camera is the first provider).
30074
+ *
30075
+ * Why a NEW cap rather than overloading `ptz`:
30076
+ * - `ptz` moves a *gimbal* on a fixed camera (pan/tilt/zoom of the lens). A
30077
+ * robot vacuum has no gimbal — the whole chassis drives, turns and spins.
30078
+ * The two are different physical models: PTZ is absolute-position + presets,
30079
+ * navigation is momentary drive nudges + discrete robot ACTIONS
30080
+ * (dock / spot-clean / follow-pet / go-to-point / …).
30081
+ * - This cap is the SOURCE OF TRUTH. Two consumers adapt from it rather than
30082
+ * the reverse:
30083
+ * 1. a native CamStack navigation panel (data-driven from `listActions`
30084
+ * / `getOptions`), and
30085
+ * 2. the PTZ surface — a thin adapter mimics `ptz` from `navigation` so a
30086
+ * robot camera shows up in the existing PTZ control path without every
30087
+ * PTZ provider learning about robots. The mapping lives in the adapter,
30088
+ * not here (see the addon design note):
30089
+ * ptz.continuousMove({pan,tilt}) → navigation.move({pan,tilt})
30090
+ * ptz.stop() → navigation.stop()
30091
+ * ptz.goHome() → navigation.runAction('goHome')
30092
+ * ptz.getPresets() → navigation.listActions() (id→preset)
30093
+ * ptz.goToPreset(id) → navigation.runAction(id)
30094
+ *
30095
+ * ## Continuous drive
30096
+ *
30097
+ * `move` is MOMENTARY. Fluid navigation comes from the UI (or the PTZ adapter)
30098
+ * sending `move({pan,tilt})` REPEATEDLY at ~1 Hz while a direction is held, and
30099
+ * one `stop()` on release — exactly like the robot app's remote-drive joystick.
30100
+ * The provider forwards EACH `move` to one drive write; it must NOT debounce or
30101
+ * coalesce them. The UI owns the cadence.
30102
+ *
30103
+ * ## The action dictionary
30104
+ *
30105
+ * The discrete controls (dock / locate / spot-clean / follow / flash / sounds)
30106
+ * are a DATA-DRIVEN dictionary the cap exposes via `listActions()`. Each entry
30107
+ * carries `{ id, kind, label, icon }` (plus `soundId` for sound entries) so the
30108
+ * native panel AND the PTZ mimic render buttons WITHOUT hardcoding a
30109
+ * vendor-specific list. `kind: 'action'` entries are triggered with
30110
+ * `runAction({ actionId })`; `kind: 'sound'` entries with `playSound({ soundId })`
30111
+ * (the entry carries the `soundId` to pass). The general primitives — `move`,
30112
+ * `stop`, `goToPoint` — stay as first-class methods, not dictionary entries.
30113
+ *
30114
+ * NOTE (provider wiring): the first provider (Dreame) drives this with the RAW
30115
+ * `callAction(siid,aiid,in)` / `setProperty({siid,piid,value})` MIoT primitives
30116
+ * that the currently-published `@apocaliss92/nodedreame` already exposes on
30117
+ * every device handle. A future nodedreame publish adds a typed
30118
+ * `DreameCameraController` (drive / playPetSound / spotClean / findPet / …); the
30119
+ * provider can then swap the raw calls for the typed methods with no change to
30120
+ * THIS contract.
30121
+ */
30122
+ /**
30123
+ * A momentary drive nudge. The robot MOVES (no gimbal) for as long as the caller
30124
+ * keeps sending nudges (~1 Hz); an explicit `stop` (or letting the nudges lapse)
30125
+ * halts it.
30126
+ *
30127
+ * - `pan` — turn: negative = left, positive = right, 0 = straight.
30128
+ * - `tilt` — throttle: positive = forward, negative = spin / turn-around.
30129
+ * - `speed` — optional intensity hint [0, 1]; the provider may scale the drive
30130
+ * vector by it (drivers without proportional drive ignore it).
30131
+ *
30132
+ * `pan` / `tilt` are normalized [-1, 1]. Both optional so a caller can nudge one
30133
+ * axis alone; an all-undefined nudge is a no-op.
30134
+ */
30135
+ var NavigationMoveCommandSchema = zod.z.object({
30136
+ pan: zod.z.number().min(-1).max(1).optional(),
30137
+ tilt: zod.z.number().min(-1).max(1).optional(),
30138
+ speed: zod.z.number().min(0).max(1).optional()
30139
+ });
30140
+ /**
30141
+ * The enumerated discrete actions a navigation-capable robot can perform via
30142
+ * `runAction`. This is the CLOSED vocabulary; a given device advertises the
30143
+ * subset it supports through `listActions`. Sounds are NOT here — they go through
30144
+ * `playSound` (see the `sound` dictionary entries).
30145
+ */
30146
+ var NavigationActionIdSchema = zod.z.enum([
30147
+ "goHome",
30148
+ "locate",
30149
+ "spotClean",
30150
+ "findPet",
30151
+ "personFollow",
30152
+ "stop",
30153
+ "startClean",
30154
+ "pauseClean",
30155
+ "dockWash",
30156
+ "autoEmpty",
30157
+ "flashOn",
30158
+ "flashOff"
30159
+ ]);
30160
+ /** Whether a dictionary entry is a `runAction` action or a `playSound` sound. */
30161
+ var NavigationEntryKindSchema = zod.z.enum(["action", "sound"]);
30162
+ /**
30163
+ * One entry in the navigation action dictionary — the DATA-DRIVEN unit both the
30164
+ * native panel and the PTZ mimic render as a button.
30165
+ *
30166
+ * - `id` — stable id. For `kind:'action'` it is a {@link NavigationActionId}
30167
+ * (pass to `runAction`); for `kind:'sound'` it is a namespaced id
30168
+ * (`sound:meow`) whose `soundId` is passed to `playSound`.
30169
+ * - `icon` — icon HINT (lucide-style name; the UI maps it to its own set).
30170
+ * - `label` — operator-facing English label.
30171
+ * - `soundId` — wire sound id, present only on `kind:'sound'` entries.
30172
+ * - `enabled` — per-device FEATURE FLAG. `listActions` reports it so the UI /
30173
+ * PTZ render ONLY enabled entries. Data-driven: the provider
30174
+ * flips it from config, never by editing code.
30175
+ */
30176
+ var NavigationActionEntrySchema = zod.z.object({
30177
+ id: zod.z.string(),
30178
+ kind: NavigationEntryKindSchema,
30179
+ label: zod.z.string(),
30180
+ icon: zod.z.string(),
30181
+ /** Present only on `kind:'sound'` entries — the id to pass to `playSound`. */
30182
+ soundId: zod.z.number().int().optional(),
30183
+ /** Per-device feature flag — render this entry only when true. */
30184
+ enabled: zod.z.boolean()
30185
+ });
30186
+ /**
30187
+ * Canonical dictionary of every navigation control (discrete actions + sounds)
30188
+ * with its default label + icon hint. A provider filters this to the subset a
30189
+ * device supports (and may override a label). Exported so the provider AND the
30190
+ * UI share ONE list instead of re-deriving labels / ids independently.
30191
+ *
30192
+ * Icons are lucide-style hints; the viewer maps them to its own icon set. Every
30193
+ * catalog default is `enabled: true`; a provider overrides per-device from
30194
+ * config (data-driven — enabling / disabling one later is a config change, not a
30195
+ * code change).
30196
+ */
30197
+ var NAVIGATION_ACTION_CATALOG = [
30198
+ {
30199
+ id: "startClean",
30200
+ kind: "action",
30201
+ label: "Start cleaning",
30202
+ icon: "play",
30203
+ enabled: true
30204
+ },
30205
+ {
30206
+ id: "pauseClean",
30207
+ kind: "action",
30208
+ label: "Pause cleaning",
30209
+ icon: "pause",
30210
+ enabled: true
30211
+ },
30212
+ {
30213
+ id: "stop",
30214
+ kind: "action",
30215
+ label: "Stop",
30216
+ icon: "hand",
30217
+ enabled: true
30218
+ },
30219
+ {
30220
+ id: "goHome",
30221
+ kind: "action",
30222
+ label: "Return to dock",
30223
+ icon: "home",
30224
+ enabled: true
30225
+ },
30226
+ {
30227
+ id: "locate",
30228
+ kind: "action",
30229
+ label: "Locate",
30230
+ icon: "bell",
30231
+ enabled: true
30232
+ },
30233
+ {
30234
+ id: "spotClean",
30235
+ kind: "action",
30236
+ label: "Spot clean here",
30237
+ icon: "crosshair",
30238
+ enabled: true
30239
+ },
30240
+ {
30241
+ id: "findPet",
30242
+ kind: "action",
30243
+ label: "Find pet",
30244
+ icon: "paw-print",
30245
+ enabled: true
30246
+ },
30247
+ {
30248
+ id: "personFollow",
30249
+ kind: "action",
30250
+ label: "Follow me",
30251
+ icon: "footprints",
30252
+ enabled: true
30253
+ },
30254
+ {
30255
+ id: "dockWash",
30256
+ kind: "action",
30257
+ label: "Wash mop",
30258
+ icon: "droplets",
30259
+ enabled: true
30260
+ },
30261
+ {
30262
+ id: "autoEmpty",
30263
+ kind: "action",
30264
+ label: "Empty dustbin",
30265
+ icon: "trash-2",
30266
+ enabled: true
30267
+ },
30268
+ {
30269
+ id: "flashOn",
30270
+ kind: "action",
30271
+ label: "Flash on",
30272
+ icon: "flashlight",
30273
+ enabled: true
30274
+ },
30275
+ {
30276
+ id: "flashOff",
30277
+ kind: "action",
30278
+ label: "Flash off",
30279
+ icon: "flashlight-off",
30280
+ enabled: true
30281
+ },
30282
+ {
30283
+ id: "sound:meow",
30284
+ kind: "sound",
30285
+ label: "Meow",
30286
+ icon: "cat",
30287
+ soundId: 684,
30288
+ enabled: true
30289
+ },
30290
+ {
30291
+ id: "sound:bark",
30292
+ kind: "sound",
30293
+ label: "Woof",
30294
+ icon: "dog",
30295
+ soundId: 685,
30296
+ enabled: true
30297
+ },
30298
+ {
30299
+ id: "sound:footsteps",
30300
+ kind: "sound",
30301
+ label: "Footsteps",
30302
+ icon: "footprints",
30303
+ soundId: 686,
30304
+ enabled: true
30305
+ },
30306
+ {
30307
+ id: "sound:purring",
30308
+ kind: "sound",
30309
+ label: "Purring",
30310
+ icon: "cat",
30311
+ soundId: 687,
30312
+ enabled: true
30313
+ },
30314
+ {
30315
+ id: "sound:tickTock",
30316
+ kind: "sound",
30317
+ label: "Tick-tock",
30318
+ icon: "clock",
30319
+ soundId: 688,
30320
+ enabled: true
30321
+ }
30322
+ ];
30323
+ /** Coordinates for `goToPoint` — a point on the robot's live map. */
30324
+ var NavigationPointSchema = zod.z.object({
30325
+ x: zod.z.number(),
30326
+ y: zod.z.number()
30327
+ });
30328
+ /**
30329
+ * Per-device FEATURE-FLAG report for the general (non-dictionary) primitives.
30330
+ * The cap reports which are enabled so the UI / PTZ render only the controls
30331
+ * that are turned on for THIS device. Data-driven: the provider derives these
30332
+ * from config + probe, never hardcoded in the UI. The per-DICTIONARY-entry flags
30333
+ * live on {@link NavigationActionEntrySchema.enabled}; these gate the primitives
30334
+ * that are not dictionary entries.
30335
+ *
30336
+ * - `move` / `stop` — the momentary drive joystick.
30337
+ * - `goToPoint` — send-to-map-coordinate. Ships OFF on Dreame until the
30338
+ * map-coordinate plumbing is wired.
30339
+ * - `runAction` — the discrete action buttons (dictionary `kind:'action'`).
30340
+ * - `playSound` — the sound buttons (dictionary `kind:'sound'`).
30341
+ * - `light` — the on/off fill-light toggle (works anytime).
30342
+ * - `lightMode` — the auto/manual selector + manual level slider (a
30343
+ * camera-service control; needs an active stream).
29569
30344
  */
29570
- var MotionOnMotionChangedDataSchema = zod.z.object({
29571
- deviceId: zod.z.number(),
29572
- detected: zod.z.boolean(),
29573
- timestamp: zod.z.number(),
29574
- source: MotionSourceEnum,
29575
- regions: zod.z.array(MotionRegionSchema).readonly().optional()
30345
+ var NavigationFeaturesSchema = zod.z.object({
30346
+ move: zod.z.boolean(),
30347
+ stop: zod.z.boolean(),
30348
+ goToPoint: zod.z.boolean(),
30349
+ runAction: zod.z.boolean(),
30350
+ playSound: zod.z.boolean(),
30351
+ light: zod.z.boolean(),
30352
+ lightMode: zod.z.boolean()
29576
30353
  });
29577
- var motionCapability = {
29578
- name: "motion",
29579
- scope: "device",
29580
- mode: "singleton",
29581
- /**
29582
- * Providers register per-device natives via `ctx.registerNativeCap`
29583
- * (Hikvision/Reolink/Amcrest/Wyze/HA/Homematic/Alexa/Matter) — there is
29584
- * NO system singleton provider. Without this flag `resolveCapMount`
29585
- * derived `{ kind: 'singleton' }`, so `motion.getStatus`/`isDetected`
29586
- * resolved via `registry.getSingleton('motion')` (always null) and every
29587
- * call 412'd "provider not available" while bindings listed a live
29588
- * `motion` native (2026-08-02). The flag routes the router through
29589
- * `requireDeviceScoped` → `getProviderForDevice`, like `motion-trigger`,
29590
- * `snapshot` and every other per-device native cap.
29591
- */
29592
- deviceNative: true,
29593
- deviceTypes: [require_sleep.DeviceType.Camera, require_sleep.DeviceType.Sensor],
29594
- methods: {
29595
- /**
29596
- * Pull the current motion state synchronously. Convenience shortcut
29597
- * for consumers that don't need the full status object; equivalent
29598
- * to `getStatus()?.detected ?? false`. Will likely be folded into
29599
- * `getStatus` once the auto-injected status surface lands in every
29600
- * consumer.
29601
- */
29602
- isDetected: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.boolean()) },
29603
- events: {
29604
- /**
29605
- * Fires every time the runner transitions a camera between
29606
- * `watching` and `active` phases. `source` carries which motion
29607
- * path drove the transition; `regions` is populated only for
29608
- * `source: 'analyzer'` (frame-diff regions from the ML motion
29609
- * detector) — onboard sources don't carry per-frame regions
29610
- * here (camera-provided zones / AI metadata live in dedicated
29611
- * channels: `detection.camera-native`, future zone capability).
29612
- *
29613
- * Consumers that want all motion pushes (even with `detected`
29614
- * unchanged) should subscribe to the status subscription via
29615
- * `device-manager.subscribeDeviceStatusAggregate` instead.
29616
- */
29617
- onMotionChanged: { data: MotionOnMotionChangedDataSchema } },
29618
- status: {
29619
- schema: MotionStatusSchema,
29620
- kind: "push"
29621
- },
29622
- /**
29623
- * Runtime-state slice — the last observed motion snapshot, mirrored
29624
- * by the kernel and readable cross-process via
29625
- * `device.state.motion.value`. Reads never invoke the provider, so
29626
- * UIs and other addons can poll the cached state safely.
29627
- */
29628
- runtimeState: MotionStatusSchema,
29629
- /**
29630
- * Runtime-state durability: **session** — self-clearing by construction (`autoClearAfterMs`); a restored `detected: true` is a frozen event, and the next frame re-publishes the real one.
29631
- *
29632
- * See `RuntimeStateDurability`. Enforced by
29633
- * `scripts/check-runtime-state-durability.ts`.
29634
- */
29635
- durability: "session"
29636
- };
29637
- //#endregion
29638
- //#region src/capabilities/motion-trigger.cap.ts
30354
+ /** Light mode: `auto` lets the camera choose brightness; `manual` uses `level`. */
30355
+ var NavigationLightModeSchema = zod.z.enum(["auto", "manual"]);
30356
+ /** Manual fill-light level bounds (the camera-service accepts 40..100). */
30357
+ var NAVIGATION_LIGHT_LEVEL_MIN = 40;
30358
+ var NAVIGATION_LIGHT_LEVEL_MAX = 100;
30359
+ /** Coarse work mode the robot reports — drives the UI's active-state chips. */
30360
+ var NavigationModeSchema = zod.z.enum([
30361
+ "idle",
30362
+ "cleaning",
30363
+ "spot",
30364
+ "following",
30365
+ "goto",
30366
+ "returning",
30367
+ "paused",
30368
+ "unknown"
30369
+ ]);
29639
30370
  /**
29640
- * Motion-trigger toggle for accessory devices.
29641
- *
29642
- * "Motion trigger" means: when the parent camera detects motion, the
29643
- * accessory activates automatically. The cap exposes a single boolean
29644
- * — `enabled` — that drivers map to the vendor-specific firmware
29645
- * action (Reolink: `setSirenOnMotion`, `setFloodlightOnMotion`; ONVIF
29646
- * relay: schedule binding; …).
29647
- *
29648
- * The accessory still has its own `switch` cap for direct on/off; this
29649
- * cap is independent. Toggling motion-trigger on does NOT necessarily
29650
- * toggle the switch on — it just instructs the firmware to flip the
29651
- * switch when motion fires.
29652
- *
29653
- * Driver-specific knobs (motion duration window, brightness while
29654
- * triggered, schedule windows) live in the device's
29655
- * `getSettingsUISchema()` instead of bloating this cap — same
29656
- * principle as `switch` and `brightness` keeping their surface
29657
- * minimal.
30371
+ * Live navigation state so the UI can reflect what the robot is doing:
30372
+ * - `mode` — coarse activity (idle / cleaning / following / …).
30373
+ * - `following` — person/pet follow is currently armed.
30374
+ * - `flash` — the on-camera fill light is on.
30375
+ * - `lightMode` — auto vs manual fill-light mode.
30376
+ * - `lightLevel` — manual fill-light level (40..100); meaningful when
30377
+ * `lightMode === 'manual'`.
29658
30378
  */
29659
- var MotionTriggerStatusSchema = zod.z.object({
29660
- enabled: zod.z.boolean(),
29661
- /** Ms epoch of the last operator-driven change. */
30379
+ var NavigationStatusSchema = zod.z.object({
30380
+ mode: NavigationModeSchema,
30381
+ following: zod.z.boolean(),
30382
+ flash: zod.z.boolean(),
30383
+ lightMode: NavigationLightModeSchema,
30384
+ lightLevel: zod.z.number().min(40).max(100),
30385
+ /** Ms epoch when the slice was last updated. */
29662
30386
  lastChangedAt: zod.z.number()
29663
30387
  });
29664
30388
  /**
29665
- * Persistent slice mirrored across restarts. The provider writes here
29666
- * on every successful firmware fetch / setMotionTrigger push; the cap
29667
- * router and admin-ui hero read straight from this snapshot via
29668
- * `device.state.motionTrigger.value` instead of re-issuing a firmware
29669
- * round-trip on every UI mount. `lastFetchedAt` lets the framework
29670
- * helper (`createRuntimeStateBridge`) stale-check before deciding
29671
- * whether to refresh from the camera.
29672
- */
29673
- var MotionTriggerRuntimeStateSchema = MotionTriggerStatusSchema.extend({
29674
- /** Ms epoch of the last successful camera fetch (0 = never). */
29675
- lastFetchedAt: zod.z.number() });
29676
- var motionTriggerCapability = {
29677
- name: "motion-trigger",
29678
- scope: "device",
29679
- deviceNative: true,
29680
- mode: "singleton",
29681
- deviceTypes: [
29682
- require_sleep.DeviceType.Light,
29683
- require_sleep.DeviceType.Siren,
29684
- require_sleep.DeviceType.Switch
29685
- ],
29686
- methods: { setMotionTrigger: require_sleep.method(zod.z.object({
29687
- deviceId: zod.z.number().int().nonnegative(),
29688
- enabled: zod.z.boolean()
29689
- }), zod.z.void(), {
29690
- kind: "mutation",
29691
- auth: "admin"
29692
- }) },
29693
- events: { onMotionTriggerChanged: { data: zod.z.object({
29694
- deviceId: zod.z.number(),
29695
- enabled: zod.z.boolean(),
29696
- lastChangedAt: zod.z.number()
29697
- }) } },
29698
- status: {
29699
- schema: MotionTriggerStatusSchema,
29700
- kind: "command-driven"
29701
- },
29702
- runtimeState: MotionTriggerRuntimeStateSchema,
29703
- /**
29704
- * Runtime-state durability: **session** — the authority for motion-trigger enablement is the provider's own config; the slice is a mirror of it, re-published on connect.
29705
- *
29706
- * See `RuntimeStateDurability`. Enforced by
29707
- * `scripts/check-runtime-state-durability.ts`.
29708
- */
29709
- durability: "session"
29710
- };
29711
- //#endregion
29712
- //#region src/capabilities/motion-zones.cap.ts
29713
- /**
29714
- * Motion-zones share the same MaskShape vocabulary as privacy-mask — the
29715
- * on-camera motion-detection mask is a single `grid` region (a row-major
29716
- * boolean cell lattice the camera's onboard VMD evaluates). Composing it as
29717
- * a region keeps one drawing-plane model across all geometry caps.
30389
+ * Runtime-state slice owned by this cap (kernel-managed: validated, mirrored,
30390
+ * observable). Adds `lastFetchedAt` on top of the status shape per the
30391
+ * convention.
29718
30392
  */
29719
- /** A motion-zone region — exactly one boolean cell grid today. */
29720
- var MotionZoneRegionSchema = zod.z.object({
29721
- id: zod.z.number(),
29722
- enabled: zod.z.boolean(),
29723
- shape: MaskGridShapeSchema
29724
- });
29725
- /** Current on-camera motion-detection state — master enable + sensitivity +
29726
- * the grid region(s). */
29727
- var MotionZoneStatusSchema = zod.z.object({
29728
- enabled: zod.z.boolean(),
29729
- sensitivity: zod.z.number(),
29730
- /** Grid region(s). Today exactly one `grid` shape. */
29731
- regions: zod.z.array(MotionZoneRegionSchema),
29732
- lastFetchedAt: zod.z.number()
29733
- });
29734
- /** Per-camera availability — grid dims are fixed per camera model; the UI
29735
- * sizes its editor from `grid`. */
29736
- var MotionZoneOptionsSchema = zod.z.object({
29737
- maxRegions: zod.z.number(),
29738
- supportedShapes: zod.z.array(MaskShapeKindSchema),
29739
- grid: MaskGridDimsSchema,
29740
- sensitivity: zod.z.object({
29741
- min: zod.z.number(),
29742
- max: zod.z.number(),
29743
- step: zod.z.number()
29744
- })
29745
- });
29746
- /** Partial change — every field optional. */
29747
- var MotionZonePatchSchema = zod.z.object({
29748
- enabled: zod.z.boolean().optional(),
29749
- sensitivity: zod.z.number().optional(),
29750
- regions: zod.z.array(MotionZoneRegionSchema).optional()
29751
- });
29752
- var motionZonesCapability = {
29753
- name: "motion-zones",
30393
+ var NavigationRuntimeStateSchema = NavigationStatusSchema.extend({ lastFetchedAt: zod.z.number() });
30394
+ var navigationCapability = {
30395
+ name: "navigation",
29754
30396
  scope: "device",
29755
30397
  deviceNative: true,
29756
30398
  mode: "singleton",
29757
30399
  deviceTypes: [require_sleep.DeviceType.Camera],
29758
30400
  deviceConfig: { ui: {
29759
30401
  kind: "widget",
29760
- widgetId: "host/motion-zones-grid",
29761
- tab: "motion",
29762
- label: "Motion Zones"
30402
+ widgetId: "host/navigation-panel",
30403
+ tab: "navigation",
30404
+ topTab: true,
30405
+ label: "Navigation",
30406
+ order: 0
29763
30407
  } },
29764
30408
  methods: {
29765
- getOptions: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), MotionZoneOptionsSchema),
29766
- setZone: require_sleep.method(zod.z.object({
30409
+ /**
30410
+ * Momentary drive nudge (the robot moves). `protected` — mirrors
30411
+ * `ptz.continuousMove` so the Viewer navigation panel (and the PTZ-mimic
30412
+ * path) works for any authenticated user, not admin-only. The UI sends
30413
+ * these at ~1 Hz while a control is held; the provider forwards each one to
30414
+ * a single drive write WITHOUT debouncing.
30415
+ */
30416
+ move: require_sleep.method(NavigationMoveCommandSchema.extend({ deviceId: zod.z.number() }), zod.z.void(), { kind: "mutation" }),
30417
+ /** Halt all motion immediately (zero drive vector). */
30418
+ stop: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.void(), { kind: "mutation" }),
30419
+ /** Send the robot to a point on its live map. */
30420
+ goToPoint: require_sleep.method(NavigationPointSchema.extend({ deviceId: zod.z.number() }), zod.z.void(), { kind: "mutation" }),
30421
+ /**
30422
+ * Enumerate the discrete controls THIS device supports (data-driven UI +
30423
+ * PTZ mimic). Camera-probed subset of {@link NAVIGATION_ACTION_CATALOG}.
30424
+ */
30425
+ listActions: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.array(NavigationActionEntrySchema)),
30426
+ /**
30427
+ * Run one discrete action (a `kind:'action'` dictionary entry). Invalid /
30428
+ * unsupported action ids are rejected by the provider.
30429
+ */
30430
+ runAction: require_sleep.method(zod.z.object({
29767
30431
  deviceId: zod.z.number(),
29768
- patch: MotionZonePatchSchema
29769
- }), zod.z.void(), {
29770
- kind: "mutation",
29771
- auth: "admin"
29772
- })
30432
+ actionId: NavigationActionIdSchema
30433
+ }), zod.z.void(), { kind: "mutation" }),
30434
+ /** Play a sound by its wire id (the `soundId` of a `kind:'sound'` entry). */
30435
+ playSound: require_sleep.method(zod.z.object({
30436
+ deviceId: zod.z.number(),
30437
+ soundId: zod.z.number().int()
30438
+ }), zod.z.void(), { kind: "mutation" }),
30439
+ /**
30440
+ * Turn the on-camera fill light on / off (the `OpenFullLight` control —
30441
+ * works anytime, no active stream required).
30442
+ */
30443
+ setLightOn: require_sleep.method(zod.z.object({
30444
+ deviceId: zod.z.number(),
30445
+ on: zod.z.boolean()
30446
+ }), zod.z.void(), { kind: "mutation" }),
30447
+ /**
30448
+ * Set the fill-light mode (auto vs manual). `manual` optionally carries the
30449
+ * initial `level`. The auto/manual + level control is a CAMERA-service
30450
+ * action that generally needs an active camera stream/monitor session — the
30451
+ * UI shows the manual level slider ONLY when `mode === 'manual'`.
30452
+ */
30453
+ setLightMode: require_sleep.method(zod.z.object({
30454
+ deviceId: zod.z.number(),
30455
+ mode: NavigationLightModeSchema,
30456
+ level: zod.z.number().min(40).max(100).optional()
30457
+ }), zod.z.void(), { kind: "mutation" }),
30458
+ /** Set the MANUAL fill-light level (40..100). Implies `manual` mode. */
30459
+ setLightLevel: require_sleep.method(zod.z.object({
30460
+ deviceId: zod.z.number(),
30461
+ level: zod.z.number().min(40).max(100)
30462
+ }), zod.z.void(), { kind: "mutation" }),
30463
+ /**
30464
+ * Per-device FEATURE-FLAG report for the general primitives — drives which
30465
+ * controls the UI shows (the per-entry flags for the dictionary come back on
30466
+ * `listActions`).
30467
+ */
30468
+ getFeatures: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), NavigationFeaturesSchema)
29773
30469
  },
30470
+ events: { onStatusChanged: { data: zod.z.object({
30471
+ deviceId: zod.z.number(),
30472
+ status: NavigationStatusSchema
30473
+ }) } },
29774
30474
  status: {
29775
- schema: MotionZoneStatusSchema,
29776
- kind: "poll"
30475
+ schema: NavigationStatusSchema,
30476
+ kind: "push"
29777
30477
  },
29778
- runtimeState: MotionZoneStatusSchema,
29779
30478
  /**
29780
- * Runtime-state durability: **restored** — the 14 KB polygon list is the single largest slice on the fleet and has not changed since the operator drew it. Highest value per byte in the table.
30479
+ * Runtime-state slice mirrored by the kernel. The navigation panel watches it
30480
+ * for live mode / follow / flash changes.
30481
+ */
30482
+ runtimeState: NavigationRuntimeStateSchema,
30483
+ /**
30484
+ * Runtime-state durability: **session** — like `vacuum-control`, a restored
30485
+ * `mode: cleaning` / `following: true` is a robot that is not actually doing
30486
+ * that. The live handle re-publishes on connect.
29781
30487
  *
29782
30488
  * See `RuntimeStateDurability`. Enforced by
29783
30489
  * `scripts/check-runtime-state-durability.ts`.
29784
30490
  */
29785
- durability: "restored",
29786
- /** Clock fields: written, but excluded from the compare that decides
29787
- * whether persisting is worth a SQLite commit. */
29788
- volatileStateFields: ["lastFetchedAt"]
30491
+ durability: "session"
29789
30492
  };
29790
30493
  //#endregion
29791
- //#region src/capabilities/native-object-detection.cap.ts
30494
+ //#region src/capabilities/network-link.cap.ts
29792
30495
  /**
29793
- * On-camera AI object detection cap. Surfaces per-device the classes
29794
- * the firmware can detect and the last-seen instance of each. The
29795
- * provider also fan-outs these to the global `detection.camera-native`
29796
- * event bus with `source: 'onboard'` so cross-cutting system services
29797
- * (alert-center, advanced-notifier, recording-engine) can subscribe
29798
- * once and receive events from every camera.
30496
+ * How a device reaches the network, and how well.
29799
30497
  *
29800
- * Distinct from `motion-detection` (ML pipeline) and `motion` (hardware
29801
- * PIR or firmware motion pulse): this cap is specifically the AI
29802
- * classifier output coming FROM the camera, not the local pipeline.
30498
+ * NOT `connectivity`: that cap is an UPSTREAM system's binary view of whether
30499
+ * an entity is reachable (a Home Assistant `binary_sensor` with
30500
+ * `device_class: connectivity`). This one is the device's OWN link — the
30501
+ * medium it is on and the signal it sees — the way `battery` is the device's
30502
+ * own charge.
30503
+ *
30504
+ * `'wifi'`, `'ethernet'` and `'cellular'` are links the firmware actually
30505
+ * reported. `'unknown'` is the ABSENCE of an answer — the provider has
30506
+ * registered the capability but has not read the link yet (D315: unknown is
30507
+ * not empty). Consumers skip it rather than draw a wire or a bar.
29803
30508
  */
29804
- var NativeObjectClassEnum = zod.z.enum([
29805
- "person",
29806
- "vehicle",
29807
- "animal",
29808
- "face",
29809
- "package",
29810
- "other"
29811
- ]);
29812
- var NativeDetectionSchema = zod.z.object({
29813
- class: NativeObjectClassEnum,
29814
- timestamp: zod.z.number(),
29815
- /** Firmware-provided confidence [0..1]. Reolink pushes don't carry it → undefined. */
29816
- confidence: zod.z.number().min(0).max(1).optional()
29817
- });
29818
- var NativeObjectDetectionStatusSchema = zod.z.object({
29819
- /**
29820
- * Last observed instance per class. Missing entries mean the class
29821
- * is supported but nothing has been seen since the provider started.
29822
- *
29823
- * MUST be a partial record: providers seed an empty `{}` on cold-start
29824
- * and write one class at a time as detections arrive. In Zod 4
29825
- * `z.record(enum, …)` is EXHAUSTIVE (requires every enum key), so a
29826
- * partial write throws "expected object, received undefined" for every
29827
- * unseen class. `z.partialRecord` keeps the enum-key narrowing while
29828
- * allowing the sparse shape the providers actually write.
29829
- */
29830
- lastByClass: zod.z.partialRecord(NativeObjectClassEnum, NativeDetectionSchema.nullable()),
29831
- /** Classes the firmware is capable of detecting — enumerated at device register. */
29832
- supportedClasses: zod.z.array(NativeObjectClassEnum).readonly(),
30509
+ var NETWORK_LINK_TYPES = [
30510
+ "wifi",
30511
+ "ethernet",
30512
+ "cellular",
30513
+ "unknown"
30514
+ ];
30515
+ /**
30516
+ * Network-link snapshot. Same shape for every provider (a Reolink wifi
30517
+ * camera, a Home Assistant device with a signal-strength sensor, a Tapo
30518
+ * plug): one slice under `device.runtimeState['network-link']`, one badge,
30519
+ * one Home Assistant projection.
30520
+ */
30521
+ var NetworkLinkStatusSchema = zod.z.object({
30522
+ /** The link the device is on. `'unknown'` = not read yet, not "no link". */
30523
+ type: zod.z.enum(NETWORK_LINK_TYPES),
29833
30524
  /**
29834
- * Whether forwarding of onboard AI detections is enabled for this device.
29835
- * Default FALSE (opt-in, cold-start) — onboard AI pushes are noisy/sparse and
29836
- * churn the tracker, so forwarding stays off until the operator enables it.
30525
+ * Link quality, 0..100 inclusive, normalised by the provider from whatever
30526
+ * the firmware reports (bars, RSSI, a vendor scale). **`null` means NOT
30527
+ * KNOWN or NOT APPLICABLE** — a wired link has no signal, and a wireless
30528
+ * one whose reading has not landed must not be drawn at 0 %. Consumers
30529
+ * SKIP a null rather than coerce it.
29837
30530
  */
29838
- enabled: zod.z.boolean()
30531
+ signalPercent: zod.z.number().min(0).max(100).nullable(),
30532
+ /** Raw received signal strength in dBm, when the firmware reports one. */
30533
+ rssiDbm: zod.z.number().optional(),
30534
+ /** Network name of a wireless link, when the firmware reports it. */
30535
+ ssid: zod.z.string().optional(),
30536
+ /** Ms epoch of the last observation. Lets consumers reason about freshness. */
30537
+ lastUpdated: zod.z.number()
29839
30538
  });
29840
- var NativeObjectDetectionRuntimeStateSchema = NativeObjectDetectionStatusSchema.extend({
29841
- /** Required by createRuntimeStateBridge — epoch ms of last refresh. */
29842
- lastFetchedAt: zod.z.number() });
29843
- var nativeObjectDetectionCapability = {
29844
- name: "native-object-detection",
30539
+ /** The slice a provider seeds before its first read: nothing is known yet. */
30540
+ var NETWORK_LINK_UNKNOWN = {
30541
+ type: "unknown",
30542
+ signalPercent: null,
30543
+ lastUpdated: 0
30544
+ };
30545
+ /**
30546
+ * Normalise a signal the firmware reports as BARS (0..`maxBars`) to 0..100.
30547
+ * Out-of-range or non-finite input is not a reading: `null`.
30548
+ */
30549
+ function signalPercentFromBars(bars, maxBars) {
30550
+ if (bars === void 0 || !Number.isFinite(bars) || maxBars <= 0) return null;
30551
+ if (bars < 0 || bars > maxBars) return null;
30552
+ return Math.round(bars / maxBars * 100);
30553
+ }
30554
+ /**
30555
+ * Normalise an RSSI in dBm to 0..100 on the usual wifi scale: -100 dBm and
30556
+ * below is 0 %, -50 dBm and above is 100 %, linear between. Non-finite or
30557
+ * positive input is not an RSSI: `null`.
30558
+ */
30559
+ function signalPercentFromRssi(rssiDbm) {
30560
+ if (rssiDbm === void 0 || !Number.isFinite(rssiDbm) || rssiDbm > 0) return null;
30561
+ return Math.round((Math.min(-50, Math.max(-100, rssiDbm)) + 100) * 2);
30562
+ }
30563
+ var networkLinkCapability = {
30564
+ name: "network-link",
29845
30565
  scope: "device",
29846
30566
  deviceNative: true,
29847
30567
  mode: "singleton",
29848
- deviceTypes: [require_sleep.DeviceType.Camera],
29849
- methods: { setEnabled: require_sleep.method(zod.z.object({
29850
- deviceId: zod.z.number(),
29851
- enabled: zod.z.boolean()
29852
- }), zod.z.void(), {
29853
- kind: "mutation",
29854
- auth: "admin"
29855
- }) },
29856
- events: { onDetected: { data: zod.z.object({
30568
+ deviceTypes: [
30569
+ require_sleep.DeviceType.Camera,
30570
+ require_sleep.DeviceType.Sensor,
30571
+ require_sleep.DeviceType.Button,
30572
+ require_sleep.DeviceType.Switch,
30573
+ require_sleep.DeviceType.Light,
30574
+ require_sleep.DeviceType.Lock,
30575
+ require_sleep.DeviceType.Siren
30576
+ ],
30577
+ methods: {},
30578
+ events: {
30579
+ /**
30580
+ * Emitted whenever the cached status changes (a link switch, a signal
30581
+ * reading that moved). Mirrored on the parent chain by the
30582
+ * DeviceEventPropagator like `battery.onStatusChanged`.
30583
+ */
30584
+ onStatusChanged: { data: zod.z.object({
29857
30585
  deviceId: zod.z.number(),
29858
- detection: NativeDetectionSchema
30586
+ status: NetworkLinkStatusSchema
29859
30587
  }) } },
29860
30588
  status: {
29861
- schema: NativeObjectDetectionStatusSchema,
29862
- kind: "push"
30589
+ schema: NetworkLinkStatusSchema,
30590
+ kind: "push",
30591
+ empty: NETWORK_LINK_UNKNOWN
29863
30592
  },
29864
- runtimeState: NativeObjectDetectionRuntimeStateSchema,
29865
30593
  /**
29866
- * Runtime-state durability: **restored** — `enabled` is an operator toggle on a camera whose refresh is a no-op and whose staleMs is Infinity. There is no hardware value to re-read — losing it loses the setting.
30594
+ * Runtime-state slice — every provider stores the same shape under
30595
+ * `device.runtimeState['network-link']`, read once by the badge and the
30596
+ * Home Assistant projector regardless of the driver.
30597
+ */
30598
+ runtimeState: NetworkLinkStatusSchema,
30599
+ /**
30600
+ * Runtime-state durability: **restored** — a link reading is slow to
30601
+ * change and a sleeping battery camera may not report for hours; the
30602
+ * restored slice is what the badge shows until the next read.
29867
30603
  *
29868
30604
  * See `RuntimeStateDurability`. Enforced by
29869
30605
  * `scripts/check-runtime-state-durability.ts`.
@@ -29871,7 +30607,7 @@ var nativeObjectDetectionCapability = {
29871
30607
  durability: "restored",
29872
30608
  /** Clock fields: written, but excluded from the compare that decides
29873
30609
  * whether persisting is worth a SQLite commit. */
29874
- volatileStateFields: ["lastFetchedAt"]
30610
+ volatileStateFields: ["lastUpdated"]
29875
30611
  };
29876
30612
  //#endregion
29877
30613
  //#region src/capabilities/network-quality.cap.ts
@@ -31806,431 +32542,6 @@ var ptzAutotrackCapability = {
31806
32542
  durability: "session"
31807
32543
  };
31808
32544
  //#endregion
31809
- //#region src/capabilities/navigation.cap.ts
31810
- /**
31811
- * `navigation` — a device-scoped capability that natively expresses the FULL
31812
- * navigation / action surface of a robot that DRIVES ITSELF and carries an
31813
- * on-board camera (the Dreame robot-vacuum camera is the first provider).
31814
- *
31815
- * Why a NEW cap rather than overloading `ptz`:
31816
- * - `ptz` moves a *gimbal* on a fixed camera (pan/tilt/zoom of the lens). A
31817
- * robot vacuum has no gimbal — the whole chassis drives, turns and spins.
31818
- * The two are different physical models: PTZ is absolute-position + presets,
31819
- * navigation is momentary drive nudges + discrete robot ACTIONS
31820
- * (dock / spot-clean / follow-pet / go-to-point / …).
31821
- * - This cap is the SOURCE OF TRUTH. Two consumers adapt from it rather than
31822
- * the reverse:
31823
- * 1. a native CamStack navigation panel (data-driven from `listActions`
31824
- * / `getOptions`), and
31825
- * 2. the PTZ surface — a thin adapter mimics `ptz` from `navigation` so a
31826
- * robot camera shows up in the existing PTZ control path without every
31827
- * PTZ provider learning about robots. The mapping lives in the adapter,
31828
- * not here (see the addon design note):
31829
- * ptz.continuousMove({pan,tilt}) → navigation.move({pan,tilt})
31830
- * ptz.stop() → navigation.stop()
31831
- * ptz.goHome() → navigation.runAction('goHome')
31832
- * ptz.getPresets() → navigation.listActions() (id→preset)
31833
- * ptz.goToPreset(id) → navigation.runAction(id)
31834
- *
31835
- * ## Continuous drive
31836
- *
31837
- * `move` is MOMENTARY. Fluid navigation comes from the UI (or the PTZ adapter)
31838
- * sending `move({pan,tilt})` REPEATEDLY at ~1 Hz while a direction is held, and
31839
- * one `stop()` on release — exactly like the robot app's remote-drive joystick.
31840
- * The provider forwards EACH `move` to one drive write; it must NOT debounce or
31841
- * coalesce them. The UI owns the cadence.
31842
- *
31843
- * ## The action dictionary
31844
- *
31845
- * The discrete controls (dock / locate / spot-clean / follow / flash / sounds)
31846
- * are a DATA-DRIVEN dictionary the cap exposes via `listActions()`. Each entry
31847
- * carries `{ id, kind, label, icon }` (plus `soundId` for sound entries) so the
31848
- * native panel AND the PTZ mimic render buttons WITHOUT hardcoding a
31849
- * vendor-specific list. `kind: 'action'` entries are triggered with
31850
- * `runAction({ actionId })`; `kind: 'sound'` entries with `playSound({ soundId })`
31851
- * (the entry carries the `soundId` to pass). The general primitives — `move`,
31852
- * `stop`, `goToPoint` — stay as first-class methods, not dictionary entries.
31853
- *
31854
- * NOTE (provider wiring): the first provider (Dreame) drives this with the RAW
31855
- * `callAction(siid,aiid,in)` / `setProperty({siid,piid,value})` MIoT primitives
31856
- * that the currently-published `@apocaliss92/nodedreame` already exposes on
31857
- * every device handle. A future nodedreame publish adds a typed
31858
- * `DreameCameraController` (drive / playPetSound / spotClean / findPet / …); the
31859
- * provider can then swap the raw calls for the typed methods with no change to
31860
- * THIS contract.
31861
- */
31862
- /**
31863
- * A momentary drive nudge. The robot MOVES (no gimbal) for as long as the caller
31864
- * keeps sending nudges (~1 Hz); an explicit `stop` (or letting the nudges lapse)
31865
- * halts it.
31866
- *
31867
- * - `pan` — turn: negative = left, positive = right, 0 = straight.
31868
- * - `tilt` — throttle: positive = forward, negative = spin / turn-around.
31869
- * - `speed` — optional intensity hint [0, 1]; the provider may scale the drive
31870
- * vector by it (drivers without proportional drive ignore it).
31871
- *
31872
- * `pan` / `tilt` are normalized [-1, 1]. Both optional so a caller can nudge one
31873
- * axis alone; an all-undefined nudge is a no-op.
31874
- */
31875
- var NavigationMoveCommandSchema = zod.z.object({
31876
- pan: zod.z.number().min(-1).max(1).optional(),
31877
- tilt: zod.z.number().min(-1).max(1).optional(),
31878
- speed: zod.z.number().min(0).max(1).optional()
31879
- });
31880
- /**
31881
- * The enumerated discrete actions a navigation-capable robot can perform via
31882
- * `runAction`. This is the CLOSED vocabulary; a given device advertises the
31883
- * subset it supports through `listActions`. Sounds are NOT here — they go through
31884
- * `playSound` (see the `sound` dictionary entries).
31885
- */
31886
- var NavigationActionIdSchema = zod.z.enum([
31887
- "goHome",
31888
- "locate",
31889
- "spotClean",
31890
- "findPet",
31891
- "personFollow",
31892
- "stop",
31893
- "startClean",
31894
- "pauseClean",
31895
- "dockWash",
31896
- "autoEmpty",
31897
- "flashOn",
31898
- "flashOff"
31899
- ]);
31900
- /** Whether a dictionary entry is a `runAction` action or a `playSound` sound. */
31901
- var NavigationEntryKindSchema = zod.z.enum(["action", "sound"]);
31902
- /**
31903
- * One entry in the navigation action dictionary — the DATA-DRIVEN unit both the
31904
- * native panel and the PTZ mimic render as a button.
31905
- *
31906
- * - `id` — stable id. For `kind:'action'` it is a {@link NavigationActionId}
31907
- * (pass to `runAction`); for `kind:'sound'` it is a namespaced id
31908
- * (`sound:meow`) whose `soundId` is passed to `playSound`.
31909
- * - `icon` — icon HINT (lucide-style name; the UI maps it to its own set).
31910
- * - `label` — operator-facing English label.
31911
- * - `soundId` — wire sound id, present only on `kind:'sound'` entries.
31912
- * - `enabled` — per-device FEATURE FLAG. `listActions` reports it so the UI /
31913
- * PTZ render ONLY enabled entries. Data-driven: the provider
31914
- * flips it from config, never by editing code.
31915
- */
31916
- var NavigationActionEntrySchema = zod.z.object({
31917
- id: zod.z.string(),
31918
- kind: NavigationEntryKindSchema,
31919
- label: zod.z.string(),
31920
- icon: zod.z.string(),
31921
- /** Present only on `kind:'sound'` entries — the id to pass to `playSound`. */
31922
- soundId: zod.z.number().int().optional(),
31923
- /** Per-device feature flag — render this entry only when true. */
31924
- enabled: zod.z.boolean()
31925
- });
31926
- /**
31927
- * Canonical dictionary of every navigation control (discrete actions + sounds)
31928
- * with its default label + icon hint. A provider filters this to the subset a
31929
- * device supports (and may override a label). Exported so the provider AND the
31930
- * UI share ONE list instead of re-deriving labels / ids independently.
31931
- *
31932
- * Icons are lucide-style hints; the viewer maps them to its own icon set. Every
31933
- * catalog default is `enabled: true`; a provider overrides per-device from
31934
- * config (data-driven — enabling / disabling one later is a config change, not a
31935
- * code change).
31936
- */
31937
- var NAVIGATION_ACTION_CATALOG = [
31938
- {
31939
- id: "startClean",
31940
- kind: "action",
31941
- label: "Start cleaning",
31942
- icon: "play",
31943
- enabled: true
31944
- },
31945
- {
31946
- id: "pauseClean",
31947
- kind: "action",
31948
- label: "Pause cleaning",
31949
- icon: "pause",
31950
- enabled: true
31951
- },
31952
- {
31953
- id: "stop",
31954
- kind: "action",
31955
- label: "Stop",
31956
- icon: "hand",
31957
- enabled: true
31958
- },
31959
- {
31960
- id: "goHome",
31961
- kind: "action",
31962
- label: "Return to dock",
31963
- icon: "home",
31964
- enabled: true
31965
- },
31966
- {
31967
- id: "locate",
31968
- kind: "action",
31969
- label: "Locate",
31970
- icon: "bell",
31971
- enabled: true
31972
- },
31973
- {
31974
- id: "spotClean",
31975
- kind: "action",
31976
- label: "Spot clean here",
31977
- icon: "crosshair",
31978
- enabled: true
31979
- },
31980
- {
31981
- id: "findPet",
31982
- kind: "action",
31983
- label: "Find pet",
31984
- icon: "paw-print",
31985
- enabled: true
31986
- },
31987
- {
31988
- id: "personFollow",
31989
- kind: "action",
31990
- label: "Follow me",
31991
- icon: "footprints",
31992
- enabled: true
31993
- },
31994
- {
31995
- id: "dockWash",
31996
- kind: "action",
31997
- label: "Wash mop",
31998
- icon: "droplets",
31999
- enabled: true
32000
- },
32001
- {
32002
- id: "autoEmpty",
32003
- kind: "action",
32004
- label: "Empty dustbin",
32005
- icon: "trash-2",
32006
- enabled: true
32007
- },
32008
- {
32009
- id: "flashOn",
32010
- kind: "action",
32011
- label: "Flash on",
32012
- icon: "flashlight",
32013
- enabled: true
32014
- },
32015
- {
32016
- id: "flashOff",
32017
- kind: "action",
32018
- label: "Flash off",
32019
- icon: "flashlight-off",
32020
- enabled: true
32021
- },
32022
- {
32023
- id: "sound:meow",
32024
- kind: "sound",
32025
- label: "Meow",
32026
- icon: "cat",
32027
- soundId: 684,
32028
- enabled: true
32029
- },
32030
- {
32031
- id: "sound:bark",
32032
- kind: "sound",
32033
- label: "Woof",
32034
- icon: "dog",
32035
- soundId: 685,
32036
- enabled: true
32037
- },
32038
- {
32039
- id: "sound:footsteps",
32040
- kind: "sound",
32041
- label: "Footsteps",
32042
- icon: "footprints",
32043
- soundId: 686,
32044
- enabled: true
32045
- },
32046
- {
32047
- id: "sound:purring",
32048
- kind: "sound",
32049
- label: "Purring",
32050
- icon: "cat",
32051
- soundId: 687,
32052
- enabled: true
32053
- },
32054
- {
32055
- id: "sound:tickTock",
32056
- kind: "sound",
32057
- label: "Tick-tock",
32058
- icon: "clock",
32059
- soundId: 688,
32060
- enabled: true
32061
- }
32062
- ];
32063
- /** Coordinates for `goToPoint` — a point on the robot's live map. */
32064
- var NavigationPointSchema = zod.z.object({
32065
- x: zod.z.number(),
32066
- y: zod.z.number()
32067
- });
32068
- /**
32069
- * Per-device FEATURE-FLAG report for the general (non-dictionary) primitives.
32070
- * The cap reports which are enabled so the UI / PTZ render only the controls
32071
- * that are turned on for THIS device. Data-driven: the provider derives these
32072
- * from config + probe, never hardcoded in the UI. The per-DICTIONARY-entry flags
32073
- * live on {@link NavigationActionEntrySchema.enabled}; these gate the primitives
32074
- * that are not dictionary entries.
32075
- *
32076
- * - `move` / `stop` — the momentary drive joystick.
32077
- * - `goToPoint` — send-to-map-coordinate. Ships OFF on Dreame until the
32078
- * map-coordinate plumbing is wired.
32079
- * - `runAction` — the discrete action buttons (dictionary `kind:'action'`).
32080
- * - `playSound` — the sound buttons (dictionary `kind:'sound'`).
32081
- * - `light` — the on/off fill-light toggle (works anytime).
32082
- * - `lightMode` — the auto/manual selector + manual level slider (a
32083
- * camera-service control; needs an active stream).
32084
- */
32085
- var NavigationFeaturesSchema = zod.z.object({
32086
- move: zod.z.boolean(),
32087
- stop: zod.z.boolean(),
32088
- goToPoint: zod.z.boolean(),
32089
- runAction: zod.z.boolean(),
32090
- playSound: zod.z.boolean(),
32091
- light: zod.z.boolean(),
32092
- lightMode: zod.z.boolean()
32093
- });
32094
- /** Light mode: `auto` lets the camera choose brightness; `manual` uses `level`. */
32095
- var NavigationLightModeSchema = zod.z.enum(["auto", "manual"]);
32096
- /** Manual fill-light level bounds (the camera-service accepts 40..100). */
32097
- var NAVIGATION_LIGHT_LEVEL_MIN = 40;
32098
- var NAVIGATION_LIGHT_LEVEL_MAX = 100;
32099
- /** Coarse work mode the robot reports — drives the UI's active-state chips. */
32100
- var NavigationModeSchema = zod.z.enum([
32101
- "idle",
32102
- "cleaning",
32103
- "spot",
32104
- "following",
32105
- "goto",
32106
- "returning",
32107
- "paused",
32108
- "unknown"
32109
- ]);
32110
- /**
32111
- * Live navigation state so the UI can reflect what the robot is doing:
32112
- * - `mode` — coarse activity (idle / cleaning / following / …).
32113
- * - `following` — person/pet follow is currently armed.
32114
- * - `flash` — the on-camera fill light is on.
32115
- * - `lightMode` — auto vs manual fill-light mode.
32116
- * - `lightLevel` — manual fill-light level (40..100); meaningful when
32117
- * `lightMode === 'manual'`.
32118
- */
32119
- var NavigationStatusSchema = zod.z.object({
32120
- mode: NavigationModeSchema,
32121
- following: zod.z.boolean(),
32122
- flash: zod.z.boolean(),
32123
- lightMode: NavigationLightModeSchema,
32124
- lightLevel: zod.z.number().min(40).max(100),
32125
- /** Ms epoch when the slice was last updated. */
32126
- lastChangedAt: zod.z.number()
32127
- });
32128
- /**
32129
- * Runtime-state slice owned by this cap (kernel-managed: validated, mirrored,
32130
- * observable). Adds `lastFetchedAt` on top of the status shape per the
32131
- * convention.
32132
- */
32133
- var NavigationRuntimeStateSchema = NavigationStatusSchema.extend({ lastFetchedAt: zod.z.number() });
32134
- var navigationCapability = {
32135
- name: "navigation",
32136
- scope: "device",
32137
- deviceNative: true,
32138
- mode: "singleton",
32139
- deviceTypes: [require_sleep.DeviceType.Camera],
32140
- deviceConfig: { ui: {
32141
- kind: "widget",
32142
- widgetId: "host/navigation-panel",
32143
- tab: "navigation",
32144
- topTab: true,
32145
- label: "Navigation",
32146
- order: 0
32147
- } },
32148
- methods: {
32149
- /**
32150
- * Momentary drive nudge (the robot moves). `protected` — mirrors
32151
- * `ptz.continuousMove` so the Viewer navigation panel (and the PTZ-mimic
32152
- * path) works for any authenticated user, not admin-only. The UI sends
32153
- * these at ~1 Hz while a control is held; the provider forwards each one to
32154
- * a single drive write WITHOUT debouncing.
32155
- */
32156
- move: require_sleep.method(NavigationMoveCommandSchema.extend({ deviceId: zod.z.number() }), zod.z.void(), { kind: "mutation" }),
32157
- /** Halt all motion immediately (zero drive vector). */
32158
- stop: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.void(), { kind: "mutation" }),
32159
- /** Send the robot to a point on its live map. */
32160
- goToPoint: require_sleep.method(NavigationPointSchema.extend({ deviceId: zod.z.number() }), zod.z.void(), { kind: "mutation" }),
32161
- /**
32162
- * Enumerate the discrete controls THIS device supports (data-driven UI +
32163
- * PTZ mimic). Camera-probed subset of {@link NAVIGATION_ACTION_CATALOG}.
32164
- */
32165
- listActions: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), zod.z.array(NavigationActionEntrySchema)),
32166
- /**
32167
- * Run one discrete action (a `kind:'action'` dictionary entry). Invalid /
32168
- * unsupported action ids are rejected by the provider.
32169
- */
32170
- runAction: require_sleep.method(zod.z.object({
32171
- deviceId: zod.z.number(),
32172
- actionId: NavigationActionIdSchema
32173
- }), zod.z.void(), { kind: "mutation" }),
32174
- /** Play a sound by its wire id (the `soundId` of a `kind:'sound'` entry). */
32175
- playSound: require_sleep.method(zod.z.object({
32176
- deviceId: zod.z.number(),
32177
- soundId: zod.z.number().int()
32178
- }), zod.z.void(), { kind: "mutation" }),
32179
- /**
32180
- * Turn the on-camera fill light on / off (the `OpenFullLight` control —
32181
- * works anytime, no active stream required).
32182
- */
32183
- setLightOn: require_sleep.method(zod.z.object({
32184
- deviceId: zod.z.number(),
32185
- on: zod.z.boolean()
32186
- }), zod.z.void(), { kind: "mutation" }),
32187
- /**
32188
- * Set the fill-light mode (auto vs manual). `manual` optionally carries the
32189
- * initial `level`. The auto/manual + level control is a CAMERA-service
32190
- * action that generally needs an active camera stream/monitor session — the
32191
- * UI shows the manual level slider ONLY when `mode === 'manual'`.
32192
- */
32193
- setLightMode: require_sleep.method(zod.z.object({
32194
- deviceId: zod.z.number(),
32195
- mode: NavigationLightModeSchema,
32196
- level: zod.z.number().min(40).max(100).optional()
32197
- }), zod.z.void(), { kind: "mutation" }),
32198
- /** Set the MANUAL fill-light level (40..100). Implies `manual` mode. */
32199
- setLightLevel: require_sleep.method(zod.z.object({
32200
- deviceId: zod.z.number(),
32201
- level: zod.z.number().min(40).max(100)
32202
- }), zod.z.void(), { kind: "mutation" }),
32203
- /**
32204
- * Per-device FEATURE-FLAG report for the general primitives — drives which
32205
- * controls the UI shows (the per-entry flags for the dictionary come back on
32206
- * `listActions`).
32207
- */
32208
- getFeatures: require_sleep.method(zod.z.object({ deviceId: zod.z.number() }), NavigationFeaturesSchema)
32209
- },
32210
- events: { onStatusChanged: { data: zod.z.object({
32211
- deviceId: zod.z.number(),
32212
- status: NavigationStatusSchema
32213
- }) } },
32214
- status: {
32215
- schema: NavigationStatusSchema,
32216
- kind: "push"
32217
- },
32218
- /**
32219
- * Runtime-state slice mirrored by the kernel. The navigation panel watches it
32220
- * for live mode / follow / flash changes.
32221
- */
32222
- runtimeState: NavigationRuntimeStateSchema,
32223
- /**
32224
- * Runtime-state durability: **session** — like `vacuum-control`, a restored
32225
- * `mode: cleaning` / `following: true` is a robot that is not actually doing
32226
- * that. The live handle re-publishes on connect.
32227
- *
32228
- * See `RuntimeStateDurability`. Enforced by
32229
- * `scripts/check-runtime-state-durability.ts`.
32230
- */
32231
- durability: "session"
32232
- };
32233
- //#endregion
32234
32545
  //#region src/capabilities/reboot.cap.ts
32235
32546
  /**
32236
32547
  * reboot — device-scoped capability for "soft" device reboots (firmware
@@ -36369,134 +36680,6 @@ var RUNTIME_DEFAULTS = {
36369
36680
  "auth.tokenExpiry": "30d"
36370
36681
  };
36371
36682
  //#endregion
36372
- //#region src/device/container-primary-child.ts
36373
- /**
36374
- * WHICH child a container stands for — one definition, for every consumer.
36375
- *
36376
- * A CONTAINER device has no controllable surface of its own: it groups entity
36377
- * children (a Gree air-conditioner grouping a climate child plus light, x-fan
36378
- * and health switches). Everything that has to show or act on a container has
36379
- * to answer the same question — which child IS the container — and until now
36380
- * three places answered it separately:
36381
- *
36382
- * - `ui-library/device-controls/primary-child.ts` (admin-ui rendering)
36383
- * - `addon-provider-homeassistant` PARENT_TYPE_PRIORITY (adoption)
36384
- * - the viewer's own `container-primary.ts` (linked-devices panel)
36385
- *
36386
- * Each carried the same list and a comment asking the others to stay in sync.
36387
- * This is that list, in the one package all of them already depend on.
36388
- *
36389
- * `ui-library` and the server's linked-devices expansion IMPORT it. Two
36390
- * consumers cannot, and keep a checked copy instead: the viewer resolves
36391
- * `@camstack/types` from its own `node_modules` (an installed release, where a
36392
- * newly added export simply is not there), and the Home Assistant provider
36393
- * expresses the same precedence over the `DeviceType` enum because it answers
36394
- * a different question from the same ordering. `scripts/check-container-
36395
- * priority-in-sync.ts` fails the build when either drifts — the comment that
36396
- * used to ask for this could not.
36397
- *
36398
- * The rule has two halves and the ORDER matters: an operator's explicit pick
36399
- * wins outright, and only in its absence does type priority decide. The pick is
36400
- * keyed on the child's re-sync-stable `entityId`, not its numeric id, so it
36401
- * survives a re-sync that reallocates ids.
36402
- */
36403
- /**
36404
- * Type priority, most→least "primary". An actuator (climate / lock / cover / …)
36405
- * outranks a bare `switch` so a container's defining child wins over its
36406
- * auxiliary switches. Unknown or absent types sort after every entry.
36407
- *
36408
- * NB: `siren` deliberately sits BELOW `switch` — it is a switch-family
36409
- * actuator, and a camera's siren must not out-rank the thing the container is.
36410
- *
36411
- * These strings are matched against a child's `DeviceType` VALUE, so they must
36412
- * equal the enum's string values.
36413
- */
36414
- var CONTAINER_CHILD_PRIORITY = [
36415
- "media-player",
36416
- "alarm-panel",
36417
- "thermostat",
36418
- "climate",
36419
- "humidifier",
36420
- "water-heater",
36421
- "lock",
36422
- "cover",
36423
- "valve",
36424
- "fan",
36425
- "vacuum",
36426
- "lawn-mower",
36427
- "light",
36428
- "switch",
36429
- "siren",
36430
- "button",
36431
- "control",
36432
- "notifier",
36433
- "script",
36434
- "automation",
36435
- "update",
36436
- "presence",
36437
- "weather",
36438
- "image",
36439
- "sensor"
36440
- ];
36441
- /**
36442
- * Roles that say what a container IS, most→least defining. Consulted BEFORE
36443
- * type priority, because `DeviceType` cannot tell them apart: Home Assistant
36444
- * maps a door contact, a battery level, a temperature reading and a "last seen"
36445
- * timestamp all to `DeviceType.Sensor`. Measured on container 4127 — children
36446
- * `battery-sensor`, `temperature-sensor`, `datetime-sensor`, `contact-sensor`
36447
- * and a role-less `button` — the type list ranked `button` above `sensor` and
36448
- * the container stood for its "Identifica" button instead of the door contact
36449
- * it is named after.
36450
- *
36451
- * Only STATE-DEFINING roles belong here. A diagnostic reading (battery,
36452
- * temperature, humidity, signal, last-seen) is never what a container is, so
36453
- * they are deliberately absent and fall through to type priority.
36454
- */
36455
- var CONTAINER_CHILD_ROLE_PRIORITY = [
36456
- "contact-sensor",
36457
- "motion-sensor",
36458
- "occupancy-sensor",
36459
- "smoke-sensor",
36460
- "co-sensor",
36461
- "gas-sensor",
36462
- "leak-sensor",
36463
- "vibration-sensor",
36464
- "tamper-sensor",
36465
- "sound-sensor"
36466
- ];
36467
- /**
36468
- * NOT in the list, deliberately: `binary-sensor` and `binary-helper`. They are
36469
- * GENERIC — they say "this reports a boolean", not what the container is — and
36470
- * ranking them above type priority is a live regression, not a hypothetical:
36471
- * container 1837 holds a real `lock` (features `['lock-open']`) alongside a
36472
- * child named "Actuator" whose only role is `binary-sensor`, and the generic
36473
- * role beat the lock. A role earns a place here by naming a SUBJECT (a contact,
36474
- * a leak, smoke), never by naming a datatype.
36475
- */
36476
- function roleRank(role) {
36477
- if (role === void 0) return CONTAINER_CHILD_ROLE_PRIORITY.length;
36478
- const i = CONTAINER_CHILD_ROLE_PRIORITY.indexOf(role);
36479
- return i === -1 ? CONTAINER_CHILD_ROLE_PRIORITY.length : i;
36480
- }
36481
- function rank(type) {
36482
- const i = CONTAINER_CHILD_PRIORITY.indexOf(type);
36483
- return i === -1 ? CONTAINER_CHILD_PRIORITY.length : i;
36484
- }
36485
- /**
36486
- * The child a container stands for: the operator's pick when it still exists,
36487
- * else the highest-priority type. `null` for a childless container — a caller
36488
- * must decide what an empty container means for it, rather than being handed a
36489
- * child that is not there.
36490
- */
36491
- function resolveContainerPrimaryChild(children, overrideEntityId, containerName) {
36492
- if (overrideEntityId !== void 0 && overrideEntityId !== null) {
36493
- const picked = children.find((c) => c.stableId === overrideEntityId) ?? children.find((c) => c.entityId !== void 0 && c.entityId === overrideEntityId);
36494
- if (picked !== void 0) return picked;
36495
- }
36496
- const namesake = (c) => containerName !== void 0 && containerName.length > 0 && c.name !== void 0 && c.name.toLowerCase() === containerName.toLowerCase() ? 0 : 1;
36497
- return [...children].toSorted((a, b) => roleRank(a.role) - roleRank(b.role) || namesake(a) - namesake(b) || rank(a.type) - rank(b.type))[0] ?? null;
36498
- }
36499
- //#endregion
36500
36683
  //#region src/device/accessory.ts
36501
36684
  /**
36502
36685
  * Accessory device helpers — shared across drivers.
@@ -38082,6 +38265,134 @@ function isBatteryPresenceFault(presence) {
38082
38265
  return presence === "unreachable";
38083
38266
  }
38084
38267
  //#endregion
38268
+ //#region src/device/container-primary-child.ts
38269
+ /**
38270
+ * WHICH child a container stands for — one definition, for every consumer.
38271
+ *
38272
+ * A CONTAINER device has no controllable surface of its own: it groups entity
38273
+ * children (a Gree air-conditioner grouping a climate child plus light, x-fan
38274
+ * and health switches). Everything that has to show or act on a container has
38275
+ * to answer the same question — which child IS the container — and until now
38276
+ * three places answered it separately:
38277
+ *
38278
+ * - `ui-library/device-controls/primary-child.ts` (admin-ui rendering)
38279
+ * - `addon-provider-homeassistant` PARENT_TYPE_PRIORITY (adoption)
38280
+ * - the viewer's own `container-primary.ts` (linked-devices panel)
38281
+ *
38282
+ * Each carried the same list and a comment asking the others to stay in sync.
38283
+ * This is that list, in the one package all of them already depend on.
38284
+ *
38285
+ * `ui-library` and the server's linked-devices expansion IMPORT it. Two
38286
+ * consumers cannot, and keep a checked copy instead: the viewer resolves
38287
+ * `@camstack/types` from its own `node_modules` (an installed release, where a
38288
+ * newly added export simply is not there), and the Home Assistant provider
38289
+ * expresses the same precedence over the `DeviceType` enum because it answers
38290
+ * a different question from the same ordering. `scripts/check-container-
38291
+ * priority-in-sync.ts` fails the build when either drifts — the comment that
38292
+ * used to ask for this could not.
38293
+ *
38294
+ * The rule has two halves and the ORDER matters: an operator's explicit pick
38295
+ * wins outright, and only in its absence does type priority decide. The pick is
38296
+ * keyed on the child's re-sync-stable `entityId`, not its numeric id, so it
38297
+ * survives a re-sync that reallocates ids.
38298
+ */
38299
+ /**
38300
+ * Type priority, most→least "primary". An actuator (climate / lock / cover / …)
38301
+ * outranks a bare `switch` so a container's defining child wins over its
38302
+ * auxiliary switches. Unknown or absent types sort after every entry.
38303
+ *
38304
+ * NB: `siren` deliberately sits BELOW `switch` — it is a switch-family
38305
+ * actuator, and a camera's siren must not out-rank the thing the container is.
38306
+ *
38307
+ * These strings are matched against a child's `DeviceType` VALUE, so they must
38308
+ * equal the enum's string values.
38309
+ */
38310
+ var CONTAINER_CHILD_PRIORITY = [
38311
+ "media-player",
38312
+ "alarm-panel",
38313
+ "thermostat",
38314
+ "climate",
38315
+ "humidifier",
38316
+ "water-heater",
38317
+ "lock",
38318
+ "cover",
38319
+ "valve",
38320
+ "fan",
38321
+ "vacuum",
38322
+ "lawn-mower",
38323
+ "light",
38324
+ "switch",
38325
+ "siren",
38326
+ "button",
38327
+ "control",
38328
+ "notifier",
38329
+ "script",
38330
+ "automation",
38331
+ "update",
38332
+ "presence",
38333
+ "weather",
38334
+ "image",
38335
+ "sensor"
38336
+ ];
38337
+ /**
38338
+ * Roles that say what a container IS, most→least defining. Consulted BEFORE
38339
+ * type priority, because `DeviceType` cannot tell them apart: Home Assistant
38340
+ * maps a door contact, a battery level, a temperature reading and a "last seen"
38341
+ * timestamp all to `DeviceType.Sensor`. Measured on container 4127 — children
38342
+ * `battery-sensor`, `temperature-sensor`, `datetime-sensor`, `contact-sensor`
38343
+ * and a role-less `button` — the type list ranked `button` above `sensor` and
38344
+ * the container stood for its "Identifica" button instead of the door contact
38345
+ * it is named after.
38346
+ *
38347
+ * Only STATE-DEFINING roles belong here. A diagnostic reading (battery,
38348
+ * temperature, humidity, signal, last-seen) is never what a container is, so
38349
+ * they are deliberately absent and fall through to type priority.
38350
+ */
38351
+ var CONTAINER_CHILD_ROLE_PRIORITY = [
38352
+ "contact-sensor",
38353
+ "motion-sensor",
38354
+ "occupancy-sensor",
38355
+ "smoke-sensor",
38356
+ "co-sensor",
38357
+ "gas-sensor",
38358
+ "leak-sensor",
38359
+ "vibration-sensor",
38360
+ "tamper-sensor",
38361
+ "sound-sensor"
38362
+ ];
38363
+ /**
38364
+ * NOT in the list, deliberately: `binary-sensor` and `binary-helper`. They are
38365
+ * GENERIC — they say "this reports a boolean", not what the container is — and
38366
+ * ranking them above type priority is a live regression, not a hypothetical:
38367
+ * container 1837 holds a real `lock` (features `['lock-open']`) alongside a
38368
+ * child named "Actuator" whose only role is `binary-sensor`, and the generic
38369
+ * role beat the lock. A role earns a place here by naming a SUBJECT (a contact,
38370
+ * a leak, smoke), never by naming a datatype.
38371
+ */
38372
+ function roleRank(role) {
38373
+ if (role === void 0) return CONTAINER_CHILD_ROLE_PRIORITY.length;
38374
+ const i = CONTAINER_CHILD_ROLE_PRIORITY.indexOf(role);
38375
+ return i === -1 ? CONTAINER_CHILD_ROLE_PRIORITY.length : i;
38376
+ }
38377
+ function rank(type) {
38378
+ const i = CONTAINER_CHILD_PRIORITY.indexOf(type);
38379
+ return i === -1 ? CONTAINER_CHILD_PRIORITY.length : i;
38380
+ }
38381
+ /**
38382
+ * The child a container stands for: the operator's pick when it still exists,
38383
+ * else the highest-priority type. `null` for a childless container — a caller
38384
+ * must decide what an empty container means for it, rather than being handed a
38385
+ * child that is not there.
38386
+ */
38387
+ function resolveContainerPrimaryChild(children, overrideEntityId, containerName) {
38388
+ if (overrideEntityId !== void 0 && overrideEntityId !== null) {
38389
+ const picked = children.find((c) => c.stableId === overrideEntityId) ?? children.find((c) => c.entityId !== void 0 && c.entityId === overrideEntityId);
38390
+ if (picked !== void 0) return picked;
38391
+ }
38392
+ const namesake = (c) => containerName !== void 0 && containerName.length > 0 && c.name !== void 0 && c.name.toLowerCase() === containerName.toLowerCase() ? 0 : 1;
38393
+ return [...children].toSorted((a, b) => roleRank(a.role) - roleRank(b.role) || namesake(a) - namesake(b) || rank(a.type) - rank(b.type))[0] ?? null;
38394
+ }
38395
+ //#endregion
38085
38396
  //#region src/device/declared-device.ts
38086
38397
  /** Marker written to a declared integration's `info`. */
38087
38398
  var DECLARED_INTEGRATION_FIXED_KEY = "fixed";
@@ -39891,6 +40202,7 @@ var CAPABILITY_NAMES = {
39891
40202
  storage: "storage",
39892
40203
  storageEvictable: "storage-evictable",
39893
40204
  storageMigration: "storage-migration",
40205
+ storageOccupancy: "storage-occupancy",
39894
40206
  storageProvider: "storage-provider",
39895
40207
  streamBroker: "stream-broker",
39896
40208
  streamCatalog: "stream-catalog",
@@ -40436,6 +40748,10 @@ var CAPABILITY_ROUTER_KEYS = [
40436
40748
  key: "storageMigration",
40437
40749
  name: "storage-migration"
40438
40750
  },
40751
+ {
40752
+ key: "storageOccupancy",
40753
+ name: "storage-occupancy"
40754
+ },
40439
40755
  {
40440
40756
  key: "storageProvider",
40441
40757
  name: "storage-provider"
@@ -40680,6 +40996,7 @@ var ALL_CAPABILITY_DEFINITIONS = [
40680
40996
  storageCapability,
40681
40997
  storageEvictableCapability,
40682
40998
  storageMigrationCapability,
40999
+ storageOccupancyCapability,
40683
41000
  storageProviderCapability,
40684
41001
  streamBrokerCapability,
40685
41002
  streamCatalogCapability,
@@ -45648,13 +45965,13 @@ var METHOD_ACCESS_MAP = Object.freeze({
45648
45965
  addonId: null,
45649
45966
  access: "view"
45650
45967
  },
45651
- "storage.getDefaultLocation": {
45968
+ "storage.list": {
45652
45969
  capName: "storage",
45653
45970
  capScope: "system",
45654
45971
  addonId: null,
45655
45972
  access: "view"
45656
45973
  },
45657
- "storage.list": {
45974
+ "storage.listDrainProgress": {
45658
45975
  capName: "storage",
45659
45976
  capScope: "system",
45660
45977
  addonId: null,
@@ -45804,6 +46121,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
45804
46121
  addonId: null,
45805
46122
  access: "view"
45806
46123
  },
46124
+ "storageOccupancy.getOccupancy": {
46125
+ capName: "storage-occupancy",
46126
+ capScope: "system",
46127
+ addonId: null,
46128
+ access: "view"
46129
+ },
45807
46130
  "storageProvider.abortUpload": {
45808
46131
  capName: "storage-provider",
45809
46132
  capScope: "system",
@@ -46939,6 +47262,7 @@ var KNOWN_CAP_NAMES = [
46939
47262
  "storage",
46940
47263
  "storage-evictable",
46941
47264
  "storage-migration",
47265
+ "storage-occupancy",
46942
47266
  "storage-provider",
46943
47267
  "stream-broker",
46944
47268
  "stream-catalog",
@@ -47085,6 +47409,7 @@ var SYSTEM_CAP_NAMES = [
47085
47409
  "storage",
47086
47410
  "storage-evictable",
47087
47411
  "storage-migration",
47412
+ "storage-occupancy",
47088
47413
  "storage-provider",
47089
47414
  "stream-broker",
47090
47415
  "system",
@@ -50081,10 +50406,10 @@ function createSystemProxy(api) {
50081
50406
  readChunk: (input) => dispatch("storage", "readChunk", "query", input),
50082
50407
  endDownload: (input) => dispatch("storage", "endDownload", "mutation", input),
50083
50408
  listLocations: (input) => dispatch("storage", "listLocations", "query", input),
50084
- getDefaultLocation: (input) => dispatch("storage", "getDefaultLocation", "query", input),
50085
50409
  listLocationDeclarations: (input) => dispatch("storage", "listLocationDeclarations", "query", input),
50086
50410
  upsertLocation: (input) => dispatch("storage", "upsertLocation", "mutation", input),
50087
50411
  deleteLocation: (input) => dispatch("storage", "deleteLocation", "mutation", input),
50412
+ listDrainProgress: (input) => dispatch("storage", "listDrainProgress", "query", input),
50088
50413
  testLocation: (input) => dispatch("storage", "testLocation", "query", input),
50089
50414
  listProviders: (input) => dispatch("storage", "listProviders", "query", input),
50090
50415
  testConfig: (input) => dispatch("storage", "testConfig", "query", input)
@@ -54534,6 +54859,7 @@ exports.IntercomAbilitySchema = IntercomAbilitySchema;
54534
54859
  exports.IntercomStatusSchema = IntercomStatusSchema;
54535
54860
  exports.KNOWN_CAP_NAMES = KNOWN_CAP_NAMES;
54536
54861
  exports.KeyEventSchema = KeyEventSchema;
54862
+ exports.LEGACY_READ_ONLY_CONFIG_KEY = LEGACY_READ_ONLY_CONFIG_KEY;
54537
54863
  exports.LOAD_CONTRIBUTION_ATTRIBUTIONS = LOAD_CONTRIBUTION_ATTRIBUTIONS;
54538
54864
  exports.LOAD_CONTRIBUTION_ROLES = LOAD_CONTRIBUTION_ROLES;
54539
54865
  exports.LOG_CHANNEL_TICK_MS = LOG_CHANNEL_TICK_MS;
@@ -54549,6 +54875,7 @@ exports.LedgerWalkRefusalSchema = LedgerWalkRefusalSchema;
54549
54875
  exports.LedgerWalkReportSchema = LedgerWalkReportSchema;
54550
54876
  exports.LedgerWalkSkipCountsSchema = LedgerWalkSkipCountsSchema;
54551
54877
  exports.LedgerWalkSkipReasonSchema = LedgerWalkSkipReasonSchema;
54878
+ exports.LegacyStorageLocationDefaultSchema = LegacyStorageLocationDefaultSchema;
54552
54879
  exports.LinkedDeviceSchema = LinkedDeviceSchema;
54553
54880
  exports.LinkedDevicesModeSchema = LinkedDevicesModeSchema;
54554
54881
  exports.LlmDefaultSchema = LlmDefaultSchema;
@@ -54984,6 +55311,8 @@ exports.SOURCE_CAP_CHANGED_AT_FIELD = SOURCE_CAP_CHANGED_AT_FIELD;
54984
55311
  exports.SOURCE_DEVICE_TYPES = SOURCE_DEVICE_TYPES;
54985
55312
  exports.SOURCE_INFO_METADATA_KEY = SOURCE_INFO_METADATA_KEY;
54986
55313
  exports.STORAGE_ACCESS_FALLBACK = STORAGE_ACCESS_FALLBACK;
55314
+ exports.STORAGE_BYTES_PER_GB = STORAGE_BYTES_PER_GB;
55315
+ exports.STORAGE_LOCATION_MODES = STORAGE_LOCATION_MODES;
54987
55316
  exports.STREAM_PROFILE_META = STREAM_PROFILE_META;
54988
55317
  exports.STREAM_QUALITY_LABELS = STREAM_QUALITY_LABELS;
54989
55318
  exports.SUB_DETECTION_TYPES = SUB_DETECTION_TYPES;
@@ -55045,9 +55374,12 @@ exports.StorageCleanupInputSchema = StorageCleanupInputSchema;
55045
55374
  exports.StorageCleanupJobSchema = StorageCleanupJobSchema;
55046
55375
  exports.StorageCleanupPhaseSchema = StorageCleanupPhaseSchema;
55047
55376
  exports.StorageCleanupStatusInputSchema = StorageCleanupStatusInputSchema;
55377
+ exports.StorageDrainProgressSchema = StorageDrainProgressSchema;
55048
55378
  exports.StorageEndDownloadInputSchema = EndDownloadInputSchema;
55379
+ exports.StorageEvictionPolicySchema = StorageEvictionPolicySchema;
55049
55380
  exports.StorageFinalizeUploadInputSchema = FinalizeUploadInputSchema;
55050
55381
  exports.StorageLocationDeclarationSchema = StorageLocationDeclarationSchema;
55382
+ exports.StorageLocationModeSchema = StorageLocationModeSchema;
55051
55383
  exports.StorageLocationRefSchema = StorageLocationRefSchema;
55052
55384
  exports.StorageLocationSchema = StorageLocationSchema;
55053
55385
  exports.StorageLocationTypeSchema = StorageLocationTypeSchema;
@@ -55071,6 +55403,7 @@ exports.StorageMigrationPhaseSchema = StorageMigrationPhaseSchema;
55071
55403
  exports.StorageMigrationPlanSchema = StorageMigrationPlanSchema;
55072
55404
  exports.StorageMigrationResidueSchema = StorageMigrationResidueSchema;
55073
55405
  exports.StorageMigrationSourcesSchema = StorageMigrationSourcesSchema;
55406
+ exports.StorageOccupancyReportSchema = StorageOccupancyReportSchema;
55074
55407
  exports.StorageProviderInfoSchema = ProviderInfoSchema;
55075
55408
  exports.StorageReadChunkInputSchema = ReadChunkInputSchema;
55076
55409
  exports.StorageTestLocationResultSchema = TestLocationResultSchema;
@@ -55352,6 +55685,8 @@ exports.evaluateZoneRules = evaluateZoneRules;
55352
55685
  exports.event = require_sleep.event;
55353
55686
  exports.eventEmitterCapability = eventEmitterCapability;
55354
55687
  exports.eventsCapability = eventsCapability;
55688
+ exports.evictionPolicyForMode = evictionPolicyForMode;
55689
+ exports.evictionPolicyOfLocation = evictionPolicyOfLocation;
55355
55690
  exports.expandCapMethods = require_sleep.expandCapMethods;
55356
55691
  exports.extractNestedAddonId = extractNestedAddonId;
55357
55692
  exports.extractSourceInfoFromMetadata = extractSourceInfoFromMetadata;
@@ -55367,6 +55702,7 @@ exports.foldSnapshotByFunction = foldSnapshotByFunction;
55367
55702
  exports.formatForBackend = formatForBackend;
55368
55703
  exports.formatForRuntime = formatForRuntime;
55369
55704
  exports.gasCapability = gasCapability;
55705
+ exports.gbToBytes = gbToBytes;
55370
55706
  exports.generateAutomationBlock = generateAutomationBlock;
55371
55707
  exports.getAudioMacroClassIds = getAudioMacroClassIds;
55372
55708
  exports.getByPath = getByPath;
@@ -55401,6 +55737,7 @@ exports.isDeviceScopedCap = require_sleep.isDeviceScopedCap;
55401
55737
  exports.isEvent = require_sleep.isEvent;
55402
55738
  exports.isFirstLevelMacroClass = isFirstLevelMacroClass;
55403
55739
  exports.isIsolatedBuiltin = isIsolatedBuiltin;
55740
+ exports.isLocationEnabled = isLocationEnabled;
55404
55741
  exports.isNode = isNode;
55405
55742
  exports.isObjectInput = isObjectInput;
55406
55743
  exports.isOccupancyRule = isOccupancyRule;
@@ -55410,12 +55747,14 @@ exports.isScheduleActive = isScheduleActive;
55410
55747
  exports.isSecretConfigField = isSecretConfigField;
55411
55748
  exports.isSoftwareDecode = require_canonical_hash.isSoftwareDecode;
55412
55749
  exports.isSourceCap = isSourceCap;
55750
+ exports.isStorageLocationMode = isStorageLocationMode;
55413
55751
  exports.isSystemDelivery = isSystemDelivery;
55414
55752
  exports.isVoidInput = isVoidInput;
55415
55753
  exports.jobKindSchema = jobKindSchema;
55416
55754
  exports.kebabToCamel = kebabToCamel;
55417
55755
  exports.knownValues = knownValues;
55418
55756
  exports.lawnMowerControlCapability = lawnMowerControlCapability;
55757
+ exports.legacyModeOf = legacyModeOf;
55419
55758
  exports.lifecycleJobSchema = lifecycleJobSchema;
55420
55759
  exports.lifecycleJobScopeSchema = lifecycleJobScopeSchema;
55421
55760
  exports.lifecycleJobStateSchema = lifecycleJobStateSchema;
@@ -55438,6 +55777,8 @@ exports.mapAudioLabelToMacro = mapAudioLabelToMacro;
55438
55777
  exports.markdownToHtmlLite = markdownToHtmlLite;
55439
55778
  exports.markdownToText = markdownToText;
55440
55779
  exports.maskUrlCredentials = maskUrlCredentials;
55780
+ exports.mayReadLocation = mayReadLocation;
55781
+ exports.mayWriteToLocation = mayWriteToLocation;
55441
55782
  exports.mediaPlayerCapability = mediaPlayerCapability;
55442
55783
  exports.mergeSourceInfo = mergeSourceInfo;
55443
55784
  exports.meshNetworkCapability = meshNetworkCapability;
@@ -55445,6 +55786,8 @@ exports.method = require_sleep.method;
55445
55786
  exports.methodAccessForHttpMethod = methodAccessForHttpMethod;
55446
55787
  exports.metricsProviderCapability = metricsProviderCapability;
55447
55788
  exports.migrateLegacyDeviceSignalConfig = migrateLegacyDeviceSignalConfig;
55789
+ exports.modeMayRead = modeMayRead;
55790
+ exports.modeMayWrite = modeMayWrite;
55448
55791
  exports.modelConvertCapability = modelConvertCapability;
55449
55792
  exports.modelDistributorCapability = modelDistributorCapability;
55450
55793
  exports.modelFormatForRuntime = modelFormatForRuntime;
@@ -55540,6 +55883,7 @@ exports.resolveDeviceProfile = resolveDeviceProfile;
55540
55883
  exports.resolveEgressDecodeHwAccel = resolveEgressDecodeHwAccel;
55541
55884
  exports.resolveFormat = resolveFormat;
55542
55885
  exports.resolveHydratedFieldValue = require_sleep.resolveHydratedFieldValue;
55886
+ exports.resolveLocationMode = resolveLocationMode;
55543
55887
  exports.resolveMethodAuth = resolveMethodAuth;
55544
55888
  exports.resolveModelFormat = resolveModelFormat;
55545
55889
  exports.resolveMutate = resolveMutate;
@@ -55586,6 +55930,7 @@ exports.stateVocabularyFor = stateVocabularyFor;
55586
55930
  exports.storageCapability = storageCapability;
55587
55931
  exports.storageEvictableCapability = storageEvictableCapability;
55588
55932
  exports.storageMigrationCapability = storageMigrationCapability;
55933
+ exports.storageOccupancyCapability = storageOccupancyCapability;
55589
55934
  exports.storageProviderCapability = storageProviderCapability;
55590
55935
  exports.streamBrokerCapability = streamBrokerCapability;
55591
55936
  exports.streamCatalogCapability = streamCatalogCapability;
@@ -55593,6 +55938,7 @@ exports.streamParamsCapability = streamParamsCapability;
55593
55938
  exports.streamPixels = streamPixels;
55594
55939
  exports.streamQualityLabel = streamQualityLabel;
55595
55940
  exports.stripRetiredBandPreBufferSec = stripRetiredBandPreBufferSec;
55941
+ exports.strippedOfLegacyReadOnly = strippedOfLegacyReadOnly;
55596
55942
  exports.subKindsOf = subKindsOf;
55597
55943
  exports.summarisePrivacyAudio = summarisePrivacyAudio;
55598
55944
  exports.summarizeEffectiveScope = summarizeEffectiveScope;
@@ -55643,6 +55989,7 @@ exports.wiringHealthSnapshotSchema = wiringHealthSnapshotSchema;
55643
55989
  exports.wiringNodeHealthSchema = wiringNodeHealthSchema;
55644
55990
  exports.wiringProbeKindSchema = wiringProbeKindSchema;
55645
55991
  exports.wiringProbeResultSchema = wiringProbeResultSchema;
55992
+ exports.withLocationMode = withLocationMode;
55646
55993
  exports.zodEntriesToConfigUI = zodEntriesToConfigUI;
55647
55994
  exports.zoneAnalyticsCapability = zoneAnalyticsCapability;
55648
55995
  exports.zoneRulesCapability = zoneRulesCapability;